interplane.Get Omega
Read in your language

sqlite

[Ported from github.com/sqlite/sqlite] Fix bugs in and improve the interface to the ".check" command of the CLI.

Brought by drakestapleton

branch master Branches Tags History

sqlite / src / wherecode.c

3175 lines · 124952 bytes Raw Blame History
1/*
2** 2015-06-06
3**
4** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
6**
7** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
10**
11*************************************************************************
12** This module contains C code that generates VDBE code used to process
13** the WHERE clause of SQL statements.
14**
15** This file was 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.
19*/
20#include "sqliteInt.h"
21#include "whereInt.h"
22
23#ifndef SQLITE_OMIT_EXPLAIN
24
25/*
26** Return the name of the i-th column of the pIdx index.
27*/
28static 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;
33}
34
35/*
36** This routine is a helper for explainIndexRange() below
37**
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
41** terms only.
42*/
43static 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 */
50){
51 int i;
52
53 assert( nTerm>=1 );
54 if( bAnd ) sqlite3_str_append(pStr, " AND ", 5);
55
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));
60 }
61 if( nTerm>1 ) sqlite3_str_append(pStr, ")", 1);
62
63 sqlite3_str_append(pStr, zOp, 1);
64
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);
69 }
70 if( nTerm>1 ) sqlite3_str_append(pStr, ")", 1);
71}
72
73/*
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.
77**
78** For example, if the query:
79**
80** SELECT * FROM t1 WHERE a=1 AND b>2;
81**
82** is run and there is an index on (a, b), then this function returns a
83** string similar to:
84**
85** "a=? AND b>?"
86*/
87static 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;
91 int i, j;
92
93 if( nEq==0 && (pLoop->wsFlags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ) return;
94 sqlite3_str_append(pStr, " (", 2);
95 for(i=0; i<nEq; i++){
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);
99 }
100
101 j = i;
102 if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
103 explainAppendTerm(pStr, pIndex, pLoop->u.btree.nBtm, j, i, ">");
104 i = 1;
105 }
106 if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
107 explainAppendTerm(pStr, pIndex, pLoop->u.btree.nTop, j, i, "<");
108 }
109 sqlite3_str_append(pStr, ")", 1);
110}
111
112/*
113** This function sets the P4 value of an existing OP_Explain opcode to
114** text describing the loop in pLevel. If the OP_Explain opcode already has
115** a P4 value, it is freed before it is overwritten.
116*/
117void sqlite3WhereAddExplainText(
118 Parse *pParse, /* Parse context */
119 int addr, /* Address of OP_Explain opcode */
120 SrcList *pTabList, /* Table list this loop refers to */
121 WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
122 u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
123){
124#if !defined(SQLITE_DEBUG)
125 if( sqlite3ParseToplevel(pParse)->explain==2 || IS_STMT_SCANSTATUS(pParse->db) )
126#endif
127 {
128 VdbeOp *pOp = sqlite3VdbeGetOp(pParse->pVdbe, addr);
129 SrcItem *pItem = &pTabList->a[pLevel->iFrom];
130 sqlite3 *db = pParse->db; /* Database handle */
131 int isSearch; /* True for a SEARCH. False for SCAN. */
132 WhereLoop *pLoop; /* The controlling WhereLoop object */
133 u32 flags; /* Flags that describe this loop */
134#if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_EXPLAIN)
135 char *zMsg; /* Text to add to EQP output */
136#endif
137 StrAccum str; /* EQP output string */
138 char zBuf[100]; /* Initial space for EQP output string */
139
140 if( db->mallocFailed ) return;
141
142 pLoop = pLevel->pWLoop;
143 flags = pLoop->wsFlags;
144
145 isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
146 || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
147 || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
148
149 sqlite3StrAccumInit(&str, db, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH);
150 str.printfFlags = SQLITE_PRINTF_INTERNAL;
151 sqlite3_str_appendf(&str, "%s %S%s",
152 isSearch ? "SEARCH" : "SCAN",
153 pItem,
154 pItem->fg.fromExists ? " EXISTS" : "");
155 if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0 ){
156 const char *zFmt = 0;
157 Index *pIdx;
158
159 assert( pLoop->u.btree.pIndex!=0 );
160 pIdx = pLoop->u.btree.pIndex;
161 assert( !(flags&WHERE_AUTO_INDEX) || (flags&WHERE_IDX_ONLY) );
162 if( !HasRowid(pItem->pSTab) && IsPrimaryKeyIndex(pIdx) ){
163 if( isSearch ){
164 zFmt = "PRIMARY KEY";
165 }
166 }else if( flags & WHERE_PARTIALIDX ){
167 zFmt = "AUTOMATIC PARTIAL COVERING INDEX";
168 }else if( flags & WHERE_AUTO_INDEX ){
169 zFmt = "AUTOMATIC COVERING INDEX";
170 }else if( flags & (WHERE_IDX_ONLY|WHERE_EXPRIDX) ){
171 zFmt = "COVERING INDEX %s";
172 }else{
173 zFmt = "INDEX %s";
174 }
175 if( zFmt ){
176 sqlite3_str_append(&str, " USING ", 7);
177 sqlite3_str_appendf(&str, zFmt, pIdx->zName);
178 explainIndexRange(&str, pLoop);
179 }
180 }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
181 char cRangeOp;
182#if 0 /* Better output, but breaks many tests */
183 const Table *pTab = pItem->pTab;
184 const char *zRowid = pTab->iPKey>=0 ? pTab->aCol[pTab->iPKey].zCnName:
185 "rowid";
186#else
187 const char *zRowid = "rowid";
188#endif
189 sqlite3_str_appendf(&str, " USING INTEGER PRIMARY KEY (%s", zRowid);
190 if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
191 cRangeOp = '=';
192 }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
193 sqlite3_str_appendf(&str, ">? AND %s", zRowid);
194 cRangeOp = '<';
195 }else if( flags&WHERE_BTM_LIMIT ){
196 cRangeOp = '>';
197 }else{
198 assert( flags&WHERE_TOP_LIMIT);
199 cRangeOp = '<';
200 }
201 sqlite3_str_appendf(&str, "%c?)", cRangeOp);
202 }
203#ifndef SQLITE_OMIT_VIRTUALTABLE
204 else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
205 sqlite3_str_appendall(&str, " VIRTUAL TABLE INDEX ");
206 sqlite3_str_appendf(&str,
207 pLoop->u.vtab.bIdxNumHex ? "0x%x:%s" : "%d:%s",
208 pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
209 }
210#endif
211 if( pItem->fg.jointype & JT_LEFT ){
212 sqlite3_str_appendf(&str, " LEFT-JOIN");
213 }
214#ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS
215 if( pLoop->nOut>=10 ){
216 sqlite3_str_appendf(&str, " (~%llu rows)",
217 sqlite3LogEstToInt(pLoop->nOut));
218 }else{
219 sqlite3_str_append(&str, " (~1 row)", 9);
220 }
221#endif
222#if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_EXPLAIN)
223 zMsg = sqlite3StrAccumFinish(&str);
224 sqlite3ExplainBreakpoint("",zMsg);
225#endif
226
227 assert( pOp->opcode==OP_Explain );
228 assert( pOp->p4type==P4_DYNAMIC || pOp->p4.z==0 );
229 sqlite3DbFree(db, pOp->p4.z);
230 pOp->p4type = P4_DYNAMIC;
231 pOp->p4.z = sqlite3StrAccumFinish(&str);
232 }
233}
234
235
236/*
237** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
238** command, or if stmt_scanstatus_v2() stats are enabled, or if SQLITE_DEBUG
239** was defined at compile-time. If it is not a no-op, a single OP_Explain
240** opcode is added to the output to describe the table scan strategy in pLevel.
241**
242** If an OP_Explain opcode is added to the VM, its address is returned.
243** Otherwise, if no OP_Explain is coded, zero is returned.
244*/
245int sqlite3WhereExplainOneScan(
246 Parse *pParse, /* Parse context */
247 SrcList *pTabList, /* Table list this loop refers to */
248 WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
249 u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
250){
251 int ret = 0;
252#if !defined(SQLITE_DEBUG)
253 if( sqlite3ParseToplevel(pParse)->explain==2 || IS_STMT_SCANSTATUS(pParse->db) )
254#endif
255 {
256 if( (pLevel->pWLoop->wsFlags & WHERE_MULTI_OR)==0
257 && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0
258 ){
259 Vdbe *v = pParse->pVdbe;
260 int addr = sqlite3VdbeCurrentAddr(v);
261 ret = sqlite3VdbeAddOp3(
262 v, OP_Explain, addr, pParse->addrExplain, pLevel->pWLoop->rRun
263 );
264 sqlite3WhereAddExplainText(pParse, addr, pTabList, pLevel, wctrlFlags);
265 }
266 }
267 return ret;
268}
269
270/*
271** Add a single OP_Explain opcode that describes a Bloom filter.
272**
273** Or if not processing EXPLAIN QUERY PLAN and not in a SQLITE_DEBUG and/or
274** SQLITE_ENABLE_STMT_SCANSTATUS build, then OP_Explain opcodes are not
275** required and this routine is a no-op.
276**
277** If an OP_Explain opcode is added to the VM, its address is returned.
278** Otherwise, if no OP_Explain is coded, zero is returned.
279*/
280int sqlite3WhereExplainBloomFilter(
281 const Parse *pParse, /* Parse context */
282 const WhereInfo *pWInfo, /* WHERE clause */
283 const WhereLevel *pLevel /* Bloom filter on this level */
284){
285 int ret = 0;
286 SrcItem *pItem = &pWInfo->pTabList->a[pLevel->iFrom];
287 Vdbe *v = pParse->pVdbe; /* VM being constructed */
288 sqlite3 *db = pParse->db; /* Database handle */
289 char *zMsg; /* Text to add to EQP output */
290 int i; /* Loop counter */
291 WhereLoop *pLoop; /* The where loop */
292 StrAccum str; /* EQP output string */
293 char zBuf[100]; /* Initial space for EQP output string */
294
295 sqlite3StrAccumInit(&str, db, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH);
296 str.printfFlags = SQLITE_PRINTF_INTERNAL;
297 sqlite3_str_appendf(&str, "BLOOM FILTER ON %S (", pItem);
298 pLoop = pLevel->pWLoop;
299 if( pLoop->wsFlags & WHERE_IPK ){
300 const Table *pTab = pItem->pSTab;
301 if( pTab->iPKey>=0 ){
302 sqlite3_str_appendf(&str, "%s=?", pTab->aCol[pTab->iPKey].zCnName);
303 }else{
304 sqlite3_str_appendf(&str, "rowid=?");
305 }
306 }else{
307 for(i=pLoop->nSkip; i<pLoop->u.btree.nEq; i++){
308 const char *z = explainIndexColumnName(pLoop->u.btree.pIndex, i);
309 if( i>pLoop->nSkip ) sqlite3_str_append(&str, " AND ", 5);
310 sqlite3_str_appendf(&str, "%s=?", z);
311 }
312 }
313 sqlite3_str_append(&str, ")", 1);
314 zMsg = sqlite3StrAccumFinish(&str);
315 ret = sqlite3VdbeAddOp4(v, OP_Explain, sqlite3VdbeCurrentAddr(v),
316 pParse->addrExplain, 0, zMsg,P4_DYNAMIC);
317
318 sqlite3VdbeScanStatus(v, sqlite3VdbeCurrentAddr(v)-1, 0, 0, 0, 0);
319 return ret;
320}
321#endif /* SQLITE_OMIT_EXPLAIN */
322
323#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
324/*
325** Configure the VM passed as the first argument with an
326** sqlite3_stmt_scanstatus() entry corresponding to the scan used to
327** implement level pLvl. Argument pSrclist is a pointer to the FROM
328** clause that the scan reads data from.
329**
330** If argument addrExplain is not 0, it must be the address of an
331** OP_Explain instruction that describes the same loop.
332*/
333void sqlite3WhereAddScanStatus(
334 Vdbe *v, /* Vdbe to add scanstatus entry to */
335 SrcList *pSrclist, /* FROM clause pLvl reads data from */
336 WhereLevel *pLvl, /* Level to add scanstatus() entry for */
337 int addrExplain /* Address of OP_Explain (or 0) */
338){
339 if( IS_STMT_SCANSTATUS( sqlite3VdbeDb(v) ) ){
340 const char *zObj = 0;
341 WhereLoop *pLoop = pLvl->pWLoop;
342 int wsFlags = pLoop->wsFlags;
343 int viaCoroutine = 0;
344
345 if( (wsFlags & WHERE_VIRTUALTABLE)==0 && pLoop->u.btree.pIndex!=0 ){
346 zObj = pLoop->u.btree.pIndex->zName;
347 }else{
348 zObj = pSrclist->a[pLvl->iFrom].zName;
349 viaCoroutine = pSrclist->a[pLvl->iFrom].fg.viaCoroutine;
350 }
351 sqlite3VdbeScanStatus(
352 v, addrExplain, pLvl->addrBody, pLvl->addrVisit, pLoop->nOut, zObj
353 );
354
355 if( viaCoroutine==0 ){
356 if( (wsFlags & (WHERE_MULTI_OR|WHERE_AUTO_INDEX))==0 ){
357 sqlite3VdbeScanStatusRange(v, addrExplain, -1, pLvl->iTabCur);
358 }
359 if( wsFlags & WHERE_INDEXED ){
360 sqlite3VdbeScanStatusRange(v, addrExplain, -1, pLvl->iIdxCur);
361 }
362 }else{
363 int addr;
364 VdbeOp *pOp;
365 assert( pSrclist->a[pLvl->iFrom].fg.isSubquery );
366 addr = pSrclist->a[pLvl->iFrom].u4.pSubq->addrFillSub;
367 pOp = sqlite3VdbeGetOp(v, addr-1);
368 assert( sqlite3VdbeDb(v)->mallocFailed || pOp->opcode==OP_InitCoroutine );
369 assert( sqlite3VdbeDb(v)->mallocFailed || pOp->p2>addr );
370 sqlite3VdbeScanStatusRange(v, addrExplain, addr, pOp->p2-1);
371 }
372 }
373}
374#endif
375
376
377/*
378** Disable a term in the WHERE clause. Except, do not disable the term
379** if it controls a LEFT OUTER JOIN and it did not originate in the ON
380** or USING clause of that join.
381**
382** Consider the term t2.z='ok' in the following queries:
383**
384** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
385** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
386** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
387**
388** The t2.z='ok' is disabled in the in (2) because it originates
389** in the ON clause. The term is disabled in (3) because it is not part
390** of a LEFT OUTER JOIN. In (1), the term is not disabled.
391**
392** Disabling a term causes that term to not be tested in the inner loop
393** of the join. Disabling is an optimization. When terms are satisfied
394** by indices, we disable them to prevent redundant tests in the inner
395** loop. We would get the correct results if nothing were ever disabled,
396** but joins might run a little slower. The trick is to disable as much
397** as we can without disabling too much. If we disabled in (1), we'd get
398** the wrong answer. See ticket #813.
399**
400** If all the children of a term are disabled, then that term is also
401** automatically disabled. In this way, terms get disabled if derived
402** virtual terms are tested first. For example:
403**
404** x GLOB 'abc*' AND x>='abc' AND x<'acd'
405** \___________/ \______/ \_____/
406** parent child1 child2
407**
408** Only the parent term was in the original WHERE clause. The child1
409** and child2 terms were added by the LIKE optimization. If both of
410** the virtual child terms are valid, then testing of the parent can be
411** skipped.
412**
413** Usually the parent term is marked as TERM_CODED. But if the parent
414** term was originally TERM_LIKE, then the parent gets TERM_LIKECOND instead.
415** The TERM_LIKECOND marking indicates that the term should be coded inside
416** a conditional such that is only evaluated on the second pass of a
417** LIKE-optimization loop, when scanning BLOBs instead of strings.
418*/
419static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
420 int nLoop = 0;
421 assert( pTerm!=0 );
422 while( (pTerm->wtFlags & TERM_CODED)==0
423 && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_OuterON))
424 && (pLevel->notReady & pTerm->prereqAll)==0
425 ){
426 if( nLoop && (pTerm->wtFlags & TERM_LIKE)!=0 ){
427 pTerm->wtFlags |= TERM_LIKECOND;
428 }else{
429 pTerm->wtFlags |= TERM_CODED;
430 }
431#ifdef WHERETRACE_ENABLED
432 if( (sqlite3WhereTrace & 0x4001)==0x4001 ){
433 sqlite3DebugPrintf("DISABLE-");
434 sqlite3WhereTermPrint(pTerm, (int)(pTerm - (pTerm->pWC->a)));
435 }
436#endif
437 if( pTerm->iParent<0 ) break;
438 pTerm = &pTerm->pWC->a[pTerm->iParent];
439 assert( pTerm!=0 );
440 pTerm->nChild--;
441 if( pTerm->nChild!=0 ) break;
442 nLoop++;
443 }
444}
445
446/*
447** Code an OP_Affinity opcode to apply the column affinity string zAff
448** to the n registers starting at base.
449**
450** As an optimization, SQLITE_AFF_BLOB and SQLITE_AFF_NONE entries (which
451** are no-ops) at the beginning and end of zAff are ignored. If all entries
452** in zAff are SQLITE_AFF_BLOB or SQLITE_AFF_NONE, then no code gets generated.
453**
454** This routine makes its own copy of zAff so that the caller is free
455** to modify zAff after this routine returns.
456*/
457static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
458 Vdbe *v = pParse->pVdbe;
459 if( zAff==0 ){
460 assert( pParse->db->mallocFailed );
461 return;
462 }
463 assert( v!=0 );
464
465 /* Adjust base and n to skip over SQLITE_AFF_BLOB and SQLITE_AFF_NONE
466 ** entries at the beginning and end of the affinity string.
467 */
468 assert( SQLITE_AFF_NONE<SQLITE_AFF_BLOB );
469 while( n>0 && zAff[0]<=SQLITE_AFF_BLOB ){
470 n--;
471 base++;
472 zAff++;
473 }
474 while( n>1 && zAff[n-1]<=SQLITE_AFF_BLOB ){
475 n--;
476 }
477
478 /* Code the OP_Affinity opcode if there is anything left to do. */
479 if( n>0 ){
480 sqlite3VdbeAddOp4(v, OP_Affinity, base, n, 0, zAff, n);
481 }
482}
483
484/*
485** Expression pRight, which is the RHS of a comparison operation, is
486** either a vector of n elements or, if n==1, a scalar expression.
487** Before the comparison operation, affinity zAff is to be applied
488** to the pRight values. This function modifies characters within the
489** affinity string to SQLITE_AFF_BLOB if either:
490**
491** * the comparison will be performed with no affinity, or
492** * the affinity change in zAff is guaranteed not to change the value.
493*/
494static void updateRangeAffinityStr(
495 Expr *pRight, /* RHS of comparison */
496 int n, /* Number of vector elements in comparison */
497 char *zAff /* Affinity string to modify */
498){
499 int i;
500 for(i=0; i<n; i++){
501 Expr *p = sqlite3VectorFieldSubexpr(pRight, i);
502 if( sqlite3CompareAffinity(p, zAff[i])==SQLITE_AFF_BLOB
503 || sqlite3ExprNeedsNoAffinityChange(p, zAff[i])
504 ){
505 zAff[i] = SQLITE_AFF_BLOB;
506 }
507 }
508}
509
510/*
511** The pOrderBy->a[].u.x.iOrderByCol values might be incorrect because
512** columns might have been rearranged in the result set. This routine
513** fixes them up.
514**
515** pEList is the new result set. The pEList->a[].u.x.iOrderByCol values
516** contain the *old* locations of each expression. This is a temporary
517** use of u.x.iOrderByCol, not its intended use. The caller must reset
518** u.x.iOrderByCol back to zero for all entries in pEList before the
519** caller returns.
520**
521** This routine changes pOrderBy->a[].u.x.iOrderByCol values from
522** pEList->a[N].u.x.iOrderByCol into N+1. (The "+1" is because of the 1-based
523** indexing used by iOrderByCol.) Or if no match, iOrderByCol is set to zero.
524*/
525static void adjustOrderByCol(ExprList *pOrderBy, ExprList *pEList){
526 int i, j;
527 if( pOrderBy==0 ) return;
528 for(i=0; i<pOrderBy->nExpr; i++){
529 int t = pOrderBy->a[i].u.x.iOrderByCol;
530 if( t==0 ) continue;
531 for(j=0; j<pEList->nExpr; j++){
532 if( pEList->a[j].u.x.iOrderByCol==t ){
533 pOrderBy->a[i].u.x.iOrderByCol = j+1;
534 break;
535 }
536 }
537 if( j>=pEList->nExpr ){
538 pOrderBy->a[i].u.x.iOrderByCol = 0;
539 }
540 }
541}
542
543
544/*
545** pX is an expression of the form: (vector) IN (SELECT ...)
546** In other words, it is a vector IN operator with a SELECT clause on the
547** RHS. But not all terms in the vector are indexable and the terms might
548** not be in the correct order for indexing.
549**
550** This routine makes a copy of the input pX expression and then adjusts
551** the vector on the LHS with corresponding changes to the SELECT so that
552** the vector contains only index terms and those terms are in the correct
553** order. The modified IN expression is returned. The caller is responsible
554** for deleting the returned expression.
555**
556** Example:
557**
558** CREATE TABLE t1(a,b,c,d,e,f);
559** CREATE INDEX t1x1 ON t1(e,c);
560** SELECT * FROM t1 WHERE (a,b,c,d,e) IN (SELECT v,w,x,y,z FROM t2)
561** \_______________________________________/
562** The pX expression
563**
564** Since only columns e and c can be used with the index, in that order,
565** the modified IN expression that is returned will be:
566**
567** (e,c) IN (SELECT z,x FROM t2)
568**
569** The reduced pX is different from the original (obviously) and thus is
570** only used for indexing, to improve performance. The original unaltered
571** IN expression must also be run on each output row for correctness.
572*/
573static Expr *removeUnindexableInClauseTerms(
574 Parse *pParse, /* The parsing context */
575 int iEq, /* Look at loop terms starting here */
576 WhereLoop *pLoop, /* The current loop */
577 Expr *pX /* The IN expression to be reduced */
578){
579 sqlite3 *db = pParse->db;
580 Select *pSelect; /* Pointer to the SELECT on the RHS */
581 Expr *pNew;
582 pNew = sqlite3ExprDup(db, pX, 0);
583 if( db->mallocFailed==0 ){
584 for(pSelect=pNew->x.pSelect; pSelect; pSelect=pSelect->pPrior){
585 ExprList *pOrigRhs; /* Original unmodified RHS */
586 ExprList *pOrigLhs = 0; /* Original unmodified LHS */
587 ExprList *pRhs = 0; /* New RHS after modifications */
588 ExprList *pLhs = 0; /* New LHS after mods */
589 int i; /* Loop counter */
590 int nRhs = 0; /* Number of RHS terms added so far */
591
592 assert( ExprUseXSelect(pNew) );
593 pOrigRhs = pSelect->pEList;
594 assert( pNew->pLeft!=0 );
595 assert( ExprUseXList(pNew->pLeft) );
596 if( pSelect==pNew->x.pSelect ){
597 pOrigLhs = pNew->pLeft->x.pList;
598 }
599 for(i=iEq; i<pLoop->nLTerm; i++){
600 if( pLoop->aLTerm[i]->pExpr==pX ){
601 int iField;
602 assert( (pLoop->aLTerm[i]->eOperator & (WO_OR|WO_AND))==0 );
603 iField = pLoop->aLTerm[i]->u.x.iField - 1;
604 if( iField!=nRhs ){
605 ExprClearProperty(pNew, EP_Subrtn);
606 }
607 if( NEVER(pOrigRhs->a[iField].pExpr==0) ){
608 continue; /* Duplicate PK column */
609 }
610 pRhs = sqlite3ExprListAppend(pParse, pRhs, pOrigRhs->a[iField].pExpr);
611 pOrigRhs->a[iField].pExpr = 0;
612 if( pRhs ) pRhs->a[pRhs->nExpr-1].u.x.iOrderByCol = iField+1;
613 if( pOrigLhs ){
614 assert( pOrigLhs->a[iField].pExpr!=0 );
615 pLhs = sqlite3ExprListAppend(pParse,pLhs,pOrigLhs->a[iField].pExpr);
616 pOrigLhs->a[iField].pExpr = 0;
617 }
618 nRhs++;
619 }
620 }
621 if( nRhs<pOrigRhs->nExpr ){
622 ExprClearProperty(pNew, EP_Subrtn); /* See bug 2026-10-16T22:07:15Z */
623 }
624 sqlite3ExprListDelete(db, pOrigRhs);
625 if( pOrigLhs ){
626 sqlite3ExprListDelete(db, pOrigLhs);
627 pNew->pLeft->x.pList = pLhs;
628 }
629 pSelect->pEList = pRhs;
630 pSelect->selId = ++pParse->nSelect; /* Req'd for SubrtnSig validity */
631 if( pLhs && pLhs->nExpr==1 ){
632 /* Take care here not to generate a TK_VECTOR containing only a
633 ** single value. Since the parser never creates such a vector, some
634 ** of the subroutines do not handle this case. */
635 Expr *p = pLhs->a[0].pExpr;
636 pLhs->a[0].pExpr = 0;
637 sqlite3ExprDelete(db, pNew->pLeft);
638 pNew->pLeft = p;
639 }
640
641 /* If either the ORDER BY clause or the GROUP BY clause contains
642 ** references to result-set columns, those references might now be
643 ** obsolete. So fix them up.
644 */
645 assert( pRhs!=0 || db->mallocFailed );
646 if( pRhs ){
647 adjustOrderByCol(pSelect->pOrderBy, pRhs);
648 adjustOrderByCol(pSelect->pGroupBy, pRhs);
649 for(i=0; i<pRhs->nExpr; i++) pRhs->a[i].u.x.iOrderByCol = 0;
650 }
651
652#if 0
653 printf("For indexing, change the IN expr:\n");
654 sqlite3TreeViewExpr(0, pX, 0);
655 printf("Into:\n");
656 sqlite3TreeViewExpr(0, pNew, 0);
657#endif
658 }
659 }
660 return pNew;
661}
662
663
664#ifndef SQLITE_OMIT_SUBQUERY
665/*
666** Generate code for a single X IN (....) term of the WHERE clause.
667**
668** This is a special-case of codeEqualityTerm() that works for IN operators
669** only. It is broken out into a subroutine because this case is
670** uncommon and by splitting it off into a subroutine, the common case
671** runs faster.
672**
673** The current value for the constraint is left in register iTarget.
674** This routine sets up a loop that will iterate over all values of X.
675*/
676static SQLITE_NOINLINE void codeINTerm(
677 Parse *pParse, /* The parsing context */
678 WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
679 WhereLevel *pLevel, /* The level of the FROM clause we are working on */
680 int iEq, /* Index of the equality term within this level */
681 int bRev, /* True for reverse-order IN operations */
682 int iTarget /* Attempt to leave results in this register */
683){
684 Expr *pX = pTerm->pExpr;
685 int eType = IN_INDEX_NOOP;
686 int iTab;
687 struct InLoop *pIn;
688 WhereLoop *pLoop = pLevel->pWLoop;
689 Vdbe *v = pParse->pVdbe;
690 int i;
691 int nEq = 0;
692 int *aiMap = 0;
693
694 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
695 && pLoop->u.btree.pIndex!=0
696 && pLoop->u.btree.pIndex->aSortOrder[iEq]
697 ){
698 testcase( iEq==0 );
699 testcase( bRev );
700 bRev = !bRev;
701 }
702 assert( pX->op==TK_IN );
703
704 for(i=0; i<iEq; i++){
705 if( pLoop->aLTerm[i] && pLoop->aLTerm[i]->pExpr==pX ){
706 disableTerm(pLevel, pTerm);
707 return;
708 }
709 }
710 for(i=iEq; i<pLoop->nLTerm; i++){
711 assert( pLoop->aLTerm[i]!=0 );
712 if( pLoop->aLTerm[i]->pExpr==pX ) nEq++;
713 }
714
715 iTab = 0;
716 if( !ExprUseXSelect(pX) || pX->x.pSelect->pEList->nExpr==1 ){
717 eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, 0, &iTab);
718 }else{
719 sqlite3 *db = pParse->db;
720 Expr *pXMod = removeUnindexableInClauseTerms(pParse, iEq, pLoop, pX);
721 if( nEq>1 ){
722 /* If this IN(SELECT ...) expression drives more than one column of
723 ** the index, disable the seek-scan optimization. The reasons for this
724 ** are that (a) it is only possible to make this happen by populating
725 ** the sqlite_stat1 table with inconsistent information, and (b) it
726 ** would require sqlite3FindInIndex() to find an index that is not
727 ** only unique for the columns in question, but also delivers them
728 ** in sorted order (requires checking asc/desc, and rejecting cases
729 ** where the indexed columns are not in the right order). */
730 pLoop->wsFlags &= ~WHERE_IN_SEEKSCAN;
731 }
732 if( !db->mallocFailed ){
733 int nCol = pX->x.pSelect->pEList->nExpr;
734 aiMap = (int*)sqlite3DbMallocZero(db, sizeof(int)*nCol);
735 eType = sqlite3FindInIndex(pParse, pXMod, IN_INDEX_LOOP, 0, aiMap, &iTab);
736 }
737 sqlite3ExprDelete(db, pXMod);
738 }
739
740 if( eType==IN_INDEX_INDEX_DESC ){
741 testcase( bRev );
742 bRev = !bRev;
743 }
744 sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
745 VdbeCoverageIf(v, bRev);
746 VdbeCoverageIf(v, !bRev);
747
748 assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
749 pLoop->wsFlags |= WHERE_IN_ABLE;
750 if( pLevel->u.in.nIn==0 ){
751 pLevel->addrNxt = sqlite3VdbeMakeLabel(pParse);
752 }
753 if( iEq>0 && (pLoop->wsFlags & WHERE_IN_SEEKSCAN)==0 ){
754 pLoop->wsFlags |= WHERE_IN_EARLYOUT;
755 }
756
757 i = pLevel->u.in.nIn;
758 pLevel->u.in.nIn += nEq;
759 pLevel->u.in.aInLoop =
760 sqlite3WhereRealloc(pTerm->pWC->pWInfo,
761 pLevel->u.in.aInLoop,
762 sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
763 pIn = pLevel->u.in.aInLoop;
764 if( pIn ){
765 int iMap = 0; /* Index in aiMap[] */
766 pIn += i;
767 for(i=iEq; i<pLoop->nLTerm; i++){
768 if( pLoop->aLTerm[i]->pExpr==pX ){
769 int iOut = iTarget + i - iEq;
770 if( eType==IN_INDEX_ROWID ){
771 pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iOut);
772 }else{
773 int iCol = aiMap ? aiMap[iMap++] : 0;
774 pIn->addrInTop = sqlite3VdbeAddOp3(v,OP_Column,iTab, iCol, iOut);
775 }
776 sqlite3VdbeAddOp1(v, OP_IsNull, iOut); VdbeCoverage(v);
777 if( i==iEq ){
778 pIn->iCur = iTab;
779 pIn->eEndLoopOp = bRev ? OP_Prev : OP_Next;
780 if( iEq>0 ){
781 pIn->iBase = iTarget - i;
782 pIn->nPrefix = i;
783 }else{
784 pIn->nPrefix = 0;
785 }
786 }else{
787 pIn->eEndLoopOp = OP_Noop;
788 }
789 pIn++;
790 }
791 }
792 testcase( iEq>0
793 && (pLoop->wsFlags & WHERE_IN_SEEKSCAN)==0
794 && (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 );
795 if( iEq>0
796 && (pLoop->wsFlags & (WHERE_IN_SEEKSCAN|WHERE_VIRTUALTABLE))==0
797 ){
798 sqlite3VdbeAddOp3(v, OP_SeekHit, pLevel->iIdxCur, 0, iEq);
799 }
800 }else{
801 pLevel->u.in.nIn = 0;
802 }
803 sqlite3DbFree(pParse->db, aiMap);
804}
805#endif
806
807
808/*
809** Generate code for a single equality term of the WHERE clause. An equality
810** term can be either X=expr or X IN (...). pTerm is the term to be
811** coded.
812**
813** The current value for the constraint is left in a register, the index
814** of which is returned. An attempt is made store the result in iTarget but
815** this is only guaranteed for TK_ISNULL and TK_IN constraints. If the
816** constraint is a TK_EQ or TK_IS, then the current value might be left in
817** some other register and it is the caller's responsibility to compensate.
818**
819** For a constraint of the form X=expr, the expression is evaluated in
820** straight-line code. For constraints of the form X IN (...)
821** this routine sets up a loop that will iterate over all values of X.
822*/
823static int codeEqualityTerm(
824 Parse *pParse, /* The parsing context */
825 WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
826 WhereLevel *pLevel, /* The level of the FROM clause we are working on */
827 int iEq, /* Index of the equality term within this level */
828 int bRev, /* True for reverse-order IN operations */
829 int iTarget /* Attempt to leave results in this register */
830){
831 Expr *pX = pTerm->pExpr;
832 int iReg; /* Register holding results */
833
834 assert( pLevel->pWLoop->aLTerm[iEq]==pTerm );
835 assert( iTarget>0 );
836 if( pX->op==TK_EQ || pX->op==TK_IS ){
837 iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
838 }else if( pX->op==TK_ISNULL ){
839 iReg = iTarget;
840 sqlite3VdbeAddOp2(pParse->pVdbe, OP_Null, 0, iReg);
841#ifndef SQLITE_OMIT_SUBQUERY
842 }else{
843 assert( pX->op==TK_IN );
844 iReg = iTarget;
845 codeINTerm(pParse, pTerm, pLevel, iEq, bRev, iTarget);
846#endif
847 }
848
849 /* As an optimization, try to disable the WHERE clause term that is
850 ** driving the index as it will always be true. The correct answer is
851 ** obtained regardless, but we might get the answer with fewer CPU cycles
852 ** by omitting the term.
853 **
854 ** But do not disable the term unless we are certain that the term is
855 ** not a transitive constraint. For an example of where that does not
856 ** work, see https://sqlite.org/forum/forumpost/eb8613976a (2021-05-04)
857 */
858 if( (pLevel->pWLoop->wsFlags & WHERE_TRANSCONS)==0
859 || (pTerm->eOperator & WO_EQUIV)==0
860 ){
861 disableTerm(pLevel, pTerm);
862 }
863
864 return iReg;
865}
866
867/*
868** Generate code that will evaluate all == and IN constraints for an
869** index scan.
870**
871** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
872** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
873** The index has as many as three equality constraints, but in this
874** example, the third "c" value is an inequality. So only two
875** constraints are coded. This routine will generate code to evaluate
876** a==5 and b IN (1,2,3). The current values for a and b will be stored
877** in consecutive registers and the index of the first register is returned.
878**
879** In the example above nEq==2. But this subroutine works for any value
880** of nEq including 0. If nEq==0, this routine is nearly a no-op.
881** The only thing it does is allocate the pLevel->iMem memory cell and
882** compute the affinity string.
883**
884** The nExtraReg parameter is 0 or 1. It is 0 if all WHERE clause constraints
885** are == or IN and are covered by the nEq. nExtraReg is 1 if there is
886** an inequality constraint (such as the "c>=5 AND c<10" in the example) that
887** occurs after the nEq quality constraints.
888**
889** This routine allocates a range of nEq+nExtraReg memory cells and returns
890** the index of the first memory cell in that range. The code that
891** calls this routine will use that memory range to store keys for
892** start and termination conditions of the loop.
893** key value of the loop. If one or more IN operators appear, then
894** this routine allocates an additional nEq memory cells for internal
895** use.
896**
897** Before returning, *pzAff is set to point to a buffer containing a
898** copy of the column affinity string of the index allocated using
899** sqlite3DbMalloc(). Except, entries in the copy of the string associated
900** with equality constraints that use BLOB or NONE affinity are set to
901** SQLITE_AFF_BLOB. This is to deal with SQL such as the following:
902**
903** CREATE TABLE t1(a TEXT PRIMARY KEY, b);
904** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
905**
906** In the example above, the index on t1(a) has TEXT affinity. But since
907** the right hand side of the equality constraint (t2.b) has BLOB/NONE affinity,
908** no conversion should be attempted before using a t2.b value as part of
909** a key to search the index. Hence the first byte in the returned affinity
910** string in this example would be set to SQLITE_AFF_BLOB.
911*/
912static int codeAllEqualityTerms(
913 Parse *pParse, /* Parsing context */
914 WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
915 int bRev, /* Reverse the order of IN operators */
916 int nExtraReg, /* Number of extra registers to allocate */
917 char **pzAff /* OUT: Set to point to affinity string */
918){
919 u16 nEq; /* The number of == or IN constraints to code */
920 u16 nSkip; /* Number of left-most columns to skip */
921 Vdbe *v = pParse->pVdbe; /* The vm under construction */
922 Index *pIdx; /* The index being used for this loop */
923 WhereTerm *pTerm; /* A single constraint term */
924 WhereLoop *pLoop; /* The WhereLoop object */
925 int j; /* Loop counter */
926 int regBase; /* Base register */
927 int nReg; /* Number of registers to allocate */
928 char *zAff; /* Affinity string to return */
929
930 /* This module is only called on query plans that use an index. */
931 pLoop = pLevel->pWLoop;
932 assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
933 nEq = pLoop->u.btree.nEq;
934 nSkip = pLoop->nSkip;
935 pIdx = pLoop->u.btree.pIndex;
936 assert( pIdx!=0 );
937
938 /* Figure out how many memory cells we will need then allocate them.
939 */
940 regBase = pParse->nMem + 1;
941 nReg = nEq + nExtraReg;
942 pParse->nMem += nReg;
943
944 zAff = sqlite3DbStrDup(pParse->db,sqlite3IndexAffinityStr(pParse->db,pIdx));
945 assert( zAff!=0 || pParse->db->mallocFailed );
946
947 if( nSkip ){
948 int iIdxCur = pLevel->iIdxCur;
949 sqlite3VdbeAddOp3(v, OP_Null, 0, regBase, regBase+nSkip-1);
950 sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur);
951 VdbeCoverageIf(v, bRev==0);
952 VdbeCoverageIf(v, bRev!=0);
953 VdbeComment((v, "begin skip-scan on %s", pIdx->zName));
954 j = sqlite3VdbeAddOp0(v, OP_Goto);
955 assert( pLevel->addrSkip==0 );
956 pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT),
957 iIdxCur, 0, regBase, nSkip);
958 VdbeCoverageIf(v, bRev==0);
959 VdbeCoverageIf(v, bRev!=0);
960 sqlite3VdbeJumpHere(v, j);
961 for(j=0; j<nSkip; j++){
962 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, j, regBase+j);
963 testcase( pIdx->aiColumn[j]==XN_EXPR );
964 VdbeComment((v, "%s", explainIndexColumnName(pIdx, j)));
965 }
966 }
967
968 /* Evaluate the equality constraints
969 */
970 assert( zAff==0 || (int)strlen(zAff)>=nEq );
971 for(j=nSkip; j<nEq; j++){
972 int r1;
973 pTerm = pLoop->aLTerm[j];
974 assert( pTerm!=0 );
975 /* The following testcase is true for indices with redundant columns.
976 ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
977 testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
978 testcase( pTerm->wtFlags & TERM_VIRTUAL );
979 r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
980 if( r1!=regBase+j ){
981 sqlite3VdbeAddOp2(v, OP_Copy, r1, regBase+j);
982 }
983 if( pTerm->eOperator & WO_IN ){
984 if( pTerm->pExpr->flags & EP_xIsSelect ){
985 /* No affinity ever needs to be (or should be) applied to a value
986 ** from the RHS of an "? IN (SELECT ...)" expression. The
987 ** sqlite3FindInIndex() routine has already ensured that the
988 ** affinity of the comparison has been applied to the value. */
989 if( zAff ) zAff[j] = SQLITE_AFF_BLOB;
990 }
991 }else if( (pTerm->eOperator & WO_ISNULL)==0 ){
992 Expr *pRight = pTerm->pExpr->pRight;
993 if( (pTerm->wtFlags & TERM_IS)==0 && sqlite3ExprCanBeNull(pRight) ){
994 sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk);
995 VdbeCoverage(v);
996 }
997 if( pParse->nErr==0 ){
998 assert( pParse->db->mallocFailed==0 );
999 if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_BLOB ){
1000 zAff[j] = SQLITE_AFF_BLOB;
1001 }
1002 if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
1003 zAff[j] = SQLITE_AFF_BLOB;
1004 }
1005 }
1006 }
1007 }
1008 *pzAff = zAff;
1009 return regBase;
1010}
1011
1012#ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
1013/*
1014** If the most recently coded instruction is a constant range constraint
1015** (a string literal) that originated from the LIKE optimization, then
1016** set P3 and P5 on the OP_String opcode so that the string will be cast
1017** to a BLOB at appropriate times.
1018**
1019** The LIKE optimization trys to evaluate "x LIKE 'abc%'" as a range
1020** expression: "x>='ABC' AND x<'abd'". But this requires that the range
1021** scan loop run twice, once for strings and a second time for BLOBs.
1022** The OP_String opcodes on the second pass convert the upper and lower
1023** bound string constants to blobs. This routine makes the necessary changes
1024** to the OP_String opcodes for that to happen.
1025**
1026** Except, of course, if SQLITE_LIKE_DOESNT_MATCH_BLOBS is defined, then
1027** only the one pass through the string space is required, so this routine
1028** becomes a no-op.
1029*/
1030static void whereLikeOptimizationStringFixup(
1031 Vdbe *v, /* prepared statement under construction */
1032 WhereLevel *pLevel, /* The loop that contains the LIKE operator */
1033 WhereTerm *pTerm /* The upper or lower bound just coded */
1034){
1035 if( pTerm->wtFlags & TERM_LIKEOPT ){
1036 VdbeOp *pOp;
1037 assert( pLevel->iLikeRepCntr>0 );
1038 pOp = sqlite3VdbeGetLastOp(v);
1039 assert( pOp!=0 );
1040 assert( pOp->opcode==OP_String8
1041 || pTerm->pWC->pWInfo->pParse->db->mallocFailed );
1042 pOp->p3 = (int)(pLevel->iLikeRepCntr>>1); /* Register holding counter */
1043 pOp->p5 = (u8)(pLevel->iLikeRepCntr&1); /* ASC or DESC */
1044 }
1045}
1046#else
1047# define whereLikeOptimizationStringFixup(A,B,C)
1048#endif
1049
1050#ifdef SQLITE_ENABLE_CURSOR_HINTS
1051/*
1052** Information is passed from codeCursorHint() down to individual nodes of
1053** the expression tree (by sqlite3WalkExpr()) using an instance of this
1054** structure.
1055*/
1056struct CCurHint {
1057 int iTabCur; /* Cursor for the main table */
1058 int iIdxCur; /* Cursor for the index, if pIdx!=0. Unused otherwise */
1059 Index *pIdx; /* The index used to access the table */
1060};
1061
1062/*
1063** This function is called for every node of an expression that is a candidate
1064** for a cursor hint on an index cursor. For TK_COLUMN nodes that reference
1065** the table CCurHint.iTabCur, verify that the same column can be
1066** accessed through the index. If it cannot, then set pWalker->eCode to 1.
1067*/
1068static int codeCursorHintCheckExpr(Walker *pWalker, Expr *pExpr){
1069 struct CCurHint *pHint = pWalker->u.pCCurHint;
1070 assert( pHint->pIdx!=0 );
1071 if( pExpr->op==TK_COLUMN
1072 && pExpr->iTable==pHint->iTabCur
1073 && sqlite3TableColumnToIndex(pHint->pIdx, pExpr->iColumn)<0
1074 ){
1075 pWalker->eCode = 1;
1076 }
1077 return WRC_Continue;
1078}
1079
1080/*
1081** Test whether or not expression pExpr, which was part of a WHERE clause,
1082** should be included in the cursor-hint for a table that is on the rhs
1083** of a LEFT JOIN. Set Walker.eCode to non-zero before returning if the
1084** expression is not suitable.
1085**
1086** An expression is unsuitable if it might evaluate to non NULL even if
1087** a TK_COLUMN node that does affect the value of the expression is set
1088** to NULL. For example:
1089**
1090** col IS NULL
1091** col IS NOT NULL
1092** coalesce(col, 1)
1093** CASE WHEN col THEN 0 ELSE 1 END
1094*/
1095static int codeCursorHintIsOrFunction(Walker *pWalker, Expr *pExpr){
1096 if( pExpr->op==TK_IS
1097 || pExpr->op==TK_ISNULL || pExpr->op==TK_ISNOT
1098 || pExpr->op==TK_NOTNULL || pExpr->op==TK_CASE
1099 ){
1100 pWalker->eCode = 1;
1101 }else if( pExpr->op==TK_FUNCTION ){
1102 int d1;
1103 char d2[4];
1104 if( 0==sqlite3IsLikeFunction(pWalker->pParse->db, pExpr, &d1, d2) ){
1105 pWalker->eCode = 1;
1106 }
1107 }
1108
1109 return WRC_Continue;
1110}
1111
1112
1113/*
1114** This function is called on every node of an expression tree used as an
1115** argument to the OP_CursorHint instruction. If the node is a TK_COLUMN
1116** that accesses any table other than the one identified by
1117** CCurHint.iTabCur, then do the following:
1118**
1119** 1) allocate a register and code an OP_Column instruction to read
1120** the specified column into the new register, and
1121**
1122** 2) transform the expression node to a TK_REGISTER node that reads
1123** from the newly populated register.
1124**
1125** Also, if the node is a TK_COLUMN that does access the table identified
1126** by pCCurHint.iTabCur, and an index is being used (which we will
1127** know because CCurHint.pIdx!=0) then transform the TK_COLUMN into
1128** an access of the index rather than the original table.
1129*/
1130static int codeCursorHintFixExpr(Walker *pWalker, Expr *pExpr){
1131 int rc = WRC_Continue;
1132 int reg;
1133 struct CCurHint *pHint = pWalker->u.pCCurHint;
1134 if( pExpr->op==TK_COLUMN ){
1135 if( pExpr->iTable!=pHint->iTabCur ){
1136 reg = ++pWalker->pParse->nMem; /* Register for column value */
1137 reg = sqlite3ExprCodeTarget(pWalker->pParse, pExpr, reg);
1138 pExpr->op = TK_REGISTER;
1139 pExpr->iTable = reg;
1140 }else if( pHint->pIdx!=0 ){
1141 pExpr->iTable = pHint->iIdxCur;
1142 pExpr->iColumn = sqlite3TableColumnToIndex(pHint->pIdx, pExpr->iColumn);
1143 assert( pExpr->iColumn>=0 );
1144 }
1145 }else if( pExpr->pAggInfo ){
1146 rc = WRC_Prune;
1147 reg = ++pWalker->pParse->nMem; /* Register for column value */
1148 reg = sqlite3ExprCodeTarget(pWalker->pParse, pExpr, reg);
1149 pExpr->op = TK_REGISTER;
1150 pExpr->iTable = reg;
1151 }else if( pExpr->op==TK_TRUEFALSE ){
1152 /* Do not walk disabled expressions. tag-20230504-1 */
1153 return WRC_Prune;
1154 }
1155 return rc;
1156}
1157
1158/*
1159** Insert an OP_CursorHint instruction if it is appropriate to do so.
1160*/
1161static void codeCursorHint(
1162 SrcItem *pTabItem, /* FROM clause item */
1163 WhereInfo *pWInfo, /* The where clause */
1164 WhereLevel *pLevel, /* Which loop to provide hints for */
1165 WhereTerm *pEndRange /* Hint this end-of-scan boundary term if not NULL */
1166){
1167 Parse *pParse = pWInfo->pParse;
1168 sqlite3 *db = pParse->db;
1169 Vdbe *v = pParse->pVdbe;
1170 Expr *pExpr = 0;
1171 WhereLoop *pLoop = pLevel->pWLoop;
1172 int iCur;
1173 WhereClause *pWC;
1174 WhereTerm *pTerm;
1175 int i, j;
1176 struct CCurHint sHint;
1177 Walker sWalker;
1178
1179 if( OptimizationDisabled(db, SQLITE_CursorHints) ) return;
1180 iCur = pLevel->iTabCur;
1181 assert( iCur==pWInfo->pTabList->a[pLevel->iFrom].iCursor );
1182 sHint.iTabCur = iCur;
1183 sHint.iIdxCur = pLevel->iIdxCur;
1184 sHint.pIdx = pLoop->u.btree.pIndex;
1185 memset(&sWalker, 0, sizeof(sWalker));
1186 sWalker.pParse = pParse;
1187 sWalker.u.pCCurHint = &sHint;
1188 pWC = &pWInfo->sWC;
1189 for(i=0; i<pWC->nBase; i++){
1190 pTerm = &pWC->a[i];
1191 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
1192 if( pTerm->prereqAll & pLevel->notReady ) continue;
1193
1194 /* Any terms specified as part of the ON(...) clause for any LEFT
1195 ** JOIN for which the current table is not the rhs are omitted
1196 ** from the cursor-hint.
1197 **
1198 ** If this table is the rhs of a LEFT JOIN, "IS" or "IS NULL" terms
1199 ** that were specified as part of the WHERE clause must be excluded.
1200 ** This is to address the following:
1201 **
1202 ** SELECT ... t1 LEFT JOIN t2 ON (t1.a=t2.b) WHERE t2.c IS NULL;
1203 **
1204 ** Say there is a single row in t2 that matches (t1.a=t2.b), but its
1205 ** t2.c values is not NULL. If the (t2.c IS NULL) constraint is
1206 ** pushed down to the cursor, this row is filtered out, causing
1207 ** SQLite to synthesize a row of NULL values. Which does match the
1208 ** WHERE clause, and so the query returns a row. Which is incorrect.
1209 **
1210 ** For the same reason, WHERE terms such as:
1211 **
1212 ** WHERE 1 = (t2.c IS NULL)
1213 **
1214 ** are also excluded. See codeCursorHintIsOrFunction() for details.
1215 */
1216 if( pTabItem->fg.jointype & JT_LEFT ){
1217 Expr *pExpr = pTerm->pExpr;
1218 if( !ExprHasProperty(pExpr, EP_OuterON)
1219 || pExpr->w.iJoin!=pTabItem->iCursor
1220 ){
1221 sWalker.eCode = 0;
1222 sWalker.xExprCallback = codeCursorHintIsOrFunction;
1223 sqlite3WalkExpr(&sWalker, pTerm->pExpr);
1224 if( sWalker.eCode ) continue;
1225 }
1226 }else{
1227 if( ExprHasProperty(pTerm->pExpr, EP_OuterON) ) continue;
1228 }
1229
1230 /* All terms in pWLoop->aLTerm[] except pEndRange are used to initialize
1231 ** the cursor. These terms are not needed as hints for a pure range
1232 ** scan (that has no == terms) so omit them. */
1233 if( pLoop->u.btree.nEq==0 && pTerm!=pEndRange ){
1234 for(j=0; j<pLoop->nLTerm && pLoop->aLTerm[j]!=pTerm; j++){}
1235 if( j<pLoop->nLTerm ) continue;
1236 }
1237
1238 /* No subqueries or non-deterministic functions allowed */
1239 if( sqlite3ExprContainsSubquery(pTerm->pExpr) ) continue;
1240
1241 /* For an index scan, make sure referenced columns are actually in
1242 ** the index. */
1243 if( sHint.pIdx!=0 ){
1244 sWalker.eCode = 0;
1245 sWalker.xExprCallback = codeCursorHintCheckExpr;
1246 sqlite3WalkExpr(&sWalker, pTerm->pExpr);
1247 if( sWalker.eCode ) continue;
1248 }
1249
1250 /* If we survive all prior tests, that means this term is worth hinting */
1251 pExpr = sqlite3ExprAnd(pParse, pExpr, sqlite3ExprDup(db, pTerm->pExpr, 0));
1252 }
1253 if( pExpr!=0 ){
1254 sWalker.xExprCallback = codeCursorHintFixExpr;
1255 if( pParse->nErr==0 ) sqlite3WalkExpr(&sWalker, pExpr);
1256 sqlite3VdbeAddOp4(v, OP_CursorHint,
1257 (sHint.pIdx ? sHint.iIdxCur : sHint.iTabCur), 0, 0,
1258 (const char*)pExpr, P4_EXPR);
1259 }
1260}
1261#else
1262# define codeCursorHint(A,B,C,D) /* No-op */
1263#endif /* SQLITE_ENABLE_CURSOR_HINTS */
1264
1265/*
1266** Cursor iCur is open on an intkey b-tree (a table). Register iRowid contains
1267** a rowid value just read from cursor iIdxCur, open on index pIdx. This
1268** function generates code to do a deferred seek of cursor iCur to the
1269** rowid stored in register iRowid.
1270**
1271** Normally, this is just:
1272**
1273** OP_DeferredSeek $iCur $iRowid
1274**
1275** Which causes a seek on $iCur to the row with rowid $iRowid.
1276**
1277** However, if the scan currently being coded is a branch of an OR-loop and
1278** the statement currently being coded is a SELECT, then additional information
1279** is added that might allow OP_Column to omit the seek and instead do its
1280** lookup on the index, thus avoiding an expensive seek operation. To
1281** enable this optimization, the P3 of OP_DeferredSeek is set to iIdxCur
1282** and P4 is set to an array of integers containing one entry for each column
1283** in the table. For each table column, if the column is the i'th
1284** column of the index, then the corresponding array entry is set to (i+1).
1285** If the column does not appear in the index at all, the array entry is set
1286** to 0. The OP_Column opcode can check this array to see if the column it
1287** wants is in the index and if it is, it will substitute the index cursor
1288** and column number and continue with those new values, rather than seeking
1289** the table cursor.
1290*/
1291static void codeDeferredSeek(
1292 WhereInfo *pWInfo, /* Where clause context */
1293 Index *pIdx, /* Index scan is using */
1294 int iCur, /* Cursor for IPK b-tree */
1295 int iIdxCur /* Index cursor */
1296){
1297 Parse *pParse = pWInfo->pParse; /* Parse context */
1298 Vdbe *v = pParse->pVdbe; /* Vdbe to generate code within */
1299
1300 assert( iIdxCur>0 );
1301 assert( pIdx->aiColumn[pIdx->nColumn-1]==-1 );
1302
1303 pWInfo->bDeferredSeek = 1;
1304 sqlite3VdbeAddOp3(v, OP_DeferredSeek, iIdxCur, 0, iCur);
1305 if( (pWInfo->wctrlFlags & (WHERE_OR_SUBCLAUSE|WHERE_RIGHT_JOIN))
1306 && DbMaskAllZero(sqlite3ParseToplevel(pParse)->writeMask)
1307 ){
1308 int i;
1309 Table *pTab = pIdx->pTable;
1310 u32 *ai = (u32*)sqlite3DbMallocZero(pParse->db, sizeof(u32)*(pTab->nCol+1));
1311 if( ai ){
1312 ai[0] = pTab->nCol;
1313 for(i=0; i<pIdx->nColumn-1; i++){
1314 int x1, x2;
1315 assert( pIdx->aiColumn[i]<pTab->nCol );
1316 x1 = pIdx->aiColumn[i];
1317 x2 = sqlite3TableColumnToStorage(pTab, x1);
1318 testcase( x1!=x2 );
1319 if( x1>=0 ) ai[x2+1] = i+1;
1320 }
1321 sqlite3VdbeChangeP4(v, -1, (char*)ai, P4_INTARRAY);
1322 }
1323 }
1324}
1325
1326/*
1327** If the expression passed as the second argument is a vector, generate
1328** code to write the first nReg elements of the vector into an array
1329** of registers starting with iReg.
1330**
1331** If the expression is not a vector, then nReg must be passed 1. In
1332** this case, generate code to evaluate the expression and leave the
1333** result in register iReg.
1334*/
1335static void codeExprOrVector(Parse *pParse, Expr *p, int iReg, int nReg){
1336 assert( nReg>0 );
1337 if( p && sqlite3ExprIsVector(p) ){
1338#ifndef SQLITE_OMIT_SUBQUERY
1339 if( ExprUseXSelect(p) ){
1340 Vdbe *v = pParse->pVdbe;
1341 int iSelect;
1342 assert( p->op==TK_SELECT );
1343 iSelect = sqlite3CodeSubselect(pParse, p);
1344 sqlite3VdbeAddOp3(v, OP_Copy, iSelect, iReg, nReg-1);
1345 }else
1346#endif
1347 {
1348 int i;
1349 const ExprList *pList;
1350 assert( ExprUseXList(p) );
1351 pList = p->x.pList;
1352 assert( nReg<=pList->nExpr );
1353 for(i=0; i<nReg; i++){
1354 sqlite3ExprCode(pParse, pList->a[i].pExpr, iReg+i);
1355 }
1356 }
1357 }else{
1358 assert( nReg==1 || pParse->nErr );
1359 sqlite3ExprCode(pParse, p, iReg);
1360 }
1361}
1362
1363/*
1364** The pTruth expression is always true because it is the WHERE clause
1365** a partial index that is driving a query loop. Look through all of the
1366** WHERE clause terms on the query, and if any of those terms must be
1367** true because pTruth is true, then mark those WHERE clause terms as
1368** coded.
1369*/
1370static void whereApplyPartialIndexConstraints(
1371 Expr *pTruth,
1372 int iTabCur,
1373 WhereClause *pWC
1374){
1375 int i;
1376 WhereTerm *pTerm;
1377 while( pTruth->op==TK_AND ){
1378 whereApplyPartialIndexConstraints(pTruth->pLeft, iTabCur, pWC);
1379 pTruth = pTruth->pRight;
1380 }
1381 for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
1382 Expr *pExpr;
1383 if( pTerm->wtFlags & TERM_CODED ) continue;
1384 pExpr = pTerm->pExpr;
1385 if( sqlite3ExprCompare(0, pExpr, pTruth, iTabCur)==0 ){
1386 pTerm->wtFlags |= TERM_CODED;
1387 }
1388 }
1389}
1390
1391/*
1392** This routine is called right after An OP_Filter has been generated and
1393** before the corresponding index search has been performed. This routine
1394** checks to see if there are additional Bloom filters in inner loops that
1395** can be checked prior to doing the index lookup. If there are available
1396** inner-loop Bloom filters, then evaluate those filters now, before the
1397** index lookup. The idea is that a Bloom filter check is way faster than
1398** an index lookup, and the Bloom filter might return false, meaning that
1399** the index lookup can be skipped.
1400**
1401** We know that an inner loop uses a Bloom filter because it has the
1402** WhereLevel.regFilter set. If an inner-loop Bloom filter is checked,
1403** then clear the WhereLevel.regFilter value to prevent the Bloom filter
1404** from being checked a second time when the inner loop is evaluated.
1405*/
1406static SQLITE_NOINLINE void filterPullDown(
1407 Parse *pParse, /* Parsing context */
1408 WhereInfo *pWInfo, /* Complete information about the WHERE clause */
1409 int iLevel, /* Which level of pWInfo->a[] should be coded */
1410 int addrNxt, /* Jump here to bypass inner loops */
1411 Bitmask notReady /* Loops that are not ready */
1412){
1413 int saved_addrBrk;
1414 while( ++iLevel < pWInfo->nLevel ){
1415 WhereLevel *pLevel = &pWInfo->a[iLevel];
1416 WhereLoop *pLoop = pLevel->pWLoop;
1417 if( pLevel->regFilter==0 ) continue;
1418 if( pLevel->pWLoop->nSkip ) continue;
1419 /* ,--- Because sqlite3ConstructBloomFilter() has will not have set
1420 ** vvvvv--' pLevel->regFilter if this were true. */
1421 if( NEVER(pLoop->prereq & notReady) ) continue;
1422 saved_addrBrk = pLevel->addrBrk;
1423 pLevel->addrBrk = addrNxt;
1424 if( pLoop->wsFlags & WHERE_IPK ){
1425 WhereTerm *pTerm = pLoop->aLTerm[0];
1426 int regRowid;
1427 assert( pTerm!=0 );
1428 assert( pTerm->pExpr!=0 );
1429 testcase( pTerm->wtFlags & TERM_VIRTUAL );
1430 regRowid = sqlite3GetTempReg(pParse);
1431 regRowid = codeEqualityTerm(pParse, pTerm, pLevel, 0, 0, regRowid);
1432 sqlite3VdbeAddOp2(pParse->pVdbe, OP_MustBeInt, regRowid, addrNxt);
1433 VdbeCoverage(pParse->pVdbe);
1434 assert( sqlite3WhereLoopBloomable(pLoop) );
1435 sqlite3VdbeAddOp4Int(pParse->pVdbe, OP_Filter, pLevel->regFilter,
1436 addrNxt, regRowid, 1);
1437 VdbeCoverage(pParse->pVdbe);
1438 }else{
1439 u16 nEq = pLoop->u.btree.nEq;
1440 int r1;
1441 char *zStartAff;
1442
1443 assert( pLoop->wsFlags & WHERE_INDEXED );
1444 assert( (pLoop->wsFlags & WHERE_COLUMN_IN)==0 );
1445 r1 = codeAllEqualityTerms(pParse,pLevel,0,0,&zStartAff);
1446 codeApplyAffinity(pParse, r1, nEq, zStartAff);
1447 sqlite3DbFree(pParse->db, zStartAff);
1448 assert( sqlite3WhereLoopBloomable(pLoop) );
1449 sqlite3VdbeAddOp4Int(pParse->pVdbe, OP_Filter, pLevel->regFilter,
1450 addrNxt, r1, nEq);
1451 VdbeCoverage(pParse->pVdbe);
1452 }
1453 pLevel->regFilter = 0;
1454 pLevel->addrBrk = saved_addrBrk;
1455 }
1456}
1457
1458/*
1459** Loop pLoop is a WHERE_INDEXED level that uses at least one IN(...)
1460** operator. Return true if level pLoop is guaranteed to visit only one
1461** row for each key generated for the index.
1462*/
1463static int whereLoopIsOneRow(WhereLoop *pLoop){
1464 if( pLoop->u.btree.pIndex->onError
1465 && pLoop->nSkip==0
1466 && pLoop->u.btree.nEq==pLoop->u.btree.pIndex->nKeyCol
1467 ){
1468 int ii;
1469 for(ii=0; ii<pLoop->u.btree.nEq; ii++){
1470 if( pLoop->aLTerm[ii]->eOperator & (WO_IS|WO_ISNULL) ){
1471 return 0;
1472 }
1473 }
1474 return 1;
1475 }
1476 return 0;
1477}
1478
1479/*
1480** This is called while coding loop pLevel, which scans FROM clause item
1481** pTabItem. pE is an expression for which all the prerequisites are
1482** available. This function tests if pE can be coded as part of the current
1483** loop, or whether it needs to be deferred to ensure outer joins are
1484** processed correctly. This function returns non-zero if the expression
1485** can be coded as part of the loop, or 0 if it must be deferred.
1486**
1487** The expression must be deferred if:
1488**
1489** * There are any RIGHT joins in the FROM clause and the expression
1490** was not part of an ON clause, or was part of an ON clause to the
1491** right of the join.
1492**
1493** * The table is the RHS of a LEFT JOIN and the expression was not
1494** part of an ON clause on an OUTER join, or was part of an ON clause
1495** on an OUTER join to the right of the join.
1496*/
1497static int whereExprIsReady(
1498 WhereInfo *pWInfo,
1499 WhereLevel *pLevel,
1500 SrcItem *pTabItem,
1501 Expr *pE
1502){
1503 u8 jtype = pTabItem->fg.jointype;
1504 if( jtype & (JT_LEFT|JT_LTORJ|JT_RIGHT) ){
1505 if( !ExprHasProperty(pE,EP_OuterON|EP_InnerON) ){
1506 /* Defer processing WHERE clause constraints until after outer
1507 ** join processing. tag-20220513a */
1508 return 0;
1509 }else if( (jtype & JT_LEFT) && !ExprHasProperty(pE,EP_OuterON) ){
1510 return 0;
1511 }else{
1512 Bitmask m = sqlite3WhereGetMask(&pWInfo->sMaskSet, pE->w.iJoin);
1513 if( m & pLevel->notReady ){
1514 /* An ON clause that is not ripe */
1515 return 0;
1516 }
1517 }
1518 }
1519 return 1;
1520}
1521
1522/*
1523** Find the best address for an inner loop to jump to if its join
1524** constraint matches no rows.
1525**
1526** This is an optimization. The default behavior is to continue with
1527** the inner-most of the outer loops. But if the join constraint is not
1528** influenced by the inner-most outer loop, we might as well skip that
1529** loop too, and continue with the second inner-most outer loop. And
1530** so forth through subsequent outer loops.
1531**
1532** Return 0 to use the default behavior (continue with the inner-most
1533** outer loop. Or return an optimized address to jump to instead if
1534** we can do better.
1535**
1536** Conditions for returning non-zero:
1537**
1538** 1. The SQLITE_JoinMiss optimization must be enabled.
1539**
1540** 2. The iLevel loop must have at least two outer loops, otherwise
1541** this optimization is pointless.
1542**
1543** 3. We are not attempting to do one-pass
1544**
1545** 4. The join constraints may not contain subqueries
1546**
1547** If the inner-most outer loop that influences iLevel is also the
1548** only loop that influences iLevel, and if that loop uses an
1549** automatic index, then also arrange to delete the currently used
1550** entry from that automatic index, since we know that it can never
1551** be successful.
1552**
1553** This optimization inspired by the paper: "TreeTracker Join: Simple,
1554** Optimal, Fast" by Hu, Wang, and Miranker, 2025.
1555*/
1556static int findNoMatchContinuation(
1557 WhereInfo *pWInfo, /* WHERE clause */
1558 int iLevel /* Which loop we are talking about */
1559){
1560 WhereLoop *pLoop; /* Description of this loop */
1561 WhereLevel *pParent; /* Controlling parent loop */
1562 SrcList *pTabList; /* Complete FROM clause */
1563 Bitmask mKey; /* Mask of dependent tables */
1564 int iParent; /* Inner-most loop affecting the key to iLevel */
1565 int i; /* Loop counter */
1566
1567 if( iLevel<2 ){
1568 /* If there are less than two outer loops, this optimization is no help */
1569 return 0;
1570 }
1571
1572 /* The OP_SeekGE and OP_SeekLE opcodes only work right for this
1573 ** optimization on a pure equality constraint, so skip the optimization
1574 ** for anything else.
1575 */
1576 pLoop = pWInfo->a[iLevel].pWLoop;
1577 if( (pLoop->wsFlags & WHERE_CONSTRAINT)!=WHERE_COLUMN_EQ ) return 0;
1578 if( pLoop->wsFlags & WHERE_SKIPSCAN ) return 0;
1579 if( pLoop->wsFlags & WHERE_BIGNULL_SORT ) return 0;
1580 assert( (pLoop->wsFlags & (WHERE_VIRTUALTABLE|WHERE_MULTI_OR))==0 );
1581 assert( pLoop->u.btree.nEq>0 );
1582
1583 /* Find a mask of all outer tables that influence the key. At the same
1584 ** time, check to see if any keys values are computed from subqueries and
1585 ** fail out (return 0) if there are any. */
1586 mKey = 0;
1587 for(i=0; i<pLoop->nLTerm; i++){
1588 if( sqlite3ExprContainsSubquery(pLoop->aLTerm[i]->pExpr) ){
1589 return 0;
1590 }
1591 mKey |= pLoop->aLTerm[i]->prereqRight;
1592 }
1593
1594 /* Look back through outer loops. Find the inner-most outer loop
1595 ** that influences the key. Make iParent be the index of that inner-most
1596 ** outer loop.
1597 */
1598 pTabList = pWInfo->pTabList;
1599 iParent = iLevel-1;
1600 while( iParent>0 && (pWInfo->a[iParent].pWLoop->maskSelf & mKey)==0 ){
1601 iParent--;
1602 }
1603 assert( iParent>=0 && iParent<=iLevel );
1604
1605 /* Everything needs to be an INNER join. Fail if there are any
1606 ** OUTER joins in between iParent and iLevel. */
1607 for(i=iParent; i<=iLevel; i++){
1608 if( pTabList->a[pWInfo->a[i].iFrom].fg.jointype & JT_OUTER ) return 0;
1609 }
1610
1611 /* If we reach this point, that means the conditions of the optimization
1612 ** have been met. Even so, disallow the optimization if it is disabled.
1613 */
1614 if( OptimizationDisabled(pWInfo->pParse->db, SQLITE_JoinMiss) ){
1615 return 0;
1616 }
1617
1618 /* If the inner-most outer loop that influences the key for iLevel
1619 ** is controlled by an automatic index and if the automatic index is
1620 ** the only outer loop that influences the key, then arrange to delete
1621 ** the automatic index entry if there is no match on the key.
1622 */
1623 pParent = &pWInfo->a[iParent];
1624 if( (pParent->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0
1625 && (mKey & (mKey-1))==0
1626 ){
1627 for(i=0; i<pLoop->nLTerm; i++){
1628 Expr *pX = pLoop->aLTerm[i]->pExpr;
1629 if( !sqlite3ExprIsTableConstant(pX->pRight,pParent->iTabCur,0) ) break;
1630 }
1631 if( i==pLoop->nLTerm ){
1632 if( pParent->addrDeleteCont==0 ){
1633 pParent->addrDeleteCont = sqlite3VdbeMakeLabel(pWInfo->pParse);
1634 }
1635 return pParent->addrDeleteCont;
1636 }
1637 }
1638
1639 testcase( iParent<iLevel-1 );
1640 return pParent->addrCont;
1641}
1642
1643/*
1644** Generate code for the start of the iLevel-th loop in the WHERE clause
1645** implementation described by pWInfo.
1646*/
1647Bitmask sqlite3WhereCodeOneLoopStart(
1648 Parse *pParse, /* Parsing context */
1649 Vdbe *v, /* Prepared statement under construction */
1650 WhereInfo *pWInfo, /* Complete information about the WHERE clause */
1651 int iLevel, /* Which level of pWInfo->a[] should be coded */
1652 WhereLevel *pLevel, /* The current level pointer */
1653 Bitmask notReady /* Which tables are currently available */
1654){
1655 int j, k; /* Loop counters */
1656 int iCur; /* The VDBE cursor for the table */
1657 int addrNxt; /* Where to jump to continue with the next IN case */
1658 int bRev; /* True if we need to scan in reverse order */
1659 WhereLoop *pLoop; /* The WhereLoop object being coded */
1660 WhereClause *pWC; /* Decomposition of the entire WHERE clause */
1661 WhereTerm *pTerm; /* A WHERE clause term */
1662 sqlite3 *db; /* Database connection */
1663 SrcItem *pTabItem; /* FROM clause term being coded */
1664 int addrBrk; /* Jump here to break out of the loop */
1665 int addrCont; /* Jump here to continue with next cycle */
1666 int addrMiss; /* addrCont enhanced for no-matching rows */
1667 int iRowidReg = 0; /* Rowid is stored in this register, if not zero */
1668 int iReleaseReg = 0; /* Temp register to free before returning */
1669 Index *pIdx = 0; /* Index used by loop (if any) */
1670 int iLoop; /* Iteration of constraint generator loop */
1671
1672 pWC = &pWInfo->sWC;
1673 db = pParse->db;
1674 pLoop = pLevel->pWLoop;
1675 pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
1676 iCur = pTabItem->iCursor;
1677 pLevel->notReady = notReady & ~sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur);
1678 bRev = (pWInfo->revMask>>iLevel)&1;
1679 VdbeModuleComment((v, "Begin WHERE-loop%d: %s",
1680 iLevel, pTabItem->pSTab->zName));
1681#if WHERETRACE_ENABLED /* 0x4001 */
1682 if( sqlite3WhereTrace & 0x1 ){
1683 sqlite3DebugPrintf("Coding level %d of %d: notReady=%llx iFrom=%d\n",
1684 iLevel, pWInfo->nLevel, (u64)notReady, pLevel->iFrom);
1685 if( sqlite3WhereTrace & 0x1000 ){
1686 sqlite3WhereLoopPrint(pLoop, pWC);
1687 }
1688 }
1689 if( (sqlite3WhereTrace & 0x4001)==0x4001 ){
1690 if( iLevel==0 ){
1691 sqlite3DebugPrintf("WHERE clause being coded:\n");
1692 sqlite3TreeViewExpr(0, pWInfo->pWhere, 0);
1693 }
1694 sqlite3DebugPrintf("All WHERE-clause terms before coding:\n");
1695 sqlite3WhereClausePrint(pWC);
1696 }
1697#endif
1698
1699 /* Create labels for the "break" and "continue" instructions
1700 ** for the current loop. Jump to addrBrk to break out of a loop.
1701 ** Jump to cont to go immediately to the next iteration of the
1702 ** loop.
1703 **
1704 ** When there is an IN operator, we also have a "addrNxt" label that
1705 ** means to continue with the next IN value combination. When
1706 ** there are no IN operators in the constraints, the "addrNxt" label
1707 ** is the same as "addrBrk".
1708 */
1709 addrBrk = pLevel->addrNxt = pLevel->addrBrk;
1710 addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(pParse);
1711 addrMiss = findNoMatchContinuation(pWInfo, iLevel);
1712
1713 /* If this is the right table of a LEFT OUTER JOIN, allocate and
1714 ** initialize a memory cell that records if this table matches any
1715 ** row of the left table of the join.
1716 */
1717 assert( (pWInfo->wctrlFlags & (WHERE_OR_SUBCLAUSE|WHERE_RIGHT_JOIN))
1718 || pLevel->iFrom>0 || (pTabItem[0].fg.jointype & JT_LEFT)==0
1719 );
1720 if( pLevel->iFrom>0 && (pTabItem[0].fg.jointype & JT_LEFT)!=0 ){
1721 pLevel->iLeftJoin = ++pParse->nMem;
1722 sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
1723 VdbeComment((v, "init LEFT JOIN match flag"));
1724 if( pTabItem->fg.viaCoroutine ){
1725 sqlite3VdbeAddOp2(v, OP_NullRow, pTabItem->iCursor, 1);
1726 }
1727 }
1728
1729 /* Special case of a FROM clause subquery implemented as a co-routine */
1730 if( pTabItem->fg.viaCoroutine ){
1731 int regYield;
1732 Subquery *pSubq;
1733 assert( pTabItem->fg.isSubquery && pTabItem->u4.pSubq!=0 );
1734 pSubq = pTabItem->u4.pSubq;
1735 regYield = pSubq->regReturn;
1736 sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pSubq->addrFillSub);
1737 pLevel->p2 = sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk);
1738 VdbeCoverage(v);
1739 VdbeComment((v, "next row of %s", pTabItem->pSTab->zName));
1740 pLevel->op = OP_Goto;
1741 }else
1742
1743#ifndef SQLITE_OMIT_VIRTUALTABLE
1744 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
1745 /* Case 1: The table is a virtual-table. Use the VFilter and VNext
1746 ** to access the data.
1747 */
1748 int iReg; /* P3 Value for OP_VFilter */
1749 int addrNotFound;
1750 int nConstraint = pLoop->nLTerm;
1751
1752 sqlite3MayAbort(pParse);
1753 iReg = sqlite3GetTempRange(pParse, nConstraint+2);
1754 addrNotFound = pLevel->addrBrk;
1755 for(j=0; j<nConstraint; j++){
1756 int iTarget = iReg+j+2;
1757 pTerm = pLoop->aLTerm[j];
1758 if( NEVER(pTerm==0) ) continue;
1759 if( pTerm->eOperator & WO_IN ){
1760 if( SMASKBIT32(j) & pLoop->u.vtab.mHandleIn ){
1761 int iTab = pParse->nTab++;
1762 int iCache = ++pParse->nMem;
1763 sqlite3CodeRhsOfIN(pParse, pTerm->pExpr, iTab, 0);
1764 sqlite3VdbeAddOp3(v, OP_VInitIn, iTab, iTarget, iCache);
1765 }else{
1766 codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
1767 addrNotFound = pLevel->addrNxt;
1768 }
1769 }else{
1770 Expr *pRight = pTerm->pExpr->pRight;
1771 codeExprOrVector(pParse, pRight, iTarget, 1);
1772 if( pTerm->eMatchOp==SQLITE_INDEX_CONSTRAINT_OFFSET
1773 && pLoop->u.vtab.bOmitOffset
1774 ){
1775 assert( pTerm->eOperator==WO_AUX );
1776 assert( pWInfo->pSelect!=0 );
1777 assert( pWInfo->pSelect->iOffset>0 );
1778 sqlite3VdbeAddOp2(v, OP_Integer, 0, pWInfo->pSelect->iOffset);
1779 VdbeComment((v,"Zero OFFSET counter"));
1780 }
1781 }
1782 }
1783 sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
1784 sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
1785 /* The instruction immediately prior to OP_VFilter must be an OP_Integer
1786 ** that sets the "argc" value for xVFilter. This is necessary for
1787 ** resolveP2() to work correctly. See tag-20250207a. */
1788 sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
1789 pLoop->u.vtab.idxStr,
1790 pLoop->u.vtab.needFree ? P4_DYNAMIC : P4_STATIC);
1791 VdbeCoverage(v);
1792 pLoop->u.vtab.needFree = 0;
1793 /* An OOM inside of AddOp4(OP_VFilter) instruction above might have freed
1794 ** the u.vtab.idxStr. NULL it out to prevent a use-after-free */
1795 if( db->mallocFailed ) pLoop->u.vtab.idxStr = 0;
1796 pLevel->p1 = iCur;
1797 pLevel->op = pWInfo->eOnePass ? OP_Noop : OP_VNext;
1798 pLevel->p2 = sqlite3VdbeCurrentAddr(v);
1799 assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
1800
1801 for(j=0; j<nConstraint; j++){
1802 pTerm = pLoop->aLTerm[j];
1803 if( j<16 && (pLoop->u.vtab.omitMask>>j)&1 ){
1804 disableTerm(pLevel, pTerm);
1805 continue;
1806 }
1807 if( (pTerm->eOperator & WO_IN)!=0
1808 && (SMASKBIT32(j) & pLoop->u.vtab.mHandleIn)==0
1809 && !db->mallocFailed
1810 ){
1811 Expr *pCompare; /* The comparison operator */
1812 Expr *pRight; /* RHS of the comparison */
1813 VdbeOp *pOp; /* Opcode to access the value of the IN constraint */
1814 int iIn; /* IN loop corresponding to the j-th constraint */
1815
1816 /* Reload the constraint value into reg[iReg+j+2]. The same value
1817 ** was loaded into the same register prior to the OP_VFilter, but
1818 ** the xFilter implementation might have changed the datatype or
1819 ** encoding of the value in the register, so it *must* be reloaded.
1820 */
1821 for(iIn=0; ALWAYS(iIn<pLevel->u.in.nIn); iIn++){
1822 pOp = sqlite3VdbeGetOp(v, pLevel->u.in.aInLoop[iIn].addrInTop);
1823 if( (pOp->opcode==OP_Column && pOp->p3==iReg+j+2)
1824 || (pOp->opcode==OP_Rowid && pOp->p2==iReg+j+2)
1825 ){
1826 testcase( pOp->opcode==OP_Rowid );
1827 sqlite3VdbeAddOp3(v, pOp->opcode, pOp->p1, pOp->p2, pOp->p3);
1828 break;
1829 }
1830 }
1831
1832 /* Generate code that will continue to the next row if
1833 ** the IN constraint is not satisfied
1834 */
1835 pCompare = sqlite3PExpr(pParse, TK_EQ, 0, 0);
1836 if( !db->mallocFailed ){
1837 int iFld = pTerm->u.x.iField;
1838 Expr *pLeft = pTerm->pExpr->pLeft;
1839 assert( pLeft!=0 );
1840 if( iFld>0 ){
1841 assert( pLeft->op==TK_VECTOR );
1842 assert( ExprUseXList(pLeft) );
1843 assert( iFld<=pLeft->x.pList->nExpr );
1844 pCompare->pLeft = pLeft->x.pList->a[iFld-1].pExpr;
1845 }else{
1846 pCompare->pLeft = pLeft;
1847 }
1848 pCompare->pRight = pRight = sqlite3Expr(db, TK_REGISTER, 0);
1849 if( pRight ){
1850 pRight->iTable = iReg+j+2;
1851 sqlite3ExprIfFalse(
1852 pParse, pCompare, pLevel->addrCont, SQLITE_JUMPIFNULL
1853 );
1854 }
1855 pCompare->pLeft = 0;
1856 }
1857 sqlite3ExprDelete(db, pCompare);
1858 }
1859 }
1860
1861 /* These registers need to be preserved in case there is an IN operator
1862 ** loop. So we could deallocate the registers here (and potentially
1863 ** reuse them later) if (pLoop->wsFlags & WHERE_IN_ABLE)==0. But it seems
1864 ** simpler and safer to simply not reuse the registers.
1865 **
1866 ** sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
1867 */
1868 }else
1869#endif /* SQLITE_OMIT_VIRTUALTABLE */
1870
1871 if( (pLoop->wsFlags & WHERE_IPK)!=0
1872 && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
1873 ){
1874 /* Case 2: We can directly reference a single row using an
1875 ** equality comparison against the ROWID field. Or
1876 ** we reference multiple rows using a "rowid IN (...)"
1877 ** construct.
1878 */
1879 assert( pLoop->u.btree.nEq==1 );
1880 pTerm = pLoop->aLTerm[0];
1881 assert( pTerm!=0 );
1882 assert( pTerm->pExpr!=0 );
1883 testcase( pTerm->wtFlags & TERM_VIRTUAL );
1884 iReleaseReg = ++pParse->nMem;
1885 iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
1886 if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg);
1887 addrNxt = pLevel->addrNxt;
1888 if( addrMiss==0 ) addrMiss = addrNxt;
1889 if( pLevel->regFilter ){
1890 sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrMiss);
1891 VdbeCoverage(v);
1892 sqlite3VdbeAddOp4Int(v, OP_Filter, pLevel->regFilter, addrMiss,
1893 iRowidReg, 1);
1894 VdbeCoverage(v);
1895 filterPullDown(pParse, pWInfo, iLevel, addrNxt, notReady);
1896 }
1897 sqlite3VdbeAddOp3(v, OP_SeekRowid, iCur, addrMiss, iRowidReg);
1898 VdbeCoverage(v);
1899 pLevel->op = OP_Noop;
1900 }else if( (pLoop->wsFlags & WHERE_IPK)!=0
1901 && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
1902 ){
1903 /* Case 3: We have an inequality comparison against the ROWID field.
1904 */
1905 int testOp = OP_Noop;
1906 int start;
1907 int memEndValue = 0;
1908 WhereTerm *pStart, *pEnd;
1909
1910 j = 0;
1911 pStart = pEnd = 0;
1912 if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
1913 if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
1914 assert( pStart!=0 || pEnd!=0 );
1915 if( bRev ){
1916 pTerm = pStart;
1917 pStart = pEnd;
1918 pEnd = pTerm;
1919 }
1920 codeCursorHint(pTabItem, pWInfo, pLevel, pEnd);
1921 if( pStart ){
1922 Expr *pX; /* The expression that defines the start bound */
1923 int r1, rTemp; /* Registers for holding the start boundary */
1924 int op; /* Cursor seek operation */
1925
1926 /* The following constant maps TK_xx codes into corresponding
1927 ** seek opcodes. It depends on a particular ordering of TK_xx
1928 */
1929 const u8 aMoveOp[] = {
1930 /* TK_GT */ OP_SeekGT,
1931 /* TK_LE */ OP_SeekLE,
1932 /* TK_LT */ OP_SeekLT,
1933 /* TK_GE */ OP_SeekGE
1934 };
1935 assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */
1936 assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */
1937 assert( TK_GE==TK_GT+3 ); /* ... is correct. */
1938
1939 assert( (pStart->wtFlags & TERM_VNULL)==0 );
1940 testcase( pStart->wtFlags & TERM_VIRTUAL );
1941 pX = pStart->pExpr;
1942 assert( pX!=0 );
1943 testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
1944 if( sqlite3ExprIsVector(pX->pRight) ){
1945 r1 = rTemp = sqlite3GetTempReg(pParse);
1946 codeExprOrVector(pParse, pX->pRight, r1, 1);
1947 testcase( pX->op==TK_GT );
1948 testcase( pX->op==TK_GE );
1949 testcase( pX->op==TK_LT );
1950 testcase( pX->op==TK_LE );
1951 op = aMoveOp[((pX->op - TK_GT - 1) & 0x3) | 0x1];
1952 assert( pX->op!=TK_GT || op==OP_SeekGE );
1953 assert( pX->op!=TK_GE || op==OP_SeekGE );
1954 assert( pX->op!=TK_LT || op==OP_SeekLE );
1955 assert( pX->op!=TK_LE || op==OP_SeekLE );
1956 }else{
1957 r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
1958 disableTerm(pLevel, pStart);
1959 op = aMoveOp[(pX->op - TK_GT)];
1960 }
1961 sqlite3VdbeAddOp3(v, op, iCur, addrBrk, r1);
1962 VdbeComment((v, "pk"));
1963 VdbeCoverageIf(v, pX->op==TK_GT);
1964 VdbeCoverageIf(v, pX->op==TK_LE);
1965 VdbeCoverageIf(v, pX->op==TK_LT);
1966 VdbeCoverageIf(v, pX->op==TK_GE);
1967 sqlite3ReleaseTempReg(pParse, rTemp);
1968 }else{
1969 sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, pLevel->addrHalt);
1970 VdbeCoverageIf(v, bRev==0);
1971 VdbeCoverageIf(v, bRev!=0);
1972 }
1973 if( pEnd ){
1974 Expr *pX;
1975 pX = pEnd->pExpr;
1976 assert( pX!=0 );
1977 assert( (pEnd->wtFlags & TERM_VNULL)==0 );
1978 testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
1979 testcase( pEnd->wtFlags & TERM_VIRTUAL );
1980 memEndValue = ++pParse->nMem;
1981 codeExprOrVector(pParse, pX->pRight, memEndValue, 1);
1982 if( 0==sqlite3ExprIsVector(pX->pRight)
1983 && (pX->op==TK_LT || pX->op==TK_GT)
1984 ){
1985 testOp = bRev ? OP_Le : OP_Ge;
1986 }else{
1987 testOp = bRev ? OP_Lt : OP_Gt;
1988 }
1989 if( 0==sqlite3ExprIsVector(pX->pRight) ){
1990 disableTerm(pLevel, pEnd);
1991 }
1992 }
1993 start = sqlite3VdbeCurrentAddr(v);
1994 pLevel->op = bRev ? OP_Prev : OP_Next;
1995 pLevel->p1 = iCur;
1996 pLevel->p2 = start;
1997 assert( pLevel->p5==0 );
1998 if( testOp!=OP_Noop ){
1999 iRowidReg = ++pParse->nMem;
2000 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
2001 sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
2002 VdbeCoverageIf(v, testOp==OP_Le);
2003 VdbeCoverageIf(v, testOp==OP_Lt);
2004 VdbeCoverageIf(v, testOp==OP_Ge);
2005 VdbeCoverageIf(v, testOp==OP_Gt);
2006 sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
2007 }
2008 }else if( pLoop->wsFlags & WHERE_INDEXED ){
2009 /* Case 4: Search using an index.
2010 **
2011 ** The WHERE clause may contain zero or more equality
2012 ** terms ("==" or "IN" or "IS" operators) that refer to the N
2013 ** left-most columns of the index. It may also contain
2014 ** inequality constraints (>, <, >= or <=) on the indexed
2015 ** column that immediately follows the N equalities. Only
2016 ** the right-most column can be an inequality - the rest must
2017 ** use the "==", "IN", or "IS" operators. For example, if the
2018 ** index is on (x,y,z), then the following clauses are all
2019 ** optimized:
2020 **
2021 ** x=5
2022 ** x=5 AND y=10
2023 ** x=5 AND y<10
2024 ** x=5 AND y>5 AND y<10
2025 ** x=5 AND y=5 AND z<=10
2026 **
2027 ** The z<10 term of the following cannot be used, only
2028 ** the x=5 term:
2029 **
2030 ** x=5 AND z<10
2031 **
2032 ** N may be zero if there are inequality constraints.
2033 ** If there are no inequality constraints, then N is at
2034 ** least one.
2035 **
2036 ** This case is also used when there are no WHERE clause
2037 ** constraints but an index is selected anyway, in order
2038 ** to force the output order to conform to an ORDER BY.
2039 */
2040 static const u8 aStartOp[] = {
2041 0,
2042 0,
2043 OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */
2044 OP_Last, /* 3: (!start_constraints && startEq && bRev) */
2045 OP_SeekGT, /* 4: (start_constraints && !startEq && !bRev) */
2046 OP_SeekLT, /* 5: (start_constraints && !startEq && bRev) */
2047 OP_SeekGE, /* 6: (start_constraints && startEq && !bRev) */
2048 OP_SeekLE /* 7: (start_constraints && startEq && bRev) */
2049 };
2050 static const u8 aEndOp[] = {
2051 OP_IdxGE, /* 0: (end_constraints && !bRev && !endEq) */
2052 OP_IdxGT, /* 1: (end_constraints && !bRev && endEq) */
2053 OP_IdxLE, /* 2: (end_constraints && bRev && !endEq) */
2054 OP_IdxLT, /* 3: (end_constraints && bRev && endEq) */
2055 };
2056 u16 nEq = pLoop->u.btree.nEq; /* Number of == or IN terms */
2057 u16 nBtm = pLoop->u.btree.nBtm; /* Length of BTM vector */
2058 u16 nTop = pLoop->u.btree.nTop; /* Length of TOP vector */
2059 int regBase; /* Base register holding constraint values */
2060 WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */
2061 WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */
2062 int startEq; /* True if range start uses ==, >= or <= */
2063 int endEq; /* True if range end uses ==, >= or <= */
2064 int start_constraints; /* Start of range is constrained */
2065 int nConstraint; /* Number of constraint terms */
2066 int iIdxCur; /* The VDBE cursor for the index */
2067 int nExtraReg = 0; /* Number of extra registers needed */
2068 int op; /* Instruction opcode */
2069 char *zStartAff; /* Affinity for start of range constraint */
2070 char *zEndAff = 0; /* Affinity for end of range constraint */
2071 u8 bSeekPastNull = 0; /* True to seek past initial nulls */
2072 u8 bStopAtNull = 0; /* Add condition to terminate at NULLs */
2073 int omitTable; /* True if we use the index only */
2074 int regBignull = 0; /* big-null flag register */
2075 int addrSeekScan = 0; /* Opcode of the OP_SeekScan, if any */
2076
2077 pIdx = pLoop->u.btree.pIndex;
2078 iIdxCur = pLevel->iIdxCur;
2079 assert( nEq>=pLoop->nSkip );
2080
2081 /* Find any inequality constraint terms for the start and end
2082 ** of the range.
2083 */
2084 j = nEq;
2085 if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
2086 pRangeStart = pLoop->aLTerm[j++];
2087 nExtraReg = MAX(nExtraReg, pLoop->u.btree.nBtm);
2088 /* Like optimization range constraints always occur in pairs */
2089 assert( (pRangeStart->wtFlags & TERM_LIKEOPT)==0 ||
2090 (pLoop->wsFlags & WHERE_TOP_LIMIT)!=0 );
2091 }
2092 if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
2093 pRangeEnd = pLoop->aLTerm[j++];
2094 nExtraReg = MAX(nExtraReg, pLoop->u.btree.nTop);
2095#ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
2096 if( (pRangeEnd->wtFlags & TERM_LIKEOPT)!=0 ){
2097 assert( pRangeStart!=0 ); /* LIKE opt constraints */
2098 assert( pRangeStart->wtFlags & TERM_LIKEOPT ); /* occur in pairs */
2099 pLevel->iLikeRepCntr = (u32)++pParse->nMem;
2100 /* iLikeRepCntr actually stores 2x the counter register number. The
2101 ** bottom bit indicates whether the search order is ASC or DESC. */
2102 testcase( bRev );
2103 testcase( pIdx->aSortOrder[nEq]==SQLITE_SO_DESC );
2104 assert( (bRev & ~1)==0 );
2105 pLevel->iLikeRepCntr <<=1;
2106 pLevel->iLikeRepCntr |= bRev ^ (pIdx->aSortOrder[nEq]==SQLITE_SO_DESC);
2107 }
2108#endif
2109 if( pRangeStart==0 ){
2110 j = pIdx->aiColumn[nEq];
2111 if( (j>=0 && pIdx->pTable->aCol[j].notNull==0) || j==XN_EXPR ){
2112 bSeekPastNull = 1;
2113 }
2114 }
2115 }
2116 assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 );
2117
2118 /* If the WHERE_BIGNULL_SORT flag is set, then index column nEq uses
2119 ** a non-default "big-null" sort (either ASC NULLS LAST or DESC NULLS
2120 ** FIRST). In both cases separate ordered scans are made of those
2121 ** index entries for which the column is null and for those for which
2122 ** it is not. For an ASC sort, the non-NULL entries are scanned first.
2123 ** For DESC, NULL entries are scanned first.
2124 */
2125 if( (pLoop->wsFlags & (WHERE_TOP_LIMIT|WHERE_BTM_LIMIT))==0
2126 && (pLoop->wsFlags & WHERE_IN_SEEKSCAN)==0
2127 && (pLoop->wsFlags & WHERE_BIGNULL_SORT)!=0
2128 ){
2129 assert( bSeekPastNull==0 && nExtraReg==0 && nBtm==0 && nTop==0 );
2130 assert( pRangeEnd==0 && pRangeStart==0 );
2131 testcase( pLoop->nSkip>0 );
2132 nExtraReg = 1;
2133 bSeekPastNull = 1;
2134 pLevel->regBignull = regBignull = ++pParse->nMem;
2135 if( pLevel->iLeftJoin ){
2136 sqlite3VdbeAddOp2(v, OP_Integer, 0, regBignull);
2137 }
2138 pLevel->addrBignull = sqlite3VdbeMakeLabel(pParse);
2139 }
2140
2141 /* If we are doing a reverse order scan on an ascending index, or
2142 ** a forward order scan on a descending index, interchange the
2143 ** start and end terms (pRangeStart and pRangeEnd).
2144 */
2145 if( (nEq<pIdx->nColumn && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC)) ){
2146 SWAP(WhereTerm *, pRangeEnd, pRangeStart);
2147 SWAP(u8, bSeekPastNull, bStopAtNull);
2148 SWAP(u8, nBtm, nTop);
2149 }
2150
2151 if( (iLevel>0 || (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)!=0)
2152 && (pLoop->wsFlags & WHERE_IN_SEEKSCAN)!=0
2153 ){
2154 /* In case OP_SeekScan is used, ensure that the index cursor does not
2155 ** point to a valid row for the first iteration of this loop. */
2156 sqlite3VdbeAddOp1(v, OP_NullRow, iIdxCur);
2157 }
2158
2159 /* Generate code to evaluate all constraint terms using == or IN
2160 ** and store the values of those terms in an array of registers
2161 ** starting at regBase.
2162 */
2163 codeCursorHint(pTabItem, pWInfo, pLevel, pRangeEnd);
2164 regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
2165 assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq );
2166#ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
2167 if( pLevel->iLikeRepCntr ){
2168 /* The LIKE optimization loop must be the innermost of any IN(...)
2169 ** or skip-scan loops. Otherwise rows may not be visited in index
2170 ** order. This means it needs an addrNxt label for the same reason
2171 ** IN(...) scans do. */
2172 if( pLevel->addrNxt==pLevel->addrBrk ){
2173 pLevel->addrNxt = sqlite3VdbeMakeLabel(pParse);
2174 }
2175 sqlite3VdbeAddOp2(v, OP_Integer, 1, (int)(pLevel->iLikeRepCntr>>1));
2176 VdbeComment((v, "LIKE loop counter"));
2177 pLevel->addrLikeRep = sqlite3VdbeCurrentAddr(v);
2178 }
2179#endif
2180 if( zStartAff && nTop ){
2181 zEndAff = sqlite3DbStrDup(db, &zStartAff[nEq]);
2182 }
2183 addrNxt = (regBignull ? pLevel->addrBignull : pLevel->addrNxt);
2184 if( addrMiss==0 ) addrMiss = addrNxt;
2185
2186 testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
2187 testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
2188 testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
2189 testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
2190 startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
2191 endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
2192 start_constraints = pRangeStart || nEq>0;
2193
2194 /* Seek the index cursor to the start of the range. */
2195 nConstraint = nEq;
2196 if( pRangeStart ){
2197 Expr *pRight = pRangeStart->pExpr->pRight;
2198 codeExprOrVector(pParse, pRight, regBase+nEq, nBtm);
2199 whereLikeOptimizationStringFixup(v, pLevel, pRangeStart);
2200 if( (pRangeStart->wtFlags & TERM_VNULL)==0
2201 && sqlite3ExprCanBeNull(pRight)
2202 ){
2203 sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
2204 VdbeCoverage(v);
2205 }
2206 if( zStartAff ){
2207 updateRangeAffinityStr(pRight, nBtm, &zStartAff[nEq]);
2208 }
2209 nConstraint += nBtm;
2210 testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
2211 if( sqlite3ExprIsVector(pRight)==0 ){
2212 disableTerm(pLevel, pRangeStart);
2213 }else{
2214 startEq = 1;
2215 }
2216 bSeekPastNull = 0;
2217 }else if( bSeekPastNull ){
2218 startEq = 0;
2219 sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
2220 start_constraints = 1;
2221 nConstraint++;
2222 }else if( regBignull ){
2223 sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
2224 start_constraints = 1;
2225 nConstraint++;
2226 }
2227 codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff);
2228 if( pLoop->nSkip>0 && nConstraint==pLoop->nSkip ){
2229 /* The skip-scan logic inside the call to codeAllEqualityConstraints()
2230 ** above has already left the cursor sitting on the correct row,
2231 ** so no further seeking is needed */
2232 }else{
2233 if( regBignull ){
2234 sqlite3VdbeAddOp2(v, OP_Integer, 1, regBignull);
2235 VdbeComment((v, "NULL-scan pass ctr"));
2236 }
2237 if( pLevel->regFilter ){
2238 assert( sqlite3WhereLoopBloomable(pLoop) );
2239 sqlite3VdbeAddOp4Int(v, OP_Filter, pLevel->regFilter, addrMiss,
2240 regBase, nEq);
2241 VdbeCoverage(v);
2242 filterPullDown(pParse, pWInfo, iLevel, addrNxt, notReady);
2243 }
2244
2245 op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
2246 assert( op!=0 );
2247 if( (pLoop->wsFlags & WHERE_IN_SEEKSCAN)!=0 && op==OP_SeekGE ){
2248 assert( regBignull==0 );
2249 /* TUNING: The OP_SeekScan opcode seeks to reduce the number
2250 ** of expensive seek operations by replacing a single seek with
2251 ** 1 or more step operations. The question is, how many steps
2252 ** should we try before giving up and going with a seek. The cost
2253 ** of a seek is proportional to the logarithm of the of the number
2254 ** of entries in the tree, so basing the number of steps to try
2255 ** on the estimated number of rows in the btree seems like a good
2256 ** guess. */
2257 addrSeekScan = sqlite3VdbeAddOp1(v, OP_SeekScan,
2258 (pIdx->aiRowLogEst[0]+9)/10);
2259 if( pRangeStart || pRangeEnd ){
2260 sqlite3VdbeChangeP5(v, 1);
2261 sqlite3VdbeChangeP2(v, addrSeekScan, sqlite3VdbeCurrentAddr(v)+1);
2262 addrSeekScan = 0;
2263 }
2264 VdbeCoverage(v);
2265 }
2266 sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrMiss, regBase, nConstraint);
2267 VdbeCoverage(v);
2268 VdbeCoverageIf(v, op==OP_Rewind); testcase( op==OP_Rewind );
2269 VdbeCoverageIf(v, op==OP_Last); testcase( op==OP_Last );
2270 VdbeCoverageIf(v, op==OP_SeekGT); testcase( op==OP_SeekGT );
2271 VdbeCoverageIf(v, op==OP_SeekGE); testcase( op==OP_SeekGE );
2272 VdbeCoverageIf(v, op==OP_SeekLE); testcase( op==OP_SeekLE );
2273 VdbeCoverageIf(v, op==OP_SeekLT); testcase( op==OP_SeekLT );
2274
2275 assert( bSeekPastNull==0 || bStopAtNull==0 );
2276 if( regBignull ){
2277 assert( bSeekPastNull==1 || bStopAtNull==1 );
2278 assert( bSeekPastNull==!bStopAtNull );
2279 assert( bStopAtNull==startEq );
2280 sqlite3VdbeAddOp2(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+2);
2281 op = aStartOp[(nConstraint>1)*4 + 2 + bRev];
2282 sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase,
2283 nConstraint-startEq);
2284 VdbeCoverage(v);
2285 VdbeCoverageIf(v, op==OP_Rewind); testcase( op==OP_Rewind );
2286 VdbeCoverageIf(v, op==OP_Last); testcase( op==OP_Last );
2287 VdbeCoverageIf(v, op==OP_SeekGE); testcase( op==OP_SeekGE );
2288 VdbeCoverageIf(v, op==OP_SeekLE); testcase( op==OP_SeekLE );
2289 assert( op==OP_Rewind || op==OP_Last || op==OP_SeekGE || op==OP_SeekLE);
2290 }
2291 }
2292
2293 /* Load the value for the inequality constraint at the end of the
2294 ** range (if any).
2295 */
2296 nConstraint = nEq;
2297 assert( pLevel->p2==0 );
2298 if( pRangeEnd ){
2299 Expr *pRight = pRangeEnd->pExpr->pRight;
2300 assert( addrSeekScan==0 );
2301 codeExprOrVector(pParse, pRight, regBase+nEq, nTop);
2302 whereLikeOptimizationStringFixup(v, pLevel, pRangeEnd);
2303 if( (pRangeEnd->wtFlags & TERM_VNULL)==0
2304 && sqlite3ExprCanBeNull(pRight)
2305 ){
2306 sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
2307 VdbeCoverage(v);
2308 }
2309 if( zEndAff ){
2310 updateRangeAffinityStr(pRight, nTop, zEndAff);
2311 codeApplyAffinity(pParse, regBase+nEq, nTop, zEndAff);
2312 }else{
2313 assert( pParse->db->mallocFailed );
2314 }
2315 nConstraint += nTop;
2316 testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
2317
2318 if( sqlite3ExprIsVector(pRight)==0 ){
2319 disableTerm(pLevel, pRangeEnd);
2320 }else{
2321 endEq = 1;
2322 }
2323 }else if( bStopAtNull ){
2324 if( regBignull==0 ){
2325 sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
2326 endEq = 0;
2327 }
2328 nConstraint++;
2329 }
2330 if( zStartAff ) sqlite3DbNNFreeNN(db, zStartAff);
2331 if( zEndAff ) sqlite3DbNNFreeNN(db, zEndAff);
2332
2333 /* Top of the loop body */
2334 pLevel->p2 = sqlite3VdbeCurrentAddr(v);
2335
2336 /* Check if the index cursor is past the end of the range. */
2337 if( nConstraint ){
2338 if( regBignull ){
2339 /* Except, skip the end-of-range check while doing the NULL-scan */
2340 sqlite3VdbeAddOp2(v, OP_IfNot, regBignull, sqlite3VdbeCurrentAddr(v)+3);
2341 VdbeComment((v, "If NULL-scan 2nd pass"));
2342 VdbeCoverage(v);
2343 }
2344 op = aEndOp[bRev*2 + endEq];
2345 sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
2346 testcase( op==OP_IdxGT ); VdbeCoverageIf(v, op==OP_IdxGT );
2347 testcase( op==OP_IdxGE ); VdbeCoverageIf(v, op==OP_IdxGE );
2348 testcase( op==OP_IdxLT ); VdbeCoverageIf(v, op==OP_IdxLT );
2349 testcase( op==OP_IdxLE ); VdbeCoverageIf(v, op==OP_IdxLE );
2350 if( addrSeekScan ) sqlite3VdbeJumpHere(v, addrSeekScan);
2351 }
2352 if( regBignull ){
2353 /* During a NULL-scan, check to see if we have reached the end of
2354 ** the NULLs */
2355 assert( bSeekPastNull==!bStopAtNull );
2356 assert( bSeekPastNull+bStopAtNull==1 );
2357 assert( nConstraint+bSeekPastNull>0 );
2358 sqlite3VdbeAddOp2(v, OP_If, regBignull, sqlite3VdbeCurrentAddr(v)+2);
2359 VdbeComment((v, "If NULL-scan 1st pass"));
2360 VdbeCoverage(v);
2361 op = aEndOp[bRev*2 + bSeekPastNull];
2362 sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase,
2363 nConstraint+bSeekPastNull);
2364 testcase( op==OP_IdxGT ); VdbeCoverageIf(v, op==OP_IdxGT );
2365 testcase( op==OP_IdxGE ); VdbeCoverageIf(v, op==OP_IdxGE );
2366 testcase( op==OP_IdxLT ); VdbeCoverageIf(v, op==OP_IdxLT );
2367 testcase( op==OP_IdxLE ); VdbeCoverageIf(v, op==OP_IdxLE );
2368 }
2369
2370 if( (pLoop->wsFlags & WHERE_IN_EARLYOUT)!=0 ){
2371 sqlite3VdbeAddOp3(v, OP_SeekHit, iIdxCur, nEq, nEq);
2372 }
2373
2374 /* Seek the table cursor, if required */
2375 omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
2376 && (pWInfo->wctrlFlags & (WHERE_OR_SUBCLAUSE|WHERE_RIGHT_JOIN))==0;
2377 if( omitTable ){
2378 /* pIdx is a covering index. No need to access the main table. */
2379 }else if( HasRowid(pIdx->pTable) ){
2380 codeDeferredSeek(pWInfo, pIdx, iCur, iIdxCur);
2381 }else if( iCur!=iIdxCur ){
2382 Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
2383 iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol);
2384 for(j=0; j<pPk->nKeyCol; j++){
2385 k = sqlite3TableColumnToIndex(pIdx, pPk->aiColumn[j]);
2386 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j);
2387 }
2388 sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont,
2389 iRowidReg, pPk->nKeyCol); VdbeCoverage(v);
2390 }
2391
2392 if( pLevel->iLeftJoin==0 ){
2393 /* If a partial index is driving the loop, try to eliminate WHERE clause
2394 ** terms from the query that must be true due to the WHERE clause of
2395 ** the partial index. This optimization does not work on an outer join,
2396 ** as shown by:
2397 **
2398 ** 2019-11-02 ticket 623eff57e76d45f6 (LEFT JOIN)
2399 ** 2025-05-29 forum post 7dee41d32506c4ae (RIGHT JOIN)
2400 */
2401 if( pIdx->pPartIdxWhere && pLevel->pRJ==0 ){
2402 whereApplyPartialIndexConstraints(pIdx->pPartIdxWhere, iCur, pWC);
2403 }
2404 }else{
2405 testcase( pIdx->pPartIdxWhere );
2406 /* The following assert() is not a requirement, merely an observation:
2407 ** The OR-optimization doesn't work for the right hand table of
2408 ** a LEFT JOIN: */
2409 assert( (pWInfo->wctrlFlags & (WHERE_OR_SUBCLAUSE|WHERE_RIGHT_JOIN))==0 );
2410 }
2411
2412 /* Record the instruction used to terminate the loop. */
2413 if( (pLoop->wsFlags & WHERE_ONEROW)
2414 || (pLevel->u.in.nIn && regBignull==0 && whereLoopIsOneRow(pLoop))
2415 ){
2416 pLevel->op = OP_Noop;
2417 }else if( bRev ){
2418 pLevel->op = OP_Prev;
2419 }else{
2420 pLevel->op = OP_Next;
2421 }
2422 pLevel->p1 = iIdxCur;
2423 pLevel->p3 = (pLoop->wsFlags&WHERE_UNQ_WANTED)!=0 ? 1:0;
2424 if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
2425 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
2426 }else{
2427 assert( pLevel->p5==0 );
2428 }
2429 if( omitTable ) pIdx = 0;
2430 }else
2431
2432#ifndef SQLITE_OMIT_OR_OPTIMIZATION
2433 if( pLoop->wsFlags & WHERE_MULTI_OR ){
2434 /* Case 5: Two or more separately indexed terms connected by OR
2435 **
2436 ** Example:
2437 **
2438 ** CREATE TABLE t1(a,b,c,d);
2439 ** CREATE INDEX i1 ON t1(a);
2440 ** CREATE INDEX i2 ON t1(b);
2441 ** CREATE INDEX i3 ON t1(c);
2442 **
2443 ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
2444 **
2445 ** In the example, there are three indexed terms connected by OR.
2446 ** The top of the loop looks like this:
2447 **
2448 ** Null 1 # Zero the rowset in reg 1
2449 **
2450 ** Then, for each indexed term, the following. The arguments to
2451 ** RowSetTest are such that the rowid of the current row is inserted
2452 ** into the RowSet. If it is already present, control skips the
2453 ** Gosub opcode and jumps straight to the code generated by WhereEnd().
2454 **
2455 ** sqlite3WhereBegin(<term>)
2456 ** RowSetTest # Insert rowid into rowset
2457 ** Gosub 2 A
2458 ** sqlite3WhereEnd()
2459 **
2460 ** Following the above, code to terminate the loop. Label A, the target
2461 ** of the Gosub above, jumps to the instruction right after the Goto.
2462 **
2463 ** Null 1 # Zero the rowset in reg 1
2464 ** Goto B # The loop is finished.
2465 **
2466 ** A: <loop body> # Return data, whatever.
2467 **
2468 ** Return 2 # Jump back to the Gosub
2469 **
2470 ** B: <after the loop>
2471 **
2472 ** Added 2014-05-26: If the table is a WITHOUT ROWID table, then
2473 ** use an ephemeral index instead of a RowSet to record the primary
2474 ** keys of the rows we have already seen.
2475 **
2476 */
2477 WhereClause *pOrWc; /* The OR-clause broken out into subterms */
2478 SrcList *pOrTab; /* Shortened table list or OR-clause generation */
2479 Index *pCov = 0; /* Potential covering index (or NULL) */
2480 int iCovCur = pParse->nTab++; /* Cursor used for index scans (if any) */
2481
2482 int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */
2483 int regRowset = 0; /* Register for RowSet object */
2484 int regRowid = 0; /* Register holding rowid */
2485 int iLoopBody = sqlite3VdbeMakeLabel(pParse);/* Start of loop body */
2486 int iRetInit; /* Address of regReturn init */
2487 int untestedTerms = 0; /* Some terms not completely tested */
2488 int ii; /* Loop counter */
2489 Expr *pAndExpr = 0; /* An ".. AND (...)" expression */
2490 Table *pTab = pTabItem->pSTab;
2491
2492 pTerm = pLoop->aLTerm[0];
2493 assert( pTerm!=0 );
2494 assert( pTerm->eOperator & WO_OR );
2495 assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
2496 pOrWc = &pTerm->u.pOrInfo->wc;
2497 pLevel->op = OP_Return;
2498 pLevel->p1 = regReturn;
2499
2500 /* Set up a new SrcList in pOrTab containing the table being scanned
2501 ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
2502 ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
2503 */
2504 if( pWInfo->nLevel>1 || pTabItem->fg.fromExists ){
2505 int nNotReady; /* The number of notReady tables */
2506 SrcItem *origSrc; /* Original list of tables */
2507 nNotReady = pWInfo->nLevel - iLevel - 1;
2508 pOrTab = sqlite3DbMallocRawNN(db, SZ_SRCLIST(nNotReady+1));
2509 if( pOrTab==0 ) return notReady;
2510 pOrTab->nAlloc = (u8)(nNotReady + 1);
2511 pOrTab->nSrc = pOrTab->nAlloc;
2512 memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
2513 origSrc = pWInfo->pTabList->a;
2514 for(k=1; k<=nNotReady; k++){
2515 memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
2516 }
2517
2518 /* Clear the fromExists flag on the OR-optimized table entry so that
2519 ** the calls to sqlite3WhereEnd() do not code early-exits after the
2520 ** first row is visited. The early exit applies to this table's
2521 ** overall loop - including the multiple OR branches and any WHERE
2522 ** conditions not passed to the sub-loops - not to the sub-loops. */
2523 pOrTab->a[0].fg.fromExists = 0;
2524 }else{
2525 pOrTab = pWInfo->pTabList;
2526 }
2527
2528 /* Initialize the rowset register to contain NULL. An SQL NULL is
2529 ** equivalent to an empty rowset. Or, create an ephemeral index
2530 ** capable of holding primary keys in the case of a WITHOUT ROWID.
2531 **
2532 ** Also initialize regReturn to contain the address of the instruction
2533 ** immediately following the OP_Return at the bottom of the loop. This
2534 ** is required in a few obscure LEFT JOIN cases where control jumps
2535 ** over the top of the loop into the body of it. In this case the
2536 ** correct response for the end-of-loop code (the OP_Return) is to
2537 ** fall through to the next instruction, just as an OP_Next does if
2538 ** called on an uninitialized cursor.
2539 */
2540 if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
2541 if( HasRowid(pTab) ){
2542 regRowset = ++pParse->nMem;
2543 sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
2544 }else{
2545 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
2546 regRowset = pParse->nTab++;
2547 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, regRowset, pPk->nKeyCol);
2548 sqlite3VdbeSetP4KeyInfo(pParse, pPk);
2549 }
2550 regRowid = ++pParse->nMem;
2551 }
2552 iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
2553
2554 /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y
2555 ** Then for every term xN, evaluate as the subexpression: xN AND y
2556 ** That way, terms in y that are factored into the disjunction will
2557 ** be picked up by the recursive calls to sqlite3WhereBegin() below.
2558 **
2559 ** Actually, each subexpression is converted to "xN AND w" where w is
2560 ** the "interesting" terms of z - terms that did not originate in the
2561 ** ON or USING clause of a LEFT JOIN, and terms that are usable as
2562 ** indices.
2563 **
2564 ** This optimization also only applies if the (x1 OR x2 OR ...) term
2565 ** is not contained in the ON clause of a LEFT JOIN.
2566 ** See ticket http://sqlite.org/src/info/f2369304e4
2567 **
2568 ** 2022-02-04: Do not push down slices of a row-value comparison.
2569 ** In other words, "w" or "y" may not be a slice of a vector. Otherwise,
2570 ** the initialization of the right-hand operand of the vector comparison
2571 ** might not occur, or might occur only in an OR branch that is not
2572 ** taken. dbsqlfuzz 80a9fade844b4fb43564efc972bcb2c68270f5d1.
2573 **
2574 ** 2022-03-03: Do not push down expressions that involve subqueries.
2575 ** The subquery might get coded as a subroutine. Any table-references
2576 ** in the subquery might be resolved to index-references for the index on
2577 ** the OR branch in which the subroutine is coded. But if the subroutine
2578 ** is invoked from a different OR branch that uses a different index, such
2579 ** index-references will not work. tag-20220303a
2580 ** https://sqlite.org/forum/forumpost/36937b197273d403
2581 */
2582 if( pWC->nTerm>1 ){
2583 int iTerm;
2584 for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
2585 Expr *pExpr = pWC->a[iTerm].pExpr;
2586 if( &pWC->a[iTerm] == pTerm ) continue;
2587 testcase( pWC->a[iTerm].wtFlags & TERM_VIRTUAL );
2588 testcase( pWC->a[iTerm].wtFlags & TERM_CODED );
2589 testcase( pWC->a[iTerm].wtFlags & TERM_SLICE );
2590 if( (pWC->a[iTerm].wtFlags & (TERM_VIRTUAL|TERM_CODED|TERM_SLICE))!=0 ){
2591 continue;
2592 }
2593 if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
2594 if( ExprHasProperty(pExpr, EP_Subquery) ) continue; /* tag-20220303a */
2595 if( whereExprIsReady(pWInfo, pLevel, pTabItem, pExpr)==0 ) continue;
2596 pExpr = sqlite3ExprDup(db, pExpr, 0);
2597 pAndExpr = sqlite3ExprAnd(pParse, pAndExpr, pExpr);
2598 }
2599 if( pAndExpr ){
2600 /* The extra 0x10000 bit on the opcode is masked off and does not
2601 ** become part of the new Expr.op. However, it does make the
2602 ** op==TK_AND comparison inside of sqlite3PExpr() false, and this
2603 ** prevents sqlite3PExpr() from applying the AND short-circuit
2604 ** optimization, which we do not want here. */
2605 pAndExpr = sqlite3PExpr(pParse, TK_AND|0x10000, 0, pAndExpr);
2606 }
2607 }
2608
2609 /* Run a separate WHERE clause for each term of the OR clause. After
2610 ** eliminating duplicates from other WHERE clauses, the action for each
2611 ** sub-WHERE clause is to to invoke the main loop body as a subroutine.
2612 */
2613 ExplainQueryPlan((pParse, 1, "MULTI-INDEX OR"));
2614 for(ii=0; ii<pOrWc->nTerm; ii++){
2615 WhereTerm *pOrTerm = &pOrWc->a[ii];
2616 if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
2617 WhereInfo *pSubWInfo; /* Info for single OR-term scan */
2618 Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */
2619 Expr *pDelete; /* Local copy of OR clause term */
2620 int jmp1 = 0; /* Address of jump operation */
2621 testcase( (pTabItem[0].fg.jointype & JT_LEFT)!=0
2622 && !ExprHasProperty(pOrExpr, EP_OuterON)
2623 ); /* See TH3 vtab25.400 and ticket 614b25314c766238 */
2624 pDelete = pOrExpr = sqlite3ExprDup(db, pOrExpr, 0);
2625 if( db->mallocFailed ){
2626 sqlite3ExprDelete(db, pDelete);
2627 continue;
2628 }
2629 if( pAndExpr ){
2630 pAndExpr->pLeft = pOrExpr;
2631 pOrExpr = pAndExpr;
2632 }
2633 /* Loop through table entries that match term pOrTerm. */
2634 ExplainQueryPlan((pParse, 1, "INDEX %d", ii+1));
2635 WHERETRACE(0xffffffff, ("Subplan for OR-clause:\n"));
2636 pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0, 0,
2637 WHERE_OR_SUBCLAUSE, iCovCur);
2638 assert( pSubWInfo || pParse->nErr );
2639 if( pSubWInfo ){
2640 WhereLoop *pSubLoop;
2641 int addrExplain = sqlite3WhereExplainOneScan(
2642 pParse, pOrTab, &pSubWInfo->a[0], 0
2643 );
2644 sqlite3WhereAddScanStatus(v, pOrTab, &pSubWInfo->a[0], addrExplain);
2645
2646 /* This is the sub-WHERE clause body. First skip over
2647 ** duplicate rows from prior sub-WHERE clauses, and record the
2648 ** rowid (or PRIMARY KEY) for the current row so that the same
2649 ** row will be skipped in subsequent sub-WHERE clauses.
2650 */
2651 if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
2652 int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
2653 if( HasRowid(pTab) ){
2654 sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, -1, regRowid);
2655 jmp1 = sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, 0,
2656 regRowid, iSet);
2657 VdbeCoverage(v);
2658 }else{
2659 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
2660 int nPk = pPk->nKeyCol;
2661 int iPk;
2662 int r;
2663
2664 /* Read the PK into an array of temp registers. */
2665 r = sqlite3GetTempRange(pParse, nPk);
2666 for(iPk=0; iPk<nPk; iPk++){
2667 int iCol = pPk->aiColumn[iPk];
2668 sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol,r+iPk);
2669 }
2670
2671 /* Check if the temp table already contains this key. If so,
2672 ** the row has already been included in the result set and
2673 ** can be ignored (by jumping past the Gosub below). Otherwise,
2674 ** insert the key into the temp table and proceed with processing
2675 ** the row.
2676 **
2677 ** Use some of the same optimizations as OP_RowSetTest: If iSet
2678 ** is zero, assume that the key cannot already be present in
2679 ** the temp table. And if iSet is -1, assume that there is no
2680 ** need to insert the key into the temp table, as it will never
2681 ** be tested for. */
2682 if( iSet ){
2683 jmp1 = sqlite3VdbeAddOp4Int(v, OP_Found, regRowset, 0, r, nPk);
2684 VdbeCoverage(v);
2685 }
2686 if( iSet>=0 ){
2687 sqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, regRowid);
2688 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, regRowset, regRowid,
2689 r, nPk);
2690 if( iSet ) sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
2691 }
2692
2693 /* Release the array of temp registers */
2694 sqlite3ReleaseTempRange(pParse, r, nPk);
2695 }
2696 }
2697
2698 /* Invoke the main loop body as a subroutine */
2699 sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
2700
2701 /* Jump here (skipping the main loop body subroutine) if the
2702 ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */
2703 if( jmp1 ) sqlite3VdbeJumpHere(v, jmp1);
2704
2705 /* The pSubWInfo->untestedTerms flag means that this OR term
2706 ** contained one or more AND term from a notReady table. The
2707 ** terms from the notReady table could not be tested and will
2708 ** need to be tested later.
2709 */
2710 if( pSubWInfo->untestedTerms ) untestedTerms = 1;
2711
2712 /* If all of the OR-connected terms are optimized using the same
2713 ** index, and the index is opened using the same cursor number
2714 ** by each call to sqlite3WhereBegin() made by this loop, it may
2715 ** be possible to use that index as a covering index.
2716 **
2717 ** If the call to sqlite3WhereBegin() above resulted in a scan that
2718 ** uses an index, and this is either the first OR-connected term
2719 ** processed or the index is the same as that used by all previous
2720 ** terms, set pCov to the candidate covering index. Otherwise, set
2721 ** pCov to NULL to indicate that no candidate covering index will
2722 ** be available.
2723 */
2724 pSubLoop = pSubWInfo->a[0].pWLoop;
2725 assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
2726 if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
2727 && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
2728 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pSubLoop->u.btree.pIndex))
2729 ){
2730 assert( pSubWInfo->a[0].iIdxCur==iCovCur );
2731 pCov = pSubLoop->u.btree.pIndex;
2732 }else{
2733 pCov = 0;
2734 }
2735 if( sqlite3WhereUsesDeferredSeek(pSubWInfo) ){
2736 pWInfo->bDeferredSeek = 1;
2737 }
2738
2739 /* Finish the loop through table entries that match term pOrTerm. */
2740 sqlite3WhereEnd(pSubWInfo);
2741 ExplainQueryPlanPop(pParse);
2742 }
2743 sqlite3ExprDelete(db, pDelete);
2744 }
2745 }
2746 ExplainQueryPlanPop(pParse);
2747 assert( pLevel->pWLoop==pLoop );
2748 assert( (pLoop->wsFlags & WHERE_MULTI_OR)!=0 );
2749 assert( (pLoop->wsFlags & WHERE_IN_ABLE)==0 );
2750 pLevel->u.pCoveringIdx = pCov;
2751 if( pCov ) pLevel->iIdxCur = iCovCur;
2752 if( pAndExpr ){
2753 pAndExpr->pLeft = 0;
2754 sqlite3ExprDelete(db, pAndExpr);
2755 }
2756 sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
2757 sqlite3VdbeGoto(v, pLevel->addrBrk);
2758 sqlite3VdbeResolveLabel(v, iLoopBody);
2759
2760 /* Set the P2 operand of the OP_Return opcode that will end the current
2761 ** loop to point to this spot, which is the top of the next containing
2762 ** loop. The byte-code formatter will use that P2 value as a hint to
2763 ** indent everything in between the this point and the final OP_Return.
2764 ** See tag-20220407a in vdbe.c and shell.c */
2765 assert( pLevel->op==OP_Return );
2766 pLevel->p2 = sqlite3VdbeCurrentAddr(v);
2767
2768 if( pWInfo->pTabList!=pOrTab ){ sqlite3DbFreeNN(db, pOrTab); }
2769 if( !untestedTerms ) disableTerm(pLevel, pTerm);
2770 }else
2771#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
2772
2773 {
2774 /* Case 6: There is no usable index. We must do a complete
2775 ** scan of the entire table.
2776 */
2777 static const u8 aStep[] = { OP_Next, OP_Prev };
2778 static const u8 aStart[] = { OP_Rewind, OP_Last };
2779 assert( bRev==0 || bRev==1 );
2780 if( pTabItem->fg.isRecursive ){
2781 /* Tables marked isRecursive have only a single row that is stored in
2782 ** a pseudo-cursor. No need to Rewind or Next such cursors. */
2783 pLevel->op = OP_Noop;
2784 }else{
2785 codeCursorHint(pTabItem, pWInfo, pLevel, 0);
2786 pLevel->op = aStep[bRev];
2787 pLevel->p1 = iCur;
2788 pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev],iCur,pLevel->addrHalt);
2789 VdbeCoverageIf(v, bRev==0);
2790 VdbeCoverageIf(v, bRev!=0);
2791 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
2792 }
2793 }
2794
2795#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
2796 pLevel->addrVisit = sqlite3VdbeCurrentAddr(v);
2797#endif
2798
2799 /* Insert code to test every subexpression that can be completely
2800 ** computed using the current set of tables.
2801 **
2802 ** This loop may run between one and three times, depending on the
2803 ** constraints to be generated. The value of stack variable iLoop
2804 ** determines the constraints coded by each iteration, as follows:
2805 **
2806 ** iLoop==1: Code only expressions that are entirely covered by pIdx.
2807 ** iLoop==2: Code remaining expressions that do not contain correlated
2808 ** sub-queries.
2809 ** iLoop==3: Code all remaining expressions.
2810 **
2811 ** An effort is made to skip unnecessary iterations of the loop.
2812 **
2813 ** This optimization of causing simple query restrictions to occur before
2814 ** more complex one is call the "push-down" optimization in MySQL. Here
2815 ** in SQLite, the name is "MySQL push-down", since there is also another
2816 ** totally unrelated optimization called "WHERE-clause push-down".
2817 ** Sometimes the qualifier is omitted, resulting in an ambiguity, so beware.
2818 */
2819 iLoop = (pIdx ? 1 : 2);
2820 do{
2821 int iNext = 0; /* Next value for iLoop */
2822 for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
2823 Expr *pE;
2824 int skipLikeAddr = 0;
2825 testcase( pTerm->wtFlags & TERM_VIRTUAL );
2826 testcase( pTerm->wtFlags & TERM_CODED );
2827 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
2828 if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
2829 testcase( pWInfo->untestedTerms==0
2830 && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 );
2831 pWInfo->untestedTerms = 1;
2832 continue;
2833 }
2834 pE = pTerm->pExpr;
2835 assert( pE!=0 );
2836 if( whereExprIsReady(pWInfo, pLevel, pTabItem, pE)==0 ) continue;
2837 if( iLoop==1 && !sqlite3ExprCoveredByIndex(pE, pLevel->iTabCur, pIdx) ){
2838 iNext = 2;
2839 continue;
2840 }
2841 if( iLoop<3 && (pTerm->wtFlags & TERM_VARSELECT) ){
2842 if( iNext==0 ) iNext = 3;
2843 continue;
2844 }
2845
2846 if( (pTerm->wtFlags & TERM_LIKECOND)!=0 ){
2847 /* If the TERM_LIKECOND flag is set, that means that the range search
2848 ** is sufficient to guarantee that the LIKE operator is true, so we
2849 ** can skip the call to the like(A,B) function. But this only works
2850 ** for strings. So do not skip the call to the function on the pass
2851 ** that compares BLOBs. */
2852#ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
2853 continue;
2854#else
2855 u32 x = pLevel->iLikeRepCntr;
2856 if( x>0 ){
2857 skipLikeAddr = sqlite3VdbeAddOp1(v, (x&1)?OP_IfNot:OP_If,(int)(x>>1));
2858 VdbeCoverageIf(v, (x&1)==1);
2859 VdbeCoverageIf(v, (x&1)==0);
2860 }
2861#endif
2862 }
2863#ifdef WHERETRACE_ENABLED /* 0xffffffff */
2864 if( sqlite3WhereTrace ){
2865 VdbeNoopComment((v, "WhereTerm[%d] (%p) priority=%d",
2866 pWC->nTerm-j, pTerm, iLoop));
2867 }
2868 if( sqlite3WhereTrace & 0x4000 ){
2869 sqlite3DebugPrintf("Coding auxiliary constraint:\n");
2870 sqlite3WhereTermPrint(pTerm, pWC->nTerm-j);
2871 }
2872#endif
2873 sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
2874 if( skipLikeAddr ) sqlite3VdbeJumpHere(v, skipLikeAddr);
2875 pTerm->wtFlags |= TERM_CODED;
2876 }
2877 iLoop = iNext;
2878 }while( iLoop>0 );
2879
2880 /* Insert code to test for implied constraints based on transitivity
2881 ** of the "==" operator.
2882 **
2883 ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
2884 ** and we are coding the t1 loop and the t2 loop has not yet coded,
2885 ** then we cannot use the "t1.a=t2.b" constraint, but we can code
2886 ** the implied "t1.a=123" constraint.
2887 */
2888 for(pTerm=pWC->a, j=pWC->nBase; j>0; j--, pTerm++){
2889 Expr *pE, sEAlt;
2890 WhereTerm *pAlt;
2891 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
2892 if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) continue;
2893 if( (pTerm->eOperator & WO_EQUIV)==0 ) continue;
2894 if( pTerm->leftCursor!=iCur ) continue;
2895 if( pTabItem->fg.jointype & (JT_LEFT|JT_LTORJ|JT_RIGHT) ) continue;
2896 pE = pTerm->pExpr;
2897#ifdef WHERETRACE_ENABLED /* 0x4001 */
2898 if( (sqlite3WhereTrace & 0x4001)==0x4001 ){
2899 sqlite3DebugPrintf("Coding transitive constraint:\n");
2900 sqlite3WhereTermPrint(pTerm, pWC->nTerm-j);
2901 }
2902#endif
2903 assert( !ExprHasProperty(pE, EP_OuterON) );
2904 assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
2905 assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 );
2906 pAlt = sqlite3WhereFindTerm(pWC, iCur, pTerm->u.x.leftColumn, notReady,
2907 WO_EQ|WO_IN|WO_IS, 0);
2908 if( pAlt==0 ) continue;
2909 if( pAlt->wtFlags & (TERM_CODED) ) continue;
2910 if( ExprHasProperty(pAlt->pExpr, EP_Collate) ) continue;
2911 if( (pAlt->eOperator & WO_IN)
2912 && ExprUseXSelect(pAlt->pExpr)
2913 && (pAlt->pExpr->x.pSelect->pEList->nExpr>1)
2914 ){
2915 continue;
2916 }
2917 testcase( pAlt->eOperator & WO_EQ );
2918 testcase( pAlt->eOperator & WO_IS );
2919 testcase( pAlt->eOperator & WO_IN );
2920 VdbeModuleComment((v, "begin transitive constraint"));
2921 sEAlt = *pAlt->pExpr;
2922 sEAlt.pLeft = pE->pLeft;
2923 sqlite3ExprIfFalse(pParse, &sEAlt, addrCont, SQLITE_JUMPIFNULL);
2924 pAlt->wtFlags |= TERM_CODED;
2925 }
2926
2927 /* For a RIGHT OUTER JOIN, record the fact that the current row has
2928 ** been matched at least once.
2929 */
2930 if( pLevel->pRJ ){
2931 Table *pTab;
2932 int nPk;
2933 int r;
2934 int jmp1 = 0;
2935 WhereRightJoin *pRJ = pLevel->pRJ;
2936
2937 /* pTab is the right-hand table of the RIGHT JOIN. Generate code that
2938 ** will record that the current row of that table has been matched at
2939 ** least once. This is accomplished by storing the PK for the row in
2940 ** both the iMatch index and the regBloom Bloom filter.
2941 */
2942 pTab = pWInfo->pTabList->a[pLevel->iFrom].pSTab;
2943 if( HasRowid(pTab) ){
2944 r = sqlite3GetTempRange(pParse, 2);
2945 sqlite3ExprCodeGetColumnOfTable(v, pTab, pLevel->iTabCur, -1, r+1);
2946 nPk = 1;
2947 }else{
2948 int iPk;
2949 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
2950 nPk = pPk->nKeyCol;
2951 r = sqlite3GetTempRange(pParse, nPk+1);
2952 for(iPk=0; iPk<nPk; iPk++){
2953 int iCol = pPk->aiColumn[iPk];
2954 sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol,r+1+iPk);
2955 }
2956 }
2957 jmp1 = sqlite3VdbeAddOp4Int(v, OP_Found, pRJ->iMatch, 0, r+1, nPk);
2958 VdbeCoverage(v);
2959 VdbeComment((v, "match against %s", pTab->zName));
2960 sqlite3VdbeAddOp3(v, OP_MakeRecord, r+1, nPk, r);
2961 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pRJ->iMatch, r, r+1, nPk);
2962 if( pRJ->regBloom ){
2963 sqlite3VdbeAddOp4Int(v, OP_FilterAdd, pRJ->regBloom, 0, r+1, nPk);
2964 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
2965 }
2966 sqlite3VdbeJumpHere(v, jmp1);
2967 sqlite3ReleaseTempRange(pParse, r, nPk+1);
2968 }
2969
2970 /* For a LEFT OUTER JOIN, generate code that will record the fact that
2971 ** at least one row of the right table has matched the left table.
2972 */
2973 if( pLevel->iLeftJoin ){
2974 pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
2975 sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
2976 VdbeComment((v, "record LEFT JOIN hit"));
2977 if( pLevel->pRJ==0 ){
2978 goto code_outer_join_constraints; /* WHERE clause constraints */
2979 }
2980 }
2981
2982 if( pLevel->pRJ ){
2983 /* Create a subroutine used to process all interior loops and code
2984 ** of the RIGHT JOIN. During normal operation, the subroutine will
2985 ** be in-line with the rest of the code. But at the end, a separate
2986 ** loop will run that invokes this subroutine for unmatched rows
2987 ** of pTab, with all tables to left begin set to NULL.
2988 */
2989 {
2990 WhereRightJoin *pRJ = pLevel->pRJ;
2991 sqlite3VdbeAddOp2(v, OP_BeginSubrtn, 0, pRJ->regReturn);
2992 pRJ->addrSubrtn = sqlite3VdbeCurrentAddr(v);
2993 }
2994 assert( pParse->withinRJSubrtn < 255 );
2995 pParse->withinRJSubrtn++;
2996
2997 /* WHERE clause constraints must be deferred until after outer join
2998 ** row elimination has completed, since WHERE clause constraints apply
2999 ** to the results of the OUTER JOIN. The following loop generates the
3000 ** appropriate WHERE clause constraint checks. tag-20220513a.
3001 */
3002 code_outer_join_constraints:
3003 for(pTerm=pWC->a, j=0; j<pWC->nBase; j++, pTerm++){
3004 testcase( pTerm->wtFlags & TERM_VIRTUAL );
3005 testcase( pTerm->wtFlags & TERM_CODED );
3006 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
3007 if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
3008 assert( pWInfo->untestedTerms );
3009 continue;
3010 }
3011 if( pTabItem->fg.jointype & JT_LTORJ ) continue;
3012 assert( pTerm->pExpr );
3013 sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
3014 pTerm->wtFlags |= TERM_CODED;
3015 }
3016 }
3017
3018#if WHERETRACE_ENABLED /* 0x4001 */
3019 if( sqlite3WhereTrace & 0x4000 ){
3020 sqlite3DebugPrintf("All WHERE-clause terms after coding level %d:\n",
3021 iLevel);
3022 sqlite3WhereClausePrint(pWC);
3023 }
3024 if( sqlite3WhereTrace & 0x1 ){
3025 sqlite3DebugPrintf("End Coding level %d: notReady=%llx\n",
3026 iLevel, (u64)pLevel->notReady);
3027 }
3028#endif
3029 return pLevel->notReady;
3030}
3031
3032/*
3033** Generate the code for the loop that finds all non-matched terms
3034** for a RIGHT JOIN.
3035*/
3036SQLITE_NOINLINE void sqlite3WhereRightJoinLoop(
3037 WhereInfo *pWInfo,
3038 int iLevel,
3039 WhereLevel *pLevel
3040){
3041 Parse *pParse = pWInfo->pParse;
3042 Vdbe *v = pParse->pVdbe;
3043 WhereRightJoin *pRJ = pLevel->pRJ;
3044 Expr *pSubWhere = 0;
3045 WhereClause *pWC = &pWInfo->sWC;
3046 WhereInfo *pSubWInfo;
3047 WhereLoop *pLoop = pLevel->pWLoop;
3048 SrcItem *pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
3049 SrcList *pFrom;
3050 union {
3051 SrcList sSrc;
3052 u8 fromSpace[SZ_SRCLIST_1];
3053 } uSrc;
3054 Bitmask mAll = 0;
3055 int k;
3056
3057 ExplainQueryPlan((pParse, 1, "RIGHT-JOIN %s", pTabItem->pSTab->zName));
3058 sqlite3VdbeNoJumpsOutsideSubrtn(v, pRJ->addrSubrtn, pRJ->endSubrtn,
3059 pRJ->regReturn);
3060 for(k=0; k<iLevel; k++){
3061 int iIdxCur;
3062 SrcItem *pRight;
3063 assert( pWInfo->a[k].pWLoop->iTab == pWInfo->a[k].iFrom );
3064 pRight = &pWInfo->pTabList->a[pWInfo->a[k].iFrom];
3065 mAll |= pWInfo->a[k].pWLoop->maskSelf;
3066 if( pRight->fg.viaCoroutine ){
3067 Subquery *pSubq;
3068 assert( pRight->fg.isSubquery && pRight->u4.pSubq!=0 );
3069 pSubq = pRight->u4.pSubq;
3070 assert( pSubq->pSelect!=0 && pSubq->pSelect->pEList!=0 );
3071 sqlite3VdbeAddOp3(
3072 v, OP_Null, 0, pSubq->regResult,
3073 pSubq->regResult + pSubq->pSelect->pEList->nExpr-1
3074 );
3075 }
3076 sqlite3VdbeAddOp1(v, OP_NullRow, pWInfo->a[k].iTabCur);
3077 iIdxCur = pWInfo->a[k].iIdxCur;
3078 if( iIdxCur ){
3079 sqlite3VdbeAddOp1(v, OP_NullRow, iIdxCur);
3080 }
3081 }
3082 if( (pTabItem->fg.jointype & JT_LTORJ)==0 ){
3083 mAll |= pLoop->maskSelf;
3084 for(k=0; k<pWC->nTerm; k++){
3085 WhereTerm *pTerm = &pWC->a[k];
3086 if( (pTerm->wtFlags & (TERM_VIRTUAL|TERM_SLICE))!=0
3087 && pTerm->eOperator!=WO_ROWVAL
3088 ){
3089 break;
3090 }
3091 if( pTerm->prereqAll & ~mAll ) continue;
3092 if( ExprHasProperty(pTerm->pExpr, EP_OuterON|EP_InnerON) ) continue;
3093 pSubWhere = sqlite3ExprAnd(pParse, pSubWhere,
3094 sqlite3ExprDup(pParse->db, pTerm->pExpr, 0));
3095 }
3096 }
3097 if( pLevel->iIdxCur ){
3098 /* pSubWhere may contain expressions that read from an index on the
3099 ** table on the RHS of the right join. All such expressions first test
3100 ** if the index is pointing at a NULL row, and if so, read from the
3101 ** table cursor instead. So ensure that the index cursor really is
3102 ** pointing at a NULL row here, so that no values are read from it during
3103 ** the scan of the RHS of the RIGHT join below. */
3104 sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
3105 }
3106 pFrom = &uSrc.sSrc;
3107 pFrom->nSrc = 1;
3108 pFrom->nAlloc = 1;
3109 memcpy(&pFrom->a[0], pTabItem, sizeof(SrcItem));
3110 pFrom->a[0].fg.jointype = 0;
3111 if( pParse->withinRJSubrtn >= 100 ){
3112 /* This limit --------------^^^
3113 ** is based on an historical assert(). It is not compile-time or
3114 ** run-time configurable. It could perhaps be raised as high as 254,
3115 ** but only an attack robot would ever do even 100 RIGHT JOINS within
3116 ** a single query, so we'll just leave it as it is. */
3117 sqlite3ErrorMsg(pParse, "too many RIGHT JOINs");
3118 return;
3119 }
3120 pParse->withinRJSubrtn++;
3121 pSubWInfo = sqlite3WhereBegin(pParse, pFrom, pSubWhere, 0, 0, 0,
3122 WHERE_RIGHT_JOIN, 0);
3123 if( pSubWInfo ){
3124 int iCur = pLevel->iTabCur; /* Table on RHS of RIGHT JOIN &*/
3125 int r = ++pParse->nMem; /* Register range to hold primary key */
3126 int nPk; /* Number of values in the primary key */
3127 int r2; /* Register holding record for primary key */
3128 int addrCont = sqlite3WhereContinueLabel(pSubWInfo);
3129 Table *pTab = pTabItem->pSTab; /* Table on RHS of RIGHT JOIN */
3130 if( HasRowid(pTab) ){
3131 sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, -1, r);
3132 nPk = 1;
3133 }else{
3134 int iPk;
3135 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
3136 nPk = pPk->nKeyCol;
3137 pParse->nMem += nPk - 1;
3138 for(iPk=0; iPk<nPk; iPk++){
3139 int iCol = pPk->aiColumn[iPk];
3140 sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol,r+iPk);
3141 }
3142 }
3143
3144 /* Generate code that checks to see if the current row of the RHS table
3145 ** has appeared in any prior output row. */
3146 if( pRJ->regBloom ){
3147 sqlite3VdbeAddOp4Int(v, OP_Filter, pRJ->regBloom,
3148 sqlite3VdbeCurrentAddr(v)+2, r, nPk);
3149 VdbeCoverage(v);
3150 }
3151 sqlite3VdbeAddOp4Int(v, OP_Found, pRJ->iMatch, addrCont, r, nPk);
3152 VdbeCoverage(v);
3153 r2 = sqlite3GetTempReg(pParse);
3154
3155 /* Generate code that inserts the PK of the RHS table into the
3156 ** pRH->iMatch index to indicate that the current row has appeared
3157 ** in the output set. */
3158 sqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, r2);
3159 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pRJ->iMatch, r2, r, nPk);
3160 sqlite3ReleaseTempReg(pParse, r2);
3161 if( pRJ->regBloom ){
3162 sqlite3VdbeAddOp4Int(v, OP_FilterAdd, pRJ->regBloom, 0, r, nPk);
3163 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
3164 }
3165
3166 /* Invoke the subroutine that actually puts the current RHS table row
3167 ** into the output set, with NULLs for the LHS. */
3168 sqlite3VdbeAddOp2(v, OP_Gosub, pRJ->regReturn, pRJ->addrSubrtn);
3169 sqlite3WhereEnd(pSubWInfo);
3170 }
3171 sqlite3ExprDelete(pParse->db, pSubWhere);
3172 ExplainQueryPlanPop(pParse);
3173 assert( pParse->withinRJSubrtn>0 );
3174 pParse->withinRJSubrtn--;
3175}