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