blob: 9aafa83665dfd9dd418c8b71439602ef0462128c [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/*
drhc7c46802015-08-27 20:33:38 +000045** Return the name of the i-th column of the pIdx index.
46*/
47static const char *explainIndexColumnName(Index *pIdx, int i){
48 i = pIdx->aiColumn[i];
drh4b92f982015-09-29 17:20:14 +000049 if( i==XN_EXPR ) return "<expr>";
50 if( i==XN_ROWID ) return "rowid";
drhc7c46802015-08-27 20:33:38 +000051 return pIdx->pTable->aCol[i].zName;
52}
53
54/*
drh6f82e852015-06-06 20:12:09 +000055** Argument pLevel describes a strategy for scanning table pTab. This
56** function appends text to pStr that describes the subset of table
57** rows scanned by the strategy in the form of an SQL expression.
58**
59** For example, if the query:
60**
61** SELECT * FROM t1 WHERE a=1 AND b>2;
62**
63** is run and there is an index on (a, b), then this function returns a
64** string similar to:
65**
66** "a=? AND b>?"
67*/
drh8faee872015-09-19 18:08:13 +000068static void explainIndexRange(StrAccum *pStr, WhereLoop *pLoop){
drh6f82e852015-06-06 20:12:09 +000069 Index *pIndex = pLoop->u.btree.pIndex;
70 u16 nEq = pLoop->u.btree.nEq;
71 u16 nSkip = pLoop->nSkip;
72 int i, j;
drh6f82e852015-06-06 20:12:09 +000073
74 if( nEq==0 && (pLoop->wsFlags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ) return;
75 sqlite3StrAccumAppend(pStr, " (", 2);
76 for(i=0; i<nEq; i++){
drhc7c46802015-08-27 20:33:38 +000077 const char *z = explainIndexColumnName(pIndex, i);
drh2ed0d802015-09-02 16:51:37 +000078 if( i ) sqlite3StrAccumAppend(pStr, " AND ", 5);
drh5f4a6862016-01-30 12:50:25 +000079 sqlite3XPrintf(pStr, i>=nSkip ? "%s=?" : "ANY(%s)", z);
drh6f82e852015-06-06 20:12:09 +000080 }
81
82 j = i;
83 if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
drhc7c46802015-08-27 20:33:38 +000084 const char *z = explainIndexColumnName(pIndex, i);
drh6f82e852015-06-06 20:12:09 +000085 explainAppendTerm(pStr, i++, z, ">");
86 }
87 if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
drhc7c46802015-08-27 20:33:38 +000088 const char *z = explainIndexColumnName(pIndex, j);
drh6f82e852015-06-06 20:12:09 +000089 explainAppendTerm(pStr, i, z, "<");
90 }
91 sqlite3StrAccumAppend(pStr, ")", 1);
92}
93
94/*
95** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
96** command, or if either SQLITE_DEBUG or SQLITE_ENABLE_STMT_SCANSTATUS was
97** defined at compile-time. If it is not a no-op, a single OP_Explain opcode
98** is added to the output to describe the table scan strategy in pLevel.
99**
100** If an OP_Explain opcode is added to the VM, its address is returned.
101** Otherwise, if no OP_Explain is coded, zero is returned.
102*/
103int sqlite3WhereExplainOneScan(
104 Parse *pParse, /* Parse context */
105 SrcList *pTabList, /* Table list this loop refers to */
106 WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
107 int iLevel, /* Value for "level" column of output */
108 int iFrom, /* Value for "from" column of output */
109 u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
110){
111 int ret = 0;
112#if !defined(SQLITE_DEBUG) && !defined(SQLITE_ENABLE_STMT_SCANSTATUS)
113 if( pParse->explain==2 )
114#endif
115 {
116 struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
117 Vdbe *v = pParse->pVdbe; /* VM being constructed */
118 sqlite3 *db = pParse->db; /* Database handle */
119 int iId = pParse->iSelectId; /* Select id (left-most output column) */
120 int isSearch; /* True for a SEARCH. False for SCAN. */
121 WhereLoop *pLoop; /* The controlling WhereLoop object */
122 u32 flags; /* Flags that describe this loop */
123 char *zMsg; /* Text to add to EQP output */
124 StrAccum str; /* EQP output string */
125 char zBuf[100]; /* Initial space for EQP output string */
126
127 pLoop = pLevel->pWLoop;
128 flags = pLoop->wsFlags;
drhce943bc2016-05-19 18:56:33 +0000129 if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_OR_SUBCLAUSE) ) return 0;
drh6f82e852015-06-06 20:12:09 +0000130
131 isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
132 || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
133 || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
134
135 sqlite3StrAccumInit(&str, db, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH);
136 sqlite3StrAccumAppendAll(&str, isSearch ? "SEARCH" : "SCAN");
137 if( pItem->pSelect ){
drh5f4a6862016-01-30 12:50:25 +0000138 sqlite3XPrintf(&str, " SUBQUERY %d", pItem->iSelectId);
drh6f82e852015-06-06 20:12:09 +0000139 }else{
drh5f4a6862016-01-30 12:50:25 +0000140 sqlite3XPrintf(&str, " TABLE %s", pItem->zName);
drh6f82e852015-06-06 20:12:09 +0000141 }
142
143 if( pItem->zAlias ){
drh5f4a6862016-01-30 12:50:25 +0000144 sqlite3XPrintf(&str, " AS %s", pItem->zAlias);
drh6f82e852015-06-06 20:12:09 +0000145 }
146 if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0 ){
147 const char *zFmt = 0;
148 Index *pIdx;
149
150 assert( pLoop->u.btree.pIndex!=0 );
151 pIdx = pLoop->u.btree.pIndex;
152 assert( !(flags&WHERE_AUTO_INDEX) || (flags&WHERE_IDX_ONLY) );
153 if( !HasRowid(pItem->pTab) && IsPrimaryKeyIndex(pIdx) ){
154 if( isSearch ){
155 zFmt = "PRIMARY KEY";
156 }
157 }else if( flags & WHERE_PARTIALIDX ){
158 zFmt = "AUTOMATIC PARTIAL COVERING INDEX";
159 }else if( flags & WHERE_AUTO_INDEX ){
160 zFmt = "AUTOMATIC COVERING INDEX";
161 }else if( flags & WHERE_IDX_ONLY ){
162 zFmt = "COVERING INDEX %s";
163 }else{
164 zFmt = "INDEX %s";
165 }
166 if( zFmt ){
167 sqlite3StrAccumAppend(&str, " USING ", 7);
drh5f4a6862016-01-30 12:50:25 +0000168 sqlite3XPrintf(&str, zFmt, pIdx->zName);
drh8faee872015-09-19 18:08:13 +0000169 explainIndexRange(&str, pLoop);
drh6f82e852015-06-06 20:12:09 +0000170 }
171 }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
drhd37bea52015-09-02 15:37:50 +0000172 const char *zRangeOp;
drh6f82e852015-06-06 20:12:09 +0000173 if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
drhd37bea52015-09-02 15:37:50 +0000174 zRangeOp = "=";
drh6f82e852015-06-06 20:12:09 +0000175 }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
drhd37bea52015-09-02 15:37:50 +0000176 zRangeOp = ">? AND rowid<";
drh6f82e852015-06-06 20:12:09 +0000177 }else if( flags&WHERE_BTM_LIMIT ){
drhd37bea52015-09-02 15:37:50 +0000178 zRangeOp = ">";
drh6f82e852015-06-06 20:12:09 +0000179 }else{
180 assert( flags&WHERE_TOP_LIMIT);
drhd37bea52015-09-02 15:37:50 +0000181 zRangeOp = "<";
drh6f82e852015-06-06 20:12:09 +0000182 }
drh5f4a6862016-01-30 12:50:25 +0000183 sqlite3XPrintf(&str, " USING INTEGER PRIMARY KEY (rowid%s?)",zRangeOp);
drh6f82e852015-06-06 20:12:09 +0000184 }
185#ifndef SQLITE_OMIT_VIRTUALTABLE
186 else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
drh5f4a6862016-01-30 12:50:25 +0000187 sqlite3XPrintf(&str, " VIRTUAL TABLE INDEX %d:%s",
drh6f82e852015-06-06 20:12:09 +0000188 pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
189 }
190#endif
191#ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS
192 if( pLoop->nOut>=10 ){
drh5f4a6862016-01-30 12:50:25 +0000193 sqlite3XPrintf(&str, " (~%llu rows)", sqlite3LogEstToInt(pLoop->nOut));
drh6f82e852015-06-06 20:12:09 +0000194 }else{
195 sqlite3StrAccumAppend(&str, " (~1 row)", 9);
196 }
197#endif
198 zMsg = sqlite3StrAccumFinish(&str);
199 ret = sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg,P4_DYNAMIC);
200 }
201 return ret;
202}
203#endif /* SQLITE_OMIT_EXPLAIN */
204
205#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
206/*
207** Configure the VM passed as the first argument with an
208** sqlite3_stmt_scanstatus() entry corresponding to the scan used to
209** implement level pLvl. Argument pSrclist is a pointer to the FROM
210** clause that the scan reads data from.
211**
212** If argument addrExplain is not 0, it must be the address of an
213** OP_Explain instruction that describes the same loop.
214*/
215void sqlite3WhereAddScanStatus(
216 Vdbe *v, /* Vdbe to add scanstatus entry to */
217 SrcList *pSrclist, /* FROM clause pLvl reads data from */
218 WhereLevel *pLvl, /* Level to add scanstatus() entry for */
219 int addrExplain /* Address of OP_Explain (or 0) */
220){
221 const char *zObj = 0;
222 WhereLoop *pLoop = pLvl->pWLoop;
223 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 && pLoop->u.btree.pIndex!=0 ){
224 zObj = pLoop->u.btree.pIndex->zName;
225 }else{
226 zObj = pSrclist->a[pLvl->iFrom].zName;
227 }
228 sqlite3VdbeScanStatus(
229 v, addrExplain, pLvl->addrBody, pLvl->addrVisit, pLoop->nOut, zObj
230 );
231}
232#endif
233
234
235/*
236** Disable a term in the WHERE clause. Except, do not disable the term
237** if it controls a LEFT OUTER JOIN and it did not originate in the ON
238** or USING clause of that join.
239**
240** Consider the term t2.z='ok' in the following queries:
241**
242** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
243** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
244** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
245**
246** The t2.z='ok' is disabled in the in (2) because it originates
247** in the ON clause. The term is disabled in (3) because it is not part
248** of a LEFT OUTER JOIN. In (1), the term is not disabled.
249**
250** Disabling a term causes that term to not be tested in the inner loop
251** of the join. Disabling is an optimization. When terms are satisfied
252** by indices, we disable them to prevent redundant tests in the inner
253** loop. We would get the correct results if nothing were ever disabled,
254** but joins might run a little slower. The trick is to disable as much
255** as we can without disabling too much. If we disabled in (1), we'd get
256** the wrong answer. See ticket #813.
257**
258** If all the children of a term are disabled, then that term is also
259** automatically disabled. In this way, terms get disabled if derived
260** virtual terms are tested first. For example:
261**
262** x GLOB 'abc*' AND x>='abc' AND x<'acd'
263** \___________/ \______/ \_____/
264** parent child1 child2
265**
266** Only the parent term was in the original WHERE clause. The child1
267** and child2 terms were added by the LIKE optimization. If both of
268** the virtual child terms are valid, then testing of the parent can be
269** skipped.
270**
271** Usually the parent term is marked as TERM_CODED. But if the parent
272** term was originally TERM_LIKE, then the parent gets TERM_LIKECOND instead.
273** The TERM_LIKECOND marking indicates that the term should be coded inside
274** a conditional such that is only evaluated on the second pass of a
275** LIKE-optimization loop, when scanning BLOBs instead of strings.
276*/
277static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
278 int nLoop = 0;
279 while( pTerm
280 && (pTerm->wtFlags & TERM_CODED)==0
281 && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
282 && (pLevel->notReady & pTerm->prereqAll)==0
283 ){
284 if( nLoop && (pTerm->wtFlags & TERM_LIKE)!=0 ){
285 pTerm->wtFlags |= TERM_LIKECOND;
286 }else{
287 pTerm->wtFlags |= TERM_CODED;
288 }
289 if( pTerm->iParent<0 ) break;
290 pTerm = &pTerm->pWC->a[pTerm->iParent];
291 pTerm->nChild--;
292 if( pTerm->nChild!=0 ) break;
293 nLoop++;
294 }
295}
296
297/*
298** Code an OP_Affinity opcode to apply the column affinity string zAff
299** to the n registers starting at base.
300**
301** As an optimization, SQLITE_AFF_BLOB entries (which are no-ops) at the
302** beginning and end of zAff are ignored. If all entries in zAff are
303** SQLITE_AFF_BLOB, then no code gets generated.
304**
305** This routine makes its own copy of zAff so that the caller is free
306** to modify zAff after this routine returns.
307*/
308static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
309 Vdbe *v = pParse->pVdbe;
310 if( zAff==0 ){
311 assert( pParse->db->mallocFailed );
312 return;
313 }
314 assert( v!=0 );
315
316 /* Adjust base and n to skip over SQLITE_AFF_BLOB entries at the beginning
317 ** and end of the affinity string.
318 */
319 while( n>0 && zAff[0]==SQLITE_AFF_BLOB ){
320 n--;
321 base++;
322 zAff++;
323 }
324 while( n>1 && zAff[n-1]==SQLITE_AFF_BLOB ){
325 n--;
326 }
327
328 /* Code the OP_Affinity opcode if there is anything left to do. */
329 if( n>0 ){
drh9b34abe2016-01-16 15:12:35 +0000330 sqlite3VdbeAddOp4(v, OP_Affinity, base, n, 0, zAff, n);
drh6f82e852015-06-06 20:12:09 +0000331 sqlite3ExprCacheAffinityChange(pParse, base, n);
332 }
333}
334
335
336/*
337** Generate code for a single equality term of the WHERE clause. An equality
338** term can be either X=expr or X IN (...). pTerm is the term to be
339** coded.
340**
341** The current value for the constraint is left in register iReg.
342**
343** For a constraint of the form X=expr, the expression is evaluated and its
344** result is left on the stack. For constraints of the form X IN (...)
345** this routine sets up a loop that will iterate over all values of X.
346*/
347static int codeEqualityTerm(
348 Parse *pParse, /* The parsing context */
349 WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
350 WhereLevel *pLevel, /* The level of the FROM clause we are working on */
351 int iEq, /* Index of the equality term within this level */
352 int bRev, /* True for reverse-order IN operations */
353 int iTarget /* Attempt to leave results in this register */
354){
355 Expr *pX = pTerm->pExpr;
356 Vdbe *v = pParse->pVdbe;
357 int iReg; /* Register holding results */
358
dan8da209b2016-07-26 18:06:08 +0000359 assert( pLevel->pWLoop->aLTerm[iEq]==pTerm );
drh6f82e852015-06-06 20:12:09 +0000360 assert( iTarget>0 );
361 if( pX->op==TK_EQ || pX->op==TK_IS ){
dan145b4ea2016-07-29 18:12:12 +0000362 Expr *pRight = pX->pRight;
danf9b2e052016-08-02 17:45:00 +0000363#ifndef SQLITE_OMIT_SUBQUERY
dan145b4ea2016-07-29 18:12:12 +0000364 if( pRight->op==TK_SELECT_COLUMN ){
365 /* This case occurs for expressions like "(a, b) == (SELECT ...)". */
366 WhereLoop *pLoop = pLevel->pWLoop;
367 int i;
368 Expr *pSub = pRight->pLeft;
369 assert( pSub->op==TK_SELECT );
370 for(i=pLoop->nSkip; i<iEq; i++){
371 Expr *pExpr = pLoop->aLTerm[i]->pExpr->pRight;
372 if( pExpr && pExpr->op==TK_SELECT_COLUMN && pExpr->pLeft==pSub ) break;
373 }
374
375 if( i==iEq ){
376 iReg = sqlite3CodeSubselect(pParse, pSub, 0, 0);
377 for(/*no-op*/; i<pLoop->nLTerm; i++){
378 Expr *pExpr = pLoop->aLTerm[i]->pExpr->pRight;
379 if( pExpr && pExpr->op==TK_SELECT_COLUMN && pExpr->pLeft==pSub ){
380 sqlite3VdbeAddOp2(v, OP_Copy, iReg+pExpr->iColumn, iTarget-iEq+i);
381 }
382 }
383 }
384 iReg = iTarget;
danf9b2e052016-08-02 17:45:00 +0000385 }else
386#endif
387 {
dan145b4ea2016-07-29 18:12:12 +0000388 iReg = sqlite3ExprCodeTarget(pParse, pRight, iTarget);
389 }
drh6f82e852015-06-06 20:12:09 +0000390 }else if( pX->op==TK_ISNULL ){
391 iReg = iTarget;
392 sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
393#ifndef SQLITE_OMIT_SUBQUERY
394 }else{
395 int eType;
396 int iTab;
397 struct InLoop *pIn;
398 WhereLoop *pLoop = pLevel->pWLoop;
dan8da209b2016-07-26 18:06:08 +0000399 int i;
400 int nEq = 0;
401 int *aiMap = 0;
drh6f82e852015-06-06 20:12:09 +0000402
403 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
404 && pLoop->u.btree.pIndex!=0
405 && pLoop->u.btree.pIndex->aSortOrder[iEq]
406 ){
407 testcase( iEq==0 );
408 testcase( bRev );
409 bRev = !bRev;
410 }
411 assert( pX->op==TK_IN );
412 iReg = iTarget;
dan8da209b2016-07-26 18:06:08 +0000413
414 for(i=0; i<iEq; i++){
415 if( pLoop->aLTerm[i] && pLoop->aLTerm[i]->pExpr==pX ){
416 disableTerm(pLevel, pTerm);
417 return iTarget;
418 }
419 }
420 for(i=iEq;i<pLoop->nLTerm; i++){
421 if( pLoop->aLTerm[i] && pLoop->aLTerm[i]->pExpr==pX ) nEq++;
422 }
423
424 if( nEq>1 ){
425 aiMap = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int) * nEq);
426 if( !aiMap ) return 0;
427 }
428
429 if( (pX->flags & EP_xIsSelect)==0 || pX->x.pSelect->pEList->nExpr==1 ){
430 eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, 0);
431 }else{
432 sqlite3 *db = pParse->db;
433 ExprList *pOrigRhs = pX->x.pSelect->pEList;
434 ExprList *pOrigLhs = pX->pLeft->x.pList;
435 ExprList *pRhs = 0; /* New Select.pEList for RHS */
436 ExprList *pLhs = 0; /* New pX->pLeft vector */
437
438 for(i=iEq;i<pLoop->nLTerm; i++){
439 if( pLoop->aLTerm[i]->pExpr==pX ){
440 int iField = pLoop->aLTerm[i]->iField - 1;
441 Expr *pNewRhs = sqlite3ExprDup(db, pOrigRhs->a[iField].pExpr, 0);
442 Expr *pNewLhs = sqlite3ExprDup(db, pOrigLhs->a[iField].pExpr, 0);
443
444 pRhs = sqlite3ExprListAppend(pParse, pRhs, pNewRhs);
445 pLhs = sqlite3ExprListAppend(pParse, pLhs, pNewLhs);
446 }
447 }
448
449 pX->x.pSelect->pEList = pRhs;
450 pX->pLeft->x.pList = pLhs;
451
452 eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, aiMap);
453 pX->x.pSelect->pEList = pOrigRhs;
454 pX->pLeft->x.pList = pOrigLhs;
455 sqlite3ExprListDelete(pParse->db, pLhs);
456 sqlite3ExprListDelete(pParse->db, pRhs);
457 }
458
drh6f82e852015-06-06 20:12:09 +0000459 if( eType==IN_INDEX_INDEX_DESC ){
460 testcase( bRev );
461 bRev = !bRev;
462 }
463 iTab = pX->iTable;
464 sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
465 VdbeCoverageIf(v, bRev);
466 VdbeCoverageIf(v, !bRev);
467 assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
dan8da209b2016-07-26 18:06:08 +0000468
drh6f82e852015-06-06 20:12:09 +0000469 pLoop->wsFlags |= WHERE_IN_ABLE;
470 if( pLevel->u.in.nIn==0 ){
471 pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
472 }
dan8da209b2016-07-26 18:06:08 +0000473
474 i = pLevel->u.in.nIn;
475 pLevel->u.in.nIn += nEq;
drh6f82e852015-06-06 20:12:09 +0000476 pLevel->u.in.aInLoop =
477 sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
478 sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
479 pIn = pLevel->u.in.aInLoop;
480 if( pIn ){
dan8da209b2016-07-26 18:06:08 +0000481 int iMap = 0; /* Index in aiMap[] */
482 pIn += i;
483 for(i=iEq;i<pLoop->nLTerm; i++, pIn++){
484 if( pLoop->aLTerm[i]->pExpr==pX ){
485 if( eType==IN_INDEX_ROWID ){
486 assert( nEq==1 && i==iEq );
487 pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
488 }else{
489 int iCol = aiMap ? aiMap[iMap++] : 0;
490 int iOut = iReg + i - iEq;
491 pIn->addrInTop = sqlite3VdbeAddOp3(v,OP_Column,iTab, iCol, iOut);
492 }
493 if( i==iEq ){
494 pIn->iCur = iTab;
495 pIn->eEndLoopOp = bRev ? OP_PrevIfOpen : OP_NextIfOpen;
496 }else{
497 pIn->eEndLoopOp = OP_Noop;
498 }
499 }
500 sqlite3VdbeAddOp1(v, OP_IsNull, iReg); VdbeCoverage(v);
drh6f82e852015-06-06 20:12:09 +0000501 }
drh6f82e852015-06-06 20:12:09 +0000502 }else{
503 pLevel->u.in.nIn = 0;
504 }
dan8da209b2016-07-26 18:06:08 +0000505 sqlite3DbFree(pParse->db, aiMap);
drh6f82e852015-06-06 20:12:09 +0000506#endif
507 }
508 disableTerm(pLevel, pTerm);
509 return iReg;
510}
511
512/*
513** Generate code that will evaluate all == and IN constraints for an
514** index scan.
515**
516** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
517** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
518** The index has as many as three equality constraints, but in this
519** example, the third "c" value is an inequality. So only two
520** constraints are coded. This routine will generate code to evaluate
521** a==5 and b IN (1,2,3). The current values for a and b will be stored
522** in consecutive registers and the index of the first register is returned.
523**
524** In the example above nEq==2. But this subroutine works for any value
525** of nEq including 0. If nEq==0, this routine is nearly a no-op.
526** The only thing it does is allocate the pLevel->iMem memory cell and
527** compute the affinity string.
528**
529** The nExtraReg parameter is 0 or 1. It is 0 if all WHERE clause constraints
530** are == or IN and are covered by the nEq. nExtraReg is 1 if there is
531** an inequality constraint (such as the "c>=5 AND c<10" in the example) that
532** occurs after the nEq quality constraints.
533**
534** This routine allocates a range of nEq+nExtraReg memory cells and returns
535** the index of the first memory cell in that range. The code that
536** calls this routine will use that memory range to store keys for
537** start and termination conditions of the loop.
538** key value of the loop. If one or more IN operators appear, then
539** this routine allocates an additional nEq memory cells for internal
540** use.
541**
542** Before returning, *pzAff is set to point to a buffer containing a
543** copy of the column affinity string of the index allocated using
544** sqlite3DbMalloc(). Except, entries in the copy of the string associated
545** with equality constraints that use BLOB or NONE affinity are set to
546** SQLITE_AFF_BLOB. This is to deal with SQL such as the following:
547**
548** CREATE TABLE t1(a TEXT PRIMARY KEY, b);
549** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
550**
551** In the example above, the index on t1(a) has TEXT affinity. But since
552** the right hand side of the equality constraint (t2.b) has BLOB/NONE affinity,
553** no conversion should be attempted before using a t2.b value as part of
554** a key to search the index. Hence the first byte in the returned affinity
555** string in this example would be set to SQLITE_AFF_BLOB.
556*/
557static int codeAllEqualityTerms(
558 Parse *pParse, /* Parsing context */
559 WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
560 int bRev, /* Reverse the order of IN operators */
561 int nExtraReg, /* Number of extra registers to allocate */
562 char **pzAff /* OUT: Set to point to affinity string */
563){
564 u16 nEq; /* The number of == or IN constraints to code */
565 u16 nSkip; /* Number of left-most columns to skip */
566 Vdbe *v = pParse->pVdbe; /* The vm under construction */
567 Index *pIdx; /* The index being used for this loop */
568 WhereTerm *pTerm; /* A single constraint term */
569 WhereLoop *pLoop; /* The WhereLoop object */
570 int j; /* Loop counter */
571 int regBase; /* Base register */
572 int nReg; /* Number of registers to allocate */
573 char *zAff; /* Affinity string to return */
574
575 /* This module is only called on query plans that use an index. */
576 pLoop = pLevel->pWLoop;
577 assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
578 nEq = pLoop->u.btree.nEq;
579 nSkip = pLoop->nSkip;
580 pIdx = pLoop->u.btree.pIndex;
581 assert( pIdx!=0 );
582
583 /* Figure out how many memory cells we will need then allocate them.
584 */
585 regBase = pParse->nMem + 1;
586 nReg = pLoop->u.btree.nEq + nExtraReg;
587 pParse->nMem += nReg;
588
drhe9107692015-08-25 19:20:04 +0000589 zAff = sqlite3DbStrDup(pParse->db,sqlite3IndexAffinityStr(pParse->db,pIdx));
drh4df86af2016-02-04 11:48:00 +0000590 assert( zAff!=0 || pParse->db->mallocFailed );
drh6f82e852015-06-06 20:12:09 +0000591
592 if( nSkip ){
593 int iIdxCur = pLevel->iIdxCur;
594 sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur);
595 VdbeCoverageIf(v, bRev==0);
596 VdbeCoverageIf(v, bRev!=0);
597 VdbeComment((v, "begin skip-scan on %s", pIdx->zName));
598 j = sqlite3VdbeAddOp0(v, OP_Goto);
599 pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT),
600 iIdxCur, 0, regBase, nSkip);
601 VdbeCoverageIf(v, bRev==0);
602 VdbeCoverageIf(v, bRev!=0);
603 sqlite3VdbeJumpHere(v, j);
604 for(j=0; j<nSkip; j++){
605 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, j, regBase+j);
drh4b92f982015-09-29 17:20:14 +0000606 testcase( pIdx->aiColumn[j]==XN_EXPR );
drhe63e8a62015-09-18 18:09:28 +0000607 VdbeComment((v, "%s", explainIndexColumnName(pIdx, j)));
drh6f82e852015-06-06 20:12:09 +0000608 }
609 }
610
611 /* Evaluate the equality constraints
612 */
613 assert( zAff==0 || (int)strlen(zAff)>=nEq );
614 for(j=nSkip; j<nEq; j++){
615 int r1;
616 pTerm = pLoop->aLTerm[j];
617 assert( pTerm!=0 );
618 /* The following testcase is true for indices with redundant columns.
619 ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
620 testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
621 testcase( pTerm->wtFlags & TERM_VIRTUAL );
622 r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
623 if( r1!=regBase+j ){
624 if( nReg==1 ){
625 sqlite3ReleaseTempReg(pParse, regBase);
626 regBase = r1;
627 }else{
628 sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
629 }
630 }
631 testcase( pTerm->eOperator & WO_ISNULL );
632 testcase( pTerm->eOperator & WO_IN );
633 if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
634 Expr *pRight = pTerm->pExpr->pRight;
635 if( (pTerm->wtFlags & TERM_IS)==0 && sqlite3ExprCanBeNull(pRight) ){
636 sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk);
637 VdbeCoverage(v);
638 }
639 if( zAff ){
640 if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_BLOB ){
641 zAff[j] = SQLITE_AFF_BLOB;
642 }
643 if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
644 zAff[j] = SQLITE_AFF_BLOB;
645 }
646 }
647 }
648 }
649 *pzAff = zAff;
650 return regBase;
651}
652
drh41d2e662015-12-01 21:23:07 +0000653#ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
drh6f82e852015-06-06 20:12:09 +0000654/*
drh44aebff2016-05-02 10:25:42 +0000655** If the most recently coded instruction is a constant range constraint
656** (a string literal) that originated from the LIKE optimization, then
657** set P3 and P5 on the OP_String opcode so that the string will be cast
658** to a BLOB at appropriate times.
drh6f82e852015-06-06 20:12:09 +0000659**
660** The LIKE optimization trys to evaluate "x LIKE 'abc%'" as a range
661** expression: "x>='ABC' AND x<'abd'". But this requires that the range
662** scan loop run twice, once for strings and a second time for BLOBs.
663** The OP_String opcodes on the second pass convert the upper and lower
mistachkine234cfd2016-07-10 19:35:10 +0000664** bound string constants to blobs. This routine makes the necessary changes
drh6f82e852015-06-06 20:12:09 +0000665** to the OP_String opcodes for that to happen.
drh41d2e662015-12-01 21:23:07 +0000666**
667** Except, of course, if SQLITE_LIKE_DOESNT_MATCH_BLOBS is defined, then
668** only the one pass through the string space is required, so this routine
669** becomes a no-op.
drh6f82e852015-06-06 20:12:09 +0000670*/
671static void whereLikeOptimizationStringFixup(
672 Vdbe *v, /* prepared statement under construction */
673 WhereLevel *pLevel, /* The loop that contains the LIKE operator */
674 WhereTerm *pTerm /* The upper or lower bound just coded */
675){
676 if( pTerm->wtFlags & TERM_LIKEOPT ){
677 VdbeOp *pOp;
678 assert( pLevel->iLikeRepCntr>0 );
679 pOp = sqlite3VdbeGetOp(v, -1);
680 assert( pOp!=0 );
681 assert( pOp->opcode==OP_String8
682 || pTerm->pWC->pWInfo->pParse->db->mallocFailed );
drh44aebff2016-05-02 10:25:42 +0000683 pOp->p3 = (int)(pLevel->iLikeRepCntr>>1); /* Register holding counter */
684 pOp->p5 = (u8)(pLevel->iLikeRepCntr&1); /* ASC or DESC */
drh6f82e852015-06-06 20:12:09 +0000685 }
686}
drh41d2e662015-12-01 21:23:07 +0000687#else
688# define whereLikeOptimizationStringFixup(A,B,C)
689#endif
drh6f82e852015-06-06 20:12:09 +0000690
drhbec24762015-08-13 20:07:13 +0000691#ifdef SQLITE_ENABLE_CURSOR_HINTS
drh2f2b0272015-08-14 18:50:04 +0000692/*
693** Information is passed from codeCursorHint() down to individual nodes of
694** the expression tree (by sqlite3WalkExpr()) using an instance of this
695** structure.
696*/
697struct CCurHint {
698 int iTabCur; /* Cursor for the main table */
699 int iIdxCur; /* Cursor for the index, if pIdx!=0. Unused otherwise */
700 Index *pIdx; /* The index used to access the table */
701};
702
703/*
704** This function is called for every node of an expression that is a candidate
705** for a cursor hint on an index cursor. For TK_COLUMN nodes that reference
706** the table CCurHint.iTabCur, verify that the same column can be
707** accessed through the index. If it cannot, then set pWalker->eCode to 1.
708*/
709static int codeCursorHintCheckExpr(Walker *pWalker, Expr *pExpr){
710 struct CCurHint *pHint = pWalker->u.pCCurHint;
711 assert( pHint->pIdx!=0 );
712 if( pExpr->op==TK_COLUMN
713 && pExpr->iTable==pHint->iTabCur
714 && sqlite3ColumnOfIndex(pHint->pIdx, pExpr->iColumn)<0
715 ){
716 pWalker->eCode = 1;
717 }
718 return WRC_Continue;
719}
720
dane6912fd2016-06-17 19:27:13 +0000721/*
722** Test whether or not expression pExpr, which was part of a WHERE clause,
723** should be included in the cursor-hint for a table that is on the rhs
724** of a LEFT JOIN. Set Walker.eCode to non-zero before returning if the
725** expression is not suitable.
726**
727** An expression is unsuitable if it might evaluate to non NULL even if
728** a TK_COLUMN node that does affect the value of the expression is set
729** to NULL. For example:
730**
731** col IS NULL
732** col IS NOT NULL
733** coalesce(col, 1)
734** CASE WHEN col THEN 0 ELSE 1 END
735*/
736static int codeCursorHintIsOrFunction(Walker *pWalker, Expr *pExpr){
dan2b693d62016-06-20 17:22:06 +0000737 if( pExpr->op==TK_IS
dane6912fd2016-06-17 19:27:13 +0000738 || pExpr->op==TK_ISNULL || pExpr->op==TK_ISNOT
739 || pExpr->op==TK_NOTNULL || pExpr->op==TK_CASE
740 ){
741 pWalker->eCode = 1;
dan2b693d62016-06-20 17:22:06 +0000742 }else if( pExpr->op==TK_FUNCTION ){
743 int d1;
744 char d2[3];
745 if( 0==sqlite3IsLikeFunction(pWalker->pParse->db, pExpr, &d1, d2) ){
746 pWalker->eCode = 1;
747 }
dane6912fd2016-06-17 19:27:13 +0000748 }
dan2b693d62016-06-20 17:22:06 +0000749
dane6912fd2016-06-17 19:27:13 +0000750 return WRC_Continue;
751}
752
drhbec24762015-08-13 20:07:13 +0000753
754/*
755** This function is called on every node of an expression tree used as an
756** argument to the OP_CursorHint instruction. If the node is a TK_COLUMN
drh2f2b0272015-08-14 18:50:04 +0000757** that accesses any table other than the one identified by
758** CCurHint.iTabCur, then do the following:
drhbec24762015-08-13 20:07:13 +0000759**
760** 1) allocate a register and code an OP_Column instruction to read
761** the specified column into the new register, and
762**
763** 2) transform the expression node to a TK_REGISTER node that reads
764** from the newly populated register.
drh2f2b0272015-08-14 18:50:04 +0000765**
766** Also, if the node is a TK_COLUMN that does access the table idenified
767** by pCCurHint.iTabCur, and an index is being used (which we will
768** know because CCurHint.pIdx!=0) then transform the TK_COLUMN into
769** an access of the index rather than the original table.
drhbec24762015-08-13 20:07:13 +0000770*/
771static int codeCursorHintFixExpr(Walker *pWalker, Expr *pExpr){
772 int rc = WRC_Continue;
drh2f2b0272015-08-14 18:50:04 +0000773 struct CCurHint *pHint = pWalker->u.pCCurHint;
774 if( pExpr->op==TK_COLUMN ){
775 if( pExpr->iTable!=pHint->iTabCur ){
776 Vdbe *v = pWalker->pParse->pVdbe;
777 int reg = ++pWalker->pParse->nMem; /* Register for column value */
778 sqlite3ExprCodeGetColumnOfTable(
779 v, pExpr->pTab, pExpr->iTable, pExpr->iColumn, reg
780 );
781 pExpr->op = TK_REGISTER;
782 pExpr->iTable = reg;
783 }else if( pHint->pIdx!=0 ){
784 pExpr->iTable = pHint->iIdxCur;
785 pExpr->iColumn = sqlite3ColumnOfIndex(pHint->pIdx, pExpr->iColumn);
786 assert( pExpr->iColumn>=0 );
787 }
drhbec24762015-08-13 20:07:13 +0000788 }else if( pExpr->op==TK_AGG_FUNCTION ){
789 /* An aggregate function in the WHERE clause of a query means this must
790 ** be a correlated sub-query, and expression pExpr is an aggregate from
791 ** the parent context. Do not walk the function arguments in this case.
792 **
793 ** todo: It should be possible to replace this node with a TK_REGISTER
794 ** expression, as the result of the expression must be stored in a
795 ** register at this point. The same holds for TK_AGG_COLUMN nodes. */
796 rc = WRC_Prune;
797 }
798 return rc;
799}
800
801/*
802** Insert an OP_CursorHint instruction if it is appropriate to do so.
803*/
804static void codeCursorHint(
danb324cf72016-06-17 14:33:32 +0000805 struct SrcList_item *pTabItem, /* FROM clause item */
drhb413a542015-08-17 17:19:28 +0000806 WhereInfo *pWInfo, /* The where clause */
807 WhereLevel *pLevel, /* Which loop to provide hints for */
808 WhereTerm *pEndRange /* Hint this end-of-scan boundary term if not NULL */
drhbec24762015-08-13 20:07:13 +0000809){
810 Parse *pParse = pWInfo->pParse;
811 sqlite3 *db = pParse->db;
812 Vdbe *v = pParse->pVdbe;
drhbec24762015-08-13 20:07:13 +0000813 Expr *pExpr = 0;
drh2f2b0272015-08-14 18:50:04 +0000814 WhereLoop *pLoop = pLevel->pWLoop;
drhbec24762015-08-13 20:07:13 +0000815 int iCur;
816 WhereClause *pWC;
817 WhereTerm *pTerm;
drhb413a542015-08-17 17:19:28 +0000818 int i, j;
drh2f2b0272015-08-14 18:50:04 +0000819 struct CCurHint sHint;
820 Walker sWalker;
drhbec24762015-08-13 20:07:13 +0000821
822 if( OptimizationDisabled(db, SQLITE_CursorHints) ) return;
drh2f2b0272015-08-14 18:50:04 +0000823 iCur = pLevel->iTabCur;
824 assert( iCur==pWInfo->pTabList->a[pLevel->iFrom].iCursor );
825 sHint.iTabCur = iCur;
826 sHint.iIdxCur = pLevel->iIdxCur;
827 sHint.pIdx = pLoop->u.btree.pIndex;
828 memset(&sWalker, 0, sizeof(sWalker));
829 sWalker.pParse = pParse;
830 sWalker.u.pCCurHint = &sHint;
drhbec24762015-08-13 20:07:13 +0000831 pWC = &pWInfo->sWC;
832 for(i=0; i<pWC->nTerm; i++){
833 pTerm = &pWC->a[i];
834 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
835 if( pTerm->prereqAll & pLevel->notReady ) continue;
danb324cf72016-06-17 14:33:32 +0000836
837 /* Any terms specified as part of the ON(...) clause for any LEFT
838 ** JOIN for which the current table is not the rhs are omitted
839 ** from the cursor-hint.
840 **
dane6912fd2016-06-17 19:27:13 +0000841 ** If this table is the rhs of a LEFT JOIN, "IS" or "IS NULL" terms
842 ** that were specified as part of the WHERE clause must be excluded.
843 ** This is to address the following:
danb324cf72016-06-17 14:33:32 +0000844 **
845 ** SELECT ... t1 LEFT JOIN t2 ON (t1.a=t2.b) WHERE t2.c IS NULL;
846 **
dane6912fd2016-06-17 19:27:13 +0000847 ** Say there is a single row in t2 that matches (t1.a=t2.b), but its
848 ** t2.c values is not NULL. If the (t2.c IS NULL) constraint is
849 ** pushed down to the cursor, this row is filtered out, causing
850 ** SQLite to synthesize a row of NULL values. Which does match the
851 ** WHERE clause, and so the query returns a row. Which is incorrect.
852 **
853 ** For the same reason, WHERE terms such as:
854 **
855 ** WHERE 1 = (t2.c IS NULL)
856 **
857 ** are also excluded. See codeCursorHintIsOrFunction() for details.
danb324cf72016-06-17 14:33:32 +0000858 */
859 if( pTabItem->fg.jointype & JT_LEFT ){
dane6912fd2016-06-17 19:27:13 +0000860 Expr *pExpr = pTerm->pExpr;
861 if( !ExprHasProperty(pExpr, EP_FromJoin)
862 || pExpr->iRightJoinTable!=pTabItem->iCursor
danb324cf72016-06-17 14:33:32 +0000863 ){
dane6912fd2016-06-17 19:27:13 +0000864 sWalker.eCode = 0;
865 sWalker.xExprCallback = codeCursorHintIsOrFunction;
866 sqlite3WalkExpr(&sWalker, pTerm->pExpr);
867 if( sWalker.eCode ) continue;
danb324cf72016-06-17 14:33:32 +0000868 }
869 }else{
870 if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) continue;
871 }
drhb413a542015-08-17 17:19:28 +0000872
873 /* All terms in pWLoop->aLTerm[] except pEndRange are used to initialize
drhbcf40a72015-08-18 15:58:05 +0000874 ** the cursor. These terms are not needed as hints for a pure range
875 ** scan (that has no == terms) so omit them. */
876 if( pLoop->u.btree.nEq==0 && pTerm!=pEndRange ){
877 for(j=0; j<pLoop->nLTerm && pLoop->aLTerm[j]!=pTerm; j++){}
878 if( j<pLoop->nLTerm ) continue;
drhb413a542015-08-17 17:19:28 +0000879 }
880
881 /* No subqueries or non-deterministic functions allowed */
drhbec24762015-08-13 20:07:13 +0000882 if( sqlite3ExprContainsSubquery(pTerm->pExpr) ) continue;
drhb413a542015-08-17 17:19:28 +0000883
884 /* For an index scan, make sure referenced columns are actually in
885 ** the index. */
drh2f2b0272015-08-14 18:50:04 +0000886 if( sHint.pIdx!=0 ){
887 sWalker.eCode = 0;
888 sWalker.xExprCallback = codeCursorHintCheckExpr;
889 sqlite3WalkExpr(&sWalker, pTerm->pExpr);
890 if( sWalker.eCode ) continue;
891 }
drhb413a542015-08-17 17:19:28 +0000892
893 /* If we survive all prior tests, that means this term is worth hinting */
drhbec24762015-08-13 20:07:13 +0000894 pExpr = sqlite3ExprAnd(db, pExpr, sqlite3ExprDup(db, pTerm->pExpr, 0));
895 }
896 if( pExpr!=0 ){
drhbec24762015-08-13 20:07:13 +0000897 sWalker.xExprCallback = codeCursorHintFixExpr;
drhbec24762015-08-13 20:07:13 +0000898 sqlite3WalkExpr(&sWalker, pExpr);
drh2f2b0272015-08-14 18:50:04 +0000899 sqlite3VdbeAddOp4(v, OP_CursorHint,
900 (sHint.pIdx ? sHint.iIdxCur : sHint.iTabCur), 0, 0,
901 (const char*)pExpr, P4_EXPR);
drhbec24762015-08-13 20:07:13 +0000902 }
903}
904#else
danb324cf72016-06-17 14:33:32 +0000905# define codeCursorHint(A,B,C,D) /* No-op */
drhbec24762015-08-13 20:07:13 +0000906#endif /* SQLITE_ENABLE_CURSOR_HINTS */
drh6f82e852015-06-06 20:12:09 +0000907
908/*
dande892d92016-01-29 19:29:45 +0000909** Cursor iCur is open on an intkey b-tree (a table). Register iRowid contains
910** a rowid value just read from cursor iIdxCur, open on index pIdx. This
911** function generates code to do a deferred seek of cursor iCur to the
912** rowid stored in register iRowid.
913**
914** Normally, this is just:
915**
916** OP_Seek $iCur $iRowid
917**
918** However, if the scan currently being coded is a branch of an OR-loop and
919** the statement currently being coded is a SELECT, then P3 of the OP_Seek
920** is set to iIdxCur and P4 is set to point to an array of integers
921** containing one entry for each column of the table cursor iCur is open
922** on. For each table column, if the column is the i'th column of the
923** index, then the corresponding array entry is set to (i+1). If the column
924** does not appear in the index at all, the array entry is set to 0.
925*/
926static void codeDeferredSeek(
927 WhereInfo *pWInfo, /* Where clause context */
928 Index *pIdx, /* Index scan is using */
929 int iCur, /* Cursor for IPK b-tree */
dande892d92016-01-29 19:29:45 +0000930 int iIdxCur /* Index cursor */
931){
932 Parse *pParse = pWInfo->pParse; /* Parse context */
933 Vdbe *v = pParse->pVdbe; /* Vdbe to generate code within */
934
935 assert( iIdxCur>0 );
936 assert( pIdx->aiColumn[pIdx->nColumn-1]==-1 );
937
drh784c1b92016-01-30 16:59:56 +0000938 sqlite3VdbeAddOp3(v, OP_Seek, iIdxCur, 0, iCur);
drhce943bc2016-05-19 18:56:33 +0000939 if( (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)
dancddb6ba2016-02-01 13:58:56 +0000940 && DbMaskAllZero(sqlite3ParseToplevel(pParse)->writeMask)
dande892d92016-01-29 19:29:45 +0000941 ){
942 int i;
943 Table *pTab = pIdx->pTable;
drhb1702022016-01-30 00:45:18 +0000944 int *ai = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int)*(pTab->nCol+1));
dande892d92016-01-29 19:29:45 +0000945 if( ai ){
drhb1702022016-01-30 00:45:18 +0000946 ai[0] = pTab->nCol;
dande892d92016-01-29 19:29:45 +0000947 for(i=0; i<pIdx->nColumn-1; i++){
948 assert( pIdx->aiColumn[i]<pTab->nCol );
drhb1702022016-01-30 00:45:18 +0000949 if( pIdx->aiColumn[i]>=0 ) ai[pIdx->aiColumn[i]+1] = i+1;
dande892d92016-01-29 19:29:45 +0000950 }
951 sqlite3VdbeChangeP4(v, -1, (char*)ai, P4_INTARRAY);
952 }
953 }
954}
955
dan553168c2016-08-01 20:14:31 +0000956/*
957** If the expression passed as the second argument is a vector, generate
958** code to write the first nReg elements of the vector into an array
959** of registers starting with iReg.
960**
961** If the expression is not a vector, then nReg must be passed 1. In
962** this case, generate code to evaluate the expression and leave the
963** result in register iReg.
964*/
dan71c57db2016-07-09 20:23:55 +0000965static void codeExprOrVector(Parse *pParse, Expr *p, int iReg, int nReg){
966 assert( nReg>0 );
dan625015e2016-07-30 16:39:28 +0000967 if( sqlite3ExprIsVector(p) ){
danf9b2e052016-08-02 17:45:00 +0000968#ifndef SQLITE_OMIT_SUBQUERY
969 if( (p->flags & EP_xIsSelect) ){
970 Vdbe *v = pParse->pVdbe;
971 int iSelect = sqlite3CodeSubselect(pParse, p, 0, 0);
972 sqlite3VdbeAddOp3(v, OP_Copy, iSelect, iReg, nReg-1);
973 }else
974#endif
975 {
976 int i;
dan71c57db2016-07-09 20:23:55 +0000977 ExprList *pList = p->x.pList;
978 assert( nReg<=pList->nExpr );
979 for(i=0; i<nReg; i++){
980 sqlite3ExprCode(pParse, pList->a[i].pExpr, iReg+i);
981 }
dan71c57db2016-07-09 20:23:55 +0000982 }
983 }else{
984 assert( nReg==1 );
985 sqlite3ExprCode(pParse, p, iReg);
986 }
987}
988
dande892d92016-01-29 19:29:45 +0000989/*
drh6f82e852015-06-06 20:12:09 +0000990** Generate code for the start of the iLevel-th loop in the WHERE clause
991** implementation described by pWInfo.
992*/
993Bitmask sqlite3WhereCodeOneLoopStart(
994 WhereInfo *pWInfo, /* Complete information about the WHERE clause */
995 int iLevel, /* Which level of pWInfo->a[] should be coded */
996 Bitmask notReady /* Which tables are currently available */
997){
998 int j, k; /* Loop counters */
999 int iCur; /* The VDBE cursor for the table */
1000 int addrNxt; /* Where to jump to continue with the next IN case */
1001 int omitTable; /* True if we use the index only */
1002 int bRev; /* True if we need to scan in reverse order */
1003 WhereLevel *pLevel; /* The where level to be coded */
1004 WhereLoop *pLoop; /* The WhereLoop object being coded */
1005 WhereClause *pWC; /* Decomposition of the entire WHERE clause */
1006 WhereTerm *pTerm; /* A WHERE clause term */
1007 Parse *pParse; /* Parsing context */
1008 sqlite3 *db; /* Database connection */
1009 Vdbe *v; /* The prepared stmt under constructions */
1010 struct SrcList_item *pTabItem; /* FROM clause term being coded */
1011 int addrBrk; /* Jump here to break out of the loop */
1012 int addrCont; /* Jump here to continue with next cycle */
1013 int iRowidReg = 0; /* Rowid is stored in this register, if not zero */
1014 int iReleaseReg = 0; /* Temp register to free before returning */
1015
1016 pParse = pWInfo->pParse;
1017 v = pParse->pVdbe;
1018 pWC = &pWInfo->sWC;
1019 db = pParse->db;
1020 pLevel = &pWInfo->a[iLevel];
1021 pLoop = pLevel->pWLoop;
1022 pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
1023 iCur = pTabItem->iCursor;
1024 pLevel->notReady = notReady & ~sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur);
1025 bRev = (pWInfo->revMask>>iLevel)&1;
1026 omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
drhce943bc2016-05-19 18:56:33 +00001027 && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0;
drh6f82e852015-06-06 20:12:09 +00001028 VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName));
1029
1030 /* Create labels for the "break" and "continue" instructions
1031 ** for the current loop. Jump to addrBrk to break out of a loop.
1032 ** Jump to cont to go immediately to the next iteration of the
1033 ** loop.
1034 **
1035 ** When there is an IN operator, we also have a "addrNxt" label that
1036 ** means to continue with the next IN value combination. When
1037 ** there are no IN operators in the constraints, the "addrNxt" label
1038 ** is the same as "addrBrk".
1039 */
1040 addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
1041 addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
1042
1043 /* If this is the right table of a LEFT OUTER JOIN, allocate and
1044 ** initialize a memory cell that records if this table matches any
1045 ** row of the left table of the join.
1046 */
drh8a48b9c2015-08-19 15:20:00 +00001047 if( pLevel->iFrom>0 && (pTabItem[0].fg.jointype & JT_LEFT)!=0 ){
drh6f82e852015-06-06 20:12:09 +00001048 pLevel->iLeftJoin = ++pParse->nMem;
1049 sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
1050 VdbeComment((v, "init LEFT JOIN no-match flag"));
1051 }
1052
1053 /* Special case of a FROM clause subquery implemented as a co-routine */
drh8a48b9c2015-08-19 15:20:00 +00001054 if( pTabItem->fg.viaCoroutine ){
drh6f82e852015-06-06 20:12:09 +00001055 int regYield = pTabItem->regReturn;
1056 sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
1057 pLevel->p2 = sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk);
1058 VdbeCoverage(v);
1059 VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
1060 pLevel->op = OP_Goto;
1061 }else
1062
1063#ifndef SQLITE_OMIT_VIRTUALTABLE
1064 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
1065 /* Case 1: The table is a virtual-table. Use the VFilter and VNext
1066 ** to access the data.
1067 */
1068 int iReg; /* P3 Value for OP_VFilter */
1069 int addrNotFound;
1070 int nConstraint = pLoop->nLTerm;
drhdbc49162016-03-02 03:28:07 +00001071 int iIn; /* Counter for IN constraints */
drh6f82e852015-06-06 20:12:09 +00001072
1073 sqlite3ExprCachePush(pParse);
1074 iReg = sqlite3GetTempRange(pParse, nConstraint+2);
1075 addrNotFound = pLevel->addrBrk;
1076 for(j=0; j<nConstraint; j++){
1077 int iTarget = iReg+j+2;
1078 pTerm = pLoop->aLTerm[j];
drh599d5762016-03-08 01:11:51 +00001079 if( NEVER(pTerm==0) ) continue;
drh6f82e852015-06-06 20:12:09 +00001080 if( pTerm->eOperator & WO_IN ){
1081 codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
1082 addrNotFound = pLevel->addrNxt;
1083 }else{
1084 sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget);
1085 }
1086 }
1087 sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
1088 sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
1089 sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
1090 pLoop->u.vtab.idxStr,
1091 pLoop->u.vtab.needFree ? P4_MPRINTF : P4_STATIC);
1092 VdbeCoverage(v);
1093 pLoop->u.vtab.needFree = 0;
drh6f82e852015-06-06 20:12:09 +00001094 pLevel->p1 = iCur;
dan354474a2015-09-29 10:11:26 +00001095 pLevel->op = pWInfo->eOnePass ? OP_Noop : OP_VNext;
drh6f82e852015-06-06 20:12:09 +00001096 pLevel->p2 = sqlite3VdbeCurrentAddr(v);
drhdbc49162016-03-02 03:28:07 +00001097 iIn = pLevel->u.in.nIn;
1098 for(j=nConstraint-1; j>=0; j--){
1099 pTerm = pLoop->aLTerm[j];
1100 if( j<16 && (pLoop->u.vtab.omitMask>>j)&1 ){
1101 disableTerm(pLevel, pTerm);
1102 }else if( (pTerm->eOperator & WO_IN)!=0 ){
1103 Expr *pCompare; /* The comparison operator */
1104 Expr *pRight; /* RHS of the comparison */
1105 VdbeOp *pOp; /* Opcode to access the value of the IN constraint */
1106
1107 /* Reload the constraint value into reg[iReg+j+2]. The same value
1108 ** was loaded into the same register prior to the OP_VFilter, but
1109 ** the xFilter implementation might have changed the datatype or
1110 ** encoding of the value in the register, so it *must* be reloaded. */
1111 assert( pLevel->u.in.aInLoop!=0 || db->mallocFailed );
drhfb826b82016-03-08 00:39:58 +00001112 if( !db->mallocFailed ){
drhdbc49162016-03-02 03:28:07 +00001113 assert( iIn>0 );
1114 pOp = sqlite3VdbeGetOp(v, pLevel->u.in.aInLoop[--iIn].addrInTop);
1115 assert( pOp->opcode==OP_Column || pOp->opcode==OP_Rowid );
1116 assert( pOp->opcode!=OP_Column || pOp->p3==iReg+j+2 );
1117 assert( pOp->opcode!=OP_Rowid || pOp->p2==iReg+j+2 );
1118 testcase( pOp->opcode==OP_Rowid );
1119 sqlite3VdbeAddOp3(v, pOp->opcode, pOp->p1, pOp->p2, pOp->p3);
1120 }
1121
1122 /* Generate code that will continue to the next row if
1123 ** the IN constraint is not satisfied */
1124 pCompare = sqlite3PExpr(pParse, TK_EQ, 0, 0, 0);
1125 assert( pCompare!=0 || db->mallocFailed );
1126 if( pCompare ){
1127 pCompare->pLeft = pTerm->pExpr->pLeft;
1128 pCompare->pRight = pRight = sqlite3Expr(db, TK_REGISTER, 0);
drh237b2b72016-03-07 19:08:27 +00001129 if( pRight ){
1130 pRight->iTable = iReg+j+2;
1131 sqlite3ExprIfFalse(pParse, pCompare, pLevel->addrCont, 0);
1132 }
drhdbc49162016-03-02 03:28:07 +00001133 pCompare->pLeft = 0;
1134 sqlite3ExprDelete(db, pCompare);
1135 }
1136 }
1137 }
drhba26faa2016-04-09 18:04:28 +00001138 /* These registers need to be preserved in case there is an IN operator
1139 ** loop. So we could deallocate the registers here (and potentially
1140 ** reuse them later) if (pLoop->wsFlags & WHERE_IN_ABLE)==0. But it seems
1141 ** simpler and safer to simply not reuse the registers.
1142 **
1143 ** sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
1144 */
drh6f82e852015-06-06 20:12:09 +00001145 sqlite3ExprCachePop(pParse);
1146 }else
1147#endif /* SQLITE_OMIT_VIRTUALTABLE */
1148
1149 if( (pLoop->wsFlags & WHERE_IPK)!=0
1150 && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
1151 ){
1152 /* Case 2: We can directly reference a single row using an
1153 ** equality comparison against the ROWID field. Or
1154 ** we reference multiple rows using a "rowid IN (...)"
1155 ** construct.
1156 */
1157 assert( pLoop->u.btree.nEq==1 );
1158 pTerm = pLoop->aLTerm[0];
1159 assert( pTerm!=0 );
1160 assert( pTerm->pExpr!=0 );
1161 assert( omitTable==0 );
1162 testcase( pTerm->wtFlags & TERM_VIRTUAL );
1163 iReleaseReg = ++pParse->nMem;
1164 iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
1165 if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg);
1166 addrNxt = pLevel->addrNxt;
drheeb95652016-05-26 20:56:38 +00001167 sqlite3VdbeAddOp3(v, OP_SeekRowid, iCur, addrNxt, iRowidReg);
drh6f82e852015-06-06 20:12:09 +00001168 VdbeCoverage(v);
1169 sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
1170 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
1171 VdbeComment((v, "pk"));
1172 pLevel->op = OP_Noop;
1173 }else if( (pLoop->wsFlags & WHERE_IPK)!=0
1174 && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
1175 ){
1176 /* Case 3: We have an inequality comparison against the ROWID field.
1177 */
1178 int testOp = OP_Noop;
1179 int start;
1180 int memEndValue = 0;
1181 WhereTerm *pStart, *pEnd;
1182
1183 assert( omitTable==0 );
1184 j = 0;
1185 pStart = pEnd = 0;
1186 if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
1187 if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
1188 assert( pStart!=0 || pEnd!=0 );
1189 if( bRev ){
1190 pTerm = pStart;
1191 pStart = pEnd;
1192 pEnd = pTerm;
1193 }
danb324cf72016-06-17 14:33:32 +00001194 codeCursorHint(pTabItem, pWInfo, pLevel, pEnd);
drh6f82e852015-06-06 20:12:09 +00001195 if( pStart ){
1196 Expr *pX; /* The expression that defines the start bound */
1197 int r1, rTemp; /* Registers for holding the start boundary */
dan19ff12d2016-07-29 20:58:19 +00001198 int op; /* Cursor seek operation */
drh6f82e852015-06-06 20:12:09 +00001199
1200 /* The following constant maps TK_xx codes into corresponding
1201 ** seek opcodes. It depends on a particular ordering of TK_xx
1202 */
1203 const u8 aMoveOp[] = {
1204 /* TK_GT */ OP_SeekGT,
1205 /* TK_LE */ OP_SeekLE,
1206 /* TK_LT */ OP_SeekLT,
1207 /* TK_GE */ OP_SeekGE
1208 };
1209 assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */
1210 assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */
1211 assert( TK_GE==TK_GT+3 ); /* ... is correcct. */
1212
1213 assert( (pStart->wtFlags & TERM_VNULL)==0 );
1214 testcase( pStart->wtFlags & TERM_VIRTUAL );
1215 pX = pStart->pExpr;
1216 assert( pX!=0 );
1217 testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
dan625015e2016-07-30 16:39:28 +00001218 if( sqlite3ExprIsVector(pX->pRight) ){
dan19ff12d2016-07-29 20:58:19 +00001219 r1 = rTemp = sqlite3GetTempReg(pParse);
1220 codeExprOrVector(pParse, pX->pRight, r1, 1);
1221 op = aMoveOp[(pX->op - TK_GT) | 0x0001];
1222 }else{
1223 r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
1224 disableTerm(pLevel, pStart);
1225 op = aMoveOp[(pX->op - TK_GT)];
1226 }
1227 sqlite3VdbeAddOp3(v, op, iCur, addrBrk, r1);
drh6f82e852015-06-06 20:12:09 +00001228 VdbeComment((v, "pk"));
1229 VdbeCoverageIf(v, pX->op==TK_GT);
1230 VdbeCoverageIf(v, pX->op==TK_LE);
1231 VdbeCoverageIf(v, pX->op==TK_LT);
1232 VdbeCoverageIf(v, pX->op==TK_GE);
1233 sqlite3ExprCacheAffinityChange(pParse, r1, 1);
1234 sqlite3ReleaseTempReg(pParse, rTemp);
drh6f82e852015-06-06 20:12:09 +00001235 }else{
1236 sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
1237 VdbeCoverageIf(v, bRev==0);
1238 VdbeCoverageIf(v, bRev!=0);
1239 }
1240 if( pEnd ){
1241 Expr *pX;
1242 pX = pEnd->pExpr;
1243 assert( pX!=0 );
1244 assert( (pEnd->wtFlags & TERM_VNULL)==0 );
1245 testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
1246 testcase( pEnd->wtFlags & TERM_VIRTUAL );
1247 memEndValue = ++pParse->nMem;
dan19ff12d2016-07-29 20:58:19 +00001248 codeExprOrVector(pParse, pX->pRight, memEndValue, 1);
dan625015e2016-07-30 16:39:28 +00001249 if( 0==sqlite3ExprIsVector(pX->pRight)
1250 && (pX->op==TK_LT || pX->op==TK_GT)
1251 ){
drh6f82e852015-06-06 20:12:09 +00001252 testOp = bRev ? OP_Le : OP_Ge;
1253 }else{
1254 testOp = bRev ? OP_Lt : OP_Gt;
1255 }
dan553168c2016-08-01 20:14:31 +00001256 if( 0==sqlite3ExprIsVector(pX->pRight) ){
1257 disableTerm(pLevel, pEnd);
1258 }
drh6f82e852015-06-06 20:12:09 +00001259 }
1260 start = sqlite3VdbeCurrentAddr(v);
1261 pLevel->op = bRev ? OP_Prev : OP_Next;
1262 pLevel->p1 = iCur;
1263 pLevel->p2 = start;
1264 assert( pLevel->p5==0 );
1265 if( testOp!=OP_Noop ){
1266 iRowidReg = ++pParse->nMem;
1267 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
1268 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
1269 sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
1270 VdbeCoverageIf(v, testOp==OP_Le);
1271 VdbeCoverageIf(v, testOp==OP_Lt);
1272 VdbeCoverageIf(v, testOp==OP_Ge);
1273 VdbeCoverageIf(v, testOp==OP_Gt);
1274 sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
1275 }
1276 }else if( pLoop->wsFlags & WHERE_INDEXED ){
1277 /* Case 4: A scan using an index.
1278 **
1279 ** The WHERE clause may contain zero or more equality
1280 ** terms ("==" or "IN" operators) that refer to the N
1281 ** left-most columns of the index. It may also contain
1282 ** inequality constraints (>, <, >= or <=) on the indexed
1283 ** column that immediately follows the N equalities. Only
1284 ** the right-most column can be an inequality - the rest must
1285 ** use the "==" and "IN" operators. For example, if the
1286 ** index is on (x,y,z), then the following clauses are all
1287 ** optimized:
1288 **
1289 ** x=5
1290 ** x=5 AND y=10
1291 ** x=5 AND y<10
1292 ** x=5 AND y>5 AND y<10
1293 ** x=5 AND y=5 AND z<=10
1294 **
1295 ** The z<10 term of the following cannot be used, only
1296 ** the x=5 term:
1297 **
1298 ** x=5 AND z<10
1299 **
1300 ** N may be zero if there are inequality constraints.
1301 ** If there are no inequality constraints, then N is at
1302 ** least one.
1303 **
1304 ** This case is also used when there are no WHERE clause
1305 ** constraints but an index is selected anyway, in order
1306 ** to force the output order to conform to an ORDER BY.
1307 */
1308 static const u8 aStartOp[] = {
1309 0,
1310 0,
1311 OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */
1312 OP_Last, /* 3: (!start_constraints && startEq && bRev) */
1313 OP_SeekGT, /* 4: (start_constraints && !startEq && !bRev) */
1314 OP_SeekLT, /* 5: (start_constraints && !startEq && bRev) */
1315 OP_SeekGE, /* 6: (start_constraints && startEq && !bRev) */
1316 OP_SeekLE /* 7: (start_constraints && startEq && bRev) */
1317 };
1318 static const u8 aEndOp[] = {
1319 OP_IdxGE, /* 0: (end_constraints && !bRev && !endEq) */
1320 OP_IdxGT, /* 1: (end_constraints && !bRev && endEq) */
1321 OP_IdxLE, /* 2: (end_constraints && bRev && !endEq) */
1322 OP_IdxLT, /* 3: (end_constraints && bRev && endEq) */
1323 };
1324 u16 nEq = pLoop->u.btree.nEq; /* Number of == or IN terms */
dan71c57db2016-07-09 20:23:55 +00001325 u16 nBtm = pLoop->u.btree.nBtm; /* Length of BTM vector */
1326 u16 nTop = pLoop->u.btree.nTop; /* Length of TOP vector */
drh6f82e852015-06-06 20:12:09 +00001327 int regBase; /* Base register holding constraint values */
1328 WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */
1329 WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */
1330 int startEq; /* True if range start uses ==, >= or <= */
1331 int endEq; /* True if range end uses ==, >= or <= */
1332 int start_constraints; /* Start of range is constrained */
1333 int nConstraint; /* Number of constraint terms */
1334 Index *pIdx; /* The index we will be using */
1335 int iIdxCur; /* The VDBE cursor for the index */
1336 int nExtraReg = 0; /* Number of extra registers needed */
1337 int op; /* Instruction opcode */
1338 char *zStartAff; /* Affinity for start of range constraint */
1339 char cEndAff = 0; /* Affinity for end of range constraint */
1340 u8 bSeekPastNull = 0; /* True to seek past initial nulls */
1341 u8 bStopAtNull = 0; /* Add condition to terminate at NULLs */
1342
1343 pIdx = pLoop->u.btree.pIndex;
1344 iIdxCur = pLevel->iIdxCur;
1345 assert( nEq>=pLoop->nSkip );
1346
1347 /* If this loop satisfies a sort order (pOrderBy) request that
1348 ** was passed to this function to implement a "SELECT min(x) ..."
1349 ** query, then the caller will only allow the loop to run for
1350 ** a single iteration. This means that the first row returned
1351 ** should not have a NULL value stored in 'x'. If column 'x' is
1352 ** the first one after the nEq equality constraints in the index,
1353 ** this requires some special handling.
1354 */
1355 assert( pWInfo->pOrderBy==0
1356 || pWInfo->pOrderBy->nExpr==1
1357 || (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0 );
1358 if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
1359 && pWInfo->nOBSat>0
1360 && (pIdx->nKeyCol>nEq)
1361 ){
1362 assert( pLoop->nSkip==0 );
1363 bSeekPastNull = 1;
1364 nExtraReg = 1;
1365 }
1366
1367 /* Find any inequality constraint terms for the start and end
1368 ** of the range.
1369 */
1370 j = nEq;
1371 if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
1372 pRangeStart = pLoop->aLTerm[j++];
dan71c57db2016-07-09 20:23:55 +00001373 nExtraReg = MAX(nExtraReg, pLoop->u.btree.nBtm);
drh6f82e852015-06-06 20:12:09 +00001374 /* Like optimization range constraints always occur in pairs */
1375 assert( (pRangeStart->wtFlags & TERM_LIKEOPT)==0 ||
1376 (pLoop->wsFlags & WHERE_TOP_LIMIT)!=0 );
1377 }
1378 if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
1379 pRangeEnd = pLoop->aLTerm[j++];
dan71c57db2016-07-09 20:23:55 +00001380 nExtraReg = MAX(nExtraReg, pLoop->u.btree.nTop);
drh41d2e662015-12-01 21:23:07 +00001381#ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
drh6f82e852015-06-06 20:12:09 +00001382 if( (pRangeEnd->wtFlags & TERM_LIKEOPT)!=0 ){
1383 assert( pRangeStart!=0 ); /* LIKE opt constraints */
1384 assert( pRangeStart->wtFlags & TERM_LIKEOPT ); /* occur in pairs */
drh44aebff2016-05-02 10:25:42 +00001385 pLevel->iLikeRepCntr = (u32)++pParse->nMem;
1386 sqlite3VdbeAddOp2(v, OP_Integer, 1, (int)pLevel->iLikeRepCntr);
drh6f82e852015-06-06 20:12:09 +00001387 VdbeComment((v, "LIKE loop counter"));
1388 pLevel->addrLikeRep = sqlite3VdbeCurrentAddr(v);
drh44aebff2016-05-02 10:25:42 +00001389 /* iLikeRepCntr actually stores 2x the counter register number. The
1390 ** bottom bit indicates whether the search order is ASC or DESC. */
1391 testcase( bRev );
1392 testcase( pIdx->aSortOrder[nEq]==SQLITE_SO_DESC );
1393 assert( (bRev & ~1)==0 );
1394 pLevel->iLikeRepCntr <<=1;
1395 pLevel->iLikeRepCntr |= bRev ^ (pIdx->aSortOrder[nEq]==SQLITE_SO_DESC);
drh6f82e852015-06-06 20:12:09 +00001396 }
drh41d2e662015-12-01 21:23:07 +00001397#endif
drh6f82e852015-06-06 20:12:09 +00001398 if( pRangeStart==0
1399 && (j = pIdx->aiColumn[nEq])>=0
1400 && pIdx->pTable->aCol[j].notNull==0
1401 ){
1402 bSeekPastNull = 1;
1403 }
1404 }
1405 assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 );
1406
drh6f82e852015-06-06 20:12:09 +00001407 /* If we are doing a reverse order scan on an ascending index, or
1408 ** a forward order scan on a descending index, interchange the
1409 ** start and end terms (pRangeStart and pRangeEnd).
1410 */
1411 if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
1412 || (bRev && pIdx->nKeyCol==nEq)
1413 ){
1414 SWAP(WhereTerm *, pRangeEnd, pRangeStart);
1415 SWAP(u8, bSeekPastNull, bStopAtNull);
dan71c57db2016-07-09 20:23:55 +00001416 SWAP(u8, nBtm, nTop);
drh6f82e852015-06-06 20:12:09 +00001417 }
1418
drhbcf40a72015-08-18 15:58:05 +00001419 /* Generate code to evaluate all constraint terms using == or IN
1420 ** and store the values of those terms in an array of registers
1421 ** starting at regBase.
1422 */
danb324cf72016-06-17 14:33:32 +00001423 codeCursorHint(pTabItem, pWInfo, pLevel, pRangeEnd);
drhbcf40a72015-08-18 15:58:05 +00001424 regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
1425 assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq );
1426 if( zStartAff ) cEndAff = zStartAff[nEq];
1427 addrNxt = pLevel->addrNxt;
1428
drh6f82e852015-06-06 20:12:09 +00001429 testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
1430 testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
1431 testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
1432 testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
1433 startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
1434 endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
1435 start_constraints = pRangeStart || nEq>0;
1436
1437 /* Seek the index cursor to the start of the range. */
1438 nConstraint = nEq;
1439 if( pRangeStart ){
1440 Expr *pRight = pRangeStart->pExpr->pRight;
dan71c57db2016-07-09 20:23:55 +00001441 codeExprOrVector(pParse, pRight, regBase+nEq, nBtm);
drh6f82e852015-06-06 20:12:09 +00001442 whereLikeOptimizationStringFixup(v, pLevel, pRangeStart);
1443 if( (pRangeStart->wtFlags & TERM_VNULL)==0
1444 && sqlite3ExprCanBeNull(pRight)
1445 ){
1446 sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
1447 VdbeCoverage(v);
1448 }
1449 if( zStartAff ){
1450 if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_BLOB){
1451 /* Since the comparison is to be performed with no conversions
1452 ** applied to the operands, set the affinity to apply to pRight to
1453 ** SQLITE_AFF_BLOB. */
1454 zStartAff[nEq] = SQLITE_AFF_BLOB;
1455 }
1456 if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
1457 zStartAff[nEq] = SQLITE_AFF_BLOB;
1458 }
1459 }
dan71c57db2016-07-09 20:23:55 +00001460 nConstraint += nBtm;
drh6f82e852015-06-06 20:12:09 +00001461 testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
dan625015e2016-07-30 16:39:28 +00001462 if( sqlite3ExprIsVector(pRight)==0 ){
dan71c57db2016-07-09 20:23:55 +00001463 disableTerm(pLevel, pRangeStart);
1464 }else{
1465 startEq = 1;
1466 }
drh426f4ab2016-07-26 04:31:14 +00001467 bSeekPastNull = 0;
drh6f82e852015-06-06 20:12:09 +00001468 }else if( bSeekPastNull ){
1469 sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
1470 nConstraint++;
1471 startEq = 0;
1472 start_constraints = 1;
1473 }
1474 codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff);
drh0bf2ad62016-02-22 21:19:54 +00001475 if( pLoop->nSkip>0 && nConstraint==pLoop->nSkip ){
1476 /* The skip-scan logic inside the call to codeAllEqualityConstraints()
1477 ** above has already left the cursor sitting on the correct row,
1478 ** so no further seeking is needed */
1479 }else{
drha6d2f8e2016-02-22 20:52:26 +00001480 op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
1481 assert( op!=0 );
1482 sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
1483 VdbeCoverage(v);
1484 VdbeCoverageIf(v, op==OP_Rewind); testcase( op==OP_Rewind );
1485 VdbeCoverageIf(v, op==OP_Last); testcase( op==OP_Last );
1486 VdbeCoverageIf(v, op==OP_SeekGT); testcase( op==OP_SeekGT );
1487 VdbeCoverageIf(v, op==OP_SeekGE); testcase( op==OP_SeekGE );
1488 VdbeCoverageIf(v, op==OP_SeekLE); testcase( op==OP_SeekLE );
1489 VdbeCoverageIf(v, op==OP_SeekLT); testcase( op==OP_SeekLT );
1490 }
drh0bf2ad62016-02-22 21:19:54 +00001491
drh6f82e852015-06-06 20:12:09 +00001492 /* Load the value for the inequality constraint at the end of the
1493 ** range (if any).
1494 */
1495 nConstraint = nEq;
1496 if( pRangeEnd ){
1497 Expr *pRight = pRangeEnd->pExpr->pRight;
1498 sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
dan71c57db2016-07-09 20:23:55 +00001499 codeExprOrVector(pParse, pRight, regBase+nEq, nTop);
drh6f82e852015-06-06 20:12:09 +00001500 whereLikeOptimizationStringFixup(v, pLevel, pRangeEnd);
1501 if( (pRangeEnd->wtFlags & TERM_VNULL)==0
1502 && sqlite3ExprCanBeNull(pRight)
1503 ){
1504 sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
1505 VdbeCoverage(v);
1506 }
1507 if( sqlite3CompareAffinity(pRight, cEndAff)!=SQLITE_AFF_BLOB
1508 && !sqlite3ExprNeedsNoAffinityChange(pRight, cEndAff)
1509 ){
1510 codeApplyAffinity(pParse, regBase+nEq, 1, &cEndAff);
1511 }
dan71c57db2016-07-09 20:23:55 +00001512 nConstraint += nTop;
drh6f82e852015-06-06 20:12:09 +00001513 testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
dan71c57db2016-07-09 20:23:55 +00001514
dan625015e2016-07-30 16:39:28 +00001515 if( sqlite3ExprIsVector(pRight)==0 ){
dan71c57db2016-07-09 20:23:55 +00001516 disableTerm(pLevel, pRangeEnd);
1517 }else{
1518 endEq = 1;
1519 }
drh6f82e852015-06-06 20:12:09 +00001520 }else if( bStopAtNull ){
1521 sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
1522 endEq = 0;
1523 nConstraint++;
1524 }
1525 sqlite3DbFree(db, zStartAff);
1526
1527 /* Top of the loop body */
1528 pLevel->p2 = sqlite3VdbeCurrentAddr(v);
1529
1530 /* Check if the index cursor is past the end of the range. */
1531 if( nConstraint ){
1532 op = aEndOp[bRev*2 + endEq];
1533 sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
1534 testcase( op==OP_IdxGT ); VdbeCoverageIf(v, op==OP_IdxGT );
1535 testcase( op==OP_IdxGE ); VdbeCoverageIf(v, op==OP_IdxGE );
1536 testcase( op==OP_IdxLT ); VdbeCoverageIf(v, op==OP_IdxLT );
1537 testcase( op==OP_IdxLE ); VdbeCoverageIf(v, op==OP_IdxLE );
1538 }
1539
1540 /* Seek the table cursor, if required */
drh6f82e852015-06-06 20:12:09 +00001541 if( omitTable ){
1542 /* pIdx is a covering index. No need to access the main table. */
1543 }else if( HasRowid(pIdx->pTable) ){
drhf09c4822016-05-06 20:23:12 +00001544 if( (pWInfo->wctrlFlags & WHERE_SEEK_TABLE)!=0 ){
drh784c1b92016-01-30 16:59:56 +00001545 iRowidReg = ++pParse->nMem;
1546 sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
1547 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
danc6157e12015-09-14 09:23:47 +00001548 sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, iRowidReg);
drh66336f32015-09-14 14:08:25 +00001549 VdbeCoverage(v);
danc6157e12015-09-14 09:23:47 +00001550 }else{
drh784c1b92016-01-30 16:59:56 +00001551 codeDeferredSeek(pWInfo, pIdx, iCur, iIdxCur);
danc6157e12015-09-14 09:23:47 +00001552 }
drh6f82e852015-06-06 20:12:09 +00001553 }else if( iCur!=iIdxCur ){
1554 Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
1555 iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol);
1556 for(j=0; j<pPk->nKeyCol; j++){
1557 k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
1558 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j);
1559 }
1560 sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont,
1561 iRowidReg, pPk->nKeyCol); VdbeCoverage(v);
1562 }
1563
dan71c57db2016-07-09 20:23:55 +00001564 /* Record the instruction used to terminate the loop. */
drh6f82e852015-06-06 20:12:09 +00001565 if( pLoop->wsFlags & WHERE_ONEROW ){
1566 pLevel->op = OP_Noop;
1567 }else if( bRev ){
1568 pLevel->op = OP_Prev;
1569 }else{
1570 pLevel->op = OP_Next;
1571 }
1572 pLevel->p1 = iIdxCur;
1573 pLevel->p3 = (pLoop->wsFlags&WHERE_UNQ_WANTED)!=0 ? 1:0;
1574 if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
1575 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
1576 }else{
1577 assert( pLevel->p5==0 );
1578 }
1579 }else
1580
1581#ifndef SQLITE_OMIT_OR_OPTIMIZATION
1582 if( pLoop->wsFlags & WHERE_MULTI_OR ){
1583 /* Case 5: Two or more separately indexed terms connected by OR
1584 **
1585 ** Example:
1586 **
1587 ** CREATE TABLE t1(a,b,c,d);
1588 ** CREATE INDEX i1 ON t1(a);
1589 ** CREATE INDEX i2 ON t1(b);
1590 ** CREATE INDEX i3 ON t1(c);
1591 **
1592 ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
1593 **
1594 ** In the example, there are three indexed terms connected by OR.
1595 ** The top of the loop looks like this:
1596 **
1597 ** Null 1 # Zero the rowset in reg 1
1598 **
1599 ** Then, for each indexed term, the following. The arguments to
1600 ** RowSetTest are such that the rowid of the current row is inserted
1601 ** into the RowSet. If it is already present, control skips the
1602 ** Gosub opcode and jumps straight to the code generated by WhereEnd().
1603 **
1604 ** sqlite3WhereBegin(<term>)
1605 ** RowSetTest # Insert rowid into rowset
1606 ** Gosub 2 A
1607 ** sqlite3WhereEnd()
1608 **
1609 ** Following the above, code to terminate the loop. Label A, the target
1610 ** of the Gosub above, jumps to the instruction right after the Goto.
1611 **
1612 ** Null 1 # Zero the rowset in reg 1
1613 ** Goto B # The loop is finished.
1614 **
1615 ** A: <loop body> # Return data, whatever.
1616 **
1617 ** Return 2 # Jump back to the Gosub
1618 **
1619 ** B: <after the loop>
1620 **
1621 ** Added 2014-05-26: If the table is a WITHOUT ROWID table, then
1622 ** use an ephemeral index instead of a RowSet to record the primary
1623 ** keys of the rows we have already seen.
1624 **
1625 */
1626 WhereClause *pOrWc; /* The OR-clause broken out into subterms */
1627 SrcList *pOrTab; /* Shortened table list or OR-clause generation */
1628 Index *pCov = 0; /* Potential covering index (or NULL) */
1629 int iCovCur = pParse->nTab++; /* Cursor used for index scans (if any) */
1630
1631 int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */
1632 int regRowset = 0; /* Register for RowSet object */
1633 int regRowid = 0; /* Register holding rowid */
1634 int iLoopBody = sqlite3VdbeMakeLabel(v); /* Start of loop body */
1635 int iRetInit; /* Address of regReturn init */
1636 int untestedTerms = 0; /* Some terms not completely tested */
1637 int ii; /* Loop counter */
1638 u16 wctrlFlags; /* Flags for sub-WHERE clause */
1639 Expr *pAndExpr = 0; /* An ".. AND (...)" expression */
1640 Table *pTab = pTabItem->pTab;
dan145b4ea2016-07-29 18:12:12 +00001641
drh6f82e852015-06-06 20:12:09 +00001642 pTerm = pLoop->aLTerm[0];
1643 assert( pTerm!=0 );
1644 assert( pTerm->eOperator & WO_OR );
1645 assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
1646 pOrWc = &pTerm->u.pOrInfo->wc;
1647 pLevel->op = OP_Return;
1648 pLevel->p1 = regReturn;
1649
1650 /* Set up a new SrcList in pOrTab containing the table being scanned
1651 ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
1652 ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
1653 */
1654 if( pWInfo->nLevel>1 ){
1655 int nNotReady; /* The number of notReady tables */
1656 struct SrcList_item *origSrc; /* Original list of tables */
1657 nNotReady = pWInfo->nLevel - iLevel - 1;
1658 pOrTab = sqlite3StackAllocRaw(db,
1659 sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
1660 if( pOrTab==0 ) return notReady;
1661 pOrTab->nAlloc = (u8)(nNotReady + 1);
1662 pOrTab->nSrc = pOrTab->nAlloc;
1663 memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
1664 origSrc = pWInfo->pTabList->a;
1665 for(k=1; k<=nNotReady; k++){
1666 memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
1667 }
1668 }else{
1669 pOrTab = pWInfo->pTabList;
1670 }
1671
1672 /* Initialize the rowset register to contain NULL. An SQL NULL is
1673 ** equivalent to an empty rowset. Or, create an ephemeral index
1674 ** capable of holding primary keys in the case of a WITHOUT ROWID.
1675 **
1676 ** Also initialize regReturn to contain the address of the instruction
1677 ** immediately following the OP_Return at the bottom of the loop. This
1678 ** is required in a few obscure LEFT JOIN cases where control jumps
1679 ** over the top of the loop into the body of it. In this case the
1680 ** correct response for the end-of-loop code (the OP_Return) is to
1681 ** fall through to the next instruction, just as an OP_Next does if
1682 ** called on an uninitialized cursor.
1683 */
1684 if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
1685 if( HasRowid(pTab) ){
1686 regRowset = ++pParse->nMem;
1687 sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
1688 }else{
1689 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
1690 regRowset = pParse->nTab++;
1691 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, regRowset, pPk->nKeyCol);
1692 sqlite3VdbeSetP4KeyInfo(pParse, pPk);
1693 }
1694 regRowid = ++pParse->nMem;
1695 }
1696 iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
1697
1698 /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y
1699 ** Then for every term xN, evaluate as the subexpression: xN AND z
1700 ** That way, terms in y that are factored into the disjunction will
1701 ** be picked up by the recursive calls to sqlite3WhereBegin() below.
1702 **
1703 ** Actually, each subexpression is converted to "xN AND w" where w is
1704 ** the "interesting" terms of z - terms that did not originate in the
1705 ** ON or USING clause of a LEFT JOIN, and terms that are usable as
1706 ** indices.
1707 **
1708 ** This optimization also only applies if the (x1 OR x2 OR ...) term
1709 ** is not contained in the ON clause of a LEFT JOIN.
1710 ** See ticket http://www.sqlite.org/src/info/f2369304e4
1711 */
1712 if( pWC->nTerm>1 ){
1713 int iTerm;
1714 for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
1715 Expr *pExpr = pWC->a[iTerm].pExpr;
1716 if( &pWC->a[iTerm] == pTerm ) continue;
1717 if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
drh3b83f0c2016-01-29 16:57:06 +00001718 testcase( pWC->a[iTerm].wtFlags & TERM_VIRTUAL );
1719 testcase( pWC->a[iTerm].wtFlags & TERM_CODED );
1720 if( (pWC->a[iTerm].wtFlags & (TERM_VIRTUAL|TERM_CODED))!=0 ) continue;
drh6f82e852015-06-06 20:12:09 +00001721 if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
1722 testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO );
1723 pExpr = sqlite3ExprDup(db, pExpr, 0);
1724 pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr);
1725 }
1726 if( pAndExpr ){
drh1167d322015-10-28 20:01:45 +00001727 pAndExpr = sqlite3PExpr(pParse, TK_AND|TKFLG_DONTFOLD, 0, pAndExpr, 0);
drh6f82e852015-06-06 20:12:09 +00001728 }
1729 }
1730
1731 /* Run a separate WHERE clause for each term of the OR clause. After
1732 ** eliminating duplicates from other WHERE clauses, the action for each
1733 ** sub-WHERE clause is to to invoke the main loop body as a subroutine.
1734 */
drhce943bc2016-05-19 18:56:33 +00001735 wctrlFlags = WHERE_OR_SUBCLAUSE | (pWInfo->wctrlFlags & WHERE_SEEK_TABLE);
drh6f82e852015-06-06 20:12:09 +00001736 for(ii=0; ii<pOrWc->nTerm; ii++){
1737 WhereTerm *pOrTerm = &pOrWc->a[ii];
1738 if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
1739 WhereInfo *pSubWInfo; /* Info for single OR-term scan */
1740 Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */
drh728e0f92015-10-10 14:41:28 +00001741 int jmp1 = 0; /* Address of jump operation */
drh6f82e852015-06-06 20:12:09 +00001742 if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){
1743 pAndExpr->pLeft = pOrExpr;
1744 pOrExpr = pAndExpr;
1745 }
1746 /* Loop through table entries that match term pOrTerm. */
1747 WHERETRACE(0xffff, ("Subplan for OR-clause:\n"));
1748 pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
1749 wctrlFlags, iCovCur);
1750 assert( pSubWInfo || pParse->nErr || db->mallocFailed );
1751 if( pSubWInfo ){
1752 WhereLoop *pSubLoop;
1753 int addrExplain = sqlite3WhereExplainOneScan(
1754 pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
1755 );
1756 sqlite3WhereAddScanStatus(v, pOrTab, &pSubWInfo->a[0], addrExplain);
1757
1758 /* This is the sub-WHERE clause body. First skip over
1759 ** duplicate rows from prior sub-WHERE clauses, and record the
1760 ** rowid (or PRIMARY KEY) for the current row so that the same
1761 ** row will be skipped in subsequent sub-WHERE clauses.
1762 */
1763 if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
1764 int r;
1765 int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
1766 if( HasRowid(pTab) ){
1767 r = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, regRowid, 0);
drh728e0f92015-10-10 14:41:28 +00001768 jmp1 = sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, 0,
1769 r,iSet);
drh6f82e852015-06-06 20:12:09 +00001770 VdbeCoverage(v);
1771 }else{
1772 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
1773 int nPk = pPk->nKeyCol;
1774 int iPk;
1775
1776 /* Read the PK into an array of temp registers. */
1777 r = sqlite3GetTempRange(pParse, nPk);
1778 for(iPk=0; iPk<nPk; iPk++){
1779 int iCol = pPk->aiColumn[iPk];
drhce78bc62015-10-15 19:21:51 +00001780 sqlite3ExprCodeGetColumnToReg(pParse, pTab, iCol, iCur, r+iPk);
drh6f82e852015-06-06 20:12:09 +00001781 }
1782
1783 /* Check if the temp table already contains this key. If so,
1784 ** the row has already been included in the result set and
1785 ** can be ignored (by jumping past the Gosub below). Otherwise,
1786 ** insert the key into the temp table and proceed with processing
1787 ** the row.
1788 **
1789 ** Use some of the same optimizations as OP_RowSetTest: If iSet
1790 ** is zero, assume that the key cannot already be present in
1791 ** the temp table. And if iSet is -1, assume that there is no
1792 ** need to insert the key into the temp table, as it will never
1793 ** be tested for. */
1794 if( iSet ){
drh728e0f92015-10-10 14:41:28 +00001795 jmp1 = sqlite3VdbeAddOp4Int(v, OP_Found, regRowset, 0, r, nPk);
drh6f82e852015-06-06 20:12:09 +00001796 VdbeCoverage(v);
1797 }
1798 if( iSet>=0 ){
1799 sqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, regRowid);
1800 sqlite3VdbeAddOp3(v, OP_IdxInsert, regRowset, regRowid, 0);
1801 if( iSet ) sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
1802 }
1803
1804 /* Release the array of temp registers */
1805 sqlite3ReleaseTempRange(pParse, r, nPk);
1806 }
1807 }
1808
1809 /* Invoke the main loop body as a subroutine */
1810 sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
1811
1812 /* Jump here (skipping the main loop body subroutine) if the
1813 ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */
drh728e0f92015-10-10 14:41:28 +00001814 if( jmp1 ) sqlite3VdbeJumpHere(v, jmp1);
drh6f82e852015-06-06 20:12:09 +00001815
1816 /* The pSubWInfo->untestedTerms flag means that this OR term
1817 ** contained one or more AND term from a notReady table. The
1818 ** terms from the notReady table could not be tested and will
1819 ** need to be tested later.
1820 */
1821 if( pSubWInfo->untestedTerms ) untestedTerms = 1;
1822
1823 /* If all of the OR-connected terms are optimized using the same
1824 ** index, and the index is opened using the same cursor number
1825 ** by each call to sqlite3WhereBegin() made by this loop, it may
1826 ** be possible to use that index as a covering index.
1827 **
1828 ** If the call to sqlite3WhereBegin() above resulted in a scan that
1829 ** uses an index, and this is either the first OR-connected term
1830 ** processed or the index is the same as that used by all previous
1831 ** terms, set pCov to the candidate covering index. Otherwise, set
1832 ** pCov to NULL to indicate that no candidate covering index will
1833 ** be available.
1834 */
1835 pSubLoop = pSubWInfo->a[0].pWLoop;
1836 assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
1837 if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
1838 && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
1839 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pSubLoop->u.btree.pIndex))
1840 ){
1841 assert( pSubWInfo->a[0].iIdxCur==iCovCur );
1842 pCov = pSubLoop->u.btree.pIndex;
drh6f82e852015-06-06 20:12:09 +00001843 }else{
1844 pCov = 0;
1845 }
1846
1847 /* Finish the loop through table entries that match term pOrTerm. */
1848 sqlite3WhereEnd(pSubWInfo);
1849 }
1850 }
1851 }
1852 pLevel->u.pCovidx = pCov;
1853 if( pCov ) pLevel->iIdxCur = iCovCur;
1854 if( pAndExpr ){
1855 pAndExpr->pLeft = 0;
1856 sqlite3ExprDelete(db, pAndExpr);
1857 }
1858 sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
drh076e85f2015-09-03 13:46:12 +00001859 sqlite3VdbeGoto(v, pLevel->addrBrk);
drh6f82e852015-06-06 20:12:09 +00001860 sqlite3VdbeResolveLabel(v, iLoopBody);
1861
1862 if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab);
1863 if( !untestedTerms ) disableTerm(pLevel, pTerm);
1864 }else
1865#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
1866
1867 {
1868 /* Case 6: There is no usable index. We must do a complete
1869 ** scan of the entire table.
1870 */
1871 static const u8 aStep[] = { OP_Next, OP_Prev };
1872 static const u8 aStart[] = { OP_Rewind, OP_Last };
1873 assert( bRev==0 || bRev==1 );
drh8a48b9c2015-08-19 15:20:00 +00001874 if( pTabItem->fg.isRecursive ){
drh6f82e852015-06-06 20:12:09 +00001875 /* Tables marked isRecursive have only a single row that is stored in
1876 ** a pseudo-cursor. No need to Rewind or Next such cursors. */
1877 pLevel->op = OP_Noop;
1878 }else{
danb324cf72016-06-17 14:33:32 +00001879 codeCursorHint(pTabItem, pWInfo, pLevel, 0);
drh6f82e852015-06-06 20:12:09 +00001880 pLevel->op = aStep[bRev];
1881 pLevel->p1 = iCur;
1882 pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
1883 VdbeCoverageIf(v, bRev==0);
1884 VdbeCoverageIf(v, bRev!=0);
1885 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
1886 }
1887 }
1888
1889#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
1890 pLevel->addrVisit = sqlite3VdbeCurrentAddr(v);
1891#endif
1892
1893 /* Insert code to test every subexpression that can be completely
1894 ** computed using the current set of tables.
1895 */
1896 for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
1897 Expr *pE;
1898 int skipLikeAddr = 0;
1899 testcase( pTerm->wtFlags & TERM_VIRTUAL );
1900 testcase( pTerm->wtFlags & TERM_CODED );
1901 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
1902 if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
1903 testcase( pWInfo->untestedTerms==0
drhce943bc2016-05-19 18:56:33 +00001904 && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 );
drh6f82e852015-06-06 20:12:09 +00001905 pWInfo->untestedTerms = 1;
1906 continue;
1907 }
1908 pE = pTerm->pExpr;
1909 assert( pE!=0 );
1910 if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
1911 continue;
1912 }
1913 if( pTerm->wtFlags & TERM_LIKECOND ){
drh44aebff2016-05-02 10:25:42 +00001914 /* If the TERM_LIKECOND flag is set, that means that the range search
1915 ** is sufficient to guarantee that the LIKE operator is true, so we
1916 ** can skip the call to the like(A,B) function. But this only works
1917 ** for strings. So do not skip the call to the function on the pass
1918 ** that compares BLOBs. */
drh41d2e662015-12-01 21:23:07 +00001919#ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
1920 continue;
1921#else
drh44aebff2016-05-02 10:25:42 +00001922 u32 x = pLevel->iLikeRepCntr;
1923 assert( x>0 );
1924 skipLikeAddr = sqlite3VdbeAddOp1(v, (x&1)? OP_IfNot : OP_If, (int)(x>>1));
drh6f82e852015-06-06 20:12:09 +00001925 VdbeCoverage(v);
drh41d2e662015-12-01 21:23:07 +00001926#endif
drh6f82e852015-06-06 20:12:09 +00001927 }
1928 sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
1929 if( skipLikeAddr ) sqlite3VdbeJumpHere(v, skipLikeAddr);
1930 pTerm->wtFlags |= TERM_CODED;
1931 }
1932
1933 /* Insert code to test for implied constraints based on transitivity
1934 ** of the "==" operator.
1935 **
1936 ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
1937 ** and we are coding the t1 loop and the t2 loop has not yet coded,
1938 ** then we cannot use the "t1.a=t2.b" constraint, but we can code
1939 ** the implied "t1.a=123" constraint.
1940 */
1941 for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
1942 Expr *pE, *pEAlt;
1943 WhereTerm *pAlt;
1944 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
1945 if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) continue;
1946 if( (pTerm->eOperator & WO_EQUIV)==0 ) continue;
1947 if( pTerm->leftCursor!=iCur ) continue;
1948 if( pLevel->iLeftJoin ) continue;
1949 pE = pTerm->pExpr;
1950 assert( !ExprHasProperty(pE, EP_FromJoin) );
1951 assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
1952 pAlt = sqlite3WhereFindTerm(pWC, iCur, pTerm->u.leftColumn, notReady,
1953 WO_EQ|WO_IN|WO_IS, 0);
1954 if( pAlt==0 ) continue;
1955 if( pAlt->wtFlags & (TERM_CODED) ) continue;
1956 testcase( pAlt->eOperator & WO_EQ );
1957 testcase( pAlt->eOperator & WO_IS );
1958 testcase( pAlt->eOperator & WO_IN );
1959 VdbeModuleComment((v, "begin transitive constraint"));
1960 pEAlt = sqlite3StackAllocRaw(db, sizeof(*pEAlt));
1961 if( pEAlt ){
1962 *pEAlt = *pAlt->pExpr;
1963 pEAlt->pLeft = pE->pLeft;
1964 sqlite3ExprIfFalse(pParse, pEAlt, addrCont, SQLITE_JUMPIFNULL);
1965 sqlite3StackFree(db, pEAlt);
1966 }
1967 }
1968
1969 /* For a LEFT OUTER JOIN, generate code that will record the fact that
1970 ** at least one row of the right table has matched the left table.
1971 */
1972 if( pLevel->iLeftJoin ){
1973 pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
1974 sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
1975 VdbeComment((v, "record LEFT JOIN hit"));
1976 sqlite3ExprCacheClear(pParse);
1977 for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
1978 testcase( pTerm->wtFlags & TERM_VIRTUAL );
1979 testcase( pTerm->wtFlags & TERM_CODED );
1980 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
1981 if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
1982 assert( pWInfo->untestedTerms );
1983 continue;
1984 }
1985 assert( pTerm->pExpr );
1986 sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
1987 pTerm->wtFlags |= TERM_CODED;
1988 }
1989 }
1990
1991 return pLevel->notReady;
1992}