blob: 5e7710ae8af8d24620ded437b406c094a21c6420 [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 WhereLoop *pWLoop;
685 int i, j;
drh2f2b0272015-08-14 18:50:04 +0000686 struct CCurHint sHint;
687 Walker sWalker;
drhbec24762015-08-13 20:07:13 +0000688
689 if( OptimizationDisabled(db, SQLITE_CursorHints) ) return;
drh2f2b0272015-08-14 18:50:04 +0000690 iCur = pLevel->iTabCur;
691 assert( iCur==pWInfo->pTabList->a[pLevel->iFrom].iCursor );
692 sHint.iTabCur = iCur;
693 sHint.iIdxCur = pLevel->iIdxCur;
694 sHint.pIdx = pLoop->u.btree.pIndex;
695 memset(&sWalker, 0, sizeof(sWalker));
696 sWalker.pParse = pParse;
697 sWalker.u.pCCurHint = &sHint;
drhbec24762015-08-13 20:07:13 +0000698 pWC = &pWInfo->sWC;
drhb413a542015-08-17 17:19:28 +0000699 pWLoop = pLevel->pWLoop;
drhbec24762015-08-13 20:07:13 +0000700 for(i=0; i<pWC->nTerm; i++){
701 pTerm = &pWC->a[i];
702 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
703 if( pTerm->prereqAll & pLevel->notReady ) continue;
704 if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) continue;
drhb413a542015-08-17 17:19:28 +0000705
706 /* All terms in pWLoop->aLTerm[] except pEndRange are used to initialize
707 ** the cursor. No need to hint initialization terms. */
708 if( pTerm!=pEndRange ){
709 for(j=0; j<pWLoop->nLTerm && pWLoop->aLTerm[j]!=pTerm; j++){}
710 if( j<pWLoop->nLTerm ) continue;
711 }
712
713 /* No subqueries or non-deterministic functions allowed */
drhbec24762015-08-13 20:07:13 +0000714 if( sqlite3ExprContainsSubquery(pTerm->pExpr) ) continue;
drhb413a542015-08-17 17:19:28 +0000715
716 /* For an index scan, make sure referenced columns are actually in
717 ** the index. */
drh2f2b0272015-08-14 18:50:04 +0000718 if( sHint.pIdx!=0 ){
719 sWalker.eCode = 0;
720 sWalker.xExprCallback = codeCursorHintCheckExpr;
721 sqlite3WalkExpr(&sWalker, pTerm->pExpr);
722 if( sWalker.eCode ) continue;
723 }
drhb413a542015-08-17 17:19:28 +0000724
725 /* If we survive all prior tests, that means this term is worth hinting */
drhbec24762015-08-13 20:07:13 +0000726 pExpr = sqlite3ExprAnd(db, pExpr, sqlite3ExprDup(db, pTerm->pExpr, 0));
727 }
728 if( pExpr!=0 ){
drhbec24762015-08-13 20:07:13 +0000729 sWalker.xExprCallback = codeCursorHintFixExpr;
drhbec24762015-08-13 20:07:13 +0000730 sqlite3WalkExpr(&sWalker, pExpr);
drh2f2b0272015-08-14 18:50:04 +0000731 sqlite3VdbeAddOp4(v, OP_CursorHint,
732 (sHint.pIdx ? sHint.iIdxCur : sHint.iTabCur), 0, 0,
733 (const char*)pExpr, P4_EXPR);
drhbec24762015-08-13 20:07:13 +0000734 }
735}
736#else
drhb413a542015-08-17 17:19:28 +0000737# define codeCursorHint(A,B,C) /* No-op */
drhbec24762015-08-13 20:07:13 +0000738#endif /* SQLITE_ENABLE_CURSOR_HINTS */
drh6f82e852015-06-06 20:12:09 +0000739
740/*
741** Generate code for the start of the iLevel-th loop in the WHERE clause
742** implementation described by pWInfo.
743*/
744Bitmask sqlite3WhereCodeOneLoopStart(
745 WhereInfo *pWInfo, /* Complete information about the WHERE clause */
746 int iLevel, /* Which level of pWInfo->a[] should be coded */
747 Bitmask notReady /* Which tables are currently available */
748){
749 int j, k; /* Loop counters */
750 int iCur; /* The VDBE cursor for the table */
751 int addrNxt; /* Where to jump to continue with the next IN case */
752 int omitTable; /* True if we use the index only */
753 int bRev; /* True if we need to scan in reverse order */
754 WhereLevel *pLevel; /* The where level to be coded */
755 WhereLoop *pLoop; /* The WhereLoop object being coded */
756 WhereClause *pWC; /* Decomposition of the entire WHERE clause */
757 WhereTerm *pTerm; /* A WHERE clause term */
758 Parse *pParse; /* Parsing context */
759 sqlite3 *db; /* Database connection */
760 Vdbe *v; /* The prepared stmt under constructions */
761 struct SrcList_item *pTabItem; /* FROM clause term being coded */
762 int addrBrk; /* Jump here to break out of the loop */
763 int addrCont; /* Jump here to continue with next cycle */
764 int iRowidReg = 0; /* Rowid is stored in this register, if not zero */
765 int iReleaseReg = 0; /* Temp register to free before returning */
766
767 pParse = pWInfo->pParse;
768 v = pParse->pVdbe;
769 pWC = &pWInfo->sWC;
770 db = pParse->db;
771 pLevel = &pWInfo->a[iLevel];
772 pLoop = pLevel->pWLoop;
773 pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
774 iCur = pTabItem->iCursor;
775 pLevel->notReady = notReady & ~sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur);
776 bRev = (pWInfo->revMask>>iLevel)&1;
777 omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
778 && (pWInfo->wctrlFlags & WHERE_FORCE_TABLE)==0;
779 VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName));
780
781 /* Create labels for the "break" and "continue" instructions
782 ** for the current loop. Jump to addrBrk to break out of a loop.
783 ** Jump to cont to go immediately to the next iteration of the
784 ** loop.
785 **
786 ** When there is an IN operator, we also have a "addrNxt" label that
787 ** means to continue with the next IN value combination. When
788 ** there are no IN operators in the constraints, the "addrNxt" label
789 ** is the same as "addrBrk".
790 */
791 addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
792 addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
793
794 /* If this is the right table of a LEFT OUTER JOIN, allocate and
795 ** initialize a memory cell that records if this table matches any
796 ** row of the left table of the join.
797 */
798 if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
799 pLevel->iLeftJoin = ++pParse->nMem;
800 sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
801 VdbeComment((v, "init LEFT JOIN no-match flag"));
802 }
803
804 /* Special case of a FROM clause subquery implemented as a co-routine */
805 if( pTabItem->viaCoroutine ){
806 int regYield = pTabItem->regReturn;
807 sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
808 pLevel->p2 = sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk);
809 VdbeCoverage(v);
810 VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
811 pLevel->op = OP_Goto;
812 }else
813
814#ifndef SQLITE_OMIT_VIRTUALTABLE
815 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
816 /* Case 1: The table is a virtual-table. Use the VFilter and VNext
817 ** to access the data.
818 */
819 int iReg; /* P3 Value for OP_VFilter */
820 int addrNotFound;
821 int nConstraint = pLoop->nLTerm;
822
823 sqlite3ExprCachePush(pParse);
824 iReg = sqlite3GetTempRange(pParse, nConstraint+2);
825 addrNotFound = pLevel->addrBrk;
826 for(j=0; j<nConstraint; j++){
827 int iTarget = iReg+j+2;
828 pTerm = pLoop->aLTerm[j];
829 if( pTerm==0 ) continue;
830 if( pTerm->eOperator & WO_IN ){
831 codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
832 addrNotFound = pLevel->addrNxt;
833 }else{
834 sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget);
835 }
836 }
837 sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
838 sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
839 sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
840 pLoop->u.vtab.idxStr,
841 pLoop->u.vtab.needFree ? P4_MPRINTF : P4_STATIC);
842 VdbeCoverage(v);
843 pLoop->u.vtab.needFree = 0;
844 for(j=0; j<nConstraint && j<16; j++){
845 if( (pLoop->u.vtab.omitMask>>j)&1 ){
846 disableTerm(pLevel, pLoop->aLTerm[j]);
847 }
848 }
849 pLevel->op = OP_VNext;
850 pLevel->p1 = iCur;
851 pLevel->p2 = sqlite3VdbeCurrentAddr(v);
852 sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
853 sqlite3ExprCachePop(pParse);
854 }else
855#endif /* SQLITE_OMIT_VIRTUALTABLE */
856
857 if( (pLoop->wsFlags & WHERE_IPK)!=0
858 && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
859 ){
860 /* Case 2: We can directly reference a single row using an
861 ** equality comparison against the ROWID field. Or
862 ** we reference multiple rows using a "rowid IN (...)"
863 ** construct.
864 */
865 assert( pLoop->u.btree.nEq==1 );
866 pTerm = pLoop->aLTerm[0];
867 assert( pTerm!=0 );
868 assert( pTerm->pExpr!=0 );
869 assert( omitTable==0 );
870 testcase( pTerm->wtFlags & TERM_VIRTUAL );
871 iReleaseReg = ++pParse->nMem;
872 iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
873 if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg);
874 addrNxt = pLevel->addrNxt;
875 sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt); VdbeCoverage(v);
876 sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
877 VdbeCoverage(v);
878 sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
879 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
880 VdbeComment((v, "pk"));
881 pLevel->op = OP_Noop;
882 }else if( (pLoop->wsFlags & WHERE_IPK)!=0
883 && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
884 ){
885 /* Case 3: We have an inequality comparison against the ROWID field.
886 */
887 int testOp = OP_Noop;
888 int start;
889 int memEndValue = 0;
890 WhereTerm *pStart, *pEnd;
891
892 assert( omitTable==0 );
893 j = 0;
894 pStart = pEnd = 0;
895 if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
896 if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
897 assert( pStart!=0 || pEnd!=0 );
898 if( bRev ){
899 pTerm = pStart;
900 pStart = pEnd;
901 pEnd = pTerm;
902 }
drhb413a542015-08-17 17:19:28 +0000903 codeCursorHint(pWInfo, pLevel, pEnd);
drh6f82e852015-06-06 20:12:09 +0000904 if( pStart ){
905 Expr *pX; /* The expression that defines the start bound */
906 int r1, rTemp; /* Registers for holding the start boundary */
907
908 /* The following constant maps TK_xx codes into corresponding
909 ** seek opcodes. It depends on a particular ordering of TK_xx
910 */
911 const u8 aMoveOp[] = {
912 /* TK_GT */ OP_SeekGT,
913 /* TK_LE */ OP_SeekLE,
914 /* TK_LT */ OP_SeekLT,
915 /* TK_GE */ OP_SeekGE
916 };
917 assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */
918 assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */
919 assert( TK_GE==TK_GT+3 ); /* ... is correcct. */
920
921 assert( (pStart->wtFlags & TERM_VNULL)==0 );
922 testcase( pStart->wtFlags & TERM_VIRTUAL );
923 pX = pStart->pExpr;
924 assert( pX!=0 );
925 testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
926 r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
927 sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
928 VdbeComment((v, "pk"));
929 VdbeCoverageIf(v, pX->op==TK_GT);
930 VdbeCoverageIf(v, pX->op==TK_LE);
931 VdbeCoverageIf(v, pX->op==TK_LT);
932 VdbeCoverageIf(v, pX->op==TK_GE);
933 sqlite3ExprCacheAffinityChange(pParse, r1, 1);
934 sqlite3ReleaseTempReg(pParse, rTemp);
935 disableTerm(pLevel, pStart);
936 }else{
937 sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
938 VdbeCoverageIf(v, bRev==0);
939 VdbeCoverageIf(v, bRev!=0);
940 }
941 if( pEnd ){
942 Expr *pX;
943 pX = pEnd->pExpr;
944 assert( pX!=0 );
945 assert( (pEnd->wtFlags & TERM_VNULL)==0 );
946 testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
947 testcase( pEnd->wtFlags & TERM_VIRTUAL );
948 memEndValue = ++pParse->nMem;
949 sqlite3ExprCode(pParse, pX->pRight, memEndValue);
950 if( pX->op==TK_LT || pX->op==TK_GT ){
951 testOp = bRev ? OP_Le : OP_Ge;
952 }else{
953 testOp = bRev ? OP_Lt : OP_Gt;
954 }
955 disableTerm(pLevel, pEnd);
956 }
957 start = sqlite3VdbeCurrentAddr(v);
958 pLevel->op = bRev ? OP_Prev : OP_Next;
959 pLevel->p1 = iCur;
960 pLevel->p2 = start;
961 assert( pLevel->p5==0 );
962 if( testOp!=OP_Noop ){
963 iRowidReg = ++pParse->nMem;
964 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
965 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
966 sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
967 VdbeCoverageIf(v, testOp==OP_Le);
968 VdbeCoverageIf(v, testOp==OP_Lt);
969 VdbeCoverageIf(v, testOp==OP_Ge);
970 VdbeCoverageIf(v, testOp==OP_Gt);
971 sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
972 }
973 }else if( pLoop->wsFlags & WHERE_INDEXED ){
974 /* Case 4: A scan using an index.
975 **
976 ** The WHERE clause may contain zero or more equality
977 ** terms ("==" or "IN" operators) that refer to the N
978 ** left-most columns of the index. It may also contain
979 ** inequality constraints (>, <, >= or <=) on the indexed
980 ** column that immediately follows the N equalities. Only
981 ** the right-most column can be an inequality - the rest must
982 ** use the "==" and "IN" operators. For example, if the
983 ** index is on (x,y,z), then the following clauses are all
984 ** optimized:
985 **
986 ** x=5
987 ** x=5 AND y=10
988 ** x=5 AND y<10
989 ** x=5 AND y>5 AND y<10
990 ** x=5 AND y=5 AND z<=10
991 **
992 ** The z<10 term of the following cannot be used, only
993 ** the x=5 term:
994 **
995 ** x=5 AND z<10
996 **
997 ** N may be zero if there are inequality constraints.
998 ** If there are no inequality constraints, then N is at
999 ** least one.
1000 **
1001 ** This case is also used when there are no WHERE clause
1002 ** constraints but an index is selected anyway, in order
1003 ** to force the output order to conform to an ORDER BY.
1004 */
1005 static const u8 aStartOp[] = {
1006 0,
1007 0,
1008 OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */
1009 OP_Last, /* 3: (!start_constraints && startEq && bRev) */
1010 OP_SeekGT, /* 4: (start_constraints && !startEq && !bRev) */
1011 OP_SeekLT, /* 5: (start_constraints && !startEq && bRev) */
1012 OP_SeekGE, /* 6: (start_constraints && startEq && !bRev) */
1013 OP_SeekLE /* 7: (start_constraints && startEq && bRev) */
1014 };
1015 static const u8 aEndOp[] = {
1016 OP_IdxGE, /* 0: (end_constraints && !bRev && !endEq) */
1017 OP_IdxGT, /* 1: (end_constraints && !bRev && endEq) */
1018 OP_IdxLE, /* 2: (end_constraints && bRev && !endEq) */
1019 OP_IdxLT, /* 3: (end_constraints && bRev && endEq) */
1020 };
1021 u16 nEq = pLoop->u.btree.nEq; /* Number of == or IN terms */
1022 int regBase; /* Base register holding constraint values */
1023 WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */
1024 WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */
1025 int startEq; /* True if range start uses ==, >= or <= */
1026 int endEq; /* True if range end uses ==, >= or <= */
1027 int start_constraints; /* Start of range is constrained */
1028 int nConstraint; /* Number of constraint terms */
1029 Index *pIdx; /* The index we will be using */
1030 int iIdxCur; /* The VDBE cursor for the index */
1031 int nExtraReg = 0; /* Number of extra registers needed */
1032 int op; /* Instruction opcode */
1033 char *zStartAff; /* Affinity for start of range constraint */
1034 char cEndAff = 0; /* Affinity for end of range constraint */
1035 u8 bSeekPastNull = 0; /* True to seek past initial nulls */
1036 u8 bStopAtNull = 0; /* Add condition to terminate at NULLs */
1037
1038 pIdx = pLoop->u.btree.pIndex;
1039 iIdxCur = pLevel->iIdxCur;
1040 assert( nEq>=pLoop->nSkip );
1041
1042 /* If this loop satisfies a sort order (pOrderBy) request that
1043 ** was passed to this function to implement a "SELECT min(x) ..."
1044 ** query, then the caller will only allow the loop to run for
1045 ** a single iteration. This means that the first row returned
1046 ** should not have a NULL value stored in 'x'. If column 'x' is
1047 ** the first one after the nEq equality constraints in the index,
1048 ** this requires some special handling.
1049 */
1050 assert( pWInfo->pOrderBy==0
1051 || pWInfo->pOrderBy->nExpr==1
1052 || (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0 );
1053 if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
1054 && pWInfo->nOBSat>0
1055 && (pIdx->nKeyCol>nEq)
1056 ){
1057 assert( pLoop->nSkip==0 );
1058 bSeekPastNull = 1;
1059 nExtraReg = 1;
1060 }
1061
1062 /* Find any inequality constraint terms for the start and end
1063 ** of the range.
1064 */
1065 j = nEq;
1066 if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
1067 pRangeStart = pLoop->aLTerm[j++];
1068 nExtraReg = 1;
1069 /* Like optimization range constraints always occur in pairs */
1070 assert( (pRangeStart->wtFlags & TERM_LIKEOPT)==0 ||
1071 (pLoop->wsFlags & WHERE_TOP_LIMIT)!=0 );
1072 }
1073 if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
1074 pRangeEnd = pLoop->aLTerm[j++];
1075 nExtraReg = 1;
1076 if( (pRangeEnd->wtFlags & TERM_LIKEOPT)!=0 ){
1077 assert( pRangeStart!=0 ); /* LIKE opt constraints */
1078 assert( pRangeStart->wtFlags & TERM_LIKEOPT ); /* occur in pairs */
1079 pLevel->iLikeRepCntr = ++pParse->nMem;
1080 testcase( bRev );
1081 testcase( pIdx->aSortOrder[nEq]==SQLITE_SO_DESC );
1082 sqlite3VdbeAddOp2(v, OP_Integer,
1083 bRev ^ (pIdx->aSortOrder[nEq]==SQLITE_SO_DESC),
1084 pLevel->iLikeRepCntr);
1085 VdbeComment((v, "LIKE loop counter"));
1086 pLevel->addrLikeRep = sqlite3VdbeCurrentAddr(v);
1087 }
1088 if( pRangeStart==0
1089 && (j = pIdx->aiColumn[nEq])>=0
1090 && pIdx->pTable->aCol[j].notNull==0
1091 ){
1092 bSeekPastNull = 1;
1093 }
1094 }
1095 assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 );
1096
1097 /* Generate code to evaluate all constraint terms using == or IN
1098 ** and store the values of those terms in an array of registers
1099 ** starting at regBase.
1100 */
1101 regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
1102 assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq );
1103 if( zStartAff ) cEndAff = zStartAff[nEq];
1104 addrNxt = pLevel->addrNxt;
1105
1106 /* If we are doing a reverse order scan on an ascending index, or
1107 ** a forward order scan on a descending index, interchange the
1108 ** start and end terms (pRangeStart and pRangeEnd).
1109 */
1110 if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
1111 || (bRev && pIdx->nKeyCol==nEq)
1112 ){
1113 SWAP(WhereTerm *, pRangeEnd, pRangeStart);
1114 SWAP(u8, bSeekPastNull, bStopAtNull);
1115 }
1116
1117 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. */
drhb413a542015-08-17 17:19:28 +00001126 codeCursorHint(pWInfo, pLevel, pRangeEnd);
drh6f82e852015-06-06 20:12:09 +00001127 nConstraint = nEq;
1128 if( pRangeStart ){
1129 Expr *pRight = pRangeStart->pExpr->pRight;
1130 sqlite3ExprCode(pParse, pRight, regBase+nEq);
1131 whereLikeOptimizationStringFixup(v, pLevel, pRangeStart);
1132 if( (pRangeStart->wtFlags & TERM_VNULL)==0
1133 && sqlite3ExprCanBeNull(pRight)
1134 ){
1135 sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
1136 VdbeCoverage(v);
1137 }
1138 if( zStartAff ){
1139 if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_BLOB){
1140 /* Since the comparison is to be performed with no conversions
1141 ** applied to the operands, set the affinity to apply to pRight to
1142 ** SQLITE_AFF_BLOB. */
1143 zStartAff[nEq] = SQLITE_AFF_BLOB;
1144 }
1145 if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
1146 zStartAff[nEq] = SQLITE_AFF_BLOB;
1147 }
1148 }
1149 nConstraint++;
1150 testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
1151 }else if( bSeekPastNull ){
1152 sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
1153 nConstraint++;
1154 startEq = 0;
1155 start_constraints = 1;
1156 }
1157 codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff);
1158 op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
1159 assert( op!=0 );
1160 sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
1161 VdbeCoverage(v);
1162 VdbeCoverageIf(v, op==OP_Rewind); testcase( op==OP_Rewind );
1163 VdbeCoverageIf(v, op==OP_Last); testcase( op==OP_Last );
1164 VdbeCoverageIf(v, op==OP_SeekGT); testcase( op==OP_SeekGT );
1165 VdbeCoverageIf(v, op==OP_SeekGE); testcase( op==OP_SeekGE );
1166 VdbeCoverageIf(v, op==OP_SeekLE); testcase( op==OP_SeekLE );
1167 VdbeCoverageIf(v, op==OP_SeekLT); testcase( op==OP_SeekLT );
1168
1169 /* Load the value for the inequality constraint at the end of the
1170 ** range (if any).
1171 */
1172 nConstraint = nEq;
1173 if( pRangeEnd ){
1174 Expr *pRight = pRangeEnd->pExpr->pRight;
1175 sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
1176 sqlite3ExprCode(pParse, pRight, regBase+nEq);
1177 whereLikeOptimizationStringFixup(v, pLevel, pRangeEnd);
1178 if( (pRangeEnd->wtFlags & TERM_VNULL)==0
1179 && sqlite3ExprCanBeNull(pRight)
1180 ){
1181 sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
1182 VdbeCoverage(v);
1183 }
1184 if( sqlite3CompareAffinity(pRight, cEndAff)!=SQLITE_AFF_BLOB
1185 && !sqlite3ExprNeedsNoAffinityChange(pRight, cEndAff)
1186 ){
1187 codeApplyAffinity(pParse, regBase+nEq, 1, &cEndAff);
1188 }
1189 nConstraint++;
1190 testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
1191 }else if( bStopAtNull ){
1192 sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
1193 endEq = 0;
1194 nConstraint++;
1195 }
1196 sqlite3DbFree(db, zStartAff);
1197
1198 /* Top of the loop body */
1199 pLevel->p2 = sqlite3VdbeCurrentAddr(v);
1200
1201 /* Check if the index cursor is past the end of the range. */
1202 if( nConstraint ){
1203 op = aEndOp[bRev*2 + endEq];
1204 sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
1205 testcase( op==OP_IdxGT ); VdbeCoverageIf(v, op==OP_IdxGT );
1206 testcase( op==OP_IdxGE ); VdbeCoverageIf(v, op==OP_IdxGE );
1207 testcase( op==OP_IdxLT ); VdbeCoverageIf(v, op==OP_IdxLT );
1208 testcase( op==OP_IdxLE ); VdbeCoverageIf(v, op==OP_IdxLE );
1209 }
1210
1211 /* Seek the table cursor, if required */
1212 disableTerm(pLevel, pRangeStart);
1213 disableTerm(pLevel, pRangeEnd);
1214 if( omitTable ){
1215 /* pIdx is a covering index. No need to access the main table. */
1216 }else if( HasRowid(pIdx->pTable) ){
1217 iRowidReg = ++pParse->nMem;
1218 sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
1219 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
1220 sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg); /* Deferred seek */
1221 }else if( iCur!=iIdxCur ){
1222 Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
1223 iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol);
1224 for(j=0; j<pPk->nKeyCol; j++){
1225 k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
1226 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j);
1227 }
1228 sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont,
1229 iRowidReg, pPk->nKeyCol); VdbeCoverage(v);
1230 }
1231
1232 /* Record the instruction used to terminate the loop. Disable
1233 ** WHERE clause terms made redundant by the index range scan.
1234 */
1235 if( pLoop->wsFlags & WHERE_ONEROW ){
1236 pLevel->op = OP_Noop;
1237 }else if( bRev ){
1238 pLevel->op = OP_Prev;
1239 }else{
1240 pLevel->op = OP_Next;
1241 }
1242 pLevel->p1 = iIdxCur;
1243 pLevel->p3 = (pLoop->wsFlags&WHERE_UNQ_WANTED)!=0 ? 1:0;
1244 if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
1245 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
1246 }else{
1247 assert( pLevel->p5==0 );
1248 }
1249 }else
1250
1251#ifndef SQLITE_OMIT_OR_OPTIMIZATION
1252 if( pLoop->wsFlags & WHERE_MULTI_OR ){
1253 /* Case 5: Two or more separately indexed terms connected by OR
1254 **
1255 ** Example:
1256 **
1257 ** CREATE TABLE t1(a,b,c,d);
1258 ** CREATE INDEX i1 ON t1(a);
1259 ** CREATE INDEX i2 ON t1(b);
1260 ** CREATE INDEX i3 ON t1(c);
1261 **
1262 ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
1263 **
1264 ** In the example, there are three indexed terms connected by OR.
1265 ** The top of the loop looks like this:
1266 **
1267 ** Null 1 # Zero the rowset in reg 1
1268 **
1269 ** Then, for each indexed term, the following. The arguments to
1270 ** RowSetTest are such that the rowid of the current row is inserted
1271 ** into the RowSet. If it is already present, control skips the
1272 ** Gosub opcode and jumps straight to the code generated by WhereEnd().
1273 **
1274 ** sqlite3WhereBegin(<term>)
1275 ** RowSetTest # Insert rowid into rowset
1276 ** Gosub 2 A
1277 ** sqlite3WhereEnd()
1278 **
1279 ** Following the above, code to terminate the loop. Label A, the target
1280 ** of the Gosub above, jumps to the instruction right after the Goto.
1281 **
1282 ** Null 1 # Zero the rowset in reg 1
1283 ** Goto B # The loop is finished.
1284 **
1285 ** A: <loop body> # Return data, whatever.
1286 **
1287 ** Return 2 # Jump back to the Gosub
1288 **
1289 ** B: <after the loop>
1290 **
1291 ** Added 2014-05-26: If the table is a WITHOUT ROWID table, then
1292 ** use an ephemeral index instead of a RowSet to record the primary
1293 ** keys of the rows we have already seen.
1294 **
1295 */
1296 WhereClause *pOrWc; /* The OR-clause broken out into subterms */
1297 SrcList *pOrTab; /* Shortened table list or OR-clause generation */
1298 Index *pCov = 0; /* Potential covering index (or NULL) */
1299 int iCovCur = pParse->nTab++; /* Cursor used for index scans (if any) */
1300
1301 int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */
1302 int regRowset = 0; /* Register for RowSet object */
1303 int regRowid = 0; /* Register holding rowid */
1304 int iLoopBody = sqlite3VdbeMakeLabel(v); /* Start of loop body */
1305 int iRetInit; /* Address of regReturn init */
1306 int untestedTerms = 0; /* Some terms not completely tested */
1307 int ii; /* Loop counter */
1308 u16 wctrlFlags; /* Flags for sub-WHERE clause */
1309 Expr *pAndExpr = 0; /* An ".. AND (...)" expression */
1310 Table *pTab = pTabItem->pTab;
1311
1312 pTerm = pLoop->aLTerm[0];
1313 assert( pTerm!=0 );
1314 assert( pTerm->eOperator & WO_OR );
1315 assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
1316 pOrWc = &pTerm->u.pOrInfo->wc;
1317 pLevel->op = OP_Return;
1318 pLevel->p1 = regReturn;
1319
1320 /* Set up a new SrcList in pOrTab containing the table being scanned
1321 ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
1322 ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
1323 */
1324 if( pWInfo->nLevel>1 ){
1325 int nNotReady; /* The number of notReady tables */
1326 struct SrcList_item *origSrc; /* Original list of tables */
1327 nNotReady = pWInfo->nLevel - iLevel - 1;
1328 pOrTab = sqlite3StackAllocRaw(db,
1329 sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
1330 if( pOrTab==0 ) return notReady;
1331 pOrTab->nAlloc = (u8)(nNotReady + 1);
1332 pOrTab->nSrc = pOrTab->nAlloc;
1333 memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
1334 origSrc = pWInfo->pTabList->a;
1335 for(k=1; k<=nNotReady; k++){
1336 memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
1337 }
1338 }else{
1339 pOrTab = pWInfo->pTabList;
1340 }
1341
1342 /* Initialize the rowset register to contain NULL. An SQL NULL is
1343 ** equivalent to an empty rowset. Or, create an ephemeral index
1344 ** capable of holding primary keys in the case of a WITHOUT ROWID.
1345 **
1346 ** Also initialize regReturn to contain the address of the instruction
1347 ** immediately following the OP_Return at the bottom of the loop. This
1348 ** is required in a few obscure LEFT JOIN cases where control jumps
1349 ** over the top of the loop into the body of it. In this case the
1350 ** correct response for the end-of-loop code (the OP_Return) is to
1351 ** fall through to the next instruction, just as an OP_Next does if
1352 ** called on an uninitialized cursor.
1353 */
1354 if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
1355 if( HasRowid(pTab) ){
1356 regRowset = ++pParse->nMem;
1357 sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
1358 }else{
1359 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
1360 regRowset = pParse->nTab++;
1361 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, regRowset, pPk->nKeyCol);
1362 sqlite3VdbeSetP4KeyInfo(pParse, pPk);
1363 }
1364 regRowid = ++pParse->nMem;
1365 }
1366 iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
1367
1368 /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y
1369 ** Then for every term xN, evaluate as the subexpression: xN AND z
1370 ** That way, terms in y that are factored into the disjunction will
1371 ** be picked up by the recursive calls to sqlite3WhereBegin() below.
1372 **
1373 ** Actually, each subexpression is converted to "xN AND w" where w is
1374 ** the "interesting" terms of z - terms that did not originate in the
1375 ** ON or USING clause of a LEFT JOIN, and terms that are usable as
1376 ** indices.
1377 **
1378 ** This optimization also only applies if the (x1 OR x2 OR ...) term
1379 ** is not contained in the ON clause of a LEFT JOIN.
1380 ** See ticket http://www.sqlite.org/src/info/f2369304e4
1381 */
1382 if( pWC->nTerm>1 ){
1383 int iTerm;
1384 for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
1385 Expr *pExpr = pWC->a[iTerm].pExpr;
1386 if( &pWC->a[iTerm] == pTerm ) continue;
1387 if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
1388 if( (pWC->a[iTerm].wtFlags & TERM_VIRTUAL)!=0 ) continue;
1389 if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
1390 testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO );
1391 pExpr = sqlite3ExprDup(db, pExpr, 0);
1392 pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr);
1393 }
1394 if( pAndExpr ){
1395 pAndExpr = sqlite3PExpr(pParse, TK_AND, 0, pAndExpr, 0);
1396 }
1397 }
1398
1399 /* Run a separate WHERE clause for each term of the OR clause. After
1400 ** eliminating duplicates from other WHERE clauses, the action for each
1401 ** sub-WHERE clause is to to invoke the main loop body as a subroutine.
1402 */
1403 wctrlFlags = WHERE_OMIT_OPEN_CLOSE
1404 | WHERE_FORCE_TABLE
1405 | WHERE_ONETABLE_ONLY
1406 | WHERE_NO_AUTOINDEX;
1407 for(ii=0; ii<pOrWc->nTerm; ii++){
1408 WhereTerm *pOrTerm = &pOrWc->a[ii];
1409 if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
1410 WhereInfo *pSubWInfo; /* Info for single OR-term scan */
1411 Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */
1412 int j1 = 0; /* Address of jump operation */
1413 if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){
1414 pAndExpr->pLeft = pOrExpr;
1415 pOrExpr = pAndExpr;
1416 }
1417 /* Loop through table entries that match term pOrTerm. */
1418 WHERETRACE(0xffff, ("Subplan for OR-clause:\n"));
1419 pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
1420 wctrlFlags, iCovCur);
1421 assert( pSubWInfo || pParse->nErr || db->mallocFailed );
1422 if( pSubWInfo ){
1423 WhereLoop *pSubLoop;
1424 int addrExplain = sqlite3WhereExplainOneScan(
1425 pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
1426 );
1427 sqlite3WhereAddScanStatus(v, pOrTab, &pSubWInfo->a[0], addrExplain);
1428
1429 /* This is the sub-WHERE clause body. First skip over
1430 ** duplicate rows from prior sub-WHERE clauses, and record the
1431 ** rowid (or PRIMARY KEY) for the current row so that the same
1432 ** row will be skipped in subsequent sub-WHERE clauses.
1433 */
1434 if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
1435 int r;
1436 int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
1437 if( HasRowid(pTab) ){
1438 r = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, regRowid, 0);
1439 j1 = sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, 0, r,iSet);
1440 VdbeCoverage(v);
1441 }else{
1442 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
1443 int nPk = pPk->nKeyCol;
1444 int iPk;
1445
1446 /* Read the PK into an array of temp registers. */
1447 r = sqlite3GetTempRange(pParse, nPk);
1448 for(iPk=0; iPk<nPk; iPk++){
1449 int iCol = pPk->aiColumn[iPk];
drhd3e3f0b2015-07-23 16:39:33 +00001450 int rx;
1451 rx = sqlite3ExprCodeGetColumn(pParse, pTab, iCol, iCur,r+iPk,0);
1452 if( rx!=r+iPk ){
1453 sqlite3VdbeAddOp2(v, OP_SCopy, rx, r+iPk);
1454 }
drh6f82e852015-06-06 20:12:09 +00001455 }
1456
1457 /* Check if the temp table already contains this key. If so,
1458 ** the row has already been included in the result set and
1459 ** can be ignored (by jumping past the Gosub below). Otherwise,
1460 ** insert the key into the temp table and proceed with processing
1461 ** the row.
1462 **
1463 ** Use some of the same optimizations as OP_RowSetTest: If iSet
1464 ** is zero, assume that the key cannot already be present in
1465 ** the temp table. And if iSet is -1, assume that there is no
1466 ** need to insert the key into the temp table, as it will never
1467 ** be tested for. */
1468 if( iSet ){
1469 j1 = sqlite3VdbeAddOp4Int(v, OP_Found, regRowset, 0, r, nPk);
1470 VdbeCoverage(v);
1471 }
1472 if( iSet>=0 ){
1473 sqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, regRowid);
1474 sqlite3VdbeAddOp3(v, OP_IdxInsert, regRowset, regRowid, 0);
1475 if( iSet ) sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
1476 }
1477
1478 /* Release the array of temp registers */
1479 sqlite3ReleaseTempRange(pParse, r, nPk);
1480 }
1481 }
1482
1483 /* Invoke the main loop body as a subroutine */
1484 sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
1485
1486 /* Jump here (skipping the main loop body subroutine) if the
1487 ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */
1488 if( j1 ) sqlite3VdbeJumpHere(v, j1);
1489
1490 /* The pSubWInfo->untestedTerms flag means that this OR term
1491 ** contained one or more AND term from a notReady table. The
1492 ** terms from the notReady table could not be tested and will
1493 ** need to be tested later.
1494 */
1495 if( pSubWInfo->untestedTerms ) untestedTerms = 1;
1496
1497 /* If all of the OR-connected terms are optimized using the same
1498 ** index, and the index is opened using the same cursor number
1499 ** by each call to sqlite3WhereBegin() made by this loop, it may
1500 ** be possible to use that index as a covering index.
1501 **
1502 ** If the call to sqlite3WhereBegin() above resulted in a scan that
1503 ** uses an index, and this is either the first OR-connected term
1504 ** processed or the index is the same as that used by all previous
1505 ** terms, set pCov to the candidate covering index. Otherwise, set
1506 ** pCov to NULL to indicate that no candidate covering index will
1507 ** be available.
1508 */
1509 pSubLoop = pSubWInfo->a[0].pWLoop;
1510 assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
1511 if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
1512 && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
1513 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pSubLoop->u.btree.pIndex))
1514 ){
1515 assert( pSubWInfo->a[0].iIdxCur==iCovCur );
1516 pCov = pSubLoop->u.btree.pIndex;
1517 wctrlFlags |= WHERE_REOPEN_IDX;
1518 }else{
1519 pCov = 0;
1520 }
1521
1522 /* Finish the loop through table entries that match term pOrTerm. */
1523 sqlite3WhereEnd(pSubWInfo);
1524 }
1525 }
1526 }
1527 pLevel->u.pCovidx = pCov;
1528 if( pCov ) pLevel->iIdxCur = iCovCur;
1529 if( pAndExpr ){
1530 pAndExpr->pLeft = 0;
1531 sqlite3ExprDelete(db, pAndExpr);
1532 }
1533 sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
1534 sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
1535 sqlite3VdbeResolveLabel(v, iLoopBody);
1536
1537 if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab);
1538 if( !untestedTerms ) disableTerm(pLevel, pTerm);
1539 }else
1540#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
1541
1542 {
1543 /* Case 6: There is no usable index. We must do a complete
1544 ** scan of the entire table.
1545 */
1546 static const u8 aStep[] = { OP_Next, OP_Prev };
1547 static const u8 aStart[] = { OP_Rewind, OP_Last };
1548 assert( bRev==0 || bRev==1 );
1549 if( pTabItem->isRecursive ){
1550 /* Tables marked isRecursive have only a single row that is stored in
1551 ** a pseudo-cursor. No need to Rewind or Next such cursors. */
1552 pLevel->op = OP_Noop;
1553 }else{
drhb413a542015-08-17 17:19:28 +00001554 codeCursorHint(pWInfo, pLevel, 0);
drh6f82e852015-06-06 20:12:09 +00001555 pLevel->op = aStep[bRev];
1556 pLevel->p1 = iCur;
1557 pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
1558 VdbeCoverageIf(v, bRev==0);
1559 VdbeCoverageIf(v, bRev!=0);
1560 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
1561 }
1562 }
1563
1564#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
1565 pLevel->addrVisit = sqlite3VdbeCurrentAddr(v);
1566#endif
1567
1568 /* Insert code to test every subexpression that can be completely
1569 ** computed using the current set of tables.
1570 */
1571 for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
1572 Expr *pE;
1573 int skipLikeAddr = 0;
1574 testcase( pTerm->wtFlags & TERM_VIRTUAL );
1575 testcase( pTerm->wtFlags & TERM_CODED );
1576 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
1577 if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
1578 testcase( pWInfo->untestedTerms==0
1579 && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
1580 pWInfo->untestedTerms = 1;
1581 continue;
1582 }
1583 pE = pTerm->pExpr;
1584 assert( pE!=0 );
1585 if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
1586 continue;
1587 }
1588 if( pTerm->wtFlags & TERM_LIKECOND ){
1589 assert( pLevel->iLikeRepCntr>0 );
1590 skipLikeAddr = sqlite3VdbeAddOp1(v, OP_IfNot, pLevel->iLikeRepCntr);
1591 VdbeCoverage(v);
1592 }
1593 sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
1594 if( skipLikeAddr ) sqlite3VdbeJumpHere(v, skipLikeAddr);
1595 pTerm->wtFlags |= TERM_CODED;
1596 }
1597
1598 /* Insert code to test for implied constraints based on transitivity
1599 ** of the "==" operator.
1600 **
1601 ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
1602 ** and we are coding the t1 loop and the t2 loop has not yet coded,
1603 ** then we cannot use the "t1.a=t2.b" constraint, but we can code
1604 ** the implied "t1.a=123" constraint.
1605 */
1606 for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
1607 Expr *pE, *pEAlt;
1608 WhereTerm *pAlt;
1609 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
1610 if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) continue;
1611 if( (pTerm->eOperator & WO_EQUIV)==0 ) continue;
1612 if( pTerm->leftCursor!=iCur ) continue;
1613 if( pLevel->iLeftJoin ) continue;
1614 pE = pTerm->pExpr;
1615 assert( !ExprHasProperty(pE, EP_FromJoin) );
1616 assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
1617 pAlt = sqlite3WhereFindTerm(pWC, iCur, pTerm->u.leftColumn, notReady,
1618 WO_EQ|WO_IN|WO_IS, 0);
1619 if( pAlt==0 ) continue;
1620 if( pAlt->wtFlags & (TERM_CODED) ) continue;
1621 testcase( pAlt->eOperator & WO_EQ );
1622 testcase( pAlt->eOperator & WO_IS );
1623 testcase( pAlt->eOperator & WO_IN );
1624 VdbeModuleComment((v, "begin transitive constraint"));
1625 pEAlt = sqlite3StackAllocRaw(db, sizeof(*pEAlt));
1626 if( pEAlt ){
1627 *pEAlt = *pAlt->pExpr;
1628 pEAlt->pLeft = pE->pLeft;
1629 sqlite3ExprIfFalse(pParse, pEAlt, addrCont, SQLITE_JUMPIFNULL);
1630 sqlite3StackFree(db, pEAlt);
1631 }
1632 }
1633
1634 /* For a LEFT OUTER JOIN, generate code that will record the fact that
1635 ** at least one row of the right table has matched the left table.
1636 */
1637 if( pLevel->iLeftJoin ){
1638 pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
1639 sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
1640 VdbeComment((v, "record LEFT JOIN hit"));
1641 sqlite3ExprCacheClear(pParse);
1642 for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
1643 testcase( pTerm->wtFlags & TERM_VIRTUAL );
1644 testcase( pTerm->wtFlags & TERM_CODED );
1645 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
1646 if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
1647 assert( pWInfo->untestedTerms );
1648 continue;
1649 }
1650 assert( pTerm->pExpr );
1651 sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
1652 pTerm->wtFlags |= TERM_CODED;
1653 }
1654 }
1655
1656 return pLevel->notReady;
1657}