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
);
319 int addr
= pSrclist
->a
[pLvl
->iFrom
].addrFillSub
;
320 VdbeOp
*pOp
= sqlite3VdbeGetOp(v
, addr
-1);
321 assert( sqlite3VdbeDb(v
)->mallocFailed
|| pOp
->opcode
==OP_InitCoroutine
);
322 assert( sqlite3VdbeDb(v
)->mallocFailed
|| pOp
->p2
>addr
);
323 sqlite3VdbeScanStatusRange(v
, addrExplain
, addr
, pOp
->p2
-1);
331 ** Disable a term in the WHERE clause. Except, do not disable the term
332 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
333 ** or USING clause of that join.
335 ** Consider the term t2.z='ok' in the following queries:
337 ** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
338 ** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
339 ** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
341 ** The t2.z='ok' is disabled in the in (2) because it originates
342 ** in the ON clause. The term is disabled in (3) because it is not part
343 ** of a LEFT OUTER JOIN. In (1), the term is not disabled.
345 ** Disabling a term causes that term to not be tested in the inner loop
346 ** of the join. Disabling is an optimization. When terms are satisfied
347 ** by indices, we disable them to prevent redundant tests in the inner
348 ** loop. We would get the correct results if nothing were ever disabled,
349 ** but joins might run a little slower. The trick is to disable as much
350 ** as we can without disabling too much. If we disabled in (1), we'd get
351 ** the wrong answer. See ticket #813.
353 ** If all the children of a term are disabled, then that term is also
354 ** automatically disabled. In this way, terms get disabled if derived
355 ** virtual terms are tested first. For example:
357 ** x GLOB 'abc*' AND x>='abc' AND x<'acd'
358 ** \___________/ \______/ \_____/
359 ** parent child1 child2
361 ** Only the parent term was in the original WHERE clause. The child1
362 ** and child2 terms were added by the LIKE optimization. If both of
363 ** the virtual child terms are valid, then testing of the parent can be
366 ** Usually the parent term is marked as TERM_CODED. But if the parent
367 ** term was originally TERM_LIKE, then the parent gets TERM_LIKECOND instead.
368 ** The TERM_LIKECOND marking indicates that the term should be coded inside
369 ** a conditional such that is only evaluated on the second pass of a
370 ** LIKE-optimization loop, when scanning BLOBs instead of strings.
372 static void disableTerm(WhereLevel
*pLevel
, WhereTerm
*pTerm
){
375 while( (pTerm
->wtFlags
& TERM_CODED
)==0
376 && (pLevel
->iLeftJoin
==0 || ExprHasProperty(pTerm
->pExpr
, EP_OuterON
))
377 && (pLevel
->notReady
& pTerm
->prereqAll
)==0
379 if( nLoop
&& (pTerm
->wtFlags
& TERM_LIKE
)!=0 ){
380 pTerm
->wtFlags
|= TERM_LIKECOND
;
382 pTerm
->wtFlags
|= TERM_CODED
;
384 #ifdef WHERETRACE_ENABLED
385 if( (sqlite3WhereTrace
& 0x4001)==0x4001 ){
386 sqlite3DebugPrintf("DISABLE-");
387 sqlite3WhereTermPrint(pTerm
, (int)(pTerm
- (pTerm
->pWC
->a
)));
390 if( pTerm
->iParent
<0 ) break;
391 pTerm
= &pTerm
->pWC
->a
[pTerm
->iParent
];
394 if( pTerm
->nChild
!=0 ) break;
400 ** Code an OP_Affinity opcode to apply the column affinity string zAff
401 ** to the n registers starting at base.
403 ** As an optimization, SQLITE_AFF_BLOB and SQLITE_AFF_NONE entries (which
404 ** are no-ops) at the beginning and end of zAff are ignored. If all entries
405 ** in zAff are SQLITE_AFF_BLOB or SQLITE_AFF_NONE, then no code gets generated.
407 ** This routine makes its own copy of zAff so that the caller is free
408 ** to modify zAff after this routine returns.
410 static void codeApplyAffinity(Parse
*pParse
, int base
, int n
, char *zAff
){
411 Vdbe
*v
= pParse
->pVdbe
;
413 assert( pParse
->db
->mallocFailed
);
418 /* Adjust base and n to skip over SQLITE_AFF_BLOB and SQLITE_AFF_NONE
419 ** entries at the beginning and end of the affinity string.
421 assert( SQLITE_AFF_NONE
<SQLITE_AFF_BLOB
);
422 while( n
>0 && zAff
[0]<=SQLITE_AFF_BLOB
){
427 while( n
>1 && zAff
[n
-1]<=SQLITE_AFF_BLOB
){
431 /* Code the OP_Affinity opcode if there is anything left to do. */
433 sqlite3VdbeAddOp4(v
, OP_Affinity
, base
, n
, 0, zAff
, n
);
438 ** Expression pRight, which is the RHS of a comparison operation, is
439 ** either a vector of n elements or, if n==1, a scalar expression.
440 ** Before the comparison operation, affinity zAff is to be applied
441 ** to the pRight values. This function modifies characters within the
442 ** affinity string to SQLITE_AFF_BLOB if either:
444 ** * the comparison will be performed with no affinity, or
445 ** * the affinity change in zAff is guaranteed not to change the value.
447 static void updateRangeAffinityStr(
448 Expr
*pRight
, /* RHS of comparison */
449 int n
, /* Number of vector elements in comparison */
450 char *zAff
/* Affinity string to modify */
454 Expr
*p
= sqlite3VectorFieldSubexpr(pRight
, i
);
455 if( sqlite3CompareAffinity(p
, zAff
[i
])==SQLITE_AFF_BLOB
456 || sqlite3ExprNeedsNoAffinityChange(p
, zAff
[i
])
458 zAff
[i
] = SQLITE_AFF_BLOB
;
465 ** pX is an expression of the form: (vector) IN (SELECT ...)
466 ** In other words, it is a vector IN operator with a SELECT clause on the
467 ** LHS. But not all terms in the vector are indexable and the terms might
468 ** not be in the correct order for indexing.
470 ** This routine makes a copy of the input pX expression and then adjusts
471 ** the vector on the LHS with corresponding changes to the SELECT so that
472 ** the vector contains only index terms and those terms are in the correct
473 ** order. The modified IN expression is returned. The caller is responsible
474 ** for deleting the returned expression.
478 ** CREATE TABLE t1(a,b,c,d,e,f);
479 ** CREATE INDEX t1x1 ON t1(e,c);
480 ** SELECT * FROM t1 WHERE (a,b,c,d,e) IN (SELECT v,w,x,y,z FROM t2)
481 ** \_______________________________________/
484 ** Since only columns e and c can be used with the index, in that order,
485 ** the modified IN expression that is returned will be:
487 ** (e,c) IN (SELECT z,x FROM t2)
489 ** The reduced pX is different from the original (obviously) and thus is
490 ** only used for indexing, to improve performance. The original unaltered
491 ** IN expression must also be run on each output row for correctness.
493 static Expr
*removeUnindexableInClauseTerms(
494 Parse
*pParse
, /* The parsing context */
495 int iEq
, /* Look at loop terms starting here */
496 WhereLoop
*pLoop
, /* The current loop */
497 Expr
*pX
/* The IN expression to be reduced */
499 sqlite3
*db
= pParse
->db
;
500 Select
*pSelect
; /* Pointer to the SELECT on the RHS */
502 pNew
= sqlite3ExprDup(db
, pX
, 0);
503 if( db
->mallocFailed
==0 ){
504 for(pSelect
=pNew
->x
.pSelect
; pSelect
; pSelect
=pSelect
->pPrior
){
505 ExprList
*pOrigRhs
; /* Original unmodified RHS */
506 ExprList
*pOrigLhs
= 0; /* Original unmodified LHS */
507 ExprList
*pRhs
= 0; /* New RHS after modifications */
508 ExprList
*pLhs
= 0; /* New LHS after mods */
509 int i
; /* Loop counter */
511 assert( ExprUseXSelect(pNew
) );
512 pOrigRhs
= pSelect
->pEList
;
513 assert( pNew
->pLeft
!=0 );
514 assert( ExprUseXList(pNew
->pLeft
) );
515 if( pSelect
==pNew
->x
.pSelect
){
516 pOrigLhs
= pNew
->pLeft
->x
.pList
;
518 for(i
=iEq
; i
<pLoop
->nLTerm
; i
++){
519 if( pLoop
->aLTerm
[i
]->pExpr
==pX
){
521 assert( (pLoop
->aLTerm
[i
]->eOperator
& (WO_OR
|WO_AND
))==0 );
522 iField
= pLoop
->aLTerm
[i
]->u
.x
.iField
- 1;
523 if( pOrigRhs
->a
[iField
].pExpr
==0 ) continue; /* Duplicate PK column */
524 pRhs
= sqlite3ExprListAppend(pParse
, pRhs
, pOrigRhs
->a
[iField
].pExpr
);
525 pOrigRhs
->a
[iField
].pExpr
= 0;
527 assert( pOrigLhs
->a
[iField
].pExpr
!=0 );
528 pLhs
= sqlite3ExprListAppend(pParse
,pLhs
,pOrigLhs
->a
[iField
].pExpr
);
529 pOrigLhs
->a
[iField
].pExpr
= 0;
533 sqlite3ExprListDelete(db
, pOrigRhs
);
535 sqlite3ExprListDelete(db
, pOrigLhs
);
536 pNew
->pLeft
->x
.pList
= pLhs
;
538 pSelect
->pEList
= pRhs
;
539 if( pLhs
&& pLhs
->nExpr
==1 ){
540 /* Take care here not to generate a TK_VECTOR containing only a
541 ** single value. Since the parser never creates such a vector, some
542 ** of the subroutines do not handle this case. */
543 Expr
*p
= pLhs
->a
[0].pExpr
;
544 pLhs
->a
[0].pExpr
= 0;
545 sqlite3ExprDelete(db
, pNew
->pLeft
);
548 if( pSelect
->pOrderBy
){
549 /* If the SELECT statement has an ORDER BY clause, zero the
550 ** iOrderByCol variables. These are set to non-zero when an
551 ** ORDER BY term exactly matches one of the terms of the
552 ** result-set. Since the result-set of the SELECT statement may
553 ** have been modified or reordered, these variables are no longer
554 ** set correctly. Since setting them is just an optimization,
555 ** it's easiest just to zero them here. */
556 ExprList
*pOrderBy
= pSelect
->pOrderBy
;
557 for(i
=0; i
<pOrderBy
->nExpr
; i
++){
558 pOrderBy
->a
[i
].u
.x
.iOrderByCol
= 0;
563 printf("For indexing, change the IN expr:\n");
564 sqlite3TreeViewExpr(0, pX
, 0);
566 sqlite3TreeViewExpr(0, pNew
, 0);
575 ** Generate code for a single equality term of the WHERE clause. An equality
576 ** term can be either X=expr or X IN (...). pTerm is the term to be
579 ** The current value for the constraint is left in a register, the index
580 ** of which is returned. An attempt is made store the result in iTarget but
581 ** this is only guaranteed for TK_ISNULL and TK_IN constraints. If the
582 ** constraint is a TK_EQ or TK_IS, then the current value might be left in
583 ** some other register and it is the caller's responsibility to compensate.
585 ** For a constraint of the form X=expr, the expression is evaluated in
586 ** straight-line code. For constraints of the form X IN (...)
587 ** this routine sets up a loop that will iterate over all values of X.
589 static int codeEqualityTerm(
590 Parse
*pParse
, /* The parsing context */
591 WhereTerm
*pTerm
, /* The term of the WHERE clause to be coded */
592 WhereLevel
*pLevel
, /* The level of the FROM clause we are working on */
593 int iEq
, /* Index of the equality term within this level */
594 int bRev
, /* True for reverse-order IN operations */
595 int iTarget
/* Attempt to leave results in this register */
597 Expr
*pX
= pTerm
->pExpr
;
598 Vdbe
*v
= pParse
->pVdbe
;
599 int iReg
; /* Register holding results */
601 assert( pLevel
->pWLoop
->aLTerm
[iEq
]==pTerm
);
603 if( pX
->op
==TK_EQ
|| pX
->op
==TK_IS
){
604 iReg
= sqlite3ExprCodeTarget(pParse
, pX
->pRight
, iTarget
);
605 }else if( pX
->op
==TK_ISNULL
){
607 sqlite3VdbeAddOp2(v
, OP_Null
, 0, iReg
);
608 #ifndef SQLITE_OMIT_SUBQUERY
610 int eType
= IN_INDEX_NOOP
;
613 WhereLoop
*pLoop
= pLevel
->pWLoop
;
618 if( (pLoop
->wsFlags
& WHERE_VIRTUALTABLE
)==0
619 && pLoop
->u
.btree
.pIndex
!=0
620 && pLoop
->u
.btree
.pIndex
->aSortOrder
[iEq
]
626 assert( pX
->op
==TK_IN
);
629 for(i
=0; i
<iEq
; i
++){
630 if( pLoop
->aLTerm
[i
] && pLoop
->aLTerm
[i
]->pExpr
==pX
){
631 disableTerm(pLevel
, pTerm
);
635 for(i
=iEq
;i
<pLoop
->nLTerm
; i
++){
636 assert( pLoop
->aLTerm
[i
]!=0 );
637 if( pLoop
->aLTerm
[i
]->pExpr
==pX
) nEq
++;
641 if( !ExprUseXSelect(pX
) || pX
->x
.pSelect
->pEList
->nExpr
==1 ){
642 eType
= sqlite3FindInIndex(pParse
, pX
, IN_INDEX_LOOP
, 0, 0, &iTab
);
644 Expr
*pExpr
= pTerm
->pExpr
;
645 if( pExpr
->iTable
==0 || !ExprHasProperty(pExpr
, EP_Subrtn
) ){
646 sqlite3
*db
= pParse
->db
;
647 pX
= removeUnindexableInClauseTerms(pParse
, iEq
, pLoop
, pX
);
648 if( !db
->mallocFailed
){
649 aiMap
= (int*)sqlite3DbMallocZero(pParse
->db
, sizeof(int)*nEq
);
650 eType
= sqlite3FindInIndex(pParse
, pX
, IN_INDEX_LOOP
, 0, aiMap
,&iTab
);
651 pExpr
->iTable
= iTab
;
653 sqlite3ExprDelete(db
, pX
);
655 int n
= sqlite3ExprVectorSize(pX
->pLeft
);
656 aiMap
= (int*)sqlite3DbMallocZero(pParse
->db
, sizeof(int)*MAX(nEq
,n
));
657 eType
= sqlite3FindInIndex(pParse
, pX
, IN_INDEX_LOOP
, 0, aiMap
, &iTab
);
662 if( eType
==IN_INDEX_INDEX_DESC
){
666 sqlite3VdbeAddOp2(v
, bRev
? OP_Last
: OP_Rewind
, iTab
, 0);
667 VdbeCoverageIf(v
, bRev
);
668 VdbeCoverageIf(v
, !bRev
);
670 assert( (pLoop
->wsFlags
& WHERE_MULTI_OR
)==0 );
671 pLoop
->wsFlags
|= WHERE_IN_ABLE
;
672 if( pLevel
->u
.in
.nIn
==0 ){
673 pLevel
->addrNxt
= sqlite3VdbeMakeLabel(pParse
);
675 if( iEq
>0 && (pLoop
->wsFlags
& WHERE_IN_SEEKSCAN
)==0 ){
676 pLoop
->wsFlags
|= WHERE_IN_EARLYOUT
;
679 i
= pLevel
->u
.in
.nIn
;
680 pLevel
->u
.in
.nIn
+= nEq
;
681 pLevel
->u
.in
.aInLoop
=
682 sqlite3WhereRealloc(pTerm
->pWC
->pWInfo
,
683 pLevel
->u
.in
.aInLoop
,
684 sizeof(pLevel
->u
.in
.aInLoop
[0])*pLevel
->u
.in
.nIn
);
685 pIn
= pLevel
->u
.in
.aInLoop
;
687 int iMap
= 0; /* Index in aiMap[] */
689 for(i
=iEq
;i
<pLoop
->nLTerm
; i
++){
690 if( pLoop
->aLTerm
[i
]->pExpr
==pX
){
691 int iOut
= iReg
+ i
- iEq
;
692 if( eType
==IN_INDEX_ROWID
){
693 pIn
->addrInTop
= sqlite3VdbeAddOp2(v
, OP_Rowid
, iTab
, iOut
);
695 int iCol
= aiMap
? aiMap
[iMap
++] : 0;
696 pIn
->addrInTop
= sqlite3VdbeAddOp3(v
,OP_Column
,iTab
, iCol
, iOut
);
698 sqlite3VdbeAddOp1(v
, OP_IsNull
, iOut
); VdbeCoverage(v
);
701 pIn
->eEndLoopOp
= bRev
? OP_Prev
: OP_Next
;
703 pIn
->iBase
= iReg
- i
;
709 pIn
->eEndLoopOp
= OP_Noop
;
715 && (pLoop
->wsFlags
& WHERE_IN_SEEKSCAN
)==0
716 && (pLoop
->wsFlags
& WHERE_VIRTUALTABLE
)!=0 );
718 && (pLoop
->wsFlags
& (WHERE_IN_SEEKSCAN
|WHERE_VIRTUALTABLE
))==0
720 sqlite3VdbeAddOp3(v
, OP_SeekHit
, pLevel
->iIdxCur
, 0, iEq
);
723 pLevel
->u
.in
.nIn
= 0;
725 sqlite3DbFree(pParse
->db
, aiMap
);
729 /* As an optimization, try to disable the WHERE clause term that is
730 ** driving the index as it will always be true. The correct answer is
731 ** obtained regardless, but we might get the answer with fewer CPU cycles
732 ** by omitting the term.
734 ** But do not disable the term unless we are certain that the term is
735 ** not a transitive constraint. For an example of where that does not
736 ** work, see https://sqlite.org/forum/forumpost/eb8613976a (2021-05-04)
738 if( (pLevel
->pWLoop
->wsFlags
& WHERE_TRANSCONS
)==0
739 || (pTerm
->eOperator
& WO_EQUIV
)==0
741 disableTerm(pLevel
, pTerm
);
748 ** Generate code that will evaluate all == and IN constraints for an
751 ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
752 ** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
753 ** The index has as many as three equality constraints, but in this
754 ** example, the third "c" value is an inequality. So only two
755 ** constraints are coded. This routine will generate code to evaluate
756 ** a==5 and b IN (1,2,3). The current values for a and b will be stored
757 ** in consecutive registers and the index of the first register is returned.
759 ** In the example above nEq==2. But this subroutine works for any value
760 ** of nEq including 0. If nEq==0, this routine is nearly a no-op.
761 ** The only thing it does is allocate the pLevel->iMem memory cell and
762 ** compute the affinity string.
764 ** The nExtraReg parameter is 0 or 1. It is 0 if all WHERE clause constraints
765 ** are == or IN and are covered by the nEq. nExtraReg is 1 if there is
766 ** an inequality constraint (such as the "c>=5 AND c<10" in the example) that
767 ** occurs after the nEq quality constraints.
769 ** This routine allocates a range of nEq+nExtraReg memory cells and returns
770 ** the index of the first memory cell in that range. The code that
771 ** calls this routine will use that memory range to store keys for
772 ** start and termination conditions of the loop.
773 ** key value of the loop. If one or more IN operators appear, then
774 ** this routine allocates an additional nEq memory cells for internal
777 ** Before returning, *pzAff is set to point to a buffer containing a
778 ** copy of the column affinity string of the index allocated using
779 ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
780 ** with equality constraints that use BLOB or NONE affinity are set to
781 ** SQLITE_AFF_BLOB. This is to deal with SQL such as the following:
783 ** CREATE TABLE t1(a TEXT PRIMARY KEY, b);
784 ** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
786 ** In the example above, the index on t1(a) has TEXT affinity. But since
787 ** the right hand side of the equality constraint (t2.b) has BLOB/NONE affinity,
788 ** no conversion should be attempted before using a t2.b value as part of
789 ** a key to search the index. Hence the first byte in the returned affinity
790 ** string in this example would be set to SQLITE_AFF_BLOB.
792 static int codeAllEqualityTerms(
793 Parse
*pParse
, /* Parsing context */
794 WhereLevel
*pLevel
, /* Which nested loop of the FROM we are coding */
795 int bRev
, /* Reverse the order of IN operators */
796 int nExtraReg
, /* Number of extra registers to allocate */
797 char **pzAff
/* OUT: Set to point to affinity string */
799 u16 nEq
; /* The number of == or IN constraints to code */
800 u16 nSkip
; /* Number of left-most columns to skip */
801 Vdbe
*v
= pParse
->pVdbe
; /* The vm under construction */
802 Index
*pIdx
; /* The index being used for this loop */
803 WhereTerm
*pTerm
; /* A single constraint term */
804 WhereLoop
*pLoop
; /* The WhereLoop object */
805 int j
; /* Loop counter */
806 int regBase
; /* Base register */
807 int nReg
; /* Number of registers to allocate */
808 char *zAff
; /* Affinity string to return */
810 /* This module is only called on query plans that use an index. */
811 pLoop
= pLevel
->pWLoop
;
812 assert( (pLoop
->wsFlags
& WHERE_VIRTUALTABLE
)==0 );
813 nEq
= pLoop
->u
.btree
.nEq
;
814 nSkip
= pLoop
->nSkip
;
815 pIdx
= pLoop
->u
.btree
.pIndex
;
818 /* Figure out how many memory cells we will need then allocate them.
820 regBase
= pParse
->nMem
+ 1;
821 nReg
= nEq
+ nExtraReg
;
822 pParse
->nMem
+= nReg
;
824 zAff
= sqlite3DbStrDup(pParse
->db
,sqlite3IndexAffinityStr(pParse
->db
,pIdx
));
825 assert( zAff
!=0 || pParse
->db
->mallocFailed
);
828 int iIdxCur
= pLevel
->iIdxCur
;
829 sqlite3VdbeAddOp3(v
, OP_Null
, 0, regBase
, regBase
+nSkip
-1);
830 sqlite3VdbeAddOp1(v
, (bRev
?OP_Last
:OP_Rewind
), iIdxCur
);
831 VdbeCoverageIf(v
, bRev
==0);
832 VdbeCoverageIf(v
, bRev
!=0);
833 VdbeComment((v
, "begin skip-scan on %s", pIdx
->zName
));
834 j
= sqlite3VdbeAddOp0(v
, OP_Goto
);
835 assert( pLevel
->addrSkip
==0 );
836 pLevel
->addrSkip
= sqlite3VdbeAddOp4Int(v
, (bRev
?OP_SeekLT
:OP_SeekGT
),
837 iIdxCur
, 0, regBase
, nSkip
);
838 VdbeCoverageIf(v
, bRev
==0);
839 VdbeCoverageIf(v
, bRev
!=0);
840 sqlite3VdbeJumpHere(v
, j
);
841 for(j
=0; j
<nSkip
; j
++){
842 sqlite3VdbeAddOp3(v
, OP_Column
, iIdxCur
, j
, regBase
+j
);
843 testcase( pIdx
->aiColumn
[j
]==XN_EXPR
);
844 VdbeComment((v
, "%s", explainIndexColumnName(pIdx
, j
)));
848 /* Evaluate the equality constraints
850 assert( zAff
==0 || (int)strlen(zAff
)>=nEq
);
851 for(j
=nSkip
; j
<nEq
; j
++){
853 pTerm
= pLoop
->aLTerm
[j
];
855 /* The following testcase is true for indices with redundant columns.
856 ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
857 testcase( (pTerm
->wtFlags
& TERM_CODED
)!=0 );
858 testcase( pTerm
->wtFlags
& TERM_VIRTUAL
);
859 r1
= codeEqualityTerm(pParse
, pTerm
, pLevel
, j
, bRev
, regBase
+j
);
862 sqlite3ReleaseTempReg(pParse
, regBase
);
865 sqlite3VdbeAddOp2(v
, OP_Copy
, r1
, regBase
+j
);
868 if( pTerm
->eOperator
& WO_IN
){
869 if( pTerm
->pExpr
->flags
& EP_xIsSelect
){
870 /* No affinity ever needs to be (or should be) applied to a value
871 ** from the RHS of an "? IN (SELECT ...)" expression. The
872 ** sqlite3FindInIndex() routine has already ensured that the
873 ** affinity of the comparison has been applied to the value. */
874 if( zAff
) zAff
[j
] = SQLITE_AFF_BLOB
;
876 }else if( (pTerm
->eOperator
& WO_ISNULL
)==0 ){
877 Expr
*pRight
= pTerm
->pExpr
->pRight
;
878 if( (pTerm
->wtFlags
& TERM_IS
)==0 && sqlite3ExprCanBeNull(pRight
) ){
879 sqlite3VdbeAddOp2(v
, OP_IsNull
, regBase
+j
, pLevel
->addrBrk
);
882 if( pParse
->nErr
==0 ){
883 assert( pParse
->db
->mallocFailed
==0 );
884 if( sqlite3CompareAffinity(pRight
, zAff
[j
])==SQLITE_AFF_BLOB
){
885 zAff
[j
] = SQLITE_AFF_BLOB
;
887 if( sqlite3ExprNeedsNoAffinityChange(pRight
, zAff
[j
]) ){
888 zAff
[j
] = SQLITE_AFF_BLOB
;
897 #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
899 ** If the most recently coded instruction is a constant range constraint
900 ** (a string literal) that originated from the LIKE optimization, then
901 ** set P3 and P5 on the OP_String opcode so that the string will be cast
902 ** to a BLOB at appropriate times.
904 ** The LIKE optimization trys to evaluate "x LIKE 'abc%'" as a range
905 ** expression: "x>='ABC' AND x<'abd'". But this requires that the range
906 ** scan loop run twice, once for strings and a second time for BLOBs.
907 ** The OP_String opcodes on the second pass convert the upper and lower
908 ** bound string constants to blobs. This routine makes the necessary changes
909 ** to the OP_String opcodes for that to happen.
911 ** Except, of course, if SQLITE_LIKE_DOESNT_MATCH_BLOBS is defined, then
912 ** only the one pass through the string space is required, so this routine
915 static void whereLikeOptimizationStringFixup(
916 Vdbe
*v
, /* prepared statement under construction */
917 WhereLevel
*pLevel
, /* The loop that contains the LIKE operator */
918 WhereTerm
*pTerm
/* The upper or lower bound just coded */
920 if( pTerm
->wtFlags
& TERM_LIKEOPT
){
922 assert( pLevel
->iLikeRepCntr
>0 );
923 pOp
= sqlite3VdbeGetLastOp(v
);
925 assert( pOp
->opcode
==OP_String8
926 || pTerm
->pWC
->pWInfo
->pParse
->db
->mallocFailed
);
927 pOp
->p3
= (int)(pLevel
->iLikeRepCntr
>>1); /* Register holding counter */
928 pOp
->p5
= (u8
)(pLevel
->iLikeRepCntr
&1); /* ASC or DESC */
932 # define whereLikeOptimizationStringFixup(A,B,C)
935 #ifdef SQLITE_ENABLE_CURSOR_HINTS
937 ** Information is passed from codeCursorHint() down to individual nodes of
938 ** the expression tree (by sqlite3WalkExpr()) using an instance of this
942 int iTabCur
; /* Cursor for the main table */
943 int iIdxCur
; /* Cursor for the index, if pIdx!=0. Unused otherwise */
944 Index
*pIdx
; /* The index used to access the table */
948 ** This function is called for every node of an expression that is a candidate
949 ** for a cursor hint on an index cursor. For TK_COLUMN nodes that reference
950 ** the table CCurHint.iTabCur, verify that the same column can be
951 ** accessed through the index. If it cannot, then set pWalker->eCode to 1.
953 static int codeCursorHintCheckExpr(Walker
*pWalker
, Expr
*pExpr
){
954 struct CCurHint
*pHint
= pWalker
->u
.pCCurHint
;
955 assert( pHint
->pIdx
!=0 );
956 if( pExpr
->op
==TK_COLUMN
957 && pExpr
->iTable
==pHint
->iTabCur
958 && sqlite3TableColumnToIndex(pHint
->pIdx
, pExpr
->iColumn
)<0
966 ** Test whether or not expression pExpr, which was part of a WHERE clause,
967 ** should be included in the cursor-hint for a table that is on the rhs
968 ** of a LEFT JOIN. Set Walker.eCode to non-zero before returning if the
969 ** expression is not suitable.
971 ** An expression is unsuitable if it might evaluate to non NULL even if
972 ** a TK_COLUMN node that does affect the value of the expression is set
973 ** to NULL. For example:
978 ** CASE WHEN col THEN 0 ELSE 1 END
980 static int codeCursorHintIsOrFunction(Walker
*pWalker
, Expr
*pExpr
){
982 || pExpr
->op
==TK_ISNULL
|| pExpr
->op
==TK_ISNOT
983 || pExpr
->op
==TK_NOTNULL
|| pExpr
->op
==TK_CASE
986 }else if( pExpr
->op
==TK_FUNCTION
){
989 if( 0==sqlite3IsLikeFunction(pWalker
->pParse
->db
, pExpr
, &d1
, d2
) ){
999 ** This function is called on every node of an expression tree used as an
1000 ** argument to the OP_CursorHint instruction. If the node is a TK_COLUMN
1001 ** that accesses any table other than the one identified by
1002 ** CCurHint.iTabCur, then do the following:
1004 ** 1) allocate a register and code an OP_Column instruction to read
1005 ** the specified column into the new register, and
1007 ** 2) transform the expression node to a TK_REGISTER node that reads
1008 ** from the newly populated register.
1010 ** Also, if the node is a TK_COLUMN that does access the table identified
1011 ** by pCCurHint.iTabCur, and an index is being used (which we will
1012 ** know because CCurHint.pIdx!=0) then transform the TK_COLUMN into
1013 ** an access of the index rather than the original table.
1015 static int codeCursorHintFixExpr(Walker
*pWalker
, Expr
*pExpr
){
1016 int rc
= WRC_Continue
;
1018 struct CCurHint
*pHint
= pWalker
->u
.pCCurHint
;
1019 if( pExpr
->op
==TK_COLUMN
){
1020 if( pExpr
->iTable
!=pHint
->iTabCur
){
1021 reg
= ++pWalker
->pParse
->nMem
; /* Register for column value */
1022 reg
= sqlite3ExprCodeTarget(pWalker
->pParse
, pExpr
, reg
);
1023 pExpr
->op
= TK_REGISTER
;
1024 pExpr
->iTable
= reg
;
1025 }else if( pHint
->pIdx
!=0 ){
1026 pExpr
->iTable
= pHint
->iIdxCur
;
1027 pExpr
->iColumn
= sqlite3TableColumnToIndex(pHint
->pIdx
, pExpr
->iColumn
);
1028 assert( pExpr
->iColumn
>=0 );
1030 }else if( pExpr
->pAggInfo
){
1032 reg
= ++pWalker
->pParse
->nMem
; /* Register for column value */
1033 reg
= sqlite3ExprCodeTarget(pWalker
->pParse
, pExpr
, reg
);
1034 pExpr
->op
= TK_REGISTER
;
1035 pExpr
->iTable
= reg
;
1036 }else if( pExpr
->op
==TK_TRUEFALSE
){
1037 /* Do not walk disabled expressions. tag-20230504-1 */
1044 ** Insert an OP_CursorHint instruction if it is appropriate to do so.
1046 static void codeCursorHint(
1047 SrcItem
*pTabItem
, /* FROM clause item */
1048 WhereInfo
*pWInfo
, /* The where clause */
1049 WhereLevel
*pLevel
, /* Which loop to provide hints for */
1050 WhereTerm
*pEndRange
/* Hint this end-of-scan boundary term if not NULL */
1052 Parse
*pParse
= pWInfo
->pParse
;
1053 sqlite3
*db
= pParse
->db
;
1054 Vdbe
*v
= pParse
->pVdbe
;
1056 WhereLoop
*pLoop
= pLevel
->pWLoop
;
1061 struct CCurHint sHint
;
1064 if( OptimizationDisabled(db
, SQLITE_CursorHints
) ) return;
1065 iCur
= pLevel
->iTabCur
;
1066 assert( iCur
==pWInfo
->pTabList
->a
[pLevel
->iFrom
].iCursor
);
1067 sHint
.iTabCur
= iCur
;
1068 sHint
.iIdxCur
= pLevel
->iIdxCur
;
1069 sHint
.pIdx
= pLoop
->u
.btree
.pIndex
;
1070 memset(&sWalker
, 0, sizeof(sWalker
));
1071 sWalker
.pParse
= pParse
;
1072 sWalker
.u
.pCCurHint
= &sHint
;
1074 for(i
=0; i
<pWC
->nBase
; i
++){
1076 if( pTerm
->wtFlags
& (TERM_VIRTUAL
|TERM_CODED
) ) continue;
1077 if( pTerm
->prereqAll
& pLevel
->notReady
) continue;
1079 /* Any terms specified as part of the ON(...) clause for any LEFT
1080 ** JOIN for which the current table is not the rhs are omitted
1081 ** from the cursor-hint.
1083 ** If this table is the rhs of a LEFT JOIN, "IS" or "IS NULL" terms
1084 ** that were specified as part of the WHERE clause must be excluded.
1085 ** This is to address the following:
1087 ** SELECT ... t1 LEFT JOIN t2 ON (t1.a=t2.b) WHERE t2.c IS NULL;
1089 ** Say there is a single row in t2 that matches (t1.a=t2.b), but its
1090 ** t2.c values is not NULL. If the (t2.c IS NULL) constraint is
1091 ** pushed down to the cursor, this row is filtered out, causing
1092 ** SQLite to synthesize a row of NULL values. Which does match the
1093 ** WHERE clause, and so the query returns a row. Which is incorrect.
1095 ** For the same reason, WHERE terms such as:
1097 ** WHERE 1 = (t2.c IS NULL)
1099 ** are also excluded. See codeCursorHintIsOrFunction() for details.
1101 if( pTabItem
->fg
.jointype
& JT_LEFT
){
1102 Expr
*pExpr
= pTerm
->pExpr
;
1103 if( !ExprHasProperty(pExpr
, EP_OuterON
)
1104 || pExpr
->w
.iJoin
!=pTabItem
->iCursor
1107 sWalker
.xExprCallback
= codeCursorHintIsOrFunction
;
1108 sqlite3WalkExpr(&sWalker
, pTerm
->pExpr
);
1109 if( sWalker
.eCode
) continue;
1112 if( ExprHasProperty(pTerm
->pExpr
, EP_OuterON
) ) continue;
1115 /* All terms in pWLoop->aLTerm[] except pEndRange are used to initialize
1116 ** the cursor. These terms are not needed as hints for a pure range
1117 ** scan (that has no == terms) so omit them. */
1118 if( pLoop
->u
.btree
.nEq
==0 && pTerm
!=pEndRange
){
1119 for(j
=0; j
<pLoop
->nLTerm
&& pLoop
->aLTerm
[j
]!=pTerm
; j
++){}
1120 if( j
<pLoop
->nLTerm
) continue;
1123 /* No subqueries or non-deterministic functions allowed */
1124 if( sqlite3ExprContainsSubquery(pTerm
->pExpr
) ) continue;
1126 /* For an index scan, make sure referenced columns are actually in
1128 if( sHint
.pIdx
!=0 ){
1130 sWalker
.xExprCallback
= codeCursorHintCheckExpr
;
1131 sqlite3WalkExpr(&sWalker
, pTerm
->pExpr
);
1132 if( sWalker
.eCode
) continue;
1135 /* If we survive all prior tests, that means this term is worth hinting */
1136 pExpr
= sqlite3ExprAnd(pParse
, pExpr
, sqlite3ExprDup(db
, pTerm
->pExpr
, 0));
1139 sWalker
.xExprCallback
= codeCursorHintFixExpr
;
1140 if( pParse
->nErr
==0 ) sqlite3WalkExpr(&sWalker
, pExpr
);
1141 sqlite3VdbeAddOp4(v
, OP_CursorHint
,
1142 (sHint
.pIdx
? sHint
.iIdxCur
: sHint
.iTabCur
), 0, 0,
1143 (const char*)pExpr
, P4_EXPR
);
1147 # define codeCursorHint(A,B,C,D) /* No-op */
1148 #endif /* SQLITE_ENABLE_CURSOR_HINTS */
1151 ** Cursor iCur is open on an intkey b-tree (a table). Register iRowid contains
1152 ** a rowid value just read from cursor iIdxCur, open on index pIdx. This
1153 ** function generates code to do a deferred seek of cursor iCur to the
1154 ** rowid stored in register iRowid.
1156 ** Normally, this is just:
1158 ** OP_DeferredSeek $iCur $iRowid
1160 ** Which causes a seek on $iCur to the row with rowid $iRowid.
1162 ** However, if the scan currently being coded is a branch of an OR-loop and
1163 ** the statement currently being coded is a SELECT, then additional information
1164 ** is added that might allow OP_Column to omit the seek and instead do its
1165 ** lookup on the index, thus avoiding an expensive seek operation. To
1166 ** enable this optimization, the P3 of OP_DeferredSeek is set to iIdxCur
1167 ** and P4 is set to an array of integers containing one entry for each column
1168 ** in the table. For each table column, if the column is the i'th
1169 ** column of the index, then the corresponding array entry is set to (i+1).
1170 ** If the column does not appear in the index at all, the array entry is set
1171 ** to 0. The OP_Column opcode can check this array to see if the column it
1172 ** wants is in the index and if it is, it will substitute the index cursor
1173 ** and column number and continue with those new values, rather than seeking
1174 ** the table cursor.
1176 static void codeDeferredSeek(
1177 WhereInfo
*pWInfo
, /* Where clause context */
1178 Index
*pIdx
, /* Index scan is using */
1179 int iCur
, /* Cursor for IPK b-tree */
1180 int iIdxCur
/* Index cursor */
1182 Parse
*pParse
= pWInfo
->pParse
; /* Parse context */
1183 Vdbe
*v
= pParse
->pVdbe
; /* Vdbe to generate code within */
1185 assert( iIdxCur
>0 );
1186 assert( pIdx
->aiColumn
[pIdx
->nColumn
-1]==-1 );
1188 pWInfo
->bDeferredSeek
= 1;
1189 sqlite3VdbeAddOp3(v
, OP_DeferredSeek
, iIdxCur
, 0, iCur
);
1190 if( (pWInfo
->wctrlFlags
& (WHERE_OR_SUBCLAUSE
|WHERE_RIGHT_JOIN
))
1191 && DbMaskAllZero(sqlite3ParseToplevel(pParse
)->writeMask
)
1194 Table
*pTab
= pIdx
->pTable
;
1195 u32
*ai
= (u32
*)sqlite3DbMallocZero(pParse
->db
, sizeof(u32
)*(pTab
->nCol
+1));
1198 for(i
=0; i
<pIdx
->nColumn
-1; i
++){
1200 assert( pIdx
->aiColumn
[i
]<pTab
->nCol
);
1201 x1
= pIdx
->aiColumn
[i
];
1202 x2
= sqlite3TableColumnToStorage(pTab
, x1
);
1204 if( x1
>=0 ) ai
[x2
+1] = i
+1;
1206 sqlite3VdbeChangeP4(v
, -1, (char*)ai
, P4_INTARRAY
);
1212 ** If the expression passed as the second argument is a vector, generate
1213 ** code to write the first nReg elements of the vector into an array
1214 ** of registers starting with iReg.
1216 ** If the expression is not a vector, then nReg must be passed 1. In
1217 ** this case, generate code to evaluate the expression and leave the
1218 ** result in register iReg.
1220 static void codeExprOrVector(Parse
*pParse
, Expr
*p
, int iReg
, int nReg
){
1222 if( p
&& sqlite3ExprIsVector(p
) ){
1223 #ifndef SQLITE_OMIT_SUBQUERY
1224 if( ExprUseXSelect(p
) ){
1225 Vdbe
*v
= pParse
->pVdbe
;
1227 assert( p
->op
==TK_SELECT
);
1228 iSelect
= sqlite3CodeSubselect(pParse
, p
);
1229 sqlite3VdbeAddOp3(v
, OP_Copy
, iSelect
, iReg
, nReg
-1);
1234 const ExprList
*pList
;
1235 assert( ExprUseXList(p
) );
1237 assert( nReg
<=pList
->nExpr
);
1238 for(i
=0; i
<nReg
; i
++){
1239 sqlite3ExprCode(pParse
, pList
->a
[i
].pExpr
, iReg
+i
);
1243 assert( nReg
==1 || pParse
->nErr
);
1244 sqlite3ExprCode(pParse
, p
, iReg
);
1249 ** The pTruth expression is always true because it is the WHERE clause
1250 ** a partial index that is driving a query loop. Look through all of the
1251 ** WHERE clause terms on the query, and if any of those terms must be
1252 ** true because pTruth is true, then mark those WHERE clause terms as
1255 static void whereApplyPartialIndexConstraints(
1262 while( pTruth
->op
==TK_AND
){
1263 whereApplyPartialIndexConstraints(pTruth
->pLeft
, iTabCur
, pWC
);
1264 pTruth
= pTruth
->pRight
;
1266 for(i
=0, pTerm
=pWC
->a
; i
<pWC
->nTerm
; i
++, pTerm
++){
1268 if( pTerm
->wtFlags
& TERM_CODED
) continue;
1269 pExpr
= pTerm
->pExpr
;
1270 if( sqlite3ExprCompare(0, pExpr
, pTruth
, iTabCur
)==0 ){
1271 pTerm
->wtFlags
|= TERM_CODED
;
1277 ** This routine is called right after An OP_Filter has been generated and
1278 ** before the corresponding index search has been performed. This routine
1279 ** checks to see if there are additional Bloom filters in inner loops that
1280 ** can be checked prior to doing the index lookup. If there are available
1281 ** inner-loop Bloom filters, then evaluate those filters now, before the
1282 ** index lookup. The idea is that a Bloom filter check is way faster than
1283 ** an index lookup, and the Bloom filter might return false, meaning that
1284 ** the index lookup can be skipped.
1286 ** We know that an inner loop uses a Bloom filter because it has the
1287 ** WhereLevel.regFilter set. If an inner-loop Bloom filter is checked,
1288 ** then clear the WhereLevel.regFilter value to prevent the Bloom filter
1289 ** from being checked a second time when the inner loop is evaluated.
1291 static SQLITE_NOINLINE
void filterPullDown(
1292 Parse
*pParse
, /* Parsing context */
1293 WhereInfo
*pWInfo
, /* Complete information about the WHERE clause */
1294 int iLevel
, /* Which level of pWInfo->a[] should be coded */
1295 int addrNxt
, /* Jump here to bypass inner loops */
1296 Bitmask notReady
/* Loops that are not ready */
1298 while( ++iLevel
< pWInfo
->nLevel
){
1299 WhereLevel
*pLevel
= &pWInfo
->a
[iLevel
];
1300 WhereLoop
*pLoop
= pLevel
->pWLoop
;
1301 if( pLevel
->regFilter
==0 ) continue;
1302 if( pLevel
->pWLoop
->nSkip
) continue;
1303 /* ,--- Because sqlite3ConstructBloomFilter() has will not have set
1304 ** vvvvv--' pLevel->regFilter if this were true. */
1305 if( NEVER(pLoop
->prereq
& notReady
) ) continue;
1306 assert( pLevel
->addrBrk
==0 );
1307 pLevel
->addrBrk
= addrNxt
;
1308 if( pLoop
->wsFlags
& WHERE_IPK
){
1309 WhereTerm
*pTerm
= pLoop
->aLTerm
[0];
1312 assert( pTerm
->pExpr
!=0 );
1313 testcase( pTerm
->wtFlags
& TERM_VIRTUAL
);
1314 regRowid
= sqlite3GetTempReg(pParse
);
1315 regRowid
= codeEqualityTerm(pParse
, pTerm
, pLevel
, 0, 0, regRowid
);
1316 sqlite3VdbeAddOp2(pParse
->pVdbe
, OP_MustBeInt
, regRowid
, addrNxt
);
1317 VdbeCoverage(pParse
->pVdbe
);
1318 sqlite3VdbeAddOp4Int(pParse
->pVdbe
, OP_Filter
, pLevel
->regFilter
,
1319 addrNxt
, regRowid
, 1);
1320 VdbeCoverage(pParse
->pVdbe
);
1322 u16 nEq
= pLoop
->u
.btree
.nEq
;
1326 assert( pLoop
->wsFlags
& WHERE_INDEXED
);
1327 assert( (pLoop
->wsFlags
& WHERE_COLUMN_IN
)==0 );
1328 r1
= codeAllEqualityTerms(pParse
,pLevel
,0,0,&zStartAff
);
1329 codeApplyAffinity(pParse
, r1
, nEq
, zStartAff
);
1330 sqlite3DbFree(pParse
->db
, zStartAff
);
1331 sqlite3VdbeAddOp4Int(pParse
->pVdbe
, OP_Filter
, pLevel
->regFilter
,
1333 VdbeCoverage(pParse
->pVdbe
);
1335 pLevel
->regFilter
= 0;
1336 pLevel
->addrBrk
= 0;
1341 ** Loop pLoop is a WHERE_INDEXED level that uses at least one IN(...)
1342 ** operator. Return true if level pLoop is guaranteed to visit only one
1343 ** row for each key generated for the index.
1345 static int whereLoopIsOneRow(WhereLoop
*pLoop
){
1346 if( pLoop
->u
.btree
.pIndex
->onError
1348 && pLoop
->u
.btree
.nEq
==pLoop
->u
.btree
.pIndex
->nKeyCol
1351 for(ii
=0; ii
<pLoop
->u
.btree
.nEq
; ii
++){
1352 if( pLoop
->aLTerm
[ii
]->eOperator
& (WO_IS
|WO_ISNULL
) ){
1362 ** Generate code for the start of the iLevel-th loop in the WHERE clause
1363 ** implementation described by pWInfo.
1365 Bitmask
sqlite3WhereCodeOneLoopStart(
1366 Parse
*pParse
, /* Parsing context */
1367 Vdbe
*v
, /* Prepared statement under construction */
1368 WhereInfo
*pWInfo
, /* Complete information about the WHERE clause */
1369 int iLevel
, /* Which level of pWInfo->a[] should be coded */
1370 WhereLevel
*pLevel
, /* The current level pointer */
1371 Bitmask notReady
/* Which tables are currently available */
1373 int j
, k
; /* Loop counters */
1374 int iCur
; /* The VDBE cursor for the table */
1375 int addrNxt
; /* Where to jump to continue with the next IN case */
1376 int bRev
; /* True if we need to scan in reverse order */
1377 WhereLoop
*pLoop
; /* The WhereLoop object being coded */
1378 WhereClause
*pWC
; /* Decomposition of the entire WHERE clause */
1379 WhereTerm
*pTerm
; /* A WHERE clause term */
1380 sqlite3
*db
; /* Database connection */
1381 SrcItem
*pTabItem
; /* FROM clause term being coded */
1382 int addrBrk
; /* Jump here to break out of the loop */
1383 int addrHalt
; /* addrBrk for the outermost loop */
1384 int addrCont
; /* Jump here to continue with next cycle */
1385 int iRowidReg
= 0; /* Rowid is stored in this register, if not zero */
1386 int iReleaseReg
= 0; /* Temp register to free before returning */
1387 Index
*pIdx
= 0; /* Index used by loop (if any) */
1388 int iLoop
; /* Iteration of constraint generator loop */
1392 pLoop
= pLevel
->pWLoop
;
1393 pTabItem
= &pWInfo
->pTabList
->a
[pLevel
->iFrom
];
1394 iCur
= pTabItem
->iCursor
;
1395 pLevel
->notReady
= notReady
& ~sqlite3WhereGetMask(&pWInfo
->sMaskSet
, iCur
);
1396 bRev
= (pWInfo
->revMask
>>iLevel
)&1;
1397 VdbeModuleComment((v
, "Begin WHERE-loop%d: %s",iLevel
,pTabItem
->pTab
->zName
));
1398 #if WHERETRACE_ENABLED /* 0x4001 */
1399 if( sqlite3WhereTrace
& 0x1 ){
1400 sqlite3DebugPrintf("Coding level %d of %d: notReady=%llx iFrom=%d\n",
1401 iLevel
, pWInfo
->nLevel
, (u64
)notReady
, pLevel
->iFrom
);
1402 if( sqlite3WhereTrace
& 0x1000 ){
1403 sqlite3WhereLoopPrint(pLoop
, pWC
);
1406 if( (sqlite3WhereTrace
& 0x4001)==0x4001 ){
1408 sqlite3DebugPrintf("WHERE clause being coded:\n");
1409 sqlite3TreeViewExpr(0, pWInfo
->pWhere
, 0);
1411 sqlite3DebugPrintf("All WHERE-clause terms before coding:\n");
1412 sqlite3WhereClausePrint(pWC
);
1416 /* Create labels for the "break" and "continue" instructions
1417 ** for the current loop. Jump to addrBrk to break out of a loop.
1418 ** Jump to cont to go immediately to the next iteration of the
1421 ** When there is an IN operator, we also have a "addrNxt" label that
1422 ** means to continue with the next IN value combination. When
1423 ** there are no IN operators in the constraints, the "addrNxt" label
1424 ** is the same as "addrBrk".
1426 addrBrk
= pLevel
->addrBrk
= pLevel
->addrNxt
= sqlite3VdbeMakeLabel(pParse
);
1427 addrCont
= pLevel
->addrCont
= sqlite3VdbeMakeLabel(pParse
);
1429 /* If this is the right table of a LEFT OUTER JOIN, allocate and
1430 ** initialize a memory cell that records if this table matches any
1431 ** row of the left table of the join.
1433 assert( (pWInfo
->wctrlFlags
& (WHERE_OR_SUBCLAUSE
|WHERE_RIGHT_JOIN
))
1434 || pLevel
->iFrom
>0 || (pTabItem
[0].fg
.jointype
& JT_LEFT
)==0
1436 if( pLevel
->iFrom
>0 && (pTabItem
[0].fg
.jointype
& JT_LEFT
)!=0 ){
1437 pLevel
->iLeftJoin
= ++pParse
->nMem
;
1438 sqlite3VdbeAddOp2(v
, OP_Integer
, 0, pLevel
->iLeftJoin
);
1439 VdbeComment((v
, "init LEFT JOIN match flag"));
1442 /* Compute a safe address to jump to if we discover that the table for
1443 ** this loop is empty and can never contribute content. */
1444 for(j
=iLevel
; j
>0; j
--){
1445 if( pWInfo
->a
[j
].iLeftJoin
) break;
1446 if( pWInfo
->a
[j
].pRJ
) break;
1448 addrHalt
= pWInfo
->a
[j
].addrBrk
;
1450 /* Special case of a FROM clause subquery implemented as a co-routine */
1451 if( pTabItem
->fg
.viaCoroutine
){
1452 int regYield
= pTabItem
->regReturn
;
1453 sqlite3VdbeAddOp3(v
, OP_InitCoroutine
, regYield
, 0, pTabItem
->addrFillSub
);
1454 pLevel
->p2
= sqlite3VdbeAddOp2(v
, OP_Yield
, regYield
, addrBrk
);
1456 VdbeComment((v
, "next row of %s", pTabItem
->pTab
->zName
));
1457 pLevel
->op
= OP_Goto
;
1460 #ifndef SQLITE_OMIT_VIRTUALTABLE
1461 if( (pLoop
->wsFlags
& WHERE_VIRTUALTABLE
)!=0 ){
1462 /* Case 1: The table is a virtual-table. Use the VFilter and VNext
1463 ** to access the data.
1465 int iReg
; /* P3 Value for OP_VFilter */
1467 int nConstraint
= pLoop
->nLTerm
;
1469 iReg
= sqlite3GetTempRange(pParse
, nConstraint
+2);
1470 addrNotFound
= pLevel
->addrBrk
;
1471 for(j
=0; j
<nConstraint
; j
++){
1472 int iTarget
= iReg
+j
+2;
1473 pTerm
= pLoop
->aLTerm
[j
];
1474 if( NEVER(pTerm
==0) ) continue;
1475 if( pTerm
->eOperator
& WO_IN
){
1476 if( SMASKBIT32(j
) & pLoop
->u
.vtab
.mHandleIn
){
1477 int iTab
= pParse
->nTab
++;
1478 int iCache
= ++pParse
->nMem
;
1479 sqlite3CodeRhsOfIN(pParse
, pTerm
->pExpr
, iTab
);
1480 sqlite3VdbeAddOp3(v
, OP_VInitIn
, iTab
, iTarget
, iCache
);
1482 codeEqualityTerm(pParse
, pTerm
, pLevel
, j
, bRev
, iTarget
);
1483 addrNotFound
= pLevel
->addrNxt
;
1486 Expr
*pRight
= pTerm
->pExpr
->pRight
;
1487 codeExprOrVector(pParse
, pRight
, iTarget
, 1);
1488 if( pTerm
->eMatchOp
==SQLITE_INDEX_CONSTRAINT_OFFSET
1489 && pLoop
->u
.vtab
.bOmitOffset
1491 assert( pTerm
->eOperator
==WO_AUX
);
1492 assert( pWInfo
->pSelect
!=0 );
1493 assert( pWInfo
->pSelect
->iOffset
>0 );
1494 sqlite3VdbeAddOp2(v
, OP_Integer
, 0, pWInfo
->pSelect
->iOffset
);
1495 VdbeComment((v
,"Zero OFFSET counter"));
1499 sqlite3VdbeAddOp2(v
, OP_Integer
, pLoop
->u
.vtab
.idxNum
, iReg
);
1500 sqlite3VdbeAddOp2(v
, OP_Integer
, nConstraint
, iReg
+1);
1501 sqlite3VdbeAddOp4(v
, OP_VFilter
, iCur
, addrNotFound
, iReg
,
1502 pLoop
->u
.vtab
.idxStr
,
1503 pLoop
->u
.vtab
.needFree
? P4_DYNAMIC
: P4_STATIC
);
1505 pLoop
->u
.vtab
.needFree
= 0;
1506 /* An OOM inside of AddOp4(OP_VFilter) instruction above might have freed
1507 ** the u.vtab.idxStr. NULL it out to prevent a use-after-free */
1508 if( db
->mallocFailed
) pLoop
->u
.vtab
.idxStr
= 0;
1510 pLevel
->op
= pWInfo
->eOnePass
? OP_Noop
: OP_VNext
;
1511 pLevel
->p2
= sqlite3VdbeCurrentAddr(v
);
1512 assert( (pLoop
->wsFlags
& WHERE_MULTI_OR
)==0 );
1514 for(j
=0; j
<nConstraint
; j
++){
1515 pTerm
= pLoop
->aLTerm
[j
];
1516 if( j
<16 && (pLoop
->u
.vtab
.omitMask
>>j
)&1 ){
1517 disableTerm(pLevel
, pTerm
);
1520 if( (pTerm
->eOperator
& WO_IN
)!=0
1521 && (SMASKBIT32(j
) & pLoop
->u
.vtab
.mHandleIn
)==0
1522 && !db
->mallocFailed
1524 Expr
*pCompare
; /* The comparison operator */
1525 Expr
*pRight
; /* RHS of the comparison */
1526 VdbeOp
*pOp
; /* Opcode to access the value of the IN constraint */
1527 int iIn
; /* IN loop corresponding to the j-th constraint */
1529 /* Reload the constraint value into reg[iReg+j+2]. The same value
1530 ** was loaded into the same register prior to the OP_VFilter, but
1531 ** the xFilter implementation might have changed the datatype or
1532 ** encoding of the value in the register, so it *must* be reloaded.
1534 for(iIn
=0; ALWAYS(iIn
<pLevel
->u
.in
.nIn
); iIn
++){
1535 pOp
= sqlite3VdbeGetOp(v
, pLevel
->u
.in
.aInLoop
[iIn
].addrInTop
);
1536 if( (pOp
->opcode
==OP_Column
&& pOp
->p3
==iReg
+j
+2)
1537 || (pOp
->opcode
==OP_Rowid
&& pOp
->p2
==iReg
+j
+2)
1539 testcase( pOp
->opcode
==OP_Rowid
);
1540 sqlite3VdbeAddOp3(v
, pOp
->opcode
, pOp
->p1
, pOp
->p2
, pOp
->p3
);
1545 /* Generate code that will continue to the next row if
1546 ** the IN constraint is not satisfied
1548 pCompare
= sqlite3PExpr(pParse
, TK_EQ
, 0, 0);
1549 if( !db
->mallocFailed
){
1550 int iFld
= pTerm
->u
.x
.iField
;
1551 Expr
*pLeft
= pTerm
->pExpr
->pLeft
;
1554 assert( pLeft
->op
==TK_VECTOR
);
1555 assert( ExprUseXList(pLeft
) );
1556 assert( iFld
<=pLeft
->x
.pList
->nExpr
);
1557 pCompare
->pLeft
= pLeft
->x
.pList
->a
[iFld
-1].pExpr
;
1559 pCompare
->pLeft
= pLeft
;
1561 pCompare
->pRight
= pRight
= sqlite3Expr(db
, TK_REGISTER
, 0);
1563 pRight
->iTable
= iReg
+j
+2;
1565 pParse
, pCompare
, pLevel
->addrCont
, SQLITE_JUMPIFNULL
1568 pCompare
->pLeft
= 0;
1570 sqlite3ExprDelete(db
, pCompare
);
1574 /* These registers need to be preserved in case there is an IN operator
1575 ** loop. So we could deallocate the registers here (and potentially
1576 ** reuse them later) if (pLoop->wsFlags & WHERE_IN_ABLE)==0. But it seems
1577 ** simpler and safer to simply not reuse the registers.
1579 ** sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
1582 #endif /* SQLITE_OMIT_VIRTUALTABLE */
1584 if( (pLoop
->wsFlags
& WHERE_IPK
)!=0
1585 && (pLoop
->wsFlags
& (WHERE_COLUMN_IN
|WHERE_COLUMN_EQ
))!=0
1587 /* Case 2: We can directly reference a single row using an
1588 ** equality comparison against the ROWID field. Or
1589 ** we reference multiple rows using a "rowid IN (...)"
1592 assert( pLoop
->u
.btree
.nEq
==1 );
1593 pTerm
= pLoop
->aLTerm
[0];
1595 assert( pTerm
->pExpr
!=0 );
1596 testcase( pTerm
->wtFlags
& TERM_VIRTUAL
);
1597 iReleaseReg
= ++pParse
->nMem
;
1598 iRowidReg
= codeEqualityTerm(pParse
, pTerm
, pLevel
, 0, bRev
, iReleaseReg
);
1599 if( iRowidReg
!=iReleaseReg
) sqlite3ReleaseTempReg(pParse
, iReleaseReg
);
1600 addrNxt
= pLevel
->addrNxt
;
1601 if( pLevel
->regFilter
){
1602 sqlite3VdbeAddOp2(v
, OP_MustBeInt
, iRowidReg
, addrNxt
);
1604 sqlite3VdbeAddOp4Int(v
, OP_Filter
, pLevel
->regFilter
, addrNxt
,
1607 filterPullDown(pParse
, pWInfo
, iLevel
, addrNxt
, notReady
);
1609 sqlite3VdbeAddOp3(v
, OP_SeekRowid
, iCur
, addrNxt
, iRowidReg
);
1611 pLevel
->op
= OP_Noop
;
1612 }else if( (pLoop
->wsFlags
& WHERE_IPK
)!=0
1613 && (pLoop
->wsFlags
& WHERE_COLUMN_RANGE
)!=0
1615 /* Case 3: We have an inequality comparison against the ROWID field.
1617 int testOp
= OP_Noop
;
1619 int memEndValue
= 0;
1620 WhereTerm
*pStart
, *pEnd
;
1624 if( pLoop
->wsFlags
& WHERE_BTM_LIMIT
) pStart
= pLoop
->aLTerm
[j
++];
1625 if( pLoop
->wsFlags
& WHERE_TOP_LIMIT
) pEnd
= pLoop
->aLTerm
[j
++];
1626 assert( pStart
!=0 || pEnd
!=0 );
1632 codeCursorHint(pTabItem
, pWInfo
, pLevel
, pEnd
);
1634 Expr
*pX
; /* The expression that defines the start bound */
1635 int r1
, rTemp
; /* Registers for holding the start boundary */
1636 int op
; /* Cursor seek operation */
1638 /* The following constant maps TK_xx codes into corresponding
1639 ** seek opcodes. It depends on a particular ordering of TK_xx
1641 const u8 aMoveOp
[] = {
1642 /* TK_GT */ OP_SeekGT
,
1643 /* TK_LE */ OP_SeekLE
,
1644 /* TK_LT */ OP_SeekLT
,
1645 /* TK_GE */ OP_SeekGE
1647 assert( TK_LE
==TK_GT
+1 ); /* Make sure the ordering.. */
1648 assert( TK_LT
==TK_GT
+2 ); /* ... of the TK_xx values... */
1649 assert( TK_GE
==TK_GT
+3 ); /* ... is correct. */
1651 assert( (pStart
->wtFlags
& TERM_VNULL
)==0 );
1652 testcase( pStart
->wtFlags
& TERM_VIRTUAL
);
1655 testcase( pStart
->leftCursor
!=iCur
); /* transitive constraints */
1656 if( sqlite3ExprIsVector(pX
->pRight
) ){
1657 r1
= rTemp
= sqlite3GetTempReg(pParse
);
1658 codeExprOrVector(pParse
, pX
->pRight
, r1
, 1);
1659 testcase( pX
->op
==TK_GT
);
1660 testcase( pX
->op
==TK_GE
);
1661 testcase( pX
->op
==TK_LT
);
1662 testcase( pX
->op
==TK_LE
);
1663 op
= aMoveOp
[((pX
->op
- TK_GT
- 1) & 0x3) | 0x1];
1664 assert( pX
->op
!=TK_GT
|| op
==OP_SeekGE
);
1665 assert( pX
->op
!=TK_GE
|| op
==OP_SeekGE
);
1666 assert( pX
->op
!=TK_LT
|| op
==OP_SeekLE
);
1667 assert( pX
->op
!=TK_LE
|| op
==OP_SeekLE
);
1669 r1
= sqlite3ExprCodeTemp(pParse
, pX
->pRight
, &rTemp
);
1670 disableTerm(pLevel
, pStart
);
1671 op
= aMoveOp
[(pX
->op
- TK_GT
)];
1673 sqlite3VdbeAddOp3(v
, op
, iCur
, addrBrk
, r1
);
1674 VdbeComment((v
, "pk"));
1675 VdbeCoverageIf(v
, pX
->op
==TK_GT
);
1676 VdbeCoverageIf(v
, pX
->op
==TK_LE
);
1677 VdbeCoverageIf(v
, pX
->op
==TK_LT
);
1678 VdbeCoverageIf(v
, pX
->op
==TK_GE
);
1679 sqlite3ReleaseTempReg(pParse
, rTemp
);
1681 sqlite3VdbeAddOp2(v
, bRev
? OP_Last
: OP_Rewind
, iCur
, addrHalt
);
1682 VdbeCoverageIf(v
, bRev
==0);
1683 VdbeCoverageIf(v
, bRev
!=0);
1689 assert( (pEnd
->wtFlags
& TERM_VNULL
)==0 );
1690 testcase( pEnd
->leftCursor
!=iCur
); /* Transitive constraints */
1691 testcase( pEnd
->wtFlags
& TERM_VIRTUAL
);
1692 memEndValue
= ++pParse
->nMem
;
1693 codeExprOrVector(pParse
, pX
->pRight
, memEndValue
, 1);
1694 if( 0==sqlite3ExprIsVector(pX
->pRight
)
1695 && (pX
->op
==TK_LT
|| pX
->op
==TK_GT
)
1697 testOp
= bRev
? OP_Le
: OP_Ge
;
1699 testOp
= bRev
? OP_Lt
: OP_Gt
;
1701 if( 0==sqlite3ExprIsVector(pX
->pRight
) ){
1702 disableTerm(pLevel
, pEnd
);
1705 start
= sqlite3VdbeCurrentAddr(v
);
1706 pLevel
->op
= bRev
? OP_Prev
: OP_Next
;
1709 assert( pLevel
->p5
==0 );
1710 if( testOp
!=OP_Noop
){
1711 iRowidReg
= ++pParse
->nMem
;
1712 sqlite3VdbeAddOp2(v
, OP_Rowid
, iCur
, iRowidReg
);
1713 sqlite3VdbeAddOp3(v
, testOp
, memEndValue
, addrBrk
, iRowidReg
);
1714 VdbeCoverageIf(v
, testOp
==OP_Le
);
1715 VdbeCoverageIf(v
, testOp
==OP_Lt
);
1716 VdbeCoverageIf(v
, testOp
==OP_Ge
);
1717 VdbeCoverageIf(v
, testOp
==OP_Gt
);
1718 sqlite3VdbeChangeP5(v
, SQLITE_AFF_NUMERIC
| SQLITE_JUMPIFNULL
);
1720 }else if( pLoop
->wsFlags
& WHERE_INDEXED
){
1721 /* Case 4: A scan using an index.
1723 ** The WHERE clause may contain zero or more equality
1724 ** terms ("==" or "IN" operators) that refer to the N
1725 ** left-most columns of the index. It may also contain
1726 ** inequality constraints (>, <, >= or <=) on the indexed
1727 ** column that immediately follows the N equalities. Only
1728 ** the right-most column can be an inequality - the rest must
1729 ** use the "==" and "IN" operators. For example, if the
1730 ** index is on (x,y,z), then the following clauses are all
1736 ** x=5 AND y>5 AND y<10
1737 ** x=5 AND y=5 AND z<=10
1739 ** The z<10 term of the following cannot be used, only
1744 ** N may be zero if there are inequality constraints.
1745 ** If there are no inequality constraints, then N is at
1748 ** This case is also used when there are no WHERE clause
1749 ** constraints but an index is selected anyway, in order
1750 ** to force the output order to conform to an ORDER BY.
1752 static const u8 aStartOp
[] = {
1755 OP_Rewind
, /* 2: (!start_constraints && startEq && !bRev) */
1756 OP_Last
, /* 3: (!start_constraints && startEq && bRev) */
1757 OP_SeekGT
, /* 4: (start_constraints && !startEq && !bRev) */
1758 OP_SeekLT
, /* 5: (start_constraints && !startEq && bRev) */
1759 OP_SeekGE
, /* 6: (start_constraints && startEq && !bRev) */
1760 OP_SeekLE
/* 7: (start_constraints && startEq && bRev) */
1762 static const u8 aEndOp
[] = {
1763 OP_IdxGE
, /* 0: (end_constraints && !bRev && !endEq) */
1764 OP_IdxGT
, /* 1: (end_constraints && !bRev && endEq) */
1765 OP_IdxLE
, /* 2: (end_constraints && bRev && !endEq) */
1766 OP_IdxLT
, /* 3: (end_constraints && bRev && endEq) */
1768 u16 nEq
= pLoop
->u
.btree
.nEq
; /* Number of == or IN terms */
1769 u16 nBtm
= pLoop
->u
.btree
.nBtm
; /* Length of BTM vector */
1770 u16 nTop
= pLoop
->u
.btree
.nTop
; /* Length of TOP vector */
1771 int regBase
; /* Base register holding constraint values */
1772 WhereTerm
*pRangeStart
= 0; /* Inequality constraint at range start */
1773 WhereTerm
*pRangeEnd
= 0; /* Inequality constraint at range end */
1774 int startEq
; /* True if range start uses ==, >= or <= */
1775 int endEq
; /* True if range end uses ==, >= or <= */
1776 int start_constraints
; /* Start of range is constrained */
1777 int nConstraint
; /* Number of constraint terms */
1778 int iIdxCur
; /* The VDBE cursor for the index */
1779 int nExtraReg
= 0; /* Number of extra registers needed */
1780 int op
; /* Instruction opcode */
1781 char *zStartAff
; /* Affinity for start of range constraint */
1782 char *zEndAff
= 0; /* Affinity for end of range constraint */
1783 u8 bSeekPastNull
= 0; /* True to seek past initial nulls */
1784 u8 bStopAtNull
= 0; /* Add condition to terminate at NULLs */
1785 int omitTable
; /* True if we use the index only */
1786 int regBignull
= 0; /* big-null flag register */
1787 int addrSeekScan
= 0; /* Opcode of the OP_SeekScan, if any */
1789 pIdx
= pLoop
->u
.btree
.pIndex
;
1790 iIdxCur
= pLevel
->iIdxCur
;
1791 assert( nEq
>=pLoop
->nSkip
);
1793 /* Find any inequality constraint terms for the start and end
1797 if( pLoop
->wsFlags
& WHERE_BTM_LIMIT
){
1798 pRangeStart
= pLoop
->aLTerm
[j
++];
1799 nExtraReg
= MAX(nExtraReg
, pLoop
->u
.btree
.nBtm
);
1800 /* Like optimization range constraints always occur in pairs */
1801 assert( (pRangeStart
->wtFlags
& TERM_LIKEOPT
)==0 ||
1802 (pLoop
->wsFlags
& WHERE_TOP_LIMIT
)!=0 );
1804 if( pLoop
->wsFlags
& WHERE_TOP_LIMIT
){
1805 pRangeEnd
= pLoop
->aLTerm
[j
++];
1806 nExtraReg
= MAX(nExtraReg
, pLoop
->u
.btree
.nTop
);
1807 #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
1808 if( (pRangeEnd
->wtFlags
& TERM_LIKEOPT
)!=0 ){
1809 assert( pRangeStart
!=0 ); /* LIKE opt constraints */
1810 assert( pRangeStart
->wtFlags
& TERM_LIKEOPT
); /* occur in pairs */
1811 pLevel
->iLikeRepCntr
= (u32
)++pParse
->nMem
;
1812 sqlite3VdbeAddOp2(v
, OP_Integer
, 1, (int)pLevel
->iLikeRepCntr
);
1813 VdbeComment((v
, "LIKE loop counter"));
1814 pLevel
->addrLikeRep
= sqlite3VdbeCurrentAddr(v
);
1815 /* iLikeRepCntr actually stores 2x the counter register number. The
1816 ** bottom bit indicates whether the search order is ASC or DESC. */
1818 testcase( pIdx
->aSortOrder
[nEq
]==SQLITE_SO_DESC
);
1819 assert( (bRev
& ~1)==0 );
1820 pLevel
->iLikeRepCntr
<<=1;
1821 pLevel
->iLikeRepCntr
|= bRev
^ (pIdx
->aSortOrder
[nEq
]==SQLITE_SO_DESC
);
1824 if( pRangeStart
==0 ){
1825 j
= pIdx
->aiColumn
[nEq
];
1826 if( (j
>=0 && pIdx
->pTable
->aCol
[j
].notNull
==0) || j
==XN_EXPR
){
1831 assert( pRangeEnd
==0 || (pRangeEnd
->wtFlags
& TERM_VNULL
)==0 );
1833 /* If the WHERE_BIGNULL_SORT flag is set, then index column nEq uses
1834 ** a non-default "big-null" sort (either ASC NULLS LAST or DESC NULLS
1835 ** FIRST). In both cases separate ordered scans are made of those
1836 ** index entries for which the column is null and for those for which
1837 ** it is not. For an ASC sort, the non-NULL entries are scanned first.
1838 ** For DESC, NULL entries are scanned first.
1840 if( (pLoop
->wsFlags
& (WHERE_TOP_LIMIT
|WHERE_BTM_LIMIT
))==0
1841 && (pLoop
->wsFlags
& WHERE_BIGNULL_SORT
)!=0
1843 assert( bSeekPastNull
==0 && nExtraReg
==0 && nBtm
==0 && nTop
==0 );
1844 assert( pRangeEnd
==0 && pRangeStart
==0 );
1845 testcase( pLoop
->nSkip
>0 );
1848 pLevel
->regBignull
= regBignull
= ++pParse
->nMem
;
1849 if( pLevel
->iLeftJoin
){
1850 sqlite3VdbeAddOp2(v
, OP_Integer
, 0, regBignull
);
1852 pLevel
->addrBignull
= sqlite3VdbeMakeLabel(pParse
);
1855 /* If we are doing a reverse order scan on an ascending index, or
1856 ** a forward order scan on a descending index, interchange the
1857 ** start and end terms (pRangeStart and pRangeEnd).
1859 if( (nEq
<pIdx
->nColumn
&& bRev
==(pIdx
->aSortOrder
[nEq
]==SQLITE_SO_ASC
)) ){
1860 SWAP(WhereTerm
*, pRangeEnd
, pRangeStart
);
1861 SWAP(u8
, bSeekPastNull
, bStopAtNull
);
1862 SWAP(u8
, nBtm
, nTop
);
1865 if( iLevel
>0 && (pLoop
->wsFlags
& WHERE_IN_SEEKSCAN
)!=0 ){
1866 /* In case OP_SeekScan is used, ensure that the index cursor does not
1867 ** point to a valid row for the first iteration of this loop. */
1868 sqlite3VdbeAddOp1(v
, OP_NullRow
, iIdxCur
);
1871 /* Generate code to evaluate all constraint terms using == or IN
1872 ** and store the values of those terms in an array of registers
1873 ** starting at regBase.
1875 codeCursorHint(pTabItem
, pWInfo
, pLevel
, pRangeEnd
);
1876 regBase
= codeAllEqualityTerms(pParse
,pLevel
,bRev
,nExtraReg
,&zStartAff
);
1877 assert( zStartAff
==0 || sqlite3Strlen30(zStartAff
)>=nEq
);
1878 if( zStartAff
&& nTop
){
1879 zEndAff
= sqlite3DbStrDup(db
, &zStartAff
[nEq
]);
1881 addrNxt
= (regBignull
? pLevel
->addrBignull
: pLevel
->addrNxt
);
1883 testcase( pRangeStart
&& (pRangeStart
->eOperator
& WO_LE
)!=0 );
1884 testcase( pRangeStart
&& (pRangeStart
->eOperator
& WO_GE
)!=0 );
1885 testcase( pRangeEnd
&& (pRangeEnd
->eOperator
& WO_LE
)!=0 );
1886 testcase( pRangeEnd
&& (pRangeEnd
->eOperator
& WO_GE
)!=0 );
1887 startEq
= !pRangeStart
|| pRangeStart
->eOperator
& (WO_LE
|WO_GE
);
1888 endEq
= !pRangeEnd
|| pRangeEnd
->eOperator
& (WO_LE
|WO_GE
);
1889 start_constraints
= pRangeStart
|| nEq
>0;
1891 /* Seek the index cursor to the start of the range. */
1894 Expr
*pRight
= pRangeStart
->pExpr
->pRight
;
1895 codeExprOrVector(pParse
, pRight
, regBase
+nEq
, nBtm
);
1896 whereLikeOptimizationStringFixup(v
, pLevel
, pRangeStart
);
1897 if( (pRangeStart
->wtFlags
& TERM_VNULL
)==0
1898 && sqlite3ExprCanBeNull(pRight
)
1900 sqlite3VdbeAddOp2(v
, OP_IsNull
, regBase
+nEq
, addrNxt
);
1904 updateRangeAffinityStr(pRight
, nBtm
, &zStartAff
[nEq
]);
1906 nConstraint
+= nBtm
;
1907 testcase( pRangeStart
->wtFlags
& TERM_VIRTUAL
);
1908 if( sqlite3ExprIsVector(pRight
)==0 ){
1909 disableTerm(pLevel
, pRangeStart
);
1914 }else if( bSeekPastNull
){
1916 sqlite3VdbeAddOp2(v
, OP_Null
, 0, regBase
+nEq
);
1917 start_constraints
= 1;
1919 }else if( regBignull
){
1920 sqlite3VdbeAddOp2(v
, OP_Null
, 0, regBase
+nEq
);
1921 start_constraints
= 1;
1924 codeApplyAffinity(pParse
, regBase
, nConstraint
- bSeekPastNull
, zStartAff
);
1925 if( pLoop
->nSkip
>0 && nConstraint
==pLoop
->nSkip
){
1926 /* The skip-scan logic inside the call to codeAllEqualityConstraints()
1927 ** above has already left the cursor sitting on the correct row,
1928 ** so no further seeking is needed */
1931 sqlite3VdbeAddOp2(v
, OP_Integer
, 1, regBignull
);
1932 VdbeComment((v
, "NULL-scan pass ctr"));
1934 if( pLevel
->regFilter
){
1935 sqlite3VdbeAddOp4Int(v
, OP_Filter
, pLevel
->regFilter
, addrNxt
,
1938 filterPullDown(pParse
, pWInfo
, iLevel
, addrNxt
, notReady
);
1941 op
= aStartOp
[(start_constraints
<<2) + (startEq
<<1) + bRev
];
1943 if( (pLoop
->wsFlags
& WHERE_IN_SEEKSCAN
)!=0 && op
==OP_SeekGE
){
1944 assert( regBignull
==0 );
1945 /* TUNING: The OP_SeekScan opcode seeks to reduce the number
1946 ** of expensive seek operations by replacing a single seek with
1947 ** 1 or more step operations. The question is, how many steps
1948 ** should we try before giving up and going with a seek. The cost
1949 ** of a seek is proportional to the logarithm of the of the number
1950 ** of entries in the tree, so basing the number of steps to try
1951 ** on the estimated number of rows in the btree seems like a good
1953 addrSeekScan
= sqlite3VdbeAddOp1(v
, OP_SeekScan
,
1954 (pIdx
->aiRowLogEst
[0]+9)/10);
1955 if( pRangeStart
|| pRangeEnd
){
1956 sqlite3VdbeChangeP5(v
, 1);
1957 sqlite3VdbeChangeP2(v
, addrSeekScan
, sqlite3VdbeCurrentAddr(v
)+1);
1962 sqlite3VdbeAddOp4Int(v
, op
, iIdxCur
, addrNxt
, regBase
, nConstraint
);
1964 VdbeCoverageIf(v
, op
==OP_Rewind
); testcase( op
==OP_Rewind
);
1965 VdbeCoverageIf(v
, op
==OP_Last
); testcase( op
==OP_Last
);
1966 VdbeCoverageIf(v
, op
==OP_SeekGT
); testcase( op
==OP_SeekGT
);
1967 VdbeCoverageIf(v
, op
==OP_SeekGE
); testcase( op
==OP_SeekGE
);
1968 VdbeCoverageIf(v
, op
==OP_SeekLE
); testcase( op
==OP_SeekLE
);
1969 VdbeCoverageIf(v
, op
==OP_SeekLT
); testcase( op
==OP_SeekLT
);
1971 assert( bSeekPastNull
==0 || bStopAtNull
==0 );
1973 assert( bSeekPastNull
==1 || bStopAtNull
==1 );
1974 assert( bSeekPastNull
==!bStopAtNull
);
1975 assert( bStopAtNull
==startEq
);
1976 sqlite3VdbeAddOp2(v
, OP_Goto
, 0, sqlite3VdbeCurrentAddr(v
)+2);
1977 op
= aStartOp
[(nConstraint
>1)*4 + 2 + bRev
];
1978 sqlite3VdbeAddOp4Int(v
, op
, iIdxCur
, addrNxt
, regBase
,
1979 nConstraint
-startEq
);
1981 VdbeCoverageIf(v
, op
==OP_Rewind
); testcase( op
==OP_Rewind
);
1982 VdbeCoverageIf(v
, op
==OP_Last
); testcase( op
==OP_Last
);
1983 VdbeCoverageIf(v
, op
==OP_SeekGE
); testcase( op
==OP_SeekGE
);
1984 VdbeCoverageIf(v
, op
==OP_SeekLE
); testcase( op
==OP_SeekLE
);
1985 assert( op
==OP_Rewind
|| op
==OP_Last
|| op
==OP_SeekGE
|| op
==OP_SeekLE
);
1989 /* Load the value for the inequality constraint at the end of the
1993 assert( pLevel
->p2
==0 );
1995 Expr
*pRight
= pRangeEnd
->pExpr
->pRight
;
1996 assert( addrSeekScan
==0 );
1997 codeExprOrVector(pParse
, pRight
, regBase
+nEq
, nTop
);
1998 whereLikeOptimizationStringFixup(v
, pLevel
, pRangeEnd
);
1999 if( (pRangeEnd
->wtFlags
& TERM_VNULL
)==0
2000 && sqlite3ExprCanBeNull(pRight
)
2002 sqlite3VdbeAddOp2(v
, OP_IsNull
, regBase
+nEq
, addrNxt
);
2006 updateRangeAffinityStr(pRight
, nTop
, zEndAff
);
2007 codeApplyAffinity(pParse
, regBase
+nEq
, nTop
, zEndAff
);
2009 assert( pParse
->db
->mallocFailed
);
2011 nConstraint
+= nTop
;
2012 testcase( pRangeEnd
->wtFlags
& TERM_VIRTUAL
);
2014 if( sqlite3ExprIsVector(pRight
)==0 ){
2015 disableTerm(pLevel
, pRangeEnd
);
2019 }else if( bStopAtNull
){
2020 if( regBignull
==0 ){
2021 sqlite3VdbeAddOp2(v
, OP_Null
, 0, regBase
+nEq
);
2026 if( zStartAff
) sqlite3DbNNFreeNN(db
, zStartAff
);
2027 if( zEndAff
) sqlite3DbNNFreeNN(db
, zEndAff
);
2029 /* Top of the loop body */
2030 pLevel
->p2
= sqlite3VdbeCurrentAddr(v
);
2032 /* Check if the index cursor is past the end of the range. */
2035 /* Except, skip the end-of-range check while doing the NULL-scan */
2036 sqlite3VdbeAddOp2(v
, OP_IfNot
, regBignull
, sqlite3VdbeCurrentAddr(v
)+3);
2037 VdbeComment((v
, "If NULL-scan 2nd pass"));
2040 op
= aEndOp
[bRev
*2 + endEq
];
2041 sqlite3VdbeAddOp4Int(v
, op
, iIdxCur
, addrNxt
, regBase
, nConstraint
);
2042 testcase( op
==OP_IdxGT
); VdbeCoverageIf(v
, op
==OP_IdxGT
);
2043 testcase( op
==OP_IdxGE
); VdbeCoverageIf(v
, op
==OP_IdxGE
);
2044 testcase( op
==OP_IdxLT
); VdbeCoverageIf(v
, op
==OP_IdxLT
);
2045 testcase( op
==OP_IdxLE
); VdbeCoverageIf(v
, op
==OP_IdxLE
);
2046 if( addrSeekScan
) sqlite3VdbeJumpHere(v
, addrSeekScan
);
2049 /* During a NULL-scan, check to see if we have reached the end of
2051 assert( bSeekPastNull
==!bStopAtNull
);
2052 assert( bSeekPastNull
+bStopAtNull
==1 );
2053 assert( nConstraint
+bSeekPastNull
>0 );
2054 sqlite3VdbeAddOp2(v
, OP_If
, regBignull
, sqlite3VdbeCurrentAddr(v
)+2);
2055 VdbeComment((v
, "If NULL-scan 1st pass"));
2057 op
= aEndOp
[bRev
*2 + bSeekPastNull
];
2058 sqlite3VdbeAddOp4Int(v
, op
, iIdxCur
, addrNxt
, regBase
,
2059 nConstraint
+bSeekPastNull
);
2060 testcase( op
==OP_IdxGT
); VdbeCoverageIf(v
, op
==OP_IdxGT
);
2061 testcase( op
==OP_IdxGE
); VdbeCoverageIf(v
, op
==OP_IdxGE
);
2062 testcase( op
==OP_IdxLT
); VdbeCoverageIf(v
, op
==OP_IdxLT
);
2063 testcase( op
==OP_IdxLE
); VdbeCoverageIf(v
, op
==OP_IdxLE
);
2066 if( (pLoop
->wsFlags
& WHERE_IN_EARLYOUT
)!=0 ){
2067 sqlite3VdbeAddOp3(v
, OP_SeekHit
, iIdxCur
, nEq
, nEq
);
2070 /* Seek the table cursor, if required */
2071 omitTable
= (pLoop
->wsFlags
& WHERE_IDX_ONLY
)!=0
2072 && (pWInfo
->wctrlFlags
& (WHERE_OR_SUBCLAUSE
|WHERE_RIGHT_JOIN
))==0;
2074 /* pIdx is a covering index. No need to access the main table. */
2075 }else if( HasRowid(pIdx
->pTable
) ){
2076 codeDeferredSeek(pWInfo
, pIdx
, iCur
, iIdxCur
);
2077 }else if( iCur
!=iIdxCur
){
2078 Index
*pPk
= sqlite3PrimaryKeyIndex(pIdx
->pTable
);
2079 iRowidReg
= sqlite3GetTempRange(pParse
, pPk
->nKeyCol
);
2080 for(j
=0; j
<pPk
->nKeyCol
; j
++){
2081 k
= sqlite3TableColumnToIndex(pIdx
, pPk
->aiColumn
[j
]);
2082 sqlite3VdbeAddOp3(v
, OP_Column
, iIdxCur
, k
, iRowidReg
+j
);
2084 sqlite3VdbeAddOp4Int(v
, OP_NotFound
, iCur
, addrCont
,
2085 iRowidReg
, pPk
->nKeyCol
); VdbeCoverage(v
);
2088 if( pLevel
->iLeftJoin
==0 ){
2089 /* If a partial index is driving the loop, try to eliminate WHERE clause
2090 ** terms from the query that must be true due to the WHERE clause of
2091 ** the partial index.
2093 ** 2019-11-02 ticket 623eff57e76d45f6: This optimization does not work
2096 if( pIdx
->pPartIdxWhere
){
2097 whereApplyPartialIndexConstraints(pIdx
->pPartIdxWhere
, iCur
, pWC
);
2100 testcase( pIdx
->pPartIdxWhere
);
2101 /* The following assert() is not a requirement, merely an observation:
2102 ** The OR-optimization doesn't work for the right hand table of
2104 assert( (pWInfo
->wctrlFlags
& (WHERE_OR_SUBCLAUSE
|WHERE_RIGHT_JOIN
))==0 );
2107 /* Record the instruction used to terminate the loop. */
2108 if( (pLoop
->wsFlags
& WHERE_ONEROW
)
2109 || (pLevel
->u
.in
.nIn
&& regBignull
==0 && whereLoopIsOneRow(pLoop
))
2111 pLevel
->op
= OP_Noop
;
2113 pLevel
->op
= OP_Prev
;
2115 pLevel
->op
= OP_Next
;
2117 pLevel
->p1
= iIdxCur
;
2118 pLevel
->p3
= (pLoop
->wsFlags
&WHERE_UNQ_WANTED
)!=0 ? 1:0;
2119 if( (pLoop
->wsFlags
& WHERE_CONSTRAINT
)==0 ){
2120 pLevel
->p5
= SQLITE_STMTSTATUS_FULLSCAN_STEP
;
2122 assert( pLevel
->p5
==0 );
2124 if( omitTable
) pIdx
= 0;
2127 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
2128 if( pLoop
->wsFlags
& WHERE_MULTI_OR
){
2129 /* Case 5: Two or more separately indexed terms connected by OR
2133 ** CREATE TABLE t1(a,b,c,d);
2134 ** CREATE INDEX i1 ON t1(a);
2135 ** CREATE INDEX i2 ON t1(b);
2136 ** CREATE INDEX i3 ON t1(c);
2138 ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
2140 ** In the example, there are three indexed terms connected by OR.
2141 ** The top of the loop looks like this:
2143 ** Null 1 # Zero the rowset in reg 1
2145 ** Then, for each indexed term, the following. The arguments to
2146 ** RowSetTest are such that the rowid of the current row is inserted
2147 ** into the RowSet. If it is already present, control skips the
2148 ** Gosub opcode and jumps straight to the code generated by WhereEnd().
2150 ** sqlite3WhereBegin(<term>)
2151 ** RowSetTest # Insert rowid into rowset
2153 ** sqlite3WhereEnd()
2155 ** Following the above, code to terminate the loop. Label A, the target
2156 ** of the Gosub above, jumps to the instruction right after the Goto.
2158 ** Null 1 # Zero the rowset in reg 1
2159 ** Goto B # The loop is finished.
2161 ** A: <loop body> # Return data, whatever.
2163 ** Return 2 # Jump back to the Gosub
2165 ** B: <after the loop>
2167 ** Added 2014-05-26: If the table is a WITHOUT ROWID table, then
2168 ** use an ephemeral index instead of a RowSet to record the primary
2169 ** keys of the rows we have already seen.
2172 WhereClause
*pOrWc
; /* The OR-clause broken out into subterms */
2173 SrcList
*pOrTab
; /* Shortened table list or OR-clause generation */
2174 Index
*pCov
= 0; /* Potential covering index (or NULL) */
2175 int iCovCur
= pParse
->nTab
++; /* Cursor used for index scans (if any) */
2177 int regReturn
= ++pParse
->nMem
; /* Register used with OP_Gosub */
2178 int regRowset
= 0; /* Register for RowSet object */
2179 int regRowid
= 0; /* Register holding rowid */
2180 int iLoopBody
= sqlite3VdbeMakeLabel(pParse
);/* Start of loop body */
2181 int iRetInit
; /* Address of regReturn init */
2182 int untestedTerms
= 0; /* Some terms not completely tested */
2183 int ii
; /* Loop counter */
2184 Expr
*pAndExpr
= 0; /* An ".. AND (...)" expression */
2185 Table
*pTab
= pTabItem
->pTab
;
2187 pTerm
= pLoop
->aLTerm
[0];
2189 assert( pTerm
->eOperator
& WO_OR
);
2190 assert( (pTerm
->wtFlags
& TERM_ORINFO
)!=0 );
2191 pOrWc
= &pTerm
->u
.pOrInfo
->wc
;
2192 pLevel
->op
= OP_Return
;
2193 pLevel
->p1
= regReturn
;
2195 /* Set up a new SrcList in pOrTab containing the table being scanned
2196 ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
2197 ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
2199 if( pWInfo
->nLevel
>1 ){
2200 int nNotReady
; /* The number of notReady tables */
2201 SrcItem
*origSrc
; /* Original list of tables */
2202 nNotReady
= pWInfo
->nLevel
- iLevel
- 1;
2203 pOrTab
= sqlite3DbMallocRawNN(db
,
2204 sizeof(*pOrTab
)+ nNotReady
*sizeof(pOrTab
->a
[0]));
2205 if( pOrTab
==0 ) return notReady
;
2206 pOrTab
->nAlloc
= (u8
)(nNotReady
+ 1);
2207 pOrTab
->nSrc
= pOrTab
->nAlloc
;
2208 memcpy(pOrTab
->a
, pTabItem
, sizeof(*pTabItem
));
2209 origSrc
= pWInfo
->pTabList
->a
;
2210 for(k
=1; k
<=nNotReady
; k
++){
2211 memcpy(&pOrTab
->a
[k
], &origSrc
[pLevel
[k
].iFrom
], sizeof(pOrTab
->a
[k
]));
2214 pOrTab
= pWInfo
->pTabList
;
2217 /* Initialize the rowset register to contain NULL. An SQL NULL is
2218 ** equivalent to an empty rowset. Or, create an ephemeral index
2219 ** capable of holding primary keys in the case of a WITHOUT ROWID.
2221 ** Also initialize regReturn to contain the address of the instruction
2222 ** immediately following the OP_Return at the bottom of the loop. This
2223 ** is required in a few obscure LEFT JOIN cases where control jumps
2224 ** over the top of the loop into the body of it. In this case the
2225 ** correct response for the end-of-loop code (the OP_Return) is to
2226 ** fall through to the next instruction, just as an OP_Next does if
2227 ** called on an uninitialized cursor.
2229 if( (pWInfo
->wctrlFlags
& WHERE_DUPLICATES_OK
)==0 ){
2230 if( HasRowid(pTab
) ){
2231 regRowset
= ++pParse
->nMem
;
2232 sqlite3VdbeAddOp2(v
, OP_Null
, 0, regRowset
);
2234 Index
*pPk
= sqlite3PrimaryKeyIndex(pTab
);
2235 regRowset
= pParse
->nTab
++;
2236 sqlite3VdbeAddOp2(v
, OP_OpenEphemeral
, regRowset
, pPk
->nKeyCol
);
2237 sqlite3VdbeSetP4KeyInfo(pParse
, pPk
);
2239 regRowid
= ++pParse
->nMem
;
2241 iRetInit
= sqlite3VdbeAddOp2(v
, OP_Integer
, 0, regReturn
);
2243 /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y
2244 ** Then for every term xN, evaluate as the subexpression: xN AND y
2245 ** That way, terms in y that are factored into the disjunction will
2246 ** be picked up by the recursive calls to sqlite3WhereBegin() below.
2248 ** Actually, each subexpression is converted to "xN AND w" where w is
2249 ** the "interesting" terms of z - terms that did not originate in the
2250 ** ON or USING clause of a LEFT JOIN, and terms that are usable as
2253 ** This optimization also only applies if the (x1 OR x2 OR ...) term
2254 ** is not contained in the ON clause of a LEFT JOIN.
2255 ** See ticket http://www.sqlite.org/src/info/f2369304e4
2257 ** 2022-02-04: Do not push down slices of a row-value comparison.
2258 ** In other words, "w" or "y" may not be a slice of a vector. Otherwise,
2259 ** the initialization of the right-hand operand of the vector comparison
2260 ** might not occur, or might occur only in an OR branch that is not
2261 ** taken. dbsqlfuzz 80a9fade844b4fb43564efc972bcb2c68270f5d1.
2263 ** 2022-03-03: Do not push down expressions that involve subqueries.
2264 ** The subquery might get coded as a subroutine. Any table-references
2265 ** in the subquery might be resolved to index-references for the index on
2266 ** the OR branch in which the subroutine is coded. But if the subroutine
2267 ** is invoked from a different OR branch that uses a different index, such
2268 ** index-references will not work. tag-20220303a
2269 ** https://sqlite.org/forum/forumpost/36937b197273d403
2273 for(iTerm
=0; iTerm
<pWC
->nTerm
; iTerm
++){
2274 Expr
*pExpr
= pWC
->a
[iTerm
].pExpr
;
2275 if( &pWC
->a
[iTerm
] == pTerm
) continue;
2276 testcase( pWC
->a
[iTerm
].wtFlags
& TERM_VIRTUAL
);
2277 testcase( pWC
->a
[iTerm
].wtFlags
& TERM_CODED
);
2278 testcase( pWC
->a
[iTerm
].wtFlags
& TERM_SLICE
);
2279 if( (pWC
->a
[iTerm
].wtFlags
& (TERM_VIRTUAL
|TERM_CODED
|TERM_SLICE
))!=0 ){
2282 if( (pWC
->a
[iTerm
].eOperator
& WO_ALL
)==0 ) continue;
2283 if( ExprHasProperty(pExpr
, EP_Subquery
) ) continue; /* tag-20220303a */
2284 pExpr
= sqlite3ExprDup(db
, pExpr
, 0);
2285 pAndExpr
= sqlite3ExprAnd(pParse
, pAndExpr
, pExpr
);
2288 /* The extra 0x10000 bit on the opcode is masked off and does not
2289 ** become part of the new Expr.op. However, it does make the
2290 ** op==TK_AND comparison inside of sqlite3PExpr() false, and this
2291 ** prevents sqlite3PExpr() from applying the AND short-circuit
2292 ** optimization, which we do not want here. */
2293 pAndExpr
= sqlite3PExpr(pParse
, TK_AND
|0x10000, 0, pAndExpr
);
2297 /* Run a separate WHERE clause for each term of the OR clause. After
2298 ** eliminating duplicates from other WHERE clauses, the action for each
2299 ** sub-WHERE clause is to to invoke the main loop body as a subroutine.
2301 ExplainQueryPlan((pParse
, 1, "MULTI-INDEX OR"));
2302 for(ii
=0; ii
<pOrWc
->nTerm
; ii
++){
2303 WhereTerm
*pOrTerm
= &pOrWc
->a
[ii
];
2304 if( pOrTerm
->leftCursor
==iCur
|| (pOrTerm
->eOperator
& WO_AND
)!=0 ){
2305 WhereInfo
*pSubWInfo
; /* Info for single OR-term scan */
2306 Expr
*pOrExpr
= pOrTerm
->pExpr
; /* Current OR clause term */
2307 Expr
*pDelete
; /* Local copy of OR clause term */
2308 int jmp1
= 0; /* Address of jump operation */
2309 testcase( (pTabItem
[0].fg
.jointype
& JT_LEFT
)!=0
2310 && !ExprHasProperty(pOrExpr
, EP_OuterON
)
2311 ); /* See TH3 vtab25.400 and ticket 614b25314c766238 */
2312 pDelete
= pOrExpr
= sqlite3ExprDup(db
, pOrExpr
, 0);
2313 if( db
->mallocFailed
){
2314 sqlite3ExprDelete(db
, pDelete
);
2318 pAndExpr
->pLeft
= pOrExpr
;
2321 /* Loop through table entries that match term pOrTerm. */
2322 ExplainQueryPlan((pParse
, 1, "INDEX %d", ii
+1));
2323 WHERETRACE(0xffffffff, ("Subplan for OR-clause:\n"));
2324 pSubWInfo
= sqlite3WhereBegin(pParse
, pOrTab
, pOrExpr
, 0, 0, 0,
2325 WHERE_OR_SUBCLAUSE
, iCovCur
);
2326 assert( pSubWInfo
|| pParse
->nErr
);
2328 WhereLoop
*pSubLoop
;
2329 int addrExplain
= sqlite3WhereExplainOneScan(
2330 pParse
, pOrTab
, &pSubWInfo
->a
[0], 0
2332 sqlite3WhereAddScanStatus(v
, pOrTab
, &pSubWInfo
->a
[0], addrExplain
);
2334 /* This is the sub-WHERE clause body. First skip over
2335 ** duplicate rows from prior sub-WHERE clauses, and record the
2336 ** rowid (or PRIMARY KEY) for the current row so that the same
2337 ** row will be skipped in subsequent sub-WHERE clauses.
2339 if( (pWInfo
->wctrlFlags
& WHERE_DUPLICATES_OK
)==0 ){
2340 int iSet
= ((ii
==pOrWc
->nTerm
-1)?-1:ii
);
2341 if( HasRowid(pTab
) ){
2342 sqlite3ExprCodeGetColumnOfTable(v
, pTab
, iCur
, -1, regRowid
);
2343 jmp1
= sqlite3VdbeAddOp4Int(v
, OP_RowSetTest
, regRowset
, 0,
2347 Index
*pPk
= sqlite3PrimaryKeyIndex(pTab
);
2348 int nPk
= pPk
->nKeyCol
;
2352 /* Read the PK into an array of temp registers. */
2353 r
= sqlite3GetTempRange(pParse
, nPk
);
2354 for(iPk
=0; iPk
<nPk
; iPk
++){
2355 int iCol
= pPk
->aiColumn
[iPk
];
2356 sqlite3ExprCodeGetColumnOfTable(v
, pTab
, iCur
, iCol
,r
+iPk
);
2359 /* Check if the temp table already contains this key. If so,
2360 ** the row has already been included in the result set and
2361 ** can be ignored (by jumping past the Gosub below). Otherwise,
2362 ** insert the key into the temp table and proceed with processing
2365 ** Use some of the same optimizations as OP_RowSetTest: If iSet
2366 ** is zero, assume that the key cannot already be present in
2367 ** the temp table. And if iSet is -1, assume that there is no
2368 ** need to insert the key into the temp table, as it will never
2369 ** be tested for. */
2371 jmp1
= sqlite3VdbeAddOp4Int(v
, OP_Found
, regRowset
, 0, r
, nPk
);
2375 sqlite3VdbeAddOp3(v
, OP_MakeRecord
, r
, nPk
, regRowid
);
2376 sqlite3VdbeAddOp4Int(v
, OP_IdxInsert
, regRowset
, regRowid
,
2378 if( iSet
) sqlite3VdbeChangeP5(v
, OPFLAG_USESEEKRESULT
);
2381 /* Release the array of temp registers */
2382 sqlite3ReleaseTempRange(pParse
, r
, nPk
);
2386 /* Invoke the main loop body as a subroutine */
2387 sqlite3VdbeAddOp2(v
, OP_Gosub
, regReturn
, iLoopBody
);
2389 /* Jump here (skipping the main loop body subroutine) if the
2390 ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */
2391 if( jmp1
) sqlite3VdbeJumpHere(v
, jmp1
);
2393 /* The pSubWInfo->untestedTerms flag means that this OR term
2394 ** contained one or more AND term from a notReady table. The
2395 ** terms from the notReady table could not be tested and will
2396 ** need to be tested later.
2398 if( pSubWInfo
->untestedTerms
) untestedTerms
= 1;
2400 /* If all of the OR-connected terms are optimized using the same
2401 ** index, and the index is opened using the same cursor number
2402 ** by each call to sqlite3WhereBegin() made by this loop, it may
2403 ** be possible to use that index as a covering index.
2405 ** If the call to sqlite3WhereBegin() above resulted in a scan that
2406 ** uses an index, and this is either the first OR-connected term
2407 ** processed or the index is the same as that used by all previous
2408 ** terms, set pCov to the candidate covering index. Otherwise, set
2409 ** pCov to NULL to indicate that no candidate covering index will
2412 pSubLoop
= pSubWInfo
->a
[0].pWLoop
;
2413 assert( (pSubLoop
->wsFlags
& WHERE_AUTO_INDEX
)==0 );
2414 if( (pSubLoop
->wsFlags
& WHERE_INDEXED
)!=0
2415 && (ii
==0 || pSubLoop
->u
.btree
.pIndex
==pCov
)
2416 && (HasRowid(pTab
) || !IsPrimaryKeyIndex(pSubLoop
->u
.btree
.pIndex
))
2418 assert( pSubWInfo
->a
[0].iIdxCur
==iCovCur
);
2419 pCov
= pSubLoop
->u
.btree
.pIndex
;
2423 if( sqlite3WhereUsesDeferredSeek(pSubWInfo
) ){
2424 pWInfo
->bDeferredSeek
= 1;
2427 /* Finish the loop through table entries that match term pOrTerm. */
2428 sqlite3WhereEnd(pSubWInfo
);
2429 ExplainQueryPlanPop(pParse
);
2431 sqlite3ExprDelete(db
, pDelete
);
2434 ExplainQueryPlanPop(pParse
);
2435 assert( pLevel
->pWLoop
==pLoop
);
2436 assert( (pLoop
->wsFlags
& WHERE_MULTI_OR
)!=0 );
2437 assert( (pLoop
->wsFlags
& WHERE_IN_ABLE
)==0 );
2438 pLevel
->u
.pCoveringIdx
= pCov
;
2439 if( pCov
) pLevel
->iIdxCur
= iCovCur
;
2441 pAndExpr
->pLeft
= 0;
2442 sqlite3ExprDelete(db
, pAndExpr
);
2444 sqlite3VdbeChangeP1(v
, iRetInit
, sqlite3VdbeCurrentAddr(v
));
2445 sqlite3VdbeGoto(v
, pLevel
->addrBrk
);
2446 sqlite3VdbeResolveLabel(v
, iLoopBody
);
2448 /* Set the P2 operand of the OP_Return opcode that will end the current
2449 ** loop to point to this spot, which is the top of the next containing
2450 ** loop. The byte-code formatter will use that P2 value as a hint to
2451 ** indent everything in between the this point and the final OP_Return.
2452 ** See tag-20220407a in vdbe.c and shell.c */
2453 assert( pLevel
->op
==OP_Return
);
2454 pLevel
->p2
= sqlite3VdbeCurrentAddr(v
);
2456 if( pWInfo
->nLevel
>1 ){ sqlite3DbFreeNN(db
, pOrTab
); }
2457 if( !untestedTerms
) disableTerm(pLevel
, pTerm
);
2459 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
2462 /* Case 6: There is no usable index. We must do a complete
2463 ** scan of the entire table.
2465 static const u8 aStep
[] = { OP_Next
, OP_Prev
};
2466 static const u8 aStart
[] = { OP_Rewind
, OP_Last
};
2467 assert( bRev
==0 || bRev
==1 );
2468 if( pTabItem
->fg
.isRecursive
){
2469 /* Tables marked isRecursive have only a single row that is stored in
2470 ** a pseudo-cursor. No need to Rewind or Next such cursors. */
2471 pLevel
->op
= OP_Noop
;
2473 codeCursorHint(pTabItem
, pWInfo
, pLevel
, 0);
2474 pLevel
->op
= aStep
[bRev
];
2476 pLevel
->p2
= 1 + sqlite3VdbeAddOp2(v
, aStart
[bRev
], iCur
, addrHalt
);
2477 VdbeCoverageIf(v
, bRev
==0);
2478 VdbeCoverageIf(v
, bRev
!=0);
2479 pLevel
->p5
= SQLITE_STMTSTATUS_FULLSCAN_STEP
;
2483 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
2484 pLevel
->addrVisit
= sqlite3VdbeCurrentAddr(v
);
2487 /* Insert code to test every subexpression that can be completely
2488 ** computed using the current set of tables.
2490 ** This loop may run between one and three times, depending on the
2491 ** constraints to be generated. The value of stack variable iLoop
2492 ** determines the constraints coded by each iteration, as follows:
2494 ** iLoop==1: Code only expressions that are entirely covered by pIdx.
2495 ** iLoop==2: Code remaining expressions that do not contain correlated
2497 ** iLoop==3: Code all remaining expressions.
2499 ** An effort is made to skip unnecessary iterations of the loop.
2501 ** This optimization of causing simple query restrictions to occur before
2502 ** more complex one is call the "push-down" optimization in MySQL. Here
2503 ** in SQLite, the name is "MySQL push-down", since there is also another
2504 ** totally unrelated optimization called "WHERE-clause push-down".
2505 ** Sometimes the qualifier is omitted, resulting in an ambiguity, so beware.
2507 iLoop
= (pIdx
? 1 : 2);
2509 int iNext
= 0; /* Next value for iLoop */
2510 for(pTerm
=pWC
->a
, j
=pWC
->nTerm
; j
>0; j
--, pTerm
++){
2512 int skipLikeAddr
= 0;
2513 testcase( pTerm
->wtFlags
& TERM_VIRTUAL
);
2514 testcase( pTerm
->wtFlags
& TERM_CODED
);
2515 if( pTerm
->wtFlags
& (TERM_VIRTUAL
|TERM_CODED
) ) continue;
2516 if( (pTerm
->prereqAll
& pLevel
->notReady
)!=0 ){
2517 testcase( pWInfo
->untestedTerms
==0
2518 && (pWInfo
->wctrlFlags
& WHERE_OR_SUBCLAUSE
)!=0 );
2519 pWInfo
->untestedTerms
= 1;
2524 if( pTabItem
->fg
.jointype
& (JT_LEFT
|JT_LTORJ
|JT_RIGHT
) ){
2525 if( !ExprHasProperty(pE
,EP_OuterON
|EP_InnerON
) ){
2526 /* Defer processing WHERE clause constraints until after outer
2527 ** join processing. tag-20220513a */
2529 }else if( (pTabItem
->fg
.jointype
& JT_LEFT
)==JT_LEFT
2530 && !ExprHasProperty(pE
,EP_OuterON
) ){
2533 Bitmask m
= sqlite3WhereGetMask(&pWInfo
->sMaskSet
, pE
->w
.iJoin
);
2534 if( m
& pLevel
->notReady
){
2535 /* An ON clause that is not ripe */
2540 if( iLoop
==1 && !sqlite3ExprCoveredByIndex(pE
, pLevel
->iTabCur
, pIdx
) ){
2544 if( iLoop
<3 && (pTerm
->wtFlags
& TERM_VARSELECT
) ){
2545 if( iNext
==0 ) iNext
= 3;
2549 if( (pTerm
->wtFlags
& TERM_LIKECOND
)!=0 ){
2550 /* If the TERM_LIKECOND flag is set, that means that the range search
2551 ** is sufficient to guarantee that the LIKE operator is true, so we
2552 ** can skip the call to the like(A,B) function. But this only works
2553 ** for strings. So do not skip the call to the function on the pass
2554 ** that compares BLOBs. */
2555 #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
2558 u32 x
= pLevel
->iLikeRepCntr
;
2560 skipLikeAddr
= sqlite3VdbeAddOp1(v
, (x
&1)?OP_IfNot
:OP_If
,(int)(x
>>1));
2561 VdbeCoverageIf(v
, (x
&1)==1);
2562 VdbeCoverageIf(v
, (x
&1)==0);
2566 #ifdef WHERETRACE_ENABLED /* 0xffffffff */
2567 if( sqlite3WhereTrace
){
2568 VdbeNoopComment((v
, "WhereTerm[%d] (%p) priority=%d",
2569 pWC
->nTerm
-j
, pTerm
, iLoop
));
2571 if( sqlite3WhereTrace
& 0x4000 ){
2572 sqlite3DebugPrintf("Coding auxiliary constraint:\n");
2573 sqlite3WhereTermPrint(pTerm
, pWC
->nTerm
-j
);
2576 sqlite3ExprIfFalse(pParse
, pE
, addrCont
, SQLITE_JUMPIFNULL
);
2577 if( skipLikeAddr
) sqlite3VdbeJumpHere(v
, skipLikeAddr
);
2578 pTerm
->wtFlags
|= TERM_CODED
;
2583 /* Insert code to test for implied constraints based on transitivity
2584 ** of the "==" operator.
2586 ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
2587 ** and we are coding the t1 loop and the t2 loop has not yet coded,
2588 ** then we cannot use the "t1.a=t2.b" constraint, but we can code
2589 ** the implied "t1.a=123" constraint.
2591 for(pTerm
=pWC
->a
, j
=pWC
->nBase
; j
>0; j
--, pTerm
++){
2594 if( pTerm
->wtFlags
& (TERM_VIRTUAL
|TERM_CODED
) ) continue;
2595 if( (pTerm
->eOperator
& (WO_EQ
|WO_IS
))==0 ) continue;
2596 if( (pTerm
->eOperator
& WO_EQUIV
)==0 ) continue;
2597 if( pTerm
->leftCursor
!=iCur
) continue;
2598 if( pTabItem
->fg
.jointype
& (JT_LEFT
|JT_LTORJ
|JT_RIGHT
) ) continue;
2600 #ifdef WHERETRACE_ENABLED /* 0x4001 */
2601 if( (sqlite3WhereTrace
& 0x4001)==0x4001 ){
2602 sqlite3DebugPrintf("Coding transitive constraint:\n");
2603 sqlite3WhereTermPrint(pTerm
, pWC
->nTerm
-j
);
2606 assert( !ExprHasProperty(pE
, EP_OuterON
) );
2607 assert( (pTerm
->prereqRight
& pLevel
->notReady
)!=0 );
2608 assert( (pTerm
->eOperator
& (WO_OR
|WO_AND
))==0 );
2609 pAlt
= sqlite3WhereFindTerm(pWC
, iCur
, pTerm
->u
.x
.leftColumn
, notReady
,
2610 WO_EQ
|WO_IN
|WO_IS
, 0);
2611 if( pAlt
==0 ) continue;
2612 if( pAlt
->wtFlags
& (TERM_CODED
) ) continue;
2613 if( (pAlt
->eOperator
& WO_IN
)
2614 && ExprUseXSelect(pAlt
->pExpr
)
2615 && (pAlt
->pExpr
->x
.pSelect
->pEList
->nExpr
>1)
2619 testcase( pAlt
->eOperator
& WO_EQ
);
2620 testcase( pAlt
->eOperator
& WO_IS
);
2621 testcase( pAlt
->eOperator
& WO_IN
);
2622 VdbeModuleComment((v
, "begin transitive constraint"));
2623 sEAlt
= *pAlt
->pExpr
;
2624 sEAlt
.pLeft
= pE
->pLeft
;
2625 sqlite3ExprIfFalse(pParse
, &sEAlt
, addrCont
, SQLITE_JUMPIFNULL
);
2626 pAlt
->wtFlags
|= TERM_CODED
;
2629 /* For a RIGHT OUTER JOIN, record the fact that the current row has
2630 ** been matched at least once.
2637 WhereRightJoin
*pRJ
= pLevel
->pRJ
;
2639 /* pTab is the right-hand table of the RIGHT JOIN. Generate code that
2640 ** will record that the current row of that table has been matched at
2641 ** least once. This is accomplished by storing the PK for the row in
2642 ** both the iMatch index and the regBloom Bloom filter.
2644 pTab
= pWInfo
->pTabList
->a
[pLevel
->iFrom
].pTab
;
2645 if( HasRowid(pTab
) ){
2646 r
= sqlite3GetTempRange(pParse
, 2);
2647 sqlite3ExprCodeGetColumnOfTable(v
, pTab
, pLevel
->iTabCur
, -1, r
+1);
2651 Index
*pPk
= sqlite3PrimaryKeyIndex(pTab
);
2653 r
= sqlite3GetTempRange(pParse
, nPk
+1);
2654 for(iPk
=0; iPk
<nPk
; iPk
++){
2655 int iCol
= pPk
->aiColumn
[iPk
];
2656 sqlite3ExprCodeGetColumnOfTable(v
, pTab
, iCur
, iCol
,r
+1+iPk
);
2659 jmp1
= sqlite3VdbeAddOp4Int(v
, OP_Found
, pRJ
->iMatch
, 0, r
+1, nPk
);
2661 VdbeComment((v
, "match against %s", pTab
->zName
));
2662 sqlite3VdbeAddOp3(v
, OP_MakeRecord
, r
+1, nPk
, r
);
2663 sqlite3VdbeAddOp4Int(v
, OP_IdxInsert
, pRJ
->iMatch
, r
, r
+1, nPk
);
2664 sqlite3VdbeAddOp4Int(v
, OP_FilterAdd
, pRJ
->regBloom
, 0, r
+1, nPk
);
2665 sqlite3VdbeChangeP5(v
, OPFLAG_USESEEKRESULT
);
2666 sqlite3VdbeJumpHere(v
, jmp1
);
2667 sqlite3ReleaseTempRange(pParse
, r
, nPk
+1);
2670 /* For a LEFT OUTER JOIN, generate code that will record the fact that
2671 ** at least one row of the right table has matched the left table.
2673 if( pLevel
->iLeftJoin
){
2674 pLevel
->addrFirst
= sqlite3VdbeCurrentAddr(v
);
2675 sqlite3VdbeAddOp2(v
, OP_Integer
, 1, pLevel
->iLeftJoin
);
2676 VdbeComment((v
, "record LEFT JOIN hit"));
2677 if( pLevel
->pRJ
==0 ){
2678 goto code_outer_join_constraints
; /* WHERE clause constraints */
2683 /* Create a subroutine used to process all interior loops and code
2684 ** of the RIGHT JOIN. During normal operation, the subroutine will
2685 ** be in-line with the rest of the code. But at the end, a separate
2686 ** loop will run that invokes this subroutine for unmatched rows
2687 ** of pTab, with all tables to left begin set to NULL.
2689 WhereRightJoin
*pRJ
= pLevel
->pRJ
;
2690 sqlite3VdbeAddOp2(v
, OP_BeginSubrtn
, 0, pRJ
->regReturn
);
2691 pRJ
->addrSubrtn
= sqlite3VdbeCurrentAddr(v
);
2692 assert( pParse
->withinRJSubrtn
< 255 );
2693 pParse
->withinRJSubrtn
++;
2695 /* WHERE clause constraints must be deferred until after outer join
2696 ** row elimination has completed, since WHERE clause constraints apply
2697 ** to the results of the OUTER JOIN. The following loop generates the
2698 ** appropriate WHERE clause constraint checks. tag-20220513a.
2700 code_outer_join_constraints
:
2701 for(pTerm
=pWC
->a
, j
=0; j
<pWC
->nBase
; j
++, pTerm
++){
2702 testcase( pTerm
->wtFlags
& TERM_VIRTUAL
);
2703 testcase( pTerm
->wtFlags
& TERM_CODED
);
2704 if( pTerm
->wtFlags
& (TERM_VIRTUAL
|TERM_CODED
) ) continue;
2705 if( (pTerm
->prereqAll
& pLevel
->notReady
)!=0 ){
2706 assert( pWInfo
->untestedTerms
);
2709 if( pTabItem
->fg
.jointype
& JT_LTORJ
) continue;
2710 assert( pTerm
->pExpr
);
2711 sqlite3ExprIfFalse(pParse
, pTerm
->pExpr
, addrCont
, SQLITE_JUMPIFNULL
);
2712 pTerm
->wtFlags
|= TERM_CODED
;
2716 #if WHERETRACE_ENABLED /* 0x4001 */
2717 if( sqlite3WhereTrace
& 0x4000 ){
2718 sqlite3DebugPrintf("All WHERE-clause terms after coding level %d:\n",
2720 sqlite3WhereClausePrint(pWC
);
2722 if( sqlite3WhereTrace
& 0x1 ){
2723 sqlite3DebugPrintf("End Coding level %d: notReady=%llx\n",
2724 iLevel
, (u64
)pLevel
->notReady
);
2727 return pLevel
->notReady
;
2731 ** Generate the code for the loop that finds all non-matched terms
2732 ** for a RIGHT JOIN.
2734 SQLITE_NOINLINE
void sqlite3WhereRightJoinLoop(
2739 Parse
*pParse
= pWInfo
->pParse
;
2740 Vdbe
*v
= pParse
->pVdbe
;
2741 WhereRightJoin
*pRJ
= pLevel
->pRJ
;
2742 Expr
*pSubWhere
= 0;
2743 WhereClause
*pWC
= &pWInfo
->sWC
;
2744 WhereInfo
*pSubWInfo
;
2745 WhereLoop
*pLoop
= pLevel
->pWLoop
;
2746 SrcItem
*pTabItem
= &pWInfo
->pTabList
->a
[pLevel
->iFrom
];
2751 ExplainQueryPlan((pParse
, 1, "RIGHT-JOIN %s", pTabItem
->pTab
->zName
));
2752 sqlite3VdbeNoJumpsOutsideSubrtn(v
, pRJ
->addrSubrtn
, pRJ
->endSubrtn
,
2754 for(k
=0; k
<iLevel
; k
++){
2757 assert( pWInfo
->a
[k
].pWLoop
->iTab
== pWInfo
->a
[k
].iFrom
);
2758 pRight
= &pWInfo
->pTabList
->a
[pWInfo
->a
[k
].iFrom
];
2759 mAll
|= pWInfo
->a
[k
].pWLoop
->maskSelf
;
2760 if( pRight
->fg
.viaCoroutine
){
2762 v
, OP_Null
, 0, pRight
->regResult
,
2763 pRight
->regResult
+ pRight
->pSelect
->pEList
->nExpr
-1
2766 sqlite3VdbeAddOp1(v
, OP_NullRow
, pWInfo
->a
[k
].iTabCur
);
2767 iIdxCur
= pWInfo
->a
[k
].iIdxCur
;
2769 sqlite3VdbeAddOp1(v
, OP_NullRow
, iIdxCur
);
2772 if( (pTabItem
->fg
.jointype
& JT_LTORJ
)==0 ){
2773 mAll
|= pLoop
->maskSelf
;
2774 for(k
=0; k
<pWC
->nTerm
; k
++){
2775 WhereTerm
*pTerm
= &pWC
->a
[k
];
2776 if( (pTerm
->wtFlags
& (TERM_VIRTUAL
|TERM_SLICE
))!=0
2777 && pTerm
->eOperator
!=WO_ROWVAL
2781 if( pTerm
->prereqAll
& ~mAll
) continue;
2782 if( ExprHasProperty(pTerm
->pExpr
, EP_OuterON
|EP_InnerON
) ) continue;
2783 pSubWhere
= sqlite3ExprAnd(pParse
, pSubWhere
,
2784 sqlite3ExprDup(pParse
->db
, pTerm
->pExpr
, 0));
2789 memcpy(&sFrom
.a
[0], pTabItem
, sizeof(SrcItem
));
2790 sFrom
.a
[0].fg
.jointype
= 0;
2791 assert( pParse
->withinRJSubrtn
< 100 );
2792 pParse
->withinRJSubrtn
++;
2793 pSubWInfo
= sqlite3WhereBegin(pParse
, &sFrom
, pSubWhere
, 0, 0, 0,
2794 WHERE_RIGHT_JOIN
, 0);
2796 int iCur
= pLevel
->iTabCur
;
2797 int r
= ++pParse
->nMem
;
2800 int addrCont
= sqlite3WhereContinueLabel(pSubWInfo
);
2801 Table
*pTab
= pTabItem
->pTab
;
2802 if( HasRowid(pTab
) ){
2803 sqlite3ExprCodeGetColumnOfTable(v
, pTab
, iCur
, -1, r
);
2807 Index
*pPk
= sqlite3PrimaryKeyIndex(pTab
);
2809 pParse
->nMem
+= nPk
- 1;
2810 for(iPk
=0; iPk
<nPk
; iPk
++){
2811 int iCol
= pPk
->aiColumn
[iPk
];
2812 sqlite3ExprCodeGetColumnOfTable(v
, pTab
, iCur
, iCol
,r
+iPk
);
2815 jmp
= sqlite3VdbeAddOp4Int(v
, OP_Filter
, pRJ
->regBloom
, 0, r
, nPk
);
2817 sqlite3VdbeAddOp4Int(v
, OP_Found
, pRJ
->iMatch
, addrCont
, r
, nPk
);
2819 sqlite3VdbeJumpHere(v
, jmp
);
2820 sqlite3VdbeAddOp2(v
, OP_Gosub
, pRJ
->regReturn
, pRJ
->addrSubrtn
);
2821 sqlite3WhereEnd(pSubWInfo
);
2823 sqlite3ExprDelete(pParse
->db
, pSubWhere
);
2824 ExplainQueryPlanPop(pParse
);
2825 assert( pParse
->withinRJSubrtn
>0 );
2826 pParse
->withinRJSubrtn
--;