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]; |
drh | 4b92f98 | 2015-09-29 17:20:14 +0000 | [diff] [blame] | 49 | if( i==XN_EXPR ) return "<expr>"; |
| 50 | if( i==XN_ROWID ) return "rowid"; |
drh | c7c4680 | 2015-08-27 20:33:38 +0000 | [diff] [blame] | 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 | */ |
drh | 8faee87 | 2015-09-19 18:08:13 +0000 | [diff] [blame] | 68 | static void explainIndexRange(StrAccum *pStr, WhereLoop *pLoop){ |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 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 | 2ed0d80 | 2015-09-02 16:51:37 +0000 | [diff] [blame] | 78 | if( i ) sqlite3StrAccumAppend(pStr, " AND ", 5); |
drh | 5f4a686 | 2016-01-30 12:50:25 +0000 | [diff] [blame] | 79 | sqlite3XPrintf(pStr, i>=nSkip ? "%s=?" : "ANY(%s)", z); |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 80 | } |
| 81 | |
| 82 | j = i; |
| 83 | if( pLoop->wsFlags&WHERE_BTM_LIMIT ){ |
drh | c7c4680 | 2015-08-27 20:33:38 +0000 | [diff] [blame] | 84 | const char *z = explainIndexColumnName(pIndex, i); |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 85 | explainAppendTerm(pStr, i++, z, ">"); |
| 86 | } |
| 87 | if( pLoop->wsFlags&WHERE_TOP_LIMIT ){ |
drh | c7c4680 | 2015-08-27 20:33:38 +0000 | [diff] [blame] | 88 | const char *z = explainIndexColumnName(pIndex, j); |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 89 | 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 | */ |
| 103 | int 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; |
drh | ce943bc | 2016-05-19 18:56:33 +0000 | [diff] [blame] | 129 | if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_OR_SUBCLAUSE) ) return 0; |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 130 | |
| 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 ){ |
drh | 5f4a686 | 2016-01-30 12:50:25 +0000 | [diff] [blame] | 138 | sqlite3XPrintf(&str, " SUBQUERY %d", pItem->iSelectId); |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 139 | }else{ |
drh | 5f4a686 | 2016-01-30 12:50:25 +0000 | [diff] [blame] | 140 | sqlite3XPrintf(&str, " TABLE %s", pItem->zName); |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 141 | } |
| 142 | |
| 143 | if( pItem->zAlias ){ |
drh | 5f4a686 | 2016-01-30 12:50:25 +0000 | [diff] [blame] | 144 | sqlite3XPrintf(&str, " AS %s", pItem->zAlias); |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 145 | } |
| 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); |
drh | 5f4a686 | 2016-01-30 12:50:25 +0000 | [diff] [blame] | 168 | sqlite3XPrintf(&str, zFmt, pIdx->zName); |
drh | 8faee87 | 2015-09-19 18:08:13 +0000 | [diff] [blame] | 169 | explainIndexRange(&str, pLoop); |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 170 | } |
| 171 | }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){ |
drh | d37bea5 | 2015-09-02 15:37:50 +0000 | [diff] [blame] | 172 | const char *zRangeOp; |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 173 | if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){ |
drh | d37bea5 | 2015-09-02 15:37:50 +0000 | [diff] [blame] | 174 | zRangeOp = "="; |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 175 | }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){ |
drh | d37bea5 | 2015-09-02 15:37:50 +0000 | [diff] [blame] | 176 | zRangeOp = ">? AND rowid<"; |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 177 | }else if( flags&WHERE_BTM_LIMIT ){ |
drh | d37bea5 | 2015-09-02 15:37:50 +0000 | [diff] [blame] | 178 | zRangeOp = ">"; |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 179 | }else{ |
| 180 | assert( flags&WHERE_TOP_LIMIT); |
drh | d37bea5 | 2015-09-02 15:37:50 +0000 | [diff] [blame] | 181 | zRangeOp = "<"; |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 182 | } |
drh | 5f4a686 | 2016-01-30 12:50:25 +0000 | [diff] [blame] | 183 | sqlite3XPrintf(&str, " USING INTEGER PRIMARY KEY (rowid%s?)",zRangeOp); |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 184 | } |
| 185 | #ifndef SQLITE_OMIT_VIRTUALTABLE |
| 186 | else if( (flags & WHERE_VIRTUALTABLE)!=0 ){ |
drh | 5f4a686 | 2016-01-30 12:50:25 +0000 | [diff] [blame] | 187 | sqlite3XPrintf(&str, " VIRTUAL TABLE INDEX %d:%s", |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 188 | pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr); |
| 189 | } |
| 190 | #endif |
| 191 | #ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS |
| 192 | if( pLoop->nOut>=10 ){ |
drh | 5f4a686 | 2016-01-30 12:50:25 +0000 | [diff] [blame] | 193 | sqlite3XPrintf(&str, " (~%llu rows)", sqlite3LogEstToInt(pLoop->nOut)); |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 194 | }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 | */ |
| 215 | void 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 | */ |
| 277 | static 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 | */ |
| 308 | static 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 ){ |
drh | 9b34abe | 2016-01-16 15:12:35 +0000 | [diff] [blame] | 330 | sqlite3VdbeAddOp4(v, OP_Affinity, base, n, 0, zAff, n); |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 331 | 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 | */ |
| 347 | static 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 | |
dan | 8da209b | 2016-07-26 18:06:08 +0000 | [diff] [blame] | 359 | assert( pLevel->pWLoop->aLTerm[iEq]==pTerm ); |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 360 | assert( iTarget>0 ); |
| 361 | if( pX->op==TK_EQ || pX->op==TK_IS ){ |
dan | 145b4ea | 2016-07-29 18:12:12 +0000 | [diff] [blame] | 362 | Expr *pRight = pX->pRight; |
| 363 | if( pRight->op==TK_SELECT_COLUMN ){ |
| 364 | /* This case occurs for expressions like "(a, b) == (SELECT ...)". */ |
| 365 | WhereLoop *pLoop = pLevel->pWLoop; |
| 366 | int i; |
| 367 | Expr *pSub = pRight->pLeft; |
| 368 | assert( pSub->op==TK_SELECT ); |
| 369 | for(i=pLoop->nSkip; i<iEq; i++){ |
| 370 | Expr *pExpr = pLoop->aLTerm[i]->pExpr->pRight; |
| 371 | if( pExpr && pExpr->op==TK_SELECT_COLUMN && pExpr->pLeft==pSub ) break; |
| 372 | } |
| 373 | |
| 374 | if( i==iEq ){ |
| 375 | iReg = sqlite3CodeSubselect(pParse, pSub, 0, 0); |
| 376 | for(/*no-op*/; i<pLoop->nLTerm; i++){ |
| 377 | Expr *pExpr = pLoop->aLTerm[i]->pExpr->pRight; |
| 378 | if( pExpr && pExpr->op==TK_SELECT_COLUMN && pExpr->pLeft==pSub ){ |
| 379 | sqlite3VdbeAddOp2(v, OP_Copy, iReg+pExpr->iColumn, iTarget-iEq+i); |
| 380 | } |
| 381 | } |
| 382 | } |
| 383 | iReg = iTarget; |
| 384 | }else{ |
| 385 | iReg = sqlite3ExprCodeTarget(pParse, pRight, iTarget); |
| 386 | } |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 387 | }else if( pX->op==TK_ISNULL ){ |
| 388 | iReg = iTarget; |
| 389 | sqlite3VdbeAddOp2(v, OP_Null, 0, iReg); |
| 390 | #ifndef SQLITE_OMIT_SUBQUERY |
| 391 | }else{ |
| 392 | int eType; |
| 393 | int iTab; |
| 394 | struct InLoop *pIn; |
| 395 | WhereLoop *pLoop = pLevel->pWLoop; |
dan | 8da209b | 2016-07-26 18:06:08 +0000 | [diff] [blame] | 396 | int i; |
| 397 | int nEq = 0; |
| 398 | int *aiMap = 0; |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 399 | |
| 400 | if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 |
| 401 | && pLoop->u.btree.pIndex!=0 |
| 402 | && pLoop->u.btree.pIndex->aSortOrder[iEq] |
| 403 | ){ |
| 404 | testcase( iEq==0 ); |
| 405 | testcase( bRev ); |
| 406 | bRev = !bRev; |
| 407 | } |
| 408 | assert( pX->op==TK_IN ); |
| 409 | iReg = iTarget; |
dan | 8da209b | 2016-07-26 18:06:08 +0000 | [diff] [blame] | 410 | |
| 411 | for(i=0; i<iEq; i++){ |
| 412 | if( pLoop->aLTerm[i] && pLoop->aLTerm[i]->pExpr==pX ){ |
| 413 | disableTerm(pLevel, pTerm); |
| 414 | return iTarget; |
| 415 | } |
| 416 | } |
| 417 | for(i=iEq;i<pLoop->nLTerm; i++){ |
| 418 | if( pLoop->aLTerm[i] && pLoop->aLTerm[i]->pExpr==pX ) nEq++; |
| 419 | } |
| 420 | |
| 421 | if( nEq>1 ){ |
| 422 | aiMap = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int) * nEq); |
| 423 | if( !aiMap ) return 0; |
| 424 | } |
| 425 | |
| 426 | if( (pX->flags & EP_xIsSelect)==0 || pX->x.pSelect->pEList->nExpr==1 ){ |
| 427 | eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, 0); |
| 428 | }else{ |
| 429 | sqlite3 *db = pParse->db; |
| 430 | ExprList *pOrigRhs = pX->x.pSelect->pEList; |
| 431 | ExprList *pOrigLhs = pX->pLeft->x.pList; |
| 432 | ExprList *pRhs = 0; /* New Select.pEList for RHS */ |
| 433 | ExprList *pLhs = 0; /* New pX->pLeft vector */ |
| 434 | |
| 435 | for(i=iEq;i<pLoop->nLTerm; i++){ |
| 436 | if( pLoop->aLTerm[i]->pExpr==pX ){ |
| 437 | int iField = pLoop->aLTerm[i]->iField - 1; |
| 438 | Expr *pNewRhs = sqlite3ExprDup(db, pOrigRhs->a[iField].pExpr, 0); |
| 439 | Expr *pNewLhs = sqlite3ExprDup(db, pOrigLhs->a[iField].pExpr, 0); |
| 440 | |
| 441 | pRhs = sqlite3ExprListAppend(pParse, pRhs, pNewRhs); |
| 442 | pLhs = sqlite3ExprListAppend(pParse, pLhs, pNewLhs); |
| 443 | } |
| 444 | } |
| 445 | |
| 446 | pX->x.pSelect->pEList = pRhs; |
| 447 | pX->pLeft->x.pList = pLhs; |
| 448 | |
| 449 | eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, aiMap); |
| 450 | pX->x.pSelect->pEList = pOrigRhs; |
| 451 | pX->pLeft->x.pList = pOrigLhs; |
| 452 | sqlite3ExprListDelete(pParse->db, pLhs); |
| 453 | sqlite3ExprListDelete(pParse->db, pRhs); |
| 454 | } |
| 455 | |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 456 | if( eType==IN_INDEX_INDEX_DESC ){ |
| 457 | testcase( bRev ); |
| 458 | bRev = !bRev; |
| 459 | } |
| 460 | iTab = pX->iTable; |
| 461 | sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0); |
| 462 | VdbeCoverageIf(v, bRev); |
| 463 | VdbeCoverageIf(v, !bRev); |
| 464 | assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 ); |
dan | 8da209b | 2016-07-26 18:06:08 +0000 | [diff] [blame] | 465 | |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 466 | pLoop->wsFlags |= WHERE_IN_ABLE; |
| 467 | if( pLevel->u.in.nIn==0 ){ |
| 468 | pLevel->addrNxt = sqlite3VdbeMakeLabel(v); |
| 469 | } |
dan | 8da209b | 2016-07-26 18:06:08 +0000 | [diff] [blame] | 470 | |
| 471 | i = pLevel->u.in.nIn; |
| 472 | pLevel->u.in.nIn += nEq; |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 473 | pLevel->u.in.aInLoop = |
| 474 | sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop, |
| 475 | sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn); |
| 476 | pIn = pLevel->u.in.aInLoop; |
| 477 | if( pIn ){ |
dan | 8da209b | 2016-07-26 18:06:08 +0000 | [diff] [blame] | 478 | int iMap = 0; /* Index in aiMap[] */ |
| 479 | pIn += i; |
| 480 | for(i=iEq;i<pLoop->nLTerm; i++, pIn++){ |
| 481 | if( pLoop->aLTerm[i]->pExpr==pX ){ |
| 482 | if( eType==IN_INDEX_ROWID ){ |
| 483 | assert( nEq==1 && i==iEq ); |
| 484 | pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg); |
| 485 | }else{ |
| 486 | int iCol = aiMap ? aiMap[iMap++] : 0; |
| 487 | int iOut = iReg + i - iEq; |
| 488 | pIn->addrInTop = sqlite3VdbeAddOp3(v,OP_Column,iTab, iCol, iOut); |
| 489 | } |
| 490 | if( i==iEq ){ |
| 491 | pIn->iCur = iTab; |
| 492 | pIn->eEndLoopOp = bRev ? OP_PrevIfOpen : OP_NextIfOpen; |
| 493 | }else{ |
| 494 | pIn->eEndLoopOp = OP_Noop; |
| 495 | } |
| 496 | } |
| 497 | sqlite3VdbeAddOp1(v, OP_IsNull, iReg); VdbeCoverage(v); |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 498 | } |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 499 | }else{ |
| 500 | pLevel->u.in.nIn = 0; |
| 501 | } |
dan | 8da209b | 2016-07-26 18:06:08 +0000 | [diff] [blame] | 502 | sqlite3DbFree(pParse->db, aiMap); |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 503 | #endif |
| 504 | } |
| 505 | disableTerm(pLevel, pTerm); |
| 506 | return iReg; |
| 507 | } |
| 508 | |
| 509 | /* |
| 510 | ** Generate code that will evaluate all == and IN constraints for an |
| 511 | ** index scan. |
| 512 | ** |
| 513 | ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c). |
| 514 | ** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10 |
| 515 | ** The index has as many as three equality constraints, but in this |
| 516 | ** example, the third "c" value is an inequality. So only two |
| 517 | ** constraints are coded. This routine will generate code to evaluate |
| 518 | ** a==5 and b IN (1,2,3). The current values for a and b will be stored |
| 519 | ** in consecutive registers and the index of the first register is returned. |
| 520 | ** |
| 521 | ** In the example above nEq==2. But this subroutine works for any value |
| 522 | ** of nEq including 0. If nEq==0, this routine is nearly a no-op. |
| 523 | ** The only thing it does is allocate the pLevel->iMem memory cell and |
| 524 | ** compute the affinity string. |
| 525 | ** |
| 526 | ** The nExtraReg parameter is 0 or 1. It is 0 if all WHERE clause constraints |
| 527 | ** are == or IN and are covered by the nEq. nExtraReg is 1 if there is |
| 528 | ** an inequality constraint (such as the "c>=5 AND c<10" in the example) that |
| 529 | ** occurs after the nEq quality constraints. |
| 530 | ** |
| 531 | ** This routine allocates a range of nEq+nExtraReg memory cells and returns |
| 532 | ** the index of the first memory cell in that range. The code that |
| 533 | ** calls this routine will use that memory range to store keys for |
| 534 | ** start and termination conditions of the loop. |
| 535 | ** key value of the loop. If one or more IN operators appear, then |
| 536 | ** this routine allocates an additional nEq memory cells for internal |
| 537 | ** use. |
| 538 | ** |
| 539 | ** Before returning, *pzAff is set to point to a buffer containing a |
| 540 | ** copy of the column affinity string of the index allocated using |
| 541 | ** sqlite3DbMalloc(). Except, entries in the copy of the string associated |
| 542 | ** with equality constraints that use BLOB or NONE affinity are set to |
| 543 | ** SQLITE_AFF_BLOB. This is to deal with SQL such as the following: |
| 544 | ** |
| 545 | ** CREATE TABLE t1(a TEXT PRIMARY KEY, b); |
| 546 | ** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b; |
| 547 | ** |
| 548 | ** In the example above, the index on t1(a) has TEXT affinity. But since |
| 549 | ** the right hand side of the equality constraint (t2.b) has BLOB/NONE affinity, |
| 550 | ** no conversion should be attempted before using a t2.b value as part of |
| 551 | ** a key to search the index. Hence the first byte in the returned affinity |
| 552 | ** string in this example would be set to SQLITE_AFF_BLOB. |
| 553 | */ |
| 554 | static int codeAllEqualityTerms( |
| 555 | Parse *pParse, /* Parsing context */ |
| 556 | WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */ |
| 557 | int bRev, /* Reverse the order of IN operators */ |
| 558 | int nExtraReg, /* Number of extra registers to allocate */ |
| 559 | char **pzAff /* OUT: Set to point to affinity string */ |
| 560 | ){ |
| 561 | u16 nEq; /* The number of == or IN constraints to code */ |
| 562 | u16 nSkip; /* Number of left-most columns to skip */ |
| 563 | Vdbe *v = pParse->pVdbe; /* The vm under construction */ |
| 564 | Index *pIdx; /* The index being used for this loop */ |
| 565 | WhereTerm *pTerm; /* A single constraint term */ |
| 566 | WhereLoop *pLoop; /* The WhereLoop object */ |
| 567 | int j; /* Loop counter */ |
| 568 | int regBase; /* Base register */ |
| 569 | int nReg; /* Number of registers to allocate */ |
| 570 | char *zAff; /* Affinity string to return */ |
| 571 | |
| 572 | /* This module is only called on query plans that use an index. */ |
| 573 | pLoop = pLevel->pWLoop; |
| 574 | assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 ); |
| 575 | nEq = pLoop->u.btree.nEq; |
| 576 | nSkip = pLoop->nSkip; |
| 577 | pIdx = pLoop->u.btree.pIndex; |
| 578 | assert( pIdx!=0 ); |
| 579 | |
| 580 | /* Figure out how many memory cells we will need then allocate them. |
| 581 | */ |
| 582 | regBase = pParse->nMem + 1; |
| 583 | nReg = pLoop->u.btree.nEq + nExtraReg; |
| 584 | pParse->nMem += nReg; |
| 585 | |
drh | e910769 | 2015-08-25 19:20:04 +0000 | [diff] [blame] | 586 | zAff = sqlite3DbStrDup(pParse->db,sqlite3IndexAffinityStr(pParse->db,pIdx)); |
drh | 4df86af | 2016-02-04 11:48:00 +0000 | [diff] [blame] | 587 | assert( zAff!=0 || pParse->db->mallocFailed ); |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 588 | |
| 589 | if( nSkip ){ |
| 590 | int iIdxCur = pLevel->iIdxCur; |
| 591 | sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur); |
| 592 | VdbeCoverageIf(v, bRev==0); |
| 593 | VdbeCoverageIf(v, bRev!=0); |
| 594 | VdbeComment((v, "begin skip-scan on %s", pIdx->zName)); |
| 595 | j = sqlite3VdbeAddOp0(v, OP_Goto); |
| 596 | pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT), |
| 597 | iIdxCur, 0, regBase, nSkip); |
| 598 | VdbeCoverageIf(v, bRev==0); |
| 599 | VdbeCoverageIf(v, bRev!=0); |
| 600 | sqlite3VdbeJumpHere(v, j); |
| 601 | for(j=0; j<nSkip; j++){ |
| 602 | sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, j, regBase+j); |
drh | 4b92f98 | 2015-09-29 17:20:14 +0000 | [diff] [blame] | 603 | testcase( pIdx->aiColumn[j]==XN_EXPR ); |
drh | e63e8a6 | 2015-09-18 18:09:28 +0000 | [diff] [blame] | 604 | VdbeComment((v, "%s", explainIndexColumnName(pIdx, j))); |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 605 | } |
| 606 | } |
| 607 | |
| 608 | /* Evaluate the equality constraints |
| 609 | */ |
| 610 | assert( zAff==0 || (int)strlen(zAff)>=nEq ); |
| 611 | for(j=nSkip; j<nEq; j++){ |
| 612 | int r1; |
| 613 | pTerm = pLoop->aLTerm[j]; |
| 614 | assert( pTerm!=0 ); |
| 615 | /* The following testcase is true for indices with redundant columns. |
| 616 | ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */ |
| 617 | testcase( (pTerm->wtFlags & TERM_CODED)!=0 ); |
| 618 | testcase( pTerm->wtFlags & TERM_VIRTUAL ); |
| 619 | r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j); |
| 620 | if( r1!=regBase+j ){ |
| 621 | if( nReg==1 ){ |
| 622 | sqlite3ReleaseTempReg(pParse, regBase); |
| 623 | regBase = r1; |
| 624 | }else{ |
| 625 | sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j); |
| 626 | } |
| 627 | } |
| 628 | testcase( pTerm->eOperator & WO_ISNULL ); |
| 629 | testcase( pTerm->eOperator & WO_IN ); |
| 630 | if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){ |
| 631 | Expr *pRight = pTerm->pExpr->pRight; |
| 632 | if( (pTerm->wtFlags & TERM_IS)==0 && sqlite3ExprCanBeNull(pRight) ){ |
| 633 | sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk); |
| 634 | VdbeCoverage(v); |
| 635 | } |
| 636 | if( zAff ){ |
| 637 | if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_BLOB ){ |
| 638 | zAff[j] = SQLITE_AFF_BLOB; |
| 639 | } |
| 640 | if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){ |
| 641 | zAff[j] = SQLITE_AFF_BLOB; |
| 642 | } |
| 643 | } |
| 644 | } |
| 645 | } |
| 646 | *pzAff = zAff; |
| 647 | return regBase; |
| 648 | } |
| 649 | |
drh | 41d2e66 | 2015-12-01 21:23:07 +0000 | [diff] [blame] | 650 | #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 651 | /* |
drh | 44aebff | 2016-05-02 10:25:42 +0000 | [diff] [blame] | 652 | ** If the most recently coded instruction is a constant range constraint |
| 653 | ** (a string literal) that originated from the LIKE optimization, then |
| 654 | ** set P3 and P5 on the OP_String opcode so that the string will be cast |
| 655 | ** to a BLOB at appropriate times. |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 656 | ** |
| 657 | ** The LIKE optimization trys to evaluate "x LIKE 'abc%'" as a range |
| 658 | ** expression: "x>='ABC' AND x<'abd'". But this requires that the range |
| 659 | ** scan loop run twice, once for strings and a second time for BLOBs. |
| 660 | ** The OP_String opcodes on the second pass convert the upper and lower |
mistachkin | e234cfd | 2016-07-10 19:35:10 +0000 | [diff] [blame] | 661 | ** bound string constants to blobs. This routine makes the necessary changes |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 662 | ** to the OP_String opcodes for that to happen. |
drh | 41d2e66 | 2015-12-01 21:23:07 +0000 | [diff] [blame] | 663 | ** |
| 664 | ** Except, of course, if SQLITE_LIKE_DOESNT_MATCH_BLOBS is defined, then |
| 665 | ** only the one pass through the string space is required, so this routine |
| 666 | ** becomes a no-op. |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 667 | */ |
| 668 | static void whereLikeOptimizationStringFixup( |
| 669 | Vdbe *v, /* prepared statement under construction */ |
| 670 | WhereLevel *pLevel, /* The loop that contains the LIKE operator */ |
| 671 | WhereTerm *pTerm /* The upper or lower bound just coded */ |
| 672 | ){ |
| 673 | if( pTerm->wtFlags & TERM_LIKEOPT ){ |
| 674 | VdbeOp *pOp; |
| 675 | assert( pLevel->iLikeRepCntr>0 ); |
| 676 | pOp = sqlite3VdbeGetOp(v, -1); |
| 677 | assert( pOp!=0 ); |
| 678 | assert( pOp->opcode==OP_String8 |
| 679 | || pTerm->pWC->pWInfo->pParse->db->mallocFailed ); |
drh | 44aebff | 2016-05-02 10:25:42 +0000 | [diff] [blame] | 680 | pOp->p3 = (int)(pLevel->iLikeRepCntr>>1); /* Register holding counter */ |
| 681 | pOp->p5 = (u8)(pLevel->iLikeRepCntr&1); /* ASC or DESC */ |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 682 | } |
| 683 | } |
drh | 41d2e66 | 2015-12-01 21:23:07 +0000 | [diff] [blame] | 684 | #else |
| 685 | # define whereLikeOptimizationStringFixup(A,B,C) |
| 686 | #endif |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 687 | |
drh | bec2476 | 2015-08-13 20:07:13 +0000 | [diff] [blame] | 688 | #ifdef SQLITE_ENABLE_CURSOR_HINTS |
drh | 2f2b027 | 2015-08-14 18:50:04 +0000 | [diff] [blame] | 689 | /* |
| 690 | ** Information is passed from codeCursorHint() down to individual nodes of |
| 691 | ** the expression tree (by sqlite3WalkExpr()) using an instance of this |
| 692 | ** structure. |
| 693 | */ |
| 694 | struct CCurHint { |
| 695 | int iTabCur; /* Cursor for the main table */ |
| 696 | int iIdxCur; /* Cursor for the index, if pIdx!=0. Unused otherwise */ |
| 697 | Index *pIdx; /* The index used to access the table */ |
| 698 | }; |
| 699 | |
| 700 | /* |
| 701 | ** This function is called for every node of an expression that is a candidate |
| 702 | ** for a cursor hint on an index cursor. For TK_COLUMN nodes that reference |
| 703 | ** the table CCurHint.iTabCur, verify that the same column can be |
| 704 | ** accessed through the index. If it cannot, then set pWalker->eCode to 1. |
| 705 | */ |
| 706 | static int codeCursorHintCheckExpr(Walker *pWalker, Expr *pExpr){ |
| 707 | struct CCurHint *pHint = pWalker->u.pCCurHint; |
| 708 | assert( pHint->pIdx!=0 ); |
| 709 | if( pExpr->op==TK_COLUMN |
| 710 | && pExpr->iTable==pHint->iTabCur |
| 711 | && sqlite3ColumnOfIndex(pHint->pIdx, pExpr->iColumn)<0 |
| 712 | ){ |
| 713 | pWalker->eCode = 1; |
| 714 | } |
| 715 | return WRC_Continue; |
| 716 | } |
| 717 | |
dan | e6912fd | 2016-06-17 19:27:13 +0000 | [diff] [blame] | 718 | /* |
| 719 | ** Test whether or not expression pExpr, which was part of a WHERE clause, |
| 720 | ** should be included in the cursor-hint for a table that is on the rhs |
| 721 | ** of a LEFT JOIN. Set Walker.eCode to non-zero before returning if the |
| 722 | ** expression is not suitable. |
| 723 | ** |
| 724 | ** An expression is unsuitable if it might evaluate to non NULL even if |
| 725 | ** a TK_COLUMN node that does affect the value of the expression is set |
| 726 | ** to NULL. For example: |
| 727 | ** |
| 728 | ** col IS NULL |
| 729 | ** col IS NOT NULL |
| 730 | ** coalesce(col, 1) |
| 731 | ** CASE WHEN col THEN 0 ELSE 1 END |
| 732 | */ |
| 733 | static int codeCursorHintIsOrFunction(Walker *pWalker, Expr *pExpr){ |
dan | 2b693d6 | 2016-06-20 17:22:06 +0000 | [diff] [blame] | 734 | if( pExpr->op==TK_IS |
dan | e6912fd | 2016-06-17 19:27:13 +0000 | [diff] [blame] | 735 | || pExpr->op==TK_ISNULL || pExpr->op==TK_ISNOT |
| 736 | || pExpr->op==TK_NOTNULL || pExpr->op==TK_CASE |
| 737 | ){ |
| 738 | pWalker->eCode = 1; |
dan | 2b693d6 | 2016-06-20 17:22:06 +0000 | [diff] [blame] | 739 | }else if( pExpr->op==TK_FUNCTION ){ |
| 740 | int d1; |
| 741 | char d2[3]; |
| 742 | if( 0==sqlite3IsLikeFunction(pWalker->pParse->db, pExpr, &d1, d2) ){ |
| 743 | pWalker->eCode = 1; |
| 744 | } |
dan | e6912fd | 2016-06-17 19:27:13 +0000 | [diff] [blame] | 745 | } |
dan | 2b693d6 | 2016-06-20 17:22:06 +0000 | [diff] [blame] | 746 | |
dan | e6912fd | 2016-06-17 19:27:13 +0000 | [diff] [blame] | 747 | return WRC_Continue; |
| 748 | } |
| 749 | |
drh | bec2476 | 2015-08-13 20:07:13 +0000 | [diff] [blame] | 750 | |
| 751 | /* |
| 752 | ** This function is called on every node of an expression tree used as an |
| 753 | ** argument to the OP_CursorHint instruction. If the node is a TK_COLUMN |
drh | 2f2b027 | 2015-08-14 18:50:04 +0000 | [diff] [blame] | 754 | ** that accesses any table other than the one identified by |
| 755 | ** CCurHint.iTabCur, then do the following: |
drh | bec2476 | 2015-08-13 20:07:13 +0000 | [diff] [blame] | 756 | ** |
| 757 | ** 1) allocate a register and code an OP_Column instruction to read |
| 758 | ** the specified column into the new register, and |
| 759 | ** |
| 760 | ** 2) transform the expression node to a TK_REGISTER node that reads |
| 761 | ** from the newly populated register. |
drh | 2f2b027 | 2015-08-14 18:50:04 +0000 | [diff] [blame] | 762 | ** |
| 763 | ** Also, if the node is a TK_COLUMN that does access the table idenified |
| 764 | ** by pCCurHint.iTabCur, and an index is being used (which we will |
| 765 | ** know because CCurHint.pIdx!=0) then transform the TK_COLUMN into |
| 766 | ** an access of the index rather than the original table. |
drh | bec2476 | 2015-08-13 20:07:13 +0000 | [diff] [blame] | 767 | */ |
| 768 | static int codeCursorHintFixExpr(Walker *pWalker, Expr *pExpr){ |
| 769 | int rc = WRC_Continue; |
drh | 2f2b027 | 2015-08-14 18:50:04 +0000 | [diff] [blame] | 770 | struct CCurHint *pHint = pWalker->u.pCCurHint; |
| 771 | if( pExpr->op==TK_COLUMN ){ |
| 772 | if( pExpr->iTable!=pHint->iTabCur ){ |
| 773 | Vdbe *v = pWalker->pParse->pVdbe; |
| 774 | int reg = ++pWalker->pParse->nMem; /* Register for column value */ |
| 775 | sqlite3ExprCodeGetColumnOfTable( |
| 776 | v, pExpr->pTab, pExpr->iTable, pExpr->iColumn, reg |
| 777 | ); |
| 778 | pExpr->op = TK_REGISTER; |
| 779 | pExpr->iTable = reg; |
| 780 | }else if( pHint->pIdx!=0 ){ |
| 781 | pExpr->iTable = pHint->iIdxCur; |
| 782 | pExpr->iColumn = sqlite3ColumnOfIndex(pHint->pIdx, pExpr->iColumn); |
| 783 | assert( pExpr->iColumn>=0 ); |
| 784 | } |
drh | bec2476 | 2015-08-13 20:07:13 +0000 | [diff] [blame] | 785 | }else if( pExpr->op==TK_AGG_FUNCTION ){ |
| 786 | /* An aggregate function in the WHERE clause of a query means this must |
| 787 | ** be a correlated sub-query, and expression pExpr is an aggregate from |
| 788 | ** the parent context. Do not walk the function arguments in this case. |
| 789 | ** |
| 790 | ** todo: It should be possible to replace this node with a TK_REGISTER |
| 791 | ** expression, as the result of the expression must be stored in a |
| 792 | ** register at this point. The same holds for TK_AGG_COLUMN nodes. */ |
| 793 | rc = WRC_Prune; |
| 794 | } |
| 795 | return rc; |
| 796 | } |
| 797 | |
| 798 | /* |
| 799 | ** Insert an OP_CursorHint instruction if it is appropriate to do so. |
| 800 | */ |
| 801 | static void codeCursorHint( |
dan | b324cf7 | 2016-06-17 14:33:32 +0000 | [diff] [blame] | 802 | struct SrcList_item *pTabItem, /* FROM clause item */ |
drh | b413a54 | 2015-08-17 17:19:28 +0000 | [diff] [blame] | 803 | WhereInfo *pWInfo, /* The where clause */ |
| 804 | WhereLevel *pLevel, /* Which loop to provide hints for */ |
| 805 | WhereTerm *pEndRange /* Hint this end-of-scan boundary term if not NULL */ |
drh | bec2476 | 2015-08-13 20:07:13 +0000 | [diff] [blame] | 806 | ){ |
| 807 | Parse *pParse = pWInfo->pParse; |
| 808 | sqlite3 *db = pParse->db; |
| 809 | Vdbe *v = pParse->pVdbe; |
drh | bec2476 | 2015-08-13 20:07:13 +0000 | [diff] [blame] | 810 | Expr *pExpr = 0; |
drh | 2f2b027 | 2015-08-14 18:50:04 +0000 | [diff] [blame] | 811 | WhereLoop *pLoop = pLevel->pWLoop; |
drh | bec2476 | 2015-08-13 20:07:13 +0000 | [diff] [blame] | 812 | int iCur; |
| 813 | WhereClause *pWC; |
| 814 | WhereTerm *pTerm; |
drh | b413a54 | 2015-08-17 17:19:28 +0000 | [diff] [blame] | 815 | int i, j; |
drh | 2f2b027 | 2015-08-14 18:50:04 +0000 | [diff] [blame] | 816 | struct CCurHint sHint; |
| 817 | Walker sWalker; |
drh | bec2476 | 2015-08-13 20:07:13 +0000 | [diff] [blame] | 818 | |
| 819 | if( OptimizationDisabled(db, SQLITE_CursorHints) ) return; |
drh | 2f2b027 | 2015-08-14 18:50:04 +0000 | [diff] [blame] | 820 | iCur = pLevel->iTabCur; |
| 821 | assert( iCur==pWInfo->pTabList->a[pLevel->iFrom].iCursor ); |
| 822 | sHint.iTabCur = iCur; |
| 823 | sHint.iIdxCur = pLevel->iIdxCur; |
| 824 | sHint.pIdx = pLoop->u.btree.pIndex; |
| 825 | memset(&sWalker, 0, sizeof(sWalker)); |
| 826 | sWalker.pParse = pParse; |
| 827 | sWalker.u.pCCurHint = &sHint; |
drh | bec2476 | 2015-08-13 20:07:13 +0000 | [diff] [blame] | 828 | pWC = &pWInfo->sWC; |
| 829 | for(i=0; i<pWC->nTerm; i++){ |
| 830 | pTerm = &pWC->a[i]; |
| 831 | if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue; |
| 832 | if( pTerm->prereqAll & pLevel->notReady ) continue; |
dan | b324cf7 | 2016-06-17 14:33:32 +0000 | [diff] [blame] | 833 | |
| 834 | /* Any terms specified as part of the ON(...) clause for any LEFT |
| 835 | ** JOIN for which the current table is not the rhs are omitted |
| 836 | ** from the cursor-hint. |
| 837 | ** |
dan | e6912fd | 2016-06-17 19:27:13 +0000 | [diff] [blame] | 838 | ** If this table is the rhs of a LEFT JOIN, "IS" or "IS NULL" terms |
| 839 | ** that were specified as part of the WHERE clause must be excluded. |
| 840 | ** This is to address the following: |
dan | b324cf7 | 2016-06-17 14:33:32 +0000 | [diff] [blame] | 841 | ** |
| 842 | ** SELECT ... t1 LEFT JOIN t2 ON (t1.a=t2.b) WHERE t2.c IS NULL; |
| 843 | ** |
dan | e6912fd | 2016-06-17 19:27:13 +0000 | [diff] [blame] | 844 | ** Say there is a single row in t2 that matches (t1.a=t2.b), but its |
| 845 | ** t2.c values is not NULL. If the (t2.c IS NULL) constraint is |
| 846 | ** pushed down to the cursor, this row is filtered out, causing |
| 847 | ** SQLite to synthesize a row of NULL values. Which does match the |
| 848 | ** WHERE clause, and so the query returns a row. Which is incorrect. |
| 849 | ** |
| 850 | ** For the same reason, WHERE terms such as: |
| 851 | ** |
| 852 | ** WHERE 1 = (t2.c IS NULL) |
| 853 | ** |
| 854 | ** are also excluded. See codeCursorHintIsOrFunction() for details. |
dan | b324cf7 | 2016-06-17 14:33:32 +0000 | [diff] [blame] | 855 | */ |
| 856 | if( pTabItem->fg.jointype & JT_LEFT ){ |
dan | e6912fd | 2016-06-17 19:27:13 +0000 | [diff] [blame] | 857 | Expr *pExpr = pTerm->pExpr; |
| 858 | if( !ExprHasProperty(pExpr, EP_FromJoin) |
| 859 | || pExpr->iRightJoinTable!=pTabItem->iCursor |
dan | b324cf7 | 2016-06-17 14:33:32 +0000 | [diff] [blame] | 860 | ){ |
dan | e6912fd | 2016-06-17 19:27:13 +0000 | [diff] [blame] | 861 | sWalker.eCode = 0; |
| 862 | sWalker.xExprCallback = codeCursorHintIsOrFunction; |
| 863 | sqlite3WalkExpr(&sWalker, pTerm->pExpr); |
| 864 | if( sWalker.eCode ) continue; |
dan | b324cf7 | 2016-06-17 14:33:32 +0000 | [diff] [blame] | 865 | } |
| 866 | }else{ |
| 867 | if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) continue; |
| 868 | } |
drh | b413a54 | 2015-08-17 17:19:28 +0000 | [diff] [blame] | 869 | |
| 870 | /* All terms in pWLoop->aLTerm[] except pEndRange are used to initialize |
drh | bcf40a7 | 2015-08-18 15:58:05 +0000 | [diff] [blame] | 871 | ** the cursor. These terms are not needed as hints for a pure range |
| 872 | ** scan (that has no == terms) so omit them. */ |
| 873 | if( pLoop->u.btree.nEq==0 && pTerm!=pEndRange ){ |
| 874 | for(j=0; j<pLoop->nLTerm && pLoop->aLTerm[j]!=pTerm; j++){} |
| 875 | if( j<pLoop->nLTerm ) continue; |
drh | b413a54 | 2015-08-17 17:19:28 +0000 | [diff] [blame] | 876 | } |
| 877 | |
| 878 | /* No subqueries or non-deterministic functions allowed */ |
drh | bec2476 | 2015-08-13 20:07:13 +0000 | [diff] [blame] | 879 | if( sqlite3ExprContainsSubquery(pTerm->pExpr) ) continue; |
drh | b413a54 | 2015-08-17 17:19:28 +0000 | [diff] [blame] | 880 | |
| 881 | /* For an index scan, make sure referenced columns are actually in |
| 882 | ** the index. */ |
drh | 2f2b027 | 2015-08-14 18:50:04 +0000 | [diff] [blame] | 883 | if( sHint.pIdx!=0 ){ |
| 884 | sWalker.eCode = 0; |
| 885 | sWalker.xExprCallback = codeCursorHintCheckExpr; |
| 886 | sqlite3WalkExpr(&sWalker, pTerm->pExpr); |
| 887 | if( sWalker.eCode ) continue; |
| 888 | } |
drh | b413a54 | 2015-08-17 17:19:28 +0000 | [diff] [blame] | 889 | |
| 890 | /* If we survive all prior tests, that means this term is worth hinting */ |
drh | bec2476 | 2015-08-13 20:07:13 +0000 | [diff] [blame] | 891 | pExpr = sqlite3ExprAnd(db, pExpr, sqlite3ExprDup(db, pTerm->pExpr, 0)); |
| 892 | } |
| 893 | if( pExpr!=0 ){ |
drh | bec2476 | 2015-08-13 20:07:13 +0000 | [diff] [blame] | 894 | sWalker.xExprCallback = codeCursorHintFixExpr; |
drh | bec2476 | 2015-08-13 20:07:13 +0000 | [diff] [blame] | 895 | sqlite3WalkExpr(&sWalker, pExpr); |
drh | 2f2b027 | 2015-08-14 18:50:04 +0000 | [diff] [blame] | 896 | sqlite3VdbeAddOp4(v, OP_CursorHint, |
| 897 | (sHint.pIdx ? sHint.iIdxCur : sHint.iTabCur), 0, 0, |
| 898 | (const char*)pExpr, P4_EXPR); |
drh | bec2476 | 2015-08-13 20:07:13 +0000 | [diff] [blame] | 899 | } |
| 900 | } |
| 901 | #else |
dan | b324cf7 | 2016-06-17 14:33:32 +0000 | [diff] [blame] | 902 | # define codeCursorHint(A,B,C,D) /* No-op */ |
drh | bec2476 | 2015-08-13 20:07:13 +0000 | [diff] [blame] | 903 | #endif /* SQLITE_ENABLE_CURSOR_HINTS */ |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 904 | |
| 905 | /* |
dan | de892d9 | 2016-01-29 19:29:45 +0000 | [diff] [blame] | 906 | ** Cursor iCur is open on an intkey b-tree (a table). Register iRowid contains |
| 907 | ** a rowid value just read from cursor iIdxCur, open on index pIdx. This |
| 908 | ** function generates code to do a deferred seek of cursor iCur to the |
| 909 | ** rowid stored in register iRowid. |
| 910 | ** |
| 911 | ** Normally, this is just: |
| 912 | ** |
| 913 | ** OP_Seek $iCur $iRowid |
| 914 | ** |
| 915 | ** However, if the scan currently being coded is a branch of an OR-loop and |
| 916 | ** the statement currently being coded is a SELECT, then P3 of the OP_Seek |
| 917 | ** is set to iIdxCur and P4 is set to point to an array of integers |
| 918 | ** containing one entry for each column of the table cursor iCur is open |
| 919 | ** on. For each table column, if the column is the i'th column of the |
| 920 | ** index, then the corresponding array entry is set to (i+1). If the column |
| 921 | ** does not appear in the index at all, the array entry is set to 0. |
| 922 | */ |
| 923 | static void codeDeferredSeek( |
| 924 | WhereInfo *pWInfo, /* Where clause context */ |
| 925 | Index *pIdx, /* Index scan is using */ |
| 926 | int iCur, /* Cursor for IPK b-tree */ |
dan | de892d9 | 2016-01-29 19:29:45 +0000 | [diff] [blame] | 927 | int iIdxCur /* Index cursor */ |
| 928 | ){ |
| 929 | Parse *pParse = pWInfo->pParse; /* Parse context */ |
| 930 | Vdbe *v = pParse->pVdbe; /* Vdbe to generate code within */ |
| 931 | |
| 932 | assert( iIdxCur>0 ); |
| 933 | assert( pIdx->aiColumn[pIdx->nColumn-1]==-1 ); |
| 934 | |
drh | 784c1b9 | 2016-01-30 16:59:56 +0000 | [diff] [blame] | 935 | sqlite3VdbeAddOp3(v, OP_Seek, iIdxCur, 0, iCur); |
drh | ce943bc | 2016-05-19 18:56:33 +0000 | [diff] [blame] | 936 | if( (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE) |
dan | cddb6ba | 2016-02-01 13:58:56 +0000 | [diff] [blame] | 937 | && DbMaskAllZero(sqlite3ParseToplevel(pParse)->writeMask) |
dan | de892d9 | 2016-01-29 19:29:45 +0000 | [diff] [blame] | 938 | ){ |
| 939 | int i; |
| 940 | Table *pTab = pIdx->pTable; |
drh | b170202 | 2016-01-30 00:45:18 +0000 | [diff] [blame] | 941 | int *ai = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int)*(pTab->nCol+1)); |
dan | de892d9 | 2016-01-29 19:29:45 +0000 | [diff] [blame] | 942 | if( ai ){ |
drh | b170202 | 2016-01-30 00:45:18 +0000 | [diff] [blame] | 943 | ai[0] = pTab->nCol; |
dan | de892d9 | 2016-01-29 19:29:45 +0000 | [diff] [blame] | 944 | for(i=0; i<pIdx->nColumn-1; i++){ |
| 945 | assert( pIdx->aiColumn[i]<pTab->nCol ); |
drh | b170202 | 2016-01-30 00:45:18 +0000 | [diff] [blame] | 946 | if( pIdx->aiColumn[i]>=0 ) ai[pIdx->aiColumn[i]+1] = i+1; |
dan | de892d9 | 2016-01-29 19:29:45 +0000 | [diff] [blame] | 947 | } |
| 948 | sqlite3VdbeChangeP4(v, -1, (char*)ai, P4_INTARRAY); |
| 949 | } |
| 950 | } |
| 951 | } |
| 952 | |
dan | 71c57db | 2016-07-09 20:23:55 +0000 | [diff] [blame] | 953 | static void codeExprOrVector(Parse *pParse, Expr *p, int iReg, int nReg){ |
| 954 | assert( nReg>0 ); |
dan | 625015e | 2016-07-30 16:39:28 +0000 | [diff] [blame^] | 955 | if( sqlite3ExprIsVector(p) ){ |
dan | 71c57db | 2016-07-09 20:23:55 +0000 | [diff] [blame] | 956 | int i; |
| 957 | if( (p->flags & EP_xIsSelect)==0 ){ |
| 958 | ExprList *pList = p->x.pList; |
| 959 | assert( nReg<=pList->nExpr ); |
| 960 | for(i=0; i<nReg; i++){ |
| 961 | sqlite3ExprCode(pParse, pList->a[i].pExpr, iReg+i); |
| 962 | } |
| 963 | }else{ |
| 964 | Vdbe *v = pParse->pVdbe; |
| 965 | int iSelect = sqlite3CodeSubselect(pParse, p, 0, 0); |
| 966 | sqlite3VdbeAddOp3(v, OP_Copy, iSelect, iReg, nReg-1); |
dan | 71c57db | 2016-07-09 20:23:55 +0000 | [diff] [blame] | 967 | } |
| 968 | }else{ |
| 969 | assert( nReg==1 ); |
| 970 | sqlite3ExprCode(pParse, p, iReg); |
| 971 | } |
| 972 | } |
| 973 | |
dan | de892d9 | 2016-01-29 19:29:45 +0000 | [diff] [blame] | 974 | /* |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 975 | ** Generate code for the start of the iLevel-th loop in the WHERE clause |
| 976 | ** implementation described by pWInfo. |
| 977 | */ |
| 978 | Bitmask sqlite3WhereCodeOneLoopStart( |
| 979 | WhereInfo *pWInfo, /* Complete information about the WHERE clause */ |
| 980 | int iLevel, /* Which level of pWInfo->a[] should be coded */ |
| 981 | Bitmask notReady /* Which tables are currently available */ |
| 982 | ){ |
| 983 | int j, k; /* Loop counters */ |
| 984 | int iCur; /* The VDBE cursor for the table */ |
| 985 | int addrNxt; /* Where to jump to continue with the next IN case */ |
| 986 | int omitTable; /* True if we use the index only */ |
| 987 | int bRev; /* True if we need to scan in reverse order */ |
| 988 | WhereLevel *pLevel; /* The where level to be coded */ |
| 989 | WhereLoop *pLoop; /* The WhereLoop object being coded */ |
| 990 | WhereClause *pWC; /* Decomposition of the entire WHERE clause */ |
| 991 | WhereTerm *pTerm; /* A WHERE clause term */ |
| 992 | Parse *pParse; /* Parsing context */ |
| 993 | sqlite3 *db; /* Database connection */ |
| 994 | Vdbe *v; /* The prepared stmt under constructions */ |
| 995 | struct SrcList_item *pTabItem; /* FROM clause term being coded */ |
| 996 | int addrBrk; /* Jump here to break out of the loop */ |
| 997 | int addrCont; /* Jump here to continue with next cycle */ |
| 998 | int iRowidReg = 0; /* Rowid is stored in this register, if not zero */ |
| 999 | int iReleaseReg = 0; /* Temp register to free before returning */ |
| 1000 | |
| 1001 | pParse = pWInfo->pParse; |
| 1002 | v = pParse->pVdbe; |
| 1003 | pWC = &pWInfo->sWC; |
| 1004 | db = pParse->db; |
| 1005 | pLevel = &pWInfo->a[iLevel]; |
| 1006 | pLoop = pLevel->pWLoop; |
| 1007 | pTabItem = &pWInfo->pTabList->a[pLevel->iFrom]; |
| 1008 | iCur = pTabItem->iCursor; |
| 1009 | pLevel->notReady = notReady & ~sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur); |
| 1010 | bRev = (pWInfo->revMask>>iLevel)&1; |
| 1011 | omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0 |
drh | ce943bc | 2016-05-19 18:56:33 +0000 | [diff] [blame] | 1012 | && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0; |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 1013 | VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName)); |
| 1014 | |
| 1015 | /* Create labels for the "break" and "continue" instructions |
| 1016 | ** for the current loop. Jump to addrBrk to break out of a loop. |
| 1017 | ** Jump to cont to go immediately to the next iteration of the |
| 1018 | ** loop. |
| 1019 | ** |
| 1020 | ** When there is an IN operator, we also have a "addrNxt" label that |
| 1021 | ** means to continue with the next IN value combination. When |
| 1022 | ** there are no IN operators in the constraints, the "addrNxt" label |
| 1023 | ** is the same as "addrBrk". |
| 1024 | */ |
| 1025 | addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v); |
| 1026 | addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v); |
| 1027 | |
| 1028 | /* If this is the right table of a LEFT OUTER JOIN, allocate and |
| 1029 | ** initialize a memory cell that records if this table matches any |
| 1030 | ** row of the left table of the join. |
| 1031 | */ |
drh | 8a48b9c | 2015-08-19 15:20:00 +0000 | [diff] [blame] | 1032 | if( pLevel->iFrom>0 && (pTabItem[0].fg.jointype & JT_LEFT)!=0 ){ |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 1033 | pLevel->iLeftJoin = ++pParse->nMem; |
| 1034 | sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin); |
| 1035 | VdbeComment((v, "init LEFT JOIN no-match flag")); |
| 1036 | } |
| 1037 | |
| 1038 | /* Special case of a FROM clause subquery implemented as a co-routine */ |
drh | 8a48b9c | 2015-08-19 15:20:00 +0000 | [diff] [blame] | 1039 | if( pTabItem->fg.viaCoroutine ){ |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 1040 | int regYield = pTabItem->regReturn; |
| 1041 | sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub); |
| 1042 | pLevel->p2 = sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk); |
| 1043 | VdbeCoverage(v); |
| 1044 | VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName)); |
| 1045 | pLevel->op = OP_Goto; |
| 1046 | }else |
| 1047 | |
| 1048 | #ifndef SQLITE_OMIT_VIRTUALTABLE |
| 1049 | if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){ |
| 1050 | /* Case 1: The table is a virtual-table. Use the VFilter and VNext |
| 1051 | ** to access the data. |
| 1052 | */ |
| 1053 | int iReg; /* P3 Value for OP_VFilter */ |
| 1054 | int addrNotFound; |
| 1055 | int nConstraint = pLoop->nLTerm; |
drh | dbc4916 | 2016-03-02 03:28:07 +0000 | [diff] [blame] | 1056 | int iIn; /* Counter for IN constraints */ |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 1057 | |
| 1058 | sqlite3ExprCachePush(pParse); |
| 1059 | iReg = sqlite3GetTempRange(pParse, nConstraint+2); |
| 1060 | addrNotFound = pLevel->addrBrk; |
| 1061 | for(j=0; j<nConstraint; j++){ |
| 1062 | int iTarget = iReg+j+2; |
| 1063 | pTerm = pLoop->aLTerm[j]; |
drh | 599d576 | 2016-03-08 01:11:51 +0000 | [diff] [blame] | 1064 | if( NEVER(pTerm==0) ) continue; |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 1065 | if( pTerm->eOperator & WO_IN ){ |
| 1066 | codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget); |
| 1067 | addrNotFound = pLevel->addrNxt; |
| 1068 | }else{ |
| 1069 | sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget); |
| 1070 | } |
| 1071 | } |
| 1072 | sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg); |
| 1073 | sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1); |
| 1074 | sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg, |
| 1075 | pLoop->u.vtab.idxStr, |
| 1076 | pLoop->u.vtab.needFree ? P4_MPRINTF : P4_STATIC); |
| 1077 | VdbeCoverage(v); |
| 1078 | pLoop->u.vtab.needFree = 0; |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 1079 | pLevel->p1 = iCur; |
dan | 354474a | 2015-09-29 10:11:26 +0000 | [diff] [blame] | 1080 | pLevel->op = pWInfo->eOnePass ? OP_Noop : OP_VNext; |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 1081 | pLevel->p2 = sqlite3VdbeCurrentAddr(v); |
drh | dbc4916 | 2016-03-02 03:28:07 +0000 | [diff] [blame] | 1082 | iIn = pLevel->u.in.nIn; |
| 1083 | for(j=nConstraint-1; j>=0; j--){ |
| 1084 | pTerm = pLoop->aLTerm[j]; |
| 1085 | if( j<16 && (pLoop->u.vtab.omitMask>>j)&1 ){ |
| 1086 | disableTerm(pLevel, pTerm); |
| 1087 | }else if( (pTerm->eOperator & WO_IN)!=0 ){ |
| 1088 | Expr *pCompare; /* The comparison operator */ |
| 1089 | Expr *pRight; /* RHS of the comparison */ |
| 1090 | VdbeOp *pOp; /* Opcode to access the value of the IN constraint */ |
| 1091 | |
| 1092 | /* Reload the constraint value into reg[iReg+j+2]. The same value |
| 1093 | ** was loaded into the same register prior to the OP_VFilter, but |
| 1094 | ** the xFilter implementation might have changed the datatype or |
| 1095 | ** encoding of the value in the register, so it *must* be reloaded. */ |
| 1096 | assert( pLevel->u.in.aInLoop!=0 || db->mallocFailed ); |
drh | fb826b8 | 2016-03-08 00:39:58 +0000 | [diff] [blame] | 1097 | if( !db->mallocFailed ){ |
drh | dbc4916 | 2016-03-02 03:28:07 +0000 | [diff] [blame] | 1098 | assert( iIn>0 ); |
| 1099 | pOp = sqlite3VdbeGetOp(v, pLevel->u.in.aInLoop[--iIn].addrInTop); |
| 1100 | assert( pOp->opcode==OP_Column || pOp->opcode==OP_Rowid ); |
| 1101 | assert( pOp->opcode!=OP_Column || pOp->p3==iReg+j+2 ); |
| 1102 | assert( pOp->opcode!=OP_Rowid || pOp->p2==iReg+j+2 ); |
| 1103 | testcase( pOp->opcode==OP_Rowid ); |
| 1104 | sqlite3VdbeAddOp3(v, pOp->opcode, pOp->p1, pOp->p2, pOp->p3); |
| 1105 | } |
| 1106 | |
| 1107 | /* Generate code that will continue to the next row if |
| 1108 | ** the IN constraint is not satisfied */ |
| 1109 | pCompare = sqlite3PExpr(pParse, TK_EQ, 0, 0, 0); |
| 1110 | assert( pCompare!=0 || db->mallocFailed ); |
| 1111 | if( pCompare ){ |
| 1112 | pCompare->pLeft = pTerm->pExpr->pLeft; |
| 1113 | pCompare->pRight = pRight = sqlite3Expr(db, TK_REGISTER, 0); |
drh | 237b2b7 | 2016-03-07 19:08:27 +0000 | [diff] [blame] | 1114 | if( pRight ){ |
| 1115 | pRight->iTable = iReg+j+2; |
| 1116 | sqlite3ExprIfFalse(pParse, pCompare, pLevel->addrCont, 0); |
| 1117 | } |
drh | dbc4916 | 2016-03-02 03:28:07 +0000 | [diff] [blame] | 1118 | pCompare->pLeft = 0; |
| 1119 | sqlite3ExprDelete(db, pCompare); |
| 1120 | } |
| 1121 | } |
| 1122 | } |
drh | ba26faa | 2016-04-09 18:04:28 +0000 | [diff] [blame] | 1123 | /* These registers need to be preserved in case there is an IN operator |
| 1124 | ** loop. So we could deallocate the registers here (and potentially |
| 1125 | ** reuse them later) if (pLoop->wsFlags & WHERE_IN_ABLE)==0. But it seems |
| 1126 | ** simpler and safer to simply not reuse the registers. |
| 1127 | ** |
| 1128 | ** sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2); |
| 1129 | */ |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 1130 | sqlite3ExprCachePop(pParse); |
| 1131 | }else |
| 1132 | #endif /* SQLITE_OMIT_VIRTUALTABLE */ |
| 1133 | |
| 1134 | if( (pLoop->wsFlags & WHERE_IPK)!=0 |
| 1135 | && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0 |
| 1136 | ){ |
| 1137 | /* Case 2: We can directly reference a single row using an |
| 1138 | ** equality comparison against the ROWID field. Or |
| 1139 | ** we reference multiple rows using a "rowid IN (...)" |
| 1140 | ** construct. |
| 1141 | */ |
| 1142 | assert( pLoop->u.btree.nEq==1 ); |
| 1143 | pTerm = pLoop->aLTerm[0]; |
| 1144 | assert( pTerm!=0 ); |
| 1145 | assert( pTerm->pExpr!=0 ); |
| 1146 | assert( omitTable==0 ); |
| 1147 | testcase( pTerm->wtFlags & TERM_VIRTUAL ); |
| 1148 | iReleaseReg = ++pParse->nMem; |
| 1149 | iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg); |
| 1150 | if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg); |
| 1151 | addrNxt = pLevel->addrNxt; |
drh | eeb9565 | 2016-05-26 20:56:38 +0000 | [diff] [blame] | 1152 | sqlite3VdbeAddOp3(v, OP_SeekRowid, iCur, addrNxt, iRowidReg); |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 1153 | VdbeCoverage(v); |
| 1154 | sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1); |
| 1155 | sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg); |
| 1156 | VdbeComment((v, "pk")); |
| 1157 | pLevel->op = OP_Noop; |
| 1158 | }else if( (pLoop->wsFlags & WHERE_IPK)!=0 |
| 1159 | && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0 |
| 1160 | ){ |
| 1161 | /* Case 3: We have an inequality comparison against the ROWID field. |
| 1162 | */ |
| 1163 | int testOp = OP_Noop; |
| 1164 | int start; |
| 1165 | int memEndValue = 0; |
| 1166 | WhereTerm *pStart, *pEnd; |
| 1167 | |
| 1168 | assert( omitTable==0 ); |
| 1169 | j = 0; |
| 1170 | pStart = pEnd = 0; |
| 1171 | if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++]; |
| 1172 | if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++]; |
| 1173 | assert( pStart!=0 || pEnd!=0 ); |
| 1174 | if( bRev ){ |
| 1175 | pTerm = pStart; |
| 1176 | pStart = pEnd; |
| 1177 | pEnd = pTerm; |
| 1178 | } |
dan | b324cf7 | 2016-06-17 14:33:32 +0000 | [diff] [blame] | 1179 | codeCursorHint(pTabItem, pWInfo, pLevel, pEnd); |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 1180 | if( pStart ){ |
| 1181 | Expr *pX; /* The expression that defines the start bound */ |
| 1182 | int r1, rTemp; /* Registers for holding the start boundary */ |
dan | 19ff12d | 2016-07-29 20:58:19 +0000 | [diff] [blame] | 1183 | int op; /* Cursor seek operation */ |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 1184 | |
| 1185 | /* The following constant maps TK_xx codes into corresponding |
| 1186 | ** seek opcodes. It depends on a particular ordering of TK_xx |
| 1187 | */ |
| 1188 | const u8 aMoveOp[] = { |
| 1189 | /* TK_GT */ OP_SeekGT, |
| 1190 | /* TK_LE */ OP_SeekLE, |
| 1191 | /* TK_LT */ OP_SeekLT, |
| 1192 | /* TK_GE */ OP_SeekGE |
| 1193 | }; |
| 1194 | assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */ |
| 1195 | assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */ |
| 1196 | assert( TK_GE==TK_GT+3 ); /* ... is correcct. */ |
| 1197 | |
| 1198 | assert( (pStart->wtFlags & TERM_VNULL)==0 ); |
| 1199 | testcase( pStart->wtFlags & TERM_VIRTUAL ); |
| 1200 | pX = pStart->pExpr; |
| 1201 | assert( pX!=0 ); |
| 1202 | testcase( pStart->leftCursor!=iCur ); /* transitive constraints */ |
dan | 625015e | 2016-07-30 16:39:28 +0000 | [diff] [blame^] | 1203 | if( sqlite3ExprIsVector(pX->pRight) ){ |
dan | 19ff12d | 2016-07-29 20:58:19 +0000 | [diff] [blame] | 1204 | r1 = rTemp = sqlite3GetTempReg(pParse); |
| 1205 | codeExprOrVector(pParse, pX->pRight, r1, 1); |
| 1206 | op = aMoveOp[(pX->op - TK_GT) | 0x0001]; |
| 1207 | }else{ |
| 1208 | r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp); |
| 1209 | disableTerm(pLevel, pStart); |
| 1210 | op = aMoveOp[(pX->op - TK_GT)]; |
| 1211 | } |
| 1212 | sqlite3VdbeAddOp3(v, op, iCur, addrBrk, r1); |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 1213 | VdbeComment((v, "pk")); |
| 1214 | VdbeCoverageIf(v, pX->op==TK_GT); |
| 1215 | VdbeCoverageIf(v, pX->op==TK_LE); |
| 1216 | VdbeCoverageIf(v, pX->op==TK_LT); |
| 1217 | VdbeCoverageIf(v, pX->op==TK_GE); |
| 1218 | sqlite3ExprCacheAffinityChange(pParse, r1, 1); |
| 1219 | sqlite3ReleaseTempReg(pParse, rTemp); |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 1220 | }else{ |
| 1221 | sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk); |
| 1222 | VdbeCoverageIf(v, bRev==0); |
| 1223 | VdbeCoverageIf(v, bRev!=0); |
| 1224 | } |
| 1225 | if( pEnd ){ |
| 1226 | Expr *pX; |
| 1227 | pX = pEnd->pExpr; |
| 1228 | assert( pX!=0 ); |
| 1229 | assert( (pEnd->wtFlags & TERM_VNULL)==0 ); |
| 1230 | testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */ |
| 1231 | testcase( pEnd->wtFlags & TERM_VIRTUAL ); |
| 1232 | memEndValue = ++pParse->nMem; |
dan | 19ff12d | 2016-07-29 20:58:19 +0000 | [diff] [blame] | 1233 | codeExprOrVector(pParse, pX->pRight, memEndValue, 1); |
dan | 625015e | 2016-07-30 16:39:28 +0000 | [diff] [blame^] | 1234 | if( 0==sqlite3ExprIsVector(pX->pRight) |
| 1235 | && (pX->op==TK_LT || pX->op==TK_GT) |
| 1236 | ){ |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 1237 | testOp = bRev ? OP_Le : OP_Ge; |
| 1238 | }else{ |
| 1239 | testOp = bRev ? OP_Lt : OP_Gt; |
| 1240 | } |
| 1241 | disableTerm(pLevel, pEnd); |
| 1242 | } |
| 1243 | start = sqlite3VdbeCurrentAddr(v); |
| 1244 | pLevel->op = bRev ? OP_Prev : OP_Next; |
| 1245 | pLevel->p1 = iCur; |
| 1246 | pLevel->p2 = start; |
| 1247 | assert( pLevel->p5==0 ); |
| 1248 | if( testOp!=OP_Noop ){ |
| 1249 | iRowidReg = ++pParse->nMem; |
| 1250 | sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg); |
| 1251 | sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg); |
| 1252 | sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg); |
| 1253 | VdbeCoverageIf(v, testOp==OP_Le); |
| 1254 | VdbeCoverageIf(v, testOp==OP_Lt); |
| 1255 | VdbeCoverageIf(v, testOp==OP_Ge); |
| 1256 | VdbeCoverageIf(v, testOp==OP_Gt); |
| 1257 | sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL); |
| 1258 | } |
| 1259 | }else if( pLoop->wsFlags & WHERE_INDEXED ){ |
| 1260 | /* Case 4: A scan using an index. |
| 1261 | ** |
| 1262 | ** The WHERE clause may contain zero or more equality |
| 1263 | ** terms ("==" or "IN" operators) that refer to the N |
| 1264 | ** left-most columns of the index. It may also contain |
| 1265 | ** inequality constraints (>, <, >= or <=) on the indexed |
| 1266 | ** column that immediately follows the N equalities. Only |
| 1267 | ** the right-most column can be an inequality - the rest must |
| 1268 | ** use the "==" and "IN" operators. For example, if the |
| 1269 | ** index is on (x,y,z), then the following clauses are all |
| 1270 | ** optimized: |
| 1271 | ** |
| 1272 | ** x=5 |
| 1273 | ** x=5 AND y=10 |
| 1274 | ** x=5 AND y<10 |
| 1275 | ** x=5 AND y>5 AND y<10 |
| 1276 | ** x=5 AND y=5 AND z<=10 |
| 1277 | ** |
| 1278 | ** The z<10 term of the following cannot be used, only |
| 1279 | ** the x=5 term: |
| 1280 | ** |
| 1281 | ** x=5 AND z<10 |
| 1282 | ** |
| 1283 | ** N may be zero if there are inequality constraints. |
| 1284 | ** If there are no inequality constraints, then N is at |
| 1285 | ** least one. |
| 1286 | ** |
| 1287 | ** This case is also used when there are no WHERE clause |
| 1288 | ** constraints but an index is selected anyway, in order |
| 1289 | ** to force the output order to conform to an ORDER BY. |
| 1290 | */ |
| 1291 | static const u8 aStartOp[] = { |
| 1292 | 0, |
| 1293 | 0, |
| 1294 | OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */ |
| 1295 | OP_Last, /* 3: (!start_constraints && startEq && bRev) */ |
| 1296 | OP_SeekGT, /* 4: (start_constraints && !startEq && !bRev) */ |
| 1297 | OP_SeekLT, /* 5: (start_constraints && !startEq && bRev) */ |
| 1298 | OP_SeekGE, /* 6: (start_constraints && startEq && !bRev) */ |
| 1299 | OP_SeekLE /* 7: (start_constraints && startEq && bRev) */ |
| 1300 | }; |
| 1301 | static const u8 aEndOp[] = { |
| 1302 | OP_IdxGE, /* 0: (end_constraints && !bRev && !endEq) */ |
| 1303 | OP_IdxGT, /* 1: (end_constraints && !bRev && endEq) */ |
| 1304 | OP_IdxLE, /* 2: (end_constraints && bRev && !endEq) */ |
| 1305 | OP_IdxLT, /* 3: (end_constraints && bRev && endEq) */ |
| 1306 | }; |
| 1307 | u16 nEq = pLoop->u.btree.nEq; /* Number of == or IN terms */ |
dan | 71c57db | 2016-07-09 20:23:55 +0000 | [diff] [blame] | 1308 | u16 nBtm = pLoop->u.btree.nBtm; /* Length of BTM vector */ |
| 1309 | u16 nTop = pLoop->u.btree.nTop; /* Length of TOP vector */ |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 1310 | int regBase; /* Base register holding constraint values */ |
| 1311 | WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */ |
| 1312 | WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */ |
| 1313 | int startEq; /* True if range start uses ==, >= or <= */ |
| 1314 | int endEq; /* True if range end uses ==, >= or <= */ |
| 1315 | int start_constraints; /* Start of range is constrained */ |
| 1316 | int nConstraint; /* Number of constraint terms */ |
| 1317 | Index *pIdx; /* The index we will be using */ |
| 1318 | int iIdxCur; /* The VDBE cursor for the index */ |
| 1319 | int nExtraReg = 0; /* Number of extra registers needed */ |
| 1320 | int op; /* Instruction opcode */ |
| 1321 | char *zStartAff; /* Affinity for start of range constraint */ |
| 1322 | char cEndAff = 0; /* Affinity for end of range constraint */ |
| 1323 | u8 bSeekPastNull = 0; /* True to seek past initial nulls */ |
| 1324 | u8 bStopAtNull = 0; /* Add condition to terminate at NULLs */ |
| 1325 | |
| 1326 | pIdx = pLoop->u.btree.pIndex; |
| 1327 | iIdxCur = pLevel->iIdxCur; |
| 1328 | assert( nEq>=pLoop->nSkip ); |
| 1329 | |
| 1330 | /* If this loop satisfies a sort order (pOrderBy) request that |
| 1331 | ** was passed to this function to implement a "SELECT min(x) ..." |
| 1332 | ** query, then the caller will only allow the loop to run for |
| 1333 | ** a single iteration. This means that the first row returned |
| 1334 | ** should not have a NULL value stored in 'x'. If column 'x' is |
| 1335 | ** the first one after the nEq equality constraints in the index, |
| 1336 | ** this requires some special handling. |
| 1337 | */ |
| 1338 | assert( pWInfo->pOrderBy==0 |
| 1339 | || pWInfo->pOrderBy->nExpr==1 |
| 1340 | || (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0 ); |
| 1341 | if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0 |
| 1342 | && pWInfo->nOBSat>0 |
| 1343 | && (pIdx->nKeyCol>nEq) |
| 1344 | ){ |
| 1345 | assert( pLoop->nSkip==0 ); |
| 1346 | bSeekPastNull = 1; |
| 1347 | nExtraReg = 1; |
| 1348 | } |
| 1349 | |
| 1350 | /* Find any inequality constraint terms for the start and end |
| 1351 | ** of the range. |
| 1352 | */ |
| 1353 | j = nEq; |
| 1354 | if( pLoop->wsFlags & WHERE_BTM_LIMIT ){ |
| 1355 | pRangeStart = pLoop->aLTerm[j++]; |
dan | 71c57db | 2016-07-09 20:23:55 +0000 | [diff] [blame] | 1356 | nExtraReg = MAX(nExtraReg, pLoop->u.btree.nBtm); |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 1357 | /* Like optimization range constraints always occur in pairs */ |
| 1358 | assert( (pRangeStart->wtFlags & TERM_LIKEOPT)==0 || |
| 1359 | (pLoop->wsFlags & WHERE_TOP_LIMIT)!=0 ); |
| 1360 | } |
| 1361 | if( pLoop->wsFlags & WHERE_TOP_LIMIT ){ |
| 1362 | pRangeEnd = pLoop->aLTerm[j++]; |
dan | 71c57db | 2016-07-09 20:23:55 +0000 | [diff] [blame] | 1363 | nExtraReg = MAX(nExtraReg, pLoop->u.btree.nTop); |
drh | 41d2e66 | 2015-12-01 21:23:07 +0000 | [diff] [blame] | 1364 | #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 1365 | if( (pRangeEnd->wtFlags & TERM_LIKEOPT)!=0 ){ |
| 1366 | assert( pRangeStart!=0 ); /* LIKE opt constraints */ |
| 1367 | assert( pRangeStart->wtFlags & TERM_LIKEOPT ); /* occur in pairs */ |
drh | 44aebff | 2016-05-02 10:25:42 +0000 | [diff] [blame] | 1368 | pLevel->iLikeRepCntr = (u32)++pParse->nMem; |
| 1369 | sqlite3VdbeAddOp2(v, OP_Integer, 1, (int)pLevel->iLikeRepCntr); |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 1370 | VdbeComment((v, "LIKE loop counter")); |
| 1371 | pLevel->addrLikeRep = sqlite3VdbeCurrentAddr(v); |
drh | 44aebff | 2016-05-02 10:25:42 +0000 | [diff] [blame] | 1372 | /* iLikeRepCntr actually stores 2x the counter register number. The |
| 1373 | ** bottom bit indicates whether the search order is ASC or DESC. */ |
| 1374 | testcase( bRev ); |
| 1375 | testcase( pIdx->aSortOrder[nEq]==SQLITE_SO_DESC ); |
| 1376 | assert( (bRev & ~1)==0 ); |
| 1377 | pLevel->iLikeRepCntr <<=1; |
| 1378 | pLevel->iLikeRepCntr |= bRev ^ (pIdx->aSortOrder[nEq]==SQLITE_SO_DESC); |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 1379 | } |
drh | 41d2e66 | 2015-12-01 21:23:07 +0000 | [diff] [blame] | 1380 | #endif |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 1381 | if( pRangeStart==0 |
| 1382 | && (j = pIdx->aiColumn[nEq])>=0 |
| 1383 | && pIdx->pTable->aCol[j].notNull==0 |
| 1384 | ){ |
| 1385 | bSeekPastNull = 1; |
| 1386 | } |
| 1387 | } |
| 1388 | assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 ); |
| 1389 | |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 1390 | /* If we are doing a reverse order scan on an ascending index, or |
| 1391 | ** a forward order scan on a descending index, interchange the |
| 1392 | ** start and end terms (pRangeStart and pRangeEnd). |
| 1393 | */ |
| 1394 | if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC)) |
| 1395 | || (bRev && pIdx->nKeyCol==nEq) |
| 1396 | ){ |
| 1397 | SWAP(WhereTerm *, pRangeEnd, pRangeStart); |
| 1398 | SWAP(u8, bSeekPastNull, bStopAtNull); |
dan | 71c57db | 2016-07-09 20:23:55 +0000 | [diff] [blame] | 1399 | SWAP(u8, nBtm, nTop); |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 1400 | } |
| 1401 | |
drh | bcf40a7 | 2015-08-18 15:58:05 +0000 | [diff] [blame] | 1402 | /* Generate code to evaluate all constraint terms using == or IN |
| 1403 | ** and store the values of those terms in an array of registers |
| 1404 | ** starting at regBase. |
| 1405 | */ |
dan | b324cf7 | 2016-06-17 14:33:32 +0000 | [diff] [blame] | 1406 | codeCursorHint(pTabItem, pWInfo, pLevel, pRangeEnd); |
drh | bcf40a7 | 2015-08-18 15:58:05 +0000 | [diff] [blame] | 1407 | regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff); |
| 1408 | assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq ); |
| 1409 | if( zStartAff ) cEndAff = zStartAff[nEq]; |
| 1410 | addrNxt = pLevel->addrNxt; |
| 1411 | |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 1412 | testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 ); |
| 1413 | testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 ); |
| 1414 | testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 ); |
| 1415 | testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 ); |
| 1416 | startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE); |
| 1417 | endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE); |
| 1418 | start_constraints = pRangeStart || nEq>0; |
| 1419 | |
| 1420 | /* Seek the index cursor to the start of the range. */ |
| 1421 | nConstraint = nEq; |
| 1422 | if( pRangeStart ){ |
| 1423 | Expr *pRight = pRangeStart->pExpr->pRight; |
dan | 71c57db | 2016-07-09 20:23:55 +0000 | [diff] [blame] | 1424 | codeExprOrVector(pParse, pRight, regBase+nEq, nBtm); |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 1425 | whereLikeOptimizationStringFixup(v, pLevel, pRangeStart); |
| 1426 | if( (pRangeStart->wtFlags & TERM_VNULL)==0 |
| 1427 | && sqlite3ExprCanBeNull(pRight) |
| 1428 | ){ |
| 1429 | sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt); |
| 1430 | VdbeCoverage(v); |
| 1431 | } |
| 1432 | if( zStartAff ){ |
| 1433 | if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_BLOB){ |
| 1434 | /* Since the comparison is to be performed with no conversions |
| 1435 | ** applied to the operands, set the affinity to apply to pRight to |
| 1436 | ** SQLITE_AFF_BLOB. */ |
| 1437 | zStartAff[nEq] = SQLITE_AFF_BLOB; |
| 1438 | } |
| 1439 | if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){ |
| 1440 | zStartAff[nEq] = SQLITE_AFF_BLOB; |
| 1441 | } |
| 1442 | } |
dan | 71c57db | 2016-07-09 20:23:55 +0000 | [diff] [blame] | 1443 | nConstraint += nBtm; |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 1444 | testcase( pRangeStart->wtFlags & TERM_VIRTUAL ); |
dan | 625015e | 2016-07-30 16:39:28 +0000 | [diff] [blame^] | 1445 | if( sqlite3ExprIsVector(pRight)==0 ){ |
dan | 71c57db | 2016-07-09 20:23:55 +0000 | [diff] [blame] | 1446 | disableTerm(pLevel, pRangeStart); |
| 1447 | }else{ |
| 1448 | startEq = 1; |
| 1449 | } |
drh | 426f4ab | 2016-07-26 04:31:14 +0000 | [diff] [blame] | 1450 | bSeekPastNull = 0; |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 1451 | }else if( bSeekPastNull ){ |
| 1452 | sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq); |
| 1453 | nConstraint++; |
| 1454 | startEq = 0; |
| 1455 | start_constraints = 1; |
| 1456 | } |
| 1457 | codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff); |
drh | 0bf2ad6 | 2016-02-22 21:19:54 +0000 | [diff] [blame] | 1458 | if( pLoop->nSkip>0 && nConstraint==pLoop->nSkip ){ |
| 1459 | /* The skip-scan logic inside the call to codeAllEqualityConstraints() |
| 1460 | ** above has already left the cursor sitting on the correct row, |
| 1461 | ** so no further seeking is needed */ |
| 1462 | }else{ |
drh | a6d2f8e | 2016-02-22 20:52:26 +0000 | [diff] [blame] | 1463 | op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev]; |
| 1464 | assert( op!=0 ); |
| 1465 | sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint); |
| 1466 | VdbeCoverage(v); |
| 1467 | VdbeCoverageIf(v, op==OP_Rewind); testcase( op==OP_Rewind ); |
| 1468 | VdbeCoverageIf(v, op==OP_Last); testcase( op==OP_Last ); |
| 1469 | VdbeCoverageIf(v, op==OP_SeekGT); testcase( op==OP_SeekGT ); |
| 1470 | VdbeCoverageIf(v, op==OP_SeekGE); testcase( op==OP_SeekGE ); |
| 1471 | VdbeCoverageIf(v, op==OP_SeekLE); testcase( op==OP_SeekLE ); |
| 1472 | VdbeCoverageIf(v, op==OP_SeekLT); testcase( op==OP_SeekLT ); |
| 1473 | } |
drh | 0bf2ad6 | 2016-02-22 21:19:54 +0000 | [diff] [blame] | 1474 | |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 1475 | /* Load the value for the inequality constraint at the end of the |
| 1476 | ** range (if any). |
| 1477 | */ |
| 1478 | nConstraint = nEq; |
| 1479 | if( pRangeEnd ){ |
| 1480 | Expr *pRight = pRangeEnd->pExpr->pRight; |
| 1481 | sqlite3ExprCacheRemove(pParse, regBase+nEq, 1); |
dan | 71c57db | 2016-07-09 20:23:55 +0000 | [diff] [blame] | 1482 | codeExprOrVector(pParse, pRight, regBase+nEq, nTop); |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 1483 | whereLikeOptimizationStringFixup(v, pLevel, pRangeEnd); |
| 1484 | if( (pRangeEnd->wtFlags & TERM_VNULL)==0 |
| 1485 | && sqlite3ExprCanBeNull(pRight) |
| 1486 | ){ |
| 1487 | sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt); |
| 1488 | VdbeCoverage(v); |
| 1489 | } |
| 1490 | if( sqlite3CompareAffinity(pRight, cEndAff)!=SQLITE_AFF_BLOB |
| 1491 | && !sqlite3ExprNeedsNoAffinityChange(pRight, cEndAff) |
| 1492 | ){ |
| 1493 | codeApplyAffinity(pParse, regBase+nEq, 1, &cEndAff); |
| 1494 | } |
dan | 71c57db | 2016-07-09 20:23:55 +0000 | [diff] [blame] | 1495 | nConstraint += nTop; |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 1496 | testcase( pRangeEnd->wtFlags & TERM_VIRTUAL ); |
dan | 71c57db | 2016-07-09 20:23:55 +0000 | [diff] [blame] | 1497 | |
dan | 625015e | 2016-07-30 16:39:28 +0000 | [diff] [blame^] | 1498 | if( sqlite3ExprIsVector(pRight)==0 ){ |
dan | 71c57db | 2016-07-09 20:23:55 +0000 | [diff] [blame] | 1499 | disableTerm(pLevel, pRangeEnd); |
| 1500 | }else{ |
| 1501 | endEq = 1; |
| 1502 | } |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 1503 | }else if( bStopAtNull ){ |
| 1504 | sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq); |
| 1505 | endEq = 0; |
| 1506 | nConstraint++; |
| 1507 | } |
| 1508 | sqlite3DbFree(db, zStartAff); |
| 1509 | |
| 1510 | /* Top of the loop body */ |
| 1511 | pLevel->p2 = sqlite3VdbeCurrentAddr(v); |
| 1512 | |
| 1513 | /* Check if the index cursor is past the end of the range. */ |
| 1514 | if( nConstraint ){ |
| 1515 | op = aEndOp[bRev*2 + endEq]; |
| 1516 | sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint); |
| 1517 | testcase( op==OP_IdxGT ); VdbeCoverageIf(v, op==OP_IdxGT ); |
| 1518 | testcase( op==OP_IdxGE ); VdbeCoverageIf(v, op==OP_IdxGE ); |
| 1519 | testcase( op==OP_IdxLT ); VdbeCoverageIf(v, op==OP_IdxLT ); |
| 1520 | testcase( op==OP_IdxLE ); VdbeCoverageIf(v, op==OP_IdxLE ); |
| 1521 | } |
| 1522 | |
| 1523 | /* Seek the table cursor, if required */ |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 1524 | if( omitTable ){ |
| 1525 | /* pIdx is a covering index. No need to access the main table. */ |
| 1526 | }else if( HasRowid(pIdx->pTable) ){ |
drh | f09c482 | 2016-05-06 20:23:12 +0000 | [diff] [blame] | 1527 | if( (pWInfo->wctrlFlags & WHERE_SEEK_TABLE)!=0 ){ |
drh | 784c1b9 | 2016-01-30 16:59:56 +0000 | [diff] [blame] | 1528 | iRowidReg = ++pParse->nMem; |
| 1529 | sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg); |
| 1530 | sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg); |
dan | c6157e1 | 2015-09-14 09:23:47 +0000 | [diff] [blame] | 1531 | sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, iRowidReg); |
drh | 66336f3 | 2015-09-14 14:08:25 +0000 | [diff] [blame] | 1532 | VdbeCoverage(v); |
dan | c6157e1 | 2015-09-14 09:23:47 +0000 | [diff] [blame] | 1533 | }else{ |
drh | 784c1b9 | 2016-01-30 16:59:56 +0000 | [diff] [blame] | 1534 | codeDeferredSeek(pWInfo, pIdx, iCur, iIdxCur); |
dan | c6157e1 | 2015-09-14 09:23:47 +0000 | [diff] [blame] | 1535 | } |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 1536 | }else if( iCur!=iIdxCur ){ |
| 1537 | Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable); |
| 1538 | iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol); |
| 1539 | for(j=0; j<pPk->nKeyCol; j++){ |
| 1540 | k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]); |
| 1541 | sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j); |
| 1542 | } |
| 1543 | sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont, |
| 1544 | iRowidReg, pPk->nKeyCol); VdbeCoverage(v); |
| 1545 | } |
| 1546 | |
dan | 71c57db | 2016-07-09 20:23:55 +0000 | [diff] [blame] | 1547 | /* Record the instruction used to terminate the loop. */ |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 1548 | if( pLoop->wsFlags & WHERE_ONEROW ){ |
| 1549 | pLevel->op = OP_Noop; |
| 1550 | }else if( bRev ){ |
| 1551 | pLevel->op = OP_Prev; |
| 1552 | }else{ |
| 1553 | pLevel->op = OP_Next; |
| 1554 | } |
| 1555 | pLevel->p1 = iIdxCur; |
| 1556 | pLevel->p3 = (pLoop->wsFlags&WHERE_UNQ_WANTED)!=0 ? 1:0; |
| 1557 | if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){ |
| 1558 | pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP; |
| 1559 | }else{ |
| 1560 | assert( pLevel->p5==0 ); |
| 1561 | } |
| 1562 | }else |
| 1563 | |
| 1564 | #ifndef SQLITE_OMIT_OR_OPTIMIZATION |
| 1565 | if( pLoop->wsFlags & WHERE_MULTI_OR ){ |
| 1566 | /* Case 5: Two or more separately indexed terms connected by OR |
| 1567 | ** |
| 1568 | ** Example: |
| 1569 | ** |
| 1570 | ** CREATE TABLE t1(a,b,c,d); |
| 1571 | ** CREATE INDEX i1 ON t1(a); |
| 1572 | ** CREATE INDEX i2 ON t1(b); |
| 1573 | ** CREATE INDEX i3 ON t1(c); |
| 1574 | ** |
| 1575 | ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13) |
| 1576 | ** |
| 1577 | ** In the example, there are three indexed terms connected by OR. |
| 1578 | ** The top of the loop looks like this: |
| 1579 | ** |
| 1580 | ** Null 1 # Zero the rowset in reg 1 |
| 1581 | ** |
| 1582 | ** Then, for each indexed term, the following. The arguments to |
| 1583 | ** RowSetTest are such that the rowid of the current row is inserted |
| 1584 | ** into the RowSet. If it is already present, control skips the |
| 1585 | ** Gosub opcode and jumps straight to the code generated by WhereEnd(). |
| 1586 | ** |
| 1587 | ** sqlite3WhereBegin(<term>) |
| 1588 | ** RowSetTest # Insert rowid into rowset |
| 1589 | ** Gosub 2 A |
| 1590 | ** sqlite3WhereEnd() |
| 1591 | ** |
| 1592 | ** Following the above, code to terminate the loop. Label A, the target |
| 1593 | ** of the Gosub above, jumps to the instruction right after the Goto. |
| 1594 | ** |
| 1595 | ** Null 1 # Zero the rowset in reg 1 |
| 1596 | ** Goto B # The loop is finished. |
| 1597 | ** |
| 1598 | ** A: <loop body> # Return data, whatever. |
| 1599 | ** |
| 1600 | ** Return 2 # Jump back to the Gosub |
| 1601 | ** |
| 1602 | ** B: <after the loop> |
| 1603 | ** |
| 1604 | ** Added 2014-05-26: If the table is a WITHOUT ROWID table, then |
| 1605 | ** use an ephemeral index instead of a RowSet to record the primary |
| 1606 | ** keys of the rows we have already seen. |
| 1607 | ** |
| 1608 | */ |
| 1609 | WhereClause *pOrWc; /* The OR-clause broken out into subterms */ |
| 1610 | SrcList *pOrTab; /* Shortened table list or OR-clause generation */ |
| 1611 | Index *pCov = 0; /* Potential covering index (or NULL) */ |
| 1612 | int iCovCur = pParse->nTab++; /* Cursor used for index scans (if any) */ |
| 1613 | |
| 1614 | int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */ |
| 1615 | int regRowset = 0; /* Register for RowSet object */ |
| 1616 | int regRowid = 0; /* Register holding rowid */ |
| 1617 | int iLoopBody = sqlite3VdbeMakeLabel(v); /* Start of loop body */ |
| 1618 | int iRetInit; /* Address of regReturn init */ |
| 1619 | int untestedTerms = 0; /* Some terms not completely tested */ |
| 1620 | int ii; /* Loop counter */ |
| 1621 | u16 wctrlFlags; /* Flags for sub-WHERE clause */ |
| 1622 | Expr *pAndExpr = 0; /* An ".. AND (...)" expression */ |
| 1623 | Table *pTab = pTabItem->pTab; |
dan | 145b4ea | 2016-07-29 18:12:12 +0000 | [diff] [blame] | 1624 | |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 1625 | pTerm = pLoop->aLTerm[0]; |
| 1626 | assert( pTerm!=0 ); |
| 1627 | assert( pTerm->eOperator & WO_OR ); |
| 1628 | assert( (pTerm->wtFlags & TERM_ORINFO)!=0 ); |
| 1629 | pOrWc = &pTerm->u.pOrInfo->wc; |
| 1630 | pLevel->op = OP_Return; |
| 1631 | pLevel->p1 = regReturn; |
| 1632 | |
| 1633 | /* Set up a new SrcList in pOrTab containing the table being scanned |
| 1634 | ** by this loop in the a[0] slot and all notReady tables in a[1..] slots. |
| 1635 | ** This becomes the SrcList in the recursive call to sqlite3WhereBegin(). |
| 1636 | */ |
| 1637 | if( pWInfo->nLevel>1 ){ |
| 1638 | int nNotReady; /* The number of notReady tables */ |
| 1639 | struct SrcList_item *origSrc; /* Original list of tables */ |
| 1640 | nNotReady = pWInfo->nLevel - iLevel - 1; |
| 1641 | pOrTab = sqlite3StackAllocRaw(db, |
| 1642 | sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0])); |
| 1643 | if( pOrTab==0 ) return notReady; |
| 1644 | pOrTab->nAlloc = (u8)(nNotReady + 1); |
| 1645 | pOrTab->nSrc = pOrTab->nAlloc; |
| 1646 | memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem)); |
| 1647 | origSrc = pWInfo->pTabList->a; |
| 1648 | for(k=1; k<=nNotReady; k++){ |
| 1649 | memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k])); |
| 1650 | } |
| 1651 | }else{ |
| 1652 | pOrTab = pWInfo->pTabList; |
| 1653 | } |
| 1654 | |
| 1655 | /* Initialize the rowset register to contain NULL. An SQL NULL is |
| 1656 | ** equivalent to an empty rowset. Or, create an ephemeral index |
| 1657 | ** capable of holding primary keys in the case of a WITHOUT ROWID. |
| 1658 | ** |
| 1659 | ** Also initialize regReturn to contain the address of the instruction |
| 1660 | ** immediately following the OP_Return at the bottom of the loop. This |
| 1661 | ** is required in a few obscure LEFT JOIN cases where control jumps |
| 1662 | ** over the top of the loop into the body of it. In this case the |
| 1663 | ** correct response for the end-of-loop code (the OP_Return) is to |
| 1664 | ** fall through to the next instruction, just as an OP_Next does if |
| 1665 | ** called on an uninitialized cursor. |
| 1666 | */ |
| 1667 | if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){ |
| 1668 | if( HasRowid(pTab) ){ |
| 1669 | regRowset = ++pParse->nMem; |
| 1670 | sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset); |
| 1671 | }else{ |
| 1672 | Index *pPk = sqlite3PrimaryKeyIndex(pTab); |
| 1673 | regRowset = pParse->nTab++; |
| 1674 | sqlite3VdbeAddOp2(v, OP_OpenEphemeral, regRowset, pPk->nKeyCol); |
| 1675 | sqlite3VdbeSetP4KeyInfo(pParse, pPk); |
| 1676 | } |
| 1677 | regRowid = ++pParse->nMem; |
| 1678 | } |
| 1679 | iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn); |
| 1680 | |
| 1681 | /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y |
| 1682 | ** Then for every term xN, evaluate as the subexpression: xN AND z |
| 1683 | ** That way, terms in y that are factored into the disjunction will |
| 1684 | ** be picked up by the recursive calls to sqlite3WhereBegin() below. |
| 1685 | ** |
| 1686 | ** Actually, each subexpression is converted to "xN AND w" where w is |
| 1687 | ** the "interesting" terms of z - terms that did not originate in the |
| 1688 | ** ON or USING clause of a LEFT JOIN, and terms that are usable as |
| 1689 | ** indices. |
| 1690 | ** |
| 1691 | ** This optimization also only applies if the (x1 OR x2 OR ...) term |
| 1692 | ** is not contained in the ON clause of a LEFT JOIN. |
| 1693 | ** See ticket http://www.sqlite.org/src/info/f2369304e4 |
| 1694 | */ |
| 1695 | if( pWC->nTerm>1 ){ |
| 1696 | int iTerm; |
| 1697 | for(iTerm=0; iTerm<pWC->nTerm; iTerm++){ |
| 1698 | Expr *pExpr = pWC->a[iTerm].pExpr; |
| 1699 | if( &pWC->a[iTerm] == pTerm ) continue; |
| 1700 | if( ExprHasProperty(pExpr, EP_FromJoin) ) continue; |
drh | 3b83f0c | 2016-01-29 16:57:06 +0000 | [diff] [blame] | 1701 | testcase( pWC->a[iTerm].wtFlags & TERM_VIRTUAL ); |
| 1702 | testcase( pWC->a[iTerm].wtFlags & TERM_CODED ); |
| 1703 | if( (pWC->a[iTerm].wtFlags & (TERM_VIRTUAL|TERM_CODED))!=0 ) continue; |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 1704 | if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue; |
| 1705 | testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO ); |
| 1706 | pExpr = sqlite3ExprDup(db, pExpr, 0); |
| 1707 | pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr); |
| 1708 | } |
| 1709 | if( pAndExpr ){ |
drh | 1167d32 | 2015-10-28 20:01:45 +0000 | [diff] [blame] | 1710 | pAndExpr = sqlite3PExpr(pParse, TK_AND|TKFLG_DONTFOLD, 0, pAndExpr, 0); |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 1711 | } |
| 1712 | } |
| 1713 | |
| 1714 | /* Run a separate WHERE clause for each term of the OR clause. After |
| 1715 | ** eliminating duplicates from other WHERE clauses, the action for each |
| 1716 | ** sub-WHERE clause is to to invoke the main loop body as a subroutine. |
| 1717 | */ |
drh | ce943bc | 2016-05-19 18:56:33 +0000 | [diff] [blame] | 1718 | wctrlFlags = WHERE_OR_SUBCLAUSE | (pWInfo->wctrlFlags & WHERE_SEEK_TABLE); |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 1719 | for(ii=0; ii<pOrWc->nTerm; ii++){ |
| 1720 | WhereTerm *pOrTerm = &pOrWc->a[ii]; |
| 1721 | if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){ |
| 1722 | WhereInfo *pSubWInfo; /* Info for single OR-term scan */ |
| 1723 | Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */ |
drh | 728e0f9 | 2015-10-10 14:41:28 +0000 | [diff] [blame] | 1724 | int jmp1 = 0; /* Address of jump operation */ |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 1725 | if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){ |
| 1726 | pAndExpr->pLeft = pOrExpr; |
| 1727 | pOrExpr = pAndExpr; |
| 1728 | } |
| 1729 | /* Loop through table entries that match term pOrTerm. */ |
| 1730 | WHERETRACE(0xffff, ("Subplan for OR-clause:\n")); |
| 1731 | pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0, |
| 1732 | wctrlFlags, iCovCur); |
| 1733 | assert( pSubWInfo || pParse->nErr || db->mallocFailed ); |
| 1734 | if( pSubWInfo ){ |
| 1735 | WhereLoop *pSubLoop; |
| 1736 | int addrExplain = sqlite3WhereExplainOneScan( |
| 1737 | pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0 |
| 1738 | ); |
| 1739 | sqlite3WhereAddScanStatus(v, pOrTab, &pSubWInfo->a[0], addrExplain); |
| 1740 | |
| 1741 | /* This is the sub-WHERE clause body. First skip over |
| 1742 | ** duplicate rows from prior sub-WHERE clauses, and record the |
| 1743 | ** rowid (or PRIMARY KEY) for the current row so that the same |
| 1744 | ** row will be skipped in subsequent sub-WHERE clauses. |
| 1745 | */ |
| 1746 | if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){ |
| 1747 | int r; |
| 1748 | int iSet = ((ii==pOrWc->nTerm-1)?-1:ii); |
| 1749 | if( HasRowid(pTab) ){ |
| 1750 | r = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, regRowid, 0); |
drh | 728e0f9 | 2015-10-10 14:41:28 +0000 | [diff] [blame] | 1751 | jmp1 = sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, 0, |
| 1752 | r,iSet); |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 1753 | VdbeCoverage(v); |
| 1754 | }else{ |
| 1755 | Index *pPk = sqlite3PrimaryKeyIndex(pTab); |
| 1756 | int nPk = pPk->nKeyCol; |
| 1757 | int iPk; |
| 1758 | |
| 1759 | /* Read the PK into an array of temp registers. */ |
| 1760 | r = sqlite3GetTempRange(pParse, nPk); |
| 1761 | for(iPk=0; iPk<nPk; iPk++){ |
| 1762 | int iCol = pPk->aiColumn[iPk]; |
drh | ce78bc6 | 2015-10-15 19:21:51 +0000 | [diff] [blame] | 1763 | sqlite3ExprCodeGetColumnToReg(pParse, pTab, iCol, iCur, r+iPk); |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 1764 | } |
| 1765 | |
| 1766 | /* Check if the temp table already contains this key. If so, |
| 1767 | ** the row has already been included in the result set and |
| 1768 | ** can be ignored (by jumping past the Gosub below). Otherwise, |
| 1769 | ** insert the key into the temp table and proceed with processing |
| 1770 | ** the row. |
| 1771 | ** |
| 1772 | ** Use some of the same optimizations as OP_RowSetTest: If iSet |
| 1773 | ** is zero, assume that the key cannot already be present in |
| 1774 | ** the temp table. And if iSet is -1, assume that there is no |
| 1775 | ** need to insert the key into the temp table, as it will never |
| 1776 | ** be tested for. */ |
| 1777 | if( iSet ){ |
drh | 728e0f9 | 2015-10-10 14:41:28 +0000 | [diff] [blame] | 1778 | jmp1 = sqlite3VdbeAddOp4Int(v, OP_Found, regRowset, 0, r, nPk); |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 1779 | VdbeCoverage(v); |
| 1780 | } |
| 1781 | if( iSet>=0 ){ |
| 1782 | sqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, regRowid); |
| 1783 | sqlite3VdbeAddOp3(v, OP_IdxInsert, regRowset, regRowid, 0); |
| 1784 | if( iSet ) sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); |
| 1785 | } |
| 1786 | |
| 1787 | /* Release the array of temp registers */ |
| 1788 | sqlite3ReleaseTempRange(pParse, r, nPk); |
| 1789 | } |
| 1790 | } |
| 1791 | |
| 1792 | /* Invoke the main loop body as a subroutine */ |
| 1793 | sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody); |
| 1794 | |
| 1795 | /* Jump here (skipping the main loop body subroutine) if the |
| 1796 | ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */ |
drh | 728e0f9 | 2015-10-10 14:41:28 +0000 | [diff] [blame] | 1797 | if( jmp1 ) sqlite3VdbeJumpHere(v, jmp1); |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 1798 | |
| 1799 | /* The pSubWInfo->untestedTerms flag means that this OR term |
| 1800 | ** contained one or more AND term from a notReady table. The |
| 1801 | ** terms from the notReady table could not be tested and will |
| 1802 | ** need to be tested later. |
| 1803 | */ |
| 1804 | if( pSubWInfo->untestedTerms ) untestedTerms = 1; |
| 1805 | |
| 1806 | /* If all of the OR-connected terms are optimized using the same |
| 1807 | ** index, and the index is opened using the same cursor number |
| 1808 | ** by each call to sqlite3WhereBegin() made by this loop, it may |
| 1809 | ** be possible to use that index as a covering index. |
| 1810 | ** |
| 1811 | ** If the call to sqlite3WhereBegin() above resulted in a scan that |
| 1812 | ** uses an index, and this is either the first OR-connected term |
| 1813 | ** processed or the index is the same as that used by all previous |
| 1814 | ** terms, set pCov to the candidate covering index. Otherwise, set |
| 1815 | ** pCov to NULL to indicate that no candidate covering index will |
| 1816 | ** be available. |
| 1817 | */ |
| 1818 | pSubLoop = pSubWInfo->a[0].pWLoop; |
| 1819 | assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 ); |
| 1820 | if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0 |
| 1821 | && (ii==0 || pSubLoop->u.btree.pIndex==pCov) |
| 1822 | && (HasRowid(pTab) || !IsPrimaryKeyIndex(pSubLoop->u.btree.pIndex)) |
| 1823 | ){ |
| 1824 | assert( pSubWInfo->a[0].iIdxCur==iCovCur ); |
| 1825 | pCov = pSubLoop->u.btree.pIndex; |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 1826 | }else{ |
| 1827 | pCov = 0; |
| 1828 | } |
| 1829 | |
| 1830 | /* Finish the loop through table entries that match term pOrTerm. */ |
| 1831 | sqlite3WhereEnd(pSubWInfo); |
| 1832 | } |
| 1833 | } |
| 1834 | } |
| 1835 | pLevel->u.pCovidx = pCov; |
| 1836 | if( pCov ) pLevel->iIdxCur = iCovCur; |
| 1837 | if( pAndExpr ){ |
| 1838 | pAndExpr->pLeft = 0; |
| 1839 | sqlite3ExprDelete(db, pAndExpr); |
| 1840 | } |
| 1841 | sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v)); |
drh | 076e85f | 2015-09-03 13:46:12 +0000 | [diff] [blame] | 1842 | sqlite3VdbeGoto(v, pLevel->addrBrk); |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 1843 | sqlite3VdbeResolveLabel(v, iLoopBody); |
| 1844 | |
| 1845 | if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab); |
| 1846 | if( !untestedTerms ) disableTerm(pLevel, pTerm); |
| 1847 | }else |
| 1848 | #endif /* SQLITE_OMIT_OR_OPTIMIZATION */ |
| 1849 | |
| 1850 | { |
| 1851 | /* Case 6: There is no usable index. We must do a complete |
| 1852 | ** scan of the entire table. |
| 1853 | */ |
| 1854 | static const u8 aStep[] = { OP_Next, OP_Prev }; |
| 1855 | static const u8 aStart[] = { OP_Rewind, OP_Last }; |
| 1856 | assert( bRev==0 || bRev==1 ); |
drh | 8a48b9c | 2015-08-19 15:20:00 +0000 | [diff] [blame] | 1857 | if( pTabItem->fg.isRecursive ){ |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 1858 | /* Tables marked isRecursive have only a single row that is stored in |
| 1859 | ** a pseudo-cursor. No need to Rewind or Next such cursors. */ |
| 1860 | pLevel->op = OP_Noop; |
| 1861 | }else{ |
dan | b324cf7 | 2016-06-17 14:33:32 +0000 | [diff] [blame] | 1862 | codeCursorHint(pTabItem, pWInfo, pLevel, 0); |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 1863 | pLevel->op = aStep[bRev]; |
| 1864 | pLevel->p1 = iCur; |
| 1865 | pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk); |
| 1866 | VdbeCoverageIf(v, bRev==0); |
| 1867 | VdbeCoverageIf(v, bRev!=0); |
| 1868 | pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP; |
| 1869 | } |
| 1870 | } |
| 1871 | |
| 1872 | #ifdef SQLITE_ENABLE_STMT_SCANSTATUS |
| 1873 | pLevel->addrVisit = sqlite3VdbeCurrentAddr(v); |
| 1874 | #endif |
| 1875 | |
| 1876 | /* Insert code to test every subexpression that can be completely |
| 1877 | ** computed using the current set of tables. |
| 1878 | */ |
| 1879 | for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){ |
| 1880 | Expr *pE; |
| 1881 | int skipLikeAddr = 0; |
| 1882 | testcase( pTerm->wtFlags & TERM_VIRTUAL ); |
| 1883 | testcase( pTerm->wtFlags & TERM_CODED ); |
| 1884 | if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue; |
| 1885 | if( (pTerm->prereqAll & pLevel->notReady)!=0 ){ |
| 1886 | testcase( pWInfo->untestedTerms==0 |
drh | ce943bc | 2016-05-19 18:56:33 +0000 | [diff] [blame] | 1887 | && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 ); |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 1888 | pWInfo->untestedTerms = 1; |
| 1889 | continue; |
| 1890 | } |
| 1891 | pE = pTerm->pExpr; |
| 1892 | assert( pE!=0 ); |
| 1893 | if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){ |
| 1894 | continue; |
| 1895 | } |
| 1896 | if( pTerm->wtFlags & TERM_LIKECOND ){ |
drh | 44aebff | 2016-05-02 10:25:42 +0000 | [diff] [blame] | 1897 | /* If the TERM_LIKECOND flag is set, that means that the range search |
| 1898 | ** is sufficient to guarantee that the LIKE operator is true, so we |
| 1899 | ** can skip the call to the like(A,B) function. But this only works |
| 1900 | ** for strings. So do not skip the call to the function on the pass |
| 1901 | ** that compares BLOBs. */ |
drh | 41d2e66 | 2015-12-01 21:23:07 +0000 | [diff] [blame] | 1902 | #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS |
| 1903 | continue; |
| 1904 | #else |
drh | 44aebff | 2016-05-02 10:25:42 +0000 | [diff] [blame] | 1905 | u32 x = pLevel->iLikeRepCntr; |
| 1906 | assert( x>0 ); |
| 1907 | skipLikeAddr = sqlite3VdbeAddOp1(v, (x&1)? OP_IfNot : OP_If, (int)(x>>1)); |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 1908 | VdbeCoverage(v); |
drh | 41d2e66 | 2015-12-01 21:23:07 +0000 | [diff] [blame] | 1909 | #endif |
drh | 6f82e85 | 2015-06-06 20:12:09 +0000 | [diff] [blame] | 1910 | } |
| 1911 | sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL); |
| 1912 | if( skipLikeAddr ) sqlite3VdbeJumpHere(v, skipLikeAddr); |
| 1913 | pTerm->wtFlags |= TERM_CODED; |
| 1914 | } |
| 1915 | |
| 1916 | /* Insert code to test for implied constraints based on transitivity |
| 1917 | ** of the "==" operator. |
| 1918 | ** |
| 1919 | ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123" |
| 1920 | ** and we are coding the t1 loop and the t2 loop has not yet coded, |
| 1921 | ** then we cannot use the "t1.a=t2.b" constraint, but we can code |
| 1922 | ** the implied "t1.a=123" constraint. |
| 1923 | */ |
| 1924 | for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){ |
| 1925 | Expr *pE, *pEAlt; |
| 1926 | WhereTerm *pAlt; |
| 1927 | if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue; |
| 1928 | if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) continue; |
| 1929 | if( (pTerm->eOperator & WO_EQUIV)==0 ) continue; |
| 1930 | if( pTerm->leftCursor!=iCur ) continue; |
| 1931 | if( pLevel->iLeftJoin ) continue; |
| 1932 | pE = pTerm->pExpr; |
| 1933 | assert( !ExprHasProperty(pE, EP_FromJoin) ); |
| 1934 | assert( (pTerm->prereqRight & pLevel->notReady)!=0 ); |
| 1935 | pAlt = sqlite3WhereFindTerm(pWC, iCur, pTerm->u.leftColumn, notReady, |
| 1936 | WO_EQ|WO_IN|WO_IS, 0); |
| 1937 | if( pAlt==0 ) continue; |
| 1938 | if( pAlt->wtFlags & (TERM_CODED) ) continue; |
| 1939 | testcase( pAlt->eOperator & WO_EQ ); |
| 1940 | testcase( pAlt->eOperator & WO_IS ); |
| 1941 | testcase( pAlt->eOperator & WO_IN ); |
| 1942 | VdbeModuleComment((v, "begin transitive constraint")); |
| 1943 | pEAlt = sqlite3StackAllocRaw(db, sizeof(*pEAlt)); |
| 1944 | if( pEAlt ){ |
| 1945 | *pEAlt = *pAlt->pExpr; |
| 1946 | pEAlt->pLeft = pE->pLeft; |
| 1947 | sqlite3ExprIfFalse(pParse, pEAlt, addrCont, SQLITE_JUMPIFNULL); |
| 1948 | sqlite3StackFree(db, pEAlt); |
| 1949 | } |
| 1950 | } |
| 1951 | |
| 1952 | /* For a LEFT OUTER JOIN, generate code that will record the fact that |
| 1953 | ** at least one row of the right table has matched the left table. |
| 1954 | */ |
| 1955 | if( pLevel->iLeftJoin ){ |
| 1956 | pLevel->addrFirst = sqlite3VdbeCurrentAddr(v); |
| 1957 | sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin); |
| 1958 | VdbeComment((v, "record LEFT JOIN hit")); |
| 1959 | sqlite3ExprCacheClear(pParse); |
| 1960 | for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){ |
| 1961 | testcase( pTerm->wtFlags & TERM_VIRTUAL ); |
| 1962 | testcase( pTerm->wtFlags & TERM_CODED ); |
| 1963 | if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue; |
| 1964 | if( (pTerm->prereqAll & pLevel->notReady)!=0 ){ |
| 1965 | assert( pWInfo->untestedTerms ); |
| 1966 | continue; |
| 1967 | } |
| 1968 | assert( pTerm->pExpr ); |
| 1969 | sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL); |
| 1970 | pTerm->wtFlags |= TERM_CODED; |
| 1971 | } |
| 1972 | } |
| 1973 | |
| 1974 | return pLevel->notReady; |
| 1975 | } |