Fix typo in comment. [https://fossil-scm.org/forum/forumpost/cc20266bf2|Fossil forum...
[sqlite.git] / src / whereexpr.c
blobdaf3d5d95024e107ad5a2944120fccb736f1fda2
1 /*
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.
11 *************************************************************************
12 ** This module contains C code that generates VDBE code used to process
13 ** the WHERE clause of SQL statements.
15 ** This file was originally part of where.c but was split out to improve
16 ** readability and editability. This file contains utility routines for
17 ** analyzing Expr objects in the WHERE clause.
19 #include "sqliteInt.h"
20 #include "whereInt.h"
22 /* Forward declarations */
23 static void exprAnalyze(SrcList*, WhereClause*, int);
26 ** Deallocate all memory associated with a WhereOrInfo object.
28 static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
29 sqlite3WhereClauseClear(&p->wc);
30 sqlite3DbFree(db, p);
34 ** Deallocate all memory associated with a WhereAndInfo object.
36 static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
37 sqlite3WhereClauseClear(&p->wc);
38 sqlite3DbFree(db, p);
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.
49 ** This routine will increase the size of the pWC->a[] array as necessary.
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.
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.
60 static 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;
67 pWC->a = sqlite3WhereMalloc(pWC->pWInfo, sizeof(pWC->a[0])*pWC->nSlot*2 );
68 if( pWC->a==0 ){
69 if( wtFlags & TERM_DYNAMIC ){
70 sqlite3ExprDelete(db, p);
72 pWC->a = pOld;
73 return 0;
75 memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
76 pWC->nSlot = pWC->nSlot*2;
78 pTerm = &pWC->a[idx = pWC->nTerm++];
79 if( (wtFlags & TERM_VIRTUAL)==0 ) pWC->nBase = pWC->nTerm;
80 if( p && ExprHasProperty(p, EP_Unlikely) ){
81 pTerm->truthProb = sqlite3LogEst(p->iTable) - 270;
82 }else{
83 pTerm->truthProb = 1;
85 pTerm->pExpr = sqlite3ExprSkipCollateAndLikely(p);
86 pTerm->wtFlags = wtFlags;
87 pTerm->pWC = pWC;
88 pTerm->iParent = -1;
89 memset(&pTerm->eOperator, 0,
90 sizeof(WhereTerm) - offsetof(WhereTerm,eOperator));
91 return idx;
95 ** Return TRUE if the given operator is one of the operators that is
96 ** allowed for an indexable WHERE clause term. The allowed operators are
97 ** "=", "<", ">", "<=", ">=", "IN", "IS", and "IS NULL"
99 static int allowedOp(int op){
100 assert( TK_GT>TK_EQ && TK_GT<TK_GE );
101 assert( TK_LT>TK_EQ && TK_LT<TK_GE );
102 assert( TK_LE>TK_EQ && TK_LE<TK_GE );
103 assert( TK_GE==TK_EQ+4 );
104 return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL || op==TK_IS;
108 ** Commute a comparison operator. Expressions of the form "X op Y"
109 ** are converted into "Y op X".
111 static u16 exprCommute(Parse *pParse, Expr *pExpr){
112 if( pExpr->pLeft->op==TK_VECTOR
113 || pExpr->pRight->op==TK_VECTOR
114 || sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft, pExpr->pRight) !=
115 sqlite3BinaryCompareCollSeq(pParse, pExpr->pRight, pExpr->pLeft)
117 pExpr->flags ^= EP_Commuted;
119 SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
120 if( pExpr->op>=TK_GT ){
121 assert( TK_LT==TK_GT+2 );
122 assert( TK_GE==TK_LE+2 );
123 assert( TK_GT>TK_EQ );
124 assert( TK_GT<TK_LE );
125 assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
126 pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
128 return 0;
132 ** Translate from TK_xx operator to WO_xx bitmask.
134 static u16 operatorMask(int op){
135 u16 c;
136 assert( allowedOp(op) );
137 if( op==TK_IN ){
138 c = WO_IN;
139 }else if( op==TK_ISNULL ){
140 c = WO_ISNULL;
141 }else if( op==TK_IS ){
142 c = WO_IS;
143 }else{
144 assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
145 c = (u16)(WO_EQ<<(op-TK_EQ));
147 assert( op!=TK_ISNULL || c==WO_ISNULL );
148 assert( op!=TK_IN || c==WO_IN );
149 assert( op!=TK_EQ || c==WO_EQ );
150 assert( op!=TK_LT || c==WO_LT );
151 assert( op!=TK_LE || c==WO_LE );
152 assert( op!=TK_GT || c==WO_GT );
153 assert( op!=TK_GE || c==WO_GE );
154 assert( op!=TK_IS || c==WO_IS );
155 return c;
159 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
161 ** Check to see if the given expression is a LIKE or GLOB operator that
162 ** can be optimized using inequality constraints. Return TRUE if it is
163 ** so and false if not.
165 ** In order for the operator to be optimizible, the RHS must be a string
166 ** literal that does not begin with a wildcard. The LHS must be a column
167 ** that may only be NULL, a string, or a BLOB, never a number. (This means
168 ** that virtual tables cannot participate in the LIKE optimization.) The
169 ** collating sequence for the column on the LHS must be appropriate for
170 ** the operator.
172 static int isLikeOrGlob(
173 Parse *pParse, /* Parsing and code generating context */
174 Expr *pExpr, /* Test this expression */
175 Expr **ppPrefix, /* Pointer to TK_STRING expression with pattern prefix */
176 int *pisComplete, /* True if the only wildcard is % in the last character */
177 int *pnoCase /* True if uppercase is equivalent to lowercase */
179 const u8 *z = 0; /* String on RHS of LIKE operator */
180 Expr *pRight, *pLeft; /* Right and left size of LIKE operator */
181 ExprList *pList; /* List of operands to the LIKE operator */
182 u8 c; /* One character in z[] */
183 int cnt; /* Number of non-wildcard prefix characters */
184 u8 wc[4]; /* Wildcard characters */
185 sqlite3 *db = pParse->db; /* Database connection */
186 sqlite3_value *pVal = 0;
187 int op; /* Opcode of pRight */
188 int rc; /* Result code to return */
190 if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, (char*)wc) ){
191 return 0;
193 #ifdef SQLITE_EBCDIC
194 if( *pnoCase ) return 0;
195 #endif
196 assert( ExprUseXList(pExpr) );
197 pList = pExpr->x.pList;
198 pLeft = pList->a[1].pExpr;
200 pRight = sqlite3ExprSkipCollate(pList->a[0].pExpr);
201 op = pRight->op;
202 if( op==TK_VARIABLE && (db->flags & SQLITE_EnableQPSG)==0 ){
203 Vdbe *pReprepare = pParse->pReprepare;
204 int iCol = pRight->iColumn;
205 pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_BLOB);
206 if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
207 z = sqlite3_value_text(pVal);
209 sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
210 assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
211 }else if( op==TK_STRING ){
212 assert( !ExprHasProperty(pRight, EP_IntValue) );
213 z = (u8*)pRight->u.zToken;
215 if( z ){
217 /* Count the number of prefix characters prior to the first wildcard */
218 cnt = 0;
219 while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
220 cnt++;
221 if( c==wc[3] && z[cnt]!=0 ) cnt++;
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
226 ** an (illegal 0xff) character, or (3) the pattern does not consist of
227 ** a single escape character. The second condition is necessary so
228 ** that we can increment the prefix key to find an upper bound for the
229 ** 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>1 || (cnt>0 && z[0]!=wc[3])) && 255!=(u8)z[cnt-1] ){
233 Expr *pPrefix;
235 /* A "complete" match if the pattern ends with "*" or "%" */
236 *pisComplete = c==wc[0] && z[cnt+1]==0;
238 /* Get the pattern prefix. Remove all escapes from the prefix. */
239 pPrefix = sqlite3Expr(db, TK_STRING, (char*)z);
240 if( pPrefix ){
241 int iFrom, iTo;
242 char *zNew;
243 assert( !ExprHasProperty(pPrefix, EP_IntValue) );
244 zNew = pPrefix->u.zToken;
245 zNew[cnt] = 0;
246 for(iFrom=iTo=0; iFrom<cnt; iFrom++){
247 if( zNew[iFrom]==wc[3] ) iFrom++;
248 zNew[iTo++] = zNew[iFrom];
250 zNew[iTo] = 0;
251 assert( iTo>0 );
253 /* If the LHS is not an ordinary column with TEXT affinity, then the
254 ** pattern prefix boundaries (both the start and end boundaries) must
255 ** not look like a number. Otherwise the pattern might be treated as
256 ** a number, which will invalidate the LIKE optimization.
258 ** Getting this right has been a persistent source of bugs in the
259 ** LIKE optimization. See, for example:
260 ** 2018-09-10 https://sqlite.org/src/info/c94369cae9b561b1
261 ** 2019-05-02 https://sqlite.org/src/info/b043a54c3de54b28
262 ** 2019-06-10 https://sqlite.org/src/info/fd76310a5e843e07
263 ** 2019-06-14 https://sqlite.org/src/info/ce8717f0885af975
264 ** 2019-09-03 https://sqlite.org/src/info/0f0428096f17252a
266 if( pLeft->op!=TK_COLUMN
267 || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
268 || (ALWAYS( ExprUseYTab(pLeft) )
269 && ALWAYS(pLeft->y.pTab)
270 && IsVirtual(pLeft->y.pTab)) /* Might be numeric */
272 int isNum;
273 double rDummy;
274 isNum = sqlite3AtoF(zNew, &rDummy, iTo, SQLITE_UTF8);
275 if( isNum<=0 ){
276 if( iTo==1 && zNew[0]=='-' ){
277 isNum = +1;
278 }else{
279 zNew[iTo-1]++;
280 isNum = sqlite3AtoF(zNew, &rDummy, iTo, SQLITE_UTF8);
281 zNew[iTo-1]--;
284 if( isNum>0 ){
285 sqlite3ExprDelete(db, pPrefix);
286 sqlite3ValueFree(pVal);
287 return 0;
291 *ppPrefix = pPrefix;
293 /* If the RHS pattern is a bound parameter, make arrangements to
294 ** reprepare the statement when that parameter is rebound */
295 if( op==TK_VARIABLE ){
296 Vdbe *v = pParse->pVdbe;
297 sqlite3VdbeSetVarmask(v, pRight->iColumn);
298 assert( !ExprHasProperty(pRight, EP_IntValue) );
299 if( *pisComplete && pRight->u.zToken[1] ){
300 /* If the rhs of the LIKE expression is a variable, and the current
301 ** value of the variable means there is no need to invoke the LIKE
302 ** function, then no OP_Variable will be added to the program.
303 ** This causes problems for the sqlite3_bind_parameter_name()
304 ** API. To work around them, add a dummy OP_Variable here.
306 int r1 = sqlite3GetTempReg(pParse);
307 sqlite3ExprCodeTarget(pParse, pRight, r1);
308 sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
309 sqlite3ReleaseTempReg(pParse, r1);
312 }else{
313 z = 0;
317 rc = (z!=0);
318 sqlite3ValueFree(pVal);
319 return rc;
321 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
324 #ifndef SQLITE_OMIT_VIRTUALTABLE
326 ** Check to see if the pExpr expression is a form that needs to be passed
327 ** to the xBestIndex method of virtual tables. Forms of interest include:
329 ** Expression Virtual Table Operator
330 ** ----------------------- ---------------------------------
331 ** 1. column MATCH expr SQLITE_INDEX_CONSTRAINT_MATCH
332 ** 2. column GLOB expr SQLITE_INDEX_CONSTRAINT_GLOB
333 ** 3. column LIKE expr SQLITE_INDEX_CONSTRAINT_LIKE
334 ** 4. column REGEXP expr SQLITE_INDEX_CONSTRAINT_REGEXP
335 ** 5. column != expr SQLITE_INDEX_CONSTRAINT_NE
336 ** 6. expr != column SQLITE_INDEX_CONSTRAINT_NE
337 ** 7. column IS NOT expr SQLITE_INDEX_CONSTRAINT_ISNOT
338 ** 8. expr IS NOT column SQLITE_INDEX_CONSTRAINT_ISNOT
339 ** 9. column IS NOT NULL SQLITE_INDEX_CONSTRAINT_ISNOTNULL
341 ** In every case, "column" must be a column of a virtual table. If there
342 ** is a match, set *ppLeft to the "column" expression, set *ppRight to the
343 ** "expr" expression (even though in forms (6) and (8) the column is on the
344 ** right and the expression is on the left). Also set *peOp2 to the
345 ** appropriate virtual table operator. The return value is 1 or 2 if there
346 ** is a match. The usual return is 1, but if the RHS is also a column
347 ** of virtual table in forms (5) or (7) then return 2.
349 ** If the expression matches none of the patterns above, return 0.
351 static int isAuxiliaryVtabOperator(
352 sqlite3 *db, /* Parsing context */
353 Expr *pExpr, /* Test this expression */
354 unsigned char *peOp2, /* OUT: 0 for MATCH, or else an op2 value */
355 Expr **ppLeft, /* Column expression to left of MATCH/op2 */
356 Expr **ppRight /* Expression to left of MATCH/op2 */
358 if( pExpr->op==TK_FUNCTION ){
359 static const struct Op2 {
360 const char *zOp;
361 unsigned char eOp2;
362 } aOp[] = {
363 { "match", SQLITE_INDEX_CONSTRAINT_MATCH },
364 { "glob", SQLITE_INDEX_CONSTRAINT_GLOB },
365 { "like", SQLITE_INDEX_CONSTRAINT_LIKE },
366 { "regexp", SQLITE_INDEX_CONSTRAINT_REGEXP }
368 ExprList *pList;
369 Expr *pCol; /* Column reference */
370 int i;
372 assert( ExprUseXList(pExpr) );
373 pList = pExpr->x.pList;
374 if( pList==0 || pList->nExpr!=2 ){
375 return 0;
378 /* Built-in operators MATCH, GLOB, LIKE, and REGEXP attach to a
379 ** virtual table on their second argument, which is the same as
380 ** the left-hand side operand in their in-fix form.
382 ** vtab_column MATCH expression
383 ** MATCH(expression,vtab_column)
385 pCol = pList->a[1].pExpr;
386 assert( pCol->op!=TK_COLUMN || (ExprUseYTab(pCol) && pCol->y.pTab!=0) );
387 if( ExprIsVtab(pCol) ){
388 for(i=0; i<ArraySize(aOp); i++){
389 assert( !ExprHasProperty(pExpr, EP_IntValue) );
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;
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.
403 ** OVERLOADED(vtab_column,expression)
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.
409 pCol = pList->a[0].pExpr;
410 assert( pCol->op!=TK_COLUMN || ExprUseYTab(pCol) );
411 assert( pCol->op!=TK_COLUMN || (ExprUseYTab(pCol) && pCol->y.pTab!=0) );
412 if( ExprIsVtab(pCol) ){
413 sqlite3_vtab *pVtab;
414 sqlite3_module *pMod;
415 void (*xNotUsed)(sqlite3_context*,int,sqlite3_value**);
416 void *pNotUsed;
417 pVtab = sqlite3GetVTable(db, pCol->y.pTab)->pVtab;
418 assert( pVtab!=0 );
419 assert( pVtab->pModule!=0 );
420 assert( !ExprHasProperty(pExpr, EP_IntValue) );
421 pMod = (sqlite3_module *)pVtab->pModule;
422 if( pMod->xFindFunction!=0 ){
423 i = pMod->xFindFunction(pVtab,2, pExpr->u.zToken, &xNotUsed, &pNotUsed);
424 if( i>=SQLITE_INDEX_CONSTRAINT_FUNCTION ){
425 *peOp2 = i;
426 *ppRight = pList->a[1].pExpr;
427 *ppLeft = pCol;
428 return 1;
432 }else if( pExpr->op==TK_NE || pExpr->op==TK_ISNOT || pExpr->op==TK_NOTNULL ){
433 int res = 0;
434 Expr *pLeft = pExpr->pLeft;
435 Expr *pRight = pExpr->pRight;
436 assert( pLeft->op!=TK_COLUMN || (ExprUseYTab(pLeft) && pLeft->y.pTab!=0) );
437 if( ExprIsVtab(pLeft) ){
438 res++;
440 assert( pRight==0 || pRight->op!=TK_COLUMN
441 || (ExprUseYTab(pRight) && pRight->y.pTab!=0) );
442 if( pRight && ExprIsVtab(pRight) ){
443 res++;
444 SWAP(Expr*, pLeft, pRight);
446 *ppLeft = pLeft;
447 *ppRight = pRight;
448 if( pExpr->op==TK_NE ) *peOp2 = SQLITE_INDEX_CONSTRAINT_NE;
449 if( pExpr->op==TK_ISNOT ) *peOp2 = SQLITE_INDEX_CONSTRAINT_ISNOT;
450 if( pExpr->op==TK_NOTNULL ) *peOp2 = SQLITE_INDEX_CONSTRAINT_ISNOTNULL;
451 return res;
453 return 0;
455 #endif /* SQLITE_OMIT_VIRTUALTABLE */
458 ** If the pBase expression originated in the ON or USING clause of
459 ** a join, then transfer the appropriate markings over to derived.
461 static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
462 if( pDerived && ExprHasProperty(pBase, EP_OuterON|EP_InnerON) ){
463 pDerived->flags |= pBase->flags & (EP_OuterON|EP_InnerON);
464 pDerived->w.iJoin = pBase->w.iJoin;
469 ** Mark term iChild as being a child of term iParent
471 static void markTermAsChild(WhereClause *pWC, int iChild, int iParent){
472 pWC->a[iChild].iParent = iParent;
473 pWC->a[iChild].truthProb = pWC->a[iParent].truthProb;
474 pWC->a[iParent].nChild++;
478 ** Return the N-th AND-connected subterm of pTerm. Or if pTerm is not
479 ** a conjunction, then return just pTerm when N==0. If N is exceeds
480 ** the number of available subterms, return NULL.
482 static WhereTerm *whereNthSubterm(WhereTerm *pTerm, int N){
483 if( pTerm->eOperator!=WO_AND ){
484 return N==0 ? pTerm : 0;
486 if( N<pTerm->u.pAndInfo->wc.nTerm ){
487 return &pTerm->u.pAndInfo->wc.a[N];
489 return 0;
493 ** Subterms pOne and pTwo are contained within WHERE clause pWC. The
494 ** two subterms are in disjunction - they are OR-ed together.
496 ** If these two terms are both of the form: "A op B" with the same
497 ** A and B values but different operators and if the operators are
498 ** compatible (if one is = and the other is <, for example) then
499 ** add a new virtual AND term to pWC that is the combination of the
500 ** two.
502 ** Some examples:
504 ** x<y OR x=y --> x<=y
505 ** x=y OR x=y --> x=y
506 ** x<=y OR x<y --> x<=y
508 ** The following is NOT generated:
510 ** x<y OR x>y --> x!=y
512 static void whereCombineDisjuncts(
513 SrcList *pSrc, /* the FROM clause */
514 WhereClause *pWC, /* The complete WHERE clause */
515 WhereTerm *pOne, /* First disjunct */
516 WhereTerm *pTwo /* Second disjunct */
518 u16 eOp = pOne->eOperator | pTwo->eOperator;
519 sqlite3 *db; /* Database connection (for malloc) */
520 Expr *pNew; /* New virtual expression */
521 int op; /* Operator for the combined expression */
522 int idxNew; /* Index in pWC of the next virtual term */
524 if( (pOne->wtFlags | pTwo->wtFlags) & TERM_VNULL ) return;
525 if( (pOne->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
526 if( (pTwo->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
527 if( (eOp & (WO_EQ|WO_LT|WO_LE))!=eOp
528 && (eOp & (WO_EQ|WO_GT|WO_GE))!=eOp ) return;
529 assert( pOne->pExpr->pLeft!=0 && pOne->pExpr->pRight!=0 );
530 assert( pTwo->pExpr->pLeft!=0 && pTwo->pExpr->pRight!=0 );
531 if( sqlite3ExprCompare(0,pOne->pExpr->pLeft, pTwo->pExpr->pLeft, -1) ) return;
532 if( sqlite3ExprCompare(0,pOne->pExpr->pRight, pTwo->pExpr->pRight,-1) )return;
533 /* If we reach this point, it means the two subterms can be combined */
534 if( (eOp & (eOp-1))!=0 ){
535 if( eOp & (WO_LT|WO_LE) ){
536 eOp = WO_LE;
537 }else{
538 assert( eOp & (WO_GT|WO_GE) );
539 eOp = WO_GE;
542 db = pWC->pWInfo->pParse->db;
543 pNew = sqlite3ExprDup(db, pOne->pExpr, 0);
544 if( pNew==0 ) return;
545 for(op=TK_EQ; eOp!=(WO_EQ<<(op-TK_EQ)); op++){ assert( op<TK_GE ); }
546 pNew->op = op;
547 idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
548 exprAnalyze(pSrc, pWC, idxNew);
551 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
553 ** Analyze a term that consists of two or more OR-connected
554 ** subterms. So in:
556 ** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
557 ** ^^^^^^^^^^^^^^^^^^^^
559 ** This routine analyzes terms such as the middle term in the above example.
560 ** A WhereOrTerm object is computed and attached to the term under
561 ** analysis, regardless of the outcome of the analysis. Hence:
563 ** WhereTerm.wtFlags |= TERM_ORINFO
564 ** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object
566 ** The term being analyzed must have two or more of OR-connected subterms.
567 ** A single subterm might be a set of AND-connected sub-subterms.
568 ** Examples of terms under analysis:
570 ** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
571 ** (B) x=expr1 OR expr2=x OR x=expr3
572 ** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
573 ** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
574 ** (E) (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
575 ** (F) x>A OR (x=A AND y>=B)
577 ** CASE 1:
579 ** If all subterms are of the form T.C=expr for some single column of C and
580 ** a single table T (as shown in example B above) then create a new virtual
581 ** term that is an equivalent IN expression. In other words, if the term
582 ** being analyzed is:
584 ** x = expr1 OR expr2 = x OR x = expr3
586 ** then create a new virtual term like this:
588 ** x IN (expr1,expr2,expr3)
590 ** CASE 2:
592 ** If there are exactly two disjuncts and one side has x>A and the other side
593 ** has x=A (for the same x and A) then add a new virtual conjunct term to the
594 ** WHERE clause of the form "x>=A". Example:
596 ** x>A OR (x=A AND y>B) adds: x>=A
598 ** The added conjunct can sometimes be helpful in query planning.
600 ** CASE 3:
602 ** If all subterms are indexable by a single table T, then set
604 ** WhereTerm.eOperator = WO_OR
605 ** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T
607 ** A subterm is "indexable" if it is of the form
608 ** "T.C <op> <expr>" where C is any column of table T and
609 ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
610 ** A subterm is also indexable if it is an AND of two or more
611 ** subsubterms at least one of which is indexable. Indexable AND
612 ** subterms have their eOperator set to WO_AND and they have
613 ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
615 ** From another point of view, "indexable" means that the subterm could
616 ** potentially be used with an index if an appropriate index exists.
617 ** This analysis does not consider whether or not the index exists; that
618 ** is decided elsewhere. This analysis only looks at whether subterms
619 ** appropriate for indexing exist.
621 ** All examples A through E above satisfy case 3. But if a term
622 ** also satisfies case 1 (such as B) we know that the optimizer will
623 ** always prefer case 1, so in that case we pretend that case 3 is not
624 ** satisfied.
626 ** It might be the case that multiple tables are indexable. For example,
627 ** (E) above is indexable on tables P, Q, and R.
629 ** Terms that satisfy case 3 are candidates for lookup by using
630 ** separate indices to find rowids for each subterm and composing
631 ** the union of all rowids using a RowSet object. This is similar
632 ** to "bitmap indices" in other database engines.
634 ** OTHERWISE:
636 ** If none of cases 1, 2, or 3 apply, then leave the eOperator set to
637 ** zero. This term is not useful for search.
639 static void exprAnalyzeOrTerm(
640 SrcList *pSrc, /* the FROM clause */
641 WhereClause *pWC, /* the complete WHERE clause */
642 int idxTerm /* Index of the OR-term to be analyzed */
644 WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
645 Parse *pParse = pWInfo->pParse; /* Parser context */
646 sqlite3 *db = pParse->db; /* Database connection */
647 WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */
648 Expr *pExpr = pTerm->pExpr; /* The expression of the term */
649 int i; /* Loop counters */
650 WhereClause *pOrWc; /* Breakup of pTerm into subterms */
651 WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */
652 WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */
653 Bitmask chngToIN; /* Tables that might satisfy case 1 */
654 Bitmask indexable; /* Tables that are indexable, satisfying case 2 */
657 ** Break the OR clause into its separate subterms. The subterms are
658 ** stored in a WhereClause structure containing within the WhereOrInfo
659 ** object that is attached to the original OR clause term.
661 assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
662 assert( pExpr->op==TK_OR );
663 pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
664 if( pOrInfo==0 ) return;
665 pTerm->wtFlags |= TERM_ORINFO;
666 pOrWc = &pOrInfo->wc;
667 memset(pOrWc->aStatic, 0, sizeof(pOrWc->aStatic));
668 sqlite3WhereClauseInit(pOrWc, pWInfo);
669 sqlite3WhereSplit(pOrWc, pExpr, TK_OR);
670 sqlite3WhereExprAnalyze(pSrc, pOrWc);
671 if( db->mallocFailed ) return;
672 assert( pOrWc->nTerm>=2 );
675 ** Compute the set of tables that might satisfy cases 1 or 3.
677 indexable = ~(Bitmask)0;
678 chngToIN = ~(Bitmask)0;
679 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
680 if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
681 WhereAndInfo *pAndInfo;
682 assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
683 chngToIN = 0;
684 pAndInfo = sqlite3DbMallocRawNN(db, sizeof(*pAndInfo));
685 if( pAndInfo ){
686 WhereClause *pAndWC;
687 WhereTerm *pAndTerm;
688 int j;
689 Bitmask b = 0;
690 pOrTerm->u.pAndInfo = pAndInfo;
691 pOrTerm->wtFlags |= TERM_ANDINFO;
692 pOrTerm->eOperator = WO_AND;
693 pOrTerm->leftCursor = -1;
694 pAndWC = &pAndInfo->wc;
695 memset(pAndWC->aStatic, 0, sizeof(pAndWC->aStatic));
696 sqlite3WhereClauseInit(pAndWC, pWC->pWInfo);
697 sqlite3WhereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
698 sqlite3WhereExprAnalyze(pSrc, pAndWC);
699 pAndWC->pOuter = pWC;
700 if( !db->mallocFailed ){
701 for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
702 assert( pAndTerm->pExpr );
703 if( allowedOp(pAndTerm->pExpr->op)
704 || pAndTerm->eOperator==WO_AUX
706 b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
710 indexable &= b;
712 }else if( pOrTerm->wtFlags & TERM_COPIED ){
713 /* Skip this term for now. We revisit it when we process the
714 ** corresponding TERM_VIRTUAL term */
715 }else{
716 Bitmask b;
717 b = sqlite3WhereGetMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
718 if( pOrTerm->wtFlags & TERM_VIRTUAL ){
719 WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
720 b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pOther->leftCursor);
722 indexable &= b;
723 if( (pOrTerm->eOperator & WO_EQ)==0 ){
724 chngToIN = 0;
725 }else{
726 chngToIN &= b;
732 ** Record the set of tables that satisfy case 3. The set might be
733 ** empty.
735 pOrInfo->indexable = indexable;
736 pTerm->eOperator = WO_OR;
737 pTerm->leftCursor = -1;
738 if( indexable ){
739 pWC->hasOr = 1;
742 /* For a two-way OR, attempt to implementation case 2.
744 if( indexable && pOrWc->nTerm==2 ){
745 int iOne = 0;
746 WhereTerm *pOne;
747 while( (pOne = whereNthSubterm(&pOrWc->a[0],iOne++))!=0 ){
748 int iTwo = 0;
749 WhereTerm *pTwo;
750 while( (pTwo = whereNthSubterm(&pOrWc->a[1],iTwo++))!=0 ){
751 whereCombineDisjuncts(pSrc, pWC, pOne, pTwo);
757 ** chngToIN holds a set of tables that *might* satisfy case 1. But
758 ** we have to do some additional checking to see if case 1 really
759 ** is satisfied.
761 ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means
762 ** that there is no possibility of transforming the OR clause into an
763 ** IN operator because one or more terms in the OR clause contain
764 ** something other than == on a column in the single table. The 1-bit
765 ** case means that every term of the OR clause is of the form
766 ** "table.column=expr" for some single table. The one bit that is set
767 ** will correspond to the common table. We still need to check to make
768 ** sure the same column is used on all terms. The 2-bit case is when
769 ** the all terms are of the form "table1.column=table2.column". It
770 ** might be possible to form an IN operator with either table1.column
771 ** or table2.column as the LHS if either is common to every term of
772 ** the OR clause.
774 ** Note that terms of the form "table.column1=table.column2" (the
775 ** same table on both sizes of the ==) cannot be optimized.
777 if( chngToIN ){
778 int okToChngToIN = 0; /* True if the conversion to IN is valid */
779 int iColumn = -1; /* Column index on lhs of IN operator */
780 int iCursor = -1; /* Table cursor common to all terms */
781 int j = 0; /* Loop counter */
783 /* Search for a table and column that appears on one side or the
784 ** other of the == operator in every subterm. That table and column
785 ** will be recorded in iCursor and iColumn. There might not be any
786 ** such table and column. Set okToChngToIN if an appropriate table
787 ** and column is found but leave okToChngToIN false if not found.
789 for(j=0; j<2 && !okToChngToIN; j++){
790 Expr *pLeft = 0;
791 pOrTerm = pOrWc->a;
792 for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
793 assert( pOrTerm->eOperator & WO_EQ );
794 pOrTerm->wtFlags &= ~TERM_OK;
795 if( pOrTerm->leftCursor==iCursor ){
796 /* This is the 2-bit case and we are on the second iteration and
797 ** current term is from the first iteration. So skip this term. */
798 assert( j==1 );
799 continue;
801 if( (chngToIN & sqlite3WhereGetMask(&pWInfo->sMaskSet,
802 pOrTerm->leftCursor))==0 ){
803 /* This term must be of the form t1.a==t2.b where t2 is in the
804 ** chngToIN set but t1 is not. This term will be either preceded
805 ** or followed by an inverted copy (t2.b==t1.a). Skip this term
806 ** and use its inversion. */
807 testcase( pOrTerm->wtFlags & TERM_COPIED );
808 testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
809 assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
810 continue;
812 assert( (pOrTerm->eOperator & (WO_OR|WO_AND))==0 );
813 iColumn = pOrTerm->u.x.leftColumn;
814 iCursor = pOrTerm->leftCursor;
815 pLeft = pOrTerm->pExpr->pLeft;
816 break;
818 if( i<0 ){
819 /* No candidate table+column was found. This can only occur
820 ** on the second iteration */
821 assert( j==1 );
822 assert( IsPowerOfTwo(chngToIN) );
823 assert( chngToIN==sqlite3WhereGetMask(&pWInfo->sMaskSet, iCursor) );
824 break;
826 testcase( j==1 );
828 /* We have found a candidate table and column. Check to see if that
829 ** table and column is common to every term in the OR clause */
830 okToChngToIN = 1;
831 for(; i>=0 && okToChngToIN; i--, pOrTerm++){
832 assert( pOrTerm->eOperator & WO_EQ );
833 assert( (pOrTerm->eOperator & (WO_OR|WO_AND))==0 );
834 if( pOrTerm->leftCursor!=iCursor ){
835 pOrTerm->wtFlags &= ~TERM_OK;
836 }else if( pOrTerm->u.x.leftColumn!=iColumn || (iColumn==XN_EXPR
837 && sqlite3ExprCompare(pParse, pOrTerm->pExpr->pLeft, pLeft, -1)
839 okToChngToIN = 0;
840 }else{
841 int affLeft, affRight;
842 /* If the right-hand side is also a column, then the affinities
843 ** of both right and left sides must be such that no type
844 ** conversions are required on the right. (Ticket #2249)
846 affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
847 affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
848 if( affRight!=0 && affRight!=affLeft ){
849 okToChngToIN = 0;
850 }else{
851 pOrTerm->wtFlags |= TERM_OK;
857 /* At this point, okToChngToIN is true if original pTerm satisfies
858 ** case 1. In that case, construct a new virtual term that is
859 ** pTerm converted into an IN operator.
861 if( okToChngToIN ){
862 Expr *pDup; /* A transient duplicate expression */
863 ExprList *pList = 0; /* The RHS of the IN operator */
864 Expr *pLeft = 0; /* The LHS of the IN operator */
865 Expr *pNew; /* The complete IN operator */
867 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
868 if( (pOrTerm->wtFlags & TERM_OK)==0 ) continue;
869 assert( pOrTerm->eOperator & WO_EQ );
870 assert( (pOrTerm->eOperator & (WO_OR|WO_AND))==0 );
871 assert( pOrTerm->leftCursor==iCursor );
872 assert( pOrTerm->u.x.leftColumn==iColumn );
873 pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
874 pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
875 pLeft = pOrTerm->pExpr->pLeft;
877 assert( pLeft!=0 );
878 pDup = sqlite3ExprDup(db, pLeft, 0);
879 pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0);
880 if( pNew ){
881 int idxNew;
882 transferJoinMarkings(pNew, pExpr);
883 assert( ExprUseXList(pNew) );
884 pNew->x.pList = pList;
885 idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
886 testcase( idxNew==0 );
887 exprAnalyze(pSrc, pWC, idxNew);
888 /* pTerm = &pWC->a[idxTerm]; // would be needed if pTerm where reused */
889 markTermAsChild(pWC, idxNew, idxTerm);
890 }else{
891 sqlite3ExprListDelete(db, pList);
896 #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
899 ** We already know that pExpr is a binary operator where both operands are
900 ** column references. This routine checks to see if pExpr is an equivalence
901 ** relation:
902 ** 1. The SQLITE_Transitive optimization must be enabled
903 ** 2. Must be either an == or an IS operator
904 ** 3. Not originating in the ON clause of an OUTER JOIN
905 ** 4. The affinities of A and B must be compatible
906 ** 5a. Both operands use the same collating sequence OR
907 ** 5b. The overall collating sequence is BINARY
908 ** If this routine returns TRUE, that means that the RHS can be substituted
909 ** for the LHS anyplace else in the WHERE clause where the LHS column occurs.
910 ** This is an optimization. No harm comes from returning 0. But if 1 is
911 ** returned when it should not be, then incorrect answers might result.
913 static int termIsEquivalence(Parse *pParse, Expr *pExpr){
914 char aff1, aff2;
915 CollSeq *pColl;
916 if( !OptimizationEnabled(pParse->db, SQLITE_Transitive) ) return 0;
917 if( pExpr->op!=TK_EQ && pExpr->op!=TK_IS ) return 0;
918 if( ExprHasProperty(pExpr, EP_OuterON) ) return 0;
919 aff1 = sqlite3ExprAffinity(pExpr->pLeft);
920 aff2 = sqlite3ExprAffinity(pExpr->pRight);
921 if( aff1!=aff2
922 && (!sqlite3IsNumericAffinity(aff1) || !sqlite3IsNumericAffinity(aff2))
924 return 0;
926 pColl = sqlite3ExprCompareCollSeq(pParse, pExpr);
927 if( sqlite3IsBinary(pColl) ) return 1;
928 return sqlite3ExprCollSeqMatch(pParse, pExpr->pLeft, pExpr->pRight);
932 ** Recursively walk the expressions of a SELECT statement and generate
933 ** a bitmask indicating which tables are used in that expression
934 ** tree.
936 static Bitmask exprSelectUsage(WhereMaskSet *pMaskSet, Select *pS){
937 Bitmask mask = 0;
938 while( pS ){
939 SrcList *pSrc = pS->pSrc;
940 mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pEList);
941 mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pGroupBy);
942 mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pOrderBy);
943 mask |= sqlite3WhereExprUsage(pMaskSet, pS->pWhere);
944 mask |= sqlite3WhereExprUsage(pMaskSet, pS->pHaving);
945 if( ALWAYS(pSrc!=0) ){
946 int i;
947 for(i=0; i<pSrc->nSrc; i++){
948 mask |= exprSelectUsage(pMaskSet, pSrc->a[i].pSelect);
949 if( pSrc->a[i].fg.isUsing==0 ){
950 mask |= sqlite3WhereExprUsage(pMaskSet, pSrc->a[i].u3.pOn);
952 if( pSrc->a[i].fg.isTabFunc ){
953 mask |= sqlite3WhereExprListUsage(pMaskSet, pSrc->a[i].u1.pFuncArg);
957 pS = pS->pPrior;
959 return mask;
963 ** Expression pExpr is one operand of a comparison operator that might
964 ** be useful for indexing. This routine checks to see if pExpr appears
965 ** in any index. Return TRUE (1) if pExpr is an indexed term and return
966 ** FALSE (0) if not. If TRUE is returned, also set aiCurCol[0] to the cursor
967 ** number of the table that is indexed and aiCurCol[1] to the column number
968 ** of the column that is indexed, or XN_EXPR (-2) if an expression is being
969 ** indexed.
971 ** If pExpr is a TK_COLUMN column reference, then this routine always returns
972 ** true even if that particular column is not indexed, because the column
973 ** might be added to an automatic index later.
975 static SQLITE_NOINLINE int exprMightBeIndexed2(
976 SrcList *pFrom, /* The FROM clause */
977 int *aiCurCol, /* Write the referenced table cursor and column here */
978 Expr *pExpr, /* An operand of a comparison operator */
979 int j /* Start looking with the j-th pFrom entry */
981 Index *pIdx;
982 int i;
983 int iCur;
985 iCur = pFrom->a[j].iCursor;
986 for(pIdx=pFrom->a[j].pTab->pIndex; pIdx; pIdx=pIdx->pNext){
987 if( pIdx->aColExpr==0 ) continue;
988 for(i=0; i<pIdx->nKeyCol; i++){
989 if( pIdx->aiColumn[i]!=XN_EXPR ) continue;
990 assert( pIdx->bHasExpr );
991 if( sqlite3ExprCompareSkip(pExpr,pIdx->aColExpr->a[i].pExpr,iCur)==0
992 && pExpr->op!=TK_STRING
994 aiCurCol[0] = iCur;
995 aiCurCol[1] = XN_EXPR;
996 return 1;
1000 }while( ++j < pFrom->nSrc );
1001 return 0;
1003 static int exprMightBeIndexed(
1004 SrcList *pFrom, /* The FROM clause */
1005 int *aiCurCol, /* Write the referenced table cursor & column here */
1006 Expr *pExpr, /* An operand of a comparison operator */
1007 int op /* The specific comparison operator */
1009 int i;
1011 /* If this expression is a vector to the left or right of a
1012 ** inequality constraint (>, <, >= or <=), perform the processing
1013 ** on the first element of the vector. */
1014 assert( TK_GT+1==TK_LE && TK_GT+2==TK_LT && TK_GT+3==TK_GE );
1015 assert( TK_IS<TK_GE && TK_ISNULL<TK_GE && TK_IN<TK_GE );
1016 assert( op<=TK_GE );
1017 if( pExpr->op==TK_VECTOR && (op>=TK_GT && ALWAYS(op<=TK_GE)) ){
1018 assert( ExprUseXList(pExpr) );
1019 pExpr = pExpr->x.pList->a[0].pExpr;
1022 if( pExpr->op==TK_COLUMN ){
1023 aiCurCol[0] = pExpr->iTable;
1024 aiCurCol[1] = pExpr->iColumn;
1025 return 1;
1028 for(i=0; i<pFrom->nSrc; i++){
1029 Index *pIdx;
1030 for(pIdx=pFrom->a[i].pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1031 if( pIdx->aColExpr ){
1032 return exprMightBeIndexed2(pFrom,aiCurCol,pExpr,i);
1036 return 0;
1041 ** The input to this routine is an WhereTerm structure with only the
1042 ** "pExpr" field filled in. The job of this routine is to analyze the
1043 ** subexpression and populate all the other fields of the WhereTerm
1044 ** structure.
1046 ** If the expression is of the form "<expr> <op> X" it gets commuted
1047 ** to the standard form of "X <op> <expr>".
1049 ** If the expression is of the form "X <op> Y" where both X and Y are
1050 ** columns, then the original expression is unchanged and a new virtual
1051 ** term of the form "Y <op> X" is added to the WHERE clause and
1052 ** analyzed separately. The original term is marked with TERM_COPIED
1053 ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
1054 ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
1055 ** is a commuted copy of a prior term.) The original term has nChild=1
1056 ** and the copy has idxParent set to the index of the original term.
1058 static void exprAnalyze(
1059 SrcList *pSrc, /* the FROM clause */
1060 WhereClause *pWC, /* the WHERE clause */
1061 int idxTerm /* Index of the term to be analyzed */
1063 WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
1064 WhereTerm *pTerm; /* The term to be analyzed */
1065 WhereMaskSet *pMaskSet; /* Set of table index masks */
1066 Expr *pExpr; /* The expression to be analyzed */
1067 Bitmask prereqLeft; /* Prerequisites of the pExpr->pLeft */
1068 Bitmask prereqAll; /* Prerequisites of pExpr */
1069 Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */
1070 Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */
1071 int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */
1072 int noCase = 0; /* uppercase equivalent to lowercase */
1073 int op; /* Top-level operator. pExpr->op */
1074 Parse *pParse = pWInfo->pParse; /* Parsing context */
1075 sqlite3 *db = pParse->db; /* Database connection */
1076 unsigned char eOp2 = 0; /* op2 value for LIKE/REGEXP/GLOB */
1077 int nLeft; /* Number of elements on left side vector */
1079 if( db->mallocFailed ){
1080 return;
1082 assert( pWC->nTerm > idxTerm );
1083 pTerm = &pWC->a[idxTerm];
1084 pMaskSet = &pWInfo->sMaskSet;
1085 pExpr = pTerm->pExpr;
1086 assert( pExpr!=0 ); /* Because malloc() has not failed */
1087 assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
1088 pMaskSet->bVarSelect = 0;
1089 prereqLeft = sqlite3WhereExprUsage(pMaskSet, pExpr->pLeft);
1090 op = pExpr->op;
1091 if( op==TK_IN ){
1092 assert( pExpr->pRight==0 );
1093 if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
1094 if( ExprUseXSelect(pExpr) ){
1095 pTerm->prereqRight = exprSelectUsage(pMaskSet, pExpr->x.pSelect);
1096 }else{
1097 pTerm->prereqRight = sqlite3WhereExprListUsage(pMaskSet, pExpr->x.pList);
1099 prereqAll = prereqLeft | pTerm->prereqRight;
1100 }else{
1101 pTerm->prereqRight = sqlite3WhereExprUsage(pMaskSet, pExpr->pRight);
1102 if( pExpr->pLeft==0
1103 || ExprHasProperty(pExpr, EP_xIsSelect|EP_IfNullRow)
1104 || pExpr->x.pList!=0
1106 prereqAll = sqlite3WhereExprUsageNN(pMaskSet, pExpr);
1107 }else{
1108 prereqAll = prereqLeft | pTerm->prereqRight;
1111 if( pMaskSet->bVarSelect ) pTerm->wtFlags |= TERM_VARSELECT;
1113 #ifdef SQLITE_DEBUG
1114 if( prereqAll!=sqlite3WhereExprUsageNN(pMaskSet, pExpr) ){
1115 printf("\n*** Incorrect prereqAll computed for:\n");
1116 sqlite3TreeViewExpr(0,pExpr,0);
1117 assert( 0 );
1119 #endif
1121 if( ExprHasProperty(pExpr, EP_OuterON|EP_InnerON) ){
1122 Bitmask x = sqlite3WhereGetMask(pMaskSet, pExpr->w.iJoin);
1123 if( ExprHasProperty(pExpr, EP_OuterON) ){
1124 prereqAll |= x;
1125 extraRight = x-1; /* ON clause terms may not be used with an index
1126 ** on left table of a LEFT JOIN. Ticket #3015 */
1127 if( (prereqAll>>1)>=x ){
1128 sqlite3ErrorMsg(pParse, "ON clause references tables to its right");
1129 return;
1131 }else if( (prereqAll>>1)>=x ){
1132 /* The ON clause of an INNER JOIN references a table to its right.
1133 ** Most other SQL database engines raise an error. But SQLite versions
1134 ** 3.0 through 3.38 just put the ON clause constraint into the WHERE
1135 ** clause and carried on. Beginning with 3.39, raise an error only
1136 ** if there is a RIGHT or FULL JOIN in the query. This makes SQLite
1137 ** more like other systems, and also preserves legacy. */
1138 if( ALWAYS(pSrc->nSrc>0) && (pSrc->a[0].fg.jointype & JT_LTORJ)!=0 ){
1139 sqlite3ErrorMsg(pParse, "ON clause references tables to its right");
1140 return;
1142 ExprClearProperty(pExpr, EP_InnerON);
1145 pTerm->prereqAll = prereqAll;
1146 pTerm->leftCursor = -1;
1147 pTerm->iParent = -1;
1148 pTerm->eOperator = 0;
1149 if( allowedOp(op) ){
1150 int aiCurCol[2];
1151 Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
1152 Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
1153 u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
1155 if( pTerm->u.x.iField>0 ){
1156 assert( op==TK_IN );
1157 assert( pLeft->op==TK_VECTOR );
1158 assert( ExprUseXList(pLeft) );
1159 pLeft = pLeft->x.pList->a[pTerm->u.x.iField-1].pExpr;
1162 if( exprMightBeIndexed(pSrc, aiCurCol, pLeft, op) ){
1163 pTerm->leftCursor = aiCurCol[0];
1164 assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 );
1165 pTerm->u.x.leftColumn = aiCurCol[1];
1166 pTerm->eOperator = operatorMask(op) & opMask;
1168 if( op==TK_IS ) pTerm->wtFlags |= TERM_IS;
1169 if( pRight
1170 && exprMightBeIndexed(pSrc, aiCurCol, pRight, op)
1171 && !ExprHasProperty(pRight, EP_FixedCol)
1173 WhereTerm *pNew;
1174 Expr *pDup;
1175 u16 eExtraOp = 0; /* Extra bits for pNew->eOperator */
1176 assert( pTerm->u.x.iField==0 );
1177 if( pTerm->leftCursor>=0 ){
1178 int idxNew;
1179 pDup = sqlite3ExprDup(db, pExpr, 0);
1180 if( db->mallocFailed ){
1181 sqlite3ExprDelete(db, pDup);
1182 return;
1184 idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
1185 if( idxNew==0 ) return;
1186 pNew = &pWC->a[idxNew];
1187 markTermAsChild(pWC, idxNew, idxTerm);
1188 if( op==TK_IS ) pNew->wtFlags |= TERM_IS;
1189 pTerm = &pWC->a[idxTerm];
1190 pTerm->wtFlags |= TERM_COPIED;
1192 if( termIsEquivalence(pParse, pDup) ){
1193 pTerm->eOperator |= WO_EQUIV;
1194 eExtraOp = WO_EQUIV;
1196 }else{
1197 pDup = pExpr;
1198 pNew = pTerm;
1200 pNew->wtFlags |= exprCommute(pParse, pDup);
1201 pNew->leftCursor = aiCurCol[0];
1202 assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 );
1203 pNew->u.x.leftColumn = aiCurCol[1];
1204 testcase( (prereqLeft | extraRight) != prereqLeft );
1205 pNew->prereqRight = prereqLeft | extraRight;
1206 pNew->prereqAll = prereqAll;
1207 pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
1208 }else
1209 if( op==TK_ISNULL
1210 && !ExprHasProperty(pExpr,EP_OuterON)
1211 && 0==sqlite3ExprCanBeNull(pLeft)
1213 assert( !ExprHasProperty(pExpr, EP_IntValue) );
1214 pExpr->op = TK_TRUEFALSE; /* See tag-20230504-1 */
1215 pExpr->u.zToken = "false";
1216 ExprSetProperty(pExpr, EP_IsFalse);
1217 pTerm->prereqAll = 0;
1218 pTerm->eOperator = 0;
1222 #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
1223 /* If a term is the BETWEEN operator, create two new virtual terms
1224 ** that define the range that the BETWEEN implements. For example:
1226 ** a BETWEEN b AND c
1228 ** is converted into:
1230 ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
1232 ** The two new terms are added onto the end of the WhereClause object.
1233 ** The new terms are "dynamic" and are children of the original BETWEEN
1234 ** term. That means that if the BETWEEN term is coded, the children are
1235 ** skipped. Or, if the children are satisfied by an index, the original
1236 ** BETWEEN term is skipped.
1238 else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
1239 ExprList *pList;
1240 int i;
1241 static const u8 ops[] = {TK_GE, TK_LE};
1242 assert( ExprUseXList(pExpr) );
1243 pList = pExpr->x.pList;
1244 assert( pList!=0 );
1245 assert( pList->nExpr==2 );
1246 for(i=0; i<2; i++){
1247 Expr *pNewExpr;
1248 int idxNew;
1249 pNewExpr = sqlite3PExpr(pParse, ops[i],
1250 sqlite3ExprDup(db, pExpr->pLeft, 0),
1251 sqlite3ExprDup(db, pList->a[i].pExpr, 0));
1252 transferJoinMarkings(pNewExpr, pExpr);
1253 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
1254 testcase( idxNew==0 );
1255 exprAnalyze(pSrc, pWC, idxNew);
1256 pTerm = &pWC->a[idxTerm];
1257 markTermAsChild(pWC, idxNew, idxTerm);
1260 #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
1262 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
1263 /* Analyze a term that is composed of two or more subterms connected by
1264 ** an OR operator.
1266 else if( pExpr->op==TK_OR ){
1267 assert( pWC->op==TK_AND );
1268 exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
1269 pTerm = &pWC->a[idxTerm];
1271 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
1272 /* The form "x IS NOT NULL" can sometimes be evaluated more efficiently
1273 ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a
1274 ** virtual term of that form.
1276 ** The virtual term must be tagged with TERM_VNULL.
1278 else if( pExpr->op==TK_NOTNULL ){
1279 if( pExpr->pLeft->op==TK_COLUMN
1280 && pExpr->pLeft->iColumn>=0
1281 && !ExprHasProperty(pExpr, EP_OuterON)
1283 Expr *pNewExpr;
1284 Expr *pLeft = pExpr->pLeft;
1285 int idxNew;
1286 WhereTerm *pNewTerm;
1288 pNewExpr = sqlite3PExpr(pParse, TK_GT,
1289 sqlite3ExprDup(db, pLeft, 0),
1290 sqlite3ExprAlloc(db, TK_NULL, 0, 0));
1292 idxNew = whereClauseInsert(pWC, pNewExpr,
1293 TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
1294 if( idxNew ){
1295 pNewTerm = &pWC->a[idxNew];
1296 pNewTerm->prereqRight = 0;
1297 pNewTerm->leftCursor = pLeft->iTable;
1298 pNewTerm->u.x.leftColumn = pLeft->iColumn;
1299 pNewTerm->eOperator = WO_GT;
1300 markTermAsChild(pWC, idxNew, idxTerm);
1301 pTerm = &pWC->a[idxTerm];
1302 pTerm->wtFlags |= TERM_COPIED;
1303 pNewTerm->prereqAll = pTerm->prereqAll;
1309 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
1310 /* Add constraints to reduce the search space on a LIKE or GLOB
1311 ** operator.
1313 ** A like pattern of the form "x LIKE 'aBc%'" is changed into constraints
1315 ** x>='ABC' AND x<'abd' AND x LIKE 'aBc%'
1317 ** The last character of the prefix "abc" is incremented to form the
1318 ** termination condition "abd". If case is not significant (the default
1319 ** for LIKE) then the lower-bound is made all uppercase and the upper-
1320 ** bound is made all lowercase so that the bounds also work when comparing
1321 ** BLOBs.
1323 else if( pExpr->op==TK_FUNCTION
1324 && pWC->op==TK_AND
1325 && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
1327 Expr *pLeft; /* LHS of LIKE/GLOB operator */
1328 Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */
1329 Expr *pNewExpr1;
1330 Expr *pNewExpr2;
1331 int idxNew1;
1332 int idxNew2;
1333 const char *zCollSeqName; /* Name of collating sequence */
1334 const u16 wtFlags = TERM_LIKEOPT | TERM_VIRTUAL | TERM_DYNAMIC;
1336 assert( ExprUseXList(pExpr) );
1337 pLeft = pExpr->x.pList->a[1].pExpr;
1338 pStr2 = sqlite3ExprDup(db, pStr1, 0);
1339 assert( pStr1==0 || !ExprHasProperty(pStr1, EP_IntValue) );
1340 assert( pStr2==0 || !ExprHasProperty(pStr2, EP_IntValue) );
1343 /* Convert the lower bound to upper-case and the upper bound to
1344 ** lower-case (upper-case is less than lower-case in ASCII) so that
1345 ** the range constraints also work for BLOBs
1347 if( noCase && !pParse->db->mallocFailed ){
1348 int i;
1349 char c;
1350 pTerm->wtFlags |= TERM_LIKE;
1351 for(i=0; (c = pStr1->u.zToken[i])!=0; i++){
1352 pStr1->u.zToken[i] = sqlite3Toupper(c);
1353 pStr2->u.zToken[i] = sqlite3Tolower(c);
1357 if( !db->mallocFailed ){
1358 u8 c, *pC; /* Last character before the first wildcard */
1359 pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
1360 c = *pC;
1361 if( noCase ){
1362 /* The point is to increment the last character before the first
1363 ** wildcard. But if we increment '@', that will push it into the
1364 ** alphabetic range where case conversions will mess up the
1365 ** inequality. To avoid this, make sure to also run the full
1366 ** LIKE on all candidate expressions by clearing the isComplete flag
1368 if( c=='A'-1 ) isComplete = 0;
1369 c = sqlite3UpperToLower[c];
1371 *pC = c + 1;
1373 zCollSeqName = noCase ? "NOCASE" : sqlite3StrBINARY;
1374 pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
1375 pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
1376 sqlite3ExprAddCollateString(pParse,pNewExpr1,zCollSeqName),
1377 pStr1);
1378 transferJoinMarkings(pNewExpr1, pExpr);
1379 idxNew1 = whereClauseInsert(pWC, pNewExpr1, wtFlags);
1380 testcase( idxNew1==0 );
1381 pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
1382 pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
1383 sqlite3ExprAddCollateString(pParse,pNewExpr2,zCollSeqName),
1384 pStr2);
1385 transferJoinMarkings(pNewExpr2, pExpr);
1386 idxNew2 = whereClauseInsert(pWC, pNewExpr2, wtFlags);
1387 testcase( idxNew2==0 );
1388 exprAnalyze(pSrc, pWC, idxNew1);
1389 exprAnalyze(pSrc, pWC, idxNew2);
1390 pTerm = &pWC->a[idxTerm];
1391 if( isComplete ){
1392 markTermAsChild(pWC, idxNew1, idxTerm);
1393 markTermAsChild(pWC, idxNew2, idxTerm);
1396 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
1398 /* If there is a vector == or IS term - e.g. "(a, b) == (?, ?)" - create
1399 ** new terms for each component comparison - "a = ?" and "b = ?". The
1400 ** new terms completely replace the original vector comparison, which is
1401 ** no longer used.
1403 ** This is only required if at least one side of the comparison operation
1404 ** is not a sub-select.
1406 ** tag-20220128a
1408 if( (pExpr->op==TK_EQ || pExpr->op==TK_IS)
1409 && (nLeft = sqlite3ExprVectorSize(pExpr->pLeft))>1
1410 && sqlite3ExprVectorSize(pExpr->pRight)==nLeft
1411 && ( (pExpr->pLeft->flags & EP_xIsSelect)==0
1412 || (pExpr->pRight->flags & EP_xIsSelect)==0)
1413 && pWC->op==TK_AND
1415 int i;
1416 for(i=0; i<nLeft; i++){
1417 int idxNew;
1418 Expr *pNew;
1419 Expr *pLeft = sqlite3ExprForVectorField(pParse, pExpr->pLeft, i, nLeft);
1420 Expr *pRight = sqlite3ExprForVectorField(pParse, pExpr->pRight, i, nLeft);
1422 pNew = sqlite3PExpr(pParse, pExpr->op, pLeft, pRight);
1423 transferJoinMarkings(pNew, pExpr);
1424 idxNew = whereClauseInsert(pWC, pNew, TERM_DYNAMIC|TERM_SLICE);
1425 exprAnalyze(pSrc, pWC, idxNew);
1427 pTerm = &pWC->a[idxTerm];
1428 pTerm->wtFlags |= TERM_CODED|TERM_VIRTUAL; /* Disable the original */
1429 pTerm->eOperator = WO_ROWVAL;
1432 /* If there is a vector IN term - e.g. "(a, b) IN (SELECT ...)" - create
1433 ** a virtual term for each vector component. The expression object
1434 ** used by each such virtual term is pExpr (the full vector IN(...)
1435 ** expression). The WhereTerm.u.x.iField variable identifies the index within
1436 ** the vector on the LHS that the virtual term represents.
1438 ** This only works if the RHS is a simple SELECT (not a compound) that does
1439 ** not use window functions.
1441 else if( pExpr->op==TK_IN
1442 && pTerm->u.x.iField==0
1443 && pExpr->pLeft->op==TK_VECTOR
1444 && ALWAYS( ExprUseXSelect(pExpr) )
1445 && (pExpr->x.pSelect->pPrior==0 || (pExpr->x.pSelect->selFlags & SF_Values))
1446 #ifndef SQLITE_OMIT_WINDOWFUNC
1447 && pExpr->x.pSelect->pWin==0
1448 #endif
1449 && pWC->op==TK_AND
1451 int i;
1452 for(i=0; i<sqlite3ExprVectorSize(pExpr->pLeft); i++){
1453 int idxNew;
1454 idxNew = whereClauseInsert(pWC, pExpr, TERM_VIRTUAL|TERM_SLICE);
1455 pWC->a[idxNew].u.x.iField = i+1;
1456 exprAnalyze(pSrc, pWC, idxNew);
1457 markTermAsChild(pWC, idxNew, idxTerm);
1461 #ifndef SQLITE_OMIT_VIRTUALTABLE
1462 /* Add a WO_AUX auxiliary term to the constraint set if the
1463 ** current expression is of the form "column OP expr" where OP
1464 ** is an operator that gets passed into virtual tables but which is
1465 ** not normally optimized for ordinary tables. In other words, OP
1466 ** is one of MATCH, LIKE, GLOB, REGEXP, !=, IS, IS NOT, or NOT NULL.
1467 ** This information is used by the xBestIndex methods of
1468 ** virtual tables. The native query optimizer does not attempt
1469 ** to do anything with MATCH functions.
1471 else if( pWC->op==TK_AND ){
1472 Expr *pRight = 0, *pLeft = 0;
1473 int res = isAuxiliaryVtabOperator(db, pExpr, &eOp2, &pLeft, &pRight);
1474 while( res-- > 0 ){
1475 int idxNew;
1476 WhereTerm *pNewTerm;
1477 Bitmask prereqColumn, prereqExpr;
1479 prereqExpr = sqlite3WhereExprUsage(pMaskSet, pRight);
1480 prereqColumn = sqlite3WhereExprUsage(pMaskSet, pLeft);
1481 if( (prereqExpr & prereqColumn)==0 ){
1482 Expr *pNewExpr;
1483 pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
1484 0, sqlite3ExprDup(db, pRight, 0));
1485 if( ExprHasProperty(pExpr, EP_OuterON) && pNewExpr ){
1486 ExprSetProperty(pNewExpr, EP_OuterON);
1487 pNewExpr->w.iJoin = pExpr->w.iJoin;
1489 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
1490 testcase( idxNew==0 );
1491 pNewTerm = &pWC->a[idxNew];
1492 pNewTerm->prereqRight = prereqExpr;
1493 pNewTerm->leftCursor = pLeft->iTable;
1494 pNewTerm->u.x.leftColumn = pLeft->iColumn;
1495 pNewTerm->eOperator = WO_AUX;
1496 pNewTerm->eMatchOp = eOp2;
1497 markTermAsChild(pWC, idxNew, idxTerm);
1498 pTerm = &pWC->a[idxTerm];
1499 pTerm->wtFlags |= TERM_COPIED;
1500 pNewTerm->prereqAll = pTerm->prereqAll;
1502 SWAP(Expr*, pLeft, pRight);
1505 #endif /* SQLITE_OMIT_VIRTUALTABLE */
1507 /* Prevent ON clause terms of a LEFT JOIN from being used to drive
1508 ** an index for tables to the left of the join.
1510 testcase( pTerm!=&pWC->a[idxTerm] );
1511 pTerm = &pWC->a[idxTerm];
1512 pTerm->prereqRight |= extraRight;
1515 /***************************************************************************
1516 ** Routines with file scope above. Interface to the rest of the where.c
1517 ** subsystem follows.
1518 ***************************************************************************/
1521 ** This routine identifies subexpressions in the WHERE clause where
1522 ** each subexpression is separated by the AND operator or some other
1523 ** operator specified in the op parameter. The WhereClause structure
1524 ** is filled with pointers to subexpressions. For example:
1526 ** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
1527 ** \________/ \_______________/ \________________/
1528 ** slot[0] slot[1] slot[2]
1530 ** The original WHERE clause in pExpr is unaltered. All this routine
1531 ** does is make slot[] entries point to substructure within pExpr.
1533 ** In the previous sentence and in the diagram, "slot[]" refers to
1534 ** the WhereClause.a[] array. The slot[] array grows as needed to contain
1535 ** all terms of the WHERE clause.
1537 void sqlite3WhereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
1538 Expr *pE2 = sqlite3ExprSkipCollateAndLikely(pExpr);
1539 pWC->op = op;
1540 assert( pE2!=0 || pExpr==0 );
1541 if( pE2==0 ) return;
1542 if( pE2->op!=op ){
1543 whereClauseInsert(pWC, pExpr, 0);
1544 }else{
1545 sqlite3WhereSplit(pWC, pE2->pLeft, op);
1546 sqlite3WhereSplit(pWC, pE2->pRight, op);
1551 ** Add either a LIMIT (if eMatchOp==SQLITE_INDEX_CONSTRAINT_LIMIT) or
1552 ** OFFSET (if eMatchOp==SQLITE_INDEX_CONSTRAINT_OFFSET) term to the
1553 ** where-clause passed as the first argument. The value for the term
1554 ** is found in register iReg.
1556 ** In the common case where the value is a simple integer
1557 ** (example: "LIMIT 5 OFFSET 10") then the expression codes as a
1558 ** TK_INTEGER so that it will be available to sqlite3_vtab_rhs_value().
1559 ** If not, then it codes as a TK_REGISTER expression.
1561 static void whereAddLimitExpr(
1562 WhereClause *pWC, /* Add the constraint to this WHERE clause */
1563 int iReg, /* Register that will hold value of the limit/offset */
1564 Expr *pExpr, /* Expression that defines the limit/offset */
1565 int iCsr, /* Cursor to which the constraint applies */
1566 int eMatchOp /* SQLITE_INDEX_CONSTRAINT_LIMIT or _OFFSET */
1568 Parse *pParse = pWC->pWInfo->pParse;
1569 sqlite3 *db = pParse->db;
1570 Expr *pNew;
1571 int iVal = 0;
1573 if( sqlite3ExprIsInteger(pExpr, &iVal) && iVal>=0 ){
1574 Expr *pVal = sqlite3Expr(db, TK_INTEGER, 0);
1575 if( pVal==0 ) return;
1576 ExprSetProperty(pVal, EP_IntValue);
1577 pVal->u.iValue = iVal;
1578 pNew = sqlite3PExpr(pParse, TK_MATCH, 0, pVal);
1579 }else{
1580 Expr *pVal = sqlite3Expr(db, TK_REGISTER, 0);
1581 if( pVal==0 ) return;
1582 pVal->iTable = iReg;
1583 pNew = sqlite3PExpr(pParse, TK_MATCH, 0, pVal);
1585 if( pNew ){
1586 WhereTerm *pTerm;
1587 int idx;
1588 idx = whereClauseInsert(pWC, pNew, TERM_DYNAMIC|TERM_VIRTUAL);
1589 pTerm = &pWC->a[idx];
1590 pTerm->leftCursor = iCsr;
1591 pTerm->eOperator = WO_AUX;
1592 pTerm->eMatchOp = eMatchOp;
1597 ** Possibly add terms corresponding to the LIMIT and OFFSET clauses of the
1598 ** SELECT statement passed as the second argument. These terms are only
1599 ** added if:
1601 ** 1. The SELECT statement has a LIMIT clause, and
1602 ** 2. The SELECT statement is not an aggregate or DISTINCT query, and
1603 ** 3. The SELECT statement has exactly one object in its from clause, and
1604 ** that object is a virtual table, and
1605 ** 4. There are no terms in the WHERE clause that will not be passed
1606 ** to the virtual table xBestIndex method.
1607 ** 5. The ORDER BY clause, if any, will be made available to the xBestIndex
1608 ** method.
1610 ** LIMIT and OFFSET terms are ignored by most of the planner code. They
1611 ** exist only so that they may be passed to the xBestIndex method of the
1612 ** single virtual table in the FROM clause of the SELECT.
1614 void SQLITE_NOINLINE sqlite3WhereAddLimit(WhereClause *pWC, Select *p){
1615 assert( p!=0 && p->pLimit!=0 ); /* 1 -- checked by caller */
1616 if( p->pGroupBy==0
1617 && (p->selFlags & (SF_Distinct|SF_Aggregate))==0 /* 2 */
1618 && (p->pSrc->nSrc==1 && IsVirtual(p->pSrc->a[0].pTab)) /* 3 */
1620 ExprList *pOrderBy = p->pOrderBy;
1621 int iCsr = p->pSrc->a[0].iCursor;
1622 int ii;
1624 /* Check condition (4). Return early if it is not met. */
1625 for(ii=0; ii<pWC->nTerm; ii++){
1626 if( pWC->a[ii].wtFlags & TERM_CODED ){
1627 /* This term is a vector operation that has been decomposed into
1628 ** other, subsequent terms. It can be ignored. See tag-20220128a */
1629 assert( pWC->a[ii].wtFlags & TERM_VIRTUAL );
1630 assert( pWC->a[ii].eOperator==WO_ROWVAL );
1631 continue;
1633 if( pWC->a[ii].nChild ){
1634 /* If this term has child terms, then they are also part of the
1635 ** pWC->a[] array. So this term can be ignored, as a LIMIT clause
1636 ** will only be added if each of the child terms passes the
1637 ** (leftCursor==iCsr) test below. */
1638 continue;
1640 if( pWC->a[ii].leftCursor!=iCsr ) return;
1643 /* Check condition (5). Return early if it is not met. */
1644 if( pOrderBy ){
1645 for(ii=0; ii<pOrderBy->nExpr; ii++){
1646 Expr *pExpr = pOrderBy->a[ii].pExpr;
1647 if( pExpr->op!=TK_COLUMN ) return;
1648 if( pExpr->iTable!=iCsr ) return;
1649 if( pOrderBy->a[ii].fg.sortFlags & KEYINFO_ORDER_BIGNULL ) return;
1653 /* All conditions are met. Add the terms to the where-clause object. */
1654 assert( p->pLimit->op==TK_LIMIT );
1655 whereAddLimitExpr(pWC, p->iLimit, p->pLimit->pLeft,
1656 iCsr, SQLITE_INDEX_CONSTRAINT_LIMIT);
1657 if( p->iOffset>0 ){
1658 whereAddLimitExpr(pWC, p->iOffset, p->pLimit->pRight,
1659 iCsr, SQLITE_INDEX_CONSTRAINT_OFFSET);
1665 ** Initialize a preallocated WhereClause structure.
1667 void sqlite3WhereClauseInit(
1668 WhereClause *pWC, /* The WhereClause to be initialized */
1669 WhereInfo *pWInfo /* The WHERE processing context */
1671 pWC->pWInfo = pWInfo;
1672 pWC->hasOr = 0;
1673 pWC->pOuter = 0;
1674 pWC->nTerm = 0;
1675 pWC->nBase = 0;
1676 pWC->nSlot = ArraySize(pWC->aStatic);
1677 pWC->a = pWC->aStatic;
1681 ** Deallocate a WhereClause structure. The WhereClause structure
1682 ** itself is not freed. This routine is the inverse of
1683 ** sqlite3WhereClauseInit().
1685 void sqlite3WhereClauseClear(WhereClause *pWC){
1686 sqlite3 *db = pWC->pWInfo->pParse->db;
1687 assert( pWC->nTerm>=pWC->nBase );
1688 if( pWC->nTerm>0 ){
1689 WhereTerm *a = pWC->a;
1690 WhereTerm *aLast = &pWC->a[pWC->nTerm-1];
1691 #ifdef SQLITE_DEBUG
1692 int i;
1693 /* Verify that every term past pWC->nBase is virtual */
1694 for(i=pWC->nBase; i<pWC->nTerm; i++){
1695 assert( (pWC->a[i].wtFlags & TERM_VIRTUAL)!=0 );
1697 #endif
1698 while(1){
1699 assert( a->eMatchOp==0 || a->eOperator==WO_AUX );
1700 if( a->wtFlags & TERM_DYNAMIC ){
1701 sqlite3ExprDelete(db, a->pExpr);
1703 if( a->wtFlags & (TERM_ORINFO|TERM_ANDINFO) ){
1704 if( a->wtFlags & TERM_ORINFO ){
1705 assert( (a->wtFlags & TERM_ANDINFO)==0 );
1706 whereOrInfoDelete(db, a->u.pOrInfo);
1707 }else{
1708 assert( (a->wtFlags & TERM_ANDINFO)!=0 );
1709 whereAndInfoDelete(db, a->u.pAndInfo);
1712 if( a==aLast ) break;
1713 a++;
1720 ** These routines walk (recursively) an expression tree and generate
1721 ** a bitmask indicating which tables are used in that expression
1722 ** tree.
1724 ** sqlite3WhereExprUsage(MaskSet, Expr) ->
1726 ** Return a Bitmask of all tables referenced by Expr. Expr can be
1727 ** be NULL, in which case 0 is returned.
1729 ** sqlite3WhereExprUsageNN(MaskSet, Expr) ->
1731 ** Same as sqlite3WhereExprUsage() except that Expr must not be
1732 ** NULL. The "NN" suffix on the name stands for "Not Null".
1734 ** sqlite3WhereExprListUsage(MaskSet, ExprList) ->
1736 ** Return a Bitmask of all tables referenced by every expression
1737 ** in the expression list ExprList. ExprList can be NULL, in which
1738 ** case 0 is returned.
1740 ** sqlite3WhereExprUsageFull(MaskSet, ExprList) ->
1742 ** Internal use only. Called only by sqlite3WhereExprUsageNN() for
1743 ** complex expressions that require pushing register values onto
1744 ** the stack. Many calls to sqlite3WhereExprUsageNN() do not need
1745 ** the more complex analysis done by this routine. Hence, the
1746 ** computations done by this routine are broken out into a separate
1747 ** "no-inline" function to avoid the stack push overhead in the
1748 ** common case where it is not needed.
1750 static SQLITE_NOINLINE Bitmask sqlite3WhereExprUsageFull(
1751 WhereMaskSet *pMaskSet,
1752 Expr *p
1754 Bitmask mask;
1755 mask = (p->op==TK_IF_NULL_ROW) ? sqlite3WhereGetMask(pMaskSet, p->iTable) : 0;
1756 if( p->pLeft ) mask |= sqlite3WhereExprUsageNN(pMaskSet, p->pLeft);
1757 if( p->pRight ){
1758 mask |= sqlite3WhereExprUsageNN(pMaskSet, p->pRight);
1759 assert( p->x.pList==0 );
1760 }else if( ExprUseXSelect(p) ){
1761 if( ExprHasProperty(p, EP_VarSelect) ) pMaskSet->bVarSelect = 1;
1762 mask |= exprSelectUsage(pMaskSet, p->x.pSelect);
1763 }else if( p->x.pList ){
1764 mask |= sqlite3WhereExprListUsage(pMaskSet, p->x.pList);
1766 #ifndef SQLITE_OMIT_WINDOWFUNC
1767 if( (p->op==TK_FUNCTION || p->op==TK_AGG_FUNCTION) && ExprUseYWin(p) ){
1768 assert( p->y.pWin!=0 );
1769 mask |= sqlite3WhereExprListUsage(pMaskSet, p->y.pWin->pPartition);
1770 mask |= sqlite3WhereExprListUsage(pMaskSet, p->y.pWin->pOrderBy);
1771 mask |= sqlite3WhereExprUsage(pMaskSet, p->y.pWin->pFilter);
1773 #endif
1774 return mask;
1776 Bitmask sqlite3WhereExprUsageNN(WhereMaskSet *pMaskSet, Expr *p){
1777 if( p->op==TK_COLUMN && !ExprHasProperty(p, EP_FixedCol) ){
1778 return sqlite3WhereGetMask(pMaskSet, p->iTable);
1779 }else if( ExprHasProperty(p, EP_TokenOnly|EP_Leaf) ){
1780 assert( p->op!=TK_IF_NULL_ROW );
1781 return 0;
1783 return sqlite3WhereExprUsageFull(pMaskSet, p);
1785 Bitmask sqlite3WhereExprUsage(WhereMaskSet *pMaskSet, Expr *p){
1786 return p ? sqlite3WhereExprUsageNN(pMaskSet,p) : 0;
1788 Bitmask sqlite3WhereExprListUsage(WhereMaskSet *pMaskSet, ExprList *pList){
1789 int i;
1790 Bitmask mask = 0;
1791 if( pList ){
1792 for(i=0; i<pList->nExpr; i++){
1793 mask |= sqlite3WhereExprUsage(pMaskSet, pList->a[i].pExpr);
1796 return mask;
1801 ** Call exprAnalyze on all terms in a WHERE clause.
1803 ** Note that exprAnalyze() might add new virtual terms onto the
1804 ** end of the WHERE clause. We do not want to analyze these new
1805 ** virtual terms, so start analyzing at the end and work forward
1806 ** so that the added virtual terms are never processed.
1808 void sqlite3WhereExprAnalyze(
1809 SrcList *pTabList, /* the FROM clause */
1810 WhereClause *pWC /* the WHERE clause to be analyzed */
1812 int i;
1813 for(i=pWC->nTerm-1; i>=0; i--){
1814 exprAnalyze(pTabList, pWC, i);
1819 ** For table-valued-functions, transform the function arguments into
1820 ** new WHERE clause terms.
1822 ** Each function argument translates into an equality constraint against
1823 ** a HIDDEN column in the table.
1825 void sqlite3WhereTabFuncArgs(
1826 Parse *pParse, /* Parsing context */
1827 SrcItem *pItem, /* The FROM clause term to process */
1828 WhereClause *pWC /* Xfer function arguments to here */
1830 Table *pTab;
1831 int j, k;
1832 ExprList *pArgs;
1833 Expr *pColRef;
1834 Expr *pTerm;
1835 if( pItem->fg.isTabFunc==0 ) return;
1836 pTab = pItem->pTab;
1837 assert( pTab!=0 );
1838 pArgs = pItem->u1.pFuncArg;
1839 if( pArgs==0 ) return;
1840 for(j=k=0; j<pArgs->nExpr; j++){
1841 Expr *pRhs;
1842 u32 joinType;
1843 while( k<pTab->nCol && (pTab->aCol[k].colFlags & COLFLAG_HIDDEN)==0 ){k++;}
1844 if( k>=pTab->nCol ){
1845 sqlite3ErrorMsg(pParse, "too many arguments on %s() - max %d",
1846 pTab->zName, j);
1847 return;
1849 pColRef = sqlite3ExprAlloc(pParse->db, TK_COLUMN, 0, 0);
1850 if( pColRef==0 ) return;
1851 pColRef->iTable = pItem->iCursor;
1852 pColRef->iColumn = k++;
1853 assert( ExprUseYTab(pColRef) );
1854 pColRef->y.pTab = pTab;
1855 pItem->colUsed |= sqlite3ExprColUsed(pColRef);
1856 pRhs = sqlite3PExpr(pParse, TK_UPLUS,
1857 sqlite3ExprDup(pParse->db, pArgs->a[j].pExpr, 0), 0);
1858 pTerm = sqlite3PExpr(pParse, TK_EQ, pColRef, pRhs);
1859 if( pItem->fg.jointype & (JT_LEFT|JT_RIGHT) ){
1860 testcase( pItem->fg.jointype & JT_LEFT ); /* testtag-20230227a */
1861 testcase( pItem->fg.jointype & JT_RIGHT ); /* testtag-20230227b */
1862 joinType = EP_OuterON;
1863 }else{
1864 testcase( pItem->fg.jointype & JT_LTORJ ); /* testtag-20230227c */
1865 joinType = EP_InnerON;
1867 sqlite3SetJoinExpr(pTerm, pItem->iCursor, joinType);
1868 whereClauseInsert(pWC, pTerm, TERM_DYNAMIC);