blob: 99ebfe1d4f1e152c2fc46e2fcf4a139c4cb58048 [file] [log] [blame]
drh6f82e852015-06-06 20:12:09 +00001/*
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** This routine is a helper for explainIndexRange() below
26**
27** pStr holds the text of an expression that we are building up one term
28** at a time. This routine adds a new term to the end of the expression.
29** Terms are separated by AND so add the "AND" text for second and subsequent
30** terms only.
31*/
32static void explainAppendTerm(
33 StrAccum *pStr, /* The text expression being built */
34 int iTerm, /* Index of this term. First is zero */
35 const char *zColumn, /* Name of the column */
36 const char *zOp /* Name of the operator */
37){
38 if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
39 sqlite3StrAccumAppendAll(pStr, zColumn);
40 sqlite3StrAccumAppend(pStr, zOp, 1);
41 sqlite3StrAccumAppend(pStr, "?", 1);
42}
43
44/*
45** Argument pLevel describes a strategy for scanning table pTab. This
46** function appends text to pStr that describes the subset of table
47** rows scanned by the strategy in the form of an SQL expression.
48**
49** For example, if the query:
50**
51** SELECT * FROM t1 WHERE a=1 AND b>2;
52**
53** is run and there is an index on (a, b), then this function returns a
54** string similar to:
55**
56** "a=? AND b>?"
57*/
58static void explainIndexRange(StrAccum *pStr, WhereLoop *pLoop, Table *pTab){
59 Index *pIndex = pLoop->u.btree.pIndex;
60 u16 nEq = pLoop->u.btree.nEq;
61 u16 nSkip = pLoop->nSkip;
62 int i, j;
63 Column *aCol = pTab->aCol;
64 i16 *aiColumn = pIndex->aiColumn;
65
66 if( nEq==0 && (pLoop->wsFlags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ) return;
67 sqlite3StrAccumAppend(pStr, " (", 2);
68 for(i=0; i<nEq; i++){
69 char *z = aiColumn[i] < 0 ? "rowid" : aCol[aiColumn[i]].zName;
70 if( i>=nSkip ){
71 explainAppendTerm(pStr, i, z, "=");
72 }else{
73 if( i ) sqlite3StrAccumAppend(pStr, " AND ", 5);
74 sqlite3XPrintf(pStr, 0, "ANY(%s)", z);
75 }
76 }
77
78 j = i;
79 if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
80 char *z = aiColumn[j] < 0 ? "rowid" : aCol[aiColumn[j]].zName;
81 explainAppendTerm(pStr, i++, z, ">");
82 }
83 if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
84 char *z = aiColumn[j] < 0 ? "rowid" : aCol[aiColumn[j]].zName;
85 explainAppendTerm(pStr, i, z, "<");
86 }
87 sqlite3StrAccumAppend(pStr, ")", 1);
88}
89
90/*
91** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
92** command, or if either SQLITE_DEBUG or SQLITE_ENABLE_STMT_SCANSTATUS was
93** defined at compile-time. If it is not a no-op, a single OP_Explain opcode
94** is added to the output to describe the table scan strategy in pLevel.
95**
96** If an OP_Explain opcode is added to the VM, its address is returned.
97** Otherwise, if no OP_Explain is coded, zero is returned.
98*/
99int sqlite3WhereExplainOneScan(
100 Parse *pParse, /* Parse context */
101 SrcList *pTabList, /* Table list this loop refers to */
102 WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
103 int iLevel, /* Value for "level" column of output */
104 int iFrom, /* Value for "from" column of output */
105 u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
106){
107 int ret = 0;
108#if !defined(SQLITE_DEBUG) && !defined(SQLITE_ENABLE_STMT_SCANSTATUS)
109 if( pParse->explain==2 )
110#endif
111 {
112 struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
113 Vdbe *v = pParse->pVdbe; /* VM being constructed */
114 sqlite3 *db = pParse->db; /* Database handle */
115 int iId = pParse->iSelectId; /* Select id (left-most output column) */
116 int isSearch; /* True for a SEARCH. False for SCAN. */
117 WhereLoop *pLoop; /* The controlling WhereLoop object */
118 u32 flags; /* Flags that describe this loop */
119 char *zMsg; /* Text to add to EQP output */
120 StrAccum str; /* EQP output string */
121 char zBuf[100]; /* Initial space for EQP output string */
122
123 pLoop = pLevel->pWLoop;
124 flags = pLoop->wsFlags;
125 if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return 0;
126
127 isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
128 || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
129 || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
130
131 sqlite3StrAccumInit(&str, db, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH);
132 sqlite3StrAccumAppendAll(&str, isSearch ? "SEARCH" : "SCAN");
133 if( pItem->pSelect ){
134 sqlite3XPrintf(&str, 0, " SUBQUERY %d", pItem->iSelectId);
135 }else{
136 sqlite3XPrintf(&str, 0, " TABLE %s", pItem->zName);
137 }
138
139 if( pItem->zAlias ){
140 sqlite3XPrintf(&str, 0, " AS %s", pItem->zAlias);
141 }
142 if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0 ){
143 const char *zFmt = 0;
144 Index *pIdx;
145
146 assert( pLoop->u.btree.pIndex!=0 );
147 pIdx = pLoop->u.btree.pIndex;
148 assert( !(flags&WHERE_AUTO_INDEX) || (flags&WHERE_IDX_ONLY) );
149 if( !HasRowid(pItem->pTab) && IsPrimaryKeyIndex(pIdx) ){
150 if( isSearch ){
151 zFmt = "PRIMARY KEY";
152 }
153 }else if( flags & WHERE_PARTIALIDX ){
154 zFmt = "AUTOMATIC PARTIAL COVERING INDEX";
155 }else if( flags & WHERE_AUTO_INDEX ){
156 zFmt = "AUTOMATIC COVERING INDEX";
157 }else if( flags & WHERE_IDX_ONLY ){
158 zFmt = "COVERING INDEX %s";
159 }else{
160 zFmt = "INDEX %s";
161 }
162 if( zFmt ){
163 sqlite3StrAccumAppend(&str, " USING ", 7);
164 sqlite3XPrintf(&str, 0, zFmt, pIdx->zName);
165 explainIndexRange(&str, pLoop, pItem->pTab);
166 }
167 }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
drhd37bea52015-09-02 15:37:50 +0000168 const char *zRangeOp;
drh6f82e852015-06-06 20:12:09 +0000169 if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
drhd37bea52015-09-02 15:37:50 +0000170 zRangeOp = "=";
drh6f82e852015-06-06 20:12:09 +0000171 }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
drhd37bea52015-09-02 15:37:50 +0000172 zRangeOp = ">? AND rowid<";
drh6f82e852015-06-06 20:12:09 +0000173 }else if( flags&WHERE_BTM_LIMIT ){
drhd37bea52015-09-02 15:37:50 +0000174 zRangeOp = ">";
drh6f82e852015-06-06 20:12:09 +0000175 }else{
176 assert( flags&WHERE_TOP_LIMIT);
drhd37bea52015-09-02 15:37:50 +0000177 zRangeOp = "<";
drh6f82e852015-06-06 20:12:09 +0000178 }
drhd37bea52015-09-02 15:37:50 +0000179 sqlite3XPrintf(&str, 0, " USING INTEGER PRIMARY KEY (rowid%s?)",zRangeOp);
drh6f82e852015-06-06 20:12:09 +0000180 }
181#ifndef SQLITE_OMIT_VIRTUALTABLE
182 else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
183 sqlite3XPrintf(&str, 0, " VIRTUAL TABLE INDEX %d:%s",
184 pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
185 }
186#endif
187#ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS
188 if( pLoop->nOut>=10 ){
189 sqlite3XPrintf(&str, 0, " (~%llu rows)", sqlite3LogEstToInt(pLoop->nOut));
190 }else{
191 sqlite3StrAccumAppend(&str, " (~1 row)", 9);
192 }
193#endif
194 zMsg = sqlite3StrAccumFinish(&str);
195 ret = sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg,P4_DYNAMIC);
196 }
197 return ret;
198}
199#endif /* SQLITE_OMIT_EXPLAIN */
200
201#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
202/*
203** Configure the VM passed as the first argument with an
204** sqlite3_stmt_scanstatus() entry corresponding to the scan used to
205** implement level pLvl. Argument pSrclist is a pointer to the FROM
206** clause that the scan reads data from.
207**
208** If argument addrExplain is not 0, it must be the address of an
209** OP_Explain instruction that describes the same loop.
210*/
211void sqlite3WhereAddScanStatus(
212 Vdbe *v, /* Vdbe to add scanstatus entry to */
213 SrcList *pSrclist, /* FROM clause pLvl reads data from */
214 WhereLevel *pLvl, /* Level to add scanstatus() entry for */
215 int addrExplain /* Address of OP_Explain (or 0) */
216){
217 const char *zObj = 0;
218 WhereLoop *pLoop = pLvl->pWLoop;
219 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 && pLoop->u.btree.pIndex!=0 ){
220 zObj = pLoop->u.btree.pIndex->zName;
221 }else{
222 zObj = pSrclist->a[pLvl->iFrom].zName;
223 }
224 sqlite3VdbeScanStatus(
225 v, addrExplain, pLvl->addrBody, pLvl->addrVisit, pLoop->nOut, zObj
226 );
227}
228#endif
229
230
231/*
232** Disable a term in the WHERE clause. Except, do not disable the term
233** if it controls a LEFT OUTER JOIN and it did not originate in the ON
234** or USING clause of that join.
235**
236** Consider the term t2.z='ok' in the following queries:
237**
238** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
239** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
240** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
241**
242** The t2.z='ok' is disabled in the in (2) because it originates
243** in the ON clause. The term is disabled in (3) because it is not part
244** of a LEFT OUTER JOIN. In (1), the term is not disabled.
245**
246** Disabling a term causes that term to not be tested in the inner loop
247** of the join. Disabling is an optimization. When terms are satisfied
248** by indices, we disable them to prevent redundant tests in the inner
249** loop. We would get the correct results if nothing were ever disabled,
250** but joins might run a little slower. The trick is to disable as much
251** as we can without disabling too much. If we disabled in (1), we'd get
252** the wrong answer. See ticket #813.
253**
254** If all the children of a term are disabled, then that term is also
255** automatically disabled. In this way, terms get disabled if derived
256** virtual terms are tested first. For example:
257**
258** x GLOB 'abc*' AND x>='abc' AND x<'acd'
259** \___________/ \______/ \_____/
260** parent child1 child2
261**
262** Only the parent term was in the original WHERE clause. The child1
263** and child2 terms were added by the LIKE optimization. If both of
264** the virtual child terms are valid, then testing of the parent can be
265** skipped.
266**
267** Usually the parent term is marked as TERM_CODED. But if the parent
268** term was originally TERM_LIKE, then the parent gets TERM_LIKECOND instead.
269** The TERM_LIKECOND marking indicates that the term should be coded inside
270** a conditional such that is only evaluated on the second pass of a
271** LIKE-optimization loop, when scanning BLOBs instead of strings.
272*/
273static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
274 int nLoop = 0;
275 while( pTerm
276 && (pTerm->wtFlags & TERM_CODED)==0
277 && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
278 && (pLevel->notReady & pTerm->prereqAll)==0
279 ){
280 if( nLoop && (pTerm->wtFlags & TERM_LIKE)!=0 ){
281 pTerm->wtFlags |= TERM_LIKECOND;
282 }else{
283 pTerm->wtFlags |= TERM_CODED;
284 }
285 if( pTerm->iParent<0 ) break;
286 pTerm = &pTerm->pWC->a[pTerm->iParent];
287 pTerm->nChild--;
288 if( pTerm->nChild!=0 ) break;
289 nLoop++;
290 }
291}
292
293/*
294** Code an OP_Affinity opcode to apply the column affinity string zAff
295** to the n registers starting at base.
296**
297** As an optimization, SQLITE_AFF_BLOB entries (which are no-ops) at the
298** beginning and end of zAff are ignored. If all entries in zAff are
299** SQLITE_AFF_BLOB, then no code gets generated.
300**
301** This routine makes its own copy of zAff so that the caller is free
302** to modify zAff after this routine returns.
303*/
304static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
305 Vdbe *v = pParse->pVdbe;
306 if( zAff==0 ){
307 assert( pParse->db->mallocFailed );
308 return;
309 }
310 assert( v!=0 );
311
312 /* Adjust base and n to skip over SQLITE_AFF_BLOB entries at the beginning
313 ** and end of the affinity string.
314 */
315 while( n>0 && zAff[0]==SQLITE_AFF_BLOB ){
316 n--;
317 base++;
318 zAff++;
319 }
320 while( n>1 && zAff[n-1]==SQLITE_AFF_BLOB ){
321 n--;
322 }
323
324 /* Code the OP_Affinity opcode if there is anything left to do. */
325 if( n>0 ){
326 sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
327 sqlite3VdbeChangeP4(v, -1, zAff, n);
328 sqlite3ExprCacheAffinityChange(pParse, base, n);
329 }
330}
331
332
333/*
334** Generate code for a single equality term of the WHERE clause. An equality
335** term can be either X=expr or X IN (...). pTerm is the term to be
336** coded.
337**
338** The current value for the constraint is left in register iReg.
339**
340** For a constraint of the form X=expr, the expression is evaluated and its
341** result is left on the stack. For constraints of the form X IN (...)
342** this routine sets up a loop that will iterate over all values of X.
343*/
344static int codeEqualityTerm(
345 Parse *pParse, /* The parsing context */
346 WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
347 WhereLevel *pLevel, /* The level of the FROM clause we are working on */
348 int iEq, /* Index of the equality term within this level */
349 int bRev, /* True for reverse-order IN operations */
350 int iTarget /* Attempt to leave results in this register */
351){
352 Expr *pX = pTerm->pExpr;
353 Vdbe *v = pParse->pVdbe;
354 int iReg; /* Register holding results */
355
356 assert( iTarget>0 );
357 if( pX->op==TK_EQ || pX->op==TK_IS ){
358 iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
359 }else if( pX->op==TK_ISNULL ){
360 iReg = iTarget;
361 sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
362#ifndef SQLITE_OMIT_SUBQUERY
363 }else{
364 int eType;
365 int iTab;
366 struct InLoop *pIn;
367 WhereLoop *pLoop = pLevel->pWLoop;
368
369 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
370 && pLoop->u.btree.pIndex!=0
371 && pLoop->u.btree.pIndex->aSortOrder[iEq]
372 ){
373 testcase( iEq==0 );
374 testcase( bRev );
375 bRev = !bRev;
376 }
377 assert( pX->op==TK_IN );
378 iReg = iTarget;
379 eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0);
380 if( eType==IN_INDEX_INDEX_DESC ){
381 testcase( bRev );
382 bRev = !bRev;
383 }
384 iTab = pX->iTable;
385 sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
386 VdbeCoverageIf(v, bRev);
387 VdbeCoverageIf(v, !bRev);
388 assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
389 pLoop->wsFlags |= WHERE_IN_ABLE;
390 if( pLevel->u.in.nIn==0 ){
391 pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
392 }
393 pLevel->u.in.nIn++;
394 pLevel->u.in.aInLoop =
395 sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
396 sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
397 pIn = pLevel->u.in.aInLoop;
398 if( pIn ){
399 pIn += pLevel->u.in.nIn - 1;
400 pIn->iCur = iTab;
401 if( eType==IN_INDEX_ROWID ){
402 pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
403 }else{
404 pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
405 }
406 pIn->eEndLoopOp = bRev ? OP_PrevIfOpen : OP_NextIfOpen;
407 sqlite3VdbeAddOp1(v, OP_IsNull, iReg); VdbeCoverage(v);
408 }else{
409 pLevel->u.in.nIn = 0;
410 }
411#endif
412 }
413 disableTerm(pLevel, pTerm);
414 return iReg;
415}
416
417/*
418** Generate code that will evaluate all == and IN constraints for an
419** index scan.
420**
421** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
422** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
423** The index has as many as three equality constraints, but in this
424** example, the third "c" value is an inequality. So only two
425** constraints are coded. This routine will generate code to evaluate
426** a==5 and b IN (1,2,3). The current values for a and b will be stored
427** in consecutive registers and the index of the first register is returned.
428**
429** In the example above nEq==2. But this subroutine works for any value
430** of nEq including 0. If nEq==0, this routine is nearly a no-op.
431** The only thing it does is allocate the pLevel->iMem memory cell and
432** compute the affinity string.
433**
434** The nExtraReg parameter is 0 or 1. It is 0 if all WHERE clause constraints
435** are == or IN and are covered by the nEq. nExtraReg is 1 if there is
436** an inequality constraint (such as the "c>=5 AND c<10" in the example) that
437** occurs after the nEq quality constraints.
438**
439** This routine allocates a range of nEq+nExtraReg memory cells and returns
440** the index of the first memory cell in that range. The code that
441** calls this routine will use that memory range to store keys for
442** start and termination conditions of the loop.
443** key value of the loop. If one or more IN operators appear, then
444** this routine allocates an additional nEq memory cells for internal
445** use.
446**
447** Before returning, *pzAff is set to point to a buffer containing a
448** copy of the column affinity string of the index allocated using
449** sqlite3DbMalloc(). Except, entries in the copy of the string associated
450** with equality constraints that use BLOB or NONE affinity are set to
451** SQLITE_AFF_BLOB. This is to deal with SQL such as the following:
452**
453** CREATE TABLE t1(a TEXT PRIMARY KEY, b);
454** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
455**
456** In the example above, the index on t1(a) has TEXT affinity. But since
457** the right hand side of the equality constraint (t2.b) has BLOB/NONE affinity,
458** no conversion should be attempted before using a t2.b value as part of
459** a key to search the index. Hence the first byte in the returned affinity
460** string in this example would be set to SQLITE_AFF_BLOB.
461*/
462static int codeAllEqualityTerms(
463 Parse *pParse, /* Parsing context */
464 WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
465 int bRev, /* Reverse the order of IN operators */
466 int nExtraReg, /* Number of extra registers to allocate */
467 char **pzAff /* OUT: Set to point to affinity string */
468){
469 u16 nEq; /* The number of == or IN constraints to code */
470 u16 nSkip; /* Number of left-most columns to skip */
471 Vdbe *v = pParse->pVdbe; /* The vm under construction */
472 Index *pIdx; /* The index being used for this loop */
473 WhereTerm *pTerm; /* A single constraint term */
474 WhereLoop *pLoop; /* The WhereLoop object */
475 int j; /* Loop counter */
476 int regBase; /* Base register */
477 int nReg; /* Number of registers to allocate */
478 char *zAff; /* Affinity string to return */
479
480 /* This module is only called on query plans that use an index. */
481 pLoop = pLevel->pWLoop;
482 assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
483 nEq = pLoop->u.btree.nEq;
484 nSkip = pLoop->nSkip;
485 pIdx = pLoop->u.btree.pIndex;
486 assert( pIdx!=0 );
487
488 /* Figure out how many memory cells we will need then allocate them.
489 */
490 regBase = pParse->nMem + 1;
491 nReg = pLoop->u.btree.nEq + nExtraReg;
492 pParse->nMem += nReg;
493
drhe9107692015-08-25 19:20:04 +0000494 zAff = sqlite3DbStrDup(pParse->db,sqlite3IndexAffinityStr(pParse->db,pIdx));
drh6f82e852015-06-06 20:12:09 +0000495 if( !zAff ){
496 pParse->db->mallocFailed = 1;
497 }
498
499 if( nSkip ){
500 int iIdxCur = pLevel->iIdxCur;
501 sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur);
502 VdbeCoverageIf(v, bRev==0);
503 VdbeCoverageIf(v, bRev!=0);
504 VdbeComment((v, "begin skip-scan on %s", pIdx->zName));
505 j = sqlite3VdbeAddOp0(v, OP_Goto);
506 pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT),
507 iIdxCur, 0, regBase, nSkip);
508 VdbeCoverageIf(v, bRev==0);
509 VdbeCoverageIf(v, bRev!=0);
510 sqlite3VdbeJumpHere(v, j);
511 for(j=0; j<nSkip; j++){
512 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, j, regBase+j);
513 assert( pIdx->aiColumn[j]>=0 );
514 VdbeComment((v, "%s", pIdx->pTable->aCol[pIdx->aiColumn[j]].zName));
515 }
516 }
517
518 /* Evaluate the equality constraints
519 */
520 assert( zAff==0 || (int)strlen(zAff)>=nEq );
521 for(j=nSkip; j<nEq; j++){
522 int r1;
523 pTerm = pLoop->aLTerm[j];
524 assert( pTerm!=0 );
525 /* The following testcase is true for indices with redundant columns.
526 ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
527 testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
528 testcase( pTerm->wtFlags & TERM_VIRTUAL );
529 r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
530 if( r1!=regBase+j ){
531 if( nReg==1 ){
532 sqlite3ReleaseTempReg(pParse, regBase);
533 regBase = r1;
534 }else{
535 sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
536 }
537 }
538 testcase( pTerm->eOperator & WO_ISNULL );
539 testcase( pTerm->eOperator & WO_IN );
540 if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
541 Expr *pRight = pTerm->pExpr->pRight;
542 if( (pTerm->wtFlags & TERM_IS)==0 && sqlite3ExprCanBeNull(pRight) ){
543 sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk);
544 VdbeCoverage(v);
545 }
546 if( zAff ){
547 if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_BLOB ){
548 zAff[j] = SQLITE_AFF_BLOB;
549 }
550 if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
551 zAff[j] = SQLITE_AFF_BLOB;
552 }
553 }
554 }
555 }
556 *pzAff = zAff;
557 return regBase;
558}
559
560/*
561** If the most recently coded instruction is a constant range contraint
562** that originated from the LIKE optimization, then change the P3 to be
563** pLoop->iLikeRepCntr and set P5.
564**
565** The LIKE optimization trys to evaluate "x LIKE 'abc%'" as a range
566** expression: "x>='ABC' AND x<'abd'". But this requires that the range
567** scan loop run twice, once for strings and a second time for BLOBs.
568** The OP_String opcodes on the second pass convert the upper and lower
569** bound string contants to blobs. This routine makes the necessary changes
570** to the OP_String opcodes for that to happen.
571*/
572static void whereLikeOptimizationStringFixup(
573 Vdbe *v, /* prepared statement under construction */
574 WhereLevel *pLevel, /* The loop that contains the LIKE operator */
575 WhereTerm *pTerm /* The upper or lower bound just coded */
576){
577 if( pTerm->wtFlags & TERM_LIKEOPT ){
578 VdbeOp *pOp;
579 assert( pLevel->iLikeRepCntr>0 );
580 pOp = sqlite3VdbeGetOp(v, -1);
581 assert( pOp!=0 );
582 assert( pOp->opcode==OP_String8
583 || pTerm->pWC->pWInfo->pParse->db->mallocFailed );
584 pOp->p3 = pLevel->iLikeRepCntr;
585 pOp->p5 = 1;
586 }
587}
588
589
590/*
591** Generate code for the start of the iLevel-th loop in the WHERE clause
592** implementation described by pWInfo.
593*/
594Bitmask sqlite3WhereCodeOneLoopStart(
595 WhereInfo *pWInfo, /* Complete information about the WHERE clause */
596 int iLevel, /* Which level of pWInfo->a[] should be coded */
597 Bitmask notReady /* Which tables are currently available */
598){
599 int j, k; /* Loop counters */
600 int iCur; /* The VDBE cursor for the table */
601 int addrNxt; /* Where to jump to continue with the next IN case */
602 int omitTable; /* True if we use the index only */
603 int bRev; /* True if we need to scan in reverse order */
604 WhereLevel *pLevel; /* The where level to be coded */
605 WhereLoop *pLoop; /* The WhereLoop object being coded */
606 WhereClause *pWC; /* Decomposition of the entire WHERE clause */
607 WhereTerm *pTerm; /* A WHERE clause term */
608 Parse *pParse; /* Parsing context */
609 sqlite3 *db; /* Database connection */
610 Vdbe *v; /* The prepared stmt under constructions */
611 struct SrcList_item *pTabItem; /* FROM clause term being coded */
612 int addrBrk; /* Jump here to break out of the loop */
613 int addrCont; /* Jump here to continue with next cycle */
614 int iRowidReg = 0; /* Rowid is stored in this register, if not zero */
615 int iReleaseReg = 0; /* Temp register to free before returning */
616
617 pParse = pWInfo->pParse;
618 v = pParse->pVdbe;
619 pWC = &pWInfo->sWC;
620 db = pParse->db;
621 pLevel = &pWInfo->a[iLevel];
622 pLoop = pLevel->pWLoop;
623 pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
624 iCur = pTabItem->iCursor;
625 pLevel->notReady = notReady & ~sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur);
626 bRev = (pWInfo->revMask>>iLevel)&1;
627 omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
628 && (pWInfo->wctrlFlags & WHERE_FORCE_TABLE)==0;
629 VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName));
630
631 /* Create labels for the "break" and "continue" instructions
632 ** for the current loop. Jump to addrBrk to break out of a loop.
633 ** Jump to cont to go immediately to the next iteration of the
634 ** loop.
635 **
636 ** When there is an IN operator, we also have a "addrNxt" label that
637 ** means to continue with the next IN value combination. When
638 ** there are no IN operators in the constraints, the "addrNxt" label
639 ** is the same as "addrBrk".
640 */
641 addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
642 addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
643
644 /* If this is the right table of a LEFT OUTER JOIN, allocate and
645 ** initialize a memory cell that records if this table matches any
646 ** row of the left table of the join.
647 */
drh8a48b9c2015-08-19 15:20:00 +0000648 if( pLevel->iFrom>0 && (pTabItem[0].fg.jointype & JT_LEFT)!=0 ){
drh6f82e852015-06-06 20:12:09 +0000649 pLevel->iLeftJoin = ++pParse->nMem;
650 sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
651 VdbeComment((v, "init LEFT JOIN no-match flag"));
652 }
653
654 /* Special case of a FROM clause subquery implemented as a co-routine */
drh8a48b9c2015-08-19 15:20:00 +0000655 if( pTabItem->fg.viaCoroutine ){
drh6f82e852015-06-06 20:12:09 +0000656 int regYield = pTabItem->regReturn;
657 sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
658 pLevel->p2 = sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk);
659 VdbeCoverage(v);
660 VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
661 pLevel->op = OP_Goto;
662 }else
663
664#ifndef SQLITE_OMIT_VIRTUALTABLE
665 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
666 /* Case 1: The table is a virtual-table. Use the VFilter and VNext
667 ** to access the data.
668 */
669 int iReg; /* P3 Value for OP_VFilter */
670 int addrNotFound;
671 int nConstraint = pLoop->nLTerm;
672
673 sqlite3ExprCachePush(pParse);
674 iReg = sqlite3GetTempRange(pParse, nConstraint+2);
675 addrNotFound = pLevel->addrBrk;
676 for(j=0; j<nConstraint; j++){
677 int iTarget = iReg+j+2;
678 pTerm = pLoop->aLTerm[j];
679 if( pTerm==0 ) continue;
680 if( pTerm->eOperator & WO_IN ){
681 codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
682 addrNotFound = pLevel->addrNxt;
683 }else{
684 sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget);
685 }
686 }
687 sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
688 sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
689 sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
690 pLoop->u.vtab.idxStr,
691 pLoop->u.vtab.needFree ? P4_MPRINTF : P4_STATIC);
692 VdbeCoverage(v);
693 pLoop->u.vtab.needFree = 0;
694 for(j=0; j<nConstraint && j<16; j++){
695 if( (pLoop->u.vtab.omitMask>>j)&1 ){
696 disableTerm(pLevel, pLoop->aLTerm[j]);
697 }
698 }
699 pLevel->op = OP_VNext;
700 pLevel->p1 = iCur;
701 pLevel->p2 = sqlite3VdbeCurrentAddr(v);
702 sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
703 sqlite3ExprCachePop(pParse);
704 }else
705#endif /* SQLITE_OMIT_VIRTUALTABLE */
706
707 if( (pLoop->wsFlags & WHERE_IPK)!=0
708 && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
709 ){
710 /* Case 2: We can directly reference a single row using an
711 ** equality comparison against the ROWID field. Or
712 ** we reference multiple rows using a "rowid IN (...)"
713 ** construct.
714 */
715 assert( pLoop->u.btree.nEq==1 );
716 pTerm = pLoop->aLTerm[0];
717 assert( pTerm!=0 );
718 assert( pTerm->pExpr!=0 );
719 assert( omitTable==0 );
720 testcase( pTerm->wtFlags & TERM_VIRTUAL );
721 iReleaseReg = ++pParse->nMem;
722 iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
723 if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg);
724 addrNxt = pLevel->addrNxt;
725 sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt); VdbeCoverage(v);
726 sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
727 VdbeCoverage(v);
728 sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
729 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
730 VdbeComment((v, "pk"));
731 pLevel->op = OP_Noop;
732 }else if( (pLoop->wsFlags & WHERE_IPK)!=0
733 && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
734 ){
735 /* Case 3: We have an inequality comparison against the ROWID field.
736 */
737 int testOp = OP_Noop;
738 int start;
739 int memEndValue = 0;
740 WhereTerm *pStart, *pEnd;
741
742 assert( omitTable==0 );
743 j = 0;
744 pStart = pEnd = 0;
745 if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
746 if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
747 assert( pStart!=0 || pEnd!=0 );
748 if( bRev ){
749 pTerm = pStart;
750 pStart = pEnd;
751 pEnd = pTerm;
752 }
753 if( pStart ){
754 Expr *pX; /* The expression that defines the start bound */
755 int r1, rTemp; /* Registers for holding the start boundary */
756
757 /* The following constant maps TK_xx codes into corresponding
758 ** seek opcodes. It depends on a particular ordering of TK_xx
759 */
760 const u8 aMoveOp[] = {
761 /* TK_GT */ OP_SeekGT,
762 /* TK_LE */ OP_SeekLE,
763 /* TK_LT */ OP_SeekLT,
764 /* TK_GE */ OP_SeekGE
765 };
766 assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */
767 assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */
768 assert( TK_GE==TK_GT+3 ); /* ... is correcct. */
769
770 assert( (pStart->wtFlags & TERM_VNULL)==0 );
771 testcase( pStart->wtFlags & TERM_VIRTUAL );
772 pX = pStart->pExpr;
773 assert( pX!=0 );
774 testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
775 r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
776 sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
777 VdbeComment((v, "pk"));
778 VdbeCoverageIf(v, pX->op==TK_GT);
779 VdbeCoverageIf(v, pX->op==TK_LE);
780 VdbeCoverageIf(v, pX->op==TK_LT);
781 VdbeCoverageIf(v, pX->op==TK_GE);
782 sqlite3ExprCacheAffinityChange(pParse, r1, 1);
783 sqlite3ReleaseTempReg(pParse, rTemp);
784 disableTerm(pLevel, pStart);
785 }else{
786 sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
787 VdbeCoverageIf(v, bRev==0);
788 VdbeCoverageIf(v, bRev!=0);
789 }
790 if( pEnd ){
791 Expr *pX;
792 pX = pEnd->pExpr;
793 assert( pX!=0 );
794 assert( (pEnd->wtFlags & TERM_VNULL)==0 );
795 testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
796 testcase( pEnd->wtFlags & TERM_VIRTUAL );
797 memEndValue = ++pParse->nMem;
798 sqlite3ExprCode(pParse, pX->pRight, memEndValue);
799 if( pX->op==TK_LT || pX->op==TK_GT ){
800 testOp = bRev ? OP_Le : OP_Ge;
801 }else{
802 testOp = bRev ? OP_Lt : OP_Gt;
803 }
804 disableTerm(pLevel, pEnd);
805 }
806 start = sqlite3VdbeCurrentAddr(v);
807 pLevel->op = bRev ? OP_Prev : OP_Next;
808 pLevel->p1 = iCur;
809 pLevel->p2 = start;
810 assert( pLevel->p5==0 );
811 if( testOp!=OP_Noop ){
812 iRowidReg = ++pParse->nMem;
813 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
814 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
815 sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
816 VdbeCoverageIf(v, testOp==OP_Le);
817 VdbeCoverageIf(v, testOp==OP_Lt);
818 VdbeCoverageIf(v, testOp==OP_Ge);
819 VdbeCoverageIf(v, testOp==OP_Gt);
820 sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
821 }
822 }else if( pLoop->wsFlags & WHERE_INDEXED ){
823 /* Case 4: A scan using an index.
824 **
825 ** The WHERE clause may contain zero or more equality
826 ** terms ("==" or "IN" operators) that refer to the N
827 ** left-most columns of the index. It may also contain
828 ** inequality constraints (>, <, >= or <=) on the indexed
829 ** column that immediately follows the N equalities. Only
830 ** the right-most column can be an inequality - the rest must
831 ** use the "==" and "IN" operators. For example, if the
832 ** index is on (x,y,z), then the following clauses are all
833 ** optimized:
834 **
835 ** x=5
836 ** x=5 AND y=10
837 ** x=5 AND y<10
838 ** x=5 AND y>5 AND y<10
839 ** x=5 AND y=5 AND z<=10
840 **
841 ** The z<10 term of the following cannot be used, only
842 ** the x=5 term:
843 **
844 ** x=5 AND z<10
845 **
846 ** N may be zero if there are inequality constraints.
847 ** If there are no inequality constraints, then N is at
848 ** least one.
849 **
850 ** This case is also used when there are no WHERE clause
851 ** constraints but an index is selected anyway, in order
852 ** to force the output order to conform to an ORDER BY.
853 */
854 static const u8 aStartOp[] = {
855 0,
856 0,
857 OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */
858 OP_Last, /* 3: (!start_constraints && startEq && bRev) */
859 OP_SeekGT, /* 4: (start_constraints && !startEq && !bRev) */
860 OP_SeekLT, /* 5: (start_constraints && !startEq && bRev) */
861 OP_SeekGE, /* 6: (start_constraints && startEq && !bRev) */
862 OP_SeekLE /* 7: (start_constraints && startEq && bRev) */
863 };
864 static const u8 aEndOp[] = {
865 OP_IdxGE, /* 0: (end_constraints && !bRev && !endEq) */
866 OP_IdxGT, /* 1: (end_constraints && !bRev && endEq) */
867 OP_IdxLE, /* 2: (end_constraints && bRev && !endEq) */
868 OP_IdxLT, /* 3: (end_constraints && bRev && endEq) */
869 };
870 u16 nEq = pLoop->u.btree.nEq; /* Number of == or IN terms */
871 int regBase; /* Base register holding constraint values */
872 WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */
873 WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */
874 int startEq; /* True if range start uses ==, >= or <= */
875 int endEq; /* True if range end uses ==, >= or <= */
876 int start_constraints; /* Start of range is constrained */
877 int nConstraint; /* Number of constraint terms */
878 Index *pIdx; /* The index we will be using */
879 int iIdxCur; /* The VDBE cursor for the index */
880 int nExtraReg = 0; /* Number of extra registers needed */
881 int op; /* Instruction opcode */
882 char *zStartAff; /* Affinity for start of range constraint */
883 char cEndAff = 0; /* Affinity for end of range constraint */
884 u8 bSeekPastNull = 0; /* True to seek past initial nulls */
885 u8 bStopAtNull = 0; /* Add condition to terminate at NULLs */
886
887 pIdx = pLoop->u.btree.pIndex;
888 iIdxCur = pLevel->iIdxCur;
889 assert( nEq>=pLoop->nSkip );
890
891 /* If this loop satisfies a sort order (pOrderBy) request that
892 ** was passed to this function to implement a "SELECT min(x) ..."
893 ** query, then the caller will only allow the loop to run for
894 ** a single iteration. This means that the first row returned
895 ** should not have a NULL value stored in 'x'. If column 'x' is
896 ** the first one after the nEq equality constraints in the index,
897 ** this requires some special handling.
898 */
899 assert( pWInfo->pOrderBy==0
900 || pWInfo->pOrderBy->nExpr==1
901 || (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0 );
902 if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
903 && pWInfo->nOBSat>0
904 && (pIdx->nKeyCol>nEq)
905 ){
906 assert( pLoop->nSkip==0 );
907 bSeekPastNull = 1;
908 nExtraReg = 1;
909 }
910
911 /* Find any inequality constraint terms for the start and end
912 ** of the range.
913 */
914 j = nEq;
915 if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
916 pRangeStart = pLoop->aLTerm[j++];
917 nExtraReg = 1;
918 /* Like optimization range constraints always occur in pairs */
919 assert( (pRangeStart->wtFlags & TERM_LIKEOPT)==0 ||
920 (pLoop->wsFlags & WHERE_TOP_LIMIT)!=0 );
921 }
922 if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
923 pRangeEnd = pLoop->aLTerm[j++];
924 nExtraReg = 1;
925 if( (pRangeEnd->wtFlags & TERM_LIKEOPT)!=0 ){
926 assert( pRangeStart!=0 ); /* LIKE opt constraints */
927 assert( pRangeStart->wtFlags & TERM_LIKEOPT ); /* occur in pairs */
928 pLevel->iLikeRepCntr = ++pParse->nMem;
929 testcase( bRev );
930 testcase( pIdx->aSortOrder[nEq]==SQLITE_SO_DESC );
931 sqlite3VdbeAddOp2(v, OP_Integer,
932 bRev ^ (pIdx->aSortOrder[nEq]==SQLITE_SO_DESC),
933 pLevel->iLikeRepCntr);
934 VdbeComment((v, "LIKE loop counter"));
935 pLevel->addrLikeRep = sqlite3VdbeCurrentAddr(v);
936 }
937 if( pRangeStart==0
938 && (j = pIdx->aiColumn[nEq])>=0
939 && pIdx->pTable->aCol[j].notNull==0
940 ){
941 bSeekPastNull = 1;
942 }
943 }
944 assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 );
945
946 /* Generate code to evaluate all constraint terms using == or IN
947 ** and store the values of those terms in an array of registers
948 ** starting at regBase.
949 */
950 regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
951 assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq );
952 if( zStartAff ) cEndAff = zStartAff[nEq];
953 addrNxt = pLevel->addrNxt;
954
955 /* If we are doing a reverse order scan on an ascending index, or
956 ** a forward order scan on a descending index, interchange the
957 ** start and end terms (pRangeStart and pRangeEnd).
958 */
959 if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
960 || (bRev && pIdx->nKeyCol==nEq)
961 ){
962 SWAP(WhereTerm *, pRangeEnd, pRangeStart);
963 SWAP(u8, bSeekPastNull, bStopAtNull);
964 }
965
966 testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
967 testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
968 testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
969 testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
970 startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
971 endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
972 start_constraints = pRangeStart || nEq>0;
973
974 /* Seek the index cursor to the start of the range. */
975 nConstraint = nEq;
976 if( pRangeStart ){
977 Expr *pRight = pRangeStart->pExpr->pRight;
978 sqlite3ExprCode(pParse, pRight, regBase+nEq);
979 whereLikeOptimizationStringFixup(v, pLevel, pRangeStart);
980 if( (pRangeStart->wtFlags & TERM_VNULL)==0
981 && sqlite3ExprCanBeNull(pRight)
982 ){
983 sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
984 VdbeCoverage(v);
985 }
986 if( zStartAff ){
987 if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_BLOB){
988 /* Since the comparison is to be performed with no conversions
989 ** applied to the operands, set the affinity to apply to pRight to
990 ** SQLITE_AFF_BLOB. */
991 zStartAff[nEq] = SQLITE_AFF_BLOB;
992 }
993 if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
994 zStartAff[nEq] = SQLITE_AFF_BLOB;
995 }
996 }
997 nConstraint++;
998 testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
999 }else if( bSeekPastNull ){
1000 sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
1001 nConstraint++;
1002 startEq = 0;
1003 start_constraints = 1;
1004 }
1005 codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff);
1006 op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
1007 assert( op!=0 );
1008 sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
1009 VdbeCoverage(v);
1010 VdbeCoverageIf(v, op==OP_Rewind); testcase( op==OP_Rewind );
1011 VdbeCoverageIf(v, op==OP_Last); testcase( op==OP_Last );
1012 VdbeCoverageIf(v, op==OP_SeekGT); testcase( op==OP_SeekGT );
1013 VdbeCoverageIf(v, op==OP_SeekGE); testcase( op==OP_SeekGE );
1014 VdbeCoverageIf(v, op==OP_SeekLE); testcase( op==OP_SeekLE );
1015 VdbeCoverageIf(v, op==OP_SeekLT); testcase( op==OP_SeekLT );
1016
1017 /* Load the value for the inequality constraint at the end of the
1018 ** range (if any).
1019 */
1020 nConstraint = nEq;
1021 if( pRangeEnd ){
1022 Expr *pRight = pRangeEnd->pExpr->pRight;
1023 sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
1024 sqlite3ExprCode(pParse, pRight, regBase+nEq);
1025 whereLikeOptimizationStringFixup(v, pLevel, pRangeEnd);
1026 if( (pRangeEnd->wtFlags & TERM_VNULL)==0
1027 && sqlite3ExprCanBeNull(pRight)
1028 ){
1029 sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
1030 VdbeCoverage(v);
1031 }
1032 if( sqlite3CompareAffinity(pRight, cEndAff)!=SQLITE_AFF_BLOB
1033 && !sqlite3ExprNeedsNoAffinityChange(pRight, cEndAff)
1034 ){
1035 codeApplyAffinity(pParse, regBase+nEq, 1, &cEndAff);
1036 }
1037 nConstraint++;
1038 testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
1039 }else if( bStopAtNull ){
1040 sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
1041 endEq = 0;
1042 nConstraint++;
1043 }
1044 sqlite3DbFree(db, zStartAff);
1045
1046 /* Top of the loop body */
1047 pLevel->p2 = sqlite3VdbeCurrentAddr(v);
1048
1049 /* Check if the index cursor is past the end of the range. */
1050 if( nConstraint ){
1051 op = aEndOp[bRev*2 + endEq];
1052 sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
1053 testcase( op==OP_IdxGT ); VdbeCoverageIf(v, op==OP_IdxGT );
1054 testcase( op==OP_IdxGE ); VdbeCoverageIf(v, op==OP_IdxGE );
1055 testcase( op==OP_IdxLT ); VdbeCoverageIf(v, op==OP_IdxLT );
1056 testcase( op==OP_IdxLE ); VdbeCoverageIf(v, op==OP_IdxLE );
1057 }
1058
1059 /* Seek the table cursor, if required */
1060 disableTerm(pLevel, pRangeStart);
1061 disableTerm(pLevel, pRangeEnd);
1062 if( omitTable ){
1063 /* pIdx is a covering index. No need to access the main table. */
1064 }else if( HasRowid(pIdx->pTable) ){
1065 iRowidReg = ++pParse->nMem;
1066 sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
1067 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
1068 sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg); /* Deferred seek */
1069 }else if( iCur!=iIdxCur ){
1070 Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
1071 iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol);
1072 for(j=0; j<pPk->nKeyCol; j++){
1073 k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
1074 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j);
1075 }
1076 sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont,
1077 iRowidReg, pPk->nKeyCol); VdbeCoverage(v);
1078 }
1079
1080 /* Record the instruction used to terminate the loop. Disable
1081 ** WHERE clause terms made redundant by the index range scan.
1082 */
1083 if( pLoop->wsFlags & WHERE_ONEROW ){
1084 pLevel->op = OP_Noop;
1085 }else if( bRev ){
1086 pLevel->op = OP_Prev;
1087 }else{
1088 pLevel->op = OP_Next;
1089 }
1090 pLevel->p1 = iIdxCur;
1091 pLevel->p3 = (pLoop->wsFlags&WHERE_UNQ_WANTED)!=0 ? 1:0;
1092 if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
1093 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
1094 }else{
1095 assert( pLevel->p5==0 );
1096 }
1097 }else
1098
1099#ifndef SQLITE_OMIT_OR_OPTIMIZATION
1100 if( pLoop->wsFlags & WHERE_MULTI_OR ){
1101 /* Case 5: Two or more separately indexed terms connected by OR
1102 **
1103 ** Example:
1104 **
1105 ** CREATE TABLE t1(a,b,c,d);
1106 ** CREATE INDEX i1 ON t1(a);
1107 ** CREATE INDEX i2 ON t1(b);
1108 ** CREATE INDEX i3 ON t1(c);
1109 **
1110 ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
1111 **
1112 ** In the example, there are three indexed terms connected by OR.
1113 ** The top of the loop looks like this:
1114 **
1115 ** Null 1 # Zero the rowset in reg 1
1116 **
1117 ** Then, for each indexed term, the following. The arguments to
1118 ** RowSetTest are such that the rowid of the current row is inserted
1119 ** into the RowSet. If it is already present, control skips the
1120 ** Gosub opcode and jumps straight to the code generated by WhereEnd().
1121 **
1122 ** sqlite3WhereBegin(<term>)
1123 ** RowSetTest # Insert rowid into rowset
1124 ** Gosub 2 A
1125 ** sqlite3WhereEnd()
1126 **
1127 ** Following the above, code to terminate the loop. Label A, the target
1128 ** of the Gosub above, jumps to the instruction right after the Goto.
1129 **
1130 ** Null 1 # Zero the rowset in reg 1
1131 ** Goto B # The loop is finished.
1132 **
1133 ** A: <loop body> # Return data, whatever.
1134 **
1135 ** Return 2 # Jump back to the Gosub
1136 **
1137 ** B: <after the loop>
1138 **
1139 ** Added 2014-05-26: If the table is a WITHOUT ROWID table, then
1140 ** use an ephemeral index instead of a RowSet to record the primary
1141 ** keys of the rows we have already seen.
1142 **
1143 */
1144 WhereClause *pOrWc; /* The OR-clause broken out into subterms */
1145 SrcList *pOrTab; /* Shortened table list or OR-clause generation */
1146 Index *pCov = 0; /* Potential covering index (or NULL) */
1147 int iCovCur = pParse->nTab++; /* Cursor used for index scans (if any) */
1148
1149 int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */
1150 int regRowset = 0; /* Register for RowSet object */
1151 int regRowid = 0; /* Register holding rowid */
1152 int iLoopBody = sqlite3VdbeMakeLabel(v); /* Start of loop body */
1153 int iRetInit; /* Address of regReturn init */
1154 int untestedTerms = 0; /* Some terms not completely tested */
1155 int ii; /* Loop counter */
1156 u16 wctrlFlags; /* Flags for sub-WHERE clause */
1157 Expr *pAndExpr = 0; /* An ".. AND (...)" expression */
1158 Table *pTab = pTabItem->pTab;
1159
1160 pTerm = pLoop->aLTerm[0];
1161 assert( pTerm!=0 );
1162 assert( pTerm->eOperator & WO_OR );
1163 assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
1164 pOrWc = &pTerm->u.pOrInfo->wc;
1165 pLevel->op = OP_Return;
1166 pLevel->p1 = regReturn;
1167
1168 /* Set up a new SrcList in pOrTab containing the table being scanned
1169 ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
1170 ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
1171 */
1172 if( pWInfo->nLevel>1 ){
1173 int nNotReady; /* The number of notReady tables */
1174 struct SrcList_item *origSrc; /* Original list of tables */
1175 nNotReady = pWInfo->nLevel - iLevel - 1;
1176 pOrTab = sqlite3StackAllocRaw(db,
1177 sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
1178 if( pOrTab==0 ) return notReady;
1179 pOrTab->nAlloc = (u8)(nNotReady + 1);
1180 pOrTab->nSrc = pOrTab->nAlloc;
1181 memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
1182 origSrc = pWInfo->pTabList->a;
1183 for(k=1; k<=nNotReady; k++){
1184 memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
1185 }
1186 }else{
1187 pOrTab = pWInfo->pTabList;
1188 }
1189
1190 /* Initialize the rowset register to contain NULL. An SQL NULL is
1191 ** equivalent to an empty rowset. Or, create an ephemeral index
1192 ** capable of holding primary keys in the case of a WITHOUT ROWID.
1193 **
1194 ** Also initialize regReturn to contain the address of the instruction
1195 ** immediately following the OP_Return at the bottom of the loop. This
1196 ** is required in a few obscure LEFT JOIN cases where control jumps
1197 ** over the top of the loop into the body of it. In this case the
1198 ** correct response for the end-of-loop code (the OP_Return) is to
1199 ** fall through to the next instruction, just as an OP_Next does if
1200 ** called on an uninitialized cursor.
1201 */
1202 if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
1203 if( HasRowid(pTab) ){
1204 regRowset = ++pParse->nMem;
1205 sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
1206 }else{
1207 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
1208 regRowset = pParse->nTab++;
1209 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, regRowset, pPk->nKeyCol);
1210 sqlite3VdbeSetP4KeyInfo(pParse, pPk);
1211 }
1212 regRowid = ++pParse->nMem;
1213 }
1214 iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
1215
1216 /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y
1217 ** Then for every term xN, evaluate as the subexpression: xN AND z
1218 ** That way, terms in y that are factored into the disjunction will
1219 ** be picked up by the recursive calls to sqlite3WhereBegin() below.
1220 **
1221 ** Actually, each subexpression is converted to "xN AND w" where w is
1222 ** the "interesting" terms of z - terms that did not originate in the
1223 ** ON or USING clause of a LEFT JOIN, and terms that are usable as
1224 ** indices.
1225 **
1226 ** This optimization also only applies if the (x1 OR x2 OR ...) term
1227 ** is not contained in the ON clause of a LEFT JOIN.
1228 ** See ticket http://www.sqlite.org/src/info/f2369304e4
1229 */
1230 if( pWC->nTerm>1 ){
1231 int iTerm;
1232 for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
1233 Expr *pExpr = pWC->a[iTerm].pExpr;
1234 if( &pWC->a[iTerm] == pTerm ) continue;
1235 if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
1236 if( (pWC->a[iTerm].wtFlags & TERM_VIRTUAL)!=0 ) continue;
1237 if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
1238 testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO );
1239 pExpr = sqlite3ExprDup(db, pExpr, 0);
1240 pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr);
1241 }
1242 if( pAndExpr ){
1243 pAndExpr = sqlite3PExpr(pParse, TK_AND, 0, pAndExpr, 0);
1244 }
1245 }
1246
1247 /* Run a separate WHERE clause for each term of the OR clause. After
1248 ** eliminating duplicates from other WHERE clauses, the action for each
1249 ** sub-WHERE clause is to to invoke the main loop body as a subroutine.
1250 */
1251 wctrlFlags = WHERE_OMIT_OPEN_CLOSE
1252 | WHERE_FORCE_TABLE
1253 | WHERE_ONETABLE_ONLY
1254 | WHERE_NO_AUTOINDEX;
1255 for(ii=0; ii<pOrWc->nTerm; ii++){
1256 WhereTerm *pOrTerm = &pOrWc->a[ii];
1257 if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
1258 WhereInfo *pSubWInfo; /* Info for single OR-term scan */
1259 Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */
1260 int j1 = 0; /* Address of jump operation */
1261 if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){
1262 pAndExpr->pLeft = pOrExpr;
1263 pOrExpr = pAndExpr;
1264 }
1265 /* Loop through table entries that match term pOrTerm. */
1266 WHERETRACE(0xffff, ("Subplan for OR-clause:\n"));
1267 pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
1268 wctrlFlags, iCovCur);
1269 assert( pSubWInfo || pParse->nErr || db->mallocFailed );
1270 if( pSubWInfo ){
1271 WhereLoop *pSubLoop;
1272 int addrExplain = sqlite3WhereExplainOneScan(
1273 pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
1274 );
1275 sqlite3WhereAddScanStatus(v, pOrTab, &pSubWInfo->a[0], addrExplain);
1276
1277 /* This is the sub-WHERE clause body. First skip over
1278 ** duplicate rows from prior sub-WHERE clauses, and record the
1279 ** rowid (or PRIMARY KEY) for the current row so that the same
1280 ** row will be skipped in subsequent sub-WHERE clauses.
1281 */
1282 if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
1283 int r;
1284 int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
1285 if( HasRowid(pTab) ){
1286 r = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, regRowid, 0);
1287 j1 = sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, 0, r,iSet);
1288 VdbeCoverage(v);
1289 }else{
1290 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
1291 int nPk = pPk->nKeyCol;
1292 int iPk;
1293
1294 /* Read the PK into an array of temp registers. */
1295 r = sqlite3GetTempRange(pParse, nPk);
1296 for(iPk=0; iPk<nPk; iPk++){
1297 int iCol = pPk->aiColumn[iPk];
drhd3e3f0b2015-07-23 16:39:33 +00001298 int rx;
1299 rx = sqlite3ExprCodeGetColumn(pParse, pTab, iCol, iCur,r+iPk,0);
1300 if( rx!=r+iPk ){
1301 sqlite3VdbeAddOp2(v, OP_SCopy, rx, r+iPk);
1302 }
drh6f82e852015-06-06 20:12:09 +00001303 }
1304
1305 /* Check if the temp table already contains this key. If so,
1306 ** the row has already been included in the result set and
1307 ** can be ignored (by jumping past the Gosub below). Otherwise,
1308 ** insert the key into the temp table and proceed with processing
1309 ** the row.
1310 **
1311 ** Use some of the same optimizations as OP_RowSetTest: If iSet
1312 ** is zero, assume that the key cannot already be present in
1313 ** the temp table. And if iSet is -1, assume that there is no
1314 ** need to insert the key into the temp table, as it will never
1315 ** be tested for. */
1316 if( iSet ){
1317 j1 = sqlite3VdbeAddOp4Int(v, OP_Found, regRowset, 0, r, nPk);
1318 VdbeCoverage(v);
1319 }
1320 if( iSet>=0 ){
1321 sqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, regRowid);
1322 sqlite3VdbeAddOp3(v, OP_IdxInsert, regRowset, regRowid, 0);
1323 if( iSet ) sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
1324 }
1325
1326 /* Release the array of temp registers */
1327 sqlite3ReleaseTempRange(pParse, r, nPk);
1328 }
1329 }
1330
1331 /* Invoke the main loop body as a subroutine */
1332 sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
1333
1334 /* Jump here (skipping the main loop body subroutine) if the
1335 ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */
1336 if( j1 ) sqlite3VdbeJumpHere(v, j1);
1337
1338 /* The pSubWInfo->untestedTerms flag means that this OR term
1339 ** contained one or more AND term from a notReady table. The
1340 ** terms from the notReady table could not be tested and will
1341 ** need to be tested later.
1342 */
1343 if( pSubWInfo->untestedTerms ) untestedTerms = 1;
1344
1345 /* If all of the OR-connected terms are optimized using the same
1346 ** index, and the index is opened using the same cursor number
1347 ** by each call to sqlite3WhereBegin() made by this loop, it may
1348 ** be possible to use that index as a covering index.
1349 **
1350 ** If the call to sqlite3WhereBegin() above resulted in a scan that
1351 ** uses an index, and this is either the first OR-connected term
1352 ** processed or the index is the same as that used by all previous
1353 ** terms, set pCov to the candidate covering index. Otherwise, set
1354 ** pCov to NULL to indicate that no candidate covering index will
1355 ** be available.
1356 */
1357 pSubLoop = pSubWInfo->a[0].pWLoop;
1358 assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
1359 if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
1360 && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
1361 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pSubLoop->u.btree.pIndex))
1362 ){
1363 assert( pSubWInfo->a[0].iIdxCur==iCovCur );
1364 pCov = pSubLoop->u.btree.pIndex;
1365 wctrlFlags |= WHERE_REOPEN_IDX;
1366 }else{
1367 pCov = 0;
1368 }
1369
1370 /* Finish the loop through table entries that match term pOrTerm. */
1371 sqlite3WhereEnd(pSubWInfo);
1372 }
1373 }
1374 }
1375 pLevel->u.pCovidx = pCov;
1376 if( pCov ) pLevel->iIdxCur = iCovCur;
1377 if( pAndExpr ){
1378 pAndExpr->pLeft = 0;
1379 sqlite3ExprDelete(db, pAndExpr);
1380 }
1381 sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
1382 sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
1383 sqlite3VdbeResolveLabel(v, iLoopBody);
1384
1385 if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab);
1386 if( !untestedTerms ) disableTerm(pLevel, pTerm);
1387 }else
1388#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
1389
1390 {
1391 /* Case 6: There is no usable index. We must do a complete
1392 ** scan of the entire table.
1393 */
1394 static const u8 aStep[] = { OP_Next, OP_Prev };
1395 static const u8 aStart[] = { OP_Rewind, OP_Last };
1396 assert( bRev==0 || bRev==1 );
drh8a48b9c2015-08-19 15:20:00 +00001397 if( pTabItem->fg.isRecursive ){
drh6f82e852015-06-06 20:12:09 +00001398 /* Tables marked isRecursive have only a single row that is stored in
1399 ** a pseudo-cursor. No need to Rewind or Next such cursors. */
1400 pLevel->op = OP_Noop;
1401 }else{
1402 pLevel->op = aStep[bRev];
1403 pLevel->p1 = iCur;
1404 pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
1405 VdbeCoverageIf(v, bRev==0);
1406 VdbeCoverageIf(v, bRev!=0);
1407 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
1408 }
1409 }
1410
1411#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
1412 pLevel->addrVisit = sqlite3VdbeCurrentAddr(v);
1413#endif
1414
1415 /* Insert code to test every subexpression that can be completely
1416 ** computed using the current set of tables.
1417 */
1418 for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
1419 Expr *pE;
1420 int skipLikeAddr = 0;
1421 testcase( pTerm->wtFlags & TERM_VIRTUAL );
1422 testcase( pTerm->wtFlags & TERM_CODED );
1423 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
1424 if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
1425 testcase( pWInfo->untestedTerms==0
1426 && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
1427 pWInfo->untestedTerms = 1;
1428 continue;
1429 }
1430 pE = pTerm->pExpr;
1431 assert( pE!=0 );
1432 if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
1433 continue;
1434 }
1435 if( pTerm->wtFlags & TERM_LIKECOND ){
1436 assert( pLevel->iLikeRepCntr>0 );
1437 skipLikeAddr = sqlite3VdbeAddOp1(v, OP_IfNot, pLevel->iLikeRepCntr);
1438 VdbeCoverage(v);
1439 }
1440 sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
1441 if( skipLikeAddr ) sqlite3VdbeJumpHere(v, skipLikeAddr);
1442 pTerm->wtFlags |= TERM_CODED;
1443 }
1444
1445 /* Insert code to test for implied constraints based on transitivity
1446 ** of the "==" operator.
1447 **
1448 ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
1449 ** and we are coding the t1 loop and the t2 loop has not yet coded,
1450 ** then we cannot use the "t1.a=t2.b" constraint, but we can code
1451 ** the implied "t1.a=123" constraint.
1452 */
1453 for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
1454 Expr *pE, *pEAlt;
1455 WhereTerm *pAlt;
1456 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
1457 if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) continue;
1458 if( (pTerm->eOperator & WO_EQUIV)==0 ) continue;
1459 if( pTerm->leftCursor!=iCur ) continue;
1460 if( pLevel->iLeftJoin ) continue;
1461 pE = pTerm->pExpr;
1462 assert( !ExprHasProperty(pE, EP_FromJoin) );
1463 assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
1464 pAlt = sqlite3WhereFindTerm(pWC, iCur, pTerm->u.leftColumn, notReady,
1465 WO_EQ|WO_IN|WO_IS, 0);
1466 if( pAlt==0 ) continue;
1467 if( pAlt->wtFlags & (TERM_CODED) ) continue;
1468 testcase( pAlt->eOperator & WO_EQ );
1469 testcase( pAlt->eOperator & WO_IS );
1470 testcase( pAlt->eOperator & WO_IN );
1471 VdbeModuleComment((v, "begin transitive constraint"));
1472 pEAlt = sqlite3StackAllocRaw(db, sizeof(*pEAlt));
1473 if( pEAlt ){
1474 *pEAlt = *pAlt->pExpr;
1475 pEAlt->pLeft = pE->pLeft;
1476 sqlite3ExprIfFalse(pParse, pEAlt, addrCont, SQLITE_JUMPIFNULL);
1477 sqlite3StackFree(db, pEAlt);
1478 }
1479 }
1480
1481 /* For a LEFT OUTER JOIN, generate code that will record the fact that
1482 ** at least one row of the right table has matched the left table.
1483 */
1484 if( pLevel->iLeftJoin ){
1485 pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
1486 sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
1487 VdbeComment((v, "record LEFT JOIN hit"));
1488 sqlite3ExprCacheClear(pParse);
1489 for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
1490 testcase( pTerm->wtFlags & TERM_VIRTUAL );
1491 testcase( pTerm->wtFlags & TERM_CODED );
1492 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
1493 if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
1494 assert( pWInfo->untestedTerms );
1495 continue;
1496 }
1497 assert( pTerm->pExpr );
1498 sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
1499 pTerm->wtFlags |= TERM_CODED;
1500 }
1501 }
1502
1503 return pLevel->notReady;
1504}