4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
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 split off from where.c on 2015-06-06 in order to reduce the
16 ** size of where.c and make it easier to edit. This file contains the routines
17 ** that actually generate the bulk of the WHERE loop code. The original where.c
18 ** file retains the code that does query planning and analysis.
20 #include "sqliteInt.h"
23 #ifndef SQLITE_OMIT_EXPLAIN
26 ** Return the name of the i-th column of the pIdx index.
28 static const char *explainIndexColumnName(Index
*pIdx
, int i
){
29 i
= pIdx
->aiColumn
[i
];
30 if( i
==XN_EXPR
) return "<expr>";
31 if( i
==XN_ROWID
) return "rowid";
32 return pIdx
->pTable
->aCol
[i
].zCnName
;
36 ** This routine is a helper for explainIndexRange() below
38 ** pStr holds the text of an expression that we are building up one term
39 ** at a time. This routine adds a new term to the end of the expression.
40 ** Terms are separated by AND so add the "AND" text for second and subsequent
43 static void explainAppendTerm(
44 StrAccum
*pStr
, /* The text expression being built */
45 Index
*pIdx
, /* Index to read column names from */
46 int nTerm
, /* Number of terms */
47 int iTerm
, /* Zero-based index of first term. */
48 int bAnd
, /* Non-zero to append " AND " */
49 const char *zOp
/* Name of the operator */
54 if( bAnd
) sqlite3_str_append(pStr
, " AND ", 5);
56 if( nTerm
>1 ) sqlite3_str_append(pStr
, "(", 1);
57 for(i
=0; i
<nTerm
; i
++){
58 if( i
) sqlite3_str_append(pStr
, ",", 1);
59 sqlite3_str_appendall(pStr
, explainIndexColumnName(pIdx
, iTerm
+i
));
61 if( nTerm
>1 ) sqlite3_str_append(pStr
, ")", 1);
63 sqlite3_str_append(pStr
, zOp
, 1);
65 if( nTerm
>1 ) sqlite3_str_append(pStr
, "(", 1);
66 for(i
=0; i
<nTerm
; i
++){
67 if( i
) sqlite3_str_append(pStr
, ",", 1);
68 sqlite3_str_append(pStr
, "?", 1);
70 if( nTerm
>1 ) sqlite3_str_append(pStr
, ")", 1);
74 ** Argument pLevel describes a strategy for scanning table pTab. This
75 ** function appends text to pStr that describes the subset of table
76 ** rows scanned by the strategy in the form of an SQL expression.
78 ** For example, if the query:
80 ** SELECT * FROM t1 WHERE a=1 AND b>2;
82 ** is run and there is an index on (a, b), then this function returns a
87 static void explainIndexRange(StrAccum
*pStr
, WhereLoop
*pLoop
){
88 Index
*pIndex
= pLoop
->u
.btree
.pIndex
;
89 u16 nEq
= pLoop
->u
.btree
.nEq
;
90 u16 nSkip
= pLoop
->nSkip
;
93 if( nEq
==0 && (pLoop
->wsFlags
&(WHERE_BTM_LIMIT
|WHERE_TOP_LIMIT
))==0 ) return;
94 sqlite3_str_append(pStr
, " (", 2);
96 const char *z
= explainIndexColumnName(pIndex
, i
);
97 if( i
) sqlite3_str_append(pStr
, " AND ", 5);
98 sqlite3_str_appendf(pStr
, i
>=nSkip
? "%s=?" : "ANY(%s)", z
);
102 if( pLoop
->wsFlags
&WHERE_BTM_LIMIT
){
103 explainAppendTerm(pStr
, pIndex
, pLoop
->u
.btree
.nBtm
, j
, i
, ">");
106 if( pLoop
->wsFlags
&WHERE_TOP_LIMIT
){
107 explainAppendTerm(pStr
, pIndex
, pLoop
->u
.btree
.nTop
, j
, i
, "<");
109 sqlite3_str_append(pStr
, ")", 1);
113 ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
114 ** command, or if stmt_scanstatus_v2() stats are enabled, or if SQLITE_DEBUG
115 ** was defined at compile-time. If it is not a no-op, a single OP_Explain
116 ** opcode is added to the output to describe the table scan strategy in pLevel.
118 ** If an OP_Explain opcode is added to the VM, its address is returned.
119 ** Otherwise, if no OP_Explain is coded, zero is returned.
121 int sqlite3WhereExplainOneScan(
122 Parse
*pParse
, /* Parse context */
123 SrcList
*pTabList
, /* Table list this loop refers to */
124 WhereLevel
*pLevel
, /* Scan to write OP_Explain opcode for */
125 u16 wctrlFlags
/* Flags passed to sqlite3WhereBegin() */
128 #if !defined(SQLITE_DEBUG)
129 if( sqlite3ParseToplevel(pParse
)->explain
==2 || IS_STMT_SCANSTATUS(pParse
->db
) )
132 SrcItem
*pItem
= &pTabList
->a
[pLevel
->iFrom
];
133 Vdbe
*v
= pParse
->pVdbe
; /* VM being constructed */
134 sqlite3
*db
= pParse
->db
; /* Database handle */
135 int isSearch
; /* True for a SEARCH. False for SCAN. */
136 WhereLoop
*pLoop
; /* The controlling WhereLoop object */
137 u32 flags
; /* Flags that describe this loop */
138 char *zMsg
; /* Text to add to EQP output */
139 StrAccum str
; /* EQP output string */
140 char zBuf
[100]; /* Initial space for EQP output string */
142 pLoop
= pLevel
->pWLoop
;
143 flags
= pLoop
->wsFlags
;
144 if( (flags
&WHERE_MULTI_OR
) || (wctrlFlags
&WHERE_OR_SUBCLAUSE
) ) return 0;
146 isSearch
= (flags
&(WHERE_BTM_LIMIT
|WHERE_TOP_LIMIT
))!=0
147 || ((flags
&WHERE_VIRTUALTABLE
)==0 && (pLoop
->u
.btree
.nEq
>0))
148 || (wctrlFlags
&(WHERE_ORDERBY_MIN
|WHERE_ORDERBY_MAX
));
150 sqlite3StrAccumInit(&str
, db
, zBuf
, sizeof(zBuf
), SQLITE_MAX_LENGTH
);
151 str
.printfFlags
= SQLITE_PRINTF_INTERNAL
;
152 sqlite3_str_appendf(&str
, "%s %S", isSearch
? "SEARCH" : "SCAN", pItem
);
153 if( (flags
& (WHERE_IPK
|WHERE_VIRTUALTABLE
))==0 ){
154 const char *zFmt
= 0;
157 assert( pLoop
->u
.btree
.pIndex
!=0 );
158 pIdx
= pLoop
->u
.btree
.pIndex
;
159 assert( !(flags
&WHERE_AUTO_INDEX
) || (flags
&WHERE_IDX_ONLY
) );
160 if( !HasRowid(pItem
->pTab
) && IsPrimaryKeyIndex(pIdx
) ){
162 zFmt
= "PRIMARY KEY";
164 }else if( flags
& WHERE_PARTIALIDX
){
165 zFmt
= "AUTOMATIC PARTIAL COVERING INDEX";
166 }else if( flags
& WHERE_AUTO_INDEX
){
167 zFmt
= "AUTOMATIC COVERING INDEX";
168 }else if( flags
& WHERE_IDX_ONLY
){
169 zFmt
= "COVERING INDEX %s";
174 sqlite3_str_append(&str
, " USING ", 7);
175 sqlite3_str_appendf(&str
, zFmt
, pIdx
->zName
);
176 explainIndexRange(&str
, pLoop
);
178 }else if( (flags
& WHERE_IPK
)!=0 && (flags
& WHERE_CONSTRAINT
)!=0 ){
180 #if 0 /* Better output, but breaks many tests */
181 const Table
*pTab
= pItem
->pTab
;
182 const char *zRowid
= pTab
->iPKey
>=0 ? pTab
->aCol
[pTab
->iPKey
].zCnName
:
185 const char *zRowid
= "rowid";
187 sqlite3_str_appendf(&str
, " USING INTEGER PRIMARY KEY (%s", zRowid
);
188 if( flags
&(WHERE_COLUMN_EQ
|WHERE_COLUMN_IN
) ){
190 }else if( (flags
&WHERE_BOTH_LIMIT
)==WHERE_BOTH_LIMIT
){
191 sqlite3_str_appendf(&str
, ">? AND %s", zRowid
);
193 }else if( flags
&WHERE_BTM_LIMIT
){
196 assert( flags
&WHERE_TOP_LIMIT
);
199 sqlite3_str_appendf(&str
, "%c?)", cRangeOp
);
201 #ifndef SQLITE_OMIT_VIRTUALTABLE
202 else if( (flags
& WHERE_VIRTUALTABLE
)!=0 ){
203 sqlite3_str_appendf(&str
, " VIRTUAL TABLE INDEX %d:%s",
204 pLoop
->u
.vtab
.idxNum
, pLoop
->u
.vtab
.idxStr
);
207 if( pItem
->fg
.jointype
& JT_LEFT
){
208 sqlite3_str_appendf(&str
, " LEFT-JOIN");
210 #ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS
211 if( pLoop
->nOut
>=10 ){
212 sqlite3_str_appendf(&str
, " (~%llu rows)",
213 sqlite3LogEstToInt(pLoop
->nOut
));
215 sqlite3_str_append(&str
, " (~1 row)", 9);
218 zMsg
= sqlite3StrAccumFinish(&str
);
219 sqlite3ExplainBreakpoint("",zMsg
);
220 ret
= sqlite3VdbeAddOp4(v
, OP_Explain
, sqlite3VdbeCurrentAddr(v
),
221 pParse
->addrExplain
, 0, zMsg
,P4_DYNAMIC
);
227 ** Add a single OP_Explain opcode that describes a Bloom filter.
229 ** Or if not processing EXPLAIN QUERY PLAN and not in a SQLITE_DEBUG and/or
230 ** SQLITE_ENABLE_STMT_SCANSTATUS build, then OP_Explain opcodes are not
231 ** required and this routine is a no-op.
233 ** If an OP_Explain opcode is added to the VM, its address is returned.
234 ** Otherwise, if no OP_Explain is coded, zero is returned.
236 int sqlite3WhereExplainBloomFilter(
237 const Parse
*pParse
, /* Parse context */
238 const WhereInfo
*pWInfo
, /* WHERE clause */
239 const WhereLevel
*pLevel
/* Bloom filter on this level */
242 SrcItem
*pItem
= &pWInfo
->pTabList
->a
[pLevel
->iFrom
];
243 Vdbe
*v
= pParse
->pVdbe
; /* VM being constructed */
244 sqlite3
*db
= pParse
->db
; /* Database handle */
245 char *zMsg
; /* Text to add to EQP output */
246 int i
; /* Loop counter */
247 WhereLoop
*pLoop
; /* The where loop */
248 StrAccum str
; /* EQP output string */
249 char zBuf
[100]; /* Initial space for EQP output string */
251 sqlite3StrAccumInit(&str
, db
, zBuf
, sizeof(zBuf
), SQLITE_MAX_LENGTH
);
252 str
.printfFlags
= SQLITE_PRINTF_INTERNAL
;
253 sqlite3_str_appendf(&str
, "BLOOM FILTER ON %S (", pItem
);
254 pLoop
= pLevel
->pWLoop
;
255 if( pLoop
->wsFlags
& WHERE_IPK
){
256 const Table
*pTab
= pItem
->pTab
;
257 if( pTab
->iPKey
>=0 ){
258 sqlite3_str_appendf(&str
, "%s=?", pTab
->aCol
[pTab
->iPKey
].zCnName
);
260 sqlite3_str_appendf(&str
, "rowid=?");
263 for(i
=pLoop
->nSkip
; i
<pLoop
->u
.btree
.nEq
; i
++){
264 const char *z
= explainIndexColumnName(pLoop
->u
.btree
.pIndex
, i
);
265 if( i
>pLoop
->nSkip
) sqlite3_str_append(&str
, " AND ", 5);
266 sqlite3_str_appendf(&str
, "%s=?", z
);
269 sqlite3_str_append(&str
, ")", 1);
270 zMsg
= sqlite3StrAccumFinish(&str
);
271 ret
= sqlite3VdbeAddOp4(v
, OP_Explain
, sqlite3VdbeCurrentAddr(v
),
272 pParse
->addrExplain
, 0, zMsg
,P4_DYNAMIC
);
274 sqlite3VdbeScanStatus(v
, sqlite3VdbeCurrentAddr(v
)-1, 0, 0, 0, 0);
277 #endif /* SQLITE_OMIT_EXPLAIN */
279 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
281 ** Configure the VM passed as the first argument with an
282 ** sqlite3_stmt_scanstatus() entry corresponding to the scan used to
283 ** implement level pLvl. Argument pSrclist is a pointer to the FROM
284 ** clause that the scan reads data from.
286 ** If argument addrExplain is not 0, it must be the address of an
287 ** OP_Explain instruction that describes the same loop.
289 void sqlite3WhereAddScanStatus(
290 Vdbe
*v
, /* Vdbe to add scanstatus entry to */
291 SrcList
*pSrclist
, /* FROM clause pLvl reads data from */
292 WhereLevel
*pLvl
, /* Level to add scanstatus() entry for */
293 int addrExplain
/* Address of OP_Explain (or 0) */
295 if( IS_STMT_SCANSTATUS( sqlite3VdbeDb(v
) ) ){
296 const char *zObj
= 0;
297 WhereLoop
*pLoop
= pLvl
->pWLoop
;
298 int wsFlags
= pLoop
->wsFlags
;
299 int viaCoroutine
= 0;
301 if( (wsFlags
& WHERE_VIRTUALTABLE
)==0 && pLoop
->u
.btree
.pIndex
!=0 ){
302 zObj
= pLoop
->u
.btree
.pIndex
->zName
;
304 zObj
= pSrclist
->a
[pLvl
->iFrom
].zName
;
305 viaCoroutine
= pSrclist
->a
[pLvl
->iFrom
].fg
.viaCoroutine
;
307 sqlite3VdbeScanStatus(
308 v
, addrExplain
, pLvl
->addrBody
, pLvl
->addrVisit
, pLoop
->nOut
, zObj
311 if( viaCoroutine
==0 ){
312 if( (wsFlags
& (WHERE_MULTI_OR
|WHERE_AUTO_INDEX
))==0 ){
313 sqlite3VdbeScanStatusRange(v
, addrExplain
, -1, pLvl
->iTabCur
);
315 if( wsFlags
& WHERE_INDEXED
){
316 sqlite3VdbeScanStatusRange(v
, addrExplain
, -1, pLvl
->iIdxCur
);
325 ** Disable a term in the WHERE clause. Except, do not disable the term
326 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
327 ** or USING clause of that join.
329 ** Consider the term t2.z='ok' in the following queries:
331 ** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
332 ** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
333 ** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
335 ** The t2.z='ok' is disabled in the in (2) because it originates
336 ** in the ON clause. The term is disabled in (3) because it is not part
337 ** of a LEFT OUTER JOIN. In (1), the term is not disabled.
339 ** Disabling a term causes that term to not be tested in the inner loop
340 ** of the join. Disabling is an optimization. When terms are satisfied
341 ** by indices, we disable them to prevent redundant tests in the inner
342 ** loop. We would get the correct results if nothing were ever disabled,
343 ** but joins might run a little slower. The trick is to disable as much
344 ** as we can without disabling too much. If we disabled in (1), we'd get
345 ** the wrong answer. See ticket #813.
347 ** If all the children of a term are disabled, then that term is also
348 ** automatically disabled. In this way, terms get disabled if derived
349 ** virtual terms are tested first. For example:
351 ** x GLOB 'abc*' AND x>='abc' AND x<'acd'
352 ** \___________/ \______/ \_____/
353 ** parent child1 child2
355 ** Only the parent term was in the original WHERE clause. The child1
356 ** and child2 terms were added by the LIKE optimization. If both of
357 ** the virtual child terms are valid, then testing of the parent can be
360 ** Usually the parent term is marked as TERM_CODED. But if the parent
361 ** term was originally TERM_LIKE, then the parent gets TERM_LIKECOND instead.
362 ** The TERM_LIKECOND marking indicates that the term should be coded inside
363 ** a conditional such that is only evaluated on the second pass of a
364 ** LIKE-optimization loop, when scanning BLOBs instead of strings.
366 static void disableTerm(WhereLevel
*pLevel
, WhereTerm
*pTerm
){
369 while( (pTerm
->wtFlags
& TERM_CODED
)==0
370 && (pLevel
->iLeftJoin
==0 || ExprHasProperty(pTerm
->pExpr
, EP_OuterON
))
371 && (pLevel
->notReady
& pTerm
->prereqAll
)==0
373 if( nLoop
&& (pTerm
->wtFlags
& TERM_LIKE
)!=0 ){
374 pTerm
->wtFlags
|= TERM_LIKECOND
;
376 pTerm
->wtFlags
|= TERM_CODED
;
378 #ifdef WHERETRACE_ENABLED
379 if( (sqlite3WhereTrace
& 0x4001)==0x4001 ){
380 sqlite3DebugPrintf("DISABLE-");
381 sqlite3WhereTermPrint(pTerm
, (int)(pTerm
- (pTerm
->pWC
->a
)));
384 if( pTerm
->iParent
<0 ) break;
385 pTerm
= &pTerm
->pWC
->a
[pTerm
->iParent
];
388 if( pTerm
->nChild
!=0 ) break;
394 ** Code an OP_Affinity opcode to apply the column affinity string zAff
395 ** to the n registers starting at base.
397 ** As an optimization, SQLITE_AFF_BLOB and SQLITE_AFF_NONE entries (which
398 ** are no-ops) at the beginning and end of zAff are ignored. If all entries
399 ** in zAff are SQLITE_AFF_BLOB or SQLITE_AFF_NONE, then no code gets generated.
401 ** This routine makes its own copy of zAff so that the caller is free
402 ** to modify zAff after this routine returns.
404 static void codeApplyAffinity(Parse
*pParse
, int base
, int n
, char *zAff
){
405 Vdbe
*v
= pParse
->pVdbe
;
407 assert( pParse
->db
->mallocFailed
);
412 /* Adjust base and n to skip over SQLITE_AFF_BLOB and SQLITE_AFF_NONE
413 ** entries at the beginning and end of the affinity string.
415 assert( SQLITE_AFF_NONE
<SQLITE_AFF_BLOB
);
416 while( n
>0 && zAff
[0]<=SQLITE_AFF_BLOB
){
421 while( n
>1 && zAff
[n
-1]<=SQLITE_AFF_BLOB
){
425 /* Code the OP_Affinity opcode if there is anything left to do. */
427 sqlite3VdbeAddOp4(v
, OP_Affinity
, base
, n
, 0, zAff
, n
);
432 ** Expression pRight, which is the RHS of a comparison operation, is
433 ** either a vector of n elements or, if n==1, a scalar expression.
434 ** Before the comparison operation, affinity zAff is to be applied
435 ** to the pRight values. This function modifies characters within the
436 ** affinity string to SQLITE_AFF_BLOB if either:
438 ** * the comparison will be performed with no affinity, or
439 ** * the affinity change in zAff is guaranteed not to change the value.
441 static void updateRangeAffinityStr(
442 Expr
*pRight
, /* RHS of comparison */
443 int n
, /* Number of vector elements in comparison */
444 char *zAff
/* Affinity string to modify */
448 Expr
*p
= sqlite3VectorFieldSubexpr(pRight
, i
);
449 if( sqlite3CompareAffinity(p
, zAff
[i
])==SQLITE_AFF_BLOB
450 || sqlite3ExprNeedsNoAffinityChange(p
, zAff
[i
])
452 zAff
[i
] = SQLITE_AFF_BLOB
;
459 ** pX is an expression of the form: (vector) IN (SELECT ...)
460 ** In other words, it is a vector IN operator with a SELECT clause on the
461 ** LHS. But not all terms in the vector are indexable and the terms might
462 ** not be in the correct order for indexing.
464 ** This routine makes a copy of the input pX expression and then adjusts
465 ** the vector on the LHS with corresponding changes to the SELECT so that
466 ** the vector contains only index terms and those terms are in the correct
467 ** order. The modified IN expression is returned. The caller is responsible
468 ** for deleting the returned expression.
472 ** CREATE TABLE t1(a,b,c,d,e,f);
473 ** CREATE INDEX t1x1 ON t1(e,c);
474 ** SELECT * FROM t1 WHERE (a,b,c,d,e) IN (SELECT v,w,x,y,z FROM t2)
475 ** \_______________________________________/
478 ** Since only columns e and c can be used with the index, in that order,
479 ** the modified IN expression that is returned will be:
481 ** (e,c) IN (SELECT z,x FROM t2)
483 ** The reduced pX is different from the original (obviously) and thus is
484 ** only used for indexing, to improve performance. The original unaltered
485 ** IN expression must also be run on each output row for correctness.
487 static Expr
*removeUnindexableInClauseTerms(
488 Parse
*pParse
, /* The parsing context */
489 int iEq
, /* Look at loop terms starting here */
490 WhereLoop
*pLoop
, /* The current loop */
491 Expr
*pX
/* The IN expression to be reduced */
493 sqlite3
*db
= pParse
->db
;
494 Select
*pSelect
; /* Pointer to the SELECT on the RHS */
496 pNew
= sqlite3ExprDup(db
, pX
, 0);
497 if( db
->mallocFailed
==0 ){
498 for(pSelect
=pNew
->x
.pSelect
; pSelect
; pSelect
=pSelect
->pPrior
){
499 ExprList
*pOrigRhs
; /* Original unmodified RHS */
500 ExprList
*pOrigLhs
= 0; /* Original unmodified LHS */
501 ExprList
*pRhs
= 0; /* New RHS after modifications */
502 ExprList
*pLhs
= 0; /* New LHS after mods */
503 int i
; /* Loop counter */
505 assert( ExprUseXSelect(pNew
) );
506 pOrigRhs
= pSelect
->pEList
;
507 assert( pNew
->pLeft
!=0 );
508 assert( ExprUseXList(pNew
->pLeft
) );
509 if( pSelect
==pNew
->x
.pSelect
){
510 pOrigLhs
= pNew
->pLeft
->x
.pList
;
512 for(i
=iEq
; i
<pLoop
->nLTerm
; i
++){
513 if( pLoop
->aLTerm
[i
]->pExpr
==pX
){
515 assert( (pLoop
->aLTerm
[i
]->eOperator
& (WO_OR
|WO_AND
))==0 );
516 iField
= pLoop
->aLTerm
[i
]->u
.x
.iField
- 1;
517 if( pOrigRhs
->a
[iField
].pExpr
==0 ) continue; /* Duplicate PK column */
518 pRhs
= sqlite3ExprListAppend(pParse
, pRhs
, pOrigRhs
->a
[iField
].pExpr
);
519 pOrigRhs
->a
[iField
].pExpr
= 0;
521 assert( pOrigLhs
->a
[iField
].pExpr
!=0 );
522 pLhs
= sqlite3ExprListAppend(pParse
,pLhs
,pOrigLhs
->a
[iField
].pExpr
);
523 pOrigLhs
->a
[iField
].pExpr
= 0;
527 sqlite3ExprListDelete(db
, pOrigRhs
);
529 sqlite3ExprListDelete(db
, pOrigLhs
);
530 pNew
->pLeft
->x
.pList
= pLhs
;
532 pSelect
->pEList
= pRhs
;
533 if( pLhs
&& pLhs
->nExpr
==1 ){
534 /* Take care here not to generate a TK_VECTOR containing only a
535 ** single value. Since the parser never creates such a vector, some
536 ** of the subroutines do not handle this case. */
537 Expr
*p
= pLhs
->a
[0].pExpr
;
538 pLhs
->a
[0].pExpr
= 0;
539 sqlite3ExprDelete(db
, pNew
->pLeft
);
542 if( pSelect
->pOrderBy
){
543 /* If the SELECT statement has an ORDER BY clause, zero the
544 ** iOrderByCol variables. These are set to non-zero when an
545 ** ORDER BY term exactly matches one of the terms of the
546 ** result-set. Since the result-set of the SELECT statement may
547 ** have been modified or reordered, these variables are no longer
548 ** set correctly. Since setting them is just an optimization,
549 ** it's easiest just to zero them here. */
550 ExprList
*pOrderBy
= pSelect
->pOrderBy
;
551 for(i
=0; i
<pOrderBy
->nExpr
; i
++){
552 pOrderBy
->a
[i
].u
.x
.iOrderByCol
= 0;
557 printf("For indexing, change the IN expr:\n");
558 sqlite3TreeViewExpr(0, pX
, 0);
560 sqlite3TreeViewExpr(0, pNew
, 0);
569 ** Generate code for a single equality term of the WHERE clause. An equality
570 ** term can be either X=expr or X IN (...). pTerm is the term to be
573 ** The current value for the constraint is left in a register, the index
574 ** of which is returned. An attempt is made store the result in iTarget but
575 ** this is only guaranteed for TK_ISNULL and TK_IN constraints. If the
576 ** constraint is a TK_EQ or TK_IS, then the current value might be left in
577 ** some other register and it is the caller's responsibility to compensate.
579 ** For a constraint of the form X=expr, the expression is evaluated in
580 ** straight-line code. For constraints of the form X IN (...)
581 ** this routine sets up a loop that will iterate over all values of X.
583 static int codeEqualityTerm(
584 Parse
*pParse
, /* The parsing context */
585 WhereTerm
*pTerm
, /* The term of the WHERE clause to be coded */
586 WhereLevel
*pLevel
, /* The level of the FROM clause we are working on */
587 int iEq
, /* Index of the equality term within this level */
588 int bRev
, /* True for reverse-order IN operations */
589 int iTarget
/* Attempt to leave results in this register */
591 Expr
*pX
= pTerm
->pExpr
;
592 Vdbe
*v
= pParse
->pVdbe
;
593 int iReg
; /* Register holding results */
595 assert( pLevel
->pWLoop
->aLTerm
[iEq
]==pTerm
);
597 if( pX
->op
==TK_EQ
|| pX
->op
==TK_IS
){
598 iReg
= sqlite3ExprCodeTarget(pParse
, pX
->pRight
, iTarget
);
599 }else if( pX
->op
==TK_ISNULL
){
601 sqlite3VdbeAddOp2(v
, OP_Null
, 0, iReg
);
602 #ifndef SQLITE_OMIT_SUBQUERY
604 int eType
= IN_INDEX_NOOP
;
607 WhereLoop
*pLoop
= pLevel
->pWLoop
;
612 if( (pLoop
->wsFlags
& WHERE_VIRTUALTABLE
)==0
613 && pLoop
->u
.btree
.pIndex
!=0
614 && pLoop
->u
.btree
.pIndex
->aSortOrder
[iEq
]
620 assert( pX
->op
==TK_IN
);
623 for(i
=0; i
<iEq
; i
++){
624 if( pLoop
->aLTerm
[i
] && pLoop
->aLTerm
[i
]->pExpr
==pX
){
625 disableTerm(pLevel
, pTerm
);
629 for(i
=iEq
;i
<pLoop
->nLTerm
; i
++){
630 assert( pLoop
->aLTerm
[i
]!=0 );
631 if( pLoop
->aLTerm
[i
]->pExpr
==pX
) nEq
++;
635 if( !ExprUseXSelect(pX
) || pX
->x
.pSelect
->pEList
->nExpr
==1 ){
636 eType
= sqlite3FindInIndex(pParse
, pX
, IN_INDEX_LOOP
, 0, 0, &iTab
);
638 Expr
*pExpr
= pTerm
->pExpr
;
639 if( pExpr
->iTable
==0 || !ExprHasProperty(pExpr
, EP_Subrtn
) ){
640 sqlite3
*db
= pParse
->db
;
641 pX
= removeUnindexableInClauseTerms(pParse
, iEq
, pLoop
, pX
);
642 if( !db
->mallocFailed
){
643 aiMap
= (int*)sqlite3DbMallocZero(pParse
->db
, sizeof(int)*nEq
);
644 eType
= sqlite3FindInIndex(pParse
, pX
, IN_INDEX_LOOP
, 0, aiMap
,&iTab
);
645 pExpr
->iTable
= iTab
;
647 sqlite3ExprDelete(db
, pX
);
649 int n
= sqlite3ExprVectorSize(pX
->pLeft
);
650 aiMap
= (int*)sqlite3DbMallocZero(pParse
->db
, sizeof(int)*MAX(nEq
,n
));
651 eType
= sqlite3FindInIndex(pParse
, pX
, IN_INDEX_LOOP
, 0, aiMap
, &iTab
);
656 if( eType
==IN_INDEX_INDEX_DESC
){
660 sqlite3VdbeAddOp2(v
, bRev
? OP_Last
: OP_Rewind
, iTab
, 0);
661 VdbeCoverageIf(v
, bRev
);
662 VdbeCoverageIf(v
, !bRev
);
664 assert( (pLoop
->wsFlags
& WHERE_MULTI_OR
)==0 );
665 pLoop
->wsFlags
|= WHERE_IN_ABLE
;
666 if( pLevel
->u
.in
.nIn
==0 ){
667 pLevel
->addrNxt
= sqlite3VdbeMakeLabel(pParse
);
669 if( iEq
>0 && (pLoop
->wsFlags
& WHERE_IN_SEEKSCAN
)==0 ){
670 pLoop
->wsFlags
|= WHERE_IN_EARLYOUT
;
673 i
= pLevel
->u
.in
.nIn
;
674 pLevel
->u
.in
.nIn
+= nEq
;
675 pLevel
->u
.in
.aInLoop
=
676 sqlite3WhereRealloc(pTerm
->pWC
->pWInfo
,
677 pLevel
->u
.in
.aInLoop
,
678 sizeof(pLevel
->u
.in
.aInLoop
[0])*pLevel
->u
.in
.nIn
);
679 pIn
= pLevel
->u
.in
.aInLoop
;
681 int iMap
= 0; /* Index in aiMap[] */
683 for(i
=iEq
;i
<pLoop
->nLTerm
; i
++){
684 if( pLoop
->aLTerm
[i
]->pExpr
==pX
){
685 int iOut
= iReg
+ i
- iEq
;
686 if( eType
==IN_INDEX_ROWID
){
687 pIn
->addrInTop
= sqlite3VdbeAddOp2(v
, OP_Rowid
, iTab
, iOut
);
689 int iCol
= aiMap
? aiMap
[iMap
++] : 0;
690 pIn
->addrInTop
= sqlite3VdbeAddOp3(v
,OP_Column
,iTab
, iCol
, iOut
);
692 sqlite3VdbeAddOp1(v
, OP_IsNull
, iOut
); VdbeCoverage(v
);
695 pIn
->eEndLoopOp
= bRev
? OP_Prev
: OP_Next
;
697 pIn
->iBase
= iReg
- i
;
703 pIn
->eEndLoopOp
= OP_Noop
;
709 && (pLoop
->wsFlags
& WHERE_IN_SEEKSCAN
)==0
710 && (pLoop
->wsFlags
& WHERE_VIRTUALTABLE
)!=0 );
712 && (pLoop
->wsFlags
& (WHERE_IN_SEEKSCAN
|WHERE_VIRTUALTABLE
))==0
714 sqlite3VdbeAddOp3(v
, OP_SeekHit
, pLevel
->iIdxCur
, 0, iEq
);
717 pLevel
->u
.in
.nIn
= 0;
719 sqlite3DbFree(pParse
->db
, aiMap
);
723 /* As an optimization, try to disable the WHERE clause term that is
724 ** driving the index as it will always be true. The correct answer is
725 ** obtained regardless, but we might get the answer with fewer CPU cycles
726 ** by omitting the term.
728 ** But do not disable the term unless we are certain that the term is
729 ** not a transitive constraint. For an example of where that does not
730 ** work, see https://sqlite.org/forum/forumpost/eb8613976a (2021-05-04)
732 if( (pLevel
->pWLoop
->wsFlags
& WHERE_TRANSCONS
)==0
733 || (pTerm
->eOperator
& WO_EQUIV
)==0
735 disableTerm(pLevel
, pTerm
);
742 ** Generate code that will evaluate all == and IN constraints for an
745 ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
746 ** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
747 ** The index has as many as three equality constraints, but in this
748 ** example, the third "c" value is an inequality. So only two
749 ** constraints are coded. This routine will generate code to evaluate
750 ** a==5 and b IN (1,2,3). The current values for a and b will be stored
751 ** in consecutive registers and the index of the first register is returned.
753 ** In the example above nEq==2. But this subroutine works for any value
754 ** of nEq including 0. If nEq==0, this routine is nearly a no-op.
755 ** The only thing it does is allocate the pLevel->iMem memory cell and
756 ** compute the affinity string.
758 ** The nExtraReg parameter is 0 or 1. It is 0 if all WHERE clause constraints
759 ** are == or IN and are covered by the nEq. nExtraReg is 1 if there is
760 ** an inequality constraint (such as the "c>=5 AND c<10" in the example) that
761 ** occurs after the nEq quality constraints.
763 ** This routine allocates a range of nEq+nExtraReg memory cells and returns
764 ** the index of the first memory cell in that range. The code that
765 ** calls this routine will use that memory range to store keys for
766 ** start and termination conditions of the loop.
767 ** key value of the loop. If one or more IN operators appear, then
768 ** this routine allocates an additional nEq memory cells for internal
771 ** Before returning, *pzAff is set to point to a buffer containing a
772 ** copy of the column affinity string of the index allocated using
773 ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
774 ** with equality constraints that use BLOB or NONE affinity are set to
775 ** SQLITE_AFF_BLOB. This is to deal with SQL such as the following:
777 ** CREATE TABLE t1(a TEXT PRIMARY KEY, b);
778 ** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
780 ** In the example above, the index on t1(a) has TEXT affinity. But since
781 ** the right hand side of the equality constraint (t2.b) has BLOB/NONE affinity,
782 ** no conversion should be attempted before using a t2.b value as part of
783 ** a key to search the index. Hence the first byte in the returned affinity
784 ** string in this example would be set to SQLITE_AFF_BLOB.
786 static int codeAllEqualityTerms(
787 Parse
*pParse
, /* Parsing context */
788 WhereLevel
*pLevel
, /* Which nested loop of the FROM we are coding */
789 int bRev
, /* Reverse the order of IN operators */
790 int nExtraReg
, /* Number of extra registers to allocate */
791 char **pzAff
/* OUT: Set to point to affinity string */
793 u16 nEq
; /* The number of == or IN constraints to code */
794 u16 nSkip
; /* Number of left-most columns to skip */
795 Vdbe
*v
= pParse
->pVdbe
; /* The vm under construction */
796 Index
*pIdx
; /* The index being used for this loop */
797 WhereTerm
*pTerm
; /* A single constraint term */
798 WhereLoop
*pLoop
; /* The WhereLoop object */
799 int j
; /* Loop counter */
800 int regBase
; /* Base register */
801 int nReg
; /* Number of registers to allocate */
802 char *zAff
; /* Affinity string to return */
804 /* This module is only called on query plans that use an index. */
805 pLoop
= pLevel
->pWLoop
;
806 assert( (pLoop
->wsFlags
& WHERE_VIRTUALTABLE
)==0 );
807 nEq
= pLoop
->u
.btree
.nEq
;
808 nSkip
= pLoop
->nSkip
;
809 pIdx
= pLoop
->u
.btree
.pIndex
;
812 /* Figure out how many memory cells we will need then allocate them.
814 regBase
= pParse
->nMem
+ 1;
815 nReg
= pLoop
->u
.btree
.nEq
+ nExtraReg
;
816 pParse
->nMem
+= nReg
;
818 zAff
= sqlite3DbStrDup(pParse
->db
,sqlite3IndexAffinityStr(pParse
->db
,pIdx
));
819 assert( zAff
!=0 || pParse
->db
->mallocFailed
);
822 int iIdxCur
= pLevel
->iIdxCur
;
823 sqlite3VdbeAddOp3(v
, OP_Null
, 0, regBase
, regBase
+nSkip
-1);
824 sqlite3VdbeAddOp1(v
, (bRev
?OP_Last
:OP_Rewind
), iIdxCur
);
825 VdbeCoverageIf(v
, bRev
==0);
826 VdbeCoverageIf(v
, bRev
!=0);
827 VdbeComment((v
, "begin skip-scan on %s", pIdx
->zName
));
828 j
= sqlite3VdbeAddOp0(v
, OP_Goto
);
829 assert( pLevel
->addrSkip
==0 );
830 pLevel
->addrSkip
= sqlite3VdbeAddOp4Int(v
, (bRev
?OP_SeekLT
:OP_SeekGT
),
831 iIdxCur
, 0, regBase
, nSkip
);
832 VdbeCoverageIf(v
, bRev
==0);
833 VdbeCoverageIf(v
, bRev
!=0);
834 sqlite3VdbeJumpHere(v
, j
);
835 for(j
=0; j
<nSkip
; j
++){
836 sqlite3VdbeAddOp3(v
, OP_Column
, iIdxCur
, j
, regBase
+j
);
837 testcase( pIdx
->aiColumn
[j
]==XN_EXPR
);
838 VdbeComment((v
, "%s", explainIndexColumnName(pIdx
, j
)));
842 /* Evaluate the equality constraints
844 assert( zAff
==0 || (int)strlen(zAff
)>=nEq
);
845 for(j
=nSkip
; j
<nEq
; j
++){
847 pTerm
= pLoop
->aLTerm
[j
];
849 /* The following testcase is true for indices with redundant columns.
850 ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
851 testcase( (pTerm
->wtFlags
& TERM_CODED
)!=0 );
852 testcase( pTerm
->wtFlags
& TERM_VIRTUAL
);
853 r1
= codeEqualityTerm(pParse
, pTerm
, pLevel
, j
, bRev
, regBase
+j
);
856 sqlite3ReleaseTempReg(pParse
, regBase
);
859 sqlite3VdbeAddOp2(v
, OP_Copy
, r1
, regBase
+j
);
863 for(j
=nSkip
; j
<nEq
; j
++){
864 pTerm
= pLoop
->aLTerm
[j
];
865 if( pTerm
->eOperator
& WO_IN
){
866 if( pTerm
->pExpr
->flags
& EP_xIsSelect
){
867 /* No affinity ever needs to be (or should be) applied to a value
868 ** from the RHS of an "? IN (SELECT ...)" expression. The
869 ** sqlite3FindInIndex() routine has already ensured that the
870 ** affinity of the comparison has been applied to the value. */
871 if( zAff
) zAff
[j
] = SQLITE_AFF_BLOB
;
873 }else if( (pTerm
->eOperator
& WO_ISNULL
)==0 ){
874 Expr
*pRight
= pTerm
->pExpr
->pRight
;
875 if( (pTerm
->wtFlags
& TERM_IS
)==0 && sqlite3ExprCanBeNull(pRight
) ){
876 sqlite3VdbeAddOp2(v
, OP_IsNull
, regBase
+j
, pLevel
->addrBrk
);
879 if( pParse
->nErr
==0 ){
880 assert( pParse
->db
->mallocFailed
==0 );
881 if( sqlite3CompareAffinity(pRight
, zAff
[j
])==SQLITE_AFF_BLOB
){
882 zAff
[j
] = SQLITE_AFF_BLOB
;
884 if( sqlite3ExprNeedsNoAffinityChange(pRight
, zAff
[j
]) ){
885 zAff
[j
] = SQLITE_AFF_BLOB
;
894 #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
896 ** If the most recently coded instruction is a constant range constraint
897 ** (a string literal) that originated from the LIKE optimization, then
898 ** set P3 and P5 on the OP_String opcode so that the string will be cast
899 ** to a BLOB at appropriate times.
901 ** The LIKE optimization trys to evaluate "x LIKE 'abc%'" as a range
902 ** expression: "x>='ABC' AND x<'abd'". But this requires that the range
903 ** scan loop run twice, once for strings and a second time for BLOBs.
904 ** The OP_String opcodes on the second pass convert the upper and lower
905 ** bound string constants to blobs. This routine makes the necessary changes
906 ** to the OP_String opcodes for that to happen.
908 ** Except, of course, if SQLITE_LIKE_DOESNT_MATCH_BLOBS is defined, then
909 ** only the one pass through the string space is required, so this routine
912 static void whereLikeOptimizationStringFixup(
913 Vdbe
*v
, /* prepared statement under construction */
914 WhereLevel
*pLevel
, /* The loop that contains the LIKE operator */
915 WhereTerm
*pTerm
/* The upper or lower bound just coded */
917 if( pTerm
->wtFlags
& TERM_LIKEOPT
){
919 assert( pLevel
->iLikeRepCntr
>0 );
920 pOp
= sqlite3VdbeGetLastOp(v
);
922 assert( pOp
->opcode
==OP_String8
923 || pTerm
->pWC
->pWInfo
->pParse
->db
->mallocFailed
);
924 pOp
->p3
= (int)(pLevel
->iLikeRepCntr
>>1); /* Register holding counter */
925 pOp
->p5
= (u8
)(pLevel
->iLikeRepCntr
&1); /* ASC or DESC */
929 # define whereLikeOptimizationStringFixup(A,B,C)
932 #ifdef SQLITE_ENABLE_CURSOR_HINTS
934 ** Information is passed from codeCursorHint() down to individual nodes of
935 ** the expression tree (by sqlite3WalkExpr()) using an instance of this
939 int iTabCur
; /* Cursor for the main table */
940 int iIdxCur
; /* Cursor for the index, if pIdx!=0. Unused otherwise */
941 Index
*pIdx
; /* The index used to access the table */
945 ** This function is called for every node of an expression that is a candidate
946 ** for a cursor hint on an index cursor. For TK_COLUMN nodes that reference
947 ** the table CCurHint.iTabCur, verify that the same column can be
948 ** accessed through the index. If it cannot, then set pWalker->eCode to 1.
950 static int codeCursorHintCheckExpr(Walker
*pWalker
, Expr
*pExpr
){
951 struct CCurHint
*pHint
= pWalker
->u
.pCCurHint
;
952 assert( pHint
->pIdx
!=0 );
953 if( pExpr
->op
==TK_COLUMN
954 && pExpr
->iTable
==pHint
->iTabCur
955 && sqlite3TableColumnToIndex(pHint
->pIdx
, pExpr
->iColumn
)<0
963 ** Test whether or not expression pExpr, which was part of a WHERE clause,
964 ** should be included in the cursor-hint for a table that is on the rhs
965 ** of a LEFT JOIN. Set Walker.eCode to non-zero before returning if the
966 ** expression is not suitable.
968 ** An expression is unsuitable if it might evaluate to non NULL even if
969 ** a TK_COLUMN node that does affect the value of the expression is set
970 ** to NULL. For example:
975 ** CASE WHEN col THEN 0 ELSE 1 END
977 static int codeCursorHintIsOrFunction(Walker
*pWalker
, Expr
*pExpr
){
979 || pExpr
->op
==TK_ISNULL
|| pExpr
->op
==TK_ISNOT
980 || pExpr
->op
==TK_NOTNULL
|| pExpr
->op
==TK_CASE
983 }else if( pExpr
->op
==TK_FUNCTION
){
986 if( 0==sqlite3IsLikeFunction(pWalker
->pParse
->db
, pExpr
, &d1
, d2
) ){
996 ** This function is called on every node of an expression tree used as an
997 ** argument to the OP_CursorHint instruction. If the node is a TK_COLUMN
998 ** that accesses any table other than the one identified by
999 ** CCurHint.iTabCur, then do the following:
1001 ** 1) allocate a register and code an OP_Column instruction to read
1002 ** the specified column into the new register, and
1004 ** 2) transform the expression node to a TK_REGISTER node that reads
1005 ** from the newly populated register.
1007 ** Also, if the node is a TK_COLUMN that does access the table idenified
1008 ** by pCCurHint.iTabCur, and an index is being used (which we will
1009 ** know because CCurHint.pIdx!=0) then transform the TK_COLUMN into
1010 ** an access of the index rather than the original table.
1012 static int codeCursorHintFixExpr(Walker
*pWalker
, Expr
*pExpr
){
1013 int rc
= WRC_Continue
;
1015 struct CCurHint
*pHint
= pWalker
->u
.pCCurHint
;
1016 if( pExpr
->op
==TK_COLUMN
){
1017 if( pExpr
->iTable
!=pHint
->iTabCur
){
1018 reg
= ++pWalker
->pParse
->nMem
; /* Register for column value */
1019 reg
= sqlite3ExprCodeTarget(pWalker
->pParse
, pExpr
, reg
);
1020 pExpr
->op
= TK_REGISTER
;
1021 pExpr
->iTable
= reg
;
1022 }else if( pHint
->pIdx
!=0 ){
1023 pExpr
->iTable
= pHint
->iIdxCur
;
1024 pExpr
->iColumn
= sqlite3TableColumnToIndex(pHint
->pIdx
, pExpr
->iColumn
);
1025 assert( pExpr
->iColumn
>=0 );
1027 }else if( pExpr
->pAggInfo
){
1029 reg
= ++pWalker
->pParse
->nMem
; /* Register for column value */
1030 reg
= sqlite3ExprCodeTarget(pWalker
->pParse
, pExpr
, reg
);
1031 pExpr
->op
= TK_REGISTER
;
1032 pExpr
->iTable
= reg
;
1033 }else if( pExpr
->op
==TK_TRUEFALSE
){
1034 /* Do not walk disabled expressions. tag-20230504-1 */
1041 ** Insert an OP_CursorHint instruction if it is appropriate to do so.
1043 static void codeCursorHint(
1044 SrcItem
*pTabItem
, /* FROM clause item */
1045 WhereInfo
*pWInfo
, /* The where clause */
1046 WhereLevel
*pLevel
, /* Which loop to provide hints for */
1047 WhereTerm
*pEndRange
/* Hint this end-of-scan boundary term if not NULL */
1049 Parse
*pParse
= pWInfo
->pParse
;
1050 sqlite3
*db
= pParse
->db
;
1051 Vdbe
*v
= pParse
->pVdbe
;
1053 WhereLoop
*pLoop
= pLevel
->pWLoop
;
1058 struct CCurHint sHint
;
1061 if( OptimizationDisabled(db
, SQLITE_CursorHints
) ) return;
1062 iCur
= pLevel
->iTabCur
;
1063 assert( iCur
==pWInfo
->pTabList
->a
[pLevel
->iFrom
].iCursor
);
1064 sHint
.iTabCur
= iCur
;
1065 sHint
.iIdxCur
= pLevel
->iIdxCur
;
1066 sHint
.pIdx
= pLoop
->u
.btree
.pIndex
;
1067 memset(&sWalker
, 0, sizeof(sWalker
));
1068 sWalker
.pParse
= pParse
;
1069 sWalker
.u
.pCCurHint
= &sHint
;
1071 for(i
=0; i
<pWC
->nBase
; i
++){
1073 if( pTerm
->wtFlags
& (TERM_VIRTUAL
|TERM_CODED
) ) continue;
1074 if( pTerm
->prereqAll
& pLevel
->notReady
) continue;
1076 /* Any terms specified as part of the ON(...) clause for any LEFT
1077 ** JOIN for which the current table is not the rhs are omitted
1078 ** from the cursor-hint.
1080 ** If this table is the rhs of a LEFT JOIN, "IS" or "IS NULL" terms
1081 ** that were specified as part of the WHERE clause must be excluded.
1082 ** This is to address the following:
1084 ** SELECT ... t1 LEFT JOIN t2 ON (t1.a=t2.b) WHERE t2.c IS NULL;
1086 ** Say there is a single row in t2 that matches (t1.a=t2.b), but its
1087 ** t2.c values is not NULL. If the (t2.c IS NULL) constraint is
1088 ** pushed down to the cursor, this row is filtered out, causing
1089 ** SQLite to synthesize a row of NULL values. Which does match the
1090 ** WHERE clause, and so the query returns a row. Which is incorrect.
1092 ** For the same reason, WHERE terms such as:
1094 ** WHERE 1 = (t2.c IS NULL)
1096 ** are also excluded. See codeCursorHintIsOrFunction() for details.
1098 if( pTabItem
->fg
.jointype
& JT_LEFT
){
1099 Expr
*pExpr
= pTerm
->pExpr
;
1100 if( !ExprHasProperty(pExpr
, EP_OuterON
)
1101 || pExpr
->w
.iJoin
!=pTabItem
->iCursor
1104 sWalker
.xExprCallback
= codeCursorHintIsOrFunction
;
1105 sqlite3WalkExpr(&sWalker
, pTerm
->pExpr
);
1106 if( sWalker
.eCode
) continue;
1109 if( ExprHasProperty(pTerm
->pExpr
, EP_OuterON
) ) continue;
1112 /* All terms in pWLoop->aLTerm[] except pEndRange are used to initialize
1113 ** the cursor. These terms are not needed as hints for a pure range
1114 ** scan (that has no == terms) so omit them. */
1115 if( pLoop
->u
.btree
.nEq
==0 && pTerm
!=pEndRange
){
1116 for(j
=0; j
<pLoop
->nLTerm
&& pLoop
->aLTerm
[j
]!=pTerm
; j
++){}
1117 if( j
<pLoop
->nLTerm
) continue;
1120 /* No subqueries or non-deterministic functions allowed */
1121 if( sqlite3ExprContainsSubquery(pTerm
->pExpr
) ) continue;
1123 /* For an index scan, make sure referenced columns are actually in
1125 if( sHint
.pIdx
!=0 ){
1127 sWalker
.xExprCallback
= codeCursorHintCheckExpr
;
1128 sqlite3WalkExpr(&sWalker
, pTerm
->pExpr
);
1129 if( sWalker
.eCode
) continue;
1132 /* If we survive all prior tests, that means this term is worth hinting */
1133 pExpr
= sqlite3ExprAnd(pParse
, pExpr
, sqlite3ExprDup(db
, pTerm
->pExpr
, 0));
1136 sWalker
.xExprCallback
= codeCursorHintFixExpr
;
1137 if( pParse
->nErr
==0 ) sqlite3WalkExpr(&sWalker
, pExpr
);
1138 sqlite3VdbeAddOp4(v
, OP_CursorHint
,
1139 (sHint
.pIdx
? sHint
.iIdxCur
: sHint
.iTabCur
), 0, 0,
1140 (const char*)pExpr
, P4_EXPR
);
1144 # define codeCursorHint(A,B,C,D) /* No-op */
1145 #endif /* SQLITE_ENABLE_CURSOR_HINTS */
1148 ** Cursor iCur is open on an intkey b-tree (a table). Register iRowid contains
1149 ** a rowid value just read from cursor iIdxCur, open on index pIdx. This
1150 ** function generates code to do a deferred seek of cursor iCur to the
1151 ** rowid stored in register iRowid.
1153 ** Normally, this is just:
1155 ** OP_DeferredSeek $iCur $iRowid
1157 ** Which causes a seek on $iCur to the row with rowid $iRowid.
1159 ** However, if the scan currently being coded is a branch of an OR-loop and
1160 ** the statement currently being coded is a SELECT, then additional information
1161 ** is added that might allow OP_Column to omit the seek and instead do its
1162 ** lookup on the index, thus avoiding an expensive seek operation. To
1163 ** enable this optimization, the P3 of OP_DeferredSeek is set to iIdxCur
1164 ** and P4 is set to an array of integers containing one entry for each column
1165 ** in the table. For each table column, if the column is the i'th
1166 ** column of the index, then the corresponding array entry is set to (i+1).
1167 ** If the column does not appear in the index at all, the array entry is set
1168 ** to 0. The OP_Column opcode can check this array to see if the column it
1169 ** wants is in the index and if it is, it will substitute the index cursor
1170 ** and column number and continue with those new values, rather than seeking
1171 ** the table cursor.
1173 static void codeDeferredSeek(
1174 WhereInfo
*pWInfo
, /* Where clause context */
1175 Index
*pIdx
, /* Index scan is using */
1176 int iCur
, /* Cursor for IPK b-tree */
1177 int iIdxCur
/* Index cursor */
1179 Parse
*pParse
= pWInfo
->pParse
; /* Parse context */
1180 Vdbe
*v
= pParse
->pVdbe
; /* Vdbe to generate code within */
1182 assert( iIdxCur
>0 );
1183 assert( pIdx
->aiColumn
[pIdx
->nColumn
-1]==-1 );
1185 pWInfo
->bDeferredSeek
= 1;
1186 sqlite3VdbeAddOp3(v
, OP_DeferredSeek
, iIdxCur
, 0, iCur
);
1187 if( (pWInfo
->wctrlFlags
& (WHERE_OR_SUBCLAUSE
|WHERE_RIGHT_JOIN
))
1188 && DbMaskAllZero(sqlite3ParseToplevel(pParse
)->writeMask
)
1191 Table
*pTab
= pIdx
->pTable
;
1192 u32
*ai
= (u32
*)sqlite3DbMallocZero(pParse
->db
, sizeof(u32
)*(pTab
->nCol
+1));
1195 for(i
=0; i
<pIdx
->nColumn
-1; i
++){
1197 assert( pIdx
->aiColumn
[i
]<pTab
->nCol
);
1198 x1
= pIdx
->aiColumn
[i
];
1199 x2
= sqlite3TableColumnToStorage(pTab
, x1
);
1201 if( x1
>=0 ) ai
[x2
+1] = i
+1;
1203 sqlite3VdbeChangeP4(v
, -1, (char*)ai
, P4_INTARRAY
);
1209 ** If the expression passed as the second argument is a vector, generate
1210 ** code to write the first nReg elements of the vector into an array
1211 ** of registers starting with iReg.
1213 ** If the expression is not a vector, then nReg must be passed 1. In
1214 ** this case, generate code to evaluate the expression and leave the
1215 ** result in register iReg.
1217 static void codeExprOrVector(Parse
*pParse
, Expr
*p
, int iReg
, int nReg
){
1219 if( p
&& sqlite3ExprIsVector(p
) ){
1220 #ifndef SQLITE_OMIT_SUBQUERY
1221 if( ExprUseXSelect(p
) ){
1222 Vdbe
*v
= pParse
->pVdbe
;
1224 assert( p
->op
==TK_SELECT
);
1225 iSelect
= sqlite3CodeSubselect(pParse
, p
);
1226 sqlite3VdbeAddOp3(v
, OP_Copy
, iSelect
, iReg
, nReg
-1);
1231 const ExprList
*pList
;
1232 assert( ExprUseXList(p
) );
1234 assert( nReg
<=pList
->nExpr
);
1235 for(i
=0; i
<nReg
; i
++){
1236 sqlite3ExprCode(pParse
, pList
->a
[i
].pExpr
, iReg
+i
);
1240 assert( nReg
==1 || pParse
->nErr
);
1241 sqlite3ExprCode(pParse
, p
, iReg
);
1246 ** The pTruth expression is always true because it is the WHERE clause
1247 ** a partial index that is driving a query loop. Look through all of the
1248 ** WHERE clause terms on the query, and if any of those terms must be
1249 ** true because pTruth is true, then mark those WHERE clause terms as
1252 static void whereApplyPartialIndexConstraints(
1259 while( pTruth
->op
==TK_AND
){
1260 whereApplyPartialIndexConstraints(pTruth
->pLeft
, iTabCur
, pWC
);
1261 pTruth
= pTruth
->pRight
;
1263 for(i
=0, pTerm
=pWC
->a
; i
<pWC
->nTerm
; i
++, pTerm
++){
1265 if( pTerm
->wtFlags
& TERM_CODED
) continue;
1266 pExpr
= pTerm
->pExpr
;
1267 if( sqlite3ExprCompare(0, pExpr
, pTruth
, iTabCur
)==0 ){
1268 pTerm
->wtFlags
|= TERM_CODED
;
1274 ** This routine is called right after An OP_Filter has been generated and
1275 ** before the corresponding index search has been performed. This routine
1276 ** checks to see if there are additional Bloom filters in inner loops that
1277 ** can be checked prior to doing the index lookup. If there are available
1278 ** inner-loop Bloom filters, then evaluate those filters now, before the
1279 ** index lookup. The idea is that a Bloom filter check is way faster than
1280 ** an index lookup, and the Bloom filter might return false, meaning that
1281 ** the index lookup can be skipped.
1283 ** We know that an inner loop uses a Bloom filter because it has the
1284 ** WhereLevel.regFilter set. If an inner-loop Bloom filter is checked,
1285 ** then clear the WhereLevel.regFilter value to prevent the Bloom filter
1286 ** from being checked a second time when the inner loop is evaluated.
1288 static SQLITE_NOINLINE
void filterPullDown(
1289 Parse
*pParse
, /* Parsing context */
1290 WhereInfo
*pWInfo
, /* Complete information about the WHERE clause */
1291 int iLevel
, /* Which level of pWInfo->a[] should be coded */
1292 int addrNxt
, /* Jump here to bypass inner loops */
1293 Bitmask notReady
/* Loops that are not ready */
1295 while( ++iLevel
< pWInfo
->nLevel
){
1296 WhereLevel
*pLevel
= &pWInfo
->a
[iLevel
];
1297 WhereLoop
*pLoop
= pLevel
->pWLoop
;
1298 if( pLevel
->regFilter
==0 ) continue;
1299 if( pLevel
->pWLoop
->nSkip
) continue;
1300 /* ,--- Because sqlite3ConstructBloomFilter() has will not have set
1301 ** vvvvv--' pLevel->regFilter if this were true. */
1302 if( NEVER(pLoop
->prereq
& notReady
) ) continue;
1303 assert( pLevel
->addrBrk
==0 );
1304 pLevel
->addrBrk
= addrNxt
;
1305 if( pLoop
->wsFlags
& WHERE_IPK
){
1306 WhereTerm
*pTerm
= pLoop
->aLTerm
[0];
1309 assert( pTerm
->pExpr
!=0 );
1310 testcase( pTerm
->wtFlags
& TERM_VIRTUAL
);
1311 regRowid
= sqlite3GetTempReg(pParse
);
1312 regRowid
= codeEqualityTerm(pParse
, pTerm
, pLevel
, 0, 0, regRowid
);
1313 sqlite3VdbeAddOp2(pParse
->pVdbe
, OP_MustBeInt
, regRowid
, addrNxt
);
1314 VdbeCoverage(pParse
->pVdbe
);
1315 sqlite3VdbeAddOp4Int(pParse
->pVdbe
, OP_Filter
, pLevel
->regFilter
,
1316 addrNxt
, regRowid
, 1);
1317 VdbeCoverage(pParse
->pVdbe
);
1319 u16 nEq
= pLoop
->u
.btree
.nEq
;
1323 assert( pLoop
->wsFlags
& WHERE_INDEXED
);
1324 assert( (pLoop
->wsFlags
& WHERE_COLUMN_IN
)==0 );
1325 r1
= codeAllEqualityTerms(pParse
,pLevel
,0,0,&zStartAff
);
1326 codeApplyAffinity(pParse
, r1
, nEq
, zStartAff
);
1327 sqlite3DbFree(pParse
->db
, zStartAff
);
1328 sqlite3VdbeAddOp4Int(pParse
->pVdbe
, OP_Filter
, pLevel
->regFilter
,
1330 VdbeCoverage(pParse
->pVdbe
);
1332 pLevel
->regFilter
= 0;
1333 pLevel
->addrBrk
= 0;
1338 ** Generate code for the start of the iLevel-th loop in the WHERE clause
1339 ** implementation described by pWInfo.
1341 Bitmask
sqlite3WhereCodeOneLoopStart(
1342 Parse
*pParse
, /* Parsing context */
1343 Vdbe
*v
, /* Prepared statement under construction */
1344 WhereInfo
*pWInfo
, /* Complete information about the WHERE clause */
1345 int iLevel
, /* Which level of pWInfo->a[] should be coded */
1346 WhereLevel
*pLevel
, /* The current level pointer */
1347 Bitmask notReady
/* Which tables are currently available */
1349 int j
, k
; /* Loop counters */
1350 int iCur
; /* The VDBE cursor for the table */
1351 int addrNxt
; /* Where to jump to continue with the next IN case */
1352 int bRev
; /* True if we need to scan in reverse order */
1353 WhereLoop
*pLoop
; /* The WhereLoop object being coded */
1354 WhereClause
*pWC
; /* Decomposition of the entire WHERE clause */
1355 WhereTerm
*pTerm
; /* A WHERE clause term */
1356 sqlite3
*db
; /* Database connection */
1357 SrcItem
*pTabItem
; /* FROM clause term being coded */
1358 int addrBrk
; /* Jump here to break out of the loop */
1359 int addrHalt
; /* addrBrk for the outermost loop */
1360 int addrCont
; /* Jump here to continue with next cycle */
1361 int iRowidReg
= 0; /* Rowid is stored in this register, if not zero */
1362 int iReleaseReg
= 0; /* Temp register to free before returning */
1363 Index
*pIdx
= 0; /* Index used by loop (if any) */
1364 int iLoop
; /* Iteration of constraint generator loop */
1368 pLoop
= pLevel
->pWLoop
;
1369 pTabItem
= &pWInfo
->pTabList
->a
[pLevel
->iFrom
];
1370 iCur
= pTabItem
->iCursor
;
1371 pLevel
->notReady
= notReady
& ~sqlite3WhereGetMask(&pWInfo
->sMaskSet
, iCur
);
1372 bRev
= (pWInfo
->revMask
>>iLevel
)&1;
1373 VdbeModuleComment((v
, "Begin WHERE-loop%d: %s",iLevel
,pTabItem
->pTab
->zName
));
1374 #if WHERETRACE_ENABLED /* 0x4001 */
1375 if( sqlite3WhereTrace
& 0x1 ){
1376 sqlite3DebugPrintf("Coding level %d of %d: notReady=%llx iFrom=%d\n",
1377 iLevel
, pWInfo
->nLevel
, (u64
)notReady
, pLevel
->iFrom
);
1378 if( sqlite3WhereTrace
& 0x1000 ){
1379 sqlite3WhereLoopPrint(pLoop
, pWC
);
1382 if( (sqlite3WhereTrace
& 0x4001)==0x4001 ){
1384 sqlite3DebugPrintf("WHERE clause being coded:\n");
1385 sqlite3TreeViewExpr(0, pWInfo
->pWhere
, 0);
1387 sqlite3DebugPrintf("All WHERE-clause terms before coding:\n");
1388 sqlite3WhereClausePrint(pWC
);
1392 /* Create labels for the "break" and "continue" instructions
1393 ** for the current loop. Jump to addrBrk to break out of a loop.
1394 ** Jump to cont to go immediately to the next iteration of the
1397 ** When there is an IN operator, we also have a "addrNxt" label that
1398 ** means to continue with the next IN value combination. When
1399 ** there are no IN operators in the constraints, the "addrNxt" label
1400 ** is the same as "addrBrk".
1402 addrBrk
= pLevel
->addrBrk
= pLevel
->addrNxt
= sqlite3VdbeMakeLabel(pParse
);
1403 addrCont
= pLevel
->addrCont
= sqlite3VdbeMakeLabel(pParse
);
1405 /* If this is the right table of a LEFT OUTER JOIN, allocate and
1406 ** initialize a memory cell that records if this table matches any
1407 ** row of the left table of the join.
1409 assert( (pWInfo
->wctrlFlags
& (WHERE_OR_SUBCLAUSE
|WHERE_RIGHT_JOIN
))
1410 || pLevel
->iFrom
>0 || (pTabItem
[0].fg
.jointype
& JT_LEFT
)==0
1412 if( pLevel
->iFrom
>0 && (pTabItem
[0].fg
.jointype
& JT_LEFT
)!=0 ){
1413 pLevel
->iLeftJoin
= ++pParse
->nMem
;
1414 sqlite3VdbeAddOp2(v
, OP_Integer
, 0, pLevel
->iLeftJoin
);
1415 VdbeComment((v
, "init LEFT JOIN no-match flag"));
1418 /* Compute a safe address to jump to if we discover that the table for
1419 ** this loop is empty and can never contribute content. */
1420 for(j
=iLevel
; j
>0; j
--){
1421 if( pWInfo
->a
[j
].iLeftJoin
) break;
1422 if( pWInfo
->a
[j
].pRJ
) break;
1424 addrHalt
= pWInfo
->a
[j
].addrBrk
;
1426 /* Special case of a FROM clause subquery implemented as a co-routine */
1427 if( pTabItem
->fg
.viaCoroutine
){
1428 int regYield
= pTabItem
->regReturn
;
1429 sqlite3VdbeAddOp3(v
, OP_InitCoroutine
, regYield
, 0, pTabItem
->addrFillSub
);
1430 pLevel
->p2
= sqlite3VdbeAddOp2(v
, OP_Yield
, regYield
, addrBrk
);
1432 VdbeComment((v
, "next row of %s", pTabItem
->pTab
->zName
));
1433 pLevel
->op
= OP_Goto
;
1436 #ifndef SQLITE_OMIT_VIRTUALTABLE
1437 if( (pLoop
->wsFlags
& WHERE_VIRTUALTABLE
)!=0 ){
1438 /* Case 1: The table is a virtual-table. Use the VFilter and VNext
1439 ** to access the data.
1441 int iReg
; /* P3 Value for OP_VFilter */
1443 int nConstraint
= pLoop
->nLTerm
;
1445 iReg
= sqlite3GetTempRange(pParse
, nConstraint
+2);
1446 addrNotFound
= pLevel
->addrBrk
;
1447 for(j
=0; j
<nConstraint
; j
++){
1448 int iTarget
= iReg
+j
+2;
1449 pTerm
= pLoop
->aLTerm
[j
];
1450 if( NEVER(pTerm
==0) ) continue;
1451 if( pTerm
->eOperator
& WO_IN
){
1452 if( SMASKBIT32(j
) & pLoop
->u
.vtab
.mHandleIn
){
1453 int iTab
= pParse
->nTab
++;
1454 int iCache
= ++pParse
->nMem
;
1455 sqlite3CodeRhsOfIN(pParse
, pTerm
->pExpr
, iTab
);
1456 sqlite3VdbeAddOp3(v
, OP_VInitIn
, iTab
, iTarget
, iCache
);
1458 codeEqualityTerm(pParse
, pTerm
, pLevel
, j
, bRev
, iTarget
);
1459 addrNotFound
= pLevel
->addrNxt
;
1462 Expr
*pRight
= pTerm
->pExpr
->pRight
;
1463 codeExprOrVector(pParse
, pRight
, iTarget
, 1);
1464 if( pTerm
->eMatchOp
==SQLITE_INDEX_CONSTRAINT_OFFSET
1465 && pLoop
->u
.vtab
.bOmitOffset
1467 assert( pTerm
->eOperator
==WO_AUX
);
1468 assert( pWInfo
->pSelect
!=0 );
1469 assert( pWInfo
->pSelect
->iOffset
>0 );
1470 sqlite3VdbeAddOp2(v
, OP_Integer
, 0, pWInfo
->pSelect
->iOffset
);
1471 VdbeComment((v
,"Zero OFFSET counter"));
1475 sqlite3VdbeAddOp2(v
, OP_Integer
, pLoop
->u
.vtab
.idxNum
, iReg
);
1476 sqlite3VdbeAddOp2(v
, OP_Integer
, nConstraint
, iReg
+1);
1477 sqlite3VdbeAddOp4(v
, OP_VFilter
, iCur
, addrNotFound
, iReg
,
1478 pLoop
->u
.vtab
.idxStr
,
1479 pLoop
->u
.vtab
.needFree
? P4_DYNAMIC
: P4_STATIC
);
1481 pLoop
->u
.vtab
.needFree
= 0;
1482 /* An OOM inside of AddOp4(OP_VFilter) instruction above might have freed
1483 ** the u.vtab.idxStr. NULL it out to prevent a use-after-free */
1484 if( db
->mallocFailed
) pLoop
->u
.vtab
.idxStr
= 0;
1486 pLevel
->op
= pWInfo
->eOnePass
? OP_Noop
: OP_VNext
;
1487 pLevel
->p2
= sqlite3VdbeCurrentAddr(v
);
1488 assert( (pLoop
->wsFlags
& WHERE_MULTI_OR
)==0 );
1490 for(j
=0; j
<nConstraint
; j
++){
1491 pTerm
= pLoop
->aLTerm
[j
];
1492 if( j
<16 && (pLoop
->u
.vtab
.omitMask
>>j
)&1 ){
1493 disableTerm(pLevel
, pTerm
);
1496 if( (pTerm
->eOperator
& WO_IN
)!=0
1497 && (SMASKBIT32(j
) & pLoop
->u
.vtab
.mHandleIn
)==0
1498 && !db
->mallocFailed
1500 Expr
*pCompare
; /* The comparison operator */
1501 Expr
*pRight
; /* RHS of the comparison */
1502 VdbeOp
*pOp
; /* Opcode to access the value of the IN constraint */
1503 int iIn
; /* IN loop corresponding to the j-th constraint */
1505 /* Reload the constraint value into reg[iReg+j+2]. The same value
1506 ** was loaded into the same register prior to the OP_VFilter, but
1507 ** the xFilter implementation might have changed the datatype or
1508 ** encoding of the value in the register, so it *must* be reloaded.
1510 for(iIn
=0; ALWAYS(iIn
<pLevel
->u
.in
.nIn
); iIn
++){
1511 pOp
= sqlite3VdbeGetOp(v
, pLevel
->u
.in
.aInLoop
[iIn
].addrInTop
);
1512 if( (pOp
->opcode
==OP_Column
&& pOp
->p3
==iReg
+j
+2)
1513 || (pOp
->opcode
==OP_Rowid
&& pOp
->p2
==iReg
+j
+2)
1515 testcase( pOp
->opcode
==OP_Rowid
);
1516 sqlite3VdbeAddOp3(v
, pOp
->opcode
, pOp
->p1
, pOp
->p2
, pOp
->p3
);
1521 /* Generate code that will continue to the next row if
1522 ** the IN constraint is not satisfied
1524 pCompare
= sqlite3PExpr(pParse
, TK_EQ
, 0, 0);
1525 if( !db
->mallocFailed
){
1526 int iFld
= pTerm
->u
.x
.iField
;
1527 Expr
*pLeft
= pTerm
->pExpr
->pLeft
;
1530 assert( pLeft
->op
==TK_VECTOR
);
1531 assert( ExprUseXList(pLeft
) );
1532 assert( iFld
<=pLeft
->x
.pList
->nExpr
);
1533 pCompare
->pLeft
= pLeft
->x
.pList
->a
[iFld
-1].pExpr
;
1535 pCompare
->pLeft
= pLeft
;
1537 pCompare
->pRight
= pRight
= sqlite3Expr(db
, TK_REGISTER
, 0);
1539 pRight
->iTable
= iReg
+j
+2;
1541 pParse
, pCompare
, pLevel
->addrCont
, SQLITE_JUMPIFNULL
1544 pCompare
->pLeft
= 0;
1546 sqlite3ExprDelete(db
, pCompare
);
1550 /* These registers need to be preserved in case there is an IN operator
1551 ** loop. So we could deallocate the registers here (and potentially
1552 ** reuse them later) if (pLoop->wsFlags & WHERE_IN_ABLE)==0. But it seems
1553 ** simpler and safer to simply not reuse the registers.
1555 ** sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
1558 #endif /* SQLITE_OMIT_VIRTUALTABLE */
1560 if( (pLoop
->wsFlags
& WHERE_IPK
)!=0
1561 && (pLoop
->wsFlags
& (WHERE_COLUMN_IN
|WHERE_COLUMN_EQ
))!=0
1563 /* Case 2: We can directly reference a single row using an
1564 ** equality comparison against the ROWID field. Or
1565 ** we reference multiple rows using a "rowid IN (...)"
1568 assert( pLoop
->u
.btree
.nEq
==1 );
1569 pTerm
= pLoop
->aLTerm
[0];
1571 assert( pTerm
->pExpr
!=0 );
1572 testcase( pTerm
->wtFlags
& TERM_VIRTUAL
);
1573 iReleaseReg
= ++pParse
->nMem
;
1574 iRowidReg
= codeEqualityTerm(pParse
, pTerm
, pLevel
, 0, bRev
, iReleaseReg
);
1575 if( iRowidReg
!=iReleaseReg
) sqlite3ReleaseTempReg(pParse
, iReleaseReg
);
1576 addrNxt
= pLevel
->addrNxt
;
1577 if( pLevel
->regFilter
){
1578 sqlite3VdbeAddOp2(v
, OP_MustBeInt
, iRowidReg
, addrNxt
);
1580 sqlite3VdbeAddOp4Int(v
, OP_Filter
, pLevel
->regFilter
, addrNxt
,
1583 filterPullDown(pParse
, pWInfo
, iLevel
, addrNxt
, notReady
);
1585 sqlite3VdbeAddOp3(v
, OP_SeekRowid
, iCur
, addrNxt
, iRowidReg
);
1587 pLevel
->op
= OP_Noop
;
1588 }else if( (pLoop
->wsFlags
& WHERE_IPK
)!=0
1589 && (pLoop
->wsFlags
& WHERE_COLUMN_RANGE
)!=0
1591 /* Case 3: We have an inequality comparison against the ROWID field.
1593 int testOp
= OP_Noop
;
1595 int memEndValue
= 0;
1596 WhereTerm
*pStart
, *pEnd
;
1600 if( pLoop
->wsFlags
& WHERE_BTM_LIMIT
) pStart
= pLoop
->aLTerm
[j
++];
1601 if( pLoop
->wsFlags
& WHERE_TOP_LIMIT
) pEnd
= pLoop
->aLTerm
[j
++];
1602 assert( pStart
!=0 || pEnd
!=0 );
1608 codeCursorHint(pTabItem
, pWInfo
, pLevel
, pEnd
);
1610 Expr
*pX
; /* The expression that defines the start bound */
1611 int r1
, rTemp
; /* Registers for holding the start boundary */
1612 int op
; /* Cursor seek operation */
1614 /* The following constant maps TK_xx codes into corresponding
1615 ** seek opcodes. It depends on a particular ordering of TK_xx
1617 const u8 aMoveOp
[] = {
1618 /* TK_GT */ OP_SeekGT
,
1619 /* TK_LE */ OP_SeekLE
,
1620 /* TK_LT */ OP_SeekLT
,
1621 /* TK_GE */ OP_SeekGE
1623 assert( TK_LE
==TK_GT
+1 ); /* Make sure the ordering.. */
1624 assert( TK_LT
==TK_GT
+2 ); /* ... of the TK_xx values... */
1625 assert( TK_GE
==TK_GT
+3 ); /* ... is correcct. */
1627 assert( (pStart
->wtFlags
& TERM_VNULL
)==0 );
1628 testcase( pStart
->wtFlags
& TERM_VIRTUAL
);
1631 testcase( pStart
->leftCursor
!=iCur
); /* transitive constraints */
1632 if( sqlite3ExprIsVector(pX
->pRight
) ){
1633 r1
= rTemp
= sqlite3GetTempReg(pParse
);
1634 codeExprOrVector(pParse
, pX
->pRight
, r1
, 1);
1635 testcase( pX
->op
==TK_GT
);
1636 testcase( pX
->op
==TK_GE
);
1637 testcase( pX
->op
==TK_LT
);
1638 testcase( pX
->op
==TK_LE
);
1639 op
= aMoveOp
[((pX
->op
- TK_GT
- 1) & 0x3) | 0x1];
1640 assert( pX
->op
!=TK_GT
|| op
==OP_SeekGE
);
1641 assert( pX
->op
!=TK_GE
|| op
==OP_SeekGE
);
1642 assert( pX
->op
!=TK_LT
|| op
==OP_SeekLE
);
1643 assert( pX
->op
!=TK_LE
|| op
==OP_SeekLE
);
1645 r1
= sqlite3ExprCodeTemp(pParse
, pX
->pRight
, &rTemp
);
1646 disableTerm(pLevel
, pStart
);
1647 op
= aMoveOp
[(pX
->op
- TK_GT
)];
1649 sqlite3VdbeAddOp3(v
, op
, iCur
, addrBrk
, r1
);
1650 VdbeComment((v
, "pk"));
1651 VdbeCoverageIf(v
, pX
->op
==TK_GT
);
1652 VdbeCoverageIf(v
, pX
->op
==TK_LE
);
1653 VdbeCoverageIf(v
, pX
->op
==TK_LT
);
1654 VdbeCoverageIf(v
, pX
->op
==TK_GE
);
1655 sqlite3ReleaseTempReg(pParse
, rTemp
);
1657 sqlite3VdbeAddOp2(v
, bRev
? OP_Last
: OP_Rewind
, iCur
, addrHalt
);
1658 VdbeCoverageIf(v
, bRev
==0);
1659 VdbeCoverageIf(v
, bRev
!=0);
1665 assert( (pEnd
->wtFlags
& TERM_VNULL
)==0 );
1666 testcase( pEnd
->leftCursor
!=iCur
); /* Transitive constraints */
1667 testcase( pEnd
->wtFlags
& TERM_VIRTUAL
);
1668 memEndValue
= ++pParse
->nMem
;
1669 codeExprOrVector(pParse
, pX
->pRight
, memEndValue
, 1);
1670 if( 0==sqlite3ExprIsVector(pX
->pRight
)
1671 && (pX
->op
==TK_LT
|| pX
->op
==TK_GT
)
1673 testOp
= bRev
? OP_Le
: OP_Ge
;
1675 testOp
= bRev
? OP_Lt
: OP_Gt
;
1677 if( 0==sqlite3ExprIsVector(pX
->pRight
) ){
1678 disableTerm(pLevel
, pEnd
);
1681 start
= sqlite3VdbeCurrentAddr(v
);
1682 pLevel
->op
= bRev
? OP_Prev
: OP_Next
;
1685 assert( pLevel
->p5
==0 );
1686 if( testOp
!=OP_Noop
){
1687 iRowidReg
= ++pParse
->nMem
;
1688 sqlite3VdbeAddOp2(v
, OP_Rowid
, iCur
, iRowidReg
);
1689 sqlite3VdbeAddOp3(v
, testOp
, memEndValue
, addrBrk
, iRowidReg
);
1690 VdbeCoverageIf(v
, testOp
==OP_Le
);
1691 VdbeCoverageIf(v
, testOp
==OP_Lt
);
1692 VdbeCoverageIf(v
, testOp
==OP_Ge
);
1693 VdbeCoverageIf(v
, testOp
==OP_Gt
);
1694 sqlite3VdbeChangeP5(v
, SQLITE_AFF_NUMERIC
| SQLITE_JUMPIFNULL
);
1696 }else if( pLoop
->wsFlags
& WHERE_INDEXED
){
1697 /* Case 4: A scan using an index.
1699 ** The WHERE clause may contain zero or more equality
1700 ** terms ("==" or "IN" operators) that refer to the N
1701 ** left-most columns of the index. It may also contain
1702 ** inequality constraints (>, <, >= or <=) on the indexed
1703 ** column that immediately follows the N equalities. Only
1704 ** the right-most column can be an inequality - the rest must
1705 ** use the "==" and "IN" operators. For example, if the
1706 ** index is on (x,y,z), then the following clauses are all
1712 ** x=5 AND y>5 AND y<10
1713 ** x=5 AND y=5 AND z<=10
1715 ** The z<10 term of the following cannot be used, only
1720 ** N may be zero if there are inequality constraints.
1721 ** If there are no inequality constraints, then N is at
1724 ** This case is also used when there are no WHERE clause
1725 ** constraints but an index is selected anyway, in order
1726 ** to force the output order to conform to an ORDER BY.
1728 static const u8 aStartOp
[] = {
1731 OP_Rewind
, /* 2: (!start_constraints && startEq && !bRev) */
1732 OP_Last
, /* 3: (!start_constraints && startEq && bRev) */
1733 OP_SeekGT
, /* 4: (start_constraints && !startEq && !bRev) */
1734 OP_SeekLT
, /* 5: (start_constraints && !startEq && bRev) */
1735 OP_SeekGE
, /* 6: (start_constraints && startEq && !bRev) */
1736 OP_SeekLE
/* 7: (start_constraints && startEq && bRev) */
1738 static const u8 aEndOp
[] = {
1739 OP_IdxGE
, /* 0: (end_constraints && !bRev && !endEq) */
1740 OP_IdxGT
, /* 1: (end_constraints && !bRev && endEq) */
1741 OP_IdxLE
, /* 2: (end_constraints && bRev && !endEq) */
1742 OP_IdxLT
, /* 3: (end_constraints && bRev && endEq) */
1744 u16 nEq
= pLoop
->u
.btree
.nEq
; /* Number of == or IN terms */
1745 u16 nBtm
= pLoop
->u
.btree
.nBtm
; /* Length of BTM vector */
1746 u16 nTop
= pLoop
->u
.btree
.nTop
; /* Length of TOP vector */
1747 int regBase
; /* Base register holding constraint values */
1748 WhereTerm
*pRangeStart
= 0; /* Inequality constraint at range start */
1749 WhereTerm
*pRangeEnd
= 0; /* Inequality constraint at range end */
1750 int startEq
; /* True if range start uses ==, >= or <= */
1751 int endEq
; /* True if range end uses ==, >= or <= */
1752 int start_constraints
; /* Start of range is constrained */
1753 int nConstraint
; /* Number of constraint terms */
1754 int iIdxCur
; /* The VDBE cursor for the index */
1755 int nExtraReg
= 0; /* Number of extra registers needed */
1756 int op
; /* Instruction opcode */
1757 char *zStartAff
; /* Affinity for start of range constraint */
1758 char *zEndAff
= 0; /* Affinity for end of range constraint */
1759 u8 bSeekPastNull
= 0; /* True to seek past initial nulls */
1760 u8 bStopAtNull
= 0; /* Add condition to terminate at NULLs */
1761 int omitTable
; /* True if we use the index only */
1762 int regBignull
= 0; /* big-null flag register */
1763 int addrSeekScan
= 0; /* Opcode of the OP_SeekScan, if any */
1765 pIdx
= pLoop
->u
.btree
.pIndex
;
1766 iIdxCur
= pLevel
->iIdxCur
;
1767 assert( nEq
>=pLoop
->nSkip
);
1769 /* Find any inequality constraint terms for the start and end
1773 if( pLoop
->wsFlags
& WHERE_BTM_LIMIT
){
1774 pRangeStart
= pLoop
->aLTerm
[j
++];
1775 nExtraReg
= MAX(nExtraReg
, pLoop
->u
.btree
.nBtm
);
1776 /* Like optimization range constraints always occur in pairs */
1777 assert( (pRangeStart
->wtFlags
& TERM_LIKEOPT
)==0 ||
1778 (pLoop
->wsFlags
& WHERE_TOP_LIMIT
)!=0 );
1780 if( pLoop
->wsFlags
& WHERE_TOP_LIMIT
){
1781 pRangeEnd
= pLoop
->aLTerm
[j
++];
1782 nExtraReg
= MAX(nExtraReg
, pLoop
->u
.btree
.nTop
);
1783 #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
1784 if( (pRangeEnd
->wtFlags
& TERM_LIKEOPT
)!=0 ){
1785 assert( pRangeStart
!=0 ); /* LIKE opt constraints */
1786 assert( pRangeStart
->wtFlags
& TERM_LIKEOPT
); /* occur in pairs */
1787 pLevel
->iLikeRepCntr
= (u32
)++pParse
->nMem
;
1788 sqlite3VdbeAddOp2(v
, OP_Integer
, 1, (int)pLevel
->iLikeRepCntr
);
1789 VdbeComment((v
, "LIKE loop counter"));
1790 pLevel
->addrLikeRep
= sqlite3VdbeCurrentAddr(v
);
1791 /* iLikeRepCntr actually stores 2x the counter register number. The
1792 ** bottom bit indicates whether the search order is ASC or DESC. */
1794 testcase( pIdx
->aSortOrder
[nEq
]==SQLITE_SO_DESC
);
1795 assert( (bRev
& ~1)==0 );
1796 pLevel
->iLikeRepCntr
<<=1;
1797 pLevel
->iLikeRepCntr
|= bRev
^ (pIdx
->aSortOrder
[nEq
]==SQLITE_SO_DESC
);
1800 if( pRangeStart
==0 ){
1801 j
= pIdx
->aiColumn
[nEq
];
1802 if( (j
>=0 && pIdx
->pTable
->aCol
[j
].notNull
==0) || j
==XN_EXPR
){
1807 assert( pRangeEnd
==0 || (pRangeEnd
->wtFlags
& TERM_VNULL
)==0 );
1809 /* If the WHERE_BIGNULL_SORT flag is set, then index column nEq uses
1810 ** a non-default "big-null" sort (either ASC NULLS LAST or DESC NULLS
1811 ** FIRST). In both cases separate ordered scans are made of those
1812 ** index entries for which the column is null and for those for which
1813 ** it is not. For an ASC sort, the non-NULL entries are scanned first.
1814 ** For DESC, NULL entries are scanned first.
1816 if( (pLoop
->wsFlags
& (WHERE_TOP_LIMIT
|WHERE_BTM_LIMIT
))==0
1817 && (pLoop
->wsFlags
& WHERE_BIGNULL_SORT
)!=0
1819 assert( bSeekPastNull
==0 && nExtraReg
==0 && nBtm
==0 && nTop
==0 );
1820 assert( pRangeEnd
==0 && pRangeStart
==0 );
1821 testcase( pLoop
->nSkip
>0 );
1824 pLevel
->regBignull
= regBignull
= ++pParse
->nMem
;
1825 if( pLevel
->iLeftJoin
){
1826 sqlite3VdbeAddOp2(v
, OP_Integer
, 0, regBignull
);
1828 pLevel
->addrBignull
= sqlite3VdbeMakeLabel(pParse
);
1831 /* If we are doing a reverse order scan on an ascending index, or
1832 ** a forward order scan on a descending index, interchange the
1833 ** start and end terms (pRangeStart and pRangeEnd).
1835 if( (nEq
<pIdx
->nColumn
&& bRev
==(pIdx
->aSortOrder
[nEq
]==SQLITE_SO_ASC
)) ){
1836 SWAP(WhereTerm
*, pRangeEnd
, pRangeStart
);
1837 SWAP(u8
, bSeekPastNull
, bStopAtNull
);
1838 SWAP(u8
, nBtm
, nTop
);
1841 if( iLevel
>0 && (pLoop
->wsFlags
& WHERE_IN_SEEKSCAN
)!=0 ){
1842 /* In case OP_SeekScan is used, ensure that the index cursor does not
1843 ** point to a valid row for the first iteration of this loop. */
1844 sqlite3VdbeAddOp1(v
, OP_NullRow
, iIdxCur
);
1847 /* Generate code to evaluate all constraint terms using == or IN
1848 ** and store the values of those terms in an array of registers
1849 ** starting at regBase.
1851 codeCursorHint(pTabItem
, pWInfo
, pLevel
, pRangeEnd
);
1852 regBase
= codeAllEqualityTerms(pParse
,pLevel
,bRev
,nExtraReg
,&zStartAff
);
1853 assert( zStartAff
==0 || sqlite3Strlen30(zStartAff
)>=nEq
);
1854 if( zStartAff
&& nTop
){
1855 zEndAff
= sqlite3DbStrDup(db
, &zStartAff
[nEq
]);
1857 addrNxt
= (regBignull
? pLevel
->addrBignull
: pLevel
->addrNxt
);
1859 testcase( pRangeStart
&& (pRangeStart
->eOperator
& WO_LE
)!=0 );
1860 testcase( pRangeStart
&& (pRangeStart
->eOperator
& WO_GE
)!=0 );
1861 testcase( pRangeEnd
&& (pRangeEnd
->eOperator
& WO_LE
)!=0 );
1862 testcase( pRangeEnd
&& (pRangeEnd
->eOperator
& WO_GE
)!=0 );
1863 startEq
= !pRangeStart
|| pRangeStart
->eOperator
& (WO_LE
|WO_GE
);
1864 endEq
= !pRangeEnd
|| pRangeEnd
->eOperator
& (WO_LE
|WO_GE
);
1865 start_constraints
= pRangeStart
|| nEq
>0;
1867 /* Seek the index cursor to the start of the range. */
1870 Expr
*pRight
= pRangeStart
->pExpr
->pRight
;
1871 codeExprOrVector(pParse
, pRight
, regBase
+nEq
, nBtm
);
1872 whereLikeOptimizationStringFixup(v
, pLevel
, pRangeStart
);
1873 if( (pRangeStart
->wtFlags
& TERM_VNULL
)==0
1874 && sqlite3ExprCanBeNull(pRight
)
1876 sqlite3VdbeAddOp2(v
, OP_IsNull
, regBase
+nEq
, addrNxt
);
1880 updateRangeAffinityStr(pRight
, nBtm
, &zStartAff
[nEq
]);
1882 nConstraint
+= nBtm
;
1883 testcase( pRangeStart
->wtFlags
& TERM_VIRTUAL
);
1884 if( sqlite3ExprIsVector(pRight
)==0 ){
1885 disableTerm(pLevel
, pRangeStart
);
1890 }else if( bSeekPastNull
){
1892 sqlite3VdbeAddOp2(v
, OP_Null
, 0, regBase
+nEq
);
1893 start_constraints
= 1;
1895 }else if( regBignull
){
1896 sqlite3VdbeAddOp2(v
, OP_Null
, 0, regBase
+nEq
);
1897 start_constraints
= 1;
1900 codeApplyAffinity(pParse
, regBase
, nConstraint
- bSeekPastNull
, zStartAff
);
1901 if( pLoop
->nSkip
>0 && nConstraint
==pLoop
->nSkip
){
1902 /* The skip-scan logic inside the call to codeAllEqualityConstraints()
1903 ** above has already left the cursor sitting on the correct row,
1904 ** so no further seeking is needed */
1907 sqlite3VdbeAddOp2(v
, OP_Integer
, 1, regBignull
);
1908 VdbeComment((v
, "NULL-scan pass ctr"));
1910 if( pLevel
->regFilter
){
1911 sqlite3VdbeAddOp4Int(v
, OP_Filter
, pLevel
->regFilter
, addrNxt
,
1914 filterPullDown(pParse
, pWInfo
, iLevel
, addrNxt
, notReady
);
1917 op
= aStartOp
[(start_constraints
<<2) + (startEq
<<1) + bRev
];
1919 if( (pLoop
->wsFlags
& WHERE_IN_SEEKSCAN
)!=0 && op
==OP_SeekGE
){
1920 assert( regBignull
==0 );
1921 /* TUNING: The OP_SeekScan opcode seeks to reduce the number
1922 ** of expensive seek operations by replacing a single seek with
1923 ** 1 or more step operations. The question is, how many steps
1924 ** should we try before giving up and going with a seek. The cost
1925 ** of a seek is proportional to the logarithm of the of the number
1926 ** of entries in the tree, so basing the number of steps to try
1927 ** on the estimated number of rows in the btree seems like a good
1929 addrSeekScan
= sqlite3VdbeAddOp1(v
, OP_SeekScan
,
1930 (pIdx
->aiRowLogEst
[0]+9)/10);
1931 if( pRangeStart
|| pRangeEnd
){
1932 sqlite3VdbeChangeP5(v
, 1);
1933 sqlite3VdbeChangeP2(v
, addrSeekScan
, sqlite3VdbeCurrentAddr(v
)+1);
1938 sqlite3VdbeAddOp4Int(v
, op
, iIdxCur
, addrNxt
, regBase
, nConstraint
);
1940 VdbeCoverageIf(v
, op
==OP_Rewind
); testcase( op
==OP_Rewind
);
1941 VdbeCoverageIf(v
, op
==OP_Last
); testcase( op
==OP_Last
);
1942 VdbeCoverageIf(v
, op
==OP_SeekGT
); testcase( op
==OP_SeekGT
);
1943 VdbeCoverageIf(v
, op
==OP_SeekGE
); testcase( op
==OP_SeekGE
);
1944 VdbeCoverageIf(v
, op
==OP_SeekLE
); testcase( op
==OP_SeekLE
);
1945 VdbeCoverageIf(v
, op
==OP_SeekLT
); testcase( op
==OP_SeekLT
);
1947 assert( bSeekPastNull
==0 || bStopAtNull
==0 );
1949 assert( bSeekPastNull
==1 || bStopAtNull
==1 );
1950 assert( bSeekPastNull
==!bStopAtNull
);
1951 assert( bStopAtNull
==startEq
);
1952 sqlite3VdbeAddOp2(v
, OP_Goto
, 0, sqlite3VdbeCurrentAddr(v
)+2);
1953 op
= aStartOp
[(nConstraint
>1)*4 + 2 + bRev
];
1954 sqlite3VdbeAddOp4Int(v
, op
, iIdxCur
, addrNxt
, regBase
,
1955 nConstraint
-startEq
);
1957 VdbeCoverageIf(v
, op
==OP_Rewind
); testcase( op
==OP_Rewind
);
1958 VdbeCoverageIf(v
, op
==OP_Last
); testcase( op
==OP_Last
);
1959 VdbeCoverageIf(v
, op
==OP_SeekGE
); testcase( op
==OP_SeekGE
);
1960 VdbeCoverageIf(v
, op
==OP_SeekLE
); testcase( op
==OP_SeekLE
);
1961 assert( op
==OP_Rewind
|| op
==OP_Last
|| op
==OP_SeekGE
|| op
==OP_SeekLE
);
1965 /* Load the value for the inequality constraint at the end of the
1969 assert( pLevel
->p2
==0 );
1971 Expr
*pRight
= pRangeEnd
->pExpr
->pRight
;
1972 assert( addrSeekScan
==0 );
1973 codeExprOrVector(pParse
, pRight
, regBase
+nEq
, nTop
);
1974 whereLikeOptimizationStringFixup(v
, pLevel
, pRangeEnd
);
1975 if( (pRangeEnd
->wtFlags
& TERM_VNULL
)==0
1976 && sqlite3ExprCanBeNull(pRight
)
1978 sqlite3VdbeAddOp2(v
, OP_IsNull
, regBase
+nEq
, addrNxt
);
1982 updateRangeAffinityStr(pRight
, nTop
, zEndAff
);
1983 codeApplyAffinity(pParse
, regBase
+nEq
, nTop
, zEndAff
);
1985 assert( pParse
->db
->mallocFailed
);
1987 nConstraint
+= nTop
;
1988 testcase( pRangeEnd
->wtFlags
& TERM_VIRTUAL
);
1990 if( sqlite3ExprIsVector(pRight
)==0 ){
1991 disableTerm(pLevel
, pRangeEnd
);
1995 }else if( bStopAtNull
){
1996 if( regBignull
==0 ){
1997 sqlite3VdbeAddOp2(v
, OP_Null
, 0, regBase
+nEq
);
2002 if( zStartAff
) sqlite3DbNNFreeNN(db
, zStartAff
);
2003 if( zEndAff
) sqlite3DbNNFreeNN(db
, zEndAff
);
2005 /* Top of the loop body */
2006 pLevel
->p2
= sqlite3VdbeCurrentAddr(v
);
2008 /* Check if the index cursor is past the end of the range. */
2011 /* Except, skip the end-of-range check while doing the NULL-scan */
2012 sqlite3VdbeAddOp2(v
, OP_IfNot
, regBignull
, sqlite3VdbeCurrentAddr(v
)+3);
2013 VdbeComment((v
, "If NULL-scan 2nd pass"));
2016 op
= aEndOp
[bRev
*2 + endEq
];
2017 sqlite3VdbeAddOp4Int(v
, op
, iIdxCur
, addrNxt
, regBase
, nConstraint
);
2018 testcase( op
==OP_IdxGT
); VdbeCoverageIf(v
, op
==OP_IdxGT
);
2019 testcase( op
==OP_IdxGE
); VdbeCoverageIf(v
, op
==OP_IdxGE
);
2020 testcase( op
==OP_IdxLT
); VdbeCoverageIf(v
, op
==OP_IdxLT
);
2021 testcase( op
==OP_IdxLE
); VdbeCoverageIf(v
, op
==OP_IdxLE
);
2022 if( addrSeekScan
) sqlite3VdbeJumpHere(v
, addrSeekScan
);
2025 /* During a NULL-scan, check to see if we have reached the end of
2027 assert( bSeekPastNull
==!bStopAtNull
);
2028 assert( bSeekPastNull
+bStopAtNull
==1 );
2029 assert( nConstraint
+bSeekPastNull
>0 );
2030 sqlite3VdbeAddOp2(v
, OP_If
, regBignull
, sqlite3VdbeCurrentAddr(v
)+2);
2031 VdbeComment((v
, "If NULL-scan 1st pass"));
2033 op
= aEndOp
[bRev
*2 + bSeekPastNull
];
2034 sqlite3VdbeAddOp4Int(v
, op
, iIdxCur
, addrNxt
, regBase
,
2035 nConstraint
+bSeekPastNull
);
2036 testcase( op
==OP_IdxGT
); VdbeCoverageIf(v
, op
==OP_IdxGT
);
2037 testcase( op
==OP_IdxGE
); VdbeCoverageIf(v
, op
==OP_IdxGE
);
2038 testcase( op
==OP_IdxLT
); VdbeCoverageIf(v
, op
==OP_IdxLT
);
2039 testcase( op
==OP_IdxLE
); VdbeCoverageIf(v
, op
==OP_IdxLE
);
2042 if( (pLoop
->wsFlags
& WHERE_IN_EARLYOUT
)!=0 ){
2043 sqlite3VdbeAddOp3(v
, OP_SeekHit
, iIdxCur
, nEq
, nEq
);
2046 /* Seek the table cursor, if required */
2047 omitTable
= (pLoop
->wsFlags
& WHERE_IDX_ONLY
)!=0
2048 && (pWInfo
->wctrlFlags
& (WHERE_OR_SUBCLAUSE
|WHERE_RIGHT_JOIN
))==0;
2050 /* pIdx is a covering index. No need to access the main table. */
2051 }else if( HasRowid(pIdx
->pTable
) ){
2052 codeDeferredSeek(pWInfo
, pIdx
, iCur
, iIdxCur
);
2053 }else if( iCur
!=iIdxCur
){
2054 Index
*pPk
= sqlite3PrimaryKeyIndex(pIdx
->pTable
);
2055 iRowidReg
= sqlite3GetTempRange(pParse
, pPk
->nKeyCol
);
2056 for(j
=0; j
<pPk
->nKeyCol
; j
++){
2057 k
= sqlite3TableColumnToIndex(pIdx
, pPk
->aiColumn
[j
]);
2058 sqlite3VdbeAddOp3(v
, OP_Column
, iIdxCur
, k
, iRowidReg
+j
);
2060 sqlite3VdbeAddOp4Int(v
, OP_NotFound
, iCur
, addrCont
,
2061 iRowidReg
, pPk
->nKeyCol
); VdbeCoverage(v
);
2064 if( pLevel
->iLeftJoin
==0 ){
2065 /* If a partial index is driving the loop, try to eliminate WHERE clause
2066 ** terms from the query that must be true due to the WHERE clause of
2067 ** the partial index.
2069 ** 2019-11-02 ticket 623eff57e76d45f6: This optimization does not work
2072 if( pIdx
->pPartIdxWhere
){
2073 whereApplyPartialIndexConstraints(pIdx
->pPartIdxWhere
, iCur
, pWC
);
2076 testcase( pIdx
->pPartIdxWhere
);
2077 /* The following assert() is not a requirement, merely an observation:
2078 ** The OR-optimization doesn't work for the right hand table of
2080 assert( (pWInfo
->wctrlFlags
& (WHERE_OR_SUBCLAUSE
|WHERE_RIGHT_JOIN
))==0 );
2083 /* Record the instruction used to terminate the loop. */
2084 if( pLoop
->wsFlags
& WHERE_ONEROW
){
2085 pLevel
->op
= OP_Noop
;
2087 pLevel
->op
= OP_Prev
;
2089 pLevel
->op
= OP_Next
;
2091 pLevel
->p1
= iIdxCur
;
2092 pLevel
->p3
= (pLoop
->wsFlags
&WHERE_UNQ_WANTED
)!=0 ? 1:0;
2093 if( (pLoop
->wsFlags
& WHERE_CONSTRAINT
)==0 ){
2094 pLevel
->p5
= SQLITE_STMTSTATUS_FULLSCAN_STEP
;
2096 assert( pLevel
->p5
==0 );
2098 if( omitTable
) pIdx
= 0;
2101 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
2102 if( pLoop
->wsFlags
& WHERE_MULTI_OR
){
2103 /* Case 5: Two or more separately indexed terms connected by OR
2107 ** CREATE TABLE t1(a,b,c,d);
2108 ** CREATE INDEX i1 ON t1(a);
2109 ** CREATE INDEX i2 ON t1(b);
2110 ** CREATE INDEX i3 ON t1(c);
2112 ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
2114 ** In the example, there are three indexed terms connected by OR.
2115 ** The top of the loop looks like this:
2117 ** Null 1 # Zero the rowset in reg 1
2119 ** Then, for each indexed term, the following. The arguments to
2120 ** RowSetTest are such that the rowid of the current row is inserted
2121 ** into the RowSet. If it is already present, control skips the
2122 ** Gosub opcode and jumps straight to the code generated by WhereEnd().
2124 ** sqlite3WhereBegin(<term>)
2125 ** RowSetTest # Insert rowid into rowset
2127 ** sqlite3WhereEnd()
2129 ** Following the above, code to terminate the loop. Label A, the target
2130 ** of the Gosub above, jumps to the instruction right after the Goto.
2132 ** Null 1 # Zero the rowset in reg 1
2133 ** Goto B # The loop is finished.
2135 ** A: <loop body> # Return data, whatever.
2137 ** Return 2 # Jump back to the Gosub
2139 ** B: <after the loop>
2141 ** Added 2014-05-26: If the table is a WITHOUT ROWID table, then
2142 ** use an ephemeral index instead of a RowSet to record the primary
2143 ** keys of the rows we have already seen.
2146 WhereClause
*pOrWc
; /* The OR-clause broken out into subterms */
2147 SrcList
*pOrTab
; /* Shortened table list or OR-clause generation */
2148 Index
*pCov
= 0; /* Potential covering index (or NULL) */
2149 int iCovCur
= pParse
->nTab
++; /* Cursor used for index scans (if any) */
2151 int regReturn
= ++pParse
->nMem
; /* Register used with OP_Gosub */
2152 int regRowset
= 0; /* Register for RowSet object */
2153 int regRowid
= 0; /* Register holding rowid */
2154 int iLoopBody
= sqlite3VdbeMakeLabel(pParse
);/* Start of loop body */
2155 int iRetInit
; /* Address of regReturn init */
2156 int untestedTerms
= 0; /* Some terms not completely tested */
2157 int ii
; /* Loop counter */
2158 Expr
*pAndExpr
= 0; /* An ".. AND (...)" expression */
2159 Table
*pTab
= pTabItem
->pTab
;
2161 pTerm
= pLoop
->aLTerm
[0];
2163 assert( pTerm
->eOperator
& WO_OR
);
2164 assert( (pTerm
->wtFlags
& TERM_ORINFO
)!=0 );
2165 pOrWc
= &pTerm
->u
.pOrInfo
->wc
;
2166 pLevel
->op
= OP_Return
;
2167 pLevel
->p1
= regReturn
;
2169 /* Set up a new SrcList in pOrTab containing the table being scanned
2170 ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
2171 ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
2173 if( pWInfo
->nLevel
>1 ){
2174 int nNotReady
; /* The number of notReady tables */
2175 SrcItem
*origSrc
; /* Original list of tables */
2176 nNotReady
= pWInfo
->nLevel
- iLevel
- 1;
2177 pOrTab
= sqlite3DbMallocRawNN(db
,
2178 sizeof(*pOrTab
)+ nNotReady
*sizeof(pOrTab
->a
[0]));
2179 if( pOrTab
==0 ) return notReady
;
2180 pOrTab
->nAlloc
= (u8
)(nNotReady
+ 1);
2181 pOrTab
->nSrc
= pOrTab
->nAlloc
;
2182 memcpy(pOrTab
->a
, pTabItem
, sizeof(*pTabItem
));
2183 origSrc
= pWInfo
->pTabList
->a
;
2184 for(k
=1; k
<=nNotReady
; k
++){
2185 memcpy(&pOrTab
->a
[k
], &origSrc
[pLevel
[k
].iFrom
], sizeof(pOrTab
->a
[k
]));
2188 pOrTab
= pWInfo
->pTabList
;
2191 /* Initialize the rowset register to contain NULL. An SQL NULL is
2192 ** equivalent to an empty rowset. Or, create an ephemeral index
2193 ** capable of holding primary keys in the case of a WITHOUT ROWID.
2195 ** Also initialize regReturn to contain the address of the instruction
2196 ** immediately following the OP_Return at the bottom of the loop. This
2197 ** is required in a few obscure LEFT JOIN cases where control jumps
2198 ** over the top of the loop into the body of it. In this case the
2199 ** correct response for the end-of-loop code (the OP_Return) is to
2200 ** fall through to the next instruction, just as an OP_Next does if
2201 ** called on an uninitialized cursor.
2203 if( (pWInfo
->wctrlFlags
& WHERE_DUPLICATES_OK
)==0 ){
2204 if( HasRowid(pTab
) ){
2205 regRowset
= ++pParse
->nMem
;
2206 sqlite3VdbeAddOp2(v
, OP_Null
, 0, regRowset
);
2208 Index
*pPk
= sqlite3PrimaryKeyIndex(pTab
);
2209 regRowset
= pParse
->nTab
++;
2210 sqlite3VdbeAddOp2(v
, OP_OpenEphemeral
, regRowset
, pPk
->nKeyCol
);
2211 sqlite3VdbeSetP4KeyInfo(pParse
, pPk
);
2213 regRowid
= ++pParse
->nMem
;
2215 iRetInit
= sqlite3VdbeAddOp2(v
, OP_Integer
, 0, regReturn
);
2217 /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y
2218 ** Then for every term xN, evaluate as the subexpression: xN AND y
2219 ** That way, terms in y that are factored into the disjunction will
2220 ** be picked up by the recursive calls to sqlite3WhereBegin() below.
2222 ** Actually, each subexpression is converted to "xN AND w" where w is
2223 ** the "interesting" terms of z - terms that did not originate in the
2224 ** ON or USING clause of a LEFT JOIN, and terms that are usable as
2227 ** This optimization also only applies if the (x1 OR x2 OR ...) term
2228 ** is not contained in the ON clause of a LEFT JOIN.
2229 ** See ticket http://www.sqlite.org/src/info/f2369304e4
2231 ** 2022-02-04: Do not push down slices of a row-value comparison.
2232 ** In other words, "w" or "y" may not be a slice of a vector. Otherwise,
2233 ** the initialization of the right-hand operand of the vector comparison
2234 ** might not occur, or might occur only in an OR branch that is not
2235 ** taken. dbsqlfuzz 80a9fade844b4fb43564efc972bcb2c68270f5d1.
2237 ** 2022-03-03: Do not push down expressions that involve subqueries.
2238 ** The subquery might get coded as a subroutine. Any table-references
2239 ** in the subquery might be resolved to index-references for the index on
2240 ** the OR branch in which the subroutine is coded. But if the subroutine
2241 ** is invoked from a different OR branch that uses a different index, such
2242 ** index-references will not work. tag-20220303a
2243 ** https://sqlite.org/forum/forumpost/36937b197273d403
2247 for(iTerm
=0; iTerm
<pWC
->nTerm
; iTerm
++){
2248 Expr
*pExpr
= pWC
->a
[iTerm
].pExpr
;
2249 if( &pWC
->a
[iTerm
] == pTerm
) continue;
2250 testcase( pWC
->a
[iTerm
].wtFlags
& TERM_VIRTUAL
);
2251 testcase( pWC
->a
[iTerm
].wtFlags
& TERM_CODED
);
2252 testcase( pWC
->a
[iTerm
].wtFlags
& TERM_SLICE
);
2253 if( (pWC
->a
[iTerm
].wtFlags
& (TERM_VIRTUAL
|TERM_CODED
|TERM_SLICE
))!=0 ){
2256 if( (pWC
->a
[iTerm
].eOperator
& WO_ALL
)==0 ) continue;
2257 if( ExprHasProperty(pExpr
, EP_Subquery
) ) continue; /* tag-20220303a */
2258 pExpr
= sqlite3ExprDup(db
, pExpr
, 0);
2259 pAndExpr
= sqlite3ExprAnd(pParse
, pAndExpr
, pExpr
);
2262 /* The extra 0x10000 bit on the opcode is masked off and does not
2263 ** become part of the new Expr.op. However, it does make the
2264 ** op==TK_AND comparison inside of sqlite3PExpr() false, and this
2265 ** prevents sqlite3PExpr() from applying the AND short-circuit
2266 ** optimization, which we do not want here. */
2267 pAndExpr
= sqlite3PExpr(pParse
, TK_AND
|0x10000, 0, pAndExpr
);
2271 /* Run a separate WHERE clause for each term of the OR clause. After
2272 ** eliminating duplicates from other WHERE clauses, the action for each
2273 ** sub-WHERE clause is to to invoke the main loop body as a subroutine.
2275 ExplainQueryPlan((pParse
, 1, "MULTI-INDEX OR"));
2276 for(ii
=0; ii
<pOrWc
->nTerm
; ii
++){
2277 WhereTerm
*pOrTerm
= &pOrWc
->a
[ii
];
2278 if( pOrTerm
->leftCursor
==iCur
|| (pOrTerm
->eOperator
& WO_AND
)!=0 ){
2279 WhereInfo
*pSubWInfo
; /* Info for single OR-term scan */
2280 Expr
*pOrExpr
= pOrTerm
->pExpr
; /* Current OR clause term */
2281 Expr
*pDelete
; /* Local copy of OR clause term */
2282 int jmp1
= 0; /* Address of jump operation */
2283 testcase( (pTabItem
[0].fg
.jointype
& JT_LEFT
)!=0
2284 && !ExprHasProperty(pOrExpr
, EP_OuterON
)
2285 ); /* See TH3 vtab25.400 and ticket 614b25314c766238 */
2286 pDelete
= pOrExpr
= sqlite3ExprDup(db
, pOrExpr
, 0);
2287 if( db
->mallocFailed
){
2288 sqlite3ExprDelete(db
, pDelete
);
2292 pAndExpr
->pLeft
= pOrExpr
;
2295 /* Loop through table entries that match term pOrTerm. */
2296 ExplainQueryPlan((pParse
, 1, "INDEX %d", ii
+1));
2297 WHERETRACE(0xffffffff, ("Subplan for OR-clause:\n"));
2298 pSubWInfo
= sqlite3WhereBegin(pParse
, pOrTab
, pOrExpr
, 0, 0, 0,
2299 WHERE_OR_SUBCLAUSE
, iCovCur
);
2300 assert( pSubWInfo
|| pParse
->nErr
);
2302 WhereLoop
*pSubLoop
;
2303 int addrExplain
= sqlite3WhereExplainOneScan(
2304 pParse
, pOrTab
, &pSubWInfo
->a
[0], 0
2306 sqlite3WhereAddScanStatus(v
, pOrTab
, &pSubWInfo
->a
[0], addrExplain
);
2308 /* This is the sub-WHERE clause body. First skip over
2309 ** duplicate rows from prior sub-WHERE clauses, and record the
2310 ** rowid (or PRIMARY KEY) for the current row so that the same
2311 ** row will be skipped in subsequent sub-WHERE clauses.
2313 if( (pWInfo
->wctrlFlags
& WHERE_DUPLICATES_OK
)==0 ){
2314 int iSet
= ((ii
==pOrWc
->nTerm
-1)?-1:ii
);
2315 if( HasRowid(pTab
) ){
2316 sqlite3ExprCodeGetColumnOfTable(v
, pTab
, iCur
, -1, regRowid
);
2317 jmp1
= sqlite3VdbeAddOp4Int(v
, OP_RowSetTest
, regRowset
, 0,
2321 Index
*pPk
= sqlite3PrimaryKeyIndex(pTab
);
2322 int nPk
= pPk
->nKeyCol
;
2326 /* Read the PK into an array of temp registers. */
2327 r
= sqlite3GetTempRange(pParse
, nPk
);
2328 for(iPk
=0; iPk
<nPk
; iPk
++){
2329 int iCol
= pPk
->aiColumn
[iPk
];
2330 sqlite3ExprCodeGetColumnOfTable(v
, pTab
, iCur
, iCol
,r
+iPk
);
2333 /* Check if the temp table already contains this key. If so,
2334 ** the row has already been included in the result set and
2335 ** can be ignored (by jumping past the Gosub below). Otherwise,
2336 ** insert the key into the temp table and proceed with processing
2339 ** Use some of the same optimizations as OP_RowSetTest: If iSet
2340 ** is zero, assume that the key cannot already be present in
2341 ** the temp table. And if iSet is -1, assume that there is no
2342 ** need to insert the key into the temp table, as it will never
2343 ** be tested for. */
2345 jmp1
= sqlite3VdbeAddOp4Int(v
, OP_Found
, regRowset
, 0, r
, nPk
);
2349 sqlite3VdbeAddOp3(v
, OP_MakeRecord
, r
, nPk
, regRowid
);
2350 sqlite3VdbeAddOp4Int(v
, OP_IdxInsert
, regRowset
, regRowid
,
2352 if( iSet
) sqlite3VdbeChangeP5(v
, OPFLAG_USESEEKRESULT
);
2355 /* Release the array of temp registers */
2356 sqlite3ReleaseTempRange(pParse
, r
, nPk
);
2360 /* Invoke the main loop body as a subroutine */
2361 sqlite3VdbeAddOp2(v
, OP_Gosub
, regReturn
, iLoopBody
);
2363 /* Jump here (skipping the main loop body subroutine) if the
2364 ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */
2365 if( jmp1
) sqlite3VdbeJumpHere(v
, jmp1
);
2367 /* The pSubWInfo->untestedTerms flag means that this OR term
2368 ** contained one or more AND term from a notReady table. The
2369 ** terms from the notReady table could not be tested and will
2370 ** need to be tested later.
2372 if( pSubWInfo
->untestedTerms
) untestedTerms
= 1;
2374 /* If all of the OR-connected terms are optimized using the same
2375 ** index, and the index is opened using the same cursor number
2376 ** by each call to sqlite3WhereBegin() made by this loop, it may
2377 ** be possible to use that index as a covering index.
2379 ** If the call to sqlite3WhereBegin() above resulted in a scan that
2380 ** uses an index, and this is either the first OR-connected term
2381 ** processed or the index is the same as that used by all previous
2382 ** terms, set pCov to the candidate covering index. Otherwise, set
2383 ** pCov to NULL to indicate that no candidate covering index will
2386 pSubLoop
= pSubWInfo
->a
[0].pWLoop
;
2387 assert( (pSubLoop
->wsFlags
& WHERE_AUTO_INDEX
)==0 );
2388 if( (pSubLoop
->wsFlags
& WHERE_INDEXED
)!=0
2389 && (ii
==0 || pSubLoop
->u
.btree
.pIndex
==pCov
)
2390 && (HasRowid(pTab
) || !IsPrimaryKeyIndex(pSubLoop
->u
.btree
.pIndex
))
2392 assert( pSubWInfo
->a
[0].iIdxCur
==iCovCur
);
2393 pCov
= pSubLoop
->u
.btree
.pIndex
;
2397 if( sqlite3WhereUsesDeferredSeek(pSubWInfo
) ){
2398 pWInfo
->bDeferredSeek
= 1;
2401 /* Finish the loop through table entries that match term pOrTerm. */
2402 sqlite3WhereEnd(pSubWInfo
);
2403 ExplainQueryPlanPop(pParse
);
2405 sqlite3ExprDelete(db
, pDelete
);
2408 ExplainQueryPlanPop(pParse
);
2409 assert( pLevel
->pWLoop
==pLoop
);
2410 assert( (pLoop
->wsFlags
& WHERE_MULTI_OR
)!=0 );
2411 assert( (pLoop
->wsFlags
& WHERE_IN_ABLE
)==0 );
2412 pLevel
->u
.pCoveringIdx
= pCov
;
2413 if( pCov
) pLevel
->iIdxCur
= iCovCur
;
2415 pAndExpr
->pLeft
= 0;
2416 sqlite3ExprDelete(db
, pAndExpr
);
2418 sqlite3VdbeChangeP1(v
, iRetInit
, sqlite3VdbeCurrentAddr(v
));
2419 sqlite3VdbeGoto(v
, pLevel
->addrBrk
);
2420 sqlite3VdbeResolveLabel(v
, iLoopBody
);
2422 /* Set the P2 operand of the OP_Return opcode that will end the current
2423 ** loop to point to this spot, which is the top of the next containing
2424 ** loop. The byte-code formatter will use that P2 value as a hint to
2425 ** indent everything in between the this point and the final OP_Return.
2426 ** See tag-20220407a in vdbe.c and shell.c */
2427 assert( pLevel
->op
==OP_Return
);
2428 pLevel
->p2
= sqlite3VdbeCurrentAddr(v
);
2430 if( pWInfo
->nLevel
>1 ){ sqlite3DbFreeNN(db
, pOrTab
); }
2431 if( !untestedTerms
) disableTerm(pLevel
, pTerm
);
2433 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
2436 /* Case 6: There is no usable index. We must do a complete
2437 ** scan of the entire table.
2439 static const u8 aStep
[] = { OP_Next
, OP_Prev
};
2440 static const u8 aStart
[] = { OP_Rewind
, OP_Last
};
2441 assert( bRev
==0 || bRev
==1 );
2442 if( pTabItem
->fg
.isRecursive
){
2443 /* Tables marked isRecursive have only a single row that is stored in
2444 ** a pseudo-cursor. No need to Rewind or Next such cursors. */
2445 pLevel
->op
= OP_Noop
;
2447 codeCursorHint(pTabItem
, pWInfo
, pLevel
, 0);
2448 pLevel
->op
= aStep
[bRev
];
2450 pLevel
->p2
= 1 + sqlite3VdbeAddOp2(v
, aStart
[bRev
], iCur
, addrHalt
);
2451 VdbeCoverageIf(v
, bRev
==0);
2452 VdbeCoverageIf(v
, bRev
!=0);
2453 pLevel
->p5
= SQLITE_STMTSTATUS_FULLSCAN_STEP
;
2457 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
2458 pLevel
->addrVisit
= sqlite3VdbeCurrentAddr(v
);
2461 /* Insert code to test every subexpression that can be completely
2462 ** computed using the current set of tables.
2464 ** This loop may run between one and three times, depending on the
2465 ** constraints to be generated. The value of stack variable iLoop
2466 ** determines the constraints coded by each iteration, as follows:
2468 ** iLoop==1: Code only expressions that are entirely covered by pIdx.
2469 ** iLoop==2: Code remaining expressions that do not contain correlated
2471 ** iLoop==3: Code all remaining expressions.
2473 ** An effort is made to skip unnecessary iterations of the loop.
2475 iLoop
= (pIdx
? 1 : 2);
2477 int iNext
= 0; /* Next value for iLoop */
2478 for(pTerm
=pWC
->a
, j
=pWC
->nTerm
; j
>0; j
--, pTerm
++){
2480 int skipLikeAddr
= 0;
2481 testcase( pTerm
->wtFlags
& TERM_VIRTUAL
);
2482 testcase( pTerm
->wtFlags
& TERM_CODED
);
2483 if( pTerm
->wtFlags
& (TERM_VIRTUAL
|TERM_CODED
) ) continue;
2484 if( (pTerm
->prereqAll
& pLevel
->notReady
)!=0 ){
2485 testcase( pWInfo
->untestedTerms
==0
2486 && (pWInfo
->wctrlFlags
& WHERE_OR_SUBCLAUSE
)!=0 );
2487 pWInfo
->untestedTerms
= 1;
2492 if( pTabItem
->fg
.jointype
& (JT_LEFT
|JT_LTORJ
|JT_RIGHT
) ){
2493 if( !ExprHasProperty(pE
,EP_OuterON
|EP_InnerON
) ){
2494 /* Defer processing WHERE clause constraints until after outer
2495 ** join processing. tag-20220513a */
2497 }else if( (pTabItem
->fg
.jointype
& JT_LEFT
)==JT_LEFT
2498 && !ExprHasProperty(pE
,EP_OuterON
) ){
2501 Bitmask m
= sqlite3WhereGetMask(&pWInfo
->sMaskSet
, pE
->w
.iJoin
);
2502 if( m
& pLevel
->notReady
){
2503 /* An ON clause that is not ripe */
2508 if( iLoop
==1 && !sqlite3ExprCoveredByIndex(pE
, pLevel
->iTabCur
, pIdx
) ){
2512 if( iLoop
<3 && (pTerm
->wtFlags
& TERM_VARSELECT
) ){
2513 if( iNext
==0 ) iNext
= 3;
2517 if( (pTerm
->wtFlags
& TERM_LIKECOND
)!=0 ){
2518 /* If the TERM_LIKECOND flag is set, that means that the range search
2519 ** is sufficient to guarantee that the LIKE operator is true, so we
2520 ** can skip the call to the like(A,B) function. But this only works
2521 ** for strings. So do not skip the call to the function on the pass
2522 ** that compares BLOBs. */
2523 #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
2526 u32 x
= pLevel
->iLikeRepCntr
;
2528 skipLikeAddr
= sqlite3VdbeAddOp1(v
, (x
&1)?OP_IfNot
:OP_If
,(int)(x
>>1));
2529 VdbeCoverageIf(v
, (x
&1)==1);
2530 VdbeCoverageIf(v
, (x
&1)==0);
2534 #ifdef WHERETRACE_ENABLED /* 0xffffffff */
2535 if( sqlite3WhereTrace
){
2536 VdbeNoopComment((v
, "WhereTerm[%d] (%p) priority=%d",
2537 pWC
->nTerm
-j
, pTerm
, iLoop
));
2539 if( sqlite3WhereTrace
& 0x4000 ){
2540 sqlite3DebugPrintf("Coding auxiliary constraint:\n");
2541 sqlite3WhereTermPrint(pTerm
, pWC
->nTerm
-j
);
2544 sqlite3ExprIfFalse(pParse
, pE
, addrCont
, SQLITE_JUMPIFNULL
);
2545 if( skipLikeAddr
) sqlite3VdbeJumpHere(v
, skipLikeAddr
);
2546 pTerm
->wtFlags
|= TERM_CODED
;
2551 /* Insert code to test for implied constraints based on transitivity
2552 ** of the "==" operator.
2554 ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
2555 ** and we are coding the t1 loop and the t2 loop has not yet coded,
2556 ** then we cannot use the "t1.a=t2.b" constraint, but we can code
2557 ** the implied "t1.a=123" constraint.
2559 for(pTerm
=pWC
->a
, j
=pWC
->nBase
; j
>0; j
--, pTerm
++){
2562 if( pTerm
->wtFlags
& (TERM_VIRTUAL
|TERM_CODED
) ) continue;
2563 if( (pTerm
->eOperator
& (WO_EQ
|WO_IS
))==0 ) continue;
2564 if( (pTerm
->eOperator
& WO_EQUIV
)==0 ) continue;
2565 if( pTerm
->leftCursor
!=iCur
) continue;
2566 if( pTabItem
->fg
.jointype
& (JT_LEFT
|JT_LTORJ
|JT_RIGHT
) ) continue;
2568 #ifdef WHERETRACE_ENABLED /* 0x4001 */
2569 if( (sqlite3WhereTrace
& 0x4001)==0x4001 ){
2570 sqlite3DebugPrintf("Coding transitive constraint:\n");
2571 sqlite3WhereTermPrint(pTerm
, pWC
->nTerm
-j
);
2574 assert( !ExprHasProperty(pE
, EP_OuterON
) );
2575 assert( (pTerm
->prereqRight
& pLevel
->notReady
)!=0 );
2576 assert( (pTerm
->eOperator
& (WO_OR
|WO_AND
))==0 );
2577 pAlt
= sqlite3WhereFindTerm(pWC
, iCur
, pTerm
->u
.x
.leftColumn
, notReady
,
2578 WO_EQ
|WO_IN
|WO_IS
, 0);
2579 if( pAlt
==0 ) continue;
2580 if( pAlt
->wtFlags
& (TERM_CODED
) ) continue;
2581 if( (pAlt
->eOperator
& WO_IN
)
2582 && ExprUseXSelect(pAlt
->pExpr
)
2583 && (pAlt
->pExpr
->x
.pSelect
->pEList
->nExpr
>1)
2587 testcase( pAlt
->eOperator
& WO_EQ
);
2588 testcase( pAlt
->eOperator
& WO_IS
);
2589 testcase( pAlt
->eOperator
& WO_IN
);
2590 VdbeModuleComment((v
, "begin transitive constraint"));
2591 sEAlt
= *pAlt
->pExpr
;
2592 sEAlt
.pLeft
= pE
->pLeft
;
2593 sqlite3ExprIfFalse(pParse
, &sEAlt
, addrCont
, SQLITE_JUMPIFNULL
);
2594 pAlt
->wtFlags
|= TERM_CODED
;
2597 /* For a RIGHT OUTER JOIN, record the fact that the current row has
2598 ** been matched at least once.
2605 WhereRightJoin
*pRJ
= pLevel
->pRJ
;
2607 /* pTab is the right-hand table of the RIGHT JOIN. Generate code that
2608 ** will record that the current row of that table has been matched at
2609 ** least once. This is accomplished by storing the PK for the row in
2610 ** both the iMatch index and the regBloom Bloom filter.
2612 pTab
= pWInfo
->pTabList
->a
[pLevel
->iFrom
].pTab
;
2613 if( HasRowid(pTab
) ){
2614 r
= sqlite3GetTempRange(pParse
, 2);
2615 sqlite3ExprCodeGetColumnOfTable(v
, pTab
, pLevel
->iTabCur
, -1, r
+1);
2619 Index
*pPk
= sqlite3PrimaryKeyIndex(pTab
);
2621 r
= sqlite3GetTempRange(pParse
, nPk
+1);
2622 for(iPk
=0; iPk
<nPk
; iPk
++){
2623 int iCol
= pPk
->aiColumn
[iPk
];
2624 sqlite3ExprCodeGetColumnOfTable(v
, pTab
, iCur
, iCol
,r
+1+iPk
);
2627 jmp1
= sqlite3VdbeAddOp4Int(v
, OP_Found
, pRJ
->iMatch
, 0, r
+1, nPk
);
2629 VdbeComment((v
, "match against %s", pTab
->zName
));
2630 sqlite3VdbeAddOp3(v
, OP_MakeRecord
, r
+1, nPk
, r
);
2631 sqlite3VdbeAddOp4Int(v
, OP_IdxInsert
, pRJ
->iMatch
, r
, r
+1, nPk
);
2632 sqlite3VdbeAddOp4Int(v
, OP_FilterAdd
, pRJ
->regBloom
, 0, r
+1, nPk
);
2633 sqlite3VdbeChangeP5(v
, OPFLAG_USESEEKRESULT
);
2634 sqlite3VdbeJumpHere(v
, jmp1
);
2635 sqlite3ReleaseTempRange(pParse
, r
, nPk
+1);
2638 /* For a LEFT OUTER JOIN, generate code that will record the fact that
2639 ** at least one row of the right table has matched the left table.
2641 if( pLevel
->iLeftJoin
){
2642 pLevel
->addrFirst
= sqlite3VdbeCurrentAddr(v
);
2643 sqlite3VdbeAddOp2(v
, OP_Integer
, 1, pLevel
->iLeftJoin
);
2644 VdbeComment((v
, "record LEFT JOIN hit"));
2645 if( pLevel
->pRJ
==0 ){
2646 goto code_outer_join_constraints
; /* WHERE clause constraints */
2651 /* Create a subroutine used to process all interior loops and code
2652 ** of the RIGHT JOIN. During normal operation, the subroutine will
2653 ** be in-line with the rest of the code. But at the end, a separate
2654 ** loop will run that invokes this subroutine for unmatched rows
2655 ** of pTab, with all tables to left begin set to NULL.
2657 WhereRightJoin
*pRJ
= pLevel
->pRJ
;
2658 sqlite3VdbeAddOp2(v
, OP_BeginSubrtn
, 0, pRJ
->regReturn
);
2659 pRJ
->addrSubrtn
= sqlite3VdbeCurrentAddr(v
);
2660 assert( pParse
->withinRJSubrtn
< 255 );
2661 pParse
->withinRJSubrtn
++;
2663 /* WHERE clause constraints must be deferred until after outer join
2664 ** row elimination has completed, since WHERE clause constraints apply
2665 ** to the results of the OUTER JOIN. The following loop generates the
2666 ** appropriate WHERE clause constraint checks. tag-20220513a.
2668 code_outer_join_constraints
:
2669 for(pTerm
=pWC
->a
, j
=0; j
<pWC
->nBase
; j
++, pTerm
++){
2670 testcase( pTerm
->wtFlags
& TERM_VIRTUAL
);
2671 testcase( pTerm
->wtFlags
& TERM_CODED
);
2672 if( pTerm
->wtFlags
& (TERM_VIRTUAL
|TERM_CODED
) ) continue;
2673 if( (pTerm
->prereqAll
& pLevel
->notReady
)!=0 ){
2674 assert( pWInfo
->untestedTerms
);
2677 if( pTabItem
->fg
.jointype
& JT_LTORJ
) continue;
2678 assert( pTerm
->pExpr
);
2679 sqlite3ExprIfFalse(pParse
, pTerm
->pExpr
, addrCont
, SQLITE_JUMPIFNULL
);
2680 pTerm
->wtFlags
|= TERM_CODED
;
2684 #if WHERETRACE_ENABLED /* 0x4001 */
2685 if( sqlite3WhereTrace
& 0x4000 ){
2686 sqlite3DebugPrintf("All WHERE-clause terms after coding level %d:\n",
2688 sqlite3WhereClausePrint(pWC
);
2690 if( sqlite3WhereTrace
& 0x1 ){
2691 sqlite3DebugPrintf("End Coding level %d: notReady=%llx\n",
2692 iLevel
, (u64
)pLevel
->notReady
);
2695 return pLevel
->notReady
;
2699 ** Generate the code for the loop that finds all non-matched terms
2700 ** for a RIGHT JOIN.
2702 SQLITE_NOINLINE
void sqlite3WhereRightJoinLoop(
2707 Parse
*pParse
= pWInfo
->pParse
;
2708 Vdbe
*v
= pParse
->pVdbe
;
2709 WhereRightJoin
*pRJ
= pLevel
->pRJ
;
2710 Expr
*pSubWhere
= 0;
2711 WhereClause
*pWC
= &pWInfo
->sWC
;
2712 WhereInfo
*pSubWInfo
;
2713 WhereLoop
*pLoop
= pLevel
->pWLoop
;
2714 SrcItem
*pTabItem
= &pWInfo
->pTabList
->a
[pLevel
->iFrom
];
2719 ExplainQueryPlan((pParse
, 1, "RIGHT-JOIN %s", pTabItem
->pTab
->zName
));
2720 sqlite3VdbeNoJumpsOutsideSubrtn(v
, pRJ
->addrSubrtn
, pRJ
->endSubrtn
,
2722 for(k
=0; k
<iLevel
; k
++){
2724 mAll
|= pWInfo
->a
[k
].pWLoop
->maskSelf
;
2725 sqlite3VdbeAddOp1(v
, OP_NullRow
, pWInfo
->a
[k
].iTabCur
);
2726 iIdxCur
= pWInfo
->a
[k
].iIdxCur
;
2728 sqlite3VdbeAddOp1(v
, OP_NullRow
, iIdxCur
);
2731 if( (pTabItem
->fg
.jointype
& JT_LTORJ
)==0 ){
2732 mAll
|= pLoop
->maskSelf
;
2733 for(k
=0; k
<pWC
->nTerm
; k
++){
2734 WhereTerm
*pTerm
= &pWC
->a
[k
];
2735 if( (pTerm
->wtFlags
& (TERM_VIRTUAL
|TERM_SLICE
))!=0
2736 && pTerm
->eOperator
!=WO_ROWVAL
2740 if( pTerm
->prereqAll
& ~mAll
) continue;
2741 if( ExprHasProperty(pTerm
->pExpr
, EP_OuterON
|EP_InnerON
) ) continue;
2742 pSubWhere
= sqlite3ExprAnd(pParse
, pSubWhere
,
2743 sqlite3ExprDup(pParse
->db
, pTerm
->pExpr
, 0));
2748 memcpy(&sFrom
.a
[0], pTabItem
, sizeof(SrcItem
));
2749 sFrom
.a
[0].fg
.jointype
= 0;
2750 assert( pParse
->withinRJSubrtn
< 100 );
2751 pParse
->withinRJSubrtn
++;
2752 pSubWInfo
= sqlite3WhereBegin(pParse
, &sFrom
, pSubWhere
, 0, 0, 0,
2753 WHERE_RIGHT_JOIN
, 0);
2755 int iCur
= pLevel
->iTabCur
;
2756 int r
= ++pParse
->nMem
;
2759 int addrCont
= sqlite3WhereContinueLabel(pSubWInfo
);
2760 Table
*pTab
= pTabItem
->pTab
;
2761 if( HasRowid(pTab
) ){
2762 sqlite3ExprCodeGetColumnOfTable(v
, pTab
, iCur
, -1, r
);
2766 Index
*pPk
= sqlite3PrimaryKeyIndex(pTab
);
2768 pParse
->nMem
+= nPk
- 1;
2769 for(iPk
=0; iPk
<nPk
; iPk
++){
2770 int iCol
= pPk
->aiColumn
[iPk
];
2771 sqlite3ExprCodeGetColumnOfTable(v
, pTab
, iCur
, iCol
,r
+iPk
);
2774 jmp
= sqlite3VdbeAddOp4Int(v
, OP_Filter
, pRJ
->regBloom
, 0, r
, nPk
);
2776 sqlite3VdbeAddOp4Int(v
, OP_Found
, pRJ
->iMatch
, addrCont
, r
, nPk
);
2778 sqlite3VdbeJumpHere(v
, jmp
);
2779 sqlite3VdbeAddOp2(v
, OP_Gosub
, pRJ
->regReturn
, pRJ
->addrSubrtn
);
2780 sqlite3WhereEnd(pSubWInfo
);
2782 sqlite3ExprDelete(pParse
->db
, pSubWhere
);
2783 ExplainQueryPlanPop(pParse
);
2784 assert( pParse
->withinRJSubrtn
>0 );
2785 pParse
->withinRJSubrtn
--;