blob: f547db4f0044e7efba284bbe6a399f7e83993f80 [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 }
drh0d950af2019-08-22 16:38:42 +000087 pTerm->pExpr = sqlite3ExprSkipCollateAndLikely(p);
drh6c1f4ef2015-06-08 14:23:15 +000088 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".
drh6c1f4ef2015-06-08 14:23:15 +0000112*/
drhc7d12f42019-09-03 14:27:25 +0000113static u16 exprCommute(Parse *pParse, Expr *pExpr){
drh98c94e62019-10-22 11:29:22 +0000114 if( pExpr->pLeft->op==TK_VECTOR
115 || pExpr->pRight->op==TK_VECTOR
116 || sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft, pExpr->pRight) !=
117 sqlite3BinaryCompareCollSeq(pParse, pExpr->pRight, pExpr->pLeft)
118 ){
drh898c5272019-10-22 00:03:41 +0000119 pExpr->flags ^= EP_Commuted;
drh6c1f4ef2015-06-08 14:23:15 +0000120 }
121 SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
122 if( pExpr->op>=TK_GT ){
123 assert( TK_LT==TK_GT+2 );
124 assert( TK_GE==TK_LE+2 );
125 assert( TK_GT>TK_EQ );
126 assert( TK_GT<TK_LE );
127 assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
128 pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
129 }
drh898c5272019-10-22 00:03:41 +0000130 return 0;
drh6c1f4ef2015-06-08 14:23:15 +0000131}
132
133/*
134** Translate from TK_xx operator to WO_xx bitmask.
135*/
136static u16 operatorMask(int op){
137 u16 c;
138 assert( allowedOp(op) );
139 if( op==TK_IN ){
140 c = WO_IN;
141 }else if( op==TK_ISNULL ){
142 c = WO_ISNULL;
143 }else if( op==TK_IS ){
144 c = WO_IS;
145 }else{
146 assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
147 c = (u16)(WO_EQ<<(op-TK_EQ));
148 }
149 assert( op!=TK_ISNULL || c==WO_ISNULL );
150 assert( op!=TK_IN || c==WO_IN );
151 assert( op!=TK_EQ || c==WO_EQ );
152 assert( op!=TK_LT || c==WO_LT );
153 assert( op!=TK_LE || c==WO_LE );
154 assert( op!=TK_GT || c==WO_GT );
155 assert( op!=TK_GE || c==WO_GE );
156 assert( op!=TK_IS || c==WO_IS );
157 return c;
158}
159
160
161#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
162/*
163** Check to see if the given expression is a LIKE or GLOB operator that
164** can be optimized using inequality constraints. Return TRUE if it is
165** so and false if not.
166**
167** In order for the operator to be optimizible, the RHS must be a string
168** literal that does not begin with a wildcard. The LHS must be a column
169** that may only be NULL, a string, or a BLOB, never a number. (This means
170** that virtual tables cannot participate in the LIKE optimization.) The
171** collating sequence for the column on the LHS must be appropriate for
172** the operator.
173*/
174static int isLikeOrGlob(
175 Parse *pParse, /* Parsing and code generating context */
176 Expr *pExpr, /* Test this expression */
177 Expr **ppPrefix, /* Pointer to TK_STRING expression with pattern prefix */
178 int *pisComplete, /* True if the only wildcard is % in the last character */
179 int *pnoCase /* True if uppercase is equivalent to lowercase */
180){
drhad9f5152018-08-09 21:45:45 +0000181 const u8 *z = 0; /* String on RHS of LIKE operator */
drh6c1f4ef2015-06-08 14:23:15 +0000182 Expr *pRight, *pLeft; /* Right and left size of LIKE operator */
183 ExprList *pList; /* List of operands to the LIKE operator */
drhad9f5152018-08-09 21:45:45 +0000184 u8 c; /* One character in z[] */
drh6c1f4ef2015-06-08 14:23:15 +0000185 int cnt; /* Number of non-wildcard prefix characters */
drhad9f5152018-08-09 21:45:45 +0000186 u8 wc[4]; /* Wildcard characters */
drh6c1f4ef2015-06-08 14:23:15 +0000187 sqlite3 *db = pParse->db; /* Database connection */
188 sqlite3_value *pVal = 0;
189 int op; /* Opcode of pRight */
drhb8763632016-01-19 17:54:21 +0000190 int rc; /* Result code to return */
drh6c1f4ef2015-06-08 14:23:15 +0000191
drhad9f5152018-08-09 21:45:45 +0000192 if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, (char*)wc) ){
drh6c1f4ef2015-06-08 14:23:15 +0000193 return 0;
194 }
195#ifdef SQLITE_EBCDIC
196 if( *pnoCase ) return 0;
197#endif
198 pList = pExpr->x.pList;
199 pLeft = pList->a[1].pExpr;
drh6c1f4ef2015-06-08 14:23:15 +0000200
201 pRight = sqlite3ExprSkipCollate(pList->a[0].pExpr);
202 op = pRight->op;
drh7df74752017-06-26 14:46:05 +0000203 if( op==TK_VARIABLE && (db->flags & SQLITE_EnableQPSG)==0 ){
drh6c1f4ef2015-06-08 14:23:15 +0000204 Vdbe *pReprepare = pParse->pReprepare;
205 int iCol = pRight->iColumn;
206 pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_BLOB);
207 if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
drhb8313cc2017-08-08 21:30:43 +0000208 z = sqlite3_value_text(pVal);
drh6c1f4ef2015-06-08 14:23:15 +0000209 }
210 sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
211 assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
212 }else if( op==TK_STRING ){
drhb8313cc2017-08-08 21:30:43 +0000213 z = (u8*)pRight->u.zToken;
drh6c1f4ef2015-06-08 14:23:15 +0000214 }
215 if( z ){
drh1c84bd42017-02-10 21:37:57 +0000216
drh1d42ea72017-07-27 20:24:29 +0000217 /* Count the number of prefix characters prior to the first wildcard */
drh6c1f4ef2015-06-08 14:23:15 +0000218 cnt = 0;
219 while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
220 cnt++;
drhf41a8d32017-08-11 03:47:21 +0000221 if( c==wc[3] && z[cnt]!=0 ) cnt++;
drh6c1f4ef2015-06-08 14:23:15 +0000222 }
drh1d42ea72017-07-27 20:24:29 +0000223
224 /* The optimization is possible only if (1) the pattern does not begin
225 ** with a wildcard and if (2) the non-wildcard prefix does not end with
dan6b4b8822018-07-02 15:03:50 +0000226 ** an (illegal 0xff) character, or (3) the pattern does not consist of
227 ** a single escape character. The second condition is necessary so
drh1d42ea72017-07-27 20:24:29 +0000228 ** that we can increment the prefix key to find an upper bound for the
dan6b4b8822018-07-02 15:03:50 +0000229 ** range search. The third is because the caller assumes that the pattern
230 ** consists of at least one character after all escapes have been
231 ** removed. */
232 if( cnt!=0 && 255!=(u8)z[cnt-1] && (cnt>1 || z[0]!=wc[3]) ){
drh6c1f4ef2015-06-08 14:23:15 +0000233 Expr *pPrefix;
drh1d42ea72017-07-27 20:24:29 +0000234
235 /* A "complete" match if the pattern ends with "*" or "%" */
drh6c1f4ef2015-06-08 14:23:15 +0000236 *pisComplete = c==wc[0] && z[cnt+1]==0;
drh1d42ea72017-07-27 20:24:29 +0000237
238 /* Get the pattern prefix. Remove all escapes from the prefix. */
drhb8313cc2017-08-08 21:30:43 +0000239 pPrefix = sqlite3Expr(db, TK_STRING, (char*)z);
drh1d42ea72017-07-27 20:24:29 +0000240 if( pPrefix ){
241 int iFrom, iTo;
242 char *zNew = pPrefix->u.zToken;
243 zNew[cnt] = 0;
244 for(iFrom=iTo=0; iFrom<cnt; iFrom++){
245 if( zNew[iFrom]==wc[3] ) iFrom++;
246 zNew[iTo++] = zNew[iFrom];
247 }
248 zNew[iTo] = 0;
drh6f7f5d92019-05-08 23:53:50 +0000249 assert( iTo>0 );
drhb7a002f2018-09-10 12:40:57 +0000250
drh060b7fa2019-06-14 12:28:21 +0000251 /* If the LHS is not an ordinary column with TEXT affinity, then the
252 ** pattern prefix boundaries (both the start and end boundaries) must
253 ** not look like a number. Otherwise the pattern might be treated as
254 ** a number, which will invalidate the LIKE optimization.
drhb7a002f2018-09-10 12:40:57 +0000255 **
drh060b7fa2019-06-14 12:28:21 +0000256 ** Getting this right has been a persistent source of bugs in the
257 ** LIKE optimization. See, for example:
258 ** 2018-09-10 https://sqlite.org/src/info/c94369cae9b561b1
259 ** 2019-05-02 https://sqlite.org/src/info/b043a54c3de54b28
260 ** 2019-06-10 https://sqlite.org/src/info/fd76310a5e843e07
261 ** 2019-06-14 https://sqlite.org/src/info/ce8717f0885af975
drh91f473b2019-09-16 18:19:41 +0000262 ** 2019-09-03 https://sqlite.org/src/info/0f0428096f17252a
drhb7a002f2018-09-10 12:40:57 +0000263 */
drh060b7fa2019-06-14 12:28:21 +0000264 if( pLeft->op!=TK_COLUMN
265 || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
266 || IsVirtual(pLeft->y.pTab) /* Value might be numeric */
drhb7a002f2018-09-10 12:40:57 +0000267 ){
drh060b7fa2019-06-14 12:28:21 +0000268 int isNum;
269 double rDummy;
270 isNum = sqlite3AtoF(zNew, &rDummy, iTo, SQLITE_UTF8);
271 if( isNum<=0 ){
drh91f473b2019-09-16 18:19:41 +0000272 if( iTo==1 && zNew[0]=='-' ){
273 isNum = +1;
274 }else{
275 zNew[iTo-1]++;
276 isNum = sqlite3AtoF(zNew, &rDummy, iTo, SQLITE_UTF8);
277 zNew[iTo-1]--;
278 }
drh060b7fa2019-06-14 12:28:21 +0000279 }
280 if( isNum>0 ){
drhb7a002f2018-09-10 12:40:57 +0000281 sqlite3ExprDelete(db, pPrefix);
282 sqlite3ValueFree(pVal);
283 return 0;
284 }
285 }
drh1d42ea72017-07-27 20:24:29 +0000286 }
drh6c1f4ef2015-06-08 14:23:15 +0000287 *ppPrefix = pPrefix;
drh1d42ea72017-07-27 20:24:29 +0000288
289 /* If the RHS pattern is a bound parameter, make arrangements to
290 ** reprepare the statement when that parameter is rebound */
drh6c1f4ef2015-06-08 14:23:15 +0000291 if( op==TK_VARIABLE ){
292 Vdbe *v = pParse->pVdbe;
293 sqlite3VdbeSetVarmask(v, pRight->iColumn);
294 if( *pisComplete && pRight->u.zToken[1] ){
295 /* If the rhs of the LIKE expression is a variable, and the current
296 ** value of the variable means there is no need to invoke the LIKE
297 ** function, then no OP_Variable will be added to the program.
298 ** This causes problems for the sqlite3_bind_parameter_name()
299 ** API. To work around them, add a dummy OP_Variable here.
300 */
301 int r1 = sqlite3GetTempReg(pParse);
302 sqlite3ExprCodeTarget(pParse, pRight, r1);
303 sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
304 sqlite3ReleaseTempReg(pParse, r1);
305 }
306 }
307 }else{
308 z = 0;
309 }
310 }
311
drhb8763632016-01-19 17:54:21 +0000312 rc = (z!=0);
drh6c1f4ef2015-06-08 14:23:15 +0000313 sqlite3ValueFree(pVal);
drhb8763632016-01-19 17:54:21 +0000314 return rc;
drh6c1f4ef2015-06-08 14:23:15 +0000315}
316#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
317
318
319#ifndef SQLITE_OMIT_VIRTUALTABLE
320/*
drh303a69b2017-09-11 19:47:37 +0000321** Check to see if the pExpr expression is a form that needs to be passed
322** to the xBestIndex method of virtual tables. Forms of interest include:
drh6c1f4ef2015-06-08 14:23:15 +0000323**
drh303a69b2017-09-11 19:47:37 +0000324** Expression Virtual Table Operator
325** ----------------------- ---------------------------------
326** 1. column MATCH expr SQLITE_INDEX_CONSTRAINT_MATCH
327** 2. column GLOB expr SQLITE_INDEX_CONSTRAINT_GLOB
328** 3. column LIKE expr SQLITE_INDEX_CONSTRAINT_LIKE
329** 4. column REGEXP expr SQLITE_INDEX_CONSTRAINT_REGEXP
330** 5. column != expr SQLITE_INDEX_CONSTRAINT_NE
331** 6. expr != column SQLITE_INDEX_CONSTRAINT_NE
332** 7. column IS NOT expr SQLITE_INDEX_CONSTRAINT_ISNOT
333** 8. expr IS NOT column SQLITE_INDEX_CONSTRAINT_ISNOT
334** 9. column IS NOT NULL SQLITE_INDEX_CONSTRAINT_ISNOTNULL
dan43970dd2015-11-24 17:39:01 +0000335**
drh303a69b2017-09-11 19:47:37 +0000336** In every case, "column" must be a column of a virtual table. If there
337** is a match, set *ppLeft to the "column" expression, set *ppRight to the
338** "expr" expression (even though in forms (6) and (8) the column is on the
339** right and the expression is on the left). Also set *peOp2 to the
340** appropriate virtual table operator. The return value is 1 or 2 if there
341** is a match. The usual return is 1, but if the RHS is also a column
342** of virtual table in forms (5) or (7) then return 2.
dand03024d2017-09-09 19:41:12 +0000343**
344** If the expression matches none of the patterns above, return 0.
drh6c1f4ef2015-06-08 14:23:15 +0000345*/
drh303a69b2017-09-11 19:47:37 +0000346static int isAuxiliaryVtabOperator(
drh59155062018-05-26 18:03:48 +0000347 sqlite3 *db, /* Parsing context */
dan07bdba82015-11-23 21:09:54 +0000348 Expr *pExpr, /* Test this expression */
dand03024d2017-09-09 19:41:12 +0000349 unsigned char *peOp2, /* OUT: 0 for MATCH, or else an op2 value */
350 Expr **ppLeft, /* Column expression to left of MATCH/op2 */
351 Expr **ppRight /* Expression to left of MATCH/op2 */
drh6c1f4ef2015-06-08 14:23:15 +0000352){
dand03024d2017-09-09 19:41:12 +0000353 if( pExpr->op==TK_FUNCTION ){
354 static const struct Op2 {
355 const char *zOp;
356 unsigned char eOp2;
357 } aOp[] = {
358 { "match", SQLITE_INDEX_CONSTRAINT_MATCH },
359 { "glob", SQLITE_INDEX_CONSTRAINT_GLOB },
360 { "like", SQLITE_INDEX_CONSTRAINT_LIKE },
361 { "regexp", SQLITE_INDEX_CONSTRAINT_REGEXP }
362 };
363 ExprList *pList;
364 Expr *pCol; /* Column reference */
365 int i;
drh6c1f4ef2015-06-08 14:23:15 +0000366
dand03024d2017-09-09 19:41:12 +0000367 pList = pExpr->x.pList;
368 if( pList==0 || pList->nExpr!=2 ){
369 return 0;
370 }
drh59155062018-05-26 18:03:48 +0000371
372 /* Built-in operators MATCH, GLOB, LIKE, and REGEXP attach to a
373 ** virtual table on their second argument, which is the same as
374 ** the left-hand side operand in their in-fix form.
375 **
376 ** vtab_column MATCH expression
377 ** MATCH(expression,vtab_column)
378 */
dand03024d2017-09-09 19:41:12 +0000379 pCol = pList->a[1].pExpr;
drh78d1d222020-02-17 19:25:07 +0000380 testcase( pCol->op==TK_COLUMN && pCol->y.pTab==0 );
381 if( ExprIsVtab(pCol) ){
drh59155062018-05-26 18:03:48 +0000382 for(i=0; i<ArraySize(aOp); i++){
383 if( sqlite3StrICmp(pExpr->u.zToken, aOp[i].zOp)==0 ){
384 *peOp2 = aOp[i].eOp2;
385 *ppRight = pList->a[0].pExpr;
386 *ppLeft = pCol;
387 return 1;
388 }
389 }
dand03024d2017-09-09 19:41:12 +0000390 }
drh59155062018-05-26 18:03:48 +0000391
392 /* We can also match against the first column of overloaded
393 ** functions where xFindFunction returns a value of at least
394 ** SQLITE_INDEX_CONSTRAINT_FUNCTION.
395 **
396 ** OVERLOADED(vtab_column,expression)
397 **
398 ** Historically, xFindFunction expected to see lower-case function
399 ** names. But for this use case, xFindFunction is expected to deal
400 ** with function names in an arbitrary case.
401 */
402 pCol = pList->a[0].pExpr;
drh78d1d222020-02-17 19:25:07 +0000403 testcase( pCol->op==TK_COLUMN && pCol->y.pTab==0 );
404 if( ExprIsVtab(pCol) ){
drh59155062018-05-26 18:03:48 +0000405 sqlite3_vtab *pVtab;
406 sqlite3_module *pMod;
407 void (*xNotUsed)(sqlite3_context*,int,sqlite3_value**);
408 void *pNotUsed;
drheda079c2018-09-20 19:02:15 +0000409 pVtab = sqlite3GetVTable(db, pCol->y.pTab)->pVtab;
drh59155062018-05-26 18:03:48 +0000410 assert( pVtab!=0 );
411 assert( pVtab->pModule!=0 );
412 pMod = (sqlite3_module *)pVtab->pModule;
413 if( pMod->xFindFunction!=0 ){
414 i = pMod->xFindFunction(pVtab,2, pExpr->u.zToken, &xNotUsed, &pNotUsed);
415 if( i>=SQLITE_INDEX_CONSTRAINT_FUNCTION ){
416 *peOp2 = i;
417 *ppRight = pList->a[1].pExpr;
418 *ppLeft = pCol;
419 return 1;
420 }
dand03024d2017-09-09 19:41:12 +0000421 }
422 }
423 }else if( pExpr->op==TK_NE || pExpr->op==TK_ISNOT || pExpr->op==TK_NOTNULL ){
424 int res = 0;
425 Expr *pLeft = pExpr->pLeft;
426 Expr *pRight = pExpr->pRight;
drh78d1d222020-02-17 19:25:07 +0000427 testcase( pLeft->op==TK_COLUMN && pLeft->y.pTab==0 );
428 if( ExprIsVtab(pLeft) ){
dand03024d2017-09-09 19:41:12 +0000429 res++;
430 }
drh78d1d222020-02-17 19:25:07 +0000431 testcase( pRight && pRight->op==TK_COLUMN && pRight->y.pTab==0 );
432 if( pRight && ExprIsVtab(pRight) ){
dand03024d2017-09-09 19:41:12 +0000433 res++;
434 SWAP(Expr*, pLeft, pRight);
435 }
436 *ppLeft = pLeft;
437 *ppRight = pRight;
438 if( pExpr->op==TK_NE ) *peOp2 = SQLITE_INDEX_CONSTRAINT_NE;
439 if( pExpr->op==TK_ISNOT ) *peOp2 = SQLITE_INDEX_CONSTRAINT_ISNOT;
440 if( pExpr->op==TK_NOTNULL ) *peOp2 = SQLITE_INDEX_CONSTRAINT_ISNOTNULL;
441 return res;
dan07bdba82015-11-23 21:09:54 +0000442 }
443 return 0;
drh6c1f4ef2015-06-08 14:23:15 +0000444}
445#endif /* SQLITE_OMIT_VIRTUALTABLE */
446
447/*
448** If the pBase expression originated in the ON or USING clause of
449** a join, then transfer the appropriate markings over to derived.
450*/
451static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
452 if( pDerived ){
453 pDerived->flags |= pBase->flags & EP_FromJoin;
454 pDerived->iRightJoinTable = pBase->iRightJoinTable;
455 }
456}
457
458/*
459** Mark term iChild as being a child of term iParent
460*/
461static void markTermAsChild(WhereClause *pWC, int iChild, int iParent){
462 pWC->a[iChild].iParent = iParent;
463 pWC->a[iChild].truthProb = pWC->a[iParent].truthProb;
464 pWC->a[iParent].nChild++;
465}
466
467/*
468** Return the N-th AND-connected subterm of pTerm. Or if pTerm is not
469** a conjunction, then return just pTerm when N==0. If N is exceeds
470** the number of available subterms, return NULL.
471*/
472static WhereTerm *whereNthSubterm(WhereTerm *pTerm, int N){
473 if( pTerm->eOperator!=WO_AND ){
474 return N==0 ? pTerm : 0;
475 }
476 if( N<pTerm->u.pAndInfo->wc.nTerm ){
477 return &pTerm->u.pAndInfo->wc.a[N];
478 }
479 return 0;
480}
481
482/*
483** Subterms pOne and pTwo are contained within WHERE clause pWC. The
484** two subterms are in disjunction - they are OR-ed together.
485**
486** If these two terms are both of the form: "A op B" with the same
487** A and B values but different operators and if the operators are
488** compatible (if one is = and the other is <, for example) then
489** add a new virtual AND term to pWC that is the combination of the
490** two.
491**
492** Some examples:
493**
494** x<y OR x=y --> x<=y
495** x=y OR x=y --> x=y
496** x<=y OR x<y --> x<=y
497**
498** The following is NOT generated:
499**
500** x<y OR x>y --> x!=y
501*/
502static void whereCombineDisjuncts(
503 SrcList *pSrc, /* the FROM clause */
504 WhereClause *pWC, /* The complete WHERE clause */
505 WhereTerm *pOne, /* First disjunct */
506 WhereTerm *pTwo /* Second disjunct */
507){
508 u16 eOp = pOne->eOperator | pTwo->eOperator;
509 sqlite3 *db; /* Database connection (for malloc) */
510 Expr *pNew; /* New virtual expression */
511 int op; /* Operator for the combined expression */
512 int idxNew; /* Index in pWC of the next virtual term */
513
514 if( (pOne->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
515 if( (pTwo->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
516 if( (eOp & (WO_EQ|WO_LT|WO_LE))!=eOp
517 && (eOp & (WO_EQ|WO_GT|WO_GE))!=eOp ) return;
518 assert( pOne->pExpr->pLeft!=0 && pOne->pExpr->pRight!=0 );
519 assert( pTwo->pExpr->pLeft!=0 && pTwo->pExpr->pRight!=0 );
dan5aa550c2017-06-24 18:10:29 +0000520 if( sqlite3ExprCompare(0,pOne->pExpr->pLeft, pTwo->pExpr->pLeft, -1) ) return;
521 if( sqlite3ExprCompare(0,pOne->pExpr->pRight, pTwo->pExpr->pRight,-1) )return;
drh6c1f4ef2015-06-08 14:23:15 +0000522 /* If we reach this point, it means the two subterms can be combined */
523 if( (eOp & (eOp-1))!=0 ){
524 if( eOp & (WO_LT|WO_LE) ){
525 eOp = WO_LE;
526 }else{
527 assert( eOp & (WO_GT|WO_GE) );
528 eOp = WO_GE;
529 }
530 }
531 db = pWC->pWInfo->pParse->db;
532 pNew = sqlite3ExprDup(db, pOne->pExpr, 0);
533 if( pNew==0 ) return;
534 for(op=TK_EQ; eOp!=(WO_EQ<<(op-TK_EQ)); op++){ assert( op<TK_GE ); }
535 pNew->op = op;
536 idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
537 exprAnalyze(pSrc, pWC, idxNew);
538}
539
540#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
541/*
542** Analyze a term that consists of two or more OR-connected
543** subterms. So in:
544**
545** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
546** ^^^^^^^^^^^^^^^^^^^^
547**
548** This routine analyzes terms such as the middle term in the above example.
549** A WhereOrTerm object is computed and attached to the term under
550** analysis, regardless of the outcome of the analysis. Hence:
551**
552** WhereTerm.wtFlags |= TERM_ORINFO
553** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object
554**
555** The term being analyzed must have two or more of OR-connected subterms.
556** A single subterm might be a set of AND-connected sub-subterms.
557** Examples of terms under analysis:
558**
559** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
560** (B) x=expr1 OR expr2=x OR x=expr3
561** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
562** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
563** (E) (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
564** (F) x>A OR (x=A AND y>=B)
565**
566** CASE 1:
567**
568** If all subterms are of the form T.C=expr for some single column of C and
569** a single table T (as shown in example B above) then create a new virtual
570** term that is an equivalent IN expression. In other words, if the term
571** being analyzed is:
572**
573** x = expr1 OR expr2 = x OR x = expr3
574**
575** then create a new virtual term like this:
576**
577** x IN (expr1,expr2,expr3)
578**
579** CASE 2:
580**
581** If there are exactly two disjuncts and one side has x>A and the other side
582** has x=A (for the same x and A) then add a new virtual conjunct term to the
583** WHERE clause of the form "x>=A". Example:
584**
585** x>A OR (x=A AND y>B) adds: x>=A
586**
587** The added conjunct can sometimes be helpful in query planning.
588**
589** CASE 3:
590**
591** If all subterms are indexable by a single table T, then set
592**
593** WhereTerm.eOperator = WO_OR
594** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T
595**
596** A subterm is "indexable" if it is of the form
597** "T.C <op> <expr>" where C is any column of table T and
598** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
599** A subterm is also indexable if it is an AND of two or more
600** subsubterms at least one of which is indexable. Indexable AND
601** subterms have their eOperator set to WO_AND and they have
602** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
603**
604** From another point of view, "indexable" means that the subterm could
605** potentially be used with an index if an appropriate index exists.
606** This analysis does not consider whether or not the index exists; that
607** is decided elsewhere. This analysis only looks at whether subterms
608** appropriate for indexing exist.
609**
610** All examples A through E above satisfy case 3. But if a term
611** also satisfies case 1 (such as B) we know that the optimizer will
612** always prefer case 1, so in that case we pretend that case 3 is not
613** satisfied.
614**
615** It might be the case that multiple tables are indexable. For example,
616** (E) above is indexable on tables P, Q, and R.
617**
618** Terms that satisfy case 3 are candidates for lookup by using
619** separate indices to find rowids for each subterm and composing
620** the union of all rowids using a RowSet object. This is similar
621** to "bitmap indices" in other database engines.
622**
623** OTHERWISE:
624**
625** If none of cases 1, 2, or 3 apply, then leave the eOperator set to
626** zero. This term is not useful for search.
627*/
628static void exprAnalyzeOrTerm(
629 SrcList *pSrc, /* the FROM clause */
630 WhereClause *pWC, /* the complete WHERE clause */
631 int idxTerm /* Index of the OR-term to be analyzed */
632){
633 WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
634 Parse *pParse = pWInfo->pParse; /* Parser context */
635 sqlite3 *db = pParse->db; /* Database connection */
636 WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */
637 Expr *pExpr = pTerm->pExpr; /* The expression of the term */
638 int i; /* Loop counters */
639 WhereClause *pOrWc; /* Breakup of pTerm into subterms */
640 WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */
641 WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */
642 Bitmask chngToIN; /* Tables that might satisfy case 1 */
643 Bitmask indexable; /* Tables that are indexable, satisfying case 2 */
644
645 /*
646 ** Break the OR clause into its separate subterms. The subterms are
647 ** stored in a WhereClause structure containing within the WhereOrInfo
648 ** object that is attached to the original OR clause term.
649 */
650 assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
651 assert( pExpr->op==TK_OR );
652 pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
653 if( pOrInfo==0 ) return;
654 pTerm->wtFlags |= TERM_ORINFO;
655 pOrWc = &pOrInfo->wc;
drh81fd3492016-02-19 14:10:44 +0000656 memset(pOrWc->aStatic, 0, sizeof(pOrWc->aStatic));
drh6c1f4ef2015-06-08 14:23:15 +0000657 sqlite3WhereClauseInit(pOrWc, pWInfo);
658 sqlite3WhereSplit(pOrWc, pExpr, TK_OR);
659 sqlite3WhereExprAnalyze(pSrc, pOrWc);
660 if( db->mallocFailed ) return;
661 assert( pOrWc->nTerm>=2 );
662
663 /*
664 ** Compute the set of tables that might satisfy cases 1 or 3.
665 */
666 indexable = ~(Bitmask)0;
667 chngToIN = ~(Bitmask)0;
668 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
669 if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
670 WhereAndInfo *pAndInfo;
671 assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
672 chngToIN = 0;
drh575fad62016-02-05 13:38:36 +0000673 pAndInfo = sqlite3DbMallocRawNN(db, sizeof(*pAndInfo));
drh6c1f4ef2015-06-08 14:23:15 +0000674 if( pAndInfo ){
675 WhereClause *pAndWC;
676 WhereTerm *pAndTerm;
677 int j;
678 Bitmask b = 0;
679 pOrTerm->u.pAndInfo = pAndInfo;
680 pOrTerm->wtFlags |= TERM_ANDINFO;
681 pOrTerm->eOperator = WO_AND;
682 pAndWC = &pAndInfo->wc;
drh81fd3492016-02-19 14:10:44 +0000683 memset(pAndWC->aStatic, 0, sizeof(pAndWC->aStatic));
drh6c1f4ef2015-06-08 14:23:15 +0000684 sqlite3WhereClauseInit(pAndWC, pWC->pWInfo);
685 sqlite3WhereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
686 sqlite3WhereExprAnalyze(pSrc, pAndWC);
687 pAndWC->pOuter = pWC;
drh6c1f4ef2015-06-08 14:23:15 +0000688 if( !db->mallocFailed ){
689 for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
690 assert( pAndTerm->pExpr );
dandbd2dcb2016-05-28 18:53:55 +0000691 if( allowedOp(pAndTerm->pExpr->op)
drh303a69b2017-09-11 19:47:37 +0000692 || pAndTerm->eOperator==WO_AUX
dandbd2dcb2016-05-28 18:53:55 +0000693 ){
drh6c1f4ef2015-06-08 14:23:15 +0000694 b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
695 }
696 }
697 }
698 indexable &= b;
699 }
700 }else if( pOrTerm->wtFlags & TERM_COPIED ){
701 /* Skip this term for now. We revisit it when we process the
702 ** corresponding TERM_VIRTUAL term */
703 }else{
704 Bitmask b;
705 b = sqlite3WhereGetMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
706 if( pOrTerm->wtFlags & TERM_VIRTUAL ){
707 WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
708 b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pOther->leftCursor);
709 }
710 indexable &= b;
711 if( (pOrTerm->eOperator & WO_EQ)==0 ){
712 chngToIN = 0;
713 }else{
714 chngToIN &= b;
715 }
716 }
717 }
718
719 /*
720 ** Record the set of tables that satisfy case 3. The set might be
721 ** empty.
722 */
723 pOrInfo->indexable = indexable;
drhda230bd2018-06-09 00:09:58 +0000724 if( indexable ){
725 pTerm->eOperator = WO_OR;
726 pWC->hasOr = 1;
727 }else{
728 pTerm->eOperator = WO_OR;
729 }
drh6c1f4ef2015-06-08 14:23:15 +0000730
731 /* For a two-way OR, attempt to implementation case 2.
732 */
733 if( indexable && pOrWc->nTerm==2 ){
734 int iOne = 0;
735 WhereTerm *pOne;
736 while( (pOne = whereNthSubterm(&pOrWc->a[0],iOne++))!=0 ){
737 int iTwo = 0;
738 WhereTerm *pTwo;
739 while( (pTwo = whereNthSubterm(&pOrWc->a[1],iTwo++))!=0 ){
740 whereCombineDisjuncts(pSrc, pWC, pOne, pTwo);
741 }
742 }
743 }
744
745 /*
746 ** chngToIN holds a set of tables that *might* satisfy case 1. But
747 ** we have to do some additional checking to see if case 1 really
748 ** is satisfied.
749 **
750 ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means
751 ** that there is no possibility of transforming the OR clause into an
752 ** IN operator because one or more terms in the OR clause contain
753 ** something other than == on a column in the single table. The 1-bit
754 ** case means that every term of the OR clause is of the form
755 ** "table.column=expr" for some single table. The one bit that is set
756 ** will correspond to the common table. We still need to check to make
757 ** sure the same column is used on all terms. The 2-bit case is when
758 ** the all terms are of the form "table1.column=table2.column". It
759 ** might be possible to form an IN operator with either table1.column
760 ** or table2.column as the LHS if either is common to every term of
761 ** the OR clause.
762 **
763 ** Note that terms of the form "table.column1=table.column2" (the
764 ** same table on both sizes of the ==) cannot be optimized.
765 */
766 if( chngToIN ){
767 int okToChngToIN = 0; /* True if the conversion to IN is valid */
768 int iColumn = -1; /* Column index on lhs of IN operator */
769 int iCursor = -1; /* Table cursor common to all terms */
770 int j = 0; /* Loop counter */
771
772 /* Search for a table and column that appears on one side or the
773 ** other of the == operator in every subterm. That table and column
774 ** will be recorded in iCursor and iColumn. There might not be any
775 ** such table and column. Set okToChngToIN if an appropriate table
776 ** and column is found but leave okToChngToIN false if not found.
777 */
778 for(j=0; j<2 && !okToChngToIN; j++){
dan7525b872018-12-14 08:40:11 +0000779 Expr *pLeft = 0;
drh3c2db5d2018-12-14 18:11:02 +0000780 pOrTerm = pOrWc->a;
drh6c1f4ef2015-06-08 14:23:15 +0000781 for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
782 assert( pOrTerm->eOperator & WO_EQ );
783 pOrTerm->wtFlags &= ~TERM_OR_OK;
784 if( pOrTerm->leftCursor==iCursor ){
785 /* This is the 2-bit case and we are on the second iteration and
786 ** current term is from the first iteration. So skip this term. */
787 assert( j==1 );
788 continue;
789 }
790 if( (chngToIN & sqlite3WhereGetMask(&pWInfo->sMaskSet,
791 pOrTerm->leftCursor))==0 ){
792 /* This term must be of the form t1.a==t2.b where t2 is in the
793 ** chngToIN set but t1 is not. This term will be either preceded
794 ** or follwed by an inverted copy (t2.b==t1.a). Skip this term
795 ** and use its inversion. */
796 testcase( pOrTerm->wtFlags & TERM_COPIED );
797 testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
798 assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
799 continue;
800 }
drh75fa2662020-09-28 15:49:43 +0000801 iColumn = pOrTerm->u.x.leftColumn;
drh6c1f4ef2015-06-08 14:23:15 +0000802 iCursor = pOrTerm->leftCursor;
dan7525b872018-12-14 08:40:11 +0000803 pLeft = pOrTerm->pExpr->pLeft;
drh6c1f4ef2015-06-08 14:23:15 +0000804 break;
805 }
806 if( i<0 ){
807 /* No candidate table+column was found. This can only occur
808 ** on the second iteration */
809 assert( j==1 );
810 assert( IsPowerOfTwo(chngToIN) );
811 assert( chngToIN==sqlite3WhereGetMask(&pWInfo->sMaskSet, iCursor) );
812 break;
813 }
814 testcase( j==1 );
815
816 /* We have found a candidate table and column. Check to see if that
817 ** table and column is common to every term in the OR clause */
818 okToChngToIN = 1;
819 for(; i>=0 && okToChngToIN; i--, pOrTerm++){
820 assert( pOrTerm->eOperator & WO_EQ );
821 if( pOrTerm->leftCursor!=iCursor ){
822 pOrTerm->wtFlags &= ~TERM_OR_OK;
drh75fa2662020-09-28 15:49:43 +0000823 }else if( pOrTerm->u.x.leftColumn!=iColumn || (iColumn==XN_EXPR
dan7525b872018-12-14 08:40:11 +0000824 && sqlite3ExprCompare(pParse, pOrTerm->pExpr->pLeft, pLeft, -1)
825 )){
drh6c1f4ef2015-06-08 14:23:15 +0000826 okToChngToIN = 0;
827 }else{
828 int affLeft, affRight;
829 /* If the right-hand side is also a column, then the affinities
830 ** of both right and left sides must be such that no type
831 ** conversions are required on the right. (Ticket #2249)
832 */
833 affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
834 affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
835 if( affRight!=0 && affRight!=affLeft ){
836 okToChngToIN = 0;
837 }else{
838 pOrTerm->wtFlags |= TERM_OR_OK;
839 }
840 }
841 }
842 }
843
844 /* At this point, okToChngToIN is true if original pTerm satisfies
845 ** case 1. In that case, construct a new virtual term that is
846 ** pTerm converted into an IN operator.
847 */
848 if( okToChngToIN ){
849 Expr *pDup; /* A transient duplicate expression */
850 ExprList *pList = 0; /* The RHS of the IN operator */
851 Expr *pLeft = 0; /* The LHS of the IN operator */
852 Expr *pNew; /* The complete IN operator */
853
854 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
855 if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
856 assert( pOrTerm->eOperator & WO_EQ );
857 assert( pOrTerm->leftCursor==iCursor );
drh75fa2662020-09-28 15:49:43 +0000858 assert( pOrTerm->u.x.leftColumn==iColumn );
drh6c1f4ef2015-06-08 14:23:15 +0000859 pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
860 pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
861 pLeft = pOrTerm->pExpr->pLeft;
862 }
863 assert( pLeft!=0 );
864 pDup = sqlite3ExprDup(db, pLeft, 0);
drhabfd35e2016-12-06 22:47:23 +0000865 pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0);
drh6c1f4ef2015-06-08 14:23:15 +0000866 if( pNew ){
867 int idxNew;
868 transferJoinMarkings(pNew, pExpr);
869 assert( !ExprHasProperty(pNew, EP_xIsSelect) );
870 pNew->x.pList = pList;
871 idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
872 testcase( idxNew==0 );
873 exprAnalyze(pSrc, pWC, idxNew);
drhc4ceea72018-08-21 12:16:33 +0000874 /* pTerm = &pWC->a[idxTerm]; // would be needed if pTerm where used again */
drh6c1f4ef2015-06-08 14:23:15 +0000875 markTermAsChild(pWC, idxNew, idxTerm);
876 }else{
877 sqlite3ExprListDelete(db, pList);
878 }
drh6c1f4ef2015-06-08 14:23:15 +0000879 }
880 }
881}
882#endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
883
884/*
885** We already know that pExpr is a binary operator where both operands are
886** column references. This routine checks to see if pExpr is an equivalence
887** relation:
888** 1. The SQLITE_Transitive optimization must be enabled
889** 2. Must be either an == or an IS operator
890** 3. Not originating in the ON clause of an OUTER JOIN
891** 4. The affinities of A and B must be compatible
892** 5a. Both operands use the same collating sequence OR
893** 5b. The overall collating sequence is BINARY
894** If this routine returns TRUE, that means that the RHS can be substituted
895** for the LHS anyplace else in the WHERE clause where the LHS column occurs.
896** This is an optimization. No harm comes from returning 0. But if 1 is
897** returned when it should not be, then incorrect answers might result.
898*/
899static int termIsEquivalence(Parse *pParse, Expr *pExpr){
900 char aff1, aff2;
901 CollSeq *pColl;
drh6c1f4ef2015-06-08 14:23:15 +0000902 if( !OptimizationEnabled(pParse->db, SQLITE_Transitive) ) return 0;
903 if( pExpr->op!=TK_EQ && pExpr->op!=TK_IS ) return 0;
904 if( ExprHasProperty(pExpr, EP_FromJoin) ) return 0;
905 aff1 = sqlite3ExprAffinity(pExpr->pLeft);
906 aff2 = sqlite3ExprAffinity(pExpr->pRight);
907 if( aff1!=aff2
908 && (!sqlite3IsNumericAffinity(aff1) || !sqlite3IsNumericAffinity(aff2))
909 ){
910 return 0;
911 }
drh898c5272019-10-22 00:03:41 +0000912 pColl = sqlite3ExprCompareCollSeq(pParse, pExpr);
drhefad2e22018-07-27 16:57:11 +0000913 if( sqlite3IsBinary(pColl) ) return 1;
drh70efa842017-09-28 01:58:23 +0000914 return sqlite3ExprCollSeqMatch(pParse, pExpr->pLeft, pExpr->pRight);
drh6c1f4ef2015-06-08 14:23:15 +0000915}
916
917/*
918** Recursively walk the expressions of a SELECT statement and generate
919** a bitmask indicating which tables are used in that expression
920** tree.
921*/
922static Bitmask exprSelectUsage(WhereMaskSet *pMaskSet, Select *pS){
923 Bitmask mask = 0;
924 while( pS ){
925 SrcList *pSrc = pS->pSrc;
926 mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pEList);
927 mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pGroupBy);
928 mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pOrderBy);
929 mask |= sqlite3WhereExprUsage(pMaskSet, pS->pWhere);
930 mask |= sqlite3WhereExprUsage(pMaskSet, pS->pHaving);
931 if( ALWAYS(pSrc!=0) ){
932 int i;
933 for(i=0; i<pSrc->nSrc; i++){
934 mask |= exprSelectUsage(pMaskSet, pSrc->a[i].pSelect);
935 mask |= sqlite3WhereExprUsage(pMaskSet, pSrc->a[i].pOn);
drh33f763d2018-01-26 22:41:59 +0000936 if( pSrc->a[i].fg.isTabFunc ){
937 mask |= sqlite3WhereExprListUsage(pMaskSet, pSrc->a[i].u1.pFuncArg);
938 }
drh6c1f4ef2015-06-08 14:23:15 +0000939 }
940 }
941 pS = pS->pPrior;
942 }
943 return mask;
944}
945
946/*
drh47991422015-08-31 15:58:06 +0000947** Expression pExpr is one operand of a comparison operator that might
948** be useful for indexing. This routine checks to see if pExpr appears
949** in any index. Return TRUE (1) if pExpr is an indexed term and return
drhe97c9ff2017-04-11 18:06:48 +0000950** FALSE (0) if not. If TRUE is returned, also set aiCurCol[0] to the cursor
951** number of the table that is indexed and aiCurCol[1] to the column number
drh8d25cb92016-08-19 19:58:06 +0000952** of the column that is indexed, or XN_EXPR (-2) if an expression is being
953** indexed.
drh47991422015-08-31 15:58:06 +0000954**
955** If pExpr is a TK_COLUMN column reference, then this routine always returns
956** true even if that particular column is not indexed, because the column
957** might be added to an automatic index later.
958*/
drhe97c9ff2017-04-11 18:06:48 +0000959static SQLITE_NOINLINE int exprMightBeIndexed2(
drh47991422015-08-31 15:58:06 +0000960 SrcList *pFrom, /* The FROM clause */
961 Bitmask mPrereq, /* Bitmask of FROM clause terms referenced by pExpr */
drhe97c9ff2017-04-11 18:06:48 +0000962 int *aiCurCol, /* Write the referenced table cursor and column here */
963 Expr *pExpr /* An operand of a comparison operator */
drh47991422015-08-31 15:58:06 +0000964){
965 Index *pIdx;
966 int i;
967 int iCur;
drhe97c9ff2017-04-11 18:06:48 +0000968 for(i=0; mPrereq>1; i++, mPrereq>>=1){}
969 iCur = pFrom->a[i].iCursor;
970 for(pIdx=pFrom->a[i].pTab->pIndex; pIdx; pIdx=pIdx->pNext){
971 if( pIdx->aColExpr==0 ) continue;
972 for(i=0; i<pIdx->nKeyCol; i++){
973 if( pIdx->aiColumn[i]!=XN_EXPR ) continue;
974 if( sqlite3ExprCompareSkip(pExpr, pIdx->aColExpr->a[i].pExpr, iCur)==0 ){
975 aiCurCol[0] = iCur;
976 aiCurCol[1] = XN_EXPR;
977 return 1;
978 }
979 }
980 }
981 return 0;
982}
983static int exprMightBeIndexed(
984 SrcList *pFrom, /* The FROM clause */
985 Bitmask mPrereq, /* Bitmask of FROM clause terms referenced by pExpr */
986 int *aiCurCol, /* Write the referenced table cursor & column here */
987 Expr *pExpr, /* An operand of a comparison operator */
988 int op /* The specific comparison operator */
989){
dan71c57db2016-07-09 20:23:55 +0000990 /* If this expression is a vector to the left or right of a
991 ** inequality constraint (>, <, >= or <=), perform the processing
992 ** on the first element of the vector. */
993 assert( TK_GT+1==TK_LE && TK_GT+2==TK_LT && TK_GT+3==TK_GE );
drh64bcb8c2016-08-26 03:42:57 +0000994 assert( TK_IS<TK_GE && TK_ISNULL<TK_GE && TK_IN<TK_GE );
995 assert( op<=TK_GE );
996 if( pExpr->op==TK_VECTOR && (op>=TK_GT && ALWAYS(op<=TK_GE)) ){
dan71c57db2016-07-09 20:23:55 +0000997 pExpr = pExpr->x.pList->a[0].pExpr;
998 }
999
drh47991422015-08-31 15:58:06 +00001000 if( pExpr->op==TK_COLUMN ){
drhe97c9ff2017-04-11 18:06:48 +00001001 aiCurCol[0] = pExpr->iTable;
1002 aiCurCol[1] = pExpr->iColumn;
drh47991422015-08-31 15:58:06 +00001003 return 1;
1004 }
1005 if( mPrereq==0 ) return 0; /* No table references */
1006 if( (mPrereq&(mPrereq-1))!=0 ) return 0; /* Refs more than one table */
drhe97c9ff2017-04-11 18:06:48 +00001007 return exprMightBeIndexed2(pFrom,mPrereq,aiCurCol,pExpr);
drh47991422015-08-31 15:58:06 +00001008}
1009
dan870a0702016-08-01 16:37:43 +00001010/*
dan6bfc1672021-01-14 20:50:40 +00001011** Expression callback for exprUsesSrclist().
1012*/
1013static int exprUsesSrclistCb(Walker *p, Expr *pExpr){
1014 if( pExpr->op==TK_COLUMN ){
1015 SrcList *pSrc = p->u.pSrcList;
1016 int iCsr = pExpr->iTable;
1017 int ii;
1018 for(ii=0; ii<pSrc->nSrc; ii++){
1019 if( pSrc->a[ii].iCursor==iCsr ){
1020 return p->eCode ? WRC_Abort : WRC_Continue;
1021 }
1022 }
1023 return p->eCode ? WRC_Continue : WRC_Abort;
1024 }
1025 return WRC_Continue;
1026}
1027
1028/*
1029** Select callback for exprUsesSrclist().
1030*/
drh87296422021-02-07 12:59:43 +00001031static int exprUsesSrclistSelectCb(Walker *NotUsed1, Select *NotUsed2){
1032 UNUSED_PARAMETER(NotUsed1);
1033 UNUSED_PARAMETER(NotUsed2);
dan6bfc1672021-01-14 20:50:40 +00001034 return WRC_Abort;
1035}
1036
1037/*
1038** This function always returns true if expression pExpr contains
1039** a sub-select.
1040**
drh06afa292021-01-18 00:11:20 +00001041** If there is no sub-select in pExpr, then return true if pExpr
1042** contains a TK_COLUMN node for a table that is (bUses==1)
1043** or is not (bUses==0) in pSrc.
dan6bfc1672021-01-14 20:50:40 +00001044**
drh06afa292021-01-18 00:11:20 +00001045** Said another way:
1046**
1047** bUses Return Meaning
1048** -------- ------ ------------------------------------------------
1049**
1050** bUses==1 true pExpr contains either a sub-select or a
1051** TK_COLUMN referencing pSrc.
1052**
1053** bUses==1 false pExpr contains no sub-selects and all TK_COLUMN
1054** nodes reference tables not found in pSrc
1055**
1056** bUses==0 true pExpr contains either a sub-select or a TK_COLUMN
1057** that references a table not in pSrc.
1058**
1059** bUses==0 false pExpr contains no sub-selects and all TK_COLUMN
1060** nodes reference pSrc
dan6bfc1672021-01-14 20:50:40 +00001061*/
1062static int exprUsesSrclist(SrcList *pSrc, Expr *pExpr, int bUses){
1063 Walker sWalker;
1064 memset(&sWalker, 0, sizeof(Walker));
1065 sWalker.eCode = bUses;
1066 sWalker.u.pSrcList = pSrc;
1067 sWalker.xExprCallback = exprUsesSrclistCb;
1068 sWalker.xSelectCallback = exprUsesSrclistSelectCb;
1069 return (sqlite3WalkExpr(&sWalker, pExpr)==WRC_Abort);
1070}
1071
dana828d562021-01-15 16:37:32 +00001072/*
1073** Context object used by exprExistsToInIter() as it iterates through an
1074** expression tree.
1075*/
dan6bfc1672021-01-14 20:50:40 +00001076struct ExistsToInCtx {
drh06afa292021-01-18 00:11:20 +00001077 SrcList *pSrc; /* The tables in an EXISTS(SELECT ... FROM <here> ...) */
1078 Expr *pInLhs; /* OUT: Use this as the LHS of the IN operator */
1079 Expr *pEq; /* OUT: The == term that include pInLhs */
1080 Expr **ppAnd; /* OUT: The AND operator that includes pEq as a child */
1081 Expr **ppParent; /* The AND operator currently being examined */
dan6bfc1672021-01-14 20:50:40 +00001082};
1083
dana828d562021-01-15 16:37:32 +00001084/*
1085** Iterate through all AND connected nodes in the expression tree
1086** headed by (*ppExpr), populating the structure passed as the first
1087** argument with the values required by exprAnalyzeExistsFindEq().
1088**
1089** This function returns non-zero if the expression tree does not meet
1090** the two conditions described by the header comment for
1091** exprAnalyzeExistsFindEq(), or zero if it does.
1092*/
dan76cac6e2021-01-15 11:39:46 +00001093static int exprExistsToInIter(struct ExistsToInCtx *p, Expr **ppExpr){
1094 Expr *pExpr = *ppExpr;
dan6bfc1672021-01-14 20:50:40 +00001095 switch( pExpr->op ){
1096 case TK_AND:
1097 p->ppParent = ppExpr;
dan76cac6e2021-01-15 11:39:46 +00001098 if( exprExistsToInIter(p, &pExpr->pLeft) ) return 1;
dan6bfc1672021-01-14 20:50:40 +00001099 p->ppParent = ppExpr;
dan76cac6e2021-01-15 11:39:46 +00001100 if( exprExistsToInIter(p, &pExpr->pRight) ) return 1;
dan6bfc1672021-01-14 20:50:40 +00001101 break;
1102 case TK_EQ: {
1103 int bLeft = exprUsesSrclist(p->pSrc, pExpr->pLeft, 0);
1104 int bRight = exprUsesSrclist(p->pSrc, pExpr->pRight, 0);
1105 if( bLeft || bRight ){
1106 if( (bLeft && bRight) || p->pInLhs ) return 1;
1107 p->pInLhs = bLeft ? pExpr->pLeft : pExpr->pRight;
dan76cac6e2021-01-15 11:39:46 +00001108 if( exprUsesSrclist(p->pSrc, p->pInLhs, 1) ) return 1;
dan6bfc1672021-01-14 20:50:40 +00001109 p->pEq = pExpr;
1110 p->ppAnd = p->ppParent;
dan6bfc1672021-01-14 20:50:40 +00001111 }
1112 break;
1113 }
1114 default:
1115 if( exprUsesSrclist(p->pSrc, pExpr, 0) ){
1116 return 1;
1117 }
1118 break;
1119 }
1120
1121 return 0;
1122}
1123
dana828d562021-01-15 16:37:32 +00001124/*
drh2a3be742021-01-16 18:22:10 +00001125** This function is used by exprAnalyzeExists() when creating virtual IN(...)
dana828d562021-01-15 16:37:32 +00001126** terms equivalent to user-supplied EXIST(...) clauses. It splits the WHERE
1127** clause of the Select object passed as the first argument into one or more
1128** expressions joined by AND operators, and then tests if the following are
1129** true:
1130**
1131** 1. Exactly one of the AND separated terms refers to the outer
1132** query, and it is an == (TK_EQ) expression.
1133**
1134** 2. Only one side of the == expression refers to the outer query, and
1135** it does not refer to any columns from the inner query.
1136**
1137** If both these conditions are true, then a pointer to the side of the ==
1138** expression that refers to the outer query is returned. The caller will
1139** use this expression as the LHS of the IN(...) virtual term. Or, if one
1140** or both of the above conditions are not true, NULL is returned.
1141**
1142** If non-NULL is returned and ppEq is non-NULL, *ppEq is set to point
1143** to the == expression node before returning. If pppAnd is non-NULL and
1144** the == node is not the root of the WHERE clause, then *pppAnd is set
1145** to point to the pointer to the AND node that is the parent of the ==
1146** node within the WHERE expression tree.
1147*/
dan6bfc1672021-01-14 20:50:40 +00001148static Expr *exprAnalyzeExistsFindEq(
drh06afa292021-01-18 00:11:20 +00001149 Select *pSel, /* The SELECT of the EXISTS */
dan6bfc1672021-01-14 20:50:40 +00001150 Expr **ppEq, /* OUT: == node from WHERE clause */
1151 Expr ***pppAnd /* OUT: Pointer to parent of ==, if any */
1152){
1153 struct ExistsToInCtx ctx;
1154 memset(&ctx, 0, sizeof(ctx));
dan76cac6e2021-01-15 11:39:46 +00001155 ctx.pSrc = pSel->pSrc;
1156 if( exprExistsToInIter(&ctx, &pSel->pWhere) ){
dan6bfc1672021-01-14 20:50:40 +00001157 return 0;
1158 }
1159 if( ppEq ) *ppEq = ctx.pEq;
1160 if( pppAnd ) *pppAnd = ctx.ppAnd;
1161 return ctx.pInLhs;
1162}
1163
1164/*
1165** Term idxTerm of the WHERE clause passed as the second argument is an
1166** EXISTS expression with a correlated SELECT statement on the RHS.
1167** This function analyzes the SELECT statement, and if possible adds an
1168** equivalent "? IN(SELECT...)" virtual term to the WHERE clause.
1169**
1170** For an EXISTS term such as the following:
1171**
1172** EXISTS (SELECT ... FROM <srclist> WHERE <e1> = <e2> AND <e3>)
1173**
1174** The virtual IN() term added is:
1175**
1176** <e1> IN (SELECT <e2> FROM <srclist> WHERE <e3>)
1177**
1178** The virtual term is only added if the following conditions are met:
1179**
1180** 1. The sub-select must not be an aggregate or use window functions,
1181**
1182** 2. The sub-select must not be a compound SELECT,
1183**
1184** 3. Expression <e1> must refer to at least one column from the outer
1185** query, and must not refer to any column from the inner query
1186** (i.e. from <srclist>).
1187**
1188** 4. <e2> and <e3> must not refer to any values from the outer query.
1189** In other words, once <e1> has been removed, the inner query
1190** must not be correlated.
1191**
1192*/
1193static void exprAnalyzeExists(
1194 SrcList *pSrc, /* the FROM clause */
1195 WhereClause *pWC, /* the WHERE clause */
1196 int idxTerm /* Index of the term to be analyzed */
1197){
1198 Parse *pParse = pWC->pWInfo->pParse;
1199 WhereTerm *pTerm = &pWC->a[idxTerm];
1200 Expr *pExpr = pTerm->pExpr;
1201 Select *pSel = pExpr->x.pSelect;
1202 Expr *pDup = 0;
1203 Expr *pEq = 0;
1204 Expr *pRet = 0;
1205 Expr *pInLhs = 0;
1206 Expr **ppAnd = 0;
1207 int idxNew;
drh9d326d62021-01-15 15:21:27 +00001208 sqlite3 *db = pParse->db;
dan6bfc1672021-01-14 20:50:40 +00001209
1210 assert( pExpr->op==TK_EXISTS );
1211 assert( (pExpr->flags & EP_VarSelect) && (pExpr->flags & EP_xIsSelect) );
1212
1213 if( (pSel->selFlags & SF_Aggregate) || pSel->pWin ) return;
1214 if( pSel->pPrior ) return;
1215 if( pSel->pWhere==0 ) return;
dan76cac6e2021-01-15 11:39:46 +00001216 if( 0==exprAnalyzeExistsFindEq(pSel, 0, 0) ) return;
dan6bfc1672021-01-14 20:50:40 +00001217
drh9d326d62021-01-15 15:21:27 +00001218 pDup = sqlite3ExprDup(db, pExpr, 0);
1219 if( db->mallocFailed ){
1220 sqlite3ExprDelete(db, pDup);
1221 return;
1222 }
dan6bfc1672021-01-14 20:50:40 +00001223 pSel = pDup->x.pSelect;
drh9d326d62021-01-15 15:21:27 +00001224 sqlite3ExprListDelete(db, pSel->pEList);
dan6bfc1672021-01-14 20:50:40 +00001225 pSel->pEList = 0;
1226
dan76cac6e2021-01-15 11:39:46 +00001227 pInLhs = exprAnalyzeExistsFindEq(pSel, &pEq, &ppAnd);
1228 assert( pInLhs && pEq );
1229 assert( pEq==pSel->pWhere || ppAnd );
dane8f7fcf2021-01-15 15:32:09 +00001230 if( pInLhs==pEq->pLeft ){
1231 pRet = pEq->pRight;
1232 }else{
drh9ffa2582021-01-16 20:22:11 +00001233 CollSeq *p = sqlite3ExprCompareCollSeq(pParse, pEq);
1234 pInLhs = sqlite3ExprAddCollateString(pParse, pInLhs, p?p->zName:"BINARY");
dane8f7fcf2021-01-15 15:32:09 +00001235 pRet = pEq->pLeft;
1236 }
dan6bfc1672021-01-14 20:50:40 +00001237
1238 assert( pDup->pLeft==0 );
1239 pDup->op = TK_IN;
1240 pDup->pLeft = pInLhs;
1241 pDup->flags &= ~EP_VarSelect;
drh4be8bdc2021-01-16 18:55:10 +00001242 if( pRet->op==TK_VECTOR ){
1243 pSel->pEList = pRet->x.pList;
1244 pRet->x.pList = 0;
1245 sqlite3ExprDelete(db, pRet);
1246 }else{
1247 pSel->pEList = sqlite3ExprListAppend(pParse, 0, pRet);
1248 }
dan6bfc1672021-01-14 20:50:40 +00001249 pEq->pLeft = 0;
1250 pEq->pRight = 0;
1251 if( ppAnd ){
1252 Expr *pAnd = *ppAnd;
1253 Expr *pOther = (pAnd->pLeft==pEq) ? pAnd->pRight : pAnd->pLeft;
1254 pAnd->pLeft = pAnd->pRight = 0;
drh9d326d62021-01-15 15:21:27 +00001255 sqlite3ExprDelete(db, pAnd);
dan6bfc1672021-01-14 20:50:40 +00001256 *ppAnd = pOther;
1257 }else{
1258 assert( pSel->pWhere==pEq );
1259 pSel->pWhere = 0;
1260 }
drh9d326d62021-01-15 15:21:27 +00001261 sqlite3ExprDelete(db, pEq);
dan6bfc1672021-01-14 20:50:40 +00001262
drh2a3be742021-01-16 18:22:10 +00001263#ifdef WHERETRACE_ENABLED /* 0x20 */
1264 if( sqlite3WhereTrace & 0x20 ){
1265 sqlite3DebugPrintf("Convert EXISTS:\n");
1266 sqlite3TreeViewExpr(0, pExpr, 0);
1267 sqlite3DebugPrintf("into IN:\n");
1268 sqlite3TreeViewExpr(0, pDup, 0);
1269 }
1270#endif
dan6bfc1672021-01-14 20:50:40 +00001271 idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
drh9fcc8c62021-01-17 00:13:12 +00001272 exprAnalyze(pSrc, pWC, idxNew);
1273 markTermAsChild(pWC, idxNew, idxTerm);
1274 pWC->a[idxTerm].wtFlags |= TERM_COPIED;
dan6bfc1672021-01-14 20:50:40 +00001275}
1276
1277/*
drh6c1f4ef2015-06-08 14:23:15 +00001278** The input to this routine is an WhereTerm structure with only the
1279** "pExpr" field filled in. The job of this routine is to analyze the
1280** subexpression and populate all the other fields of the WhereTerm
1281** structure.
1282**
1283** If the expression is of the form "<expr> <op> X" it gets commuted
1284** to the standard form of "X <op> <expr>".
1285**
1286** If the expression is of the form "X <op> Y" where both X and Y are
1287** columns, then the original expression is unchanged and a new virtual
1288** term of the form "Y <op> X" is added to the WHERE clause and
1289** analyzed separately. The original term is marked with TERM_COPIED
1290** and the new term is marked with TERM_DYNAMIC (because it's pExpr
1291** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
1292** is a commuted copy of a prior term.) The original term has nChild=1
1293** and the copy has idxParent set to the index of the original term.
1294*/
1295static void exprAnalyze(
1296 SrcList *pSrc, /* the FROM clause */
1297 WhereClause *pWC, /* the WHERE clause */
1298 int idxTerm /* Index of the term to be analyzed */
1299){
1300 WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
1301 WhereTerm *pTerm; /* The term to be analyzed */
1302 WhereMaskSet *pMaskSet; /* Set of table index masks */
1303 Expr *pExpr; /* The expression to be analyzed */
1304 Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */
1305 Bitmask prereqAll; /* Prerequesites of pExpr */
1306 Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */
1307 Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */
1308 int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */
1309 int noCase = 0; /* uppercase equivalent to lowercase */
1310 int op; /* Top-level operator. pExpr->op */
1311 Parse *pParse = pWInfo->pParse; /* Parsing context */
1312 sqlite3 *db = pParse->db; /* Database connection */
mistachkin53be36b2017-11-03 06:45:37 +00001313 unsigned char eOp2 = 0; /* op2 value for LIKE/REGEXP/GLOB */
drhd9bcb322017-01-10 15:08:06 +00001314 int nLeft; /* Number of elements on left side vector */
drh6c1f4ef2015-06-08 14:23:15 +00001315
1316 if( db->mallocFailed ){
1317 return;
1318 }
1319 pTerm = &pWC->a[idxTerm];
1320 pMaskSet = &pWInfo->sMaskSet;
1321 pExpr = pTerm->pExpr;
1322 assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
1323 prereqLeft = sqlite3WhereExprUsage(pMaskSet, pExpr->pLeft);
1324 op = pExpr->op;
1325 if( op==TK_IN ){
1326 assert( pExpr->pRight==0 );
dan7b35a772016-07-28 19:47:15 +00001327 if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
drh6c1f4ef2015-06-08 14:23:15 +00001328 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
1329 pTerm->prereqRight = exprSelectUsage(pMaskSet, pExpr->x.pSelect);
1330 }else{
1331 pTerm->prereqRight = sqlite3WhereExprListUsage(pMaskSet, pExpr->x.pList);
1332 }
1333 }else if( op==TK_ISNULL ){
1334 pTerm->prereqRight = 0;
1335 }else{
1336 pTerm->prereqRight = sqlite3WhereExprUsage(pMaskSet, pExpr->pRight);
1337 }
dand3930b12017-07-10 15:17:30 +00001338 pMaskSet->bVarSelect = 0;
drhccf6db52018-06-09 02:49:11 +00001339 prereqAll = sqlite3WhereExprUsageNN(pMaskSet, pExpr);
dand3930b12017-07-10 15:17:30 +00001340 if( pMaskSet->bVarSelect ) pTerm->wtFlags |= TERM_VARSELECT;
drh6c1f4ef2015-06-08 14:23:15 +00001341 if( ExprHasProperty(pExpr, EP_FromJoin) ){
1342 Bitmask x = sqlite3WhereGetMask(pMaskSet, pExpr->iRightJoinTable);
1343 prereqAll |= x;
1344 extraRight = x-1; /* ON clause terms may not be used with an index
1345 ** on left table of a LEFT JOIN. Ticket #3015 */
drh8e36ddd2017-01-10 17:33:43 +00001346 if( (prereqAll>>1)>=x ){
1347 sqlite3ErrorMsg(pParse, "ON clause references tables to its right");
1348 return;
1349 }
drh6c1f4ef2015-06-08 14:23:15 +00001350 }
1351 pTerm->prereqAll = prereqAll;
1352 pTerm->leftCursor = -1;
1353 pTerm->iParent = -1;
1354 pTerm->eOperator = 0;
1355 if( allowedOp(op) ){
drhe97c9ff2017-04-11 18:06:48 +00001356 int aiCurCol[2];
drh6c1f4ef2015-06-08 14:23:15 +00001357 Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
1358 Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
1359 u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
dan8da209b2016-07-26 18:06:08 +00001360
drh75fa2662020-09-28 15:49:43 +00001361 if( pTerm->u.x.iField>0 ){
dan145b4ea2016-07-29 18:12:12 +00001362 assert( op==TK_IN );
dan8da209b2016-07-26 18:06:08 +00001363 assert( pLeft->op==TK_VECTOR );
drh75fa2662020-09-28 15:49:43 +00001364 pLeft = pLeft->x.pList->a[pTerm->u.x.iField-1].pExpr;
dan8da209b2016-07-26 18:06:08 +00001365 }
1366
drhe97c9ff2017-04-11 18:06:48 +00001367 if( exprMightBeIndexed(pSrc, prereqLeft, aiCurCol, pLeft, op) ){
1368 pTerm->leftCursor = aiCurCol[0];
drh75fa2662020-09-28 15:49:43 +00001369 pTerm->u.x.leftColumn = aiCurCol[1];
drh6860e6f2015-08-27 18:24:02 +00001370 pTerm->eOperator = operatorMask(op) & opMask;
drh6c1f4ef2015-06-08 14:23:15 +00001371 }
1372 if( op==TK_IS ) pTerm->wtFlags |= TERM_IS;
drh47991422015-08-31 15:58:06 +00001373 if( pRight
drhe97c9ff2017-04-11 18:06:48 +00001374 && exprMightBeIndexed(pSrc, pTerm->prereqRight, aiCurCol, pRight, op)
drh47991422015-08-31 15:58:06 +00001375 ){
drh6c1f4ef2015-06-08 14:23:15 +00001376 WhereTerm *pNew;
1377 Expr *pDup;
1378 u16 eExtraOp = 0; /* Extra bits for pNew->eOperator */
drh75fa2662020-09-28 15:49:43 +00001379 assert( pTerm->u.x.iField==0 );
drh6c1f4ef2015-06-08 14:23:15 +00001380 if( pTerm->leftCursor>=0 ){
1381 int idxNew;
1382 pDup = sqlite3ExprDup(db, pExpr, 0);
1383 if( db->mallocFailed ){
1384 sqlite3ExprDelete(db, pDup);
1385 return;
1386 }
1387 idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
1388 if( idxNew==0 ) return;
1389 pNew = &pWC->a[idxNew];
1390 markTermAsChild(pWC, idxNew, idxTerm);
1391 if( op==TK_IS ) pNew->wtFlags |= TERM_IS;
1392 pTerm = &pWC->a[idxTerm];
1393 pTerm->wtFlags |= TERM_COPIED;
1394
1395 if( termIsEquivalence(pParse, pDup) ){
1396 pTerm->eOperator |= WO_EQUIV;
1397 eExtraOp = WO_EQUIV;
1398 }
1399 }else{
1400 pDup = pExpr;
1401 pNew = pTerm;
1402 }
drhc7d12f42019-09-03 14:27:25 +00001403 pNew->wtFlags |= exprCommute(pParse, pDup);
drhe97c9ff2017-04-11 18:06:48 +00001404 pNew->leftCursor = aiCurCol[0];
drh75fa2662020-09-28 15:49:43 +00001405 pNew->u.x.leftColumn = aiCurCol[1];
drh6c1f4ef2015-06-08 14:23:15 +00001406 testcase( (prereqLeft | extraRight) != prereqLeft );
1407 pNew->prereqRight = prereqLeft | extraRight;
1408 pNew->prereqAll = prereqAll;
1409 pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
dan8ddf6862021-02-26 20:14:32 +00001410 }else if( op==TK_ISNULL && 0==sqlite3ExprCanBeNull(pLeft) ){
1411 pExpr->op = TK_TRUEFALSE;
1412 ExprSetProperty(pExpr, EP_IsFalse);
1413 pTerm->prereqAll = 0;
1414 pTerm->eOperator = 0;
drh6c1f4ef2015-06-08 14:23:15 +00001415 }
1416 }
1417
1418#ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
1419 /* If a term is the BETWEEN operator, create two new virtual terms
1420 ** that define the range that the BETWEEN implements. For example:
1421 **
1422 ** a BETWEEN b AND c
1423 **
1424 ** is converted into:
1425 **
1426 ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
1427 **
1428 ** The two new terms are added onto the end of the WhereClause object.
1429 ** The new terms are "dynamic" and are children of the original BETWEEN
1430 ** term. That means that if the BETWEEN term is coded, the children are
1431 ** skipped. Or, if the children are satisfied by an index, the original
1432 ** BETWEEN term is skipped.
1433 */
1434 else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
1435 ExprList *pList = pExpr->x.pList;
1436 int i;
1437 static const u8 ops[] = {TK_GE, TK_LE};
1438 assert( pList!=0 );
1439 assert( pList->nExpr==2 );
1440 for(i=0; i<2; i++){
1441 Expr *pNewExpr;
1442 int idxNew;
1443 pNewExpr = sqlite3PExpr(pParse, ops[i],
1444 sqlite3ExprDup(db, pExpr->pLeft, 0),
drhabfd35e2016-12-06 22:47:23 +00001445 sqlite3ExprDup(db, pList->a[i].pExpr, 0));
drh6c1f4ef2015-06-08 14:23:15 +00001446 transferJoinMarkings(pNewExpr, pExpr);
1447 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
1448 testcase( idxNew==0 );
1449 exprAnalyze(pSrc, pWC, idxNew);
1450 pTerm = &pWC->a[idxTerm];
1451 markTermAsChild(pWC, idxNew, idxTerm);
1452 }
1453 }
1454#endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
1455
1456#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
1457 /* Analyze a term that is composed of two or more subterms connected by
1458 ** an OR operator.
1459 */
1460 else if( pExpr->op==TK_OR ){
1461 assert( pWC->op==TK_AND );
1462 exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
1463 pTerm = &pWC->a[idxTerm];
1464 }
1465#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
1466
drh10c9ef62021-01-15 14:25:06 +00001467 else if( pExpr->op==TK_EXISTS ){
1468 /* Perhaps treat an EXISTS operator as an IN operator */
drh19ef2112021-01-15 15:17:14 +00001469 if( (pExpr->flags & EP_VarSelect)!=0
1470 && OptimizationEnabled(db, SQLITE_ExistsToIN)
1471 ){
drh10c9ef62021-01-15 14:25:06 +00001472 exprAnalyzeExists(pSrc, pWC, idxTerm);
1473 }
1474 }
1475
drh6cca0aa2021-01-21 17:54:41 +00001476 /* The form "x IS NOT NULL" can sometimes be evaluated more efficiently
1477 ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a
1478 ** virtual term of that form.
1479 **
1480 ** The virtual term must be tagged with TERM_VNULL.
1481 */
1482 else if( pExpr->op==TK_NOTNULL ){
1483 if( pExpr->pLeft->op==TK_COLUMN
1484 && pExpr->pLeft->iColumn>=0
1485 && !ExprHasProperty(pExpr, EP_FromJoin)
1486 ){
1487 Expr *pNewExpr;
1488 Expr *pLeft = pExpr->pLeft;
1489 int idxNew;
1490 WhereTerm *pNewTerm;
1491
1492 pNewExpr = sqlite3PExpr(pParse, TK_GT,
1493 sqlite3ExprDup(db, pLeft, 0),
1494 sqlite3ExprAlloc(db, TK_NULL, 0, 0));
1495
1496 idxNew = whereClauseInsert(pWC, pNewExpr,
1497 TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
1498 if( idxNew ){
1499 pNewTerm = &pWC->a[idxNew];
1500 pNewTerm->prereqRight = 0;
1501 pNewTerm->leftCursor = pLeft->iTable;
1502 pNewTerm->u.x.leftColumn = pLeft->iColumn;
1503 pNewTerm->eOperator = WO_GT;
1504 markTermAsChild(pWC, idxNew, idxTerm);
1505 pTerm = &pWC->a[idxTerm];
1506 pTerm->wtFlags |= TERM_COPIED;
1507 pNewTerm->prereqAll = pTerm->prereqAll;
1508 }
1509 }
1510 }
drh10c9ef62021-01-15 14:25:06 +00001511
drh71aff852021-01-21 20:42:36 +00001512
drh6c1f4ef2015-06-08 14:23:15 +00001513#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
1514 /* Add constraints to reduce the search space on a LIKE or GLOB
1515 ** operator.
1516 **
1517 ** A like pattern of the form "x LIKE 'aBc%'" is changed into constraints
1518 **
1519 ** x>='ABC' AND x<'abd' AND x LIKE 'aBc%'
1520 **
1521 ** The last character of the prefix "abc" is incremented to form the
1522 ** termination condition "abd". If case is not significant (the default
1523 ** for LIKE) then the lower-bound is made all uppercase and the upper-
1524 ** bound is made all lowercase so that the bounds also work when comparing
1525 ** BLOBs.
1526 */
drh71aff852021-01-21 20:42:36 +00001527 else if( pExpr->op==TK_FUNCTION
1528 && pWC->op==TK_AND
drh6c1f4ef2015-06-08 14:23:15 +00001529 && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
1530 ){
1531 Expr *pLeft; /* LHS of LIKE/GLOB operator */
1532 Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */
1533 Expr *pNewExpr1;
1534 Expr *pNewExpr2;
1535 int idxNew1;
1536 int idxNew2;
1537 const char *zCollSeqName; /* Name of collating sequence */
1538 const u16 wtFlags = TERM_LIKEOPT | TERM_VIRTUAL | TERM_DYNAMIC;
1539
1540 pLeft = pExpr->x.pList->a[1].pExpr;
1541 pStr2 = sqlite3ExprDup(db, pStr1, 0);
1542
1543 /* Convert the lower bound to upper-case and the upper bound to
1544 ** lower-case (upper-case is less than lower-case in ASCII) so that
1545 ** the range constraints also work for BLOBs
1546 */
1547 if( noCase && !pParse->db->mallocFailed ){
1548 int i;
1549 char c;
1550 pTerm->wtFlags |= TERM_LIKE;
1551 for(i=0; (c = pStr1->u.zToken[i])!=0; i++){
1552 pStr1->u.zToken[i] = sqlite3Toupper(c);
1553 pStr2->u.zToken[i] = sqlite3Tolower(c);
1554 }
1555 }
1556
1557 if( !db->mallocFailed ){
1558 u8 c, *pC; /* Last character before the first wildcard */
1559 pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
1560 c = *pC;
1561 if( noCase ){
1562 /* The point is to increment the last character before the first
1563 ** wildcard. But if we increment '@', that will push it into the
1564 ** alphabetic range where case conversions will mess up the
1565 ** inequality. To avoid this, make sure to also run the full
1566 ** LIKE on all candidate expressions by clearing the isComplete flag
1567 */
1568 if( c=='A'-1 ) isComplete = 0;
1569 c = sqlite3UpperToLower[c];
1570 }
1571 *pC = c + 1;
1572 }
drh7810ab62018-07-27 17:51:20 +00001573 zCollSeqName = noCase ? "NOCASE" : sqlite3StrBINARY;
drh6c1f4ef2015-06-08 14:23:15 +00001574 pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
1575 pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
1576 sqlite3ExprAddCollateString(pParse,pNewExpr1,zCollSeqName),
drhabfd35e2016-12-06 22:47:23 +00001577 pStr1);
drh6c1f4ef2015-06-08 14:23:15 +00001578 transferJoinMarkings(pNewExpr1, pExpr);
1579 idxNew1 = whereClauseInsert(pWC, pNewExpr1, wtFlags);
1580 testcase( idxNew1==0 );
1581 exprAnalyze(pSrc, pWC, idxNew1);
1582 pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
1583 pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
1584 sqlite3ExprAddCollateString(pParse,pNewExpr2,zCollSeqName),
drhabfd35e2016-12-06 22:47:23 +00001585 pStr2);
drh6c1f4ef2015-06-08 14:23:15 +00001586 transferJoinMarkings(pNewExpr2, pExpr);
1587 idxNew2 = whereClauseInsert(pWC, pNewExpr2, wtFlags);
1588 testcase( idxNew2==0 );
1589 exprAnalyze(pSrc, pWC, idxNew2);
1590 pTerm = &pWC->a[idxTerm];
1591 if( isComplete ){
1592 markTermAsChild(pWC, idxNew1, idxTerm);
1593 markTermAsChild(pWC, idxNew2, idxTerm);
1594 }
1595 }
1596#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
1597
drh71aff852021-01-21 20:42:36 +00001598 /* If there is a vector == or IS term - e.g. "(a, b) == (?, ?)" - create
1599 ** new terms for each component comparison - "a = ?" and "b = ?". The
1600 ** new terms completely replace the original vector comparison, which is
1601 ** no longer used.
1602 **
1603 ** This is only required if at least one side of the comparison operation
1604 ** is not a sub-select. */
1605 if( (pExpr->op==TK_EQ || pExpr->op==TK_IS)
1606 && (nLeft = sqlite3ExprVectorSize(pExpr->pLeft))>1
1607 && sqlite3ExprVectorSize(pExpr->pRight)==nLeft
1608 && ( (pExpr->pLeft->flags & EP_xIsSelect)==0
1609 || (pExpr->pRight->flags & EP_xIsSelect)==0)
1610 && pWC->op==TK_AND
1611 ){
1612 int i;
1613 for(i=0; i<nLeft; i++){
1614 int idxNew;
1615 Expr *pNew;
1616 Expr *pLeft = sqlite3ExprForVectorField(pParse, pExpr->pLeft, i);
1617 Expr *pRight = sqlite3ExprForVectorField(pParse, pExpr->pRight, i);
1618
1619 pNew = sqlite3PExpr(pParse, pExpr->op, pLeft, pRight);
1620 transferJoinMarkings(pNew, pExpr);
1621 idxNew = whereClauseInsert(pWC, pNew, TERM_DYNAMIC);
1622 exprAnalyze(pSrc, pWC, idxNew);
1623 }
1624 pTerm = &pWC->a[idxTerm];
1625 pTerm->wtFlags |= TERM_CODED|TERM_VIRTUAL; /* Disable the original */
1626 pTerm->eOperator = 0;
1627 }
1628
1629 /* If there is a vector IN term - e.g. "(a, b) IN (SELECT ...)" - create
1630 ** a virtual term for each vector component. The expression object
1631 ** used by each such virtual term is pExpr (the full vector IN(...)
1632 ** expression). The WhereTerm.u.x.iField variable identifies the index within
1633 ** the vector on the LHS that the virtual term represents.
1634 **
1635 ** This only works if the RHS is a simple SELECT (not a compound) that does
1636 ** not use window functions.
1637 */
1638 else if( pExpr->op==TK_IN
1639 && pTerm->u.x.iField==0
1640 && pExpr->pLeft->op==TK_VECTOR
1641 && pExpr->x.pSelect->pPrior==0
1642#ifndef SQLITE_OMIT_WINDOWFUNC
1643 && pExpr->x.pSelect->pWin==0
1644#endif
1645 && pWC->op==TK_AND
1646 ){
1647 int i;
1648 for(i=0; i<sqlite3ExprVectorSize(pExpr->pLeft); i++){
1649 int idxNew;
1650 idxNew = whereClauseInsert(pWC, pExpr, TERM_VIRTUAL);
1651 pWC->a[idxNew].u.x.iField = i+1;
1652 exprAnalyze(pSrc, pWC, idxNew);
1653 markTermAsChild(pWC, idxNew, idxTerm);
1654 }
1655 }
1656
drh6c1f4ef2015-06-08 14:23:15 +00001657#ifndef SQLITE_OMIT_VIRTUALTABLE
drh303a69b2017-09-11 19:47:37 +00001658 /* Add a WO_AUX auxiliary term to the constraint set if the
1659 ** current expression is of the form "column OP expr" where OP
1660 ** is an operator that gets passed into virtual tables but which is
1661 ** not normally optimized for ordinary tables. In other words, OP
1662 ** is one of MATCH, LIKE, GLOB, REGEXP, !=, IS, IS NOT, or NOT NULL.
drh6c1f4ef2015-06-08 14:23:15 +00001663 ** This information is used by the xBestIndex methods of
1664 ** virtual tables. The native query optimizer does not attempt
1665 ** to do anything with MATCH functions.
1666 */
drh71aff852021-01-21 20:42:36 +00001667 else if( pWC->op==TK_AND ){
mistachkin53be36b2017-11-03 06:45:37 +00001668 Expr *pRight = 0, *pLeft = 0;
drh59155062018-05-26 18:03:48 +00001669 int res = isAuxiliaryVtabOperator(db, pExpr, &eOp2, &pLeft, &pRight);
drh303a69b2017-09-11 19:47:37 +00001670 while( res-- > 0 ){
dand03024d2017-09-09 19:41:12 +00001671 int idxNew;
1672 WhereTerm *pNewTerm;
1673 Bitmask prereqColumn, prereqExpr;
drh6c1f4ef2015-06-08 14:23:15 +00001674
dand03024d2017-09-09 19:41:12 +00001675 prereqExpr = sqlite3WhereExprUsage(pMaskSet, pRight);
1676 prereqColumn = sqlite3WhereExprUsage(pMaskSet, pLeft);
1677 if( (prereqExpr & prereqColumn)==0 ){
1678 Expr *pNewExpr;
1679 pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
1680 0, sqlite3ExprDup(db, pRight, 0));
1681 if( ExprHasProperty(pExpr, EP_FromJoin) && pNewExpr ){
1682 ExprSetProperty(pNewExpr, EP_FromJoin);
drh6e827fa2019-12-22 20:03:29 +00001683 pNewExpr->iRightJoinTable = pExpr->iRightJoinTable;
dand03024d2017-09-09 19:41:12 +00001684 }
1685 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
1686 testcase( idxNew==0 );
1687 pNewTerm = &pWC->a[idxNew];
1688 pNewTerm->prereqRight = prereqExpr;
1689 pNewTerm->leftCursor = pLeft->iTable;
drh75fa2662020-09-28 15:49:43 +00001690 pNewTerm->u.x.leftColumn = pLeft->iColumn;
drh303a69b2017-09-11 19:47:37 +00001691 pNewTerm->eOperator = WO_AUX;
dand03024d2017-09-09 19:41:12 +00001692 pNewTerm->eMatchOp = eOp2;
1693 markTermAsChild(pWC, idxNew, idxTerm);
1694 pTerm = &pWC->a[idxTerm];
1695 pTerm->wtFlags |= TERM_COPIED;
1696 pNewTerm->prereqAll = pTerm->prereqAll;
dan210ec4c2017-06-27 16:39:01 +00001697 }
dand03024d2017-09-09 19:41:12 +00001698 SWAP(Expr*, pLeft, pRight);
drh6c1f4ef2015-06-08 14:23:15 +00001699 }
1700 }
1701#endif /* SQLITE_OMIT_VIRTUALTABLE */
1702
drh6c1f4ef2015-06-08 14:23:15 +00001703 /* Prevent ON clause terms of a LEFT JOIN from being used to drive
1704 ** an index for tables to the left of the join.
1705 */
drh0f85b2f2016-11-20 12:00:27 +00001706 testcase( pTerm!=&pWC->a[idxTerm] );
1707 pTerm = &pWC->a[idxTerm];
drh6c1f4ef2015-06-08 14:23:15 +00001708 pTerm->prereqRight |= extraRight;
1709}
1710
1711/***************************************************************************
1712** Routines with file scope above. Interface to the rest of the where.c
1713** subsystem follows.
1714***************************************************************************/
1715
1716/*
1717** This routine identifies subexpressions in the WHERE clause where
1718** each subexpression is separated by the AND operator or some other
1719** operator specified in the op parameter. The WhereClause structure
1720** is filled with pointers to subexpressions. For example:
1721**
1722** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
1723** \________/ \_______________/ \________________/
1724** slot[0] slot[1] slot[2]
1725**
1726** The original WHERE clause in pExpr is unaltered. All this routine
1727** does is make slot[] entries point to substructure within pExpr.
1728**
1729** In the previous sentence and in the diagram, "slot[]" refers to
1730** the WhereClause.a[] array. The slot[] array grows as needed to contain
1731** all terms of the WHERE clause.
1732*/
1733void sqlite3WhereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
drh0d950af2019-08-22 16:38:42 +00001734 Expr *pE2 = sqlite3ExprSkipCollateAndLikely(pExpr);
drh6c1f4ef2015-06-08 14:23:15 +00001735 pWC->op = op;
drh235667a2020-11-08 20:44:30 +00001736 assert( pE2!=0 || pExpr==0 );
drh6c1f4ef2015-06-08 14:23:15 +00001737 if( pE2==0 ) return;
1738 if( pE2->op!=op ){
1739 whereClauseInsert(pWC, pExpr, 0);
1740 }else{
1741 sqlite3WhereSplit(pWC, pE2->pLeft, op);
1742 sqlite3WhereSplit(pWC, pE2->pRight, op);
1743 }
1744}
1745
1746/*
1747** Initialize a preallocated WhereClause structure.
1748*/
1749void sqlite3WhereClauseInit(
1750 WhereClause *pWC, /* The WhereClause to be initialized */
1751 WhereInfo *pWInfo /* The WHERE processing context */
1752){
1753 pWC->pWInfo = pWInfo;
drh9c3549a2018-06-11 01:30:03 +00001754 pWC->hasOr = 0;
drh6c1f4ef2015-06-08 14:23:15 +00001755 pWC->pOuter = 0;
1756 pWC->nTerm = 0;
1757 pWC->nSlot = ArraySize(pWC->aStatic);
1758 pWC->a = pWC->aStatic;
1759}
1760
1761/*
1762** Deallocate a WhereClause structure. The WhereClause structure
drh62aaa6c2015-11-21 17:27:42 +00001763** itself is not freed. This routine is the inverse of
1764** sqlite3WhereClauseInit().
drh6c1f4ef2015-06-08 14:23:15 +00001765*/
1766void sqlite3WhereClauseClear(WhereClause *pWC){
1767 int i;
1768 WhereTerm *a;
1769 sqlite3 *db = pWC->pWInfo->pParse->db;
1770 for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
1771 if( a->wtFlags & TERM_DYNAMIC ){
1772 sqlite3ExprDelete(db, a->pExpr);
1773 }
1774 if( a->wtFlags & TERM_ORINFO ){
1775 whereOrInfoDelete(db, a->u.pOrInfo);
1776 }else if( a->wtFlags & TERM_ANDINFO ){
1777 whereAndInfoDelete(db, a->u.pAndInfo);
1778 }
1779 }
1780 if( pWC->a!=pWC->aStatic ){
1781 sqlite3DbFree(db, pWC->a);
1782 }
1783}
1784
1785
1786/*
1787** These routines walk (recursively) an expression tree and generate
1788** a bitmask indicating which tables are used in that expression
1789** tree.
1790*/
drhccf6db52018-06-09 02:49:11 +00001791Bitmask sqlite3WhereExprUsageNN(WhereMaskSet *pMaskSet, Expr *p){
drh93ca3932016-08-10 20:02:21 +00001792 Bitmask mask;
drhefad2e22018-07-27 16:57:11 +00001793 if( p->op==TK_COLUMN && !ExprHasProperty(p, EP_FixedCol) ){
drhf43ce0b2017-05-25 00:08:48 +00001794 return sqlite3WhereGetMask(pMaskSet, p->iTable);
drhccf6db52018-06-09 02:49:11 +00001795 }else if( ExprHasProperty(p, EP_TokenOnly|EP_Leaf) ){
1796 assert( p->op!=TK_IF_NULL_ROW );
1797 return 0;
drh6c1f4ef2015-06-08 14:23:15 +00001798 }
drhf43ce0b2017-05-25 00:08:48 +00001799 mask = (p->op==TK_IF_NULL_ROW) ? sqlite3WhereGetMask(pMaskSet, p->iTable) : 0;
drhccf6db52018-06-09 02:49:11 +00001800 if( p->pLeft ) mask |= sqlite3WhereExprUsageNN(pMaskSet, p->pLeft);
drhe24b92b2017-07-10 15:26:09 +00001801 if( p->pRight ){
drhccf6db52018-06-09 02:49:11 +00001802 mask |= sqlite3WhereExprUsageNN(pMaskSet, p->pRight);
drhe24b92b2017-07-10 15:26:09 +00001803 assert( p->x.pList==0 );
1804 }else if( ExprHasProperty(p, EP_xIsSelect) ){
dand3930b12017-07-10 15:17:30 +00001805 if( ExprHasProperty(p, EP_VarSelect) ) pMaskSet->bVarSelect = 1;
drh6c1f4ef2015-06-08 14:23:15 +00001806 mask |= exprSelectUsage(pMaskSet, p->x.pSelect);
drh926957f2016-04-12 00:00:33 +00001807 }else if( p->x.pList ){
drh6c1f4ef2015-06-08 14:23:15 +00001808 mask |= sqlite3WhereExprListUsage(pMaskSet, p->x.pList);
1809 }
dan9e244392019-03-12 09:49:10 +00001810#ifndef SQLITE_OMIT_WINDOWFUNC
drh8cc8fea2019-12-20 15:35:56 +00001811 if( (p->op==TK_FUNCTION || p->op==TK_AGG_FUNCTION) && p->y.pWin ){
dan9e244392019-03-12 09:49:10 +00001812 mask |= sqlite3WhereExprListUsage(pMaskSet, p->y.pWin->pPartition);
1813 mask |= sqlite3WhereExprListUsage(pMaskSet, p->y.pWin->pOrderBy);
drh8cc8fea2019-12-20 15:35:56 +00001814 mask |= sqlite3WhereExprUsage(pMaskSet, p->y.pWin->pFilter);
dan9e244392019-03-12 09:49:10 +00001815 }
1816#endif
drh6c1f4ef2015-06-08 14:23:15 +00001817 return mask;
1818}
drhccf6db52018-06-09 02:49:11 +00001819Bitmask sqlite3WhereExprUsage(WhereMaskSet *pMaskSet, Expr *p){
1820 return p ? sqlite3WhereExprUsageNN(pMaskSet,p) : 0;
1821}
drh6c1f4ef2015-06-08 14:23:15 +00001822Bitmask sqlite3WhereExprListUsage(WhereMaskSet *pMaskSet, ExprList *pList){
1823 int i;
1824 Bitmask mask = 0;
1825 if( pList ){
1826 for(i=0; i<pList->nExpr; i++){
1827 mask |= sqlite3WhereExprUsage(pMaskSet, pList->a[i].pExpr);
1828 }
1829 }
1830 return mask;
1831}
1832
1833
1834/*
1835** Call exprAnalyze on all terms in a WHERE clause.
1836**
1837** Note that exprAnalyze() might add new virtual terms onto the
1838** end of the WHERE clause. We do not want to analyze these new
1839** virtual terms, so start analyzing at the end and work forward
1840** so that the added virtual terms are never processed.
1841*/
1842void sqlite3WhereExprAnalyze(
1843 SrcList *pTabList, /* the FROM clause */
1844 WhereClause *pWC /* the WHERE clause to be analyzed */
1845){
1846 int i;
1847 for(i=pWC->nTerm-1; i>=0; i--){
1848 exprAnalyze(pTabList, pWC, i);
1849 }
1850}
drh01d230c2015-08-19 17:11:37 +00001851
1852/*
1853** For table-valued-functions, transform the function arguments into
1854** new WHERE clause terms.
1855**
1856** Each function argument translates into an equality constraint against
1857** a HIDDEN column in the table.
1858*/
1859void sqlite3WhereTabFuncArgs(
1860 Parse *pParse, /* Parsing context */
drh76012942021-02-21 21:04:54 +00001861 SrcItem *pItem, /* The FROM clause term to process */
drh01d230c2015-08-19 17:11:37 +00001862 WhereClause *pWC /* Xfer function arguments to here */
1863){
1864 Table *pTab;
1865 int j, k;
1866 ExprList *pArgs;
1867 Expr *pColRef;
1868 Expr *pTerm;
1869 if( pItem->fg.isTabFunc==0 ) return;
1870 pTab = pItem->pTab;
1871 assert( pTab!=0 );
1872 pArgs = pItem->u1.pFuncArg;
drh20292312015-11-21 13:24:46 +00001873 if( pArgs==0 ) return;
drh01d230c2015-08-19 17:11:37 +00001874 for(j=k=0; j<pArgs->nExpr; j++){
danf6894002018-10-26 15:36:53 +00001875 Expr *pRhs;
drh62aaa6c2015-11-21 17:27:42 +00001876 while( k<pTab->nCol && (pTab->aCol[k].colFlags & COLFLAG_HIDDEN)==0 ){k++;}
drh01d230c2015-08-19 17:11:37 +00001877 if( k>=pTab->nCol ){
drhd8b1bfc2015-08-20 23:21:34 +00001878 sqlite3ErrorMsg(pParse, "too many arguments on %s() - max %d",
drh01d230c2015-08-19 17:11:37 +00001879 pTab->zName, j);
1880 return;
1881 }
drhe1c03b62016-09-23 20:59:31 +00001882 pColRef = sqlite3ExprAlloc(pParse->db, TK_COLUMN, 0, 0);
drh01d230c2015-08-19 17:11:37 +00001883 if( pColRef==0 ) return;
1884 pColRef->iTable = pItem->iCursor;
1885 pColRef->iColumn = k++;
drheda079c2018-09-20 19:02:15 +00001886 pColRef->y.pTab = pTab;
danf6894002018-10-26 15:36:53 +00001887 pRhs = sqlite3PExpr(pParse, TK_UPLUS,
1888 sqlite3ExprDup(pParse->db, pArgs->a[j].pExpr, 0), 0);
1889 pTerm = sqlite3PExpr(pParse, TK_EQ, pColRef, pRhs);
drh8103a032019-11-15 00:52:13 +00001890 if( pItem->fg.jointype & JT_LEFT ){
1891 sqlite3SetJoinExpr(pTerm, pItem->iCursor);
1892 }
drh01d230c2015-08-19 17:11:37 +00001893 whereClauseInsert(pWC, pTerm, TERM_DYNAMIC);
1894 }
1895}