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