blob: feccf2d11de79d9fe0c3957639acba21759f5116 [file] [log] [blame]
drh75897232000-05-29 14:26:00 +00001/*
drhb19a2bc2001-09-16 00:13:26 +00002** 2001 September 15
drh75897232000-05-29 14:26:00 +00003**
drhb19a2bc2001-09-16 00:13:26 +00004** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
drh75897232000-05-29 14:26:00 +00006**
drhb19a2bc2001-09-16 00:13:26 +00007** 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.
drh75897232000-05-29 14:26:00 +000010**
11*************************************************************************
12** This module contains C code that generates VDBE code used to process
drh909626d2008-05-30 14:58:37 +000013** the WHERE clause of SQL statements. This module is responsible for
drh51669862004-12-18 18:40:26 +000014** generating the code that loops through a table looking for applicable
15** rows. Indices are selected and used to speed the search when doing
16** so is applicable. Because this module is responsible for selecting
17** indices, you might also think of this module as the "query optimizer".
drh75897232000-05-29 14:26:00 +000018*/
19#include "sqliteInt.h"
drhe54df422013-11-12 18:37:25 +000020#include "whereInt.h"
drh51147ba2005-07-23 22:59:55 +000021
22/*
drh6f328482013-06-05 23:39:34 +000023** Return the estimated number of output rows from a WHERE clause
24*/
drhc63367e2013-06-10 20:46:50 +000025u64 sqlite3WhereOutputRowCount(WhereInfo *pWInfo){
drhbf539c42013-10-05 18:16:02 +000026 return sqlite3LogEstToInt(pWInfo->nRowOut);
drh6f328482013-06-05 23:39:34 +000027}
28
29/*
30** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
31** WHERE clause returns outputs for DISTINCT processing.
32*/
33int sqlite3WhereIsDistinct(WhereInfo *pWInfo){
34 return pWInfo->eDistinct;
35}
36
37/*
38** Return TRUE if the WHERE clause returns rows in ORDER BY order.
39** Return FALSE if the output needs to be sorted.
40*/
41int sqlite3WhereIsOrdered(WhereInfo *pWInfo){
drhddba0c22014-03-18 20:33:42 +000042 return pWInfo->nOBSat;
drh6f328482013-06-05 23:39:34 +000043}
44
45/*
46** Return the VDBE address or label to jump to in order to continue
47** immediately with the next row of a WHERE clause.
48*/
49int sqlite3WhereContinueLabel(WhereInfo *pWInfo){
drha22a75e2014-03-21 18:16:23 +000050 assert( pWInfo->iContinue!=0 );
drh6f328482013-06-05 23:39:34 +000051 return pWInfo->iContinue;
52}
53
54/*
55** Return the VDBE address or label to jump to in order to break
56** out of a WHERE loop.
57*/
58int sqlite3WhereBreakLabel(WhereInfo *pWInfo){
59 return pWInfo->iBreak;
60}
61
62/*
63** Return TRUE if an UPDATE or DELETE statement can operate directly on
64** the rowids returned by a WHERE clause. Return FALSE if doing an
65** UPDATE or DELETE might change subsequent WHERE clause results.
drhfc8d4f92013-11-08 15:19:46 +000066**
67** If the ONEPASS optimization is used (if this routine returns true)
68** then also write the indices of open cursors used by ONEPASS
69** into aiCur[0] and aiCur[1]. iaCur[0] gets the cursor of the data
70** table and iaCur[1] gets the cursor used by an auxiliary index.
71** Either value may be -1, indicating that cursor is not used.
72** Any cursors returned will have been opened for writing.
73**
74** aiCur[0] and aiCur[1] both get -1 if the where-clause logic is
75** unable to use the ONEPASS optimization.
drh6f328482013-06-05 23:39:34 +000076*/
drhfc8d4f92013-11-08 15:19:46 +000077int sqlite3WhereOkOnePass(WhereInfo *pWInfo, int *aiCur){
78 memcpy(aiCur, pWInfo->aiCurOnePass, sizeof(int)*2);
drh6f328482013-06-05 23:39:34 +000079 return pWInfo->okOnePass;
80}
81
82/*
drhaa32e3c2013-07-16 21:31:23 +000083** Move the content of pSrc into pDest
84*/
85static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){
86 pDest->n = pSrc->n;
87 memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0]));
88}
89
90/*
91** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet.
92**
93** The new entry might overwrite an existing entry, or it might be
94** appended, or it might be discarded. Do whatever is the right thing
95** so that pSet keeps the N_OR_COST best entries seen so far.
96*/
97static int whereOrInsert(
98 WhereOrSet *pSet, /* The WhereOrSet to be updated */
99 Bitmask prereq, /* Prerequisites of the new entry */
drhbf539c42013-10-05 18:16:02 +0000100 LogEst rRun, /* Run-cost of the new entry */
101 LogEst nOut /* Number of outputs for the new entry */
drhaa32e3c2013-07-16 21:31:23 +0000102){
103 u16 i;
104 WhereOrCost *p;
105 for(i=pSet->n, p=pSet->a; i>0; i--, p++){
106 if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){
107 goto whereOrInsert_done;
108 }
109 if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){
110 return 0;
111 }
112 }
113 if( pSet->n<N_OR_COST ){
114 p = &pSet->a[pSet->n++];
115 p->nOut = nOut;
116 }else{
117 p = pSet->a;
118 for(i=1; i<pSet->n; i++){
119 if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i;
120 }
121 if( p->rRun<=rRun ) return 0;
122 }
123whereOrInsert_done:
124 p->prereq = prereq;
125 p->rRun = rRun;
126 if( p->nOut>nOut ) p->nOut = nOut;
127 return 1;
128}
129
130/*
drh0aa74ed2005-07-16 13:33:20 +0000131** Initialize a preallocated WhereClause structure.
drh75897232000-05-29 14:26:00 +0000132*/
drh7b4fc6a2007-02-06 13:26:32 +0000133static void whereClauseInit(
134 WhereClause *pWC, /* The WhereClause to be initialized */
drh70d18342013-06-06 19:16:33 +0000135 WhereInfo *pWInfo /* The WHERE processing context */
drh7b4fc6a2007-02-06 13:26:32 +0000136){
drh70d18342013-06-06 19:16:33 +0000137 pWC->pWInfo = pWInfo;
drh8871ef52011-10-07 13:33:10 +0000138 pWC->pOuter = 0;
drh0aa74ed2005-07-16 13:33:20 +0000139 pWC->nTerm = 0;
drhcad651e2007-04-20 12:22:01 +0000140 pWC->nSlot = ArraySize(pWC->aStatic);
drh0aa74ed2005-07-16 13:33:20 +0000141 pWC->a = pWC->aStatic;
142}
143
drh700a2262008-12-17 19:22:15 +0000144/* Forward reference */
145static void whereClauseClear(WhereClause*);
146
147/*
148** Deallocate all memory associated with a WhereOrInfo object.
149*/
150static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
drh5bd98ae2009-01-07 18:24:03 +0000151 whereClauseClear(&p->wc);
152 sqlite3DbFree(db, p);
drh700a2262008-12-17 19:22:15 +0000153}
154
155/*
156** Deallocate all memory associated with a WhereAndInfo object.
157*/
158static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
drh5bd98ae2009-01-07 18:24:03 +0000159 whereClauseClear(&p->wc);
160 sqlite3DbFree(db, p);
drh700a2262008-12-17 19:22:15 +0000161}
162
drh0aa74ed2005-07-16 13:33:20 +0000163/*
164** Deallocate a WhereClause structure. The WhereClause structure
165** itself is not freed. This routine is the inverse of whereClauseInit().
166*/
167static void whereClauseClear(WhereClause *pWC){
168 int i;
169 WhereTerm *a;
drh70d18342013-06-06 19:16:33 +0000170 sqlite3 *db = pWC->pWInfo->pParse->db;
drh0aa74ed2005-07-16 13:33:20 +0000171 for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
drh165be382008-12-05 02:36:33 +0000172 if( a->wtFlags & TERM_DYNAMIC ){
drh633e6d52008-07-28 19:34:53 +0000173 sqlite3ExprDelete(db, a->pExpr);
drh0aa74ed2005-07-16 13:33:20 +0000174 }
drh700a2262008-12-17 19:22:15 +0000175 if( a->wtFlags & TERM_ORINFO ){
176 whereOrInfoDelete(db, a->u.pOrInfo);
177 }else if( a->wtFlags & TERM_ANDINFO ){
178 whereAndInfoDelete(db, a->u.pAndInfo);
179 }
drh0aa74ed2005-07-16 13:33:20 +0000180 }
181 if( pWC->a!=pWC->aStatic ){
drh633e6d52008-07-28 19:34:53 +0000182 sqlite3DbFree(db, pWC->a);
drh0aa74ed2005-07-16 13:33:20 +0000183 }
184}
185
186/*
drh6a1e0712008-12-05 15:24:15 +0000187** Add a single new WhereTerm entry to the WhereClause object pWC.
188** The new WhereTerm object is constructed from Expr p and with wtFlags.
189** The index in pWC->a[] of the new WhereTerm is returned on success.
190** 0 is returned if the new WhereTerm could not be added due to a memory
191** allocation error. The memory allocation failure will be recorded in
192** the db->mallocFailed flag so that higher-level functions can detect it.
193**
194** This routine will increase the size of the pWC->a[] array as necessary.
drh9eb20282005-08-24 03:52:18 +0000195**
drh165be382008-12-05 02:36:33 +0000196** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
drh6a1e0712008-12-05 15:24:15 +0000197** for freeing the expression p is assumed by the WhereClause object pWC.
198** This is true even if this routine fails to allocate a new WhereTerm.
drhb63a53d2007-03-31 01:34:44 +0000199**
drh9eb20282005-08-24 03:52:18 +0000200** WARNING: This routine might reallocate the space used to store
drh909626d2008-05-30 14:58:37 +0000201** WhereTerms. All pointers to WhereTerms should be invalidated after
drh9eb20282005-08-24 03:52:18 +0000202** calling this routine. Such pointers may be reinitialized by referencing
203** the pWC->a[] array.
drh0aa74ed2005-07-16 13:33:20 +0000204*/
drhec1724e2008-12-09 01:32:03 +0000205static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
drh0aa74ed2005-07-16 13:33:20 +0000206 WhereTerm *pTerm;
drh9eb20282005-08-24 03:52:18 +0000207 int idx;
drh39759742013-08-02 23:40:45 +0000208 testcase( wtFlags & TERM_VIRTUAL );
drh0aa74ed2005-07-16 13:33:20 +0000209 if( pWC->nTerm>=pWC->nSlot ){
210 WhereTerm *pOld = pWC->a;
drh70d18342013-06-06 19:16:33 +0000211 sqlite3 *db = pWC->pWInfo->pParse->db;
drh633e6d52008-07-28 19:34:53 +0000212 pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
drhb63a53d2007-03-31 01:34:44 +0000213 if( pWC->a==0 ){
drh165be382008-12-05 02:36:33 +0000214 if( wtFlags & TERM_DYNAMIC ){
drh633e6d52008-07-28 19:34:53 +0000215 sqlite3ExprDelete(db, p);
drhb63a53d2007-03-31 01:34:44 +0000216 }
drhf998b732007-11-26 13:36:00 +0000217 pWC->a = pOld;
drhb63a53d2007-03-31 01:34:44 +0000218 return 0;
219 }
drh0aa74ed2005-07-16 13:33:20 +0000220 memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
221 if( pOld!=pWC->aStatic ){
drh633e6d52008-07-28 19:34:53 +0000222 sqlite3DbFree(db, pOld);
drh0aa74ed2005-07-16 13:33:20 +0000223 }
drh6a1e0712008-12-05 15:24:15 +0000224 pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
drh0aa74ed2005-07-16 13:33:20 +0000225 }
drh6a1e0712008-12-05 15:24:15 +0000226 pTerm = &pWC->a[idx = pWC->nTerm++];
drha4c3c872013-09-12 17:29:25 +0000227 if( p && ExprHasProperty(p, EP_Unlikely) ){
drhd05ab6a2014-10-25 13:42:16 +0000228 pTerm->truthProb = sqlite3LogEst(p->iTable) - 270;
drhcca9f3d2013-09-06 15:23:29 +0000229 }else{
danaa9933c2014-04-24 20:04:49 +0000230 pTerm->truthProb = 1;
drhcca9f3d2013-09-06 15:23:29 +0000231 }
drh7ee751d2012-12-19 15:53:51 +0000232 pTerm->pExpr = sqlite3ExprSkipCollate(p);
drh165be382008-12-05 02:36:33 +0000233 pTerm->wtFlags = wtFlags;
drh0fcef5e2005-07-19 17:38:22 +0000234 pTerm->pWC = pWC;
drh45b1ee42005-08-02 17:48:22 +0000235 pTerm->iParent = -1;
drh9eb20282005-08-24 03:52:18 +0000236 return idx;
drh0aa74ed2005-07-16 13:33:20 +0000237}
drh75897232000-05-29 14:26:00 +0000238
239/*
drh51669862004-12-18 18:40:26 +0000240** This routine identifies subexpressions in the WHERE clause where
drhb6fb62d2005-09-20 08:47:20 +0000241** each subexpression is separated by the AND operator or some other
drh6c30be82005-07-29 15:10:17 +0000242** operator specified in the op parameter. The WhereClause structure
243** is filled with pointers to subexpressions. For example:
drh75897232000-05-29 14:26:00 +0000244**
drh51669862004-12-18 18:40:26 +0000245** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
246** \________/ \_______________/ \________________/
247** slot[0] slot[1] slot[2]
248**
249** The original WHERE clause in pExpr is unaltered. All this routine
drh51147ba2005-07-23 22:59:55 +0000250** does is make slot[] entries point to substructure within pExpr.
drh51669862004-12-18 18:40:26 +0000251**
drh51147ba2005-07-23 22:59:55 +0000252** In the previous sentence and in the diagram, "slot[]" refers to
drh902b9ee2008-12-05 17:17:07 +0000253** the WhereClause.a[] array. The slot[] array grows as needed to contain
drh51147ba2005-07-23 22:59:55 +0000254** all terms of the WHERE clause.
drh75897232000-05-29 14:26:00 +0000255*/
drh74f91d42013-06-19 18:01:44 +0000256static void whereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
257 pWC->op = op;
drh0aa74ed2005-07-16 13:33:20 +0000258 if( pExpr==0 ) return;
drh6c30be82005-07-29 15:10:17 +0000259 if( pExpr->op!=op ){
drh0aa74ed2005-07-16 13:33:20 +0000260 whereClauseInsert(pWC, pExpr, 0);
drh75897232000-05-29 14:26:00 +0000261 }else{
drh6c30be82005-07-29 15:10:17 +0000262 whereSplit(pWC, pExpr->pLeft, op);
263 whereSplit(pWC, pExpr->pRight, op);
drh75897232000-05-29 14:26:00 +0000264 }
drh75897232000-05-29 14:26:00 +0000265}
266
267/*
drh3b48e8c2013-06-12 20:18:16 +0000268** Initialize a WhereMaskSet object
drh6a3ea0e2003-05-02 14:32:12 +0000269*/
drhfd5874d2013-06-12 14:52:39 +0000270#define initMaskSet(P) (P)->n=0
drh6a3ea0e2003-05-02 14:32:12 +0000271
272/*
drh1398ad32005-01-19 23:24:50 +0000273** Return the bitmask for the given cursor number. Return 0 if
274** iCursor is not in the set.
drh6a3ea0e2003-05-02 14:32:12 +0000275*/
drh111a6a72008-12-21 03:51:16 +0000276static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
drh6a3ea0e2003-05-02 14:32:12 +0000277 int i;
drhfcd71b62011-04-05 22:08:24 +0000278 assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
drh6a3ea0e2003-05-02 14:32:12 +0000279 for(i=0; i<pMaskSet->n; i++){
drh51669862004-12-18 18:40:26 +0000280 if( pMaskSet->ix[i]==iCursor ){
drh7699d1c2013-06-04 12:42:29 +0000281 return MASKBIT(i);
drh51669862004-12-18 18:40:26 +0000282 }
drh6a3ea0e2003-05-02 14:32:12 +0000283 }
drh6a3ea0e2003-05-02 14:32:12 +0000284 return 0;
285}
286
287/*
drh1398ad32005-01-19 23:24:50 +0000288** Create a new mask for cursor iCursor.
drh0fcef5e2005-07-19 17:38:22 +0000289**
290** There is one cursor per table in the FROM clause. The number of
291** tables in the FROM clause is limited by a test early in the
drhb6fb62d2005-09-20 08:47:20 +0000292** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[]
drh0fcef5e2005-07-19 17:38:22 +0000293** array will never overflow.
drh1398ad32005-01-19 23:24:50 +0000294*/
drh111a6a72008-12-21 03:51:16 +0000295static void createMask(WhereMaskSet *pMaskSet, int iCursor){
drhcad651e2007-04-20 12:22:01 +0000296 assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
drh0fcef5e2005-07-19 17:38:22 +0000297 pMaskSet->ix[pMaskSet->n++] = iCursor;
drh1398ad32005-01-19 23:24:50 +0000298}
299
300/*
drh4a6fc352013-08-07 01:18:38 +0000301** These routines walk (recursively) an expression tree and generate
drh75897232000-05-29 14:26:00 +0000302** a bitmask indicating which tables are used in that expression
drh6a3ea0e2003-05-02 14:32:12 +0000303** tree.
drh75897232000-05-29 14:26:00 +0000304*/
drh111a6a72008-12-21 03:51:16 +0000305static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
306static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
307static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
drh51669862004-12-18 18:40:26 +0000308 Bitmask mask = 0;
drh75897232000-05-29 14:26:00 +0000309 if( p==0 ) return 0;
drh967e8b72000-06-21 13:59:10 +0000310 if( p->op==TK_COLUMN ){
drh8feb4b12004-07-19 02:12:14 +0000311 mask = getMask(pMaskSet, p->iTable);
drh8feb4b12004-07-19 02:12:14 +0000312 return mask;
drh75897232000-05-29 14:26:00 +0000313 }
danielk1977b3bce662005-01-29 08:32:43 +0000314 mask = exprTableUsage(pMaskSet, p->pRight);
315 mask |= exprTableUsage(pMaskSet, p->pLeft);
danielk19776ab3a2e2009-02-19 14:39:25 +0000316 if( ExprHasProperty(p, EP_xIsSelect) ){
317 mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
318 }else{
319 mask |= exprListTableUsage(pMaskSet, p->x.pList);
320 }
danielk1977b3bce662005-01-29 08:32:43 +0000321 return mask;
322}
drh111a6a72008-12-21 03:51:16 +0000323static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
danielk1977b3bce662005-01-29 08:32:43 +0000324 int i;
325 Bitmask mask = 0;
326 if( pList ){
327 for(i=0; i<pList->nExpr; i++){
328 mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
drhdd579122002-04-02 01:58:57 +0000329 }
330 }
drh75897232000-05-29 14:26:00 +0000331 return mask;
332}
drh111a6a72008-12-21 03:51:16 +0000333static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
drha430ae82007-09-12 15:41:01 +0000334 Bitmask mask = 0;
335 while( pS ){
drha464c232011-09-16 19:04:03 +0000336 SrcList *pSrc = pS->pSrc;
drha430ae82007-09-12 15:41:01 +0000337 mask |= exprListTableUsage(pMaskSet, pS->pEList);
drhf5b11382005-09-17 13:07:13 +0000338 mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
339 mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
340 mask |= exprTableUsage(pMaskSet, pS->pWhere);
341 mask |= exprTableUsage(pMaskSet, pS->pHaving);
drha464c232011-09-16 19:04:03 +0000342 if( ALWAYS(pSrc!=0) ){
drh88501772011-09-16 17:43:06 +0000343 int i;
344 for(i=0; i<pSrc->nSrc; i++){
345 mask |= exprSelectTableUsage(pMaskSet, pSrc->a[i].pSelect);
346 mask |= exprTableUsage(pMaskSet, pSrc->a[i].pOn);
347 }
348 }
drha430ae82007-09-12 15:41:01 +0000349 pS = pS->pPrior;
drhf5b11382005-09-17 13:07:13 +0000350 }
351 return mask;
352}
drh75897232000-05-29 14:26:00 +0000353
354/*
drh487ab3c2001-11-08 00:45:21 +0000355** Return TRUE if the given operator is one of the operators that is
drh51669862004-12-18 18:40:26 +0000356** allowed for an indexable WHERE clause term. The allowed operators are
drh3b48e8c2013-06-12 20:18:16 +0000357** "=", "<", ">", "<=", ">=", "IN", and "IS NULL"
drh487ab3c2001-11-08 00:45:21 +0000358*/
359static int allowedOp(int op){
drhfe05af82005-07-21 03:14:59 +0000360 assert( TK_GT>TK_EQ && TK_GT<TK_GE );
361 assert( TK_LT>TK_EQ && TK_LT<TK_GE );
362 assert( TK_LE>TK_EQ && TK_LE<TK_GE );
363 assert( TK_GE==TK_EQ+4 );
drh50b39962006-10-28 00:28:09 +0000364 return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
drh487ab3c2001-11-08 00:45:21 +0000365}
366
367/*
drh909626d2008-05-30 14:58:37 +0000368** Commute a comparison operator. Expressions of the form "X op Y"
drh0fcef5e2005-07-19 17:38:22 +0000369** are converted into "Y op X".
danielk1977eb5453d2007-07-30 14:40:48 +0000370**
mistachkin48864df2013-03-21 21:20:32 +0000371** If left/right precedence rules come into play when determining the
drh3b48e8c2013-06-12 20:18:16 +0000372** collating sequence, then COLLATE operators are adjusted to ensure
373** that the collating sequence does not change. For example:
374** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on
danielk1977eb5453d2007-07-30 14:40:48 +0000375** the left hand side of a comparison overrides any collation sequence
drhae80dde2012-12-06 21:16:43 +0000376** attached to the right. For the same reason the EP_Collate flag
danielk1977eb5453d2007-07-30 14:40:48 +0000377** is not commuted.
drh193bd772004-07-20 18:23:14 +0000378*/
drh7d10d5a2008-08-20 16:35:10 +0000379static void exprCommute(Parse *pParse, Expr *pExpr){
drhae80dde2012-12-06 21:16:43 +0000380 u16 expRight = (pExpr->pRight->flags & EP_Collate);
381 u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
drhfe05af82005-07-21 03:14:59 +0000382 assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
drhae80dde2012-12-06 21:16:43 +0000383 if( expRight==expLeft ){
384 /* Either X and Y both have COLLATE operator or neither do */
385 if( expRight ){
386 /* Both X and Y have COLLATE operators. Make sure X is always
387 ** used by clearing the EP_Collate flag from Y. */
388 pExpr->pRight->flags &= ~EP_Collate;
389 }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
390 /* Neither X nor Y have COLLATE operators, but X has a non-default
391 ** collating sequence. So add the EP_Collate marker on X to cause
392 ** it to be searched first. */
393 pExpr->pLeft->flags |= EP_Collate;
394 }
395 }
drh0fcef5e2005-07-19 17:38:22 +0000396 SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
397 if( pExpr->op>=TK_GT ){
398 assert( TK_LT==TK_GT+2 );
399 assert( TK_GE==TK_LE+2 );
400 assert( TK_GT>TK_EQ );
401 assert( TK_GT<TK_LE );
402 assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
403 pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
drh193bd772004-07-20 18:23:14 +0000404 }
drh193bd772004-07-20 18:23:14 +0000405}
406
407/*
drhfe05af82005-07-21 03:14:59 +0000408** Translate from TK_xx operator to WO_xx bitmask.
409*/
drhec1724e2008-12-09 01:32:03 +0000410static u16 operatorMask(int op){
411 u16 c;
drhfe05af82005-07-21 03:14:59 +0000412 assert( allowedOp(op) );
413 if( op==TK_IN ){
drh51147ba2005-07-23 22:59:55 +0000414 c = WO_IN;
drh50b39962006-10-28 00:28:09 +0000415 }else if( op==TK_ISNULL ){
416 c = WO_ISNULL;
drhfe05af82005-07-21 03:14:59 +0000417 }else{
drhec1724e2008-12-09 01:32:03 +0000418 assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
419 c = (u16)(WO_EQ<<(op-TK_EQ));
drhfe05af82005-07-21 03:14:59 +0000420 }
drh50b39962006-10-28 00:28:09 +0000421 assert( op!=TK_ISNULL || c==WO_ISNULL );
drh51147ba2005-07-23 22:59:55 +0000422 assert( op!=TK_IN || c==WO_IN );
423 assert( op!=TK_EQ || c==WO_EQ );
424 assert( op!=TK_LT || c==WO_LT );
425 assert( op!=TK_LE || c==WO_LE );
426 assert( op!=TK_GT || c==WO_GT );
427 assert( op!=TK_GE || c==WO_GE );
428 return c;
drhfe05af82005-07-21 03:14:59 +0000429}
430
431/*
drh1c8148f2013-05-04 20:25:23 +0000432** Advance to the next WhereTerm that matches according to the criteria
433** established when the pScan object was initialized by whereScanInit().
434** Return NULL if there are no more matching WhereTerms.
435*/
danb2cfc142013-07-05 11:10:54 +0000436static WhereTerm *whereScanNext(WhereScan *pScan){
drh1c8148f2013-05-04 20:25:23 +0000437 int iCur; /* The cursor on the LHS of the term */
438 int iColumn; /* The column on the LHS of the term. -1 for IPK */
439 Expr *pX; /* An expression being tested */
440 WhereClause *pWC; /* Shorthand for pScan->pWC */
441 WhereTerm *pTerm; /* The term being tested */
drh43b85ef2013-06-10 12:34:45 +0000442 int k = pScan->k; /* Where to start scanning */
drh1c8148f2013-05-04 20:25:23 +0000443
444 while( pScan->iEquiv<=pScan->nEquiv ){
445 iCur = pScan->aEquiv[pScan->iEquiv-2];
446 iColumn = pScan->aEquiv[pScan->iEquiv-1];
447 while( (pWC = pScan->pWC)!=0 ){
drh43b85ef2013-06-10 12:34:45 +0000448 for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
drhe1a086e2013-10-28 20:15:56 +0000449 if( pTerm->leftCursor==iCur
450 && pTerm->u.leftColumn==iColumn
451 && (pScan->iEquiv<=2 || !ExprHasProperty(pTerm->pExpr, EP_FromJoin))
452 ){
drh1c8148f2013-05-04 20:25:23 +0000453 if( (pTerm->eOperator & WO_EQUIV)!=0
454 && pScan->nEquiv<ArraySize(pScan->aEquiv)
455 ){
456 int j;
457 pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight);
458 assert( pX->op==TK_COLUMN );
459 for(j=0; j<pScan->nEquiv; j+=2){
460 if( pScan->aEquiv[j]==pX->iTable
461 && pScan->aEquiv[j+1]==pX->iColumn ){
462 break;
463 }
464 }
465 if( j==pScan->nEquiv ){
466 pScan->aEquiv[j] = pX->iTable;
467 pScan->aEquiv[j+1] = pX->iColumn;
468 pScan->nEquiv += 2;
469 }
470 }
471 if( (pTerm->eOperator & pScan->opMask)!=0 ){
472 /* Verify the affinity and collating sequence match */
473 if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
474 CollSeq *pColl;
drh70d18342013-06-06 19:16:33 +0000475 Parse *pParse = pWC->pWInfo->pParse;
drh1c8148f2013-05-04 20:25:23 +0000476 pX = pTerm->pExpr;
477 if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
478 continue;
479 }
480 assert(pX->pLeft);
drh70d18342013-06-06 19:16:33 +0000481 pColl = sqlite3BinaryCompareCollSeq(pParse,
drh1c8148f2013-05-04 20:25:23 +0000482 pX->pLeft, pX->pRight);
drh70d18342013-06-06 19:16:33 +0000483 if( pColl==0 ) pColl = pParse->db->pDfltColl;
drh1c8148f2013-05-04 20:25:23 +0000484 if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
485 continue;
486 }
487 }
drha184fb82013-05-08 04:22:59 +0000488 if( (pTerm->eOperator & WO_EQ)!=0
489 && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN
490 && pX->iTable==pScan->aEquiv[0]
491 && pX->iColumn==pScan->aEquiv[1]
492 ){
493 continue;
494 }
drh43b85ef2013-06-10 12:34:45 +0000495 pScan->k = k+1;
drh1c8148f2013-05-04 20:25:23 +0000496 return pTerm;
497 }
498 }
499 }
drhad01d892013-06-19 13:59:49 +0000500 pScan->pWC = pScan->pWC->pOuter;
drh43b85ef2013-06-10 12:34:45 +0000501 k = 0;
drh1c8148f2013-05-04 20:25:23 +0000502 }
503 pScan->pWC = pScan->pOrigWC;
drh43b85ef2013-06-10 12:34:45 +0000504 k = 0;
drh1c8148f2013-05-04 20:25:23 +0000505 pScan->iEquiv += 2;
506 }
drh1c8148f2013-05-04 20:25:23 +0000507 return 0;
508}
509
510/*
511** Initialize a WHERE clause scanner object. Return a pointer to the
512** first match. Return NULL if there are no matches.
513**
514** The scanner will be searching the WHERE clause pWC. It will look
515** for terms of the form "X <op> <expr>" where X is column iColumn of table
516** iCur. The <op> must be one of the operators described by opMask.
517**
drh3b48e8c2013-06-12 20:18:16 +0000518** If the search is for X and the WHERE clause contains terms of the
519** form X=Y then this routine might also return terms of the form
520** "Y <op> <expr>". The number of levels of transitivity is limited,
521** but is enough to handle most commonly occurring SQL statements.
522**
drh1c8148f2013-05-04 20:25:23 +0000523** If X is not the INTEGER PRIMARY KEY then X must be compatible with
524** index pIdx.
525*/
danb2cfc142013-07-05 11:10:54 +0000526static WhereTerm *whereScanInit(
drh1c8148f2013-05-04 20:25:23 +0000527 WhereScan *pScan, /* The WhereScan object being initialized */
528 WhereClause *pWC, /* The WHERE clause to be scanned */
529 int iCur, /* Cursor to scan for */
530 int iColumn, /* Column to scan for */
531 u32 opMask, /* Operator(s) to scan for */
532 Index *pIdx /* Must be compatible with this index */
533){
534 int j;
535
drhe9d935a2013-06-05 16:19:59 +0000536 /* memset(pScan, 0, sizeof(*pScan)); */
drh1c8148f2013-05-04 20:25:23 +0000537 pScan->pOrigWC = pWC;
538 pScan->pWC = pWC;
539 if( pIdx && iColumn>=0 ){
540 pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
541 for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
dan39129ce2014-06-30 15:23:57 +0000542 if( NEVER(j>pIdx->nColumn) ) return 0;
drh1c8148f2013-05-04 20:25:23 +0000543 }
544 pScan->zCollName = pIdx->azColl[j];
drhe9d935a2013-06-05 16:19:59 +0000545 }else{
546 pScan->idxaff = 0;
547 pScan->zCollName = 0;
drh1c8148f2013-05-04 20:25:23 +0000548 }
549 pScan->opMask = opMask;
drhe9d935a2013-06-05 16:19:59 +0000550 pScan->k = 0;
drh1c8148f2013-05-04 20:25:23 +0000551 pScan->aEquiv[0] = iCur;
552 pScan->aEquiv[1] = iColumn;
553 pScan->nEquiv = 2;
554 pScan->iEquiv = 2;
555 return whereScanNext(pScan);
556}
557
558/*
drhfe05af82005-07-21 03:14:59 +0000559** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
560** where X is a reference to the iColumn of table iCur and <op> is one of
561** the WO_xx operator codes specified by the op parameter.
562** Return a pointer to the term. Return 0 if not found.
drh58eb1c02013-01-17 00:08:42 +0000563**
564** The term returned might by Y=<expr> if there is another constraint in
565** the WHERE clause that specifies that X=Y. Any such constraints will be
566** identified by the WO_EQUIV bit in the pTerm->eOperator field. The
567** aEquiv[] array holds X and all its equivalents, with each SQL variable
568** taking up two slots in aEquiv[]. The first slot is for the cursor number
569** and the second is for the column number. There are 22 slots in aEquiv[]
570** so that means we can look for X plus up to 10 other equivalent values.
571** Hence a search for X will return <expr> if X=A1 and A1=A2 and A2=A3
572** and ... and A9=A10 and A10=<expr>.
573**
574** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
575** then try for the one with no dependencies on <expr> - in other words where
576** <expr> is a constant expression of some kind. Only return entries of
577** the form "X <op> Y" where Y is a column in another table if no terms of
drh459f63e2013-03-06 01:55:27 +0000578** the form "X <op> <const-expr>" exist. If no terms with a constant RHS
579** exist, try to return a term that does not use WO_EQUIV.
drhfe05af82005-07-21 03:14:59 +0000580*/
581static WhereTerm *findTerm(
582 WhereClause *pWC, /* The WHERE clause to be searched */
583 int iCur, /* Cursor number of LHS */
584 int iColumn, /* Column number of LHS */
585 Bitmask notReady, /* RHS must not overlap with this mask */
drhec1724e2008-12-09 01:32:03 +0000586 u32 op, /* Mask of WO_xx values describing operator */
drhfe05af82005-07-21 03:14:59 +0000587 Index *pIdx /* Must be compatible with this index, if not NULL */
588){
drh1c8148f2013-05-04 20:25:23 +0000589 WhereTerm *pResult = 0;
590 WhereTerm *p;
591 WhereScan scan;
drh7a5bcc02013-01-16 17:08:58 +0000592
drh1c8148f2013-05-04 20:25:23 +0000593 p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
594 while( p ){
595 if( (p->prereqRight & notReady)==0 ){
596 if( p->prereqRight==0 && (p->eOperator&WO_EQ)!=0 ){
597 return p;
drhfe05af82005-07-21 03:14:59 +0000598 }
drh1c8148f2013-05-04 20:25:23 +0000599 if( pResult==0 ) pResult = p;
drhfe05af82005-07-21 03:14:59 +0000600 }
drh1c8148f2013-05-04 20:25:23 +0000601 p = whereScanNext(&scan);
drhfe05af82005-07-21 03:14:59 +0000602 }
drh7a5bcc02013-01-16 17:08:58 +0000603 return pResult;
drhfe05af82005-07-21 03:14:59 +0000604}
605
drh6c30be82005-07-29 15:10:17 +0000606/* Forward reference */
drh7b4fc6a2007-02-06 13:26:32 +0000607static void exprAnalyze(SrcList*, WhereClause*, int);
drh6c30be82005-07-29 15:10:17 +0000608
609/*
610** Call exprAnalyze on all terms in a WHERE clause.
drh6c30be82005-07-29 15:10:17 +0000611*/
612static void exprAnalyzeAll(
613 SrcList *pTabList, /* the FROM clause */
drh6c30be82005-07-29 15:10:17 +0000614 WhereClause *pWC /* the WHERE clause to be analyzed */
615){
drh6c30be82005-07-29 15:10:17 +0000616 int i;
drh9eb20282005-08-24 03:52:18 +0000617 for(i=pWC->nTerm-1; i>=0; i--){
drh7b4fc6a2007-02-06 13:26:32 +0000618 exprAnalyze(pTabList, pWC, i);
drh6c30be82005-07-29 15:10:17 +0000619 }
620}
621
drhd2687b72005-08-12 22:56:09 +0000622#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
623/*
624** Check to see if the given expression is a LIKE or GLOB operator that
625** can be optimized using inequality constraints. Return TRUE if it is
626** so and false if not.
627**
628** In order for the operator to be optimizible, the RHS must be a string
629** literal that does not begin with a wildcard.
630*/
631static int isLikeOrGlob(
drh7d10d5a2008-08-20 16:35:10 +0000632 Parse *pParse, /* Parsing and code generating context */
drhd2687b72005-08-12 22:56:09 +0000633 Expr *pExpr, /* Test this expression */
dan937d0de2009-10-15 18:35:38 +0000634 Expr **ppPrefix, /* Pointer to TK_STRING expression with pattern prefix */
drh9f504ea2008-02-23 21:55:39 +0000635 int *pisComplete, /* True if the only wildcard is % in the last character */
636 int *pnoCase /* True if uppercase is equivalent to lowercase */
drhd2687b72005-08-12 22:56:09 +0000637){
dan937d0de2009-10-15 18:35:38 +0000638 const char *z = 0; /* String on RHS of LIKE operator */
drh5bd98ae2009-01-07 18:24:03 +0000639 Expr *pRight, *pLeft; /* Right and left size of LIKE operator */
640 ExprList *pList; /* List of operands to the LIKE operator */
641 int c; /* One character in z[] */
642 int cnt; /* Number of non-wildcard prefix characters */
643 char wc[3]; /* Wildcard characters */
drh5bd98ae2009-01-07 18:24:03 +0000644 sqlite3 *db = pParse->db; /* Database connection */
dan937d0de2009-10-15 18:35:38 +0000645 sqlite3_value *pVal = 0;
646 int op; /* Opcode of pRight */
drhd64fe2f2005-08-28 17:00:23 +0000647
drh9f504ea2008-02-23 21:55:39 +0000648 if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
drhd2687b72005-08-12 22:56:09 +0000649 return 0;
650 }
drh9f504ea2008-02-23 21:55:39 +0000651#ifdef SQLITE_EBCDIC
652 if( *pnoCase ) return 0;
653#endif
danielk19776ab3a2e2009-02-19 14:39:25 +0000654 pList = pExpr->x.pList;
drh55ef4d92005-08-14 01:20:37 +0000655 pLeft = pList->a[1].pExpr;
danc68939e2012-03-29 14:29:07 +0000656 if( pLeft->op!=TK_COLUMN
657 || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
658 || IsVirtual(pLeft->pTab)
659 ){
drhd91ca492009-10-22 20:50:36 +0000660 /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
661 ** be the name of an indexed column with TEXT affinity. */
drhd2687b72005-08-12 22:56:09 +0000662 return 0;
663 }
drhd91ca492009-10-22 20:50:36 +0000664 assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
dan937d0de2009-10-15 18:35:38 +0000665
drh6ade4532014-01-16 15:31:41 +0000666 pRight = sqlite3ExprSkipCollate(pList->a[0].pExpr);
dan937d0de2009-10-15 18:35:38 +0000667 op = pRight->op;
dan937d0de2009-10-15 18:35:38 +0000668 if( op==TK_VARIABLE ){
669 Vdbe *pReprepare = pParse->pReprepare;
drha7044002010-09-14 18:22:59 +0000670 int iCol = pRight->iColumn;
drhcf0fd4a2013-08-01 12:21:58 +0000671 pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_NONE);
dan937d0de2009-10-15 18:35:38 +0000672 if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
673 z = (char *)sqlite3_value_text(pVal);
674 }
drhf9b22ca2011-10-21 16:47:31 +0000675 sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
dan937d0de2009-10-15 18:35:38 +0000676 assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
677 }else if( op==TK_STRING ){
678 z = pRight->u.zToken;
679 }
680 if( z ){
shane85095702009-06-15 16:27:08 +0000681 cnt = 0;
drhb7916a72009-05-27 10:31:29 +0000682 while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
drh24fb6272009-05-01 21:13:36 +0000683 cnt++;
684 }
drh93ee23c2010-07-22 12:33:57 +0000685 if( cnt!=0 && 255!=(u8)z[cnt-1] ){
dan937d0de2009-10-15 18:35:38 +0000686 Expr *pPrefix;
drh93ee23c2010-07-22 12:33:57 +0000687 *pisComplete = c==wc[0] && z[cnt+1]==0;
dan937d0de2009-10-15 18:35:38 +0000688 pPrefix = sqlite3Expr(db, TK_STRING, z);
689 if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
690 *ppPrefix = pPrefix;
691 if( op==TK_VARIABLE ){
692 Vdbe *v = pParse->pVdbe;
drhf9b22ca2011-10-21 16:47:31 +0000693 sqlite3VdbeSetVarmask(v, pRight->iColumn);
dan937d0de2009-10-15 18:35:38 +0000694 if( *pisComplete && pRight->u.zToken[1] ){
695 /* If the rhs of the LIKE expression is a variable, and the current
696 ** value of the variable means there is no need to invoke the LIKE
697 ** function, then no OP_Variable will be added to the program.
698 ** This causes problems for the sqlite3_bind_parameter_name()
peter.d.reid60ec9142014-09-06 16:39:46 +0000699 ** API. To work around them, add a dummy OP_Variable here.
drhbec451f2009-10-17 13:13:02 +0000700 */
701 int r1 = sqlite3GetTempReg(pParse);
702 sqlite3ExprCodeTarget(pParse, pRight, r1);
dan937d0de2009-10-15 18:35:38 +0000703 sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
drhbec451f2009-10-17 13:13:02 +0000704 sqlite3ReleaseTempReg(pParse, r1);
dan937d0de2009-10-15 18:35:38 +0000705 }
706 }
707 }else{
708 z = 0;
shane85095702009-06-15 16:27:08 +0000709 }
drhf998b732007-11-26 13:36:00 +0000710 }
dan937d0de2009-10-15 18:35:38 +0000711
712 sqlite3ValueFree(pVal);
713 return (z!=0);
drhd2687b72005-08-12 22:56:09 +0000714}
715#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
716
drhedb193b2006-06-27 13:20:21 +0000717
718#ifndef SQLITE_OMIT_VIRTUALTABLE
drhfe05af82005-07-21 03:14:59 +0000719/*
drh7f375902006-06-13 17:38:59 +0000720** Check to see if the given expression is of the form
721**
722** column MATCH expr
723**
724** If it is then return TRUE. If not, return FALSE.
725*/
726static int isMatchOfColumn(
727 Expr *pExpr /* Test this expression */
728){
729 ExprList *pList;
730
731 if( pExpr->op!=TK_FUNCTION ){
732 return 0;
733 }
drh33e619f2009-05-28 01:00:55 +0000734 if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
drh7f375902006-06-13 17:38:59 +0000735 return 0;
736 }
danielk19776ab3a2e2009-02-19 14:39:25 +0000737 pList = pExpr->x.pList;
drh7f375902006-06-13 17:38:59 +0000738 if( pList->nExpr!=2 ){
739 return 0;
740 }
741 if( pList->a[1].pExpr->op != TK_COLUMN ){
742 return 0;
743 }
744 return 1;
745}
drhedb193b2006-06-27 13:20:21 +0000746#endif /* SQLITE_OMIT_VIRTUALTABLE */
drh7f375902006-06-13 17:38:59 +0000747
748/*
drh54a167d2005-11-26 14:08:07 +0000749** If the pBase expression originated in the ON or USING clause of
750** a join, then transfer the appropriate markings over to derived.
751*/
752static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
drhd41d39f2013-08-28 16:27:01 +0000753 if( pDerived ){
754 pDerived->flags |= pBase->flags & EP_FromJoin;
755 pDerived->iRightJoinTable = pBase->iRightJoinTable;
756 }
drh54a167d2005-11-26 14:08:07 +0000757}
758
drh9769efc2014-10-24 14:32:21 +0000759/*
760** Mark term iChild as being a child of term iParent
761*/
762static void markTermAsChild(WhereClause *pWC, int iChild, int iParent){
763 pWC->a[iChild].iParent = iParent;
764 pWC->a[iChild].truthProb = pWC->a[iParent].truthProb;
765 pWC->a[iParent].nChild++;
766}
767
drh3e355802007-02-23 23:13:33 +0000768#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
769/*
drh1a58fe02008-12-20 02:06:13 +0000770** Analyze a term that consists of two or more OR-connected
771** subterms. So in:
drh3e355802007-02-23 23:13:33 +0000772**
drh1a58fe02008-12-20 02:06:13 +0000773** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
774** ^^^^^^^^^^^^^^^^^^^^
drh3e355802007-02-23 23:13:33 +0000775**
drh1a58fe02008-12-20 02:06:13 +0000776** This routine analyzes terms such as the middle term in the above example.
777** A WhereOrTerm object is computed and attached to the term under
778** analysis, regardless of the outcome of the analysis. Hence:
drh3e355802007-02-23 23:13:33 +0000779**
drh1a58fe02008-12-20 02:06:13 +0000780** WhereTerm.wtFlags |= TERM_ORINFO
781** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object
drh3e355802007-02-23 23:13:33 +0000782**
drh1a58fe02008-12-20 02:06:13 +0000783** The term being analyzed must have two or more of OR-connected subterms.
danielk1977fdc40192008-12-29 18:33:32 +0000784** A single subterm might be a set of AND-connected sub-subterms.
drh1a58fe02008-12-20 02:06:13 +0000785** Examples of terms under analysis:
drh3e355802007-02-23 23:13:33 +0000786**
drh1a58fe02008-12-20 02:06:13 +0000787** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
788** (B) x=expr1 OR expr2=x OR x=expr3
789** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
790** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
791** (E) (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
drh3e355802007-02-23 23:13:33 +0000792**
drh1a58fe02008-12-20 02:06:13 +0000793** CASE 1:
794**
drhc3e552f2013-02-08 16:04:19 +0000795** If all subterms are of the form T.C=expr for some single column of C and
drh1a58fe02008-12-20 02:06:13 +0000796** a single table T (as shown in example B above) then create a new virtual
797** term that is an equivalent IN expression. In other words, if the term
798** being analyzed is:
799**
800** x = expr1 OR expr2 = x OR x = expr3
801**
802** then create a new virtual term like this:
803**
804** x IN (expr1,expr2,expr3)
805**
806** CASE 2:
807**
808** If all subterms are indexable by a single table T, then set
809**
810** WhereTerm.eOperator = WO_OR
811** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T
812**
813** A subterm is "indexable" if it is of the form
814** "T.C <op> <expr>" where C is any column of table T and
815** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
816** A subterm is also indexable if it is an AND of two or more
817** subsubterms at least one of which is indexable. Indexable AND
818** subterms have their eOperator set to WO_AND and they have
819** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
820**
821** From another point of view, "indexable" means that the subterm could
822** potentially be used with an index if an appropriate index exists.
823** This analysis does not consider whether or not the index exists; that
drh4a6fc352013-08-07 01:18:38 +0000824** is decided elsewhere. This analysis only looks at whether subterms
825** appropriate for indexing exist.
drh1a58fe02008-12-20 02:06:13 +0000826**
drh4a6fc352013-08-07 01:18:38 +0000827** All examples A through E above satisfy case 2. But if a term
peter.d.reid60ec9142014-09-06 16:39:46 +0000828** also satisfies case 1 (such as B) we know that the optimizer will
drh1a58fe02008-12-20 02:06:13 +0000829** always prefer case 1, so in that case we pretend that case 2 is not
830** satisfied.
831**
832** It might be the case that multiple tables are indexable. For example,
833** (E) above is indexable on tables P, Q, and R.
834**
835** Terms that satisfy case 2 are candidates for lookup by using
836** separate indices to find rowids for each subterm and composing
837** the union of all rowids using a RowSet object. This is similar
838** to "bitmap indices" in other database engines.
839**
840** OTHERWISE:
841**
842** If neither case 1 nor case 2 apply, then leave the eOperator set to
843** zero. This term is not useful for search.
drh3e355802007-02-23 23:13:33 +0000844*/
drh1a58fe02008-12-20 02:06:13 +0000845static void exprAnalyzeOrTerm(
846 SrcList *pSrc, /* the FROM clause */
847 WhereClause *pWC, /* the complete WHERE clause */
848 int idxTerm /* Index of the OR-term to be analyzed */
849){
drh70d18342013-06-06 19:16:33 +0000850 WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
851 Parse *pParse = pWInfo->pParse; /* Parser context */
drh1a58fe02008-12-20 02:06:13 +0000852 sqlite3 *db = pParse->db; /* Database connection */
853 WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */
854 Expr *pExpr = pTerm->pExpr; /* The expression of the term */
drh1a58fe02008-12-20 02:06:13 +0000855 int i; /* Loop counters */
856 WhereClause *pOrWc; /* Breakup of pTerm into subterms */
857 WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */
858 WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */
859 Bitmask chngToIN; /* Tables that might satisfy case 1 */
860 Bitmask indexable; /* Tables that are indexable, satisfying case 2 */
drh3e355802007-02-23 23:13:33 +0000861
drh1a58fe02008-12-20 02:06:13 +0000862 /*
863 ** Break the OR clause into its separate subterms. The subterms are
864 ** stored in a WhereClause structure containing within the WhereOrInfo
865 ** object that is attached to the original OR clause term.
866 */
867 assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
868 assert( pExpr->op==TK_OR );
drh954701a2008-12-29 23:45:07 +0000869 pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
drh1a58fe02008-12-20 02:06:13 +0000870 if( pOrInfo==0 ) return;
871 pTerm->wtFlags |= TERM_ORINFO;
872 pOrWc = &pOrInfo->wc;
drh70d18342013-06-06 19:16:33 +0000873 whereClauseInit(pOrWc, pWInfo);
drh1a58fe02008-12-20 02:06:13 +0000874 whereSplit(pOrWc, pExpr, TK_OR);
875 exprAnalyzeAll(pSrc, pOrWc);
876 if( db->mallocFailed ) return;
877 assert( pOrWc->nTerm>=2 );
878
879 /*
880 ** Compute the set of tables that might satisfy cases 1 or 2.
881 */
danielk1977e672c8e2009-05-22 15:43:26 +0000882 indexable = ~(Bitmask)0;
drhc3e552f2013-02-08 16:04:19 +0000883 chngToIN = ~(Bitmask)0;
drh1a58fe02008-12-20 02:06:13 +0000884 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
885 if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
drh29435252008-12-28 18:35:08 +0000886 WhereAndInfo *pAndInfo;
drh29435252008-12-28 18:35:08 +0000887 assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
drh1a58fe02008-12-20 02:06:13 +0000888 chngToIN = 0;
drh29435252008-12-28 18:35:08 +0000889 pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
890 if( pAndInfo ){
891 WhereClause *pAndWC;
892 WhereTerm *pAndTerm;
893 int j;
894 Bitmask b = 0;
895 pOrTerm->u.pAndInfo = pAndInfo;
896 pOrTerm->wtFlags |= TERM_ANDINFO;
897 pOrTerm->eOperator = WO_AND;
898 pAndWC = &pAndInfo->wc;
drh70d18342013-06-06 19:16:33 +0000899 whereClauseInit(pAndWC, pWC->pWInfo);
drh29435252008-12-28 18:35:08 +0000900 whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
901 exprAnalyzeAll(pSrc, pAndWC);
drh8871ef52011-10-07 13:33:10 +0000902 pAndWC->pOuter = pWC;
drh7c2fbde2009-01-07 20:58:57 +0000903 testcase( db->mallocFailed );
drh96c7a7d2009-01-10 15:34:12 +0000904 if( !db->mallocFailed ){
905 for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
906 assert( pAndTerm->pExpr );
907 if( allowedOp(pAndTerm->pExpr->op) ){
drh70d18342013-06-06 19:16:33 +0000908 b |= getMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
drh96c7a7d2009-01-10 15:34:12 +0000909 }
drh29435252008-12-28 18:35:08 +0000910 }
911 }
912 indexable &= b;
913 }
drh1a58fe02008-12-20 02:06:13 +0000914 }else if( pOrTerm->wtFlags & TERM_COPIED ){
915 /* Skip this term for now. We revisit it when we process the
916 ** corresponding TERM_VIRTUAL term */
917 }else{
918 Bitmask b;
drh70d18342013-06-06 19:16:33 +0000919 b = getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
drh1a58fe02008-12-20 02:06:13 +0000920 if( pOrTerm->wtFlags & TERM_VIRTUAL ){
921 WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
drh70d18342013-06-06 19:16:33 +0000922 b |= getMask(&pWInfo->sMaskSet, pOther->leftCursor);
drh1a58fe02008-12-20 02:06:13 +0000923 }
924 indexable &= b;
drh7a5bcc02013-01-16 17:08:58 +0000925 if( (pOrTerm->eOperator & WO_EQ)==0 ){
drh1a58fe02008-12-20 02:06:13 +0000926 chngToIN = 0;
927 }else{
928 chngToIN &= b;
929 }
930 }
drh3e355802007-02-23 23:13:33 +0000931 }
drh1a58fe02008-12-20 02:06:13 +0000932
933 /*
934 ** Record the set of tables that satisfy case 2. The set might be
drh111a6a72008-12-21 03:51:16 +0000935 ** empty.
drh1a58fe02008-12-20 02:06:13 +0000936 */
937 pOrInfo->indexable = indexable;
drh111a6a72008-12-21 03:51:16 +0000938 pTerm->eOperator = indexable==0 ? 0 : WO_OR;
drh1a58fe02008-12-20 02:06:13 +0000939
940 /*
941 ** chngToIN holds a set of tables that *might* satisfy case 1. But
942 ** we have to do some additional checking to see if case 1 really
943 ** is satisfied.
drh4e8be3b2009-06-08 17:11:08 +0000944 **
945 ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means
946 ** that there is no possibility of transforming the OR clause into an
947 ** IN operator because one or more terms in the OR clause contain
948 ** something other than == on a column in the single table. The 1-bit
949 ** case means that every term of the OR clause is of the form
950 ** "table.column=expr" for some single table. The one bit that is set
951 ** will correspond to the common table. We still need to check to make
952 ** sure the same column is used on all terms. The 2-bit case is when
953 ** the all terms are of the form "table1.column=table2.column". It
954 ** might be possible to form an IN operator with either table1.column
955 ** or table2.column as the LHS if either is common to every term of
956 ** the OR clause.
957 **
958 ** Note that terms of the form "table.column1=table.column2" (the
959 ** same table on both sizes of the ==) cannot be optimized.
drh1a58fe02008-12-20 02:06:13 +0000960 */
961 if( chngToIN ){
962 int okToChngToIN = 0; /* True if the conversion to IN is valid */
963 int iColumn = -1; /* Column index on lhs of IN operator */
shane63207ab2009-02-04 01:49:30 +0000964 int iCursor = -1; /* Table cursor common to all terms */
drh1a58fe02008-12-20 02:06:13 +0000965 int j = 0; /* Loop counter */
966
967 /* Search for a table and column that appears on one side or the
968 ** other of the == operator in every subterm. That table and column
969 ** will be recorded in iCursor and iColumn. There might not be any
970 ** such table and column. Set okToChngToIN if an appropriate table
971 ** and column is found but leave okToChngToIN false if not found.
972 */
973 for(j=0; j<2 && !okToChngToIN; j++){
974 pOrTerm = pOrWc->a;
975 for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
drh7a5bcc02013-01-16 17:08:58 +0000976 assert( pOrTerm->eOperator & WO_EQ );
drh1a58fe02008-12-20 02:06:13 +0000977 pOrTerm->wtFlags &= ~TERM_OR_OK;
drh4e8be3b2009-06-08 17:11:08 +0000978 if( pOrTerm->leftCursor==iCursor ){
979 /* This is the 2-bit case and we are on the second iteration and
980 ** current term is from the first iteration. So skip this term. */
981 assert( j==1 );
982 continue;
983 }
drh70d18342013-06-06 19:16:33 +0000984 if( (chngToIN & getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor))==0 ){
drh4e8be3b2009-06-08 17:11:08 +0000985 /* This term must be of the form t1.a==t2.b where t2 is in the
peter.d.reid60ec9142014-09-06 16:39:46 +0000986 ** chngToIN set but t1 is not. This term will be either preceded
drh4e8be3b2009-06-08 17:11:08 +0000987 ** or follwed by an inverted copy (t2.b==t1.a). Skip this term
988 ** and use its inversion. */
989 testcase( pOrTerm->wtFlags & TERM_COPIED );
990 testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
991 assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
992 continue;
993 }
drh1a58fe02008-12-20 02:06:13 +0000994 iColumn = pOrTerm->u.leftColumn;
995 iCursor = pOrTerm->leftCursor;
996 break;
997 }
998 if( i<0 ){
drh4e8be3b2009-06-08 17:11:08 +0000999 /* No candidate table+column was found. This can only occur
1000 ** on the second iteration */
drh1a58fe02008-12-20 02:06:13 +00001001 assert( j==1 );
drh7a5bcc02013-01-16 17:08:58 +00001002 assert( IsPowerOfTwo(chngToIN) );
drh70d18342013-06-06 19:16:33 +00001003 assert( chngToIN==getMask(&pWInfo->sMaskSet, iCursor) );
drh1a58fe02008-12-20 02:06:13 +00001004 break;
1005 }
drh4e8be3b2009-06-08 17:11:08 +00001006 testcase( j==1 );
1007
1008 /* We have found a candidate table and column. Check to see if that
1009 ** table and column is common to every term in the OR clause */
drh1a58fe02008-12-20 02:06:13 +00001010 okToChngToIN = 1;
1011 for(; i>=0 && okToChngToIN; i--, pOrTerm++){
drh7a5bcc02013-01-16 17:08:58 +00001012 assert( pOrTerm->eOperator & WO_EQ );
drh1a58fe02008-12-20 02:06:13 +00001013 if( pOrTerm->leftCursor!=iCursor ){
1014 pOrTerm->wtFlags &= ~TERM_OR_OK;
1015 }else if( pOrTerm->u.leftColumn!=iColumn ){
1016 okToChngToIN = 0;
1017 }else{
1018 int affLeft, affRight;
1019 /* If the right-hand side is also a column, then the affinities
1020 ** of both right and left sides must be such that no type
1021 ** conversions are required on the right. (Ticket #2249)
1022 */
1023 affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
1024 affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
1025 if( affRight!=0 && affRight!=affLeft ){
1026 okToChngToIN = 0;
1027 }else{
1028 pOrTerm->wtFlags |= TERM_OR_OK;
1029 }
1030 }
1031 }
1032 }
1033
1034 /* At this point, okToChngToIN is true if original pTerm satisfies
1035 ** case 1. In that case, construct a new virtual term that is
1036 ** pTerm converted into an IN operator.
1037 */
1038 if( okToChngToIN ){
1039 Expr *pDup; /* A transient duplicate expression */
1040 ExprList *pList = 0; /* The RHS of the IN operator */
1041 Expr *pLeft = 0; /* The LHS of the IN operator */
1042 Expr *pNew; /* The complete IN operator */
1043
1044 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
1045 if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
drh7a5bcc02013-01-16 17:08:58 +00001046 assert( pOrTerm->eOperator & WO_EQ );
drh1a58fe02008-12-20 02:06:13 +00001047 assert( pOrTerm->leftCursor==iCursor );
1048 assert( pOrTerm->u.leftColumn==iColumn );
danielk19776ab3a2e2009-02-19 14:39:25 +00001049 pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
drh70d18342013-06-06 19:16:33 +00001050 pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
drh1a58fe02008-12-20 02:06:13 +00001051 pLeft = pOrTerm->pExpr->pLeft;
1052 }
1053 assert( pLeft!=0 );
danielk19776ab3a2e2009-02-19 14:39:25 +00001054 pDup = sqlite3ExprDup(db, pLeft, 0);
drhb7916a72009-05-27 10:31:29 +00001055 pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
drh1a58fe02008-12-20 02:06:13 +00001056 if( pNew ){
1057 int idxNew;
1058 transferJoinMarkings(pNew, pExpr);
danielk19776ab3a2e2009-02-19 14:39:25 +00001059 assert( !ExprHasProperty(pNew, EP_xIsSelect) );
1060 pNew->x.pList = pList;
drh1a58fe02008-12-20 02:06:13 +00001061 idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
1062 testcase( idxNew==0 );
1063 exprAnalyze(pSrc, pWC, idxNew);
1064 pTerm = &pWC->a[idxTerm];
drh9769efc2014-10-24 14:32:21 +00001065 markTermAsChild(pWC, idxNew, idxTerm);
drh1a58fe02008-12-20 02:06:13 +00001066 }else{
1067 sqlite3ExprListDelete(db, pList);
1068 }
drh534230c2011-01-22 00:10:45 +00001069 pTerm->eOperator = WO_NOOP; /* case 1 trumps case 2 */
drh1a58fe02008-12-20 02:06:13 +00001070 }
drh3e355802007-02-23 23:13:33 +00001071 }
drh3e355802007-02-23 23:13:33 +00001072}
1073#endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
drh54a167d2005-11-26 14:08:07 +00001074
drh7a5bcc02013-01-16 17:08:58 +00001075/*
drh0aa74ed2005-07-16 13:33:20 +00001076** The input to this routine is an WhereTerm structure with only the
drh51147ba2005-07-23 22:59:55 +00001077** "pExpr" field filled in. The job of this routine is to analyze the
drh0aa74ed2005-07-16 13:33:20 +00001078** subexpression and populate all the other fields of the WhereTerm
drh75897232000-05-29 14:26:00 +00001079** structure.
drh51147ba2005-07-23 22:59:55 +00001080**
1081** If the expression is of the form "<expr> <op> X" it gets commuted
drh1a58fe02008-12-20 02:06:13 +00001082** to the standard form of "X <op> <expr>".
1083**
1084** If the expression is of the form "X <op> Y" where both X and Y are
1085** columns, then the original expression is unchanged and a new virtual
1086** term of the form "Y <op> X" is added to the WHERE clause and
1087** analyzed separately. The original term is marked with TERM_COPIED
1088** and the new term is marked with TERM_DYNAMIC (because it's pExpr
1089** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
1090** is a commuted copy of a prior term.) The original term has nChild=1
1091** and the copy has idxParent set to the index of the original term.
drh75897232000-05-29 14:26:00 +00001092*/
drh0fcef5e2005-07-19 17:38:22 +00001093static void exprAnalyze(
1094 SrcList *pSrc, /* the FROM clause */
drh9eb20282005-08-24 03:52:18 +00001095 WhereClause *pWC, /* the WHERE clause */
1096 int idxTerm /* Index of the term to be analyzed */
drh0fcef5e2005-07-19 17:38:22 +00001097){
drh70d18342013-06-06 19:16:33 +00001098 WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
drh1a58fe02008-12-20 02:06:13 +00001099 WhereTerm *pTerm; /* The term to be analyzed */
drh111a6a72008-12-21 03:51:16 +00001100 WhereMaskSet *pMaskSet; /* Set of table index masks */
drh1a58fe02008-12-20 02:06:13 +00001101 Expr *pExpr; /* The expression to be analyzed */
1102 Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */
1103 Bitmask prereqAll; /* Prerequesites of pExpr */
drh5e767c52010-02-25 04:15:47 +00001104 Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */
drh1d452e12009-11-01 19:26:59 +00001105 Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */
1106 int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */
1107 int noCase = 0; /* LIKE/GLOB distinguishes case */
drh1a58fe02008-12-20 02:06:13 +00001108 int op; /* Top-level operator. pExpr->op */
drh70d18342013-06-06 19:16:33 +00001109 Parse *pParse = pWInfo->pParse; /* Parsing context */
drh1a58fe02008-12-20 02:06:13 +00001110 sqlite3 *db = pParse->db; /* Database connection */
drh0fcef5e2005-07-19 17:38:22 +00001111
drhf998b732007-11-26 13:36:00 +00001112 if( db->mallocFailed ){
1113 return;
1114 }
1115 pTerm = &pWC->a[idxTerm];
drh70d18342013-06-06 19:16:33 +00001116 pMaskSet = &pWInfo->sMaskSet;
drh7ee751d2012-12-19 15:53:51 +00001117 pExpr = pTerm->pExpr;
1118 assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
drh0fcef5e2005-07-19 17:38:22 +00001119 prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
drh50b39962006-10-28 00:28:09 +00001120 op = pExpr->op;
1121 if( op==TK_IN ){
drhf5b11382005-09-17 13:07:13 +00001122 assert( pExpr->pRight==0 );
danielk19776ab3a2e2009-02-19 14:39:25 +00001123 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
1124 pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
1125 }else{
1126 pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
1127 }
drh50b39962006-10-28 00:28:09 +00001128 }else if( op==TK_ISNULL ){
1129 pTerm->prereqRight = 0;
drhf5b11382005-09-17 13:07:13 +00001130 }else{
1131 pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
1132 }
drh22d6a532005-09-19 21:05:48 +00001133 prereqAll = exprTableUsage(pMaskSet, pExpr);
1134 if( ExprHasProperty(pExpr, EP_FromJoin) ){
drh42165be2008-03-26 14:56:34 +00001135 Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
1136 prereqAll |= x;
drhdafc0ce2008-04-17 19:14:02 +00001137 extraRight = x-1; /* ON clause terms may not be used with an index
1138 ** on left table of a LEFT JOIN. Ticket #3015 */
drh22d6a532005-09-19 21:05:48 +00001139 }
1140 pTerm->prereqAll = prereqAll;
drh0fcef5e2005-07-19 17:38:22 +00001141 pTerm->leftCursor = -1;
drh45b1ee42005-08-02 17:48:22 +00001142 pTerm->iParent = -1;
drhb52076c2006-01-23 13:22:09 +00001143 pTerm->eOperator = 0;
drh738fc792013-01-17 15:05:17 +00001144 if( allowedOp(op) ){
drh7a66da12012-12-07 20:31:11 +00001145 Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
1146 Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
drh738fc792013-01-17 15:05:17 +00001147 u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
drh0fcef5e2005-07-19 17:38:22 +00001148 if( pLeft->op==TK_COLUMN ){
1149 pTerm->leftCursor = pLeft->iTable;
drh700a2262008-12-17 19:22:15 +00001150 pTerm->u.leftColumn = pLeft->iColumn;
drh738fc792013-01-17 15:05:17 +00001151 pTerm->eOperator = operatorMask(op) & opMask;
drh75897232000-05-29 14:26:00 +00001152 }
drh0fcef5e2005-07-19 17:38:22 +00001153 if( pRight && pRight->op==TK_COLUMN ){
1154 WhereTerm *pNew;
1155 Expr *pDup;
drh7a5bcc02013-01-16 17:08:58 +00001156 u16 eExtraOp = 0; /* Extra bits for pNew->eOperator */
drh0fcef5e2005-07-19 17:38:22 +00001157 if( pTerm->leftCursor>=0 ){
drh9eb20282005-08-24 03:52:18 +00001158 int idxNew;
danielk19776ab3a2e2009-02-19 14:39:25 +00001159 pDup = sqlite3ExprDup(db, pExpr, 0);
drh17435752007-08-16 04:30:38 +00001160 if( db->mallocFailed ){
drh633e6d52008-07-28 19:34:53 +00001161 sqlite3ExprDelete(db, pDup);
drh28f45912006-10-18 23:26:38 +00001162 return;
1163 }
drh9eb20282005-08-24 03:52:18 +00001164 idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
1165 if( idxNew==0 ) return;
1166 pNew = &pWC->a[idxNew];
drh9769efc2014-10-24 14:32:21 +00001167 markTermAsChild(pWC, idxNew, idxTerm);
drh9eb20282005-08-24 03:52:18 +00001168 pTerm = &pWC->a[idxTerm];
drh165be382008-12-05 02:36:33 +00001169 pTerm->wtFlags |= TERM_COPIED;
drheb5bc922013-01-17 16:43:33 +00001170 if( pExpr->op==TK_EQ
1171 && !ExprHasProperty(pExpr, EP_FromJoin)
1172 && OptimizationEnabled(db, SQLITE_Transitive)
1173 ){
drh7a5bcc02013-01-16 17:08:58 +00001174 pTerm->eOperator |= WO_EQUIV;
1175 eExtraOp = WO_EQUIV;
1176 }
drh0fcef5e2005-07-19 17:38:22 +00001177 }else{
1178 pDup = pExpr;
1179 pNew = pTerm;
1180 }
drh7d10d5a2008-08-20 16:35:10 +00001181 exprCommute(pParse, pDup);
drhfb76f5a2012-12-08 14:16:47 +00001182 pLeft = sqlite3ExprSkipCollate(pDup->pLeft);
drh0fcef5e2005-07-19 17:38:22 +00001183 pNew->leftCursor = pLeft->iTable;
drh700a2262008-12-17 19:22:15 +00001184 pNew->u.leftColumn = pLeft->iColumn;
drh5e767c52010-02-25 04:15:47 +00001185 testcase( (prereqLeft | extraRight) != prereqLeft );
1186 pNew->prereqRight = prereqLeft | extraRight;
drh0fcef5e2005-07-19 17:38:22 +00001187 pNew->prereqAll = prereqAll;
drh738fc792013-01-17 15:05:17 +00001188 pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
drh75897232000-05-29 14:26:00 +00001189 }
1190 }
drhed378002005-07-28 23:12:08 +00001191
drhd2687b72005-08-12 22:56:09 +00001192#ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
drhed378002005-07-28 23:12:08 +00001193 /* If a term is the BETWEEN operator, create two new virtual terms
drh1a58fe02008-12-20 02:06:13 +00001194 ** that define the range that the BETWEEN implements. For example:
1195 **
1196 ** a BETWEEN b AND c
1197 **
1198 ** is converted into:
1199 **
1200 ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
1201 **
1202 ** The two new terms are added onto the end of the WhereClause object.
1203 ** The new terms are "dynamic" and are children of the original BETWEEN
1204 ** term. That means that if the BETWEEN term is coded, the children are
1205 ** skipped. Or, if the children are satisfied by an index, the original
1206 ** BETWEEN term is skipped.
drhed378002005-07-28 23:12:08 +00001207 */
drh29435252008-12-28 18:35:08 +00001208 else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
danielk19776ab3a2e2009-02-19 14:39:25 +00001209 ExprList *pList = pExpr->x.pList;
drhed378002005-07-28 23:12:08 +00001210 int i;
1211 static const u8 ops[] = {TK_GE, TK_LE};
1212 assert( pList!=0 );
1213 assert( pList->nExpr==2 );
1214 for(i=0; i<2; i++){
1215 Expr *pNewExpr;
drh9eb20282005-08-24 03:52:18 +00001216 int idxNew;
drhb7916a72009-05-27 10:31:29 +00001217 pNewExpr = sqlite3PExpr(pParse, ops[i],
1218 sqlite3ExprDup(db, pExpr->pLeft, 0),
danielk19776ab3a2e2009-02-19 14:39:25 +00001219 sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
drhd41d39f2013-08-28 16:27:01 +00001220 transferJoinMarkings(pNewExpr, pExpr);
drh9eb20282005-08-24 03:52:18 +00001221 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
drh6a1e0712008-12-05 15:24:15 +00001222 testcase( idxNew==0 );
drh7b4fc6a2007-02-06 13:26:32 +00001223 exprAnalyze(pSrc, pWC, idxNew);
drh9eb20282005-08-24 03:52:18 +00001224 pTerm = &pWC->a[idxTerm];
drh9769efc2014-10-24 14:32:21 +00001225 markTermAsChild(pWC, idxNew, idxTerm);
drhed378002005-07-28 23:12:08 +00001226 }
drhed378002005-07-28 23:12:08 +00001227 }
drhd2687b72005-08-12 22:56:09 +00001228#endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
drhed378002005-07-28 23:12:08 +00001229
danielk19771576cd92006-01-14 08:02:28 +00001230#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
drh1a58fe02008-12-20 02:06:13 +00001231 /* Analyze a term that is composed of two or more subterms connected by
1232 ** an OR operator.
drh6c30be82005-07-29 15:10:17 +00001233 */
1234 else if( pExpr->op==TK_OR ){
drh29435252008-12-28 18:35:08 +00001235 assert( pWC->op==TK_AND );
drh1a58fe02008-12-20 02:06:13 +00001236 exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
danielk1977f51d1bd2009-07-31 06:14:51 +00001237 pTerm = &pWC->a[idxTerm];
drh6c30be82005-07-29 15:10:17 +00001238 }
drhd2687b72005-08-12 22:56:09 +00001239#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
1240
1241#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
1242 /* Add constraints to reduce the search space on a LIKE or GLOB
1243 ** operator.
drh9f504ea2008-02-23 21:55:39 +00001244 **
1245 ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
1246 **
1247 ** x>='abc' AND x<'abd' AND x LIKE 'abc%'
1248 **
1249 ** The last character of the prefix "abc" is incremented to form the
shane7bc71e52008-05-28 18:01:44 +00001250 ** termination condition "abd".
drhd2687b72005-08-12 22:56:09 +00001251 */
dan937d0de2009-10-15 18:35:38 +00001252 if( pWC->op==TK_AND
1253 && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
1254 ){
drh1d452e12009-11-01 19:26:59 +00001255 Expr *pLeft; /* LHS of LIKE/GLOB operator */
1256 Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */
1257 Expr *pNewExpr1;
1258 Expr *pNewExpr2;
1259 int idxNew1;
1260 int idxNew2;
drhae80dde2012-12-06 21:16:43 +00001261 Token sCollSeqName; /* Name of collating sequence */
drh9eb20282005-08-24 03:52:18 +00001262
danielk19776ab3a2e2009-02-19 14:39:25 +00001263 pLeft = pExpr->x.pList->a[1].pExpr;
danielk19776ab3a2e2009-02-19 14:39:25 +00001264 pStr2 = sqlite3ExprDup(db, pStr1, 0);
drhf998b732007-11-26 13:36:00 +00001265 if( !db->mallocFailed ){
drh254993e2009-06-08 19:44:36 +00001266 u8 c, *pC; /* Last character before the first wildcard */
dan937d0de2009-10-15 18:35:38 +00001267 pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
drh9f504ea2008-02-23 21:55:39 +00001268 c = *pC;
drh02a50b72008-05-26 18:33:40 +00001269 if( noCase ){
drh254993e2009-06-08 19:44:36 +00001270 /* The point is to increment the last character before the first
1271 ** wildcard. But if we increment '@', that will push it into the
1272 ** alphabetic range where case conversions will mess up the
1273 ** inequality. To avoid this, make sure to also run the full
1274 ** LIKE on all candidate expressions by clearing the isComplete flag
1275 */
drh39759742013-08-02 23:40:45 +00001276 if( c=='A'-1 ) isComplete = 0;
drh02a50b72008-05-26 18:33:40 +00001277 c = sqlite3UpperToLower[c];
1278 }
drh9f504ea2008-02-23 21:55:39 +00001279 *pC = c + 1;
drhd2687b72005-08-12 22:56:09 +00001280 }
drhae80dde2012-12-06 21:16:43 +00001281 sCollSeqName.z = noCase ? "NOCASE" : "BINARY";
1282 sCollSeqName.n = 6;
1283 pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
drh8342e492010-07-22 17:49:52 +00001284 pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
drh0a8a4062012-12-07 18:38:16 +00001285 sqlite3ExprAddCollateToken(pParse,pNewExpr1,&sCollSeqName),
drhae80dde2012-12-06 21:16:43 +00001286 pStr1, 0);
drhd41d39f2013-08-28 16:27:01 +00001287 transferJoinMarkings(pNewExpr1, pExpr);
drh9eb20282005-08-24 03:52:18 +00001288 idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
drh6a1e0712008-12-05 15:24:15 +00001289 testcase( idxNew1==0 );
drh7b4fc6a2007-02-06 13:26:32 +00001290 exprAnalyze(pSrc, pWC, idxNew1);
drhae80dde2012-12-06 21:16:43 +00001291 pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
drh8342e492010-07-22 17:49:52 +00001292 pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
drh0a8a4062012-12-07 18:38:16 +00001293 sqlite3ExprAddCollateToken(pParse,pNewExpr2,&sCollSeqName),
drhae80dde2012-12-06 21:16:43 +00001294 pStr2, 0);
drhd41d39f2013-08-28 16:27:01 +00001295 transferJoinMarkings(pNewExpr2, pExpr);
drh9eb20282005-08-24 03:52:18 +00001296 idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
drh6a1e0712008-12-05 15:24:15 +00001297 testcase( idxNew2==0 );
drh7b4fc6a2007-02-06 13:26:32 +00001298 exprAnalyze(pSrc, pWC, idxNew2);
drh9eb20282005-08-24 03:52:18 +00001299 pTerm = &pWC->a[idxTerm];
drhd2687b72005-08-12 22:56:09 +00001300 if( isComplete ){
drh9769efc2014-10-24 14:32:21 +00001301 markTermAsChild(pWC, idxNew1, idxTerm);
1302 markTermAsChild(pWC, idxNew2, idxTerm);
drhd2687b72005-08-12 22:56:09 +00001303 }
1304 }
1305#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
drh7f375902006-06-13 17:38:59 +00001306
1307#ifndef SQLITE_OMIT_VIRTUALTABLE
1308 /* Add a WO_MATCH auxiliary term to the constraint set if the
1309 ** current expression is of the form: column MATCH expr.
1310 ** This information is used by the xBestIndex methods of
1311 ** virtual tables. The native query optimizer does not attempt
1312 ** to do anything with MATCH functions.
1313 */
1314 if( isMatchOfColumn(pExpr) ){
1315 int idxNew;
1316 Expr *pRight, *pLeft;
1317 WhereTerm *pNewTerm;
1318 Bitmask prereqColumn, prereqExpr;
1319
danielk19776ab3a2e2009-02-19 14:39:25 +00001320 pRight = pExpr->x.pList->a[0].pExpr;
1321 pLeft = pExpr->x.pList->a[1].pExpr;
drh7f375902006-06-13 17:38:59 +00001322 prereqExpr = exprTableUsage(pMaskSet, pRight);
1323 prereqColumn = exprTableUsage(pMaskSet, pLeft);
1324 if( (prereqExpr & prereqColumn)==0 ){
drh1a90e092006-06-14 22:07:10 +00001325 Expr *pNewExpr;
drhb7916a72009-05-27 10:31:29 +00001326 pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
1327 0, sqlite3ExprDup(db, pRight, 0), 0);
drh1a90e092006-06-14 22:07:10 +00001328 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
drh6a1e0712008-12-05 15:24:15 +00001329 testcase( idxNew==0 );
drh7f375902006-06-13 17:38:59 +00001330 pNewTerm = &pWC->a[idxNew];
1331 pNewTerm->prereqRight = prereqExpr;
1332 pNewTerm->leftCursor = pLeft->iTable;
drh700a2262008-12-17 19:22:15 +00001333 pNewTerm->u.leftColumn = pLeft->iColumn;
drh7f375902006-06-13 17:38:59 +00001334 pNewTerm->eOperator = WO_MATCH;
drh9769efc2014-10-24 14:32:21 +00001335 markTermAsChild(pWC, idxNew, idxTerm);
drhd2ca60d2006-06-27 02:36:58 +00001336 pTerm = &pWC->a[idxTerm];
drh165be382008-12-05 02:36:33 +00001337 pTerm->wtFlags |= TERM_COPIED;
drh7f375902006-06-13 17:38:59 +00001338 pNewTerm->prereqAll = pTerm->prereqAll;
1339 }
1340 }
1341#endif /* SQLITE_OMIT_VIRTUALTABLE */
drhdafc0ce2008-04-17 19:14:02 +00001342
drh1435a9a2013-08-27 23:15:44 +00001343#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drhd3ed7342011-09-21 00:09:41 +00001344 /* When sqlite_stat3 histogram data is available an operator of the
drh534230c2011-01-22 00:10:45 +00001345 ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
1346 ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a
1347 ** virtual term of that form.
1348 **
1349 ** Note that the virtual term must be tagged with TERM_VNULL. This
1350 ** TERM_VNULL tag will suppress the not-null check at the beginning
1351 ** of the loop. Without the TERM_VNULL flag, the not-null check at
1352 ** the start of the loop will prevent any results from being returned.
1353 */
drhea6dc442011-04-08 21:35:26 +00001354 if( pExpr->op==TK_NOTNULL
1355 && pExpr->pLeft->op==TK_COLUMN
1356 && pExpr->pLeft->iColumn>=0
drhd7d71472014-10-22 19:57:16 +00001357 && OptimizationEnabled(db, SQLITE_Stat34)
drhea6dc442011-04-08 21:35:26 +00001358 ){
drh534230c2011-01-22 00:10:45 +00001359 Expr *pNewExpr;
1360 Expr *pLeft = pExpr->pLeft;
1361 int idxNew;
1362 WhereTerm *pNewTerm;
1363
1364 pNewExpr = sqlite3PExpr(pParse, TK_GT,
1365 sqlite3ExprDup(db, pLeft, 0),
1366 sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
1367
1368 idxNew = whereClauseInsert(pWC, pNewExpr,
1369 TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
drhda91e712011-02-11 06:59:02 +00001370 if( idxNew ){
1371 pNewTerm = &pWC->a[idxNew];
1372 pNewTerm->prereqRight = 0;
1373 pNewTerm->leftCursor = pLeft->iTable;
1374 pNewTerm->u.leftColumn = pLeft->iColumn;
1375 pNewTerm->eOperator = WO_GT;
drh9769efc2014-10-24 14:32:21 +00001376 markTermAsChild(pWC, idxNew, idxTerm);
drhda91e712011-02-11 06:59:02 +00001377 pTerm = &pWC->a[idxTerm];
drhda91e712011-02-11 06:59:02 +00001378 pTerm->wtFlags |= TERM_COPIED;
1379 pNewTerm->prereqAll = pTerm->prereqAll;
1380 }
drh534230c2011-01-22 00:10:45 +00001381 }
drh1435a9a2013-08-27 23:15:44 +00001382#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
drh534230c2011-01-22 00:10:45 +00001383
drhdafc0ce2008-04-17 19:14:02 +00001384 /* Prevent ON clause terms of a LEFT JOIN from being used to drive
1385 ** an index for tables to the left of the join.
1386 */
1387 pTerm->prereqRight |= extraRight;
drh75897232000-05-29 14:26:00 +00001388}
1389
drh7b4fc6a2007-02-06 13:26:32 +00001390/*
peter.d.reid60ec9142014-09-06 16:39:46 +00001391** This function searches pList for an entry that matches the iCol-th column
drh3b48e8c2013-06-12 20:18:16 +00001392** of index pIdx.
dan6f343962011-07-01 18:26:40 +00001393**
1394** If such an expression is found, its index in pList->a[] is returned. If
1395** no expression is found, -1 is returned.
1396*/
1397static int findIndexCol(
1398 Parse *pParse, /* Parse context */
1399 ExprList *pList, /* Expression list to search */
1400 int iBase, /* Cursor for table associated with pIdx */
1401 Index *pIdx, /* Index to match column of */
1402 int iCol /* Column of index to match */
1403){
1404 int i;
1405 const char *zColl = pIdx->azColl[iCol];
1406
1407 for(i=0; i<pList->nExpr; i++){
drh580c8c12012-12-08 03:34:04 +00001408 Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
drhf1d3e322011-07-09 13:00:41 +00001409 if( p->op==TK_COLUMN
1410 && p->iColumn==pIdx->aiColumn[iCol]
1411 && p->iTable==iBase
1412 ){
drh580c8c12012-12-08 03:34:04 +00001413 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
drhf1d3e322011-07-09 13:00:41 +00001414 if( ALWAYS(pColl) && 0==sqlite3StrICmp(pColl->zName, zColl) ){
dan6f343962011-07-01 18:26:40 +00001415 return i;
1416 }
1417 }
1418 }
1419
1420 return -1;
1421}
1422
1423/*
dan6f343962011-07-01 18:26:40 +00001424** Return true if the DISTINCT expression-list passed as the third argument
drh4f402f22013-06-11 18:59:38 +00001425** is redundant.
1426**
drh3b48e8c2013-06-12 20:18:16 +00001427** A DISTINCT list is redundant if the database contains some subset of
drh4f402f22013-06-11 18:59:38 +00001428** columns that are unique and non-null.
dan6f343962011-07-01 18:26:40 +00001429*/
1430static int isDistinctRedundant(
drh4f402f22013-06-11 18:59:38 +00001431 Parse *pParse, /* Parsing context */
1432 SrcList *pTabList, /* The FROM clause */
1433 WhereClause *pWC, /* The WHERE clause */
1434 ExprList *pDistinct /* The result set that needs to be DISTINCT */
dan6f343962011-07-01 18:26:40 +00001435){
1436 Table *pTab;
1437 Index *pIdx;
1438 int i;
1439 int iBase;
1440
1441 /* If there is more than one table or sub-select in the FROM clause of
1442 ** this query, then it will not be possible to show that the DISTINCT
1443 ** clause is redundant. */
1444 if( pTabList->nSrc!=1 ) return 0;
1445 iBase = pTabList->a[0].iCursor;
1446 pTab = pTabList->a[0].pTab;
1447
dan94e08d92011-07-02 06:44:05 +00001448 /* If any of the expressions is an IPK column on table iBase, then return
1449 ** true. Note: The (p->iTable==iBase) part of this test may be false if the
1450 ** current SELECT is a correlated sub-query.
1451 */
dan6f343962011-07-01 18:26:40 +00001452 for(i=0; i<pDistinct->nExpr; i++){
drh580c8c12012-12-08 03:34:04 +00001453 Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
dan94e08d92011-07-02 06:44:05 +00001454 if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
dan6f343962011-07-01 18:26:40 +00001455 }
1456
1457 /* Loop through all indices on the table, checking each to see if it makes
1458 ** the DISTINCT qualifier redundant. It does so if:
1459 **
1460 ** 1. The index is itself UNIQUE, and
1461 **
1462 ** 2. All of the columns in the index are either part of the pDistinct
1463 ** list, or else the WHERE clause contains a term of the form "col=X",
1464 ** where X is a constant value. The collation sequences of the
1465 ** comparison and select-list expressions must match those of the index.
dan6a36f432012-04-20 16:59:24 +00001466 **
1467 ** 3. All of those index columns for which the WHERE clause does not
1468 ** contain a "col=X" term are subject to a NOT NULL constraint.
dan6f343962011-07-01 18:26:40 +00001469 */
1470 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
drh5f1d1d92014-07-31 22:59:04 +00001471 if( !IsUniqueIndex(pIdx) ) continue;
drhbbbdc832013-10-22 18:01:40 +00001472 for(i=0; i<pIdx->nKeyCol; i++){
1473 i16 iCol = pIdx->aiColumn[i];
dan6a36f432012-04-20 16:59:24 +00001474 if( 0==findTerm(pWC, iBase, iCol, ~(Bitmask)0, WO_EQ, pIdx) ){
1475 int iIdxCol = findIndexCol(pParse, pDistinct, iBase, pIdx, i);
drhbbbdc832013-10-22 18:01:40 +00001476 if( iIdxCol<0 || pTab->aCol[iCol].notNull==0 ){
dan6a36f432012-04-20 16:59:24 +00001477 break;
1478 }
dan6f343962011-07-01 18:26:40 +00001479 }
1480 }
drhbbbdc832013-10-22 18:01:40 +00001481 if( i==pIdx->nKeyCol ){
dan6f343962011-07-01 18:26:40 +00001482 /* This index implies that the DISTINCT qualifier is redundant. */
1483 return 1;
1484 }
1485 }
1486
1487 return 0;
1488}
drh0fcef5e2005-07-19 17:38:22 +00001489
drh8636e9c2013-06-11 01:50:08 +00001490
drh75897232000-05-29 14:26:00 +00001491/*
drh3b48e8c2013-06-12 20:18:16 +00001492** Estimate the logarithm of the input value to base 2.
drh28c4cf42005-07-27 20:41:43 +00001493*/
drhbf539c42013-10-05 18:16:02 +00001494static LogEst estLog(LogEst N){
drh696964d2014-06-12 15:46:46 +00001495 return N<=10 ? 0 : sqlite3LogEst(N) - 33;
drh28c4cf42005-07-27 20:41:43 +00001496}
1497
drh6d209d82006-06-27 01:54:26 +00001498/*
1499** Two routines for printing the content of an sqlite3_index_info
1500** structure. Used for testing and debugging only. If neither
1501** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
1502** are no-ops.
1503*/
drhd15cb172013-05-21 19:23:10 +00001504#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
drh6d209d82006-06-27 01:54:26 +00001505static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
1506 int i;
mlcreech3a00f902008-03-04 17:45:01 +00001507 if( !sqlite3WhereTrace ) return;
drh6d209d82006-06-27 01:54:26 +00001508 for(i=0; i<p->nConstraint; i++){
1509 sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
1510 i,
1511 p->aConstraint[i].iColumn,
1512 p->aConstraint[i].iTermOffset,
1513 p->aConstraint[i].op,
1514 p->aConstraint[i].usable);
1515 }
1516 for(i=0; i<p->nOrderBy; i++){
1517 sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n",
1518 i,
1519 p->aOrderBy[i].iColumn,
1520 p->aOrderBy[i].desc);
1521 }
1522}
1523static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
1524 int i;
mlcreech3a00f902008-03-04 17:45:01 +00001525 if( !sqlite3WhereTrace ) return;
drh6d209d82006-06-27 01:54:26 +00001526 for(i=0; i<p->nConstraint; i++){
1527 sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n",
1528 i,
1529 p->aConstraintUsage[i].argvIndex,
1530 p->aConstraintUsage[i].omit);
1531 }
1532 sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum);
1533 sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr);
1534 sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed);
1535 sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost);
dana9f58152013-11-11 19:01:33 +00001536 sqlite3DebugPrintf(" estimatedRows=%lld\n", p->estimatedRows);
drh6d209d82006-06-27 01:54:26 +00001537}
1538#else
1539#define TRACE_IDX_INPUTS(A)
1540#define TRACE_IDX_OUTPUTS(A)
1541#endif
1542
drhc6339082010-04-07 16:54:58 +00001543#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
drh8b307fb2010-04-06 15:57:05 +00001544/*
drh4139c992010-04-07 14:59:45 +00001545** Return TRUE if the WHERE clause term pTerm is of a form where it
1546** could be used with an index to access pSrc, assuming an appropriate
1547** index existed.
1548*/
1549static int termCanDriveIndex(
1550 WhereTerm *pTerm, /* WHERE clause term to check */
1551 struct SrcList_item *pSrc, /* Table we are trying to access */
1552 Bitmask notReady /* Tables in outer loops of the join */
1553){
1554 char aff;
1555 if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
drh7a5bcc02013-01-16 17:08:58 +00001556 if( (pTerm->eOperator & WO_EQ)==0 ) return 0;
drh4139c992010-04-07 14:59:45 +00001557 if( (pTerm->prereqRight & notReady)!=0 ) return 0;
drh23f98da2013-05-21 15:52:07 +00001558 if( pTerm->u.leftColumn<0 ) return 0;
drh4139c992010-04-07 14:59:45 +00001559 aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
1560 if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
1561 return 1;
1562}
drhc6339082010-04-07 16:54:58 +00001563#endif
drh4139c992010-04-07 14:59:45 +00001564
drhc6339082010-04-07 16:54:58 +00001565
1566#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
drh8b307fb2010-04-06 15:57:05 +00001567/*
drhc6339082010-04-07 16:54:58 +00001568** Generate code to construct the Index object for an automatic index
1569** and to set up the WhereLevel object pLevel so that the code generator
1570** makes use of the automatic index.
drh8b307fb2010-04-06 15:57:05 +00001571*/
drhc6339082010-04-07 16:54:58 +00001572static void constructAutomaticIndex(
drh8b307fb2010-04-06 15:57:05 +00001573 Parse *pParse, /* The parsing context */
1574 WhereClause *pWC, /* The WHERE clause */
1575 struct SrcList_item *pSrc, /* The FROM clause term to get the next index */
1576 Bitmask notReady, /* Mask of cursors that are not available */
1577 WhereLevel *pLevel /* Write new index here */
1578){
drhbbbdc832013-10-22 18:01:40 +00001579 int nKeyCol; /* Number of columns in the constructed index */
drh8b307fb2010-04-06 15:57:05 +00001580 WhereTerm *pTerm; /* A single term of the WHERE clause */
1581 WhereTerm *pWCEnd; /* End of pWC->a[] */
drh8b307fb2010-04-06 15:57:05 +00001582 Index *pIdx; /* Object describing the transient index */
1583 Vdbe *v; /* Prepared statement under construction */
drh8b307fb2010-04-06 15:57:05 +00001584 int addrInit; /* Address of the initialization bypass jump */
1585 Table *pTable; /* The table being indexed */
drh8b307fb2010-04-06 15:57:05 +00001586 int addrTop; /* Top of the index fill loop */
1587 int regRecord; /* Register holding an index record */
1588 int n; /* Column counter */
drh4139c992010-04-07 14:59:45 +00001589 int i; /* Loop counter */
1590 int mxBitCol; /* Maximum column in pSrc->colUsed */
drh424aab82010-04-06 18:28:20 +00001591 CollSeq *pColl; /* Collating sequence to on a column */
drh7ba39a92013-05-30 17:43:19 +00001592 WhereLoop *pLoop; /* The Loop object */
drh77e57df2013-10-22 14:28:02 +00001593 char *zNotUsed; /* Extra space on the end of pIdx */
drh4139c992010-04-07 14:59:45 +00001594 Bitmask idxCols; /* Bitmap of columns used for indexing */
1595 Bitmask extraCols; /* Bitmap of additional columns */
drh8d56e202013-06-28 23:55:45 +00001596 u8 sentWarning = 0; /* True if a warnning has been issued */
drh059b2d52014-10-24 19:28:09 +00001597 Expr *pPartial = 0; /* Partial Index Expression */
1598 int iContinue = 0; /* Jump here to skip excluded rows */
drh8b307fb2010-04-06 15:57:05 +00001599
1600 /* Generate code to skip over the creation and initialization of the
1601 ** transient index on 2nd and subsequent iterations of the loop. */
1602 v = pParse->pVdbe;
1603 assert( v!=0 );
drh7d176102014-02-18 03:07:12 +00001604 addrInit = sqlite3CodeOnce(pParse); VdbeCoverage(v);
drh8b307fb2010-04-06 15:57:05 +00001605
drh4139c992010-04-07 14:59:45 +00001606 /* Count the number of columns that will be added to the index
1607 ** and used to match WHERE clause constraints */
drhbbbdc832013-10-22 18:01:40 +00001608 nKeyCol = 0;
drh424aab82010-04-06 18:28:20 +00001609 pTable = pSrc->pTab;
drh8b307fb2010-04-06 15:57:05 +00001610 pWCEnd = &pWC->a[pWC->nTerm];
drh7ba39a92013-05-30 17:43:19 +00001611 pLoop = pLevel->pWLoop;
drh4139c992010-04-07 14:59:45 +00001612 idxCols = 0;
drh81186b42013-06-18 01:52:41 +00001613 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
drh059b2d52014-10-24 19:28:09 +00001614 if( pLoop->prereq==0
drh051575c2014-10-25 12:28:25 +00001615 && (pTerm->wtFlags & TERM_VIRTUAL)==0
drh059b2d52014-10-24 19:28:09 +00001616 && sqlite3ExprIsTableConstant(pTerm->pExpr, pSrc->iCursor) ){
1617 pPartial = sqlite3ExprAnd(pParse->db, pPartial,
1618 sqlite3ExprDup(pParse->db, pTerm->pExpr, 0));
1619 }
drh4139c992010-04-07 14:59:45 +00001620 if( termCanDriveIndex(pTerm, pSrc, notReady) ){
1621 int iCol = pTerm->u.leftColumn;
drh7699d1c2013-06-04 12:42:29 +00001622 Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
drh52ff8ea2010-04-08 14:15:56 +00001623 testcase( iCol==BMS );
1624 testcase( iCol==BMS-1 );
drh8d56e202013-06-28 23:55:45 +00001625 if( !sentWarning ){
1626 sqlite3_log(SQLITE_WARNING_AUTOINDEX,
1627 "automatic index on %s(%s)", pTable->zName,
1628 pTable->aCol[iCol].zName);
1629 sentWarning = 1;
1630 }
drh0013e722010-04-08 00:40:15 +00001631 if( (idxCols & cMask)==0 ){
drh059b2d52014-10-24 19:28:09 +00001632 if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ){
1633 goto end_auto_index_create;
1634 }
drhbbbdc832013-10-22 18:01:40 +00001635 pLoop->aLTerm[nKeyCol++] = pTerm;
drh0013e722010-04-08 00:40:15 +00001636 idxCols |= cMask;
1637 }
drh8b307fb2010-04-06 15:57:05 +00001638 }
1639 }
drhbbbdc832013-10-22 18:01:40 +00001640 assert( nKeyCol>0 );
1641 pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol;
drh53b52f72013-05-31 11:57:39 +00001642 pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
drh986b3872013-06-28 21:12:20 +00001643 | WHERE_AUTO_INDEX;
drh4139c992010-04-07 14:59:45 +00001644
1645 /* Count the number of additional columns needed to create a
1646 ** covering index. A "covering index" is an index that contains all
1647 ** columns that are needed by the query. With a covering index, the
1648 ** original table never needs to be accessed. Automatic indices must
1649 ** be a covering index because the index will not be updated if the
1650 ** original table changes and the index and table cannot both be used
1651 ** if they go out of sync.
1652 */
drh7699d1c2013-06-04 12:42:29 +00001653 extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
drhc3ef4fa2014-10-28 15:58:50 +00001654 mxBitCol = MIN(BMS-1,pTable->nCol);
drh52ff8ea2010-04-08 14:15:56 +00001655 testcase( pTable->nCol==BMS-1 );
1656 testcase( pTable->nCol==BMS-2 );
drh4139c992010-04-07 14:59:45 +00001657 for(i=0; i<mxBitCol; i++){
drhbbbdc832013-10-22 18:01:40 +00001658 if( extraCols & MASKBIT(i) ) nKeyCol++;
drh4139c992010-04-07 14:59:45 +00001659 }
drh7699d1c2013-06-04 12:42:29 +00001660 if( pSrc->colUsed & MASKBIT(BMS-1) ){
drhbbbdc832013-10-22 18:01:40 +00001661 nKeyCol += pTable->nCol - BMS + 1;
drh4139c992010-04-07 14:59:45 +00001662 }
drh8b307fb2010-04-06 15:57:05 +00001663
1664 /* Construct the Index object to describe this index */
drhbbbdc832013-10-22 18:01:40 +00001665 pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed);
drh059b2d52014-10-24 19:28:09 +00001666 if( pIdx==0 ) goto end_auto_index_create;
drh7ba39a92013-05-30 17:43:19 +00001667 pLoop->u.btree.pIndex = pIdx;
drh8b307fb2010-04-06 15:57:05 +00001668 pIdx->zName = "auto-index";
drh424aab82010-04-06 18:28:20 +00001669 pIdx->pTable = pTable;
drh8b307fb2010-04-06 15:57:05 +00001670 n = 0;
drh0013e722010-04-08 00:40:15 +00001671 idxCols = 0;
drh8b307fb2010-04-06 15:57:05 +00001672 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
drh4139c992010-04-07 14:59:45 +00001673 if( termCanDriveIndex(pTerm, pSrc, notReady) ){
drh0013e722010-04-08 00:40:15 +00001674 int iCol = pTerm->u.leftColumn;
drh7699d1c2013-06-04 12:42:29 +00001675 Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
drh7963b0e2013-06-17 21:37:40 +00001676 testcase( iCol==BMS-1 );
1677 testcase( iCol==BMS );
drh0013e722010-04-08 00:40:15 +00001678 if( (idxCols & cMask)==0 ){
1679 Expr *pX = pTerm->pExpr;
1680 idxCols |= cMask;
1681 pIdx->aiColumn[n] = pTerm->u.leftColumn;
1682 pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
drh6f2e6c02011-02-17 13:33:15 +00001683 pIdx->azColl[n] = ALWAYS(pColl) ? pColl->zName : "BINARY";
drh0013e722010-04-08 00:40:15 +00001684 n++;
1685 }
drh8b307fb2010-04-06 15:57:05 +00001686 }
1687 }
drh7ba39a92013-05-30 17:43:19 +00001688 assert( (u32)n==pLoop->u.btree.nEq );
drh4139c992010-04-07 14:59:45 +00001689
drhc6339082010-04-07 16:54:58 +00001690 /* Add additional columns needed to make the automatic index into
1691 ** a covering index */
drh4139c992010-04-07 14:59:45 +00001692 for(i=0; i<mxBitCol; i++){
drh7699d1c2013-06-04 12:42:29 +00001693 if( extraCols & MASKBIT(i) ){
drh4139c992010-04-07 14:59:45 +00001694 pIdx->aiColumn[n] = i;
1695 pIdx->azColl[n] = "BINARY";
1696 n++;
1697 }
1698 }
drh7699d1c2013-06-04 12:42:29 +00001699 if( pSrc->colUsed & MASKBIT(BMS-1) ){
drh4139c992010-04-07 14:59:45 +00001700 for(i=BMS-1; i<pTable->nCol; i++){
1701 pIdx->aiColumn[n] = i;
1702 pIdx->azColl[n] = "BINARY";
1703 n++;
1704 }
1705 }
drhbbbdc832013-10-22 18:01:40 +00001706 assert( n==nKeyCol );
drh44156282013-10-23 22:23:03 +00001707 pIdx->aiColumn[n] = -1;
1708 pIdx->azColl[n] = "BINARY";
drh8b307fb2010-04-06 15:57:05 +00001709
drhc6339082010-04-07 16:54:58 +00001710 /* Create the automatic index */
drh8b307fb2010-04-06 15:57:05 +00001711 assert( pLevel->iIdxCur>=0 );
drha1f41242013-05-31 20:00:58 +00001712 pLevel->iIdxCur = pParse->nTab++;
drh2ec2fb22013-11-06 19:59:23 +00001713 sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1);
1714 sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
drha21a64d2010-04-06 22:33:55 +00001715 VdbeComment((v, "for %s", pTable->zName));
drh8b307fb2010-04-06 15:57:05 +00001716
drhc6339082010-04-07 16:54:58 +00001717 /* Fill the automatic index with content */
drh059b2d52014-10-24 19:28:09 +00001718 sqlite3ExprCachePush(pParse);
drh688852a2014-02-17 22:40:43 +00001719 addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v);
drh059b2d52014-10-24 19:28:09 +00001720 if( pPartial ){
1721 iContinue = sqlite3VdbeMakeLabel(v);
1722 sqlite3ExprIfFalse(pParse, pPartial, iContinue, SQLITE_JUMPIFNULL);
drh051575c2014-10-25 12:28:25 +00001723 pLoop->wsFlags |= WHERE_PARTIALIDX;
drh059b2d52014-10-24 19:28:09 +00001724 }
drh8b307fb2010-04-06 15:57:05 +00001725 regRecord = sqlite3GetTempReg(pParse);
drh1c2c0b72014-01-04 19:27:05 +00001726 sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0);
drh8b307fb2010-04-06 15:57:05 +00001727 sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
1728 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
drh059b2d52014-10-24 19:28:09 +00001729 if( pPartial ) sqlite3VdbeResolveLabel(v, iContinue);
drh688852a2014-02-17 22:40:43 +00001730 sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v);
drha21a64d2010-04-06 22:33:55 +00001731 sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
drh8b307fb2010-04-06 15:57:05 +00001732 sqlite3VdbeJumpHere(v, addrTop);
1733 sqlite3ReleaseTempReg(pParse, regRecord);
drh059b2d52014-10-24 19:28:09 +00001734 sqlite3ExprCachePop(pParse);
drh8b307fb2010-04-06 15:57:05 +00001735
1736 /* Jump here when skipping the initialization */
1737 sqlite3VdbeJumpHere(v, addrInit);
drh059b2d52014-10-24 19:28:09 +00001738
1739end_auto_index_create:
1740 sqlite3ExprDelete(pParse->db, pPartial);
drh8b307fb2010-04-06 15:57:05 +00001741}
drhc6339082010-04-07 16:54:58 +00001742#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
drh8b307fb2010-04-06 15:57:05 +00001743
drh9eff6162006-06-12 21:59:13 +00001744#ifndef SQLITE_OMIT_VIRTUALTABLE
1745/*
danielk19771d461462009-04-21 09:02:45 +00001746** Allocate and populate an sqlite3_index_info structure. It is the
1747** responsibility of the caller to eventually release the structure
1748** by passing the pointer returned by this function to sqlite3_free().
1749*/
drh5346e952013-05-08 14:14:26 +00001750static sqlite3_index_info *allocateIndexInfo(
1751 Parse *pParse,
1752 WhereClause *pWC,
1753 struct SrcList_item *pSrc,
1754 ExprList *pOrderBy
1755){
danielk19771d461462009-04-21 09:02:45 +00001756 int i, j;
1757 int nTerm;
1758 struct sqlite3_index_constraint *pIdxCons;
1759 struct sqlite3_index_orderby *pIdxOrderBy;
1760 struct sqlite3_index_constraint_usage *pUsage;
1761 WhereTerm *pTerm;
1762 int nOrderBy;
1763 sqlite3_index_info *pIdxInfo;
1764
danielk19771d461462009-04-21 09:02:45 +00001765 /* Count the number of possible WHERE clause constraints referring
1766 ** to this virtual table */
1767 for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
1768 if( pTerm->leftCursor != pSrc->iCursor ) continue;
drh7a5bcc02013-01-16 17:08:58 +00001769 assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
1770 testcase( pTerm->eOperator & WO_IN );
1771 testcase( pTerm->eOperator & WO_ISNULL );
dana4ff8252014-01-20 19:55:33 +00001772 testcase( pTerm->eOperator & WO_ALL );
1773 if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV))==0 ) continue;
drhb4256992011-08-02 01:57:39 +00001774 if( pTerm->wtFlags & TERM_VNULL ) continue;
danielk19771d461462009-04-21 09:02:45 +00001775 nTerm++;
1776 }
1777
1778 /* If the ORDER BY clause contains only columns in the current
1779 ** virtual table then allocate space for the aOrderBy part of
1780 ** the sqlite3_index_info structure.
1781 */
1782 nOrderBy = 0;
1783 if( pOrderBy ){
drh56f1b992012-09-25 14:29:39 +00001784 int n = pOrderBy->nExpr;
1785 for(i=0; i<n; i++){
danielk19771d461462009-04-21 09:02:45 +00001786 Expr *pExpr = pOrderBy->a[i].pExpr;
1787 if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
1788 }
drh56f1b992012-09-25 14:29:39 +00001789 if( i==n){
1790 nOrderBy = n;
danielk19771d461462009-04-21 09:02:45 +00001791 }
1792 }
1793
1794 /* Allocate the sqlite3_index_info structure
1795 */
1796 pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
1797 + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
1798 + sizeof(*pIdxOrderBy)*nOrderBy );
1799 if( pIdxInfo==0 ){
1800 sqlite3ErrorMsg(pParse, "out of memory");
danielk19771d461462009-04-21 09:02:45 +00001801 return 0;
1802 }
1803
1804 /* Initialize the structure. The sqlite3_index_info structure contains
1805 ** many fields that are declared "const" to prevent xBestIndex from
1806 ** changing them. We have to do some funky casting in order to
1807 ** initialize those fields.
1808 */
1809 pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
1810 pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
1811 pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
1812 *(int*)&pIdxInfo->nConstraint = nTerm;
1813 *(int*)&pIdxInfo->nOrderBy = nOrderBy;
1814 *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
1815 *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
1816 *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
1817 pUsage;
1818
1819 for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
drh281bbe22012-10-16 23:17:14 +00001820 u8 op;
danielk19771d461462009-04-21 09:02:45 +00001821 if( pTerm->leftCursor != pSrc->iCursor ) continue;
drh7a5bcc02013-01-16 17:08:58 +00001822 assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
1823 testcase( pTerm->eOperator & WO_IN );
1824 testcase( pTerm->eOperator & WO_ISNULL );
dana4ff8252014-01-20 19:55:33 +00001825 testcase( pTerm->eOperator & WO_ALL );
1826 if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV))==0 ) continue;
drhb4256992011-08-02 01:57:39 +00001827 if( pTerm->wtFlags & TERM_VNULL ) continue;
danielk19771d461462009-04-21 09:02:45 +00001828 pIdxCons[j].iColumn = pTerm->u.leftColumn;
1829 pIdxCons[j].iTermOffset = i;
drh7a5bcc02013-01-16 17:08:58 +00001830 op = (u8)pTerm->eOperator & WO_ALL;
drh281bbe22012-10-16 23:17:14 +00001831 if( op==WO_IN ) op = WO_EQ;
1832 pIdxCons[j].op = op;
danielk19771d461462009-04-21 09:02:45 +00001833 /* The direct assignment in the previous line is possible only because
1834 ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The
1835 ** following asserts verify this fact. */
1836 assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
1837 assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
1838 assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
1839 assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
1840 assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
1841 assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
drh281bbe22012-10-16 23:17:14 +00001842 assert( pTerm->eOperator & (WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
danielk19771d461462009-04-21 09:02:45 +00001843 j++;
1844 }
1845 for(i=0; i<nOrderBy; i++){
1846 Expr *pExpr = pOrderBy->a[i].pExpr;
1847 pIdxOrderBy[i].iColumn = pExpr->iColumn;
1848 pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
1849 }
1850
1851 return pIdxInfo;
1852}
1853
1854/*
1855** The table object reference passed as the second argument to this function
1856** must represent a virtual table. This function invokes the xBestIndex()
drh3b48e8c2013-06-12 20:18:16 +00001857** method of the virtual table with the sqlite3_index_info object that
1858** comes in as the 3rd argument to this function.
danielk19771d461462009-04-21 09:02:45 +00001859**
1860** If an error occurs, pParse is populated with an error message and a
1861** non-zero value is returned. Otherwise, 0 is returned and the output
1862** part of the sqlite3_index_info structure is left populated.
1863**
1864** Whether or not an error is returned, it is the responsibility of the
1865** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
1866** that this is required.
1867*/
1868static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
danielk1977595a5232009-07-24 17:58:53 +00001869 sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
danielk19771d461462009-04-21 09:02:45 +00001870 int i;
1871 int rc;
1872
danielk19771d461462009-04-21 09:02:45 +00001873 TRACE_IDX_INPUTS(p);
1874 rc = pVtab->pModule->xBestIndex(pVtab, p);
1875 TRACE_IDX_OUTPUTS(p);
danielk19771d461462009-04-21 09:02:45 +00001876
1877 if( rc!=SQLITE_OK ){
1878 if( rc==SQLITE_NOMEM ){
1879 pParse->db->mallocFailed = 1;
1880 }else if( !pVtab->zErrMsg ){
1881 sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
1882 }else{
1883 sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
1884 }
1885 }
drhb9755982010-07-24 16:34:37 +00001886 sqlite3_free(pVtab->zErrMsg);
danielk19771d461462009-04-21 09:02:45 +00001887 pVtab->zErrMsg = 0;
1888
1889 for(i=0; i<p->nConstraint; i++){
1890 if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
1891 sqlite3ErrorMsg(pParse,
1892 "table %s: xBestIndex returned an invalid plan", pTab->zName);
1893 }
1894 }
1895
1896 return pParse->nErr;
1897}
drh7ba39a92013-05-30 17:43:19 +00001898#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
danielk19771d461462009-04-21 09:02:45 +00001899
1900
drh1435a9a2013-08-27 23:15:44 +00001901#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drh28c4cf42005-07-27 20:41:43 +00001902/*
drhfaacf172011-08-12 01:51:45 +00001903** Estimate the location of a particular key among all keys in an
1904** index. Store the results in aStat as follows:
drhe847d322011-01-20 02:56:37 +00001905**
drhfaacf172011-08-12 01:51:45 +00001906** aStat[0] Est. number of rows less than pVal
1907** aStat[1] Est. number of rows equal to pVal
dan02fa4692009-08-17 17:06:58 +00001908**
drhfaacf172011-08-12 01:51:45 +00001909** Return SQLITE_OK on success.
dan02fa4692009-08-17 17:06:58 +00001910*/
danb3c02e22013-08-08 19:38:40 +00001911static void whereKeyStats(
dan02fa4692009-08-17 17:06:58 +00001912 Parse *pParse, /* Database connection */
1913 Index *pIdx, /* Index to consider domain of */
dan7a419232013-08-06 20:01:43 +00001914 UnpackedRecord *pRec, /* Vector of values to consider */
drhfaacf172011-08-12 01:51:45 +00001915 int roundUp, /* Round up if true. Round down if false */
1916 tRowcnt *aStat /* OUT: stats written here */
dan02fa4692009-08-17 17:06:58 +00001917){
danf52bb8d2013-08-03 20:24:58 +00001918 IndexSample *aSample = pIdx->aSample;
drhfbc38de2013-09-03 19:26:22 +00001919 int iCol; /* Index of required stats in anEq[] etc. */
dan84c309b2013-08-08 16:17:12 +00001920 int iMin = 0; /* Smallest sample not yet tested */
1921 int i = pIdx->nSample; /* Smallest sample larger than or equal to pRec */
1922 int iTest; /* Next sample to test */
1923 int res; /* Result of comparison operation */
dan02fa4692009-08-17 17:06:58 +00001924
drh4f991892013-10-11 15:05:05 +00001925#ifndef SQLITE_DEBUG
1926 UNUSED_PARAMETER( pParse );
1927#endif
drh7f594752013-12-03 19:49:55 +00001928 assert( pRec!=0 );
drhfbc38de2013-09-03 19:26:22 +00001929 iCol = pRec->nField - 1;
drh5c624862011-09-22 18:46:34 +00001930 assert( pIdx->nSample>0 );
dan8ad169a2013-08-12 20:14:04 +00001931 assert( pRec->nField>0 && iCol<pIdx->nSampleCol );
dan84c309b2013-08-08 16:17:12 +00001932 do{
1933 iTest = (iMin+i)/2;
drh75179de2014-09-16 14:37:35 +00001934 res = sqlite3VdbeRecordCompare(aSample[iTest].n, aSample[iTest].p, pRec);
dan84c309b2013-08-08 16:17:12 +00001935 if( res<0 ){
1936 iMin = iTest+1;
1937 }else{
1938 i = iTest;
dan02fa4692009-08-17 17:06:58 +00001939 }
dan84c309b2013-08-08 16:17:12 +00001940 }while( res && iMin<i );
drh51147ba2005-07-23 22:59:55 +00001941
dan84c309b2013-08-08 16:17:12 +00001942#ifdef SQLITE_DEBUG
1943 /* The following assert statements check that the binary search code
1944 ** above found the right answer. This block serves no purpose other
1945 ** than to invoke the asserts. */
1946 if( res==0 ){
1947 /* If (res==0) is true, then sample $i must be equal to pRec */
1948 assert( i<pIdx->nSample );
drh75179de2014-09-16 14:37:35 +00001949 assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)
drh0e1f0022013-08-16 14:49:00 +00001950 || pParse->db->mallocFailed );
dan02fa4692009-08-17 17:06:58 +00001951 }else{
dan84c309b2013-08-08 16:17:12 +00001952 /* Otherwise, pRec must be smaller than sample $i and larger than
1953 ** sample ($i-1). */
1954 assert( i==pIdx->nSample
drh75179de2014-09-16 14:37:35 +00001955 || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0
drh0e1f0022013-08-16 14:49:00 +00001956 || pParse->db->mallocFailed );
dan84c309b2013-08-08 16:17:12 +00001957 assert( i==0
drh75179de2014-09-16 14:37:35 +00001958 || sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0
drh0e1f0022013-08-16 14:49:00 +00001959 || pParse->db->mallocFailed );
drhfaacf172011-08-12 01:51:45 +00001960 }
dan84c309b2013-08-08 16:17:12 +00001961#endif /* ifdef SQLITE_DEBUG */
dan02fa4692009-08-17 17:06:58 +00001962
drhfaacf172011-08-12 01:51:45 +00001963 /* At this point, aSample[i] is the first sample that is greater than
1964 ** or equal to pVal. Or if i==pIdx->nSample, then all samples are less
dan84c309b2013-08-08 16:17:12 +00001965 ** than pVal. If aSample[i]==pVal, then res==0.
drhfaacf172011-08-12 01:51:45 +00001966 */
dan84c309b2013-08-08 16:17:12 +00001967 if( res==0 ){
daneea568d2013-08-07 19:46:15 +00001968 aStat[0] = aSample[i].anLt[iCol];
1969 aStat[1] = aSample[i].anEq[iCol];
drhfaacf172011-08-12 01:51:45 +00001970 }else{
1971 tRowcnt iLower, iUpper, iGap;
1972 if( i==0 ){
1973 iLower = 0;
daneea568d2013-08-07 19:46:15 +00001974 iUpper = aSample[0].anLt[iCol];
drhfaacf172011-08-12 01:51:45 +00001975 }else{
dancfc9df72014-04-25 15:01:01 +00001976 i64 nRow0 = sqlite3LogEstToInt(pIdx->aiRowLogEst[0]);
1977 iUpper = i>=pIdx->nSample ? nRow0 : aSample[i].anLt[iCol];
daneea568d2013-08-07 19:46:15 +00001978 iLower = aSample[i-1].anEq[iCol] + aSample[i-1].anLt[iCol];
drhfaacf172011-08-12 01:51:45 +00001979 }
dan39caccf2014-07-01 11:54:02 +00001980 aStat[1] = pIdx->aAvgEq[iCol];
drhfaacf172011-08-12 01:51:45 +00001981 if( iLower>=iUpper ){
1982 iGap = 0;
1983 }else{
1984 iGap = iUpper - iLower;
drhfaacf172011-08-12 01:51:45 +00001985 }
1986 if( roundUp ){
1987 iGap = (iGap*2)/3;
1988 }else{
1989 iGap = iGap/3;
1990 }
1991 aStat[0] = iLower + iGap;
dan02fa4692009-08-17 17:06:58 +00001992 }
dan02fa4692009-08-17 17:06:58 +00001993}
drh1435a9a2013-08-27 23:15:44 +00001994#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
dan937d0de2009-10-15 18:35:38 +00001995
1996/*
danaa9933c2014-04-24 20:04:49 +00001997** If it is not NULL, pTerm is a term that provides an upper or lower
1998** bound on a range scan. Without considering pTerm, it is estimated
1999** that the scan will visit nNew rows. This function returns the number
2000** estimated to be visited after taking pTerm into account.
2001**
2002** If the user explicitly specified a likelihood() value for this term,
2003** then the return value is the likelihood multiplied by the number of
2004** input rows. Otherwise, this function assumes that an "IS NOT NULL" term
2005** has a likelihood of 0.50, and any other term a likelihood of 0.25.
2006*/
2007static LogEst whereRangeAdjust(WhereTerm *pTerm, LogEst nNew){
2008 LogEst nRet = nNew;
2009 if( pTerm ){
2010 if( pTerm->truthProb<=0 ){
2011 nRet += pTerm->truthProb;
dan7de2a1f2014-04-28 20:11:20 +00002012 }else if( (pTerm->wtFlags & TERM_VNULL)==0 ){
danaa9933c2014-04-24 20:04:49 +00002013 nRet -= 20; assert( 20==sqlite3LogEst(4) );
2014 }
2015 }
2016 return nRet;
2017}
2018
mistachkin2d84ac42014-06-26 21:32:09 +00002019#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
danb0b82902014-06-26 20:21:46 +00002020/*
2021** This function is called to estimate the number of rows visited by a
2022** range-scan on a skip-scan index. For example:
2023**
2024** CREATE INDEX i1 ON t1(a, b, c);
2025** SELECT * FROM t1 WHERE a=? AND c BETWEEN ? AND ?;
2026**
2027** Value pLoop->nOut is currently set to the estimated number of rows
2028** visited for scanning (a=? AND b=?). This function reduces that estimate
2029** by some factor to account for the (c BETWEEN ? AND ?) expression based
2030** on the stat4 data for the index. this scan will be peformed multiple
2031** times (once for each (a,b) combination that matches a=?) is dealt with
2032** by the caller.
2033**
2034** It does this by scanning through all stat4 samples, comparing values
2035** extracted from pLower and pUpper with the corresponding column in each
2036** sample. If L and U are the number of samples found to be less than or
2037** equal to the values extracted from pLower and pUpper respectively, and
2038** N is the total number of samples, the pLoop->nOut value is adjusted
2039** as follows:
2040**
2041** nOut = nOut * ( min(U - L, 1) / N )
2042**
2043** If pLower is NULL, or a value cannot be extracted from the term, L is
2044** set to zero. If pUpper is NULL, or a value cannot be extracted from it,
2045** U is set to N.
2046**
2047** Normally, this function sets *pbDone to 1 before returning. However,
2048** if no value can be extracted from either pLower or pUpper (and so the
2049** estimate of the number of rows delivered remains unchanged), *pbDone
2050** is left as is.
2051**
2052** If an error occurs, an SQLite error code is returned. Otherwise,
2053** SQLITE_OK.
2054*/
2055static int whereRangeSkipScanEst(
2056 Parse *pParse, /* Parsing & code generating context */
2057 WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
2058 WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
2059 WhereLoop *pLoop, /* Update the .nOut value of this loop */
2060 int *pbDone /* Set to true if at least one expr. value extracted */
2061){
2062 Index *p = pLoop->u.btree.pIndex;
2063 int nEq = pLoop->u.btree.nEq;
2064 sqlite3 *db = pParse->db;
dan4e42ba42014-06-27 20:14:25 +00002065 int nLower = -1;
2066 int nUpper = p->nSample+1;
danb0b82902014-06-26 20:21:46 +00002067 int rc = SQLITE_OK;
drhd15f87e2014-07-24 22:41:20 +00002068 int iCol = p->aiColumn[nEq];
2069 u8 aff = iCol>=0 ? p->pTable->aCol[iCol].affinity : SQLITE_AFF_INTEGER;
danb0b82902014-06-26 20:21:46 +00002070 CollSeq *pColl;
2071
2072 sqlite3_value *p1 = 0; /* Value extracted from pLower */
2073 sqlite3_value *p2 = 0; /* Value extracted from pUpper */
2074 sqlite3_value *pVal = 0; /* Value extracted from record */
2075
2076 pColl = sqlite3LocateCollSeq(pParse, p->azColl[nEq]);
2077 if( pLower ){
2078 rc = sqlite3Stat4ValueFromExpr(pParse, pLower->pExpr->pRight, aff, &p1);
dan4e42ba42014-06-27 20:14:25 +00002079 nLower = 0;
danb0b82902014-06-26 20:21:46 +00002080 }
2081 if( pUpper && rc==SQLITE_OK ){
2082 rc = sqlite3Stat4ValueFromExpr(pParse, pUpper->pExpr->pRight, aff, &p2);
dan4e42ba42014-06-27 20:14:25 +00002083 nUpper = p2 ? 0 : p->nSample;
danb0b82902014-06-26 20:21:46 +00002084 }
2085
2086 if( p1 || p2 ){
2087 int i;
2088 int nDiff;
2089 for(i=0; rc==SQLITE_OK && i<p->nSample; i++){
2090 rc = sqlite3Stat4Column(db, p->aSample[i].p, p->aSample[i].n, nEq, &pVal);
2091 if( rc==SQLITE_OK && p1 ){
2092 int res = sqlite3MemCompare(p1, pVal, pColl);
dan4e42ba42014-06-27 20:14:25 +00002093 if( res>=0 ) nLower++;
danb0b82902014-06-26 20:21:46 +00002094 }
2095 if( rc==SQLITE_OK && p2 ){
2096 int res = sqlite3MemCompare(p2, pVal, pColl);
dan4e42ba42014-06-27 20:14:25 +00002097 if( res>=0 ) nUpper++;
danb0b82902014-06-26 20:21:46 +00002098 }
2099 }
danb0b82902014-06-26 20:21:46 +00002100 nDiff = (nUpper - nLower);
2101 if( nDiff<=0 ) nDiff = 1;
dan4e42ba42014-06-27 20:14:25 +00002102
2103 /* If there is both an upper and lower bound specified, and the
2104 ** comparisons indicate that they are close together, use the fallback
2105 ** method (assume that the scan visits 1/64 of the rows) for estimating
2106 ** the number of rows visited. Otherwise, estimate the number of rows
2107 ** using the method described in the header comment for this function. */
2108 if( nDiff!=1 || pUpper==0 || pLower==0 ){
2109 int nAdjust = (sqlite3LogEst(p->nSample) - sqlite3LogEst(nDiff));
2110 pLoop->nOut -= nAdjust;
2111 *pbDone = 1;
2112 WHERETRACE(0x10, ("range skip-scan regions: %u..%u adjust=%d est=%d\n",
danfa887452014-06-28 15:26:10 +00002113 nLower, nUpper, nAdjust*-1, pLoop->nOut));
dan4e42ba42014-06-27 20:14:25 +00002114 }
2115
danb0b82902014-06-26 20:21:46 +00002116 }else{
2117 assert( *pbDone==0 );
2118 }
2119
2120 sqlite3ValueFree(p1);
2121 sqlite3ValueFree(p2);
2122 sqlite3ValueFree(pVal);
2123
2124 return rc;
2125}
mistachkin2d84ac42014-06-26 21:32:09 +00002126#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
danb0b82902014-06-26 20:21:46 +00002127
danaa9933c2014-04-24 20:04:49 +00002128/*
dan02fa4692009-08-17 17:06:58 +00002129** This function is used to estimate the number of rows that will be visited
2130** by scanning an index for a range of values. The range may have an upper
2131** bound, a lower bound, or both. The WHERE clause terms that set the upper
2132** and lower bounds are represented by pLower and pUpper respectively. For
2133** example, assuming that index p is on t1(a):
2134**
2135** ... FROM t1 WHERE a > ? AND a < ? ...
2136** |_____| |_____|
2137** | |
2138** pLower pUpper
2139**
drh98cdf622009-08-20 18:14:42 +00002140** If either of the upper or lower bound is not present, then NULL is passed in
drhcdaca552009-08-20 13:45:07 +00002141** place of the corresponding WhereTerm.
dan02fa4692009-08-17 17:06:58 +00002142**
dan6cb8d762013-08-08 11:48:57 +00002143** The value in (pBuilder->pNew->u.btree.nEq) is the index of the index
2144** column subject to the range constraint. Or, equivalently, the number of
2145** equality constraints optimized by the proposed index scan. For example,
2146** assuming index p is on t1(a, b), and the SQL query is:
dan02fa4692009-08-17 17:06:58 +00002147**
2148** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
2149**
dan6cb8d762013-08-08 11:48:57 +00002150** then nEq is set to 1 (as the range restricted column, b, is the second
2151** left-most column of the index). Or, if the query is:
dan02fa4692009-08-17 17:06:58 +00002152**
2153** ... FROM t1 WHERE a > ? AND a < ? ...
2154**
dan6cb8d762013-08-08 11:48:57 +00002155** then nEq is set to 0.
dan02fa4692009-08-17 17:06:58 +00002156**
drhbf539c42013-10-05 18:16:02 +00002157** When this function is called, *pnOut is set to the sqlite3LogEst() of the
dan6cb8d762013-08-08 11:48:57 +00002158** number of rows that the index scan is expected to visit without
2159** considering the range constraints. If nEq is 0, this is the number of
2160** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced)
peter.d.reid60ec9142014-09-06 16:39:46 +00002161** to account for the range constraints pLower and pUpper.
dan6cb8d762013-08-08 11:48:57 +00002162**
2163** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be
drh94aa7e02014-06-06 17:09:52 +00002164** used, a single range inequality reduces the search space by a factor of 4.
2165** and a pair of constraints (x>? AND x<?) reduces the expected number of
2166** rows visited by a factor of 64.
dan02fa4692009-08-17 17:06:58 +00002167*/
2168static int whereRangeScanEst(
drhcdaca552009-08-20 13:45:07 +00002169 Parse *pParse, /* Parsing & code generating context */
dan7a419232013-08-06 20:01:43 +00002170 WhereLoopBuilder *pBuilder,
drhcdaca552009-08-20 13:45:07 +00002171 WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
2172 WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
drh186ad8c2013-10-08 18:40:37 +00002173 WhereLoop *pLoop /* Modify the .nOut and maybe .rRun fields */
dan02fa4692009-08-17 17:06:58 +00002174){
dan69188d92009-08-19 08:18:32 +00002175 int rc = SQLITE_OK;
drh186ad8c2013-10-08 18:40:37 +00002176 int nOut = pLoop->nOut;
drhbf539c42013-10-05 18:16:02 +00002177 LogEst nNew;
dan69188d92009-08-19 08:18:32 +00002178
drh1435a9a2013-08-27 23:15:44 +00002179#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drh186ad8c2013-10-08 18:40:37 +00002180 Index *p = pLoop->u.btree.pIndex;
drh4f991892013-10-11 15:05:05 +00002181 int nEq = pLoop->u.btree.nEq;
dan02fa4692009-08-17 17:06:58 +00002182
drh74dade22013-09-04 18:14:53 +00002183 if( p->nSample>0
dan8ad169a2013-08-12 20:14:04 +00002184 && nEq<p->nSampleCol
dan7a419232013-08-06 20:01:43 +00002185 ){
danb0b82902014-06-26 20:21:46 +00002186 if( nEq==pBuilder->nRecValid ){
2187 UnpackedRecord *pRec = pBuilder->pRec;
2188 tRowcnt a[2];
2189 u8 aff;
drh98cdf622009-08-20 18:14:42 +00002190
danb0b82902014-06-26 20:21:46 +00002191 /* Variable iLower will be set to the estimate of the number of rows in
2192 ** the index that are less than the lower bound of the range query. The
2193 ** lower bound being the concatenation of $P and $L, where $P is the
2194 ** key-prefix formed by the nEq values matched against the nEq left-most
2195 ** columns of the index, and $L is the value in pLower.
2196 **
2197 ** Or, if pLower is NULL or $L cannot be extracted from it (because it
2198 ** is not a simple variable or literal value), the lower bound of the
2199 ** range is $P. Due to a quirk in the way whereKeyStats() works, even
2200 ** if $L is available, whereKeyStats() is called for both ($P) and
2201 ** ($P:$L) and the larger of the two returned values used.
2202 **
2203 ** Similarly, iUpper is to be set to the estimate of the number of rows
2204 ** less than the upper bound of the range query. Where the upper bound
2205 ** is either ($P) or ($P:$U). Again, even if $U is available, both values
2206 ** of iUpper are requested of whereKeyStats() and the smaller used.
2207 */
2208 tRowcnt iLower;
2209 tRowcnt iUpper;
danb3c02e22013-08-08 19:38:40 +00002210
drhb34fc5b2014-08-28 17:20:37 +00002211 if( pRec ){
2212 testcase( pRec->nField!=pBuilder->nRecValid );
2213 pRec->nField = pBuilder->nRecValid;
2214 }
danb0b82902014-06-26 20:21:46 +00002215 if( nEq==p->nKeyCol ){
2216 aff = SQLITE_AFF_INTEGER;
dan7a419232013-08-06 20:01:43 +00002217 }else{
danb0b82902014-06-26 20:21:46 +00002218 aff = p->pTable->aCol[p->aiColumn[nEq]].affinity;
drhfaacf172011-08-12 01:51:45 +00002219 }
danb0b82902014-06-26 20:21:46 +00002220 /* Determine iLower and iUpper using ($P) only. */
2221 if( nEq==0 ){
2222 iLower = 0;
drh9f07cf72014-10-22 15:27:05 +00002223 iUpper = p->nRowEst0;
danb0b82902014-06-26 20:21:46 +00002224 }else{
2225 /* Note: this call could be optimized away - since the same values must
2226 ** have been requested when testing key $P in whereEqualScanEst(). */
2227 whereKeyStats(pParse, p, pRec, 0, a);
2228 iLower = a[0];
2229 iUpper = a[0] + a[1];
dan6cb8d762013-08-08 11:48:57 +00002230 }
danb0b82902014-06-26 20:21:46 +00002231
drh69afd992014-10-08 02:53:25 +00002232 assert( pLower==0 || (pLower->eOperator & (WO_GT|WO_GE))!=0 );
2233 assert( pUpper==0 || (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
drh681fca02014-10-10 15:01:46 +00002234 assert( p->aSortOrder!=0 );
2235 if( p->aSortOrder[nEq] ){
drh69afd992014-10-08 02:53:25 +00002236 /* The roles of pLower and pUpper are swapped for a DESC index */
2237 SWAP(WhereTerm*, pLower, pUpper);
2238 }
2239
danb0b82902014-06-26 20:21:46 +00002240 /* If possible, improve on the iLower estimate using ($P:$L). */
2241 if( pLower ){
2242 int bOk; /* True if value is extracted from pExpr */
2243 Expr *pExpr = pLower->pExpr->pRight;
danb0b82902014-06-26 20:21:46 +00002244 rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
2245 if( rc==SQLITE_OK && bOk ){
2246 tRowcnt iNew;
2247 whereKeyStats(pParse, p, pRec, 0, a);
drh69afd992014-10-08 02:53:25 +00002248 iNew = a[0] + ((pLower->eOperator & (WO_GT|WO_LE)) ? a[1] : 0);
danb0b82902014-06-26 20:21:46 +00002249 if( iNew>iLower ) iLower = iNew;
2250 nOut--;
danf741e042014-08-25 18:29:38 +00002251 pLower = 0;
danb0b82902014-06-26 20:21:46 +00002252 }
2253 }
2254
2255 /* If possible, improve on the iUpper estimate using ($P:$U). */
2256 if( pUpper ){
2257 int bOk; /* True if value is extracted from pExpr */
2258 Expr *pExpr = pUpper->pExpr->pRight;
danb0b82902014-06-26 20:21:46 +00002259 rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
2260 if( rc==SQLITE_OK && bOk ){
2261 tRowcnt iNew;
2262 whereKeyStats(pParse, p, pRec, 1, a);
drh69afd992014-10-08 02:53:25 +00002263 iNew = a[0] + ((pUpper->eOperator & (WO_GT|WO_LE)) ? a[1] : 0);
danb0b82902014-06-26 20:21:46 +00002264 if( iNew<iUpper ) iUpper = iNew;
2265 nOut--;
danf741e042014-08-25 18:29:38 +00002266 pUpper = 0;
danb0b82902014-06-26 20:21:46 +00002267 }
2268 }
2269
2270 pBuilder->pRec = pRec;
2271 if( rc==SQLITE_OK ){
2272 if( iUpper>iLower ){
2273 nNew = sqlite3LogEst(iUpper - iLower);
2274 }else{
2275 nNew = 10; assert( 10==sqlite3LogEst(2) );
2276 }
2277 if( nNew<nOut ){
2278 nOut = nNew;
2279 }
drhae914d72014-08-28 19:38:22 +00002280 WHERETRACE(0x10, ("STAT4 range scan: %u..%u est=%d\n",
danb0b82902014-06-26 20:21:46 +00002281 (u32)iLower, (u32)iUpper, nOut));
danb0b82902014-06-26 20:21:46 +00002282 }
2283 }else{
2284 int bDone = 0;
2285 rc = whereRangeSkipScanEst(pParse, pLower, pUpper, pLoop, &bDone);
2286 if( bDone ) return rc;
drh98cdf622009-08-20 18:14:42 +00002287 }
dan02fa4692009-08-17 17:06:58 +00002288 }
drh3f022182009-09-09 16:10:50 +00002289#else
2290 UNUSED_PARAMETER(pParse);
dan7a419232013-08-06 20:01:43 +00002291 UNUSED_PARAMETER(pBuilder);
dan02fa4692009-08-17 17:06:58 +00002292 assert( pLower || pUpper );
danf741e042014-08-25 18:29:38 +00002293#endif
dan7de2a1f2014-04-28 20:11:20 +00002294 assert( pUpper==0 || (pUpper->wtFlags & TERM_VNULL)==0 );
danaa9933c2014-04-24 20:04:49 +00002295 nNew = whereRangeAdjust(pLower, nOut);
2296 nNew = whereRangeAdjust(pUpper, nNew);
dan7de2a1f2014-04-28 20:11:20 +00002297
drh4dd96a82014-10-24 15:26:29 +00002298 /* TUNING: If there is both an upper and lower limit and neither limit
2299 ** has an application-defined likelihood(), assume the range is
dan42685f22014-04-28 19:34:06 +00002300 ** reduced by an additional 75%. This means that, by default, an open-ended
2301 ** range query (e.g. col > ?) is assumed to match 1/4 of the rows in the
2302 ** index. While a closed range (e.g. col BETWEEN ? AND ?) is estimated to
2303 ** match 1/64 of the index. */
drh4dd96a82014-10-24 15:26:29 +00002304 if( pLower && pLower->truthProb>0 && pUpper && pUpper->truthProb>0 ){
2305 nNew -= 20;
2306 }
dan7de2a1f2014-04-28 20:11:20 +00002307
danaa9933c2014-04-24 20:04:49 +00002308 nOut -= (pLower!=0) + (pUpper!=0);
drhabfa6d52013-09-11 03:53:22 +00002309 if( nNew<10 ) nNew = 10;
2310 if( nNew<nOut ) nOut = nNew;
drhae914d72014-08-28 19:38:22 +00002311#if defined(WHERETRACE_ENABLED)
2312 if( pLoop->nOut>nOut ){
2313 WHERETRACE(0x10,("Range scan lowers nOut from %d to %d\n",
2314 pLoop->nOut, nOut));
2315 }
2316#endif
drh186ad8c2013-10-08 18:40:37 +00002317 pLoop->nOut = (LogEst)nOut;
dan02fa4692009-08-17 17:06:58 +00002318 return rc;
2319}
2320
drh1435a9a2013-08-27 23:15:44 +00002321#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drh82759752011-01-20 16:52:09 +00002322/*
2323** Estimate the number of rows that will be returned based on
2324** an equality constraint x=VALUE and where that VALUE occurs in
2325** the histogram data. This only works when x is the left-most
drhfaacf172011-08-12 01:51:45 +00002326** column of an index and sqlite_stat3 histogram data is available
drhac8eb112011-03-17 01:58:21 +00002327** for that index. When pExpr==NULL that means the constraint is
2328** "x IS NULL" instead of "x=VALUE".
drh82759752011-01-20 16:52:09 +00002329**
drh0c50fa02011-01-21 16:27:18 +00002330** Write the estimated row count into *pnRow and return SQLITE_OK.
2331** If unable to make an estimate, leave *pnRow unchanged and return
2332** non-zero.
drh9b3eb0a2011-01-21 14:37:04 +00002333**
2334** This routine can fail if it is unable to load a collating sequence
2335** required for string comparison, or if unable to allocate memory
2336** for a UTF conversion required for comparison. The error is stored
2337** in the pParse structure.
drh82759752011-01-20 16:52:09 +00002338*/
drh041e09f2011-04-07 19:56:21 +00002339static int whereEqualScanEst(
drh82759752011-01-20 16:52:09 +00002340 Parse *pParse, /* Parsing & code generating context */
dan7a419232013-08-06 20:01:43 +00002341 WhereLoopBuilder *pBuilder,
drh0c50fa02011-01-21 16:27:18 +00002342 Expr *pExpr, /* Expression for VALUE in the x=VALUE constraint */
drhb8a8e8a2013-06-10 19:12:39 +00002343 tRowcnt *pnRow /* Write the revised row estimate here */
drh82759752011-01-20 16:52:09 +00002344){
dan7a419232013-08-06 20:01:43 +00002345 Index *p = pBuilder->pNew->u.btree.pIndex;
2346 int nEq = pBuilder->pNew->u.btree.nEq;
2347 UnpackedRecord *pRec = pBuilder->pRec;
drh82759752011-01-20 16:52:09 +00002348 u8 aff; /* Column affinity */
2349 int rc; /* Subfunction return code */
drhfaacf172011-08-12 01:51:45 +00002350 tRowcnt a[2]; /* Statistics */
dan7a419232013-08-06 20:01:43 +00002351 int bOk;
drh82759752011-01-20 16:52:09 +00002352
dan7a419232013-08-06 20:01:43 +00002353 assert( nEq>=1 );
danfd984b82014-06-30 18:02:20 +00002354 assert( nEq<=p->nColumn );
drh82759752011-01-20 16:52:09 +00002355 assert( p->aSample!=0 );
drh5c624862011-09-22 18:46:34 +00002356 assert( p->nSample>0 );
dan7a419232013-08-06 20:01:43 +00002357 assert( pBuilder->nRecValid<nEq );
2358
2359 /* If values are not available for all fields of the index to the left
2360 ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */
2361 if( pBuilder->nRecValid<(nEq-1) ){
2362 return SQLITE_NOTFOUND;
drh1f9c7662011-03-17 01:34:26 +00002363 }
dan7a419232013-08-06 20:01:43 +00002364
dandd6e1f12013-08-10 19:08:30 +00002365 /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue()
2366 ** below would return the same value. */
danfd984b82014-06-30 18:02:20 +00002367 if( nEq>=p->nColumn ){
dan7a419232013-08-06 20:01:43 +00002368 *pnRow = 1;
2369 return SQLITE_OK;
drh82759752011-01-20 16:52:09 +00002370 }
dan7a419232013-08-06 20:01:43 +00002371
daneea568d2013-08-07 19:46:15 +00002372 aff = p->pTable->aCol[p->aiColumn[nEq-1]].affinity;
dan87cd9322013-08-07 15:52:41 +00002373 rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq-1, &bOk);
2374 pBuilder->pRec = pRec;
dan7a419232013-08-06 20:01:43 +00002375 if( rc!=SQLITE_OK ) return rc;
2376 if( bOk==0 ) return SQLITE_NOTFOUND;
dan7a419232013-08-06 20:01:43 +00002377 pBuilder->nRecValid = nEq;
dan7a419232013-08-06 20:01:43 +00002378
danb3c02e22013-08-08 19:38:40 +00002379 whereKeyStats(pParse, p, pRec, 0, a);
drh989578e2013-10-28 14:34:35 +00002380 WHERETRACE(0x10,("equality scan regions: %d\n", (int)a[1]));
danb3c02e22013-08-08 19:38:40 +00002381 *pnRow = a[1];
daneea568d2013-08-07 19:46:15 +00002382
drh0c50fa02011-01-21 16:27:18 +00002383 return rc;
2384}
drh1435a9a2013-08-27 23:15:44 +00002385#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
drh0c50fa02011-01-21 16:27:18 +00002386
drh1435a9a2013-08-27 23:15:44 +00002387#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drh0c50fa02011-01-21 16:27:18 +00002388/*
2389** Estimate the number of rows that will be returned based on
drh5ac06072011-01-21 18:18:13 +00002390** an IN constraint where the right-hand side of the IN operator
2391** is a list of values. Example:
2392**
2393** WHERE x IN (1,2,3,4)
drh0c50fa02011-01-21 16:27:18 +00002394**
2395** Write the estimated row count into *pnRow and return SQLITE_OK.
2396** If unable to make an estimate, leave *pnRow unchanged and return
2397** non-zero.
2398**
2399** This routine can fail if it is unable to load a collating sequence
2400** required for string comparison, or if unable to allocate memory
2401** for a UTF conversion required for comparison. The error is stored
2402** in the pParse structure.
2403*/
drh041e09f2011-04-07 19:56:21 +00002404static int whereInScanEst(
drh0c50fa02011-01-21 16:27:18 +00002405 Parse *pParse, /* Parsing & code generating context */
dan7a419232013-08-06 20:01:43 +00002406 WhereLoopBuilder *pBuilder,
drh0c50fa02011-01-21 16:27:18 +00002407 ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
drhb8a8e8a2013-06-10 19:12:39 +00002408 tRowcnt *pnRow /* Write the revised row estimate here */
drh0c50fa02011-01-21 16:27:18 +00002409){
dan7a419232013-08-06 20:01:43 +00002410 Index *p = pBuilder->pNew->u.btree.pIndex;
dancfc9df72014-04-25 15:01:01 +00002411 i64 nRow0 = sqlite3LogEstToInt(p->aiRowLogEst[0]);
dan7a419232013-08-06 20:01:43 +00002412 int nRecValid = pBuilder->nRecValid;
drhb8a8e8a2013-06-10 19:12:39 +00002413 int rc = SQLITE_OK; /* Subfunction return code */
2414 tRowcnt nEst; /* Number of rows for a single term */
2415 tRowcnt nRowEst = 0; /* New estimate of the number of rows */
2416 int i; /* Loop counter */
drh0c50fa02011-01-21 16:27:18 +00002417
2418 assert( p->aSample!=0 );
drhfaacf172011-08-12 01:51:45 +00002419 for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
dancfc9df72014-04-25 15:01:01 +00002420 nEst = nRow0;
dan7a419232013-08-06 20:01:43 +00002421 rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst);
drhfaacf172011-08-12 01:51:45 +00002422 nRowEst += nEst;
dan7a419232013-08-06 20:01:43 +00002423 pBuilder->nRecValid = nRecValid;
drh0c50fa02011-01-21 16:27:18 +00002424 }
dan7a419232013-08-06 20:01:43 +00002425
drh0c50fa02011-01-21 16:27:18 +00002426 if( rc==SQLITE_OK ){
dancfc9df72014-04-25 15:01:01 +00002427 if( nRowEst > nRow0 ) nRowEst = nRow0;
drh0c50fa02011-01-21 16:27:18 +00002428 *pnRow = nRowEst;
drh5418b122014-08-28 13:42:13 +00002429 WHERETRACE(0x10,("IN row estimate: est=%d\n", nRowEst));
drh0c50fa02011-01-21 16:27:18 +00002430 }
dan7a419232013-08-06 20:01:43 +00002431 assert( pBuilder->nRecValid==nRecValid );
drh0c50fa02011-01-21 16:27:18 +00002432 return rc;
drh82759752011-01-20 16:52:09 +00002433}
drh1435a9a2013-08-27 23:15:44 +00002434#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
drh82759752011-01-20 16:52:09 +00002435
drh46c35f92012-09-26 23:17:01 +00002436/*
drh2ffb1182004-07-19 19:14:01 +00002437** Disable a term in the WHERE clause. Except, do not disable the term
2438** if it controls a LEFT OUTER JOIN and it did not originate in the ON
2439** or USING clause of that join.
2440**
2441** Consider the term t2.z='ok' in the following queries:
2442**
2443** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
2444** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
2445** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
2446**
drh23bf66d2004-12-14 03:34:34 +00002447** The t2.z='ok' is disabled in the in (2) because it originates
drh2ffb1182004-07-19 19:14:01 +00002448** in the ON clause. The term is disabled in (3) because it is not part
2449** of a LEFT OUTER JOIN. In (1), the term is not disabled.
2450**
2451** Disabling a term causes that term to not be tested in the inner loop
drhb6fb62d2005-09-20 08:47:20 +00002452** of the join. Disabling is an optimization. When terms are satisfied
2453** by indices, we disable them to prevent redundant tests in the inner
2454** loop. We would get the correct results if nothing were ever disabled,
2455** but joins might run a little slower. The trick is to disable as much
2456** as we can without disabling too much. If we disabled in (1), we'd get
2457** the wrong answer. See ticket #813.
drh2ffb1182004-07-19 19:14:01 +00002458*/
drh0fcef5e2005-07-19 17:38:22 +00002459static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
2460 if( pTerm
drhbe837bd2010-04-30 21:03:24 +00002461 && (pTerm->wtFlags & TERM_CODED)==0
drh0fcef5e2005-07-19 17:38:22 +00002462 && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
drh0259bc32013-09-09 19:37:46 +00002463 && (pLevel->notReady & pTerm->prereqAll)==0
drh0fcef5e2005-07-19 17:38:22 +00002464 ){
drh165be382008-12-05 02:36:33 +00002465 pTerm->wtFlags |= TERM_CODED;
drh45b1ee42005-08-02 17:48:22 +00002466 if( pTerm->iParent>=0 ){
2467 WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
2468 if( (--pOther->nChild)==0 ){
drhed378002005-07-28 23:12:08 +00002469 disableTerm(pLevel, pOther);
2470 }
drh0fcef5e2005-07-19 17:38:22 +00002471 }
drh2ffb1182004-07-19 19:14:01 +00002472 }
2473}
2474
2475/*
dan69f8bb92009-08-13 19:21:16 +00002476** Code an OP_Affinity opcode to apply the column affinity string zAff
2477** to the n registers starting at base.
2478**
drh039fc322009-11-17 18:31:47 +00002479** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
2480** beginning and end of zAff are ignored. If all entries in zAff are
2481** SQLITE_AFF_NONE, then no code gets generated.
2482**
2483** This routine makes its own copy of zAff so that the caller is free
2484** to modify zAff after this routine returns.
drh94a11212004-09-25 13:12:14 +00002485*/
dan69f8bb92009-08-13 19:21:16 +00002486static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
2487 Vdbe *v = pParse->pVdbe;
drh039fc322009-11-17 18:31:47 +00002488 if( zAff==0 ){
2489 assert( pParse->db->mallocFailed );
2490 return;
2491 }
dan69f8bb92009-08-13 19:21:16 +00002492 assert( v!=0 );
drh039fc322009-11-17 18:31:47 +00002493
2494 /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
2495 ** and end of the affinity string.
2496 */
2497 while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
2498 n--;
2499 base++;
2500 zAff++;
2501 }
2502 while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
2503 n--;
2504 }
2505
2506 /* Code the OP_Affinity opcode if there is anything left to do. */
2507 if( n>0 ){
2508 sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
2509 sqlite3VdbeChangeP4(v, -1, zAff, n);
2510 sqlite3ExprCacheAffinityChange(pParse, base, n);
2511 }
drh94a11212004-09-25 13:12:14 +00002512}
2513
drhe8b97272005-07-19 22:22:12 +00002514
2515/*
drh51147ba2005-07-23 22:59:55 +00002516** Generate code for a single equality term of the WHERE clause. An equality
2517** term can be either X=expr or X IN (...). pTerm is the term to be
2518** coded.
2519**
drh1db639c2008-01-17 02:36:28 +00002520** The current value for the constraint is left in register iReg.
drh51147ba2005-07-23 22:59:55 +00002521**
2522** For a constraint of the form X=expr, the expression is evaluated and its
2523** result is left on the stack. For constraints of the form X IN (...)
2524** this routine sets up a loop that will iterate over all values of X.
drh94a11212004-09-25 13:12:14 +00002525*/
drh678ccce2008-03-31 18:19:54 +00002526static int codeEqualityTerm(
drh94a11212004-09-25 13:12:14 +00002527 Parse *pParse, /* The parsing context */
drhe23399f2005-07-22 00:31:39 +00002528 WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
drh0fe456b2013-03-12 18:34:50 +00002529 WhereLevel *pLevel, /* The level of the FROM clause we are working on */
2530 int iEq, /* Index of the equality term within this level */
drh7ba39a92013-05-30 17:43:19 +00002531 int bRev, /* True for reverse-order IN operations */
drh678ccce2008-03-31 18:19:54 +00002532 int iTarget /* Attempt to leave results in this register */
drh94a11212004-09-25 13:12:14 +00002533){
drh0fcef5e2005-07-19 17:38:22 +00002534 Expr *pX = pTerm->pExpr;
drh50b39962006-10-28 00:28:09 +00002535 Vdbe *v = pParse->pVdbe;
drh678ccce2008-03-31 18:19:54 +00002536 int iReg; /* Register holding results */
drh1db639c2008-01-17 02:36:28 +00002537
danielk19772d605492008-10-01 08:43:03 +00002538 assert( iTarget>0 );
drh50b39962006-10-28 00:28:09 +00002539 if( pX->op==TK_EQ ){
drh678ccce2008-03-31 18:19:54 +00002540 iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
drh50b39962006-10-28 00:28:09 +00002541 }else if( pX->op==TK_ISNULL ){
drh678ccce2008-03-31 18:19:54 +00002542 iReg = iTarget;
drh1db639c2008-01-17 02:36:28 +00002543 sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
danielk1977b3bce662005-01-29 08:32:43 +00002544#ifndef SQLITE_OMIT_SUBQUERY
drh94a11212004-09-25 13:12:14 +00002545 }else{
danielk19779a96b662007-11-29 17:05:18 +00002546 int eType;
danielk1977b3bce662005-01-29 08:32:43 +00002547 int iTab;
drh72e8fa42007-03-28 14:30:06 +00002548 struct InLoop *pIn;
drh7ba39a92013-05-30 17:43:19 +00002549 WhereLoop *pLoop = pLevel->pWLoop;
danielk1977b3bce662005-01-29 08:32:43 +00002550
drh7ba39a92013-05-30 17:43:19 +00002551 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
2552 && pLoop->u.btree.pIndex!=0
2553 && pLoop->u.btree.pIndex->aSortOrder[iEq]
drhd3832162013-03-12 18:49:25 +00002554 ){
drh725e1ae2013-03-12 23:58:42 +00002555 testcase( iEq==0 );
drh725e1ae2013-03-12 23:58:42 +00002556 testcase( bRev );
drh1ccce442013-03-12 20:38:51 +00002557 bRev = !bRev;
drh0fe456b2013-03-12 18:34:50 +00002558 }
drh50b39962006-10-28 00:28:09 +00002559 assert( pX->op==TK_IN );
drh678ccce2008-03-31 18:19:54 +00002560 iReg = iTarget;
drh3a856252014-08-01 14:46:57 +00002561 eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0);
drh725e1ae2013-03-12 23:58:42 +00002562 if( eType==IN_INDEX_INDEX_DESC ){
2563 testcase( bRev );
2564 bRev = !bRev;
2565 }
danielk1977b3bce662005-01-29 08:32:43 +00002566 iTab = pX->iTable;
drh7d176102014-02-18 03:07:12 +00002567 sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
2568 VdbeCoverageIf(v, bRev);
2569 VdbeCoverageIf(v, !bRev);
drh6fa978d2013-05-30 19:29:19 +00002570 assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
2571 pLoop->wsFlags |= WHERE_IN_ABLE;
drh111a6a72008-12-21 03:51:16 +00002572 if( pLevel->u.in.nIn==0 ){
drhb3190c12008-12-08 21:37:14 +00002573 pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
drh72e8fa42007-03-28 14:30:06 +00002574 }
drh111a6a72008-12-21 03:51:16 +00002575 pLevel->u.in.nIn++;
2576 pLevel->u.in.aInLoop =
2577 sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
2578 sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
2579 pIn = pLevel->u.in.aInLoop;
drh72e8fa42007-03-28 14:30:06 +00002580 if( pIn ){
drh111a6a72008-12-21 03:51:16 +00002581 pIn += pLevel->u.in.nIn - 1;
drh72e8fa42007-03-28 14:30:06 +00002582 pIn->iCur = iTab;
drh1db639c2008-01-17 02:36:28 +00002583 if( eType==IN_INDEX_ROWID ){
drhb3190c12008-12-08 21:37:14 +00002584 pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
drh1db639c2008-01-17 02:36:28 +00002585 }else{
drhb3190c12008-12-08 21:37:14 +00002586 pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
drh1db639c2008-01-17 02:36:28 +00002587 }
drhf93cd942013-11-21 03:12:25 +00002588 pIn->eEndLoopOp = bRev ? OP_PrevIfOpen : OP_NextIfOpen;
drh688852a2014-02-17 22:40:43 +00002589 sqlite3VdbeAddOp1(v, OP_IsNull, iReg); VdbeCoverage(v);
drha6110402005-07-28 20:51:19 +00002590 }else{
drh111a6a72008-12-21 03:51:16 +00002591 pLevel->u.in.nIn = 0;
drhe23399f2005-07-22 00:31:39 +00002592 }
danielk1977b3bce662005-01-29 08:32:43 +00002593#endif
drh94a11212004-09-25 13:12:14 +00002594 }
drh0fcef5e2005-07-19 17:38:22 +00002595 disableTerm(pLevel, pTerm);
drh678ccce2008-03-31 18:19:54 +00002596 return iReg;
drh94a11212004-09-25 13:12:14 +00002597}
2598
drh51147ba2005-07-23 22:59:55 +00002599/*
2600** Generate code that will evaluate all == and IN constraints for an
drhcd8629e2013-11-13 12:27:25 +00002601** index scan.
drh51147ba2005-07-23 22:59:55 +00002602**
2603** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
2604** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
2605** The index has as many as three equality constraints, but in this
2606** example, the third "c" value is an inequality. So only two
2607** constraints are coded. This routine will generate code to evaluate
drh6df2acd2008-12-28 16:55:25 +00002608** a==5 and b IN (1,2,3). The current values for a and b will be stored
2609** in consecutive registers and the index of the first register is returned.
drh51147ba2005-07-23 22:59:55 +00002610**
2611** In the example above nEq==2. But this subroutine works for any value
2612** of nEq including 0. If nEq==0, this routine is nearly a no-op.
drh039fc322009-11-17 18:31:47 +00002613** The only thing it does is allocate the pLevel->iMem memory cell and
2614** compute the affinity string.
drh51147ba2005-07-23 22:59:55 +00002615**
drhcd8629e2013-11-13 12:27:25 +00002616** The nExtraReg parameter is 0 or 1. It is 0 if all WHERE clause constraints
2617** are == or IN and are covered by the nEq. nExtraReg is 1 if there is
2618** an inequality constraint (such as the "c>=5 AND c<10" in the example) that
2619** occurs after the nEq quality constraints.
2620**
2621** This routine allocates a range of nEq+nExtraReg memory cells and returns
2622** the index of the first memory cell in that range. The code that
2623** calls this routine will use that memory range to store keys for
2624** start and termination conditions of the loop.
drh51147ba2005-07-23 22:59:55 +00002625** key value of the loop. If one or more IN operators appear, then
2626** this routine allocates an additional nEq memory cells for internal
2627** use.
dan69f8bb92009-08-13 19:21:16 +00002628**
2629** Before returning, *pzAff is set to point to a buffer containing a
2630** copy of the column affinity string of the index allocated using
2631** sqlite3DbMalloc(). Except, entries in the copy of the string associated
2632** with equality constraints that use NONE affinity are set to
2633** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
2634**
2635** CREATE TABLE t1(a TEXT PRIMARY KEY, b);
2636** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
2637**
2638** In the example above, the index on t1(a) has TEXT affinity. But since
2639** the right hand side of the equality constraint (t2.b) has NONE affinity,
2640** no conversion should be attempted before using a t2.b value as part of
2641** a key to search the index. Hence the first byte in the returned affinity
2642** string in this example would be set to SQLITE_AFF_NONE.
drh51147ba2005-07-23 22:59:55 +00002643*/
drh1db639c2008-01-17 02:36:28 +00002644static int codeAllEqualityTerms(
drh51147ba2005-07-23 22:59:55 +00002645 Parse *pParse, /* Parsing context */
2646 WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
drh7ba39a92013-05-30 17:43:19 +00002647 int bRev, /* Reverse the order of IN operators */
dan69f8bb92009-08-13 19:21:16 +00002648 int nExtraReg, /* Number of extra registers to allocate */
2649 char **pzAff /* OUT: Set to point to affinity string */
drh51147ba2005-07-23 22:59:55 +00002650){
drhcd8629e2013-11-13 12:27:25 +00002651 u16 nEq; /* The number of == or IN constraints to code */
2652 u16 nSkip; /* Number of left-most columns to skip */
drh111a6a72008-12-21 03:51:16 +00002653 Vdbe *v = pParse->pVdbe; /* The vm under construction */
2654 Index *pIdx; /* The index being used for this loop */
drh51147ba2005-07-23 22:59:55 +00002655 WhereTerm *pTerm; /* A single constraint term */
drh7ba39a92013-05-30 17:43:19 +00002656 WhereLoop *pLoop; /* The WhereLoop object */
drh51147ba2005-07-23 22:59:55 +00002657 int j; /* Loop counter */
drh1db639c2008-01-17 02:36:28 +00002658 int regBase; /* Base register */
drh6df2acd2008-12-28 16:55:25 +00002659 int nReg; /* Number of registers to allocate */
dan69f8bb92009-08-13 19:21:16 +00002660 char *zAff; /* Affinity string to return */
drh51147ba2005-07-23 22:59:55 +00002661
drh111a6a72008-12-21 03:51:16 +00002662 /* This module is only called on query plans that use an index. */
drh7ba39a92013-05-30 17:43:19 +00002663 pLoop = pLevel->pWLoop;
2664 assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
2665 nEq = pLoop->u.btree.nEq;
drhc8bbce12014-10-21 01:05:09 +00002666 nSkip = pLoop->nSkip;
drh7ba39a92013-05-30 17:43:19 +00002667 pIdx = pLoop->u.btree.pIndex;
2668 assert( pIdx!=0 );
drh111a6a72008-12-21 03:51:16 +00002669
drh51147ba2005-07-23 22:59:55 +00002670 /* Figure out how many memory cells we will need then allocate them.
drh51147ba2005-07-23 22:59:55 +00002671 */
drh700a2262008-12-17 19:22:15 +00002672 regBase = pParse->nMem + 1;
drh7ba39a92013-05-30 17:43:19 +00002673 nReg = pLoop->u.btree.nEq + nExtraReg;
drh6df2acd2008-12-28 16:55:25 +00002674 pParse->nMem += nReg;
drh51147ba2005-07-23 22:59:55 +00002675
dan69f8bb92009-08-13 19:21:16 +00002676 zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
2677 if( !zAff ){
2678 pParse->db->mallocFailed = 1;
2679 }
2680
drhcd8629e2013-11-13 12:27:25 +00002681 if( nSkip ){
2682 int iIdxCur = pLevel->iIdxCur;
drh7d176102014-02-18 03:07:12 +00002683 sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur);
2684 VdbeCoverageIf(v, bRev==0);
2685 VdbeCoverageIf(v, bRev!=0);
drhe084f402013-11-13 17:24:38 +00002686 VdbeComment((v, "begin skip-scan on %s", pIdx->zName));
drh2e5ef4e2013-11-13 16:58:54 +00002687 j = sqlite3VdbeAddOp0(v, OP_Goto);
drh4a1d3652014-02-14 15:13:36 +00002688 pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT),
drh7d176102014-02-18 03:07:12 +00002689 iIdxCur, 0, regBase, nSkip);
2690 VdbeCoverageIf(v, bRev==0);
2691 VdbeCoverageIf(v, bRev!=0);
drh2e5ef4e2013-11-13 16:58:54 +00002692 sqlite3VdbeJumpHere(v, j);
drhcd8629e2013-11-13 12:27:25 +00002693 for(j=0; j<nSkip; j++){
2694 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, j, regBase+j);
2695 assert( pIdx->aiColumn[j]>=0 );
2696 VdbeComment((v, "%s", pIdx->pTable->aCol[pIdx->aiColumn[j]].zName));
2697 }
2698 }
2699
drh51147ba2005-07-23 22:59:55 +00002700 /* Evaluate the equality constraints
2701 */
mistachkinf6418892013-08-28 01:54:12 +00002702 assert( zAff==0 || (int)strlen(zAff)>=nEq );
drhcd8629e2013-11-13 12:27:25 +00002703 for(j=nSkip; j<nEq; j++){
drh678ccce2008-03-31 18:19:54 +00002704 int r1;
drh4efc9292013-06-06 23:02:03 +00002705 pTerm = pLoop->aLTerm[j];
drh7ba39a92013-05-30 17:43:19 +00002706 assert( pTerm!=0 );
drhcd8629e2013-11-13 12:27:25 +00002707 /* The following testcase is true for indices with redundant columns.
drhbe837bd2010-04-30 21:03:24 +00002708 ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
2709 testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
drh39759742013-08-02 23:40:45 +00002710 testcase( pTerm->wtFlags & TERM_VIRTUAL );
drh7ba39a92013-05-30 17:43:19 +00002711 r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
drh678ccce2008-03-31 18:19:54 +00002712 if( r1!=regBase+j ){
drh6df2acd2008-12-28 16:55:25 +00002713 if( nReg==1 ){
2714 sqlite3ReleaseTempReg(pParse, regBase);
2715 regBase = r1;
2716 }else{
2717 sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
2718 }
drh678ccce2008-03-31 18:19:54 +00002719 }
drh981642f2008-04-19 14:40:43 +00002720 testcase( pTerm->eOperator & WO_ISNULL );
2721 testcase( pTerm->eOperator & WO_IN );
drh72e8fa42007-03-28 14:30:06 +00002722 if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
drh039fc322009-11-17 18:31:47 +00002723 Expr *pRight = pTerm->pExpr->pRight;
drh7d176102014-02-18 03:07:12 +00002724 if( sqlite3ExprCanBeNull(pRight) ){
2725 sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk);
2726 VdbeCoverage(v);
2727 }
drh039fc322009-11-17 18:31:47 +00002728 if( zAff ){
2729 if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
2730 zAff[j] = SQLITE_AFF_NONE;
2731 }
2732 if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
2733 zAff[j] = SQLITE_AFF_NONE;
2734 }
dan69f8bb92009-08-13 19:21:16 +00002735 }
drh51147ba2005-07-23 22:59:55 +00002736 }
2737 }
dan69f8bb92009-08-13 19:21:16 +00002738 *pzAff = zAff;
drh1db639c2008-01-17 02:36:28 +00002739 return regBase;
drh51147ba2005-07-23 22:59:55 +00002740}
2741
dan2ce22452010-11-08 19:01:16 +00002742#ifndef SQLITE_OMIT_EXPLAIN
dan17c0bc02010-11-09 17:35:19 +00002743/*
drh69174c42010-11-12 15:35:59 +00002744** This routine is a helper for explainIndexRange() below
2745**
2746** pStr holds the text of an expression that we are building up one term
2747** at a time. This routine adds a new term to the end of the expression.
2748** Terms are separated by AND so add the "AND" text for second and subsequent
2749** terms only.
2750*/
2751static void explainAppendTerm(
2752 StrAccum *pStr, /* The text expression being built */
2753 int iTerm, /* Index of this term. First is zero */
2754 const char *zColumn, /* Name of the column */
2755 const char *zOp /* Name of the operator */
2756){
2757 if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
drha6353a32013-12-09 19:03:26 +00002758 sqlite3StrAccumAppendAll(pStr, zColumn);
drh69174c42010-11-12 15:35:59 +00002759 sqlite3StrAccumAppend(pStr, zOp, 1);
2760 sqlite3StrAccumAppend(pStr, "?", 1);
2761}
2762
2763/*
dan17c0bc02010-11-09 17:35:19 +00002764** Argument pLevel describes a strategy for scanning table pTab. This
drh6c977892014-10-10 15:47:46 +00002765** function appends text to pStr that describes the subset of table
2766** rows scanned by the strategy in the form of an SQL expression.
dan17c0bc02010-11-09 17:35:19 +00002767**
2768** For example, if the query:
2769**
2770** SELECT * FROM t1 WHERE a=1 AND b>2;
2771**
2772** is run and there is an index on (a, b), then this function returns a
2773** string similar to:
2774**
2775** "a=? AND b>?"
dan17c0bc02010-11-09 17:35:19 +00002776*/
drh1f8817c2014-10-10 19:15:35 +00002777static void explainIndexRange(StrAccum *pStr, WhereLoop *pLoop, Table *pTab){
drhef866372013-05-22 20:49:02 +00002778 Index *pIndex = pLoop->u.btree.pIndex;
drhcd8629e2013-11-13 12:27:25 +00002779 u16 nEq = pLoop->u.btree.nEq;
drhc8bbce12014-10-21 01:05:09 +00002780 u16 nSkip = pLoop->nSkip;
drh69174c42010-11-12 15:35:59 +00002781 int i, j;
2782 Column *aCol = pTab->aCol;
drhbbbdc832013-10-22 18:01:40 +00002783 i16 *aiColumn = pIndex->aiColumn;
dan2ce22452010-11-08 19:01:16 +00002784
drh6c977892014-10-10 15:47:46 +00002785 if( nEq==0 && (pLoop->wsFlags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ) return;
2786 sqlite3StrAccumAppend(pStr, " (", 2);
dan2ce22452010-11-08 19:01:16 +00002787 for(i=0; i<nEq; i++){
dan39129ce2014-06-30 15:23:57 +00002788 char *z = aiColumn[i] < 0 ? "rowid" : aCol[aiColumn[i]].zName;
drhcd8629e2013-11-13 12:27:25 +00002789 if( i>=nSkip ){
drh6c977892014-10-10 15:47:46 +00002790 explainAppendTerm(pStr, i, z, "=");
drhcd8629e2013-11-13 12:27:25 +00002791 }else{
drh6c977892014-10-10 15:47:46 +00002792 if( i ) sqlite3StrAccumAppend(pStr, " AND ", 5);
2793 sqlite3XPrintf(pStr, 0, "ANY(%s)", z);
drhcd8629e2013-11-13 12:27:25 +00002794 }
dan2ce22452010-11-08 19:01:16 +00002795 }
2796
drh69174c42010-11-12 15:35:59 +00002797 j = i;
drhef866372013-05-22 20:49:02 +00002798 if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
dan39129ce2014-06-30 15:23:57 +00002799 char *z = aiColumn[j] < 0 ? "rowid" : aCol[aiColumn[j]].zName;
drh6c977892014-10-10 15:47:46 +00002800 explainAppendTerm(pStr, i++, z, ">");
dan2ce22452010-11-08 19:01:16 +00002801 }
drhef866372013-05-22 20:49:02 +00002802 if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
dan39129ce2014-06-30 15:23:57 +00002803 char *z = aiColumn[j] < 0 ? "rowid" : aCol[aiColumn[j]].zName;
drh6c977892014-10-10 15:47:46 +00002804 explainAppendTerm(pStr, i, z, "<");
dan2ce22452010-11-08 19:01:16 +00002805 }
drh6c977892014-10-10 15:47:46 +00002806 sqlite3StrAccumAppend(pStr, ")", 1);
dan2ce22452010-11-08 19:01:16 +00002807}
2808
dan17c0bc02010-11-09 17:35:19 +00002809/*
2810** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
2811** command. If the query being compiled is an EXPLAIN QUERY PLAN, a single
2812** record is added to the output to describe the table scan strategy in
2813** pLevel.
2814*/
2815static void explainOneScan(
dan2ce22452010-11-08 19:01:16 +00002816 Parse *pParse, /* Parse context */
2817 SrcList *pTabList, /* Table list this loop refers to */
2818 WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
2819 int iLevel, /* Value for "level" column of output */
dan4a07e3d2010-11-09 14:48:59 +00002820 int iFrom, /* Value for "from" column of output */
2821 u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
dan2ce22452010-11-08 19:01:16 +00002822){
drh84e55a82013-11-13 17:58:23 +00002823#ifndef SQLITE_DEBUG
2824 if( pParse->explain==2 )
2825#endif
2826 {
dan2ce22452010-11-08 19:01:16 +00002827 struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
dan17c0bc02010-11-09 17:35:19 +00002828 Vdbe *v = pParse->pVdbe; /* VM being constructed */
2829 sqlite3 *db = pParse->db; /* Database handle */
dan4a07e3d2010-11-09 14:48:59 +00002830 int iId = pParse->iSelectId; /* Select id (left-most output column) */
dan4bc39fa2010-11-13 16:42:27 +00002831 int isSearch; /* True for a SEARCH. False for SCAN. */
drhef866372013-05-22 20:49:02 +00002832 WhereLoop *pLoop; /* The controlling WhereLoop object */
2833 u32 flags; /* Flags that describe this loop */
drh6c977892014-10-10 15:47:46 +00002834 char *zMsg; /* Text to add to EQP output */
2835 StrAccum str; /* EQP output string */
2836 char zBuf[100]; /* Initial space for EQP output string */
dan2ce22452010-11-08 19:01:16 +00002837
drhef866372013-05-22 20:49:02 +00002838 pLoop = pLevel->pWLoop;
2839 flags = pLoop->wsFlags;
dan4a07e3d2010-11-09 14:48:59 +00002840 if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return;
dan2ce22452010-11-08 19:01:16 +00002841
drhef866372013-05-22 20:49:02 +00002842 isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
2843 || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
2844 || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
dan4bc39fa2010-11-13 16:42:27 +00002845
drh6c977892014-10-10 15:47:46 +00002846 sqlite3StrAccumInit(&str, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH);
2847 str.db = db;
2848 sqlite3StrAccumAppendAll(&str, isSearch ? "SEARCH" : "SCAN");
dan4a07e3d2010-11-09 14:48:59 +00002849 if( pItem->pSelect ){
drh6c977892014-10-10 15:47:46 +00002850 sqlite3XPrintf(&str, 0, " SUBQUERY %d", pItem->iSelectId);
dan4a07e3d2010-11-09 14:48:59 +00002851 }else{
drh6c977892014-10-10 15:47:46 +00002852 sqlite3XPrintf(&str, 0, " TABLE %s", pItem->zName);
dan4a07e3d2010-11-09 14:48:59 +00002853 }
2854
dan2ce22452010-11-08 19:01:16 +00002855 if( pItem->zAlias ){
drh6c977892014-10-10 15:47:46 +00002856 sqlite3XPrintf(&str, 0, " AS %s", pItem->zAlias);
dan2ce22452010-11-08 19:01:16 +00002857 }
drh6c977892014-10-10 15:47:46 +00002858 if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0 ){
2859 const char *zFmt = 0;
2860 Index *pIdx;
2861
2862 assert( pLoop->u.btree.pIndex!=0 );
2863 pIdx = pLoop->u.btree.pIndex;
dane96f2df2014-05-23 17:17:06 +00002864 assert( !(flags&WHERE_AUTO_INDEX) || (flags&WHERE_IDX_ONLY) );
drh48dd1d82014-05-27 18:18:58 +00002865 if( !HasRowid(pItem->pTab) && IsPrimaryKeyIndex(pIdx) ){
drhc631faa2014-10-11 01:22:16 +00002866 if( isSearch ){
drh6c977892014-10-10 15:47:46 +00002867 zFmt = "PRIMARY KEY";
2868 }
drh051575c2014-10-25 12:28:25 +00002869 }else if( flags & WHERE_PARTIALIDX ){
2870 zFmt = "AUTOMATIC PARTIAL COVERING INDEX";
dane96f2df2014-05-23 17:17:06 +00002871 }else if( flags & WHERE_AUTO_INDEX ){
drh6c977892014-10-10 15:47:46 +00002872 zFmt = "AUTOMATIC COVERING INDEX";
dane96f2df2014-05-23 17:17:06 +00002873 }else if( flags & WHERE_IDX_ONLY ){
drh6c977892014-10-10 15:47:46 +00002874 zFmt = "COVERING INDEX %s";
dane96f2df2014-05-23 17:17:06 +00002875 }else{
drh6c977892014-10-10 15:47:46 +00002876 zFmt = "INDEX %s";
dane96f2df2014-05-23 17:17:06 +00002877 }
drh6c977892014-10-10 15:47:46 +00002878 if( zFmt ){
2879 sqlite3StrAccumAppend(&str, " USING ", 7);
2880 sqlite3XPrintf(&str, 0, zFmt, pIdx->zName);
2881 explainIndexRange(&str, pLoop, pItem->pTab);
2882 }
drhef71c1f2013-06-04 12:58:02 +00002883 }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
drh6c977892014-10-10 15:47:46 +00002884 const char *zRange;
drh8e23daf2013-06-11 13:30:04 +00002885 if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
drh6c977892014-10-10 15:47:46 +00002886 zRange = "(rowid=?)";
drh04098e62010-11-15 21:50:19 +00002887 }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
drh6c977892014-10-10 15:47:46 +00002888 zRange = "(rowid>? AND rowid<?)";
dan2ce22452010-11-08 19:01:16 +00002889 }else if( flags&WHERE_BTM_LIMIT ){
drh6c977892014-10-10 15:47:46 +00002890 zRange = "(rowid>?)";
2891 }else{
2892 assert( flags&WHERE_TOP_LIMIT);
2893 zRange = "(rowid<?)";
dan2ce22452010-11-08 19:01:16 +00002894 }
drh6c977892014-10-10 15:47:46 +00002895 sqlite3StrAccumAppendAll(&str, " USING INTEGER PRIMARY KEY ");
2896 sqlite3StrAccumAppendAll(&str, zRange);
dan2ce22452010-11-08 19:01:16 +00002897 }
2898#ifndef SQLITE_OMIT_VIRTUALTABLE
2899 else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
drh6c977892014-10-10 15:47:46 +00002900 sqlite3XPrintf(&str, 0, " VIRTUAL TABLE INDEX %d:%s",
drhef866372013-05-22 20:49:02 +00002901 pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
dan2ce22452010-11-08 19:01:16 +00002902 }
2903#endif
drh98545bb2014-10-10 17:20:39 +00002904#ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS
2905 if( pLoop->nOut>=10 ){
2906 sqlite3XPrintf(&str, 0, " (~%llu rows)", sqlite3LogEstToInt(pLoop->nOut));
2907 }else{
2908 sqlite3StrAccumAppend(&str, " (~1 row)", 9);
2909 }
2910#endif
drh6c977892014-10-10 15:47:46 +00002911 zMsg = sqlite3StrAccumFinish(&str);
dan4a07e3d2010-11-09 14:48:59 +00002912 sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg, P4_DYNAMIC);
dan2ce22452010-11-08 19:01:16 +00002913 }
2914}
2915#else
dan17c0bc02010-11-09 17:35:19 +00002916# define explainOneScan(u,v,w,x,y,z)
dan2ce22452010-11-08 19:01:16 +00002917#endif /* SQLITE_OMIT_EXPLAIN */
2918
2919
drh111a6a72008-12-21 03:51:16 +00002920/*
2921** Generate code for the start of the iLevel-th loop in the WHERE clause
2922** implementation described by pWInfo.
2923*/
2924static Bitmask codeOneLoopStart(
2925 WhereInfo *pWInfo, /* Complete information about the WHERE clause */
2926 int iLevel, /* Which level of pWInfo->a[] should be coded */
drh7a484802012-03-16 00:28:11 +00002927 Bitmask notReady /* Which tables are currently available */
drh111a6a72008-12-21 03:51:16 +00002928){
2929 int j, k; /* Loop counters */
2930 int iCur; /* The VDBE cursor for the table */
2931 int addrNxt; /* Where to jump to continue with the next IN case */
2932 int omitTable; /* True if we use the index only */
2933 int bRev; /* True if we need to scan in reverse order */
2934 WhereLevel *pLevel; /* The where level to be coded */
drh7ba39a92013-05-30 17:43:19 +00002935 WhereLoop *pLoop; /* The WhereLoop object being coded */
drh111a6a72008-12-21 03:51:16 +00002936 WhereClause *pWC; /* Decomposition of the entire WHERE clause */
2937 WhereTerm *pTerm; /* A WHERE clause term */
2938 Parse *pParse; /* Parsing context */
drh6b36e822013-07-30 15:10:32 +00002939 sqlite3 *db; /* Database connection */
drh111a6a72008-12-21 03:51:16 +00002940 Vdbe *v; /* The prepared stmt under constructions */
2941 struct SrcList_item *pTabItem; /* FROM clause term being coded */
drh23d04d52008-12-23 23:56:22 +00002942 int addrBrk; /* Jump here to break out of the loop */
2943 int addrCont; /* Jump here to continue with next cycle */
drh61495262009-04-22 15:32:59 +00002944 int iRowidReg = 0; /* Rowid is stored in this register, if not zero */
2945 int iReleaseReg = 0; /* Temp register to free before returning */
drh111a6a72008-12-21 03:51:16 +00002946
2947 pParse = pWInfo->pParse;
2948 v = pParse->pVdbe;
drh70d18342013-06-06 19:16:33 +00002949 pWC = &pWInfo->sWC;
drh6b36e822013-07-30 15:10:32 +00002950 db = pParse->db;
drh111a6a72008-12-21 03:51:16 +00002951 pLevel = &pWInfo->a[iLevel];
drh7ba39a92013-05-30 17:43:19 +00002952 pLoop = pLevel->pWLoop;
drh111a6a72008-12-21 03:51:16 +00002953 pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
2954 iCur = pTabItem->iCursor;
drh0259bc32013-09-09 19:37:46 +00002955 pLevel->notReady = notReady & ~getMask(&pWInfo->sMaskSet, iCur);
drh7ba39a92013-05-30 17:43:19 +00002956 bRev = (pWInfo->revMask>>iLevel)&1;
2957 omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
drh70d18342013-06-06 19:16:33 +00002958 && (pWInfo->wctrlFlags & WHERE_FORCE_TABLE)==0;
drh6bc69a22013-11-19 12:33:23 +00002959 VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName));
drh111a6a72008-12-21 03:51:16 +00002960
2961 /* Create labels for the "break" and "continue" instructions
2962 ** for the current loop. Jump to addrBrk to break out of a loop.
2963 ** Jump to cont to go immediately to the next iteration of the
2964 ** loop.
2965 **
2966 ** When there is an IN operator, we also have a "addrNxt" label that
2967 ** means to continue with the next IN value combination. When
2968 ** there are no IN operators in the constraints, the "addrNxt" label
2969 ** is the same as "addrBrk".
2970 */
2971 addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
2972 addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
2973
2974 /* If this is the right table of a LEFT OUTER JOIN, allocate and
2975 ** initialize a memory cell that records if this table matches any
2976 ** row of the left table of the join.
2977 */
2978 if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
2979 pLevel->iLeftJoin = ++pParse->nMem;
2980 sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
2981 VdbeComment((v, "init LEFT JOIN no-match flag"));
2982 }
2983
drh21172c42012-10-30 00:29:07 +00002984 /* Special case of a FROM clause subquery implemented as a co-routine */
2985 if( pTabItem->viaCoroutine ){
2986 int regYield = pTabItem->regReturn;
drhed71a832014-02-07 19:18:10 +00002987 sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
drh81cf13e2014-02-07 18:27:53 +00002988 pLevel->p2 = sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk);
drh688852a2014-02-17 22:40:43 +00002989 VdbeCoverage(v);
drh725de292014-02-08 13:12:19 +00002990 VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
drh21172c42012-10-30 00:29:07 +00002991 pLevel->op = OP_Goto;
2992 }else
2993
drh111a6a72008-12-21 03:51:16 +00002994#ifndef SQLITE_OMIT_VIRTUALTABLE
drh7ba39a92013-05-30 17:43:19 +00002995 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
2996 /* Case 1: The table is a virtual-table. Use the VFilter and VNext
drh111a6a72008-12-21 03:51:16 +00002997 ** to access the data.
2998 */
2999 int iReg; /* P3 Value for OP_VFilter */
drh281bbe22012-10-16 23:17:14 +00003000 int addrNotFound;
drh4efc9292013-06-06 23:02:03 +00003001 int nConstraint = pLoop->nLTerm;
drh111a6a72008-12-21 03:51:16 +00003002
drha62bb8d2009-11-23 21:23:45 +00003003 sqlite3ExprCachePush(pParse);
drh111a6a72008-12-21 03:51:16 +00003004 iReg = sqlite3GetTempRange(pParse, nConstraint+2);
drh281bbe22012-10-16 23:17:14 +00003005 addrNotFound = pLevel->addrBrk;
drh111a6a72008-12-21 03:51:16 +00003006 for(j=0; j<nConstraint; j++){
drhe2250172013-05-31 18:13:50 +00003007 int iTarget = iReg+j+2;
drh4efc9292013-06-06 23:02:03 +00003008 pTerm = pLoop->aLTerm[j];
drh95ed68d2013-06-12 17:55:50 +00003009 if( pTerm==0 ) continue;
drh7ba39a92013-05-30 17:43:19 +00003010 if( pTerm->eOperator & WO_IN ){
3011 codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
3012 addrNotFound = pLevel->addrNxt;
3013 }else{
3014 sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget);
3015 }
3016 }
3017 sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
drh7e47cb82013-05-31 17:55:27 +00003018 sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
drh7ba39a92013-05-30 17:43:19 +00003019 sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
3020 pLoop->u.vtab.idxStr,
3021 pLoop->u.vtab.needFree ? P4_MPRINTF : P4_STATIC);
drh688852a2014-02-17 22:40:43 +00003022 VdbeCoverage(v);
drh7ba39a92013-05-30 17:43:19 +00003023 pLoop->u.vtab.needFree = 0;
3024 for(j=0; j<nConstraint && j<16; j++){
3025 if( (pLoop->u.vtab.omitMask>>j)&1 ){
drh4efc9292013-06-06 23:02:03 +00003026 disableTerm(pLevel, pLoop->aLTerm[j]);
drh111a6a72008-12-21 03:51:16 +00003027 }
3028 }
3029 pLevel->op = OP_VNext;
3030 pLevel->p1 = iCur;
3031 pLevel->p2 = sqlite3VdbeCurrentAddr(v);
drh23d04d52008-12-23 23:56:22 +00003032 sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
drhd2490902014-04-13 19:28:15 +00003033 sqlite3ExprCachePop(pParse);
drh111a6a72008-12-21 03:51:16 +00003034 }else
3035#endif /* SQLITE_OMIT_VIRTUALTABLE */
3036
drh7ba39a92013-05-30 17:43:19 +00003037 if( (pLoop->wsFlags & WHERE_IPK)!=0
3038 && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
3039 ){
3040 /* Case 2: We can directly reference a single row using an
drh111a6a72008-12-21 03:51:16 +00003041 ** equality comparison against the ROWID field. Or
3042 ** we reference multiple rows using a "rowid IN (...)"
3043 ** construct.
3044 */
drh7ba39a92013-05-30 17:43:19 +00003045 assert( pLoop->u.btree.nEq==1 );
drh4efc9292013-06-06 23:02:03 +00003046 pTerm = pLoop->aLTerm[0];
drh111a6a72008-12-21 03:51:16 +00003047 assert( pTerm!=0 );
3048 assert( pTerm->pExpr!=0 );
drh111a6a72008-12-21 03:51:16 +00003049 assert( omitTable==0 );
drh39759742013-08-02 23:40:45 +00003050 testcase( pTerm->wtFlags & TERM_VIRTUAL );
drh0baa0352014-02-25 21:55:16 +00003051 iReleaseReg = ++pParse->nMem;
drh7ba39a92013-05-30 17:43:19 +00003052 iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
drh0baa0352014-02-25 21:55:16 +00003053 if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg);
drh111a6a72008-12-21 03:51:16 +00003054 addrNxt = pLevel->addrNxt;
drh688852a2014-02-17 22:40:43 +00003055 sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt); VdbeCoverage(v);
danielk19771d461462009-04-21 09:02:45 +00003056 sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
drh688852a2014-02-17 22:40:43 +00003057 VdbeCoverage(v);
drh459f63e2013-03-06 01:55:27 +00003058 sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
drhceea3322009-04-23 13:22:42 +00003059 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
drh111a6a72008-12-21 03:51:16 +00003060 VdbeComment((v, "pk"));
3061 pLevel->op = OP_Noop;
drh7ba39a92013-05-30 17:43:19 +00003062 }else if( (pLoop->wsFlags & WHERE_IPK)!=0
3063 && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
3064 ){
3065 /* Case 3: We have an inequality comparison against the ROWID field.
drh111a6a72008-12-21 03:51:16 +00003066 */
3067 int testOp = OP_Noop;
3068 int start;
3069 int memEndValue = 0;
3070 WhereTerm *pStart, *pEnd;
3071
3072 assert( omitTable==0 );
drh7ba39a92013-05-30 17:43:19 +00003073 j = 0;
3074 pStart = pEnd = 0;
drh4efc9292013-06-06 23:02:03 +00003075 if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
3076 if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
drh81186b42013-06-18 01:52:41 +00003077 assert( pStart!=0 || pEnd!=0 );
drh111a6a72008-12-21 03:51:16 +00003078 if( bRev ){
3079 pTerm = pStart;
3080 pStart = pEnd;
3081 pEnd = pTerm;
3082 }
3083 if( pStart ){
3084 Expr *pX; /* The expression that defines the start bound */
3085 int r1, rTemp; /* Registers for holding the start boundary */
3086
3087 /* The following constant maps TK_xx codes into corresponding
3088 ** seek opcodes. It depends on a particular ordering of TK_xx
3089 */
3090 const u8 aMoveOp[] = {
drh4a1d3652014-02-14 15:13:36 +00003091 /* TK_GT */ OP_SeekGT,
3092 /* TK_LE */ OP_SeekLE,
3093 /* TK_LT */ OP_SeekLT,
3094 /* TK_GE */ OP_SeekGE
drh111a6a72008-12-21 03:51:16 +00003095 };
3096 assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */
3097 assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */
3098 assert( TK_GE==TK_GT+3 ); /* ... is correcct. */
3099
drhb5246e52013-07-08 21:12:57 +00003100 assert( (pStart->wtFlags & TERM_VNULL)==0 );
drh39759742013-08-02 23:40:45 +00003101 testcase( pStart->wtFlags & TERM_VIRTUAL );
drh111a6a72008-12-21 03:51:16 +00003102 pX = pStart->pExpr;
3103 assert( pX!=0 );
drhb5246e52013-07-08 21:12:57 +00003104 testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
drh111a6a72008-12-21 03:51:16 +00003105 r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
3106 sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
drh7d176102014-02-18 03:07:12 +00003107 VdbeComment((v, "pk"));
3108 VdbeCoverageIf(v, pX->op==TK_GT);
3109 VdbeCoverageIf(v, pX->op==TK_LE);
3110 VdbeCoverageIf(v, pX->op==TK_LT);
3111 VdbeCoverageIf(v, pX->op==TK_GE);
drh111a6a72008-12-21 03:51:16 +00003112 sqlite3ExprCacheAffinityChange(pParse, r1, 1);
3113 sqlite3ReleaseTempReg(pParse, rTemp);
3114 disableTerm(pLevel, pStart);
3115 }else{
3116 sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
drh7d176102014-02-18 03:07:12 +00003117 VdbeCoverageIf(v, bRev==0);
3118 VdbeCoverageIf(v, bRev!=0);
drh111a6a72008-12-21 03:51:16 +00003119 }
3120 if( pEnd ){
3121 Expr *pX;
3122 pX = pEnd->pExpr;
3123 assert( pX!=0 );
drhb5246e52013-07-08 21:12:57 +00003124 assert( (pEnd->wtFlags & TERM_VNULL)==0 );
3125 testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
drh39759742013-08-02 23:40:45 +00003126 testcase( pEnd->wtFlags & TERM_VIRTUAL );
drh111a6a72008-12-21 03:51:16 +00003127 memEndValue = ++pParse->nMem;
3128 sqlite3ExprCode(pParse, pX->pRight, memEndValue);
3129 if( pX->op==TK_LT || pX->op==TK_GT ){
3130 testOp = bRev ? OP_Le : OP_Ge;
3131 }else{
3132 testOp = bRev ? OP_Lt : OP_Gt;
3133 }
3134 disableTerm(pLevel, pEnd);
3135 }
3136 start = sqlite3VdbeCurrentAddr(v);
3137 pLevel->op = bRev ? OP_Prev : OP_Next;
3138 pLevel->p1 = iCur;
3139 pLevel->p2 = start;
drh81186b42013-06-18 01:52:41 +00003140 assert( pLevel->p5==0 );
danielk19771d461462009-04-21 09:02:45 +00003141 if( testOp!=OP_Noop ){
drh0baa0352014-02-25 21:55:16 +00003142 iRowidReg = ++pParse->nMem;
danielk19771d461462009-04-21 09:02:45 +00003143 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
drhceea3322009-04-23 13:22:42 +00003144 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
danielk19771d461462009-04-21 09:02:45 +00003145 sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
drh7d176102014-02-18 03:07:12 +00003146 VdbeCoverageIf(v, testOp==OP_Le);
3147 VdbeCoverageIf(v, testOp==OP_Lt);
3148 VdbeCoverageIf(v, testOp==OP_Ge);
3149 VdbeCoverageIf(v, testOp==OP_Gt);
danielk19771d461462009-04-21 09:02:45 +00003150 sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
drh111a6a72008-12-21 03:51:16 +00003151 }
drh1b0f0262013-05-30 22:27:09 +00003152 }else if( pLoop->wsFlags & WHERE_INDEXED ){
drh7ba39a92013-05-30 17:43:19 +00003153 /* Case 4: A scan using an index.
drh111a6a72008-12-21 03:51:16 +00003154 **
3155 ** The WHERE clause may contain zero or more equality
3156 ** terms ("==" or "IN" operators) that refer to the N
3157 ** left-most columns of the index. It may also contain
3158 ** inequality constraints (>, <, >= or <=) on the indexed
3159 ** column that immediately follows the N equalities. Only
3160 ** the right-most column can be an inequality - the rest must
3161 ** use the "==" and "IN" operators. For example, if the
3162 ** index is on (x,y,z), then the following clauses are all
3163 ** optimized:
3164 **
3165 ** x=5
3166 ** x=5 AND y=10
3167 ** x=5 AND y<10
3168 ** x=5 AND y>5 AND y<10
3169 ** x=5 AND y=5 AND z<=10
3170 **
3171 ** The z<10 term of the following cannot be used, only
3172 ** the x=5 term:
3173 **
3174 ** x=5 AND z<10
3175 **
3176 ** N may be zero if there are inequality constraints.
3177 ** If there are no inequality constraints, then N is at
3178 ** least one.
3179 **
3180 ** This case is also used when there are no WHERE clause
3181 ** constraints but an index is selected anyway, in order
3182 ** to force the output order to conform to an ORDER BY.
3183 */
drh3bb9b932010-08-06 02:10:00 +00003184 static const u8 aStartOp[] = {
drh111a6a72008-12-21 03:51:16 +00003185 0,
3186 0,
3187 OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */
3188 OP_Last, /* 3: (!start_constraints && startEq && bRev) */
drh4a1d3652014-02-14 15:13:36 +00003189 OP_SeekGT, /* 4: (start_constraints && !startEq && !bRev) */
3190 OP_SeekLT, /* 5: (start_constraints && !startEq && bRev) */
3191 OP_SeekGE, /* 6: (start_constraints && startEq && !bRev) */
3192 OP_SeekLE /* 7: (start_constraints && startEq && bRev) */
drh111a6a72008-12-21 03:51:16 +00003193 };
drh3bb9b932010-08-06 02:10:00 +00003194 static const u8 aEndOp[] = {
drh4a1d3652014-02-14 15:13:36 +00003195 OP_IdxGE, /* 0: (end_constraints && !bRev && !endEq) */
3196 OP_IdxGT, /* 1: (end_constraints && !bRev && endEq) */
3197 OP_IdxLE, /* 2: (end_constraints && bRev && !endEq) */
3198 OP_IdxLT, /* 3: (end_constraints && bRev && endEq) */
drh111a6a72008-12-21 03:51:16 +00003199 };
drhcd8629e2013-11-13 12:27:25 +00003200 u16 nEq = pLoop->u.btree.nEq; /* Number of == or IN terms */
drh111a6a72008-12-21 03:51:16 +00003201 int regBase; /* Base register holding constraint values */
drh111a6a72008-12-21 03:51:16 +00003202 WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */
3203 WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */
3204 int startEq; /* True if range start uses ==, >= or <= */
3205 int endEq; /* True if range end uses ==, >= or <= */
3206 int start_constraints; /* Start of range is constrained */
3207 int nConstraint; /* Number of constraint terms */
drh3bb9b932010-08-06 02:10:00 +00003208 Index *pIdx; /* The index we will be using */
3209 int iIdxCur; /* The VDBE cursor for the index */
3210 int nExtraReg = 0; /* Number of extra registers needed */
3211 int op; /* Instruction opcode */
dan6ac43392010-06-09 15:47:11 +00003212 char *zStartAff; /* Affinity for start of range constraint */
drh33cad2f2013-11-15 12:41:01 +00003213 char cEndAff = 0; /* Affinity for end of range constraint */
drhcfc6ca42014-02-14 23:49:13 +00003214 u8 bSeekPastNull = 0; /* True to seek past initial nulls */
3215 u8 bStopAtNull = 0; /* Add condition to terminate at NULLs */
drh111a6a72008-12-21 03:51:16 +00003216
drh7ba39a92013-05-30 17:43:19 +00003217 pIdx = pLoop->u.btree.pIndex;
drh111a6a72008-12-21 03:51:16 +00003218 iIdxCur = pLevel->iIdxCur;
drhc8bbce12014-10-21 01:05:09 +00003219 assert( nEq>=pLoop->nSkip );
drh111a6a72008-12-21 03:51:16 +00003220
drh111a6a72008-12-21 03:51:16 +00003221 /* If this loop satisfies a sort order (pOrderBy) request that
3222 ** was passed to this function to implement a "SELECT min(x) ..."
3223 ** query, then the caller will only allow the loop to run for
3224 ** a single iteration. This means that the first row returned
3225 ** should not have a NULL value stored in 'x'. If column 'x' is
3226 ** the first one after the nEq equality constraints in the index,
3227 ** this requires some special handling.
3228 */
drhddba0c22014-03-18 20:33:42 +00003229 assert( pWInfo->pOrderBy==0
3230 || pWInfo->pOrderBy->nExpr==1
3231 || (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0 );
drh70d18342013-06-06 19:16:33 +00003232 if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
drhddba0c22014-03-18 20:33:42 +00003233 && pWInfo->nOBSat>0
drhbbbdc832013-10-22 18:01:40 +00003234 && (pIdx->nKeyCol>nEq)
drh111a6a72008-12-21 03:51:16 +00003235 ){
drhc8bbce12014-10-21 01:05:09 +00003236 assert( pLoop->nSkip==0 );
drhcfc6ca42014-02-14 23:49:13 +00003237 bSeekPastNull = 1;
drh6df2acd2008-12-28 16:55:25 +00003238 nExtraReg = 1;
drh111a6a72008-12-21 03:51:16 +00003239 }
3240
3241 /* Find any inequality constraint terms for the start and end
3242 ** of the range.
3243 */
drh7ba39a92013-05-30 17:43:19 +00003244 j = nEq;
3245 if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
drh4efc9292013-06-06 23:02:03 +00003246 pRangeStart = pLoop->aLTerm[j++];
drh6df2acd2008-12-28 16:55:25 +00003247 nExtraReg = 1;
drh111a6a72008-12-21 03:51:16 +00003248 }
drh7ba39a92013-05-30 17:43:19 +00003249 if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
drh4efc9292013-06-06 23:02:03 +00003250 pRangeEnd = pLoop->aLTerm[j++];
drh6df2acd2008-12-28 16:55:25 +00003251 nExtraReg = 1;
drhcfc6ca42014-02-14 23:49:13 +00003252 if( pRangeStart==0
drhcfc6ca42014-02-14 23:49:13 +00003253 && (j = pIdx->aiColumn[nEq])>=0
3254 && pIdx->pTable->aCol[j].notNull==0
3255 ){
3256 bSeekPastNull = 1;
3257 }
drh111a6a72008-12-21 03:51:16 +00003258 }
dan0df163a2014-03-06 12:36:26 +00003259 assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 );
drh111a6a72008-12-21 03:51:16 +00003260
drh6df2acd2008-12-28 16:55:25 +00003261 /* Generate code to evaluate all constraint terms using == or IN
3262 ** and store the values of those terms in an array of registers
3263 ** starting at regBase.
3264 */
drh613ba1e2013-06-15 15:11:45 +00003265 regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
drh33cad2f2013-11-15 12:41:01 +00003266 assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq );
3267 if( zStartAff ) cEndAff = zStartAff[nEq];
drh6df2acd2008-12-28 16:55:25 +00003268 addrNxt = pLevel->addrNxt;
3269
drh111a6a72008-12-21 03:51:16 +00003270 /* If we are doing a reverse order scan on an ascending index, or
3271 ** a forward order scan on a descending index, interchange the
3272 ** start and end terms (pRangeStart and pRangeEnd).
3273 */
drhbbbdc832013-10-22 18:01:40 +00003274 if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
3275 || (bRev && pIdx->nKeyCol==nEq)
dan0c733f62011-11-16 15:27:09 +00003276 ){
drh111a6a72008-12-21 03:51:16 +00003277 SWAP(WhereTerm *, pRangeEnd, pRangeStart);
drhcfc6ca42014-02-14 23:49:13 +00003278 SWAP(u8, bSeekPastNull, bStopAtNull);
drh111a6a72008-12-21 03:51:16 +00003279 }
3280
drh7963b0e2013-06-17 21:37:40 +00003281 testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
3282 testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
3283 testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
3284 testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
drh111a6a72008-12-21 03:51:16 +00003285 startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
3286 endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
3287 start_constraints = pRangeStart || nEq>0;
3288
3289 /* Seek the index cursor to the start of the range. */
3290 nConstraint = nEq;
3291 if( pRangeStart ){
dan69f8bb92009-08-13 19:21:16 +00003292 Expr *pRight = pRangeStart->pExpr->pRight;
3293 sqlite3ExprCode(pParse, pRight, regBase+nEq);
drh7d176102014-02-18 03:07:12 +00003294 if( (pRangeStart->wtFlags & TERM_VNULL)==0
3295 && sqlite3ExprCanBeNull(pRight)
3296 ){
3297 sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
3298 VdbeCoverage(v);
drh534230c2011-01-22 00:10:45 +00003299 }
dan6ac43392010-06-09 15:47:11 +00003300 if( zStartAff ){
3301 if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
drh039fc322009-11-17 18:31:47 +00003302 /* Since the comparison is to be performed with no conversions
3303 ** applied to the operands, set the affinity to apply to pRight to
3304 ** SQLITE_AFF_NONE. */
dan6ac43392010-06-09 15:47:11 +00003305 zStartAff[nEq] = SQLITE_AFF_NONE;
drh039fc322009-11-17 18:31:47 +00003306 }
dan6ac43392010-06-09 15:47:11 +00003307 if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
3308 zStartAff[nEq] = SQLITE_AFF_NONE;
drh039fc322009-11-17 18:31:47 +00003309 }
3310 }
drh111a6a72008-12-21 03:51:16 +00003311 nConstraint++;
drh39759742013-08-02 23:40:45 +00003312 testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
drhcfc6ca42014-02-14 23:49:13 +00003313 }else if( bSeekPastNull ){
drh111a6a72008-12-21 03:51:16 +00003314 sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
3315 nConstraint++;
3316 startEq = 0;
3317 start_constraints = 1;
3318 }
drhcfc6ca42014-02-14 23:49:13 +00003319 codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff);
drh111a6a72008-12-21 03:51:16 +00003320 op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
3321 assert( op!=0 );
drh8cff69d2009-11-12 19:59:44 +00003322 sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
drh688852a2014-02-17 22:40:43 +00003323 VdbeCoverage(v);
drh7d176102014-02-18 03:07:12 +00003324 VdbeCoverageIf(v, op==OP_Rewind); testcase( op==OP_Rewind );
3325 VdbeCoverageIf(v, op==OP_Last); testcase( op==OP_Last );
3326 VdbeCoverageIf(v, op==OP_SeekGT); testcase( op==OP_SeekGT );
3327 VdbeCoverageIf(v, op==OP_SeekGE); testcase( op==OP_SeekGE );
3328 VdbeCoverageIf(v, op==OP_SeekLE); testcase( op==OP_SeekLE );
3329 VdbeCoverageIf(v, op==OP_SeekLT); testcase( op==OP_SeekLT );
drh111a6a72008-12-21 03:51:16 +00003330
3331 /* Load the value for the inequality constraint at the end of the
3332 ** range (if any).
3333 */
3334 nConstraint = nEq;
3335 if( pRangeEnd ){
dan69f8bb92009-08-13 19:21:16 +00003336 Expr *pRight = pRangeEnd->pExpr->pRight;
drhf49f3522009-12-30 14:12:38 +00003337 sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
dan69f8bb92009-08-13 19:21:16 +00003338 sqlite3ExprCode(pParse, pRight, regBase+nEq);
drh7d176102014-02-18 03:07:12 +00003339 if( (pRangeEnd->wtFlags & TERM_VNULL)==0
3340 && sqlite3ExprCanBeNull(pRight)
3341 ){
3342 sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
3343 VdbeCoverage(v);
drh534230c2011-01-22 00:10:45 +00003344 }
drh33cad2f2013-11-15 12:41:01 +00003345 if( sqlite3CompareAffinity(pRight, cEndAff)!=SQLITE_AFF_NONE
3346 && !sqlite3ExprNeedsNoAffinityChange(pRight, cEndAff)
3347 ){
3348 codeApplyAffinity(pParse, regBase+nEq, 1, &cEndAff);
3349 }
drh111a6a72008-12-21 03:51:16 +00003350 nConstraint++;
drh39759742013-08-02 23:40:45 +00003351 testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
drhcfc6ca42014-02-14 23:49:13 +00003352 }else if( bStopAtNull ){
3353 sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
3354 endEq = 0;
3355 nConstraint++;
drh111a6a72008-12-21 03:51:16 +00003356 }
drh6b36e822013-07-30 15:10:32 +00003357 sqlite3DbFree(db, zStartAff);
drh111a6a72008-12-21 03:51:16 +00003358
3359 /* Top of the loop body */
3360 pLevel->p2 = sqlite3VdbeCurrentAddr(v);
3361
3362 /* Check if the index cursor is past the end of the range. */
drhcfc6ca42014-02-14 23:49:13 +00003363 if( nConstraint ){
drh4a1d3652014-02-14 15:13:36 +00003364 op = aEndOp[bRev*2 + endEq];
drh8cff69d2009-11-12 19:59:44 +00003365 sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
drh7d176102014-02-18 03:07:12 +00003366 testcase( op==OP_IdxGT ); VdbeCoverageIf(v, op==OP_IdxGT );
3367 testcase( op==OP_IdxGE ); VdbeCoverageIf(v, op==OP_IdxGE );
3368 testcase( op==OP_IdxLT ); VdbeCoverageIf(v, op==OP_IdxLT );
3369 testcase( op==OP_IdxLE ); VdbeCoverageIf(v, op==OP_IdxLE );
drh6df2acd2008-12-28 16:55:25 +00003370 }
drh111a6a72008-12-21 03:51:16 +00003371
drh111a6a72008-12-21 03:51:16 +00003372 /* Seek the table cursor, if required */
drh23d04d52008-12-23 23:56:22 +00003373 disableTerm(pLevel, pRangeStart);
3374 disableTerm(pLevel, pRangeEnd);
drh85c1c552013-10-24 00:18:18 +00003375 if( omitTable ){
3376 /* pIdx is a covering index. No need to access the main table. */
3377 }else if( HasRowid(pIdx->pTable) ){
drh0baa0352014-02-25 21:55:16 +00003378 iRowidReg = ++pParse->nMem;
danielk19771d461462009-04-21 09:02:45 +00003379 sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
drhceea3322009-04-23 13:22:42 +00003380 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
danielk19771d461462009-04-21 09:02:45 +00003381 sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg); /* Deferred seek */
drha3bc66a2014-05-27 17:57:32 +00003382 }else if( iCur!=iIdxCur ){
drh85c1c552013-10-24 00:18:18 +00003383 Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
3384 iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol);
3385 for(j=0; j<pPk->nKeyCol; j++){
3386 k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
3387 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j);
3388 }
drh261c02d2013-10-25 14:46:15 +00003389 sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont,
drh688852a2014-02-17 22:40:43 +00003390 iRowidReg, pPk->nKeyCol); VdbeCoverage(v);
drh111a6a72008-12-21 03:51:16 +00003391 }
drh111a6a72008-12-21 03:51:16 +00003392
3393 /* Record the instruction used to terminate the loop. Disable
3394 ** WHERE clause terms made redundant by the index range scan.
3395 */
drh7699d1c2013-06-04 12:42:29 +00003396 if( pLoop->wsFlags & WHERE_ONEROW ){
drh95e037b2011-03-09 21:02:31 +00003397 pLevel->op = OP_Noop;
3398 }else if( bRev ){
3399 pLevel->op = OP_Prev;
3400 }else{
3401 pLevel->op = OP_Next;
3402 }
drh111a6a72008-12-21 03:51:16 +00003403 pLevel->p1 = iIdxCur;
drh0c8a9342014-03-20 12:17:35 +00003404 pLevel->p3 = (pLoop->wsFlags&WHERE_UNQ_WANTED)!=0 ? 1:0;
drh53cfbe92013-06-13 17:28:22 +00003405 if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
drh3f4d1d12012-09-15 18:45:54 +00003406 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
3407 }else{
3408 assert( pLevel->p5==0 );
3409 }
drhdd5f5a62008-12-23 13:35:23 +00003410 }else
3411
drh23d04d52008-12-23 23:56:22 +00003412#ifndef SQLITE_OMIT_OR_OPTIMIZATION
drh7ba39a92013-05-30 17:43:19 +00003413 if( pLoop->wsFlags & WHERE_MULTI_OR ){
3414 /* Case 5: Two or more separately indexed terms connected by OR
drh111a6a72008-12-21 03:51:16 +00003415 **
3416 ** Example:
3417 **
3418 ** CREATE TABLE t1(a,b,c,d);
3419 ** CREATE INDEX i1 ON t1(a);
3420 ** CREATE INDEX i2 ON t1(b);
3421 ** CREATE INDEX i3 ON t1(c);
3422 **
3423 ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
3424 **
3425 ** In the example, there are three indexed terms connected by OR.
danielk19771d461462009-04-21 09:02:45 +00003426 ** The top of the loop looks like this:
drh111a6a72008-12-21 03:51:16 +00003427 **
drh1b26c7c2009-04-22 02:15:47 +00003428 ** Null 1 # Zero the rowset in reg 1
drh111a6a72008-12-21 03:51:16 +00003429 **
danielk19771d461462009-04-21 09:02:45 +00003430 ** Then, for each indexed term, the following. The arguments to
drh1b26c7c2009-04-22 02:15:47 +00003431 ** RowSetTest are such that the rowid of the current row is inserted
3432 ** into the RowSet. If it is already present, control skips the
danielk19771d461462009-04-21 09:02:45 +00003433 ** Gosub opcode and jumps straight to the code generated by WhereEnd().
drh111a6a72008-12-21 03:51:16 +00003434 **
danielk19771d461462009-04-21 09:02:45 +00003435 ** sqlite3WhereBegin(<term>)
drh1b26c7c2009-04-22 02:15:47 +00003436 ** RowSetTest # Insert rowid into rowset
danielk19771d461462009-04-21 09:02:45 +00003437 ** Gosub 2 A
3438 ** sqlite3WhereEnd()
3439 **
3440 ** Following the above, code to terminate the loop. Label A, the target
3441 ** of the Gosub above, jumps to the instruction right after the Goto.
3442 **
drh1b26c7c2009-04-22 02:15:47 +00003443 ** Null 1 # Zero the rowset in reg 1
danielk19771d461462009-04-21 09:02:45 +00003444 ** Goto B # The loop is finished.
3445 **
3446 ** A: <loop body> # Return data, whatever.
3447 **
3448 ** Return 2 # Jump back to the Gosub
3449 **
3450 ** B: <after the loop>
3451 **
drh5609baf2014-05-26 22:01:00 +00003452 ** Added 2014-05-26: If the table is a WITHOUT ROWID table, then
peter.d.reid60ec9142014-09-06 16:39:46 +00003453 ** use an ephemeral index instead of a RowSet to record the primary
drh5609baf2014-05-26 22:01:00 +00003454 ** keys of the rows we have already seen.
3455 **
drh111a6a72008-12-21 03:51:16 +00003456 */
drh111a6a72008-12-21 03:51:16 +00003457 WhereClause *pOrWc; /* The OR-clause broken out into subterms */
drhc01a3c12009-12-16 22:10:49 +00003458 SrcList *pOrTab; /* Shortened table list or OR-clause generation */
dan0efb72c2012-08-24 18:44:56 +00003459 Index *pCov = 0; /* Potential covering index (or NULL) */
3460 int iCovCur = pParse->nTab++; /* Cursor used for index scans (if any) */
danielk19771d461462009-04-21 09:02:45 +00003461
3462 int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */
shane85095702009-06-15 16:27:08 +00003463 int regRowset = 0; /* Register for RowSet object */
3464 int regRowid = 0; /* Register holding rowid */
danielk19771d461462009-04-21 09:02:45 +00003465 int iLoopBody = sqlite3VdbeMakeLabel(v); /* Start of loop body */
3466 int iRetInit; /* Address of regReturn init */
drhc01a3c12009-12-16 22:10:49 +00003467 int untestedTerms = 0; /* Some terms not completely tested */
drh8871ef52011-10-07 13:33:10 +00003468 int ii; /* Loop counter */
drh35263192014-07-22 20:02:19 +00003469 u16 wctrlFlags; /* Flags for sub-WHERE clause */
drh8871ef52011-10-07 13:33:10 +00003470 Expr *pAndExpr = 0; /* An ".. AND (...)" expression */
danf97dad82014-05-26 20:06:45 +00003471 Table *pTab = pTabItem->pTab;
drh111a6a72008-12-21 03:51:16 +00003472
drh4efc9292013-06-06 23:02:03 +00003473 pTerm = pLoop->aLTerm[0];
drh111a6a72008-12-21 03:51:16 +00003474 assert( pTerm!=0 );
drh7a5bcc02013-01-16 17:08:58 +00003475 assert( pTerm->eOperator & WO_OR );
drh111a6a72008-12-21 03:51:16 +00003476 assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
3477 pOrWc = &pTerm->u.pOrInfo->wc;
drhc01a3c12009-12-16 22:10:49 +00003478 pLevel->op = OP_Return;
3479 pLevel->p1 = regReturn;
drh23d04d52008-12-23 23:56:22 +00003480
danbfca6a42012-08-24 10:52:35 +00003481 /* Set up a new SrcList in pOrTab containing the table being scanned
drhc01a3c12009-12-16 22:10:49 +00003482 ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
3483 ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
3484 */
3485 if( pWInfo->nLevel>1 ){
3486 int nNotReady; /* The number of notReady tables */
3487 struct SrcList_item *origSrc; /* Original list of tables */
3488 nNotReady = pWInfo->nLevel - iLevel - 1;
drh6b36e822013-07-30 15:10:32 +00003489 pOrTab = sqlite3StackAllocRaw(db,
drhc01a3c12009-12-16 22:10:49 +00003490 sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
3491 if( pOrTab==0 ) return notReady;
drhad01d892013-06-19 13:59:49 +00003492 pOrTab->nAlloc = (u8)(nNotReady + 1);
shaneh46aae3c2009-12-31 19:06:23 +00003493 pOrTab->nSrc = pOrTab->nAlloc;
drhc01a3c12009-12-16 22:10:49 +00003494 memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
3495 origSrc = pWInfo->pTabList->a;
3496 for(k=1; k<=nNotReady; k++){
3497 memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
3498 }
3499 }else{
3500 pOrTab = pWInfo->pTabList;
3501 }
danielk19771d461462009-04-21 09:02:45 +00003502
drh1b26c7c2009-04-22 02:15:47 +00003503 /* Initialize the rowset register to contain NULL. An SQL NULL is
peter.d.reid60ec9142014-09-06 16:39:46 +00003504 ** equivalent to an empty rowset. Or, create an ephemeral index
drh5609baf2014-05-26 22:01:00 +00003505 ** capable of holding primary keys in the case of a WITHOUT ROWID.
danielk19771d461462009-04-21 09:02:45 +00003506 **
3507 ** Also initialize regReturn to contain the address of the instruction
3508 ** immediately following the OP_Return at the bottom of the loop. This
3509 ** is required in a few obscure LEFT JOIN cases where control jumps
3510 ** over the top of the loop into the body of it. In this case the
3511 ** correct response for the end-of-loop code (the OP_Return) is to
3512 ** fall through to the next instruction, just as an OP_Next does if
3513 ** called on an uninitialized cursor.
3514 */
drh70d18342013-06-06 19:16:33 +00003515 if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
danf97dad82014-05-26 20:06:45 +00003516 if( HasRowid(pTab) ){
3517 regRowset = ++pParse->nMem;
3518 sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
3519 }else{
3520 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
3521 regRowset = pParse->nTab++;
3522 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, regRowset, pPk->nKeyCol);
3523 sqlite3VdbeSetP4KeyInfo(pParse, pPk);
3524 }
drh336a5302009-04-24 15:46:21 +00003525 regRowid = ++pParse->nMem;
drh336a5302009-04-24 15:46:21 +00003526 }
danielk19771d461462009-04-21 09:02:45 +00003527 iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
3528
drh8871ef52011-10-07 13:33:10 +00003529 /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y
3530 ** Then for every term xN, evaluate as the subexpression: xN AND z
3531 ** That way, terms in y that are factored into the disjunction will
3532 ** be picked up by the recursive calls to sqlite3WhereBegin() below.
drh331b67c2012-03-09 22:02:08 +00003533 **
3534 ** Actually, each subexpression is converted to "xN AND w" where w is
3535 ** the "interesting" terms of z - terms that did not originate in the
3536 ** ON or USING clause of a LEFT JOIN, and terms that are usable as
3537 ** indices.
drhb3129fa2013-05-09 14:20:11 +00003538 **
3539 ** This optimization also only applies if the (x1 OR x2 OR ...) term
3540 ** is not contained in the ON clause of a LEFT JOIN.
3541 ** See ticket http://www.sqlite.org/src/info/f2369304e4
drh8871ef52011-10-07 13:33:10 +00003542 */
3543 if( pWC->nTerm>1 ){
drh7a484802012-03-16 00:28:11 +00003544 int iTerm;
3545 for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
3546 Expr *pExpr = pWC->a[iTerm].pExpr;
drhaa32e3c2013-07-16 21:31:23 +00003547 if( &pWC->a[iTerm] == pTerm ) continue;
drh331b67c2012-03-09 22:02:08 +00003548 if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
drh7c328062014-02-11 01:50:29 +00003549 testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO );
3550 testcase( pWC->a[iTerm].wtFlags & TERM_VIRTUAL );
3551 if( pWC->a[iTerm].wtFlags & (TERM_ORINFO|TERM_VIRTUAL) ) continue;
drh7a484802012-03-16 00:28:11 +00003552 if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
drh6b36e822013-07-30 15:10:32 +00003553 pExpr = sqlite3ExprDup(db, pExpr, 0);
3554 pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr);
drh331b67c2012-03-09 22:02:08 +00003555 }
3556 if( pAndExpr ){
3557 pAndExpr = sqlite3PExpr(pParse, TK_AND, 0, pAndExpr, 0);
3558 }
drh8871ef52011-10-07 13:33:10 +00003559 }
3560
drh3fb67302014-05-27 16:41:39 +00003561 /* Run a separate WHERE clause for each term of the OR clause. After
3562 ** eliminating duplicates from other WHERE clauses, the action for each
3563 ** sub-WHERE clause is to to invoke the main loop body as a subroutine.
3564 */
drh36be4c42014-09-30 17:31:23 +00003565 wctrlFlags = WHERE_OMIT_OPEN_CLOSE
3566 | WHERE_FORCE_TABLE
3567 | WHERE_ONETABLE_ONLY;
danielk19771d461462009-04-21 09:02:45 +00003568 for(ii=0; ii<pOrWc->nTerm; ii++){
3569 WhereTerm *pOrTerm = &pOrWc->a[ii];
drh7a5bcc02013-01-16 17:08:58 +00003570 if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
drh3fb67302014-05-27 16:41:39 +00003571 WhereInfo *pSubWInfo; /* Info for single OR-term scan */
3572 Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */
3573 int j1 = 0; /* Address of jump operation */
drhb3129fa2013-05-09 14:20:11 +00003574 if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){
drh8871ef52011-10-07 13:33:10 +00003575 pAndExpr->pLeft = pOrExpr;
3576 pOrExpr = pAndExpr;
3577 }
danielk19771d461462009-04-21 09:02:45 +00003578 /* Loop through table entries that match term pOrTerm. */
drh0a99ba32014-09-30 17:03:35 +00003579 WHERETRACE(0xffff, ("Subplan for OR-clause:\n"));
drh8871ef52011-10-07 13:33:10 +00003580 pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
drh35263192014-07-22 20:02:19 +00003581 wctrlFlags, iCovCur);
drh6b36e822013-07-30 15:10:32 +00003582 assert( pSubWInfo || pParse->nErr || db->mallocFailed );
danielk19771d461462009-04-21 09:02:45 +00003583 if( pSubWInfo ){
drh7ba39a92013-05-30 17:43:19 +00003584 WhereLoop *pSubLoop;
dan17c0bc02010-11-09 17:35:19 +00003585 explainOneScan(
dan4a07e3d2010-11-09 14:48:59 +00003586 pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
dan2ce22452010-11-08 19:01:16 +00003587 );
drh3fb67302014-05-27 16:41:39 +00003588 /* This is the sub-WHERE clause body. First skip over
3589 ** duplicate rows from prior sub-WHERE clauses, and record the
3590 ** rowid (or PRIMARY KEY) for the current row so that the same
3591 ** row will be skipped in subsequent sub-WHERE clauses.
3592 */
drh70d18342013-06-06 19:16:33 +00003593 if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
drh336a5302009-04-24 15:46:21 +00003594 int r;
danf97dad82014-05-26 20:06:45 +00003595 int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
3596 if( HasRowid(pTab) ){
3597 r = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, regRowid, 0);
drh5609baf2014-05-26 22:01:00 +00003598 j1 = sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, 0, r,iSet);
danf97dad82014-05-26 20:06:45 +00003599 VdbeCoverage(v);
3600 }else{
3601 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
3602 int nPk = pPk->nKeyCol;
3603 int iPk;
3604
3605 /* Read the PK into an array of temp registers. */
3606 r = sqlite3GetTempRange(pParse, nPk);
3607 for(iPk=0; iPk<nPk; iPk++){
3608 int iCol = pPk->aiColumn[iPk];
3609 sqlite3ExprCodeGetColumn(pParse, pTab, iCol, iCur, r+iPk, 0);
3610 }
3611
3612 /* Check if the temp table already contains this key. If so,
3613 ** the row has already been included in the result set and
3614 ** can be ignored (by jumping past the Gosub below). Otherwise,
3615 ** insert the key into the temp table and proceed with processing
3616 ** the row.
3617 **
3618 ** Use some of the same optimizations as OP_RowSetTest: If iSet
3619 ** is zero, assume that the key cannot already be present in
3620 ** the temp table. And if iSet is -1, assume that there is no
3621 ** need to insert the key into the temp table, as it will never
3622 ** be tested for. */
3623 if( iSet ){
drh5609baf2014-05-26 22:01:00 +00003624 j1 = sqlite3VdbeAddOp4Int(v, OP_Found, regRowset, 0, r, nPk);
drh68c12152014-05-26 20:25:34 +00003625 VdbeCoverage(v);
danf97dad82014-05-26 20:06:45 +00003626 }
3627 if( iSet>=0 ){
3628 sqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, regRowid);
3629 sqlite3VdbeAddOp3(v, OP_IdxInsert, regRowset, regRowid, 0);
3630 if( iSet ) sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
3631 }
3632
3633 /* Release the array of temp registers */
3634 sqlite3ReleaseTempRange(pParse, r, nPk);
3635 }
drh336a5302009-04-24 15:46:21 +00003636 }
drh3fb67302014-05-27 16:41:39 +00003637
3638 /* Invoke the main loop body as a subroutine */
danielk19771d461462009-04-21 09:02:45 +00003639 sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
drh3fb67302014-05-27 16:41:39 +00003640
3641 /* Jump here (skipping the main loop body subroutine) if the
3642 ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */
drh5609baf2014-05-26 22:01:00 +00003643 if( j1 ) sqlite3VdbeJumpHere(v, j1);
danielk19771d461462009-04-21 09:02:45 +00003644
drhc01a3c12009-12-16 22:10:49 +00003645 /* The pSubWInfo->untestedTerms flag means that this OR term
3646 ** contained one or more AND term from a notReady table. The
3647 ** terms from the notReady table could not be tested and will
3648 ** need to be tested later.
3649 */
3650 if( pSubWInfo->untestedTerms ) untestedTerms = 1;
3651
danbfca6a42012-08-24 10:52:35 +00003652 /* If all of the OR-connected terms are optimized using the same
3653 ** index, and the index is opened using the same cursor number
3654 ** by each call to sqlite3WhereBegin() made by this loop, it may
3655 ** be possible to use that index as a covering index.
3656 **
3657 ** If the call to sqlite3WhereBegin() above resulted in a scan that
3658 ** uses an index, and this is either the first OR-connected term
3659 ** processed or the index is the same as that used by all previous
dan0efb72c2012-08-24 18:44:56 +00003660 ** terms, set pCov to the candidate covering index. Otherwise, set
3661 ** pCov to NULL to indicate that no candidate covering index will
3662 ** be available.
danbfca6a42012-08-24 10:52:35 +00003663 */
drh7ba39a92013-05-30 17:43:19 +00003664 pSubLoop = pSubWInfo->a[0].pWLoop;
drh986b3872013-06-28 21:12:20 +00003665 assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
drh7ba39a92013-05-30 17:43:19 +00003666 if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
drh7ba39a92013-05-30 17:43:19 +00003667 && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
drh48dd1d82014-05-27 18:18:58 +00003668 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pSubLoop->u.btree.pIndex))
danbfca6a42012-08-24 10:52:35 +00003669 ){
drh7ba39a92013-05-30 17:43:19 +00003670 assert( pSubWInfo->a[0].iIdxCur==iCovCur );
drh907717f2013-06-04 18:03:22 +00003671 pCov = pSubLoop->u.btree.pIndex;
drh35263192014-07-22 20:02:19 +00003672 wctrlFlags |= WHERE_REOPEN_IDX;
danbfca6a42012-08-24 10:52:35 +00003673 }else{
3674 pCov = 0;
3675 }
3676
danielk19771d461462009-04-21 09:02:45 +00003677 /* Finish the loop through table entries that match term pOrTerm. */
3678 sqlite3WhereEnd(pSubWInfo);
3679 }
drhdd5f5a62008-12-23 13:35:23 +00003680 }
3681 }
drhd40e2082012-08-24 23:24:15 +00003682 pLevel->u.pCovidx = pCov;
drh90abfd02012-10-09 21:07:23 +00003683 if( pCov ) pLevel->iIdxCur = iCovCur;
drh331b67c2012-03-09 22:02:08 +00003684 if( pAndExpr ){
3685 pAndExpr->pLeft = 0;
drh6b36e822013-07-30 15:10:32 +00003686 sqlite3ExprDelete(db, pAndExpr);
drh331b67c2012-03-09 22:02:08 +00003687 }
danielk19771d461462009-04-21 09:02:45 +00003688 sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
danielk19771d461462009-04-21 09:02:45 +00003689 sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
3690 sqlite3VdbeResolveLabel(v, iLoopBody);
3691
drh6b36e822013-07-30 15:10:32 +00003692 if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab);
drhc01a3c12009-12-16 22:10:49 +00003693 if( !untestedTerms ) disableTerm(pLevel, pTerm);
drhdd5f5a62008-12-23 13:35:23 +00003694 }else
drh23d04d52008-12-23 23:56:22 +00003695#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
drhdd5f5a62008-12-23 13:35:23 +00003696
3697 {
drh7ba39a92013-05-30 17:43:19 +00003698 /* Case 6: There is no usable index. We must do a complete
drh111a6a72008-12-21 03:51:16 +00003699 ** scan of the entire table.
3700 */
drh699b3d42009-02-23 16:52:07 +00003701 static const u8 aStep[] = { OP_Next, OP_Prev };
3702 static const u8 aStart[] = { OP_Rewind, OP_Last };
3703 assert( bRev==0 || bRev==1 );
drhe73f0592014-01-21 22:25:45 +00003704 if( pTabItem->isRecursive ){
drh340309f2014-01-22 00:23:49 +00003705 /* Tables marked isRecursive have only a single row that is stored in
dan41028152014-01-22 10:22:25 +00003706 ** a pseudo-cursor. No need to Rewind or Next such cursors. */
drhe73f0592014-01-21 22:25:45 +00003707 pLevel->op = OP_Noop;
3708 }else{
3709 pLevel->op = aStep[bRev];
3710 pLevel->p1 = iCur;
3711 pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
drh7d176102014-02-18 03:07:12 +00003712 VdbeCoverageIf(v, bRev==0);
3713 VdbeCoverageIf(v, bRev!=0);
drhe73f0592014-01-21 22:25:45 +00003714 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
3715 }
drh111a6a72008-12-21 03:51:16 +00003716 }
drh111a6a72008-12-21 03:51:16 +00003717
3718 /* Insert code to test every subexpression that can be completely
3719 ** computed using the current set of tables.
3720 */
drh111a6a72008-12-21 03:51:16 +00003721 for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
3722 Expr *pE;
drh39759742013-08-02 23:40:45 +00003723 testcase( pTerm->wtFlags & TERM_VIRTUAL );
drh111a6a72008-12-21 03:51:16 +00003724 testcase( pTerm->wtFlags & TERM_CODED );
3725 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
drh0259bc32013-09-09 19:37:46 +00003726 if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
drhc01a3c12009-12-16 22:10:49 +00003727 testcase( pWInfo->untestedTerms==0
3728 && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
3729 pWInfo->untestedTerms = 1;
3730 continue;
3731 }
drh111a6a72008-12-21 03:51:16 +00003732 pE = pTerm->pExpr;
3733 assert( pE!=0 );
3734 if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
3735 continue;
3736 }
drh111a6a72008-12-21 03:51:16 +00003737 sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
drh111a6a72008-12-21 03:51:16 +00003738 pTerm->wtFlags |= TERM_CODED;
3739 }
3740
drh0c41d222013-04-22 02:39:10 +00003741 /* Insert code to test for implied constraints based on transitivity
3742 ** of the "==" operator.
3743 **
3744 ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
3745 ** and we are coding the t1 loop and the t2 loop has not yet coded,
3746 ** then we cannot use the "t1.a=t2.b" constraint, but we can code
3747 ** the implied "t1.a=123" constraint.
3748 */
3749 for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
drh6b36e822013-07-30 15:10:32 +00003750 Expr *pE, *pEAlt;
drh0c41d222013-04-22 02:39:10 +00003751 WhereTerm *pAlt;
drh0c41d222013-04-22 02:39:10 +00003752 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
3753 if( pTerm->eOperator!=(WO_EQUIV|WO_EQ) ) continue;
3754 if( pTerm->leftCursor!=iCur ) continue;
drhcdc2e432013-07-01 17:27:19 +00003755 if( pLevel->iLeftJoin ) continue;
drh0c41d222013-04-22 02:39:10 +00003756 pE = pTerm->pExpr;
3757 assert( !ExprHasProperty(pE, EP_FromJoin) );
drh0259bc32013-09-09 19:37:46 +00003758 assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
drh0c41d222013-04-22 02:39:10 +00003759 pAlt = findTerm(pWC, iCur, pTerm->u.leftColumn, notReady, WO_EQ|WO_IN, 0);
3760 if( pAlt==0 ) continue;
drh5c10f3b2013-05-01 17:22:38 +00003761 if( pAlt->wtFlags & (TERM_CODED) ) continue;
drh7963b0e2013-06-17 21:37:40 +00003762 testcase( pAlt->eOperator & WO_EQ );
3763 testcase( pAlt->eOperator & WO_IN );
drh6bc69a22013-11-19 12:33:23 +00003764 VdbeModuleComment((v, "begin transitive constraint"));
drh6b36e822013-07-30 15:10:32 +00003765 pEAlt = sqlite3StackAllocRaw(db, sizeof(*pEAlt));
3766 if( pEAlt ){
3767 *pEAlt = *pAlt->pExpr;
3768 pEAlt->pLeft = pE->pLeft;
3769 sqlite3ExprIfFalse(pParse, pEAlt, addrCont, SQLITE_JUMPIFNULL);
3770 sqlite3StackFree(db, pEAlt);
3771 }
drh0c41d222013-04-22 02:39:10 +00003772 }
3773
drh111a6a72008-12-21 03:51:16 +00003774 /* For a LEFT OUTER JOIN, generate code that will record the fact that
3775 ** at least one row of the right table has matched the left table.
3776 */
3777 if( pLevel->iLeftJoin ){
3778 pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
3779 sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
3780 VdbeComment((v, "record LEFT JOIN hit"));
drhceea3322009-04-23 13:22:42 +00003781 sqlite3ExprCacheClear(pParse);
drh111a6a72008-12-21 03:51:16 +00003782 for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
drh39759742013-08-02 23:40:45 +00003783 testcase( pTerm->wtFlags & TERM_VIRTUAL );
drh111a6a72008-12-21 03:51:16 +00003784 testcase( pTerm->wtFlags & TERM_CODED );
3785 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
drh0259bc32013-09-09 19:37:46 +00003786 if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
drhb057e562009-12-16 23:43:55 +00003787 assert( pWInfo->untestedTerms );
drhc01a3c12009-12-16 22:10:49 +00003788 continue;
3789 }
drh111a6a72008-12-21 03:51:16 +00003790 assert( pTerm->pExpr );
3791 sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
3792 pTerm->wtFlags |= TERM_CODED;
3793 }
3794 }
drh23d04d52008-12-23 23:56:22 +00003795
drh0259bc32013-09-09 19:37:46 +00003796 return pLevel->notReady;
drh111a6a72008-12-21 03:51:16 +00003797}
3798
drhd15cb172013-05-21 19:23:10 +00003799#ifdef WHERETRACE_ENABLED
drha18f3d22013-05-08 03:05:41 +00003800/*
drhc90713d2014-09-30 13:46:49 +00003801** Print the content of a WhereTerm object
3802*/
3803static void whereTermPrint(WhereTerm *pTerm, int iTerm){
drh0a99ba32014-09-30 17:03:35 +00003804 if( pTerm==0 ){
3805 sqlite3DebugPrintf("TERM-%-3d NULL\n", iTerm);
3806 }else{
3807 char zType[4];
3808 memcpy(zType, "...", 4);
3809 if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V';
3810 if( pTerm->eOperator & WO_EQUIV ) zType[1] = 'E';
3811 if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) zType[2] = 'L';
3812 sqlite3DebugPrintf("TERM-%-3d %p %s cursor=%-3d prob=%-3d op=0x%03x\n",
3813 iTerm, pTerm, zType, pTerm->leftCursor, pTerm->truthProb,
3814 pTerm->eOperator);
3815 sqlite3TreeViewExpr(0, pTerm->pExpr, 0);
3816 }
drhc90713d2014-09-30 13:46:49 +00003817}
3818#endif
3819
3820#ifdef WHERETRACE_ENABLED
3821/*
drha18f3d22013-05-08 03:05:41 +00003822** Print a WhereLoop object for debugging purposes
3823*/
drhc1ba2e72013-10-28 19:03:21 +00003824static void whereLoopPrint(WhereLoop *p, WhereClause *pWC){
3825 WhereInfo *pWInfo = pWC->pWInfo;
drh989578e2013-10-28 14:34:35 +00003826 int nb = 1+(pWInfo->pTabList->nSrc+7)/8;
3827 struct SrcList_item *pItem = pWInfo->pTabList->a + p->iTab;
drha18f3d22013-05-08 03:05:41 +00003828 Table *pTab = pItem->pTab;
drh6457a352013-06-21 00:35:37 +00003829 sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
drha184fb82013-05-08 04:22:59 +00003830 p->iTab, nb, p->maskSelf, nb, p->prereq);
drh6457a352013-06-21 00:35:37 +00003831 sqlite3DebugPrintf(" %12s",
drha18f3d22013-05-08 03:05:41 +00003832 pItem->zAlias ? pItem->zAlias : pTab->zName);
drh5346e952013-05-08 14:14:26 +00003833 if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
drhf3f69ac2014-08-20 23:38:07 +00003834 const char *zName;
3835 if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){
drh319f6772013-05-14 15:31:07 +00003836 if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
3837 int i = sqlite3Strlen30(zName) - 1;
3838 while( zName[i]!='_' ) i--;
3839 zName += i;
3840 }
drh6457a352013-06-21 00:35:37 +00003841 sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq);
drh5346e952013-05-08 14:14:26 +00003842 }else{
drh6457a352013-06-21 00:35:37 +00003843 sqlite3DebugPrintf("%20s","");
drh5346e952013-05-08 14:14:26 +00003844 }
drha18f3d22013-05-08 03:05:41 +00003845 }else{
drh5346e952013-05-08 14:14:26 +00003846 char *z;
3847 if( p->u.vtab.idxStr ){
drh3bd26f02013-05-24 14:52:03 +00003848 z = sqlite3_mprintf("(%d,\"%s\",%x)",
3849 p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
drh5346e952013-05-08 14:14:26 +00003850 }else{
drh3bd26f02013-05-24 14:52:03 +00003851 z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
drh5346e952013-05-08 14:14:26 +00003852 }
drh6457a352013-06-21 00:35:37 +00003853 sqlite3DebugPrintf(" %-19s", z);
drh5346e952013-05-08 14:14:26 +00003854 sqlite3_free(z);
drha18f3d22013-05-08 03:05:41 +00003855 }
drhf3f69ac2014-08-20 23:38:07 +00003856 if( p->wsFlags & WHERE_SKIPSCAN ){
drhc8bbce12014-10-21 01:05:09 +00003857 sqlite3DebugPrintf(" f %05x %d-%d", p->wsFlags, p->nLTerm,p->nSkip);
drhf3f69ac2014-08-20 23:38:07 +00003858 }else{
3859 sqlite3DebugPrintf(" f %05x N %d", p->wsFlags, p->nLTerm);
3860 }
drhb8a8e8a2013-06-10 19:12:39 +00003861 sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
drhc90713d2014-09-30 13:46:49 +00003862 if( p->nLTerm && (sqlite3WhereTrace & 0x100)!=0 ){
3863 int i;
3864 for(i=0; i<p->nLTerm; i++){
drh0a99ba32014-09-30 17:03:35 +00003865 whereTermPrint(p->aLTerm[i], i);
drhc90713d2014-09-30 13:46:49 +00003866 }
3867 }
drha18f3d22013-05-08 03:05:41 +00003868}
3869#endif
3870
drhf1b5f5b2013-05-02 00:15:01 +00003871/*
drh4efc9292013-06-06 23:02:03 +00003872** Convert bulk memory into a valid WhereLoop that can be passed
3873** to whereLoopClear harmlessly.
drh5346e952013-05-08 14:14:26 +00003874*/
drh4efc9292013-06-06 23:02:03 +00003875static void whereLoopInit(WhereLoop *p){
3876 p->aLTerm = p->aLTermSpace;
3877 p->nLTerm = 0;
3878 p->nLSlot = ArraySize(p->aLTermSpace);
3879 p->wsFlags = 0;
3880}
3881
3882/*
3883** Clear the WhereLoop.u union. Leave WhereLoop.pLTerm intact.
3884*/
3885static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
drh986b3872013-06-28 21:12:20 +00003886 if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){
drh13e11b42013-06-06 23:44:25 +00003887 if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
3888 sqlite3_free(p->u.vtab.idxStr);
3889 p->u.vtab.needFree = 0;
3890 p->u.vtab.idxStr = 0;
drh986b3872013-06-28 21:12:20 +00003891 }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){
drh13e11b42013-06-06 23:44:25 +00003892 sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
drh2ec2fb22013-11-06 19:59:23 +00003893 sqlite3KeyInfoUnref(p->u.btree.pIndex->pKeyInfo);
drh13e11b42013-06-06 23:44:25 +00003894 sqlite3DbFree(db, p->u.btree.pIndex);
3895 p->u.btree.pIndex = 0;
3896 }
drh5346e952013-05-08 14:14:26 +00003897 }
3898}
3899
drh4efc9292013-06-06 23:02:03 +00003900/*
3901** Deallocate internal memory used by a WhereLoop object
3902*/
3903static void whereLoopClear(sqlite3 *db, WhereLoop *p){
3904 if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
3905 whereLoopClearUnion(db, p);
3906 whereLoopInit(p);
3907}
3908
3909/*
3910** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
3911*/
3912static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
3913 WhereTerm **paNew;
3914 if( p->nLSlot>=n ) return SQLITE_OK;
3915 n = (n+7)&~7;
3916 paNew = sqlite3DbMallocRaw(db, sizeof(p->aLTerm[0])*n);
3917 if( paNew==0 ) return SQLITE_NOMEM;
3918 memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
3919 if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
3920 p->aLTerm = paNew;
3921 p->nLSlot = n;
3922 return SQLITE_OK;
3923}
3924
3925/*
3926** Transfer content from the second pLoop into the first.
3927*/
3928static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
drh4efc9292013-06-06 23:02:03 +00003929 whereLoopClearUnion(db, pTo);
drh0d31dc32013-09-06 00:40:59 +00003930 if( whereLoopResize(db, pTo, pFrom->nLTerm) ){
3931 memset(&pTo->u, 0, sizeof(pTo->u));
3932 return SQLITE_NOMEM;
3933 }
drha2014152013-06-07 00:29:23 +00003934 memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
3935 memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
drh4efc9292013-06-06 23:02:03 +00003936 if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
3937 pFrom->u.vtab.needFree = 0;
drh986b3872013-06-28 21:12:20 +00003938 }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){
drh4efc9292013-06-06 23:02:03 +00003939 pFrom->u.btree.pIndex = 0;
3940 }
3941 return SQLITE_OK;
3942}
3943
drh5346e952013-05-08 14:14:26 +00003944/*
drhf1b5f5b2013-05-02 00:15:01 +00003945** Delete a WhereLoop object
3946*/
3947static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
drh5346e952013-05-08 14:14:26 +00003948 whereLoopClear(db, p);
drhf1b5f5b2013-05-02 00:15:01 +00003949 sqlite3DbFree(db, p);
3950}
drh84bfda42005-07-15 13:05:21 +00003951
drh9eff6162006-06-12 21:59:13 +00003952/*
3953** Free a WhereInfo structure
3954*/
drh10fe8402008-10-11 16:47:35 +00003955static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
drh52ff8ea2010-04-08 14:15:56 +00003956 if( ALWAYS(pWInfo) ){
drh70d18342013-06-06 19:16:33 +00003957 whereClauseClear(&pWInfo->sWC);
drhf1b5f5b2013-05-02 00:15:01 +00003958 while( pWInfo->pLoops ){
3959 WhereLoop *p = pWInfo->pLoops;
3960 pWInfo->pLoops = p->pNextLoop;
3961 whereLoopDelete(db, p);
3962 }
drh633e6d52008-07-28 19:34:53 +00003963 sqlite3DbFree(db, pWInfo);
drh9eff6162006-06-12 21:59:13 +00003964 }
3965}
3966
drhf1b5f5b2013-05-02 00:15:01 +00003967/*
drhb355c2c2014-04-18 22:20:31 +00003968** Return TRUE if both of the following are true:
3969**
3970** (1) X has the same or lower cost that Y
3971** (2) X is a proper subset of Y
3972**
3973** By "proper subset" we mean that X uses fewer WHERE clause terms
3974** than Y and that every WHERE clause term used by X is also used
3975** by Y.
3976**
3977** If X is a proper subset of Y then Y is a better choice and ought
3978** to have a lower cost. This routine returns TRUE when that cost
3979** relationship is inverted and needs to be adjusted.
drh3fb183d2014-03-31 19:49:00 +00003980*/
drhb355c2c2014-04-18 22:20:31 +00003981static int whereLoopCheaperProperSubset(
3982 const WhereLoop *pX, /* First WhereLoop to compare */
3983 const WhereLoop *pY /* Compare against this WhereLoop */
3984){
drh3fb183d2014-03-31 19:49:00 +00003985 int i, j;
drhc8bbce12014-10-21 01:05:09 +00003986 if( pX->nLTerm-pX->nSkip >= pY->nLTerm-pY->nSkip ){
3987 return 0; /* X is not a subset of Y */
3988 }
drhb355c2c2014-04-18 22:20:31 +00003989 if( pX->rRun >= pY->rRun ){
3990 if( pX->rRun > pY->rRun ) return 0; /* X costs more than Y */
3991 if( pX->nOut > pY->nOut ) return 0; /* X costs more than Y */
drh3fb183d2014-03-31 19:49:00 +00003992 }
drh9ee88102014-05-07 20:33:17 +00003993 for(i=pX->nLTerm-1; i>=0; i--){
drhc8bbce12014-10-21 01:05:09 +00003994 if( pX->aLTerm[i]==0 ) continue;
drhb355c2c2014-04-18 22:20:31 +00003995 for(j=pY->nLTerm-1; j>=0; j--){
3996 if( pY->aLTerm[j]==pX->aLTerm[i] ) break;
3997 }
3998 if( j<0 ) return 0; /* X not a subset of Y since term X[i] not used by Y */
3999 }
4000 return 1; /* All conditions meet */
drh3fb183d2014-03-31 19:49:00 +00004001}
4002
4003/*
4004** Try to adjust the cost of WhereLoop pTemplate upwards or downwards so
4005** that:
drh53cd10a2014-03-31 18:24:18 +00004006**
drh3fb183d2014-03-31 19:49:00 +00004007** (1) pTemplate costs less than any other WhereLoops that are a proper
4008** subset of pTemplate
drh53cd10a2014-03-31 18:24:18 +00004009**
drh3fb183d2014-03-31 19:49:00 +00004010** (2) pTemplate costs more than any other WhereLoops for which pTemplate
4011** is a proper subset.
drh53cd10a2014-03-31 18:24:18 +00004012**
drh3fb183d2014-03-31 19:49:00 +00004013** To say "WhereLoop X is a proper subset of Y" means that X uses fewer
4014** WHERE clause terms than Y and that every WHERE clause term used by X is
4015** also used by Y.
drh53cd10a2014-03-31 18:24:18 +00004016*/
4017static void whereLoopAdjustCost(const WhereLoop *p, WhereLoop *pTemplate){
4018 if( (pTemplate->wsFlags & WHERE_INDEXED)==0 ) return;
drh53cd10a2014-03-31 18:24:18 +00004019 for(; p; p=p->pNextLoop){
drh3fb183d2014-03-31 19:49:00 +00004020 if( p->iTab!=pTemplate->iTab ) continue;
4021 if( (p->wsFlags & WHERE_INDEXED)==0 ) continue;
drhb355c2c2014-04-18 22:20:31 +00004022 if( whereLoopCheaperProperSubset(p, pTemplate) ){
4023 /* Adjust pTemplate cost downward so that it is cheaper than its
drhf7f2e842014-10-21 18:16:21 +00004024 ** subset p. Except, do not adjust the cost estimate downward for
4025 ** a loop that skips more columns. */
4026 if( pTemplate->nSkip>p->nSkip ) continue;
drh1b131b72014-10-21 16:01:40 +00004027 WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
4028 pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut-1));
drh3fb183d2014-03-31 19:49:00 +00004029 pTemplate->rRun = p->rRun;
4030 pTemplate->nOut = p->nOut - 1;
drhb355c2c2014-04-18 22:20:31 +00004031 }else if( whereLoopCheaperProperSubset(pTemplate, p) ){
4032 /* Adjust pTemplate cost upward so that it is costlier than p since
4033 ** pTemplate is a proper subset of p */
drh1b131b72014-10-21 16:01:40 +00004034 WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
4035 pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut+1));
drh3fb183d2014-03-31 19:49:00 +00004036 pTemplate->rRun = p->rRun;
4037 pTemplate->nOut = p->nOut + 1;
drh53cd10a2014-03-31 18:24:18 +00004038 }
4039 }
4040}
4041
4042/*
drh7a4b1642014-03-29 21:16:07 +00004043** Search the list of WhereLoops in *ppPrev looking for one that can be
4044** supplanted by pTemplate.
drhf1b5f5b2013-05-02 00:15:01 +00004045**
drh7a4b1642014-03-29 21:16:07 +00004046** Return NULL if the WhereLoop list contains an entry that can supplant
4047** pTemplate, in other words if pTemplate does not belong on the list.
drh23f98da2013-05-21 15:52:07 +00004048**
drh7a4b1642014-03-29 21:16:07 +00004049** If pX is a WhereLoop that pTemplate can supplant, then return the
4050** link that points to pX.
drh23f98da2013-05-21 15:52:07 +00004051**
drh7a4b1642014-03-29 21:16:07 +00004052** If pTemplate cannot supplant any existing element of the list but needs
4053** to be added to the list, then return a pointer to the tail of the list.
drhf1b5f5b2013-05-02 00:15:01 +00004054*/
drh7a4b1642014-03-29 21:16:07 +00004055static WhereLoop **whereLoopFindLesser(
4056 WhereLoop **ppPrev,
4057 const WhereLoop *pTemplate
4058){
4059 WhereLoop *p;
4060 for(p=(*ppPrev); p; ppPrev=&p->pNextLoop, p=*ppPrev){
drhdbb80232013-06-19 12:34:13 +00004061 if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
4062 /* If either the iTab or iSortIdx values for two WhereLoop are different
4063 ** then those WhereLoops need to be considered separately. Neither is
4064 ** a candidate to replace the other. */
4065 continue;
4066 }
4067 /* In the current implementation, the rSetup value is either zero
4068 ** or the cost of building an automatic index (NlogN) and the NlogN
4069 ** is the same for compatible WhereLoops. */
4070 assert( p->rSetup==0 || pTemplate->rSetup==0
4071 || p->rSetup==pTemplate->rSetup );
4072
4073 /* whereLoopAddBtree() always generates and inserts the automatic index
4074 ** case first. Hence compatible candidate WhereLoops never have a larger
4075 ** rSetup. Call this SETUP-INVARIANT */
4076 assert( p->rSetup>=pTemplate->rSetup );
4077
drhdabe36d2014-06-17 20:16:43 +00004078 /* Any loop using an appliation-defined index (or PRIMARY KEY or
4079 ** UNIQUE constraint) with one or more == constraints is better
4080 ** than an automatic index. */
4081 if( (p->wsFlags & WHERE_AUTO_INDEX)!=0
4082 && (pTemplate->wsFlags & WHERE_INDEXED)!=0
4083 && (pTemplate->wsFlags & WHERE_COLUMN_EQ)!=0
4084 && (p->prereq & pTemplate->prereq)==pTemplate->prereq
4085 ){
4086 break;
4087 }
4088
drh53cd10a2014-03-31 18:24:18 +00004089 /* If existing WhereLoop p is better than pTemplate, pTemplate can be
4090 ** discarded. WhereLoop p is better if:
4091 ** (1) p has no more dependencies than pTemplate, and
4092 ** (2) p has an equal or lower cost than pTemplate
4093 */
4094 if( (p->prereq & pTemplate->prereq)==p->prereq /* (1) */
4095 && p->rSetup<=pTemplate->rSetup /* (2a) */
4096 && p->rRun<=pTemplate->rRun /* (2b) */
4097 && p->nOut<=pTemplate->nOut /* (2c) */
drhf1b5f5b2013-05-02 00:15:01 +00004098 ){
drh53cd10a2014-03-31 18:24:18 +00004099 return 0; /* Discard pTemplate */
drhf1b5f5b2013-05-02 00:15:01 +00004100 }
drh53cd10a2014-03-31 18:24:18 +00004101
4102 /* If pTemplate is always better than p, then cause p to be overwritten
4103 ** with pTemplate. pTemplate is better than p if:
4104 ** (1) pTemplate has no more dependences than p, and
4105 ** (2) pTemplate has an equal or lower cost than p.
4106 */
4107 if( (p->prereq & pTemplate->prereq)==pTemplate->prereq /* (1) */
4108 && p->rRun>=pTemplate->rRun /* (2a) */
4109 && p->nOut>=pTemplate->nOut /* (2b) */
drhf1b5f5b2013-05-02 00:15:01 +00004110 ){
drhadd5ce32013-09-07 00:29:06 +00004111 assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */
drh53cd10a2014-03-31 18:24:18 +00004112 break; /* Cause p to be overwritten by pTemplate */
drhf1b5f5b2013-05-02 00:15:01 +00004113 }
4114 }
drh7a4b1642014-03-29 21:16:07 +00004115 return ppPrev;
4116}
4117
4118/*
drh94a11212004-09-25 13:12:14 +00004119** Insert or replace a WhereLoop entry using the template supplied.
4120**
4121** An existing WhereLoop entry might be overwritten if the new template
4122** is better and has fewer dependencies. Or the template will be ignored
4123** and no insert will occur if an existing WhereLoop is faster and has
4124** fewer dependencies than the template. Otherwise a new WhereLoop is
4125** added based on the template.
drh51669862004-12-18 18:40:26 +00004126**
drh7a4b1642014-03-29 21:16:07 +00004127** If pBuilder->pOrSet is not NULL then we care about only the
drh94a11212004-09-25 13:12:14 +00004128** prerequisites and rRun and nOut costs of the N best loops. That
4129** information is gathered in the pBuilder->pOrSet object. This special
drh51669862004-12-18 18:40:26 +00004130** processing mode is used only for OR clause processing.
4131**
4132** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
4133** still might overwrite similar loops with the new template if the
drh53cd10a2014-03-31 18:24:18 +00004134** new template is better. Loops may be overwritten if the following
drh94a11212004-09-25 13:12:14 +00004135** conditions are met:
4136**
4137** (1) They have the same iTab.
4138** (2) They have the same iSortIdx.
4139** (3) The template has same or fewer dependencies than the current loop
4140** (4) The template has the same or lower cost than the current loop
drh94a11212004-09-25 13:12:14 +00004141*/
4142static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
drh7a4b1642014-03-29 21:16:07 +00004143 WhereLoop **ppPrev, *p;
drh94a11212004-09-25 13:12:14 +00004144 WhereInfo *pWInfo = pBuilder->pWInfo;
4145 sqlite3 *db = pWInfo->pParse->db;
4146
4147 /* If pBuilder->pOrSet is defined, then only keep track of the costs
4148 ** and prereqs.
4149 */
4150 if( pBuilder->pOrSet!=0 ){
4151#if WHERETRACE_ENABLED
drh51669862004-12-18 18:40:26 +00004152 u16 n = pBuilder->pOrSet->n;
4153 int x =
4154#endif
4155 whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
4156 pTemplate->nOut);
drh94a11212004-09-25 13:12:14 +00004157#if WHERETRACE_ENABLED /* 0x8 */
4158 if( sqlite3WhereTrace & 0x8 ){
drhe3184742002-06-19 14:27:05 +00004159 sqlite3DebugPrintf(x?" or-%d: ":" or-X: ", n);
drhacf3b982005-01-03 01:27:18 +00004160 whereLoopPrint(pTemplate, pBuilder->pWC);
drh75897232000-05-29 14:26:00 +00004161 }
danielk19774adee202004-05-08 08:23:19 +00004162#endif
drh75897232000-05-29 14:26:00 +00004163 return SQLITE_OK;
4164 }
4165
drh7a4b1642014-03-29 21:16:07 +00004166 /* Look for an existing WhereLoop to replace with pTemplate
drh75897232000-05-29 14:26:00 +00004167 */
drh53cd10a2014-03-31 18:24:18 +00004168 whereLoopAdjustCost(pWInfo->pLoops, pTemplate);
drh7a4b1642014-03-29 21:16:07 +00004169 ppPrev = whereLoopFindLesser(&pWInfo->pLoops, pTemplate);
drhf1b5f5b2013-05-02 00:15:01 +00004170
drh7a4b1642014-03-29 21:16:07 +00004171 if( ppPrev==0 ){
4172 /* There already exists a WhereLoop on the list that is better
4173 ** than pTemplate, so just ignore pTemplate */
4174#if WHERETRACE_ENABLED /* 0x8 */
4175 if( sqlite3WhereTrace & 0x8 ){
drh9a7b41d2014-10-08 00:08:08 +00004176 sqlite3DebugPrintf(" skip: ");
drh7a4b1642014-03-29 21:16:07 +00004177 whereLoopPrint(pTemplate, pBuilder->pWC);
drhf1b5f5b2013-05-02 00:15:01 +00004178 }
drh7a4b1642014-03-29 21:16:07 +00004179#endif
4180 return SQLITE_OK;
4181 }else{
4182 p = *ppPrev;
drhf1b5f5b2013-05-02 00:15:01 +00004183 }
4184
4185 /* If we reach this point it means that either p[] should be overwritten
4186 ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
4187 ** WhereLoop and insert it.
4188 */
drh989578e2013-10-28 14:34:35 +00004189#if WHERETRACE_ENABLED /* 0x8 */
drhae70cf12013-05-31 15:18:46 +00004190 if( sqlite3WhereTrace & 0x8 ){
4191 if( p!=0 ){
drh9a7b41d2014-10-08 00:08:08 +00004192 sqlite3DebugPrintf("replace: ");
drhc1ba2e72013-10-28 19:03:21 +00004193 whereLoopPrint(p, pBuilder->pWC);
drhae70cf12013-05-31 15:18:46 +00004194 }
drh9a7b41d2014-10-08 00:08:08 +00004195 sqlite3DebugPrintf(" add: ");
drhc1ba2e72013-10-28 19:03:21 +00004196 whereLoopPrint(pTemplate, pBuilder->pWC);
drhae70cf12013-05-31 15:18:46 +00004197 }
4198#endif
drhf1b5f5b2013-05-02 00:15:01 +00004199 if( p==0 ){
drh7a4b1642014-03-29 21:16:07 +00004200 /* Allocate a new WhereLoop to add to the end of the list */
4201 *ppPrev = p = sqlite3DbMallocRaw(db, sizeof(WhereLoop));
drhf1b5f5b2013-05-02 00:15:01 +00004202 if( p==0 ) return SQLITE_NOMEM;
drh4efc9292013-06-06 23:02:03 +00004203 whereLoopInit(p);
drh7a4b1642014-03-29 21:16:07 +00004204 p->pNextLoop = 0;
4205 }else{
4206 /* We will be overwriting WhereLoop p[]. But before we do, first
4207 ** go through the rest of the list and delete any other entries besides
4208 ** p[] that are also supplated by pTemplate */
4209 WhereLoop **ppTail = &p->pNextLoop;
4210 WhereLoop *pToDel;
4211 while( *ppTail ){
4212 ppTail = whereLoopFindLesser(ppTail, pTemplate);
drhdabe36d2014-06-17 20:16:43 +00004213 if( ppTail==0 ) break;
drh7a4b1642014-03-29 21:16:07 +00004214 pToDel = *ppTail;
4215 if( pToDel==0 ) break;
4216 *ppTail = pToDel->pNextLoop;
4217#if WHERETRACE_ENABLED /* 0x8 */
4218 if( sqlite3WhereTrace & 0x8 ){
drh9a7b41d2014-10-08 00:08:08 +00004219 sqlite3DebugPrintf(" delete: ");
drh7a4b1642014-03-29 21:16:07 +00004220 whereLoopPrint(pToDel, pBuilder->pWC);
4221 }
4222#endif
4223 whereLoopDelete(db, pToDel);
4224 }
drhf1b5f5b2013-05-02 00:15:01 +00004225 }
drh4efc9292013-06-06 23:02:03 +00004226 whereLoopXfer(db, p, pTemplate);
drh5346e952013-05-08 14:14:26 +00004227 if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
drhef866372013-05-22 20:49:02 +00004228 Index *pIndex = p->u.btree.pIndex;
4229 if( pIndex && pIndex->tnum==0 ){
drhcf8fa7a2013-05-10 20:26:22 +00004230 p->u.btree.pIndex = 0;
4231 }
drh5346e952013-05-08 14:14:26 +00004232 }
drhf1b5f5b2013-05-02 00:15:01 +00004233 return SQLITE_OK;
4234}
4235
4236/*
drhcca9f3d2013-09-06 15:23:29 +00004237** Adjust the WhereLoop.nOut value downward to account for terms of the
4238** WHERE clause that reference the loop but which are not used by an
4239** index.
4240**
4241** In the current implementation, the first extra WHERE clause term reduces
4242** the number of output rows by a factor of 10 and each additional term
4243** reduces the number of output rows by sqrt(2).
4244*/
drhd8b77e22014-09-06 01:35:57 +00004245static void whereLoopOutputAdjust(
4246 WhereClause *pWC, /* The WHERE clause */
4247 WhereLoop *pLoop, /* The loop to adjust downward */
4248 LogEst nRow /* Number of rows in the entire table */
4249){
drh7d9e7d82013-09-11 17:39:09 +00004250 WhereTerm *pTerm, *pX;
drhcca9f3d2013-09-06 15:23:29 +00004251 Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf);
drh7d9e7d82013-09-11 17:39:09 +00004252 int i, j;
mistachkin6b9da122014-09-06 02:00:41 +00004253 int nEq = 0; /* Number of = constraints not within likely()/unlikely() */
drhadd5ce32013-09-07 00:29:06 +00004254
drhcca9f3d2013-09-06 15:23:29 +00004255 for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){
drh7d9e7d82013-09-11 17:39:09 +00004256 if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break;
drhcca9f3d2013-09-06 15:23:29 +00004257 if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;
4258 if( (pTerm->prereqAll & notAllowed)!=0 ) continue;
drh7d9e7d82013-09-11 17:39:09 +00004259 for(j=pLoop->nLTerm-1; j>=0; j--){
4260 pX = pLoop->aLTerm[j];
drhd2447442013-11-13 19:01:41 +00004261 if( pX==0 ) continue;
drh7d9e7d82013-09-11 17:39:09 +00004262 if( pX==pTerm ) break;
4263 if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break;
4264 }
danaa9933c2014-04-24 20:04:49 +00004265 if( j<0 ){
drhd8b77e22014-09-06 01:35:57 +00004266 if( pTerm->truthProb<=0 ){
4267 pLoop->nOut += pTerm->truthProb;
4268 }else{
4269 pLoop->nOut--;
4270 if( pTerm->eOperator&WO_EQ ) nEq++;
4271 }
danaa9933c2014-04-24 20:04:49 +00004272 }
drhcca9f3d2013-09-06 15:23:29 +00004273 }
drhd8b77e22014-09-06 01:35:57 +00004274 /* TUNING: If there is at least one equality constraint in the WHERE
4275 ** clause that does not have a likelihood() explicitly assigned to it
4276 ** then do not let the estimated number of output rows exceed half
4277 ** the number of rows in the table. */
4278 if( nEq && pLoop->nOut>nRow-10 ){
4279 pLoop->nOut = nRow - 10;
4280 }
drhcca9f3d2013-09-06 15:23:29 +00004281}
4282
4283/*
drhdbd94862014-07-23 23:57:42 +00004284** Adjust the cost C by the costMult facter T. This only occurs if
4285** compiled with -DSQLITE_ENABLE_COSTMULT
4286*/
4287#ifdef SQLITE_ENABLE_COSTMULT
4288# define ApplyCostMultiplier(C,T) C += T
4289#else
4290# define ApplyCostMultiplier(C,T)
4291#endif
4292
4293/*
dan4a6b8a02014-04-30 14:47:01 +00004294** We have so far matched pBuilder->pNew->u.btree.nEq terms of the
4295** index pIndex. Try to match one more.
4296**
4297** When this function is called, pBuilder->pNew->nOut contains the
4298** number of rows expected to be visited by filtering using the nEq
4299** terms only. If it is modified, this value is restored before this
4300** function returns.
drh1c8148f2013-05-04 20:25:23 +00004301**
4302** If pProbe->tnum==0, that means pIndex is a fake index used for the
4303** INTEGER PRIMARY KEY.
4304*/
drh5346e952013-05-08 14:14:26 +00004305static int whereLoopAddBtreeIndex(
drh1c8148f2013-05-04 20:25:23 +00004306 WhereLoopBuilder *pBuilder, /* The WhereLoop factory */
4307 struct SrcList_item *pSrc, /* FROM clause term being analyzed */
4308 Index *pProbe, /* An index on pSrc */
drhbf539c42013-10-05 18:16:02 +00004309 LogEst nInMul /* log(Number of iterations due to IN) */
drh1c8148f2013-05-04 20:25:23 +00004310){
drh70d18342013-06-06 19:16:33 +00004311 WhereInfo *pWInfo = pBuilder->pWInfo; /* WHERE analyse context */
4312 Parse *pParse = pWInfo->pParse; /* Parsing context */
4313 sqlite3 *db = pParse->db; /* Database connection malloc context */
drh1c8148f2013-05-04 20:25:23 +00004314 WhereLoop *pNew; /* Template WhereLoop under construction */
4315 WhereTerm *pTerm; /* A WhereTerm under consideration */
drh43fe25f2013-05-07 23:06:23 +00004316 int opMask; /* Valid operators for constraints */
drh1c8148f2013-05-04 20:25:23 +00004317 WhereScan scan; /* Iterator for WHERE terms */
drh4efc9292013-06-06 23:02:03 +00004318 Bitmask saved_prereq; /* Original value of pNew->prereq */
4319 u16 saved_nLTerm; /* Original value of pNew->nLTerm */
drhcd8629e2013-11-13 12:27:25 +00004320 u16 saved_nEq; /* Original value of pNew->u.btree.nEq */
drhc8bbce12014-10-21 01:05:09 +00004321 u16 saved_nSkip; /* Original value of pNew->nSkip */
drh4efc9292013-06-06 23:02:03 +00004322 u32 saved_wsFlags; /* Original value of pNew->wsFlags */
drhbf539c42013-10-05 18:16:02 +00004323 LogEst saved_nOut; /* Original value of pNew->nOut */
drha18f3d22013-05-08 03:05:41 +00004324 int iCol; /* Index of the column in the table */
drh5346e952013-05-08 14:14:26 +00004325 int rc = SQLITE_OK; /* Return code */
drhd8b77e22014-09-06 01:35:57 +00004326 LogEst rSize; /* Number of rows in the table */
drhbf539c42013-10-05 18:16:02 +00004327 LogEst rLogSize; /* Logarithm of table size */
drhc7f0d222013-06-19 03:27:12 +00004328 WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
drh1c8148f2013-05-04 20:25:23 +00004329
drh1c8148f2013-05-04 20:25:23 +00004330 pNew = pBuilder->pNew;
drh5346e952013-05-08 14:14:26 +00004331 if( db->mallocFailed ) return SQLITE_NOMEM;
drh1c8148f2013-05-04 20:25:23 +00004332
drh5346e952013-05-08 14:14:26 +00004333 assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
drh43fe25f2013-05-07 23:06:23 +00004334 assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
4335 if( pNew->wsFlags & WHERE_BTM_LIMIT ){
4336 opMask = WO_LT|WO_LE;
4337 }else if( pProbe->tnum<=0 || (pSrc->jointype & JT_LEFT)!=0 ){
4338 opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE;
drh1c8148f2013-05-04 20:25:23 +00004339 }else{
drh43fe25f2013-05-07 23:06:23 +00004340 opMask = WO_EQ|WO_IN|WO_ISNULL|WO_GT|WO_GE|WO_LT|WO_LE;
drh1c8148f2013-05-04 20:25:23 +00004341 }
drhef866372013-05-22 20:49:02 +00004342 if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
drh1c8148f2013-05-04 20:25:23 +00004343
dan39129ce2014-06-30 15:23:57 +00004344 assert( pNew->u.btree.nEq<pProbe->nColumn );
4345 iCol = pProbe->aiColumn[pNew->u.btree.nEq];
4346
drha18f3d22013-05-08 03:05:41 +00004347 pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, iCol,
drh0f133a42013-05-22 17:01:17 +00004348 opMask, pProbe);
drh4efc9292013-06-06 23:02:03 +00004349 saved_nEq = pNew->u.btree.nEq;
drhc8bbce12014-10-21 01:05:09 +00004350 saved_nSkip = pNew->nSkip;
drh4efc9292013-06-06 23:02:03 +00004351 saved_nLTerm = pNew->nLTerm;
4352 saved_wsFlags = pNew->wsFlags;
4353 saved_prereq = pNew->prereq;
4354 saved_nOut = pNew->nOut;
drhb8a8e8a2013-06-10 19:12:39 +00004355 pNew->rSetup = 0;
drhd8b77e22014-09-06 01:35:57 +00004356 rSize = pProbe->aiRowLogEst[0];
4357 rLogSize = estLog(rSize);
drh5346e952013-05-08 14:14:26 +00004358 for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
dan8ad1d8b2014-04-25 20:22:45 +00004359 u16 eOp = pTerm->eOperator; /* Shorthand for pTerm->eOperator */
danaa9933c2014-04-24 20:04:49 +00004360 LogEst rCostIdx;
dan8ad1d8b2014-04-25 20:22:45 +00004361 LogEst nOutUnadjusted; /* nOut before IN() and WHERE adjustments */
drhb8a8e8a2013-06-10 19:12:39 +00004362 int nIn = 0;
drh1435a9a2013-08-27 23:15:44 +00004363#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
dan7a419232013-08-06 20:01:43 +00004364 int nRecValid = pBuilder->nRecValid;
drhb5246e52013-07-08 21:12:57 +00004365#endif
dan8ad1d8b2014-04-25 20:22:45 +00004366 if( (eOp==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)
dan8bff07a2013-08-29 14:56:14 +00004367 && (iCol<0 || pSrc->pTab->aCol[iCol].notNull)
4368 ){
4369 continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */
4370 }
dan7a419232013-08-06 20:01:43 +00004371 if( pTerm->prereqRight & pNew->maskSelf ) continue;
4372
drh4efc9292013-06-06 23:02:03 +00004373 pNew->wsFlags = saved_wsFlags;
4374 pNew->u.btree.nEq = saved_nEq;
4375 pNew->nLTerm = saved_nLTerm;
4376 if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
4377 pNew->aLTerm[pNew->nLTerm++] = pTerm;
4378 pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
dan8ad1d8b2014-04-25 20:22:45 +00004379
4380 assert( nInMul==0
4381 || (pNew->wsFlags & WHERE_COLUMN_NULL)!=0
4382 || (pNew->wsFlags & WHERE_COLUMN_IN)!=0
4383 || (pNew->wsFlags & WHERE_SKIPSCAN)!=0
4384 );
4385
4386 if( eOp & WO_IN ){
drha18f3d22013-05-08 03:05:41 +00004387 Expr *pExpr = pTerm->pExpr;
4388 pNew->wsFlags |= WHERE_COLUMN_IN;
4389 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
drhe1e2e9a2013-06-13 15:16:53 +00004390 /* "x IN (SELECT ...)": TUNING: the SELECT returns 25 rows */
drhbf539c42013-10-05 18:16:02 +00004391 nIn = 46; assert( 46==sqlite3LogEst(25) );
drha18f3d22013-05-08 03:05:41 +00004392 }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
4393 /* "x IN (value, value, ...)" */
drhbf539c42013-10-05 18:16:02 +00004394 nIn = sqlite3LogEst(pExpr->x.pList->nExpr);
drhf1645f02013-05-07 19:44:38 +00004395 }
drh2b59b3a2014-03-20 13:26:47 +00004396 assert( nIn>0 ); /* RHS always has 2 or more terms... The parser
4397 ** changes "x IN (?)" into "x=?". */
dan8ad1d8b2014-04-25 20:22:45 +00004398
4399 }else if( eOp & (WO_EQ) ){
drha18f3d22013-05-08 03:05:41 +00004400 pNew->wsFlags |= WHERE_COLUMN_EQ;
dan8ad1d8b2014-04-25 20:22:45 +00004401 if( iCol<0 || (nInMul==0 && pNew->u.btree.nEq==pProbe->nKeyCol-1) ){
drh5f1d1d92014-07-31 22:59:04 +00004402 if( iCol>=0 && !IsUniqueIndex(pProbe) ){
drhe39a7322014-02-03 14:04:11 +00004403 pNew->wsFlags |= WHERE_UNQ_WANTED;
4404 }else{
4405 pNew->wsFlags |= WHERE_ONEROW;
4406 }
drh21f7ff72013-06-03 15:07:23 +00004407 }
dan2dd3cdc2014-04-26 20:21:14 +00004408 }else if( eOp & WO_ISNULL ){
4409 pNew->wsFlags |= WHERE_COLUMN_NULL;
dan8ad1d8b2014-04-25 20:22:45 +00004410 }else if( eOp & (WO_GT|WO_GE) ){
4411 testcase( eOp & WO_GT );
4412 testcase( eOp & WO_GE );
drha18f3d22013-05-08 03:05:41 +00004413 pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
drh6f2bfad2013-06-03 17:35:22 +00004414 pBtm = pTerm;
4415 pTop = 0;
dan2dd3cdc2014-04-26 20:21:14 +00004416 }else{
dan8ad1d8b2014-04-25 20:22:45 +00004417 assert( eOp & (WO_LT|WO_LE) );
4418 testcase( eOp & WO_LT );
4419 testcase( eOp & WO_LE );
drha18f3d22013-05-08 03:05:41 +00004420 pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
drh6f2bfad2013-06-03 17:35:22 +00004421 pTop = pTerm;
4422 pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
drh4efc9292013-06-06 23:02:03 +00004423 pNew->aLTerm[pNew->nLTerm-2] : 0;
drh1c8148f2013-05-04 20:25:23 +00004424 }
dan8ad1d8b2014-04-25 20:22:45 +00004425
4426 /* At this point pNew->nOut is set to the number of rows expected to
4427 ** be visited by the index scan before considering term pTerm, or the
4428 ** values of nIn and nInMul. In other words, assuming that all
4429 ** "x IN(...)" terms are replaced with "x = ?". This block updates
4430 ** the value of pNew->nOut to account for pTerm (but not nIn/nInMul). */
4431 assert( pNew->nOut==saved_nOut );
drh6f2bfad2013-06-03 17:35:22 +00004432 if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
danaa9933c2014-04-24 20:04:49 +00004433 /* Adjust nOut using stat3/stat4 data. Or, if there is no stat3/stat4
4434 ** data, using some other estimate. */
drh186ad8c2013-10-08 18:40:37 +00004435 whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew);
dan8ad1d8b2014-04-25 20:22:45 +00004436 }else{
4437 int nEq = ++pNew->u.btree.nEq;
4438 assert( eOp & (WO_ISNULL|WO_EQ|WO_IN) );
4439
4440 assert( pNew->nOut==saved_nOut );
dan09e1df62014-04-29 16:10:22 +00004441 if( pTerm->truthProb<=0 && iCol>=0 ){
dan8ad1d8b2014-04-25 20:22:45 +00004442 assert( (eOp & WO_IN) || nIn==0 );
drhc5f246e2014-05-01 20:24:21 +00004443 testcase( eOp & WO_IN );
dan8ad1d8b2014-04-25 20:22:45 +00004444 pNew->nOut += pTerm->truthProb;
4445 pNew->nOut -= nIn;
dan8ad1d8b2014-04-25 20:22:45 +00004446 }else{
drh1435a9a2013-08-27 23:15:44 +00004447#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
dan8ad1d8b2014-04-25 20:22:45 +00004448 tRowcnt nOut = 0;
4449 if( nInMul==0
4450 && pProbe->nSample
4451 && pNew->u.btree.nEq<=pProbe->nSampleCol
dan8ad1d8b2014-04-25 20:22:45 +00004452 && ((eOp & WO_IN)==0 || !ExprHasProperty(pTerm->pExpr, EP_xIsSelect))
dan8ad1d8b2014-04-25 20:22:45 +00004453 ){
4454 Expr *pExpr = pTerm->pExpr;
4455 if( (eOp & (WO_EQ|WO_ISNULL))!=0 ){
4456 testcase( eOp & WO_EQ );
4457 testcase( eOp & WO_ISNULL );
4458 rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut);
4459 }else{
4460 rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut);
4461 }
dan8ad1d8b2014-04-25 20:22:45 +00004462 if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
4463 if( rc!=SQLITE_OK ) break; /* Jump out of the pTerm loop */
4464 if( nOut ){
4465 pNew->nOut = sqlite3LogEst(nOut);
4466 if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut;
4467 pNew->nOut -= nIn;
4468 }
4469 }
4470 if( nOut==0 )
4471#endif
4472 {
4473 pNew->nOut += (pProbe->aiRowLogEst[nEq] - pProbe->aiRowLogEst[nEq-1]);
4474 if( eOp & WO_ISNULL ){
4475 /* TUNING: If there is no likelihood() value, assume that a
4476 ** "col IS NULL" expression matches twice as many rows
4477 ** as (col=?). */
4478 pNew->nOut += 10;
4479 }
4480 }
dan6cb8d762013-08-08 11:48:57 +00004481 }
drh6f2bfad2013-06-03 17:35:22 +00004482 }
dan8ad1d8b2014-04-25 20:22:45 +00004483
danaa9933c2014-04-24 20:04:49 +00004484 /* Set rCostIdx to the cost of visiting selected rows in index. Add
4485 ** it to pNew->rRun, which is currently set to the cost of the index
4486 ** seek only. Then, if this is a non-covering index, add the cost of
4487 ** visiting the rows in the main table. */
4488 rCostIdx = pNew->nOut + 1 + (15*pProbe->szIdxRow)/pSrc->pTab->szTabRow;
dan8ad1d8b2014-04-25 20:22:45 +00004489 pNew->rRun = sqlite3LogEstAdd(rLogSize, rCostIdx);
drhe217efc2013-06-12 03:48:41 +00004490 if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
danaa9933c2014-04-24 20:04:49 +00004491 pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut + 16);
drheb04de32013-05-10 15:16:30 +00004492 }
drhdbd94862014-07-23 23:57:42 +00004493 ApplyCostMultiplier(pNew->rRun, pProbe->pTable->costMult);
danaa9933c2014-04-24 20:04:49 +00004494
dan8ad1d8b2014-04-25 20:22:45 +00004495 nOutUnadjusted = pNew->nOut;
4496 pNew->rRun += nInMul + nIn;
4497 pNew->nOut += nInMul + nIn;
drhd8b77e22014-09-06 01:35:57 +00004498 whereLoopOutputAdjust(pBuilder->pWC, pNew, rSize);
drhcf8fa7a2013-05-10 20:26:22 +00004499 rc = whereLoopInsert(pBuilder, pNew);
dan440e6ff2014-04-28 08:49:54 +00004500
4501 if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
4502 pNew->nOut = saved_nOut;
4503 }else{
4504 pNew->nOut = nOutUnadjusted;
4505 }
dan8ad1d8b2014-04-25 20:22:45 +00004506
drh5346e952013-05-08 14:14:26 +00004507 if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
dan39129ce2014-06-30 15:23:57 +00004508 && pNew->u.btree.nEq<pProbe->nColumn
drh5346e952013-05-08 14:14:26 +00004509 ){
drhb8a8e8a2013-06-10 19:12:39 +00004510 whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
drha18f3d22013-05-08 03:05:41 +00004511 }
danad45ed72013-08-08 12:21:32 +00004512 pNew->nOut = saved_nOut;
drh1435a9a2013-08-27 23:15:44 +00004513#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
dan7a419232013-08-06 20:01:43 +00004514 pBuilder->nRecValid = nRecValid;
dan7a419232013-08-06 20:01:43 +00004515#endif
drh1c8148f2013-05-04 20:25:23 +00004516 }
drh4efc9292013-06-06 23:02:03 +00004517 pNew->prereq = saved_prereq;
4518 pNew->u.btree.nEq = saved_nEq;
drhc8bbce12014-10-21 01:05:09 +00004519 pNew->nSkip = saved_nSkip;
drh4efc9292013-06-06 23:02:03 +00004520 pNew->wsFlags = saved_wsFlags;
4521 pNew->nOut = saved_nOut;
4522 pNew->nLTerm = saved_nLTerm;
drhc8bbce12014-10-21 01:05:09 +00004523
4524 /* Consider using a skip-scan if there are no WHERE clause constraints
4525 ** available for the left-most terms of the index, and if the average
4526 ** number of repeats in the left-most terms is at least 18.
4527 **
4528 ** The magic number 18 is selected on the basis that scanning 17 rows
4529 ** is almost always quicker than an index seek (even though if the index
4530 ** contains fewer than 2^17 rows we assume otherwise in other parts of
4531 ** the code). And, even if it is not, it should not be too much slower.
4532 ** On the other hand, the extra seeks could end up being significantly
4533 ** more expensive. */
4534 assert( 42==sqlite3LogEst(18) );
4535 if( saved_nEq==saved_nSkip
4536 && saved_nEq+1<pProbe->nKeyCol
4537 && pProbe->aiRowLogEst[saved_nEq+1]>=42 /* TUNING: Minimum for skip-scan */
4538 && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK
4539 ){
4540 LogEst nIter;
4541 pNew->u.btree.nEq++;
4542 pNew->nSkip++;
4543 pNew->aLTerm[pNew->nLTerm++] = 0;
4544 pNew->wsFlags |= WHERE_SKIPSCAN;
4545 nIter = pProbe->aiRowLogEst[saved_nEq] - pProbe->aiRowLogEst[saved_nEq+1];
drhc8bbce12014-10-21 01:05:09 +00004546 pNew->nOut -= nIter;
4547 /* TUNING: Because uncertainties in the estimates for skip-scan queries,
4548 ** add a 1.375 fudge factor to make skip-scan slightly less likely. */
4549 nIter += 5;
4550 whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nIter + nInMul);
4551 pNew->nOut = saved_nOut;
4552 pNew->u.btree.nEq = saved_nEq;
4553 pNew->nSkip = saved_nSkip;
4554 pNew->wsFlags = saved_wsFlags;
4555 }
4556
drh5346e952013-05-08 14:14:26 +00004557 return rc;
drh1c8148f2013-05-04 20:25:23 +00004558}
4559
4560/*
drh23f98da2013-05-21 15:52:07 +00004561** Return True if it is possible that pIndex might be useful in
4562** implementing the ORDER BY clause in pBuilder.
4563**
4564** Return False if pBuilder does not contain an ORDER BY clause or
4565** if there is no way for pIndex to be useful in implementing that
4566** ORDER BY clause.
4567*/
4568static int indexMightHelpWithOrderBy(
4569 WhereLoopBuilder *pBuilder,
4570 Index *pIndex,
4571 int iCursor
4572){
4573 ExprList *pOB;
drh6d381472013-06-13 17:58:08 +00004574 int ii, jj;
drh23f98da2013-05-21 15:52:07 +00004575
drh53cfbe92013-06-13 17:28:22 +00004576 if( pIndex->bUnordered ) return 0;
drh70d18342013-06-06 19:16:33 +00004577 if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
drh23f98da2013-05-21 15:52:07 +00004578 for(ii=0; ii<pOB->nExpr; ii++){
drh45c154a2013-06-03 20:46:35 +00004579 Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr);
drh23f98da2013-05-21 15:52:07 +00004580 if( pExpr->op!=TK_COLUMN ) return 0;
4581 if( pExpr->iTable==iCursor ){
drh137fd4f2014-09-19 02:01:37 +00004582 if( pExpr->iColumn<0 ) return 1;
drhbbbdc832013-10-22 18:01:40 +00004583 for(jj=0; jj<pIndex->nKeyCol; jj++){
drh6d381472013-06-13 17:58:08 +00004584 if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
4585 }
drh23f98da2013-05-21 15:52:07 +00004586 }
4587 }
4588 return 0;
4589}
4590
4591/*
drh92a121f2013-06-10 12:15:47 +00004592** Return a bitmask where 1s indicate that the corresponding column of
4593** the table is used by an index. Only the first 63 columns are considered.
4594*/
drhfd5874d2013-06-12 14:52:39 +00004595static Bitmask columnsInIndex(Index *pIdx){
drh92a121f2013-06-10 12:15:47 +00004596 Bitmask m = 0;
4597 int j;
drhec95c442013-10-23 01:57:32 +00004598 for(j=pIdx->nColumn-1; j>=0; j--){
drh92a121f2013-06-10 12:15:47 +00004599 int x = pIdx->aiColumn[j];
drhec95c442013-10-23 01:57:32 +00004600 if( x>=0 ){
4601 testcase( x==BMS-1 );
4602 testcase( x==BMS-2 );
4603 if( x<BMS-1 ) m |= MASKBIT(x);
4604 }
drh92a121f2013-06-10 12:15:47 +00004605 }
4606 return m;
4607}
4608
drh4bd5f732013-07-31 23:22:39 +00004609/* Check to see if a partial index with pPartIndexWhere can be used
4610** in the current query. Return true if it can be and false if not.
4611*/
4612static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere){
4613 int i;
4614 WhereTerm *pTerm;
4615 for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
4616 if( sqlite3ExprImpliesExpr(pTerm->pExpr, pWhere, iTab) ) return 1;
4617 }
4618 return 0;
4619}
drh92a121f2013-06-10 12:15:47 +00004620
4621/*
dan51576f42013-07-02 10:06:15 +00004622** Add all WhereLoop objects for a single table of the join where the table
drh0823c892013-05-11 00:06:23 +00004623** is idenfied by pBuilder->pNew->iTab. That table is guaranteed to be
4624** a b-tree table, not a virtual table.
dan81647222014-04-30 15:00:16 +00004625**
4626** The costs (WhereLoop.rRun) of the b-tree loops added by this function
4627** are calculated as follows:
4628**
4629** For a full scan, assuming the table (or index) contains nRow rows:
4630**
4631** cost = nRow * 3.0 // full-table scan
4632** cost = nRow * K // scan of covering index
4633** cost = nRow * (K+3.0) // scan of non-covering index
4634**
4635** where K is a value between 1.1 and 3.0 set based on the relative
4636** estimated average size of the index and table records.
4637**
4638** For an index scan, where nVisit is the number of index rows visited
4639** by the scan, and nSeek is the number of seek operations required on
4640** the index b-tree:
4641**
4642** cost = nSeek * (log(nRow) + K * nVisit) // covering index
4643** cost = nSeek * (log(nRow) + (K+3.0) * nVisit) // non-covering index
4644**
4645** Normally, nSeek is 1. nSeek values greater than 1 come about if the
4646** WHERE clause includes "x IN (....)" terms used in place of "x=?". Or when
4647** implicit "x IN (SELECT x FROM tbl)" terms are added for skip-scans.
drh83a305f2014-07-22 12:05:32 +00004648**
4649** The estimated values (nRow, nVisit, nSeek) often contain a large amount
4650** of uncertainty. For this reason, scoring is designed to pick plans that
4651** "do the least harm" if the estimates are inaccurate. For example, a
4652** log(nRow) factor is omitted from a non-covering index scan in order to
4653** bias the scoring in favor of using an index, since the worst-case
4654** performance of using an index is far better than the worst-case performance
4655** of a full table scan.
drhf1b5f5b2013-05-02 00:15:01 +00004656*/
drh5346e952013-05-08 14:14:26 +00004657static int whereLoopAddBtree(
drh1c8148f2013-05-04 20:25:23 +00004658 WhereLoopBuilder *pBuilder, /* WHERE clause information */
drh1c8148f2013-05-04 20:25:23 +00004659 Bitmask mExtra /* Extra prerequesites for using this table */
drhf1b5f5b2013-05-02 00:15:01 +00004660){
drh70d18342013-06-06 19:16:33 +00004661 WhereInfo *pWInfo; /* WHERE analysis context */
drh1c8148f2013-05-04 20:25:23 +00004662 Index *pProbe; /* An index we are evaluating */
drh1c8148f2013-05-04 20:25:23 +00004663 Index sPk; /* A fake index object for the primary key */
dancfc9df72014-04-25 15:01:01 +00004664 LogEst aiRowEstPk[2]; /* The aiRowLogEst[] value for the sPk index */
drhbbbdc832013-10-22 18:01:40 +00004665 i16 aiColumnPk = -1; /* The aColumn[] value for the sPk index */
drh70d18342013-06-06 19:16:33 +00004666 SrcList *pTabList; /* The FROM clause */
drh1c8148f2013-05-04 20:25:23 +00004667 struct SrcList_item *pSrc; /* The FROM clause btree term to add */
drh1c8148f2013-05-04 20:25:23 +00004668 WhereLoop *pNew; /* Template WhereLoop object */
drh5346e952013-05-08 14:14:26 +00004669 int rc = SQLITE_OK; /* Return code */
drhd044d202013-05-31 12:43:55 +00004670 int iSortIdx = 1; /* Index number */
drh23f98da2013-05-21 15:52:07 +00004671 int b; /* A boolean value */
drhbf539c42013-10-05 18:16:02 +00004672 LogEst rSize; /* number of rows in the table */
4673 LogEst rLogSize; /* Logarithm of the number of rows in the table */
drh4bd5f732013-07-31 23:22:39 +00004674 WhereClause *pWC; /* The parsed WHERE clause */
drh3495d202013-10-07 17:32:15 +00004675 Table *pTab; /* Table being queried */
drh23f98da2013-05-21 15:52:07 +00004676
drh1c8148f2013-05-04 20:25:23 +00004677 pNew = pBuilder->pNew;
drh70d18342013-06-06 19:16:33 +00004678 pWInfo = pBuilder->pWInfo;
4679 pTabList = pWInfo->pTabList;
4680 pSrc = pTabList->a + pNew->iTab;
drh3495d202013-10-07 17:32:15 +00004681 pTab = pSrc->pTab;
drh4bd5f732013-07-31 23:22:39 +00004682 pWC = pBuilder->pWC;
drh0823c892013-05-11 00:06:23 +00004683 assert( !IsVirtual(pSrc->pTab) );
drh1c8148f2013-05-04 20:25:23 +00004684
4685 if( pSrc->pIndex ){
4686 /* An INDEXED BY clause specifies a particular index to use */
4687 pProbe = pSrc->pIndex;
drhec95c442013-10-23 01:57:32 +00004688 }else if( !HasRowid(pTab) ){
4689 pProbe = pTab->pIndex;
drh1c8148f2013-05-04 20:25:23 +00004690 }else{
4691 /* There is no INDEXED BY clause. Create a fake Index object in local
4692 ** variable sPk to represent the rowid primary key index. Make this
4693 ** fake index the first in a chain of Index objects with all of the real
4694 ** indices to follow */
4695 Index *pFirst; /* First of real indices on the table */
4696 memset(&sPk, 0, sizeof(Index));
drhbbbdc832013-10-22 18:01:40 +00004697 sPk.nKeyCol = 1;
dan39129ce2014-06-30 15:23:57 +00004698 sPk.nColumn = 1;
drh1c8148f2013-05-04 20:25:23 +00004699 sPk.aiColumn = &aiColumnPk;
dancfc9df72014-04-25 15:01:01 +00004700 sPk.aiRowLogEst = aiRowEstPk;
drh1c8148f2013-05-04 20:25:23 +00004701 sPk.onError = OE_Replace;
drh3495d202013-10-07 17:32:15 +00004702 sPk.pTable = pTab;
danaa9933c2014-04-24 20:04:49 +00004703 sPk.szIdxRow = pTab->szTabRow;
dancfc9df72014-04-25 15:01:01 +00004704 aiRowEstPk[0] = pTab->nRowLogEst;
4705 aiRowEstPk[1] = 0;
drh1c8148f2013-05-04 20:25:23 +00004706 pFirst = pSrc->pTab->pIndex;
4707 if( pSrc->notIndexed==0 ){
4708 /* The real indices of the table are only considered if the
4709 ** NOT INDEXED qualifier is omitted from the FROM clause */
4710 sPk.pNext = pFirst;
4711 }
4712 pProbe = &sPk;
4713 }
dancfc9df72014-04-25 15:01:01 +00004714 rSize = pTab->nRowLogEst;
drheb04de32013-05-10 15:16:30 +00004715 rLogSize = estLog(rSize);
4716
drhfeb56e02013-08-23 17:33:46 +00004717#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
drheb04de32013-05-10 15:16:30 +00004718 /* Automatic indexes */
drhaa32e3c2013-07-16 21:31:23 +00004719 if( !pBuilder->pOrSet
drh4fe425a2013-06-12 17:08:06 +00004720 && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
4721 && pSrc->pIndex==0
drheb04de32013-05-10 15:16:30 +00004722 && !pSrc->viaCoroutine
4723 && !pSrc->notIndexed
drhec95c442013-10-23 01:57:32 +00004724 && HasRowid(pTab)
drheb04de32013-05-10 15:16:30 +00004725 && !pSrc->isCorrelated
dan62ba4e42014-01-15 18:21:41 +00004726 && !pSrc->isRecursive
drheb04de32013-05-10 15:16:30 +00004727 ){
4728 /* Generate auto-index WhereLoops */
drheb04de32013-05-10 15:16:30 +00004729 WhereTerm *pTerm;
4730 WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
4731 for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
drh79a13bf2013-05-31 20:28:28 +00004732 if( pTerm->prereqRight & pNew->maskSelf ) continue;
drheb04de32013-05-10 15:16:30 +00004733 if( termCanDriveIndex(pTerm, pSrc, 0) ){
4734 pNew->u.btree.nEq = 1;
drhc8bbce12014-10-21 01:05:09 +00004735 pNew->nSkip = 0;
drhef866372013-05-22 20:49:02 +00004736 pNew->u.btree.pIndex = 0;
drh4efc9292013-06-06 23:02:03 +00004737 pNew->nLTerm = 1;
4738 pNew->aLTerm[0] = pTerm;
drhe1e2e9a2013-06-13 15:16:53 +00004739 /* TUNING: One-time cost for computing the automatic index is
drh7e074332014-09-22 14:30:51 +00004740 ** estimated to be X*N*log2(N) where N is the number of rows in
4741 ** the table being indexed and where X is 7 (LogEst=28) for normal
4742 ** tables or 1.375 (LogEst=4) for views and subqueries. The value
4743 ** of X is smaller for views and subqueries so that the query planner
4744 ** will be more aggressive about generating automatic indexes for
4745 ** those objects, since there is no opportunity to add schema
4746 ** indexes on subqueries and views. */
4747 pNew->rSetup = rLogSize + rSize + 4;
4748 if( pTab->pSelect==0 && (pTab->tabFlags & TF_Ephemeral)==0 ){
4749 pNew->rSetup += 24;
4750 }
drhdbd94862014-07-23 23:57:42 +00004751 ApplyCostMultiplier(pNew->rSetup, pTab->costMult);
drh986b3872013-06-28 21:12:20 +00004752 /* TUNING: Each index lookup yields 20 rows in the table. This
4753 ** is more than the usual guess of 10 rows, since we have no way
peter.d.reid60ec9142014-09-06 16:39:46 +00004754 ** of knowing how selective the index will ultimately be. It would
drh986b3872013-06-28 21:12:20 +00004755 ** not be unreasonable to make this value much larger. */
drhbf539c42013-10-05 18:16:02 +00004756 pNew->nOut = 43; assert( 43==sqlite3LogEst(20) );
drhb50596d2013-10-08 20:42:41 +00004757 pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut);
drh986b3872013-06-28 21:12:20 +00004758 pNew->wsFlags = WHERE_AUTO_INDEX;
drheb04de32013-05-10 15:16:30 +00004759 pNew->prereq = mExtra | pTerm->prereqRight;
drhcf8fa7a2013-05-10 20:26:22 +00004760 rc = whereLoopInsert(pBuilder, pNew);
drheb04de32013-05-10 15:16:30 +00004761 }
4762 }
4763 }
drhfeb56e02013-08-23 17:33:46 +00004764#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
drh1c8148f2013-05-04 20:25:23 +00004765
4766 /* Loop over all indices
4767 */
drh23f98da2013-05-21 15:52:07 +00004768 for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){
drh4bd5f732013-07-31 23:22:39 +00004769 if( pProbe->pPartIdxWhere!=0
dan08291692014-08-27 17:37:20 +00004770 && !whereUsablePartialIndex(pSrc->iCursor, pWC, pProbe->pPartIdxWhere) ){
4771 testcase( pNew->iTab!=pSrc->iCursor ); /* See ticket [98d973b8f5] */
drh4bd5f732013-07-31 23:22:39 +00004772 continue; /* Partial index inappropriate for this query */
4773 }
dan7de2a1f2014-04-28 20:11:20 +00004774 rSize = pProbe->aiRowLogEst[0];
drh5346e952013-05-08 14:14:26 +00004775 pNew->u.btree.nEq = 0;
drhc8bbce12014-10-21 01:05:09 +00004776 pNew->nSkip = 0;
drh4efc9292013-06-06 23:02:03 +00004777 pNew->nLTerm = 0;
drh23f98da2013-05-21 15:52:07 +00004778 pNew->iSortIdx = 0;
drhb8a8e8a2013-06-10 19:12:39 +00004779 pNew->rSetup = 0;
drh23f98da2013-05-21 15:52:07 +00004780 pNew->prereq = mExtra;
drh74f91d42013-06-19 18:01:44 +00004781 pNew->nOut = rSize;
drh23f98da2013-05-21 15:52:07 +00004782 pNew->u.btree.pIndex = pProbe;
4783 b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
drh53cfbe92013-06-13 17:28:22 +00004784 /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
4785 assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
drh43fe25f2013-05-07 23:06:23 +00004786 if( pProbe->tnum<=0 ){
4787 /* Integer primary key index */
4788 pNew->wsFlags = WHERE_IPK;
drh23f98da2013-05-21 15:52:07 +00004789
4790 /* Full table scan */
drhd044d202013-05-31 12:43:55 +00004791 pNew->iSortIdx = b ? iSortIdx : 0;
danaa9933c2014-04-24 20:04:49 +00004792 /* TUNING: Cost of full table scan is (N*3.0). */
4793 pNew->rRun = rSize + 16;
drhdbd94862014-07-23 23:57:42 +00004794 ApplyCostMultiplier(pNew->rRun, pTab->costMult);
drhd8b77e22014-09-06 01:35:57 +00004795 whereLoopOutputAdjust(pWC, pNew, rSize);
drh23f98da2013-05-21 15:52:07 +00004796 rc = whereLoopInsert(pBuilder, pNew);
drhcca9f3d2013-09-06 15:23:29 +00004797 pNew->nOut = rSize;
drh23f98da2013-05-21 15:52:07 +00004798 if( rc ) break;
drh43fe25f2013-05-07 23:06:23 +00004799 }else{
drhec95c442013-10-23 01:57:32 +00004800 Bitmask m;
4801 if( pProbe->isCovering ){
4802 pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
4803 m = 0;
4804 }else{
4805 m = pSrc->colUsed & ~columnsInIndex(pProbe);
4806 pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
4807 }
drh1c8148f2013-05-04 20:25:23 +00004808
drh23f98da2013-05-21 15:52:07 +00004809 /* Full scan via index */
drh53cfbe92013-06-13 17:28:22 +00004810 if( b
drh702ba9f2013-11-07 21:25:13 +00004811 || !HasRowid(pTab)
drh53cfbe92013-06-13 17:28:22 +00004812 || ( m==0
4813 && pProbe->bUnordered==0
drh702ba9f2013-11-07 21:25:13 +00004814 && (pProbe->szIdxRow<pTab->szTabRow)
drh53cfbe92013-06-13 17:28:22 +00004815 && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
4816 && sqlite3GlobalConfig.bUseCis
4817 && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
4818 )
drhe3b7c922013-06-03 19:17:40 +00004819 ){
drh23f98da2013-05-21 15:52:07 +00004820 pNew->iSortIdx = b ? iSortIdx : 0;
danaa9933c2014-04-24 20:04:49 +00004821
4822 /* The cost of visiting the index rows is N*K, where K is
4823 ** between 1.1 and 3.0, depending on the relative sizes of the
4824 ** index and table rows. If this is a non-covering index scan,
4825 ** also add the cost of visiting table rows (N*3.0). */
4826 pNew->rRun = rSize + 1 + (15*pProbe->szIdxRow)/pTab->szTabRow;
4827 if( m!=0 ){
4828 pNew->rRun = sqlite3LogEstAdd(pNew->rRun, rSize+16);
drhe1e2e9a2013-06-13 15:16:53 +00004829 }
drhdbd94862014-07-23 23:57:42 +00004830 ApplyCostMultiplier(pNew->rRun, pTab->costMult);
drhd8b77e22014-09-06 01:35:57 +00004831 whereLoopOutputAdjust(pWC, pNew, rSize);
drh23f98da2013-05-21 15:52:07 +00004832 rc = whereLoopInsert(pBuilder, pNew);
drhcca9f3d2013-09-06 15:23:29 +00004833 pNew->nOut = rSize;
drh23f98da2013-05-21 15:52:07 +00004834 if( rc ) break;
4835 }
4836 }
dan7a419232013-08-06 20:01:43 +00004837
drhb8a8e8a2013-06-10 19:12:39 +00004838 rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
drh1435a9a2013-08-27 23:15:44 +00004839#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
dan87cd9322013-08-07 15:52:41 +00004840 sqlite3Stat4ProbeFree(pBuilder->pRec);
4841 pBuilder->nRecValid = 0;
4842 pBuilder->pRec = 0;
danddc2d6e2013-08-06 20:15:06 +00004843#endif
drh1c8148f2013-05-04 20:25:23 +00004844
4845 /* If there was an INDEXED BY clause, then only that one index is
4846 ** considered. */
4847 if( pSrc->pIndex ) break;
4848 }
drh5346e952013-05-08 14:14:26 +00004849 return rc;
drhf1b5f5b2013-05-02 00:15:01 +00004850}
4851
drh8636e9c2013-06-11 01:50:08 +00004852#ifndef SQLITE_OMIT_VIRTUALTABLE
drhf1b5f5b2013-05-02 00:15:01 +00004853/*
drh0823c892013-05-11 00:06:23 +00004854** Add all WhereLoop objects for a table of the join identified by
4855** pBuilder->pNew->iTab. That table is guaranteed to be a virtual table.
drhf1b5f5b2013-05-02 00:15:01 +00004856*/
drh5346e952013-05-08 14:14:26 +00004857static int whereLoopAddVirtual(
danff4b23b2013-11-12 12:17:16 +00004858 WhereLoopBuilder *pBuilder, /* WHERE clause information */
4859 Bitmask mExtra
drhf1b5f5b2013-05-02 00:15:01 +00004860){
drh70d18342013-06-06 19:16:33 +00004861 WhereInfo *pWInfo; /* WHERE analysis context */
drh5346e952013-05-08 14:14:26 +00004862 Parse *pParse; /* The parsing context */
4863 WhereClause *pWC; /* The WHERE clause */
4864 struct SrcList_item *pSrc; /* The FROM clause term to search */
4865 Table *pTab;
4866 sqlite3 *db;
4867 sqlite3_index_info *pIdxInfo;
4868 struct sqlite3_index_constraint *pIdxCons;
4869 struct sqlite3_index_constraint_usage *pUsage;
4870 WhereTerm *pTerm;
4871 int i, j;
4872 int iTerm, mxTerm;
drh4efc9292013-06-06 23:02:03 +00004873 int nConstraint;
drh5346e952013-05-08 14:14:26 +00004874 int seenIn = 0; /* True if an IN operator is seen */
4875 int seenVar = 0; /* True if a non-constant constraint is seen */
4876 int iPhase; /* 0: const w/o IN, 1: const, 2: no IN, 2: IN */
4877 WhereLoop *pNew;
drh5346e952013-05-08 14:14:26 +00004878 int rc = SQLITE_OK;
4879
drh70d18342013-06-06 19:16:33 +00004880 pWInfo = pBuilder->pWInfo;
4881 pParse = pWInfo->pParse;
drh5346e952013-05-08 14:14:26 +00004882 db = pParse->db;
4883 pWC = pBuilder->pWC;
drh5346e952013-05-08 14:14:26 +00004884 pNew = pBuilder->pNew;
drh70d18342013-06-06 19:16:33 +00004885 pSrc = &pWInfo->pTabList->a[pNew->iTab];
drhb2a90f02013-05-10 03:30:49 +00004886 pTab = pSrc->pTab;
drh0823c892013-05-11 00:06:23 +00004887 assert( IsVirtual(pTab) );
drhb2a90f02013-05-10 03:30:49 +00004888 pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pBuilder->pOrderBy);
drh5346e952013-05-08 14:14:26 +00004889 if( pIdxInfo==0 ) return SQLITE_NOMEM;
drh5346e952013-05-08 14:14:26 +00004890 pNew->prereq = 0;
drh5346e952013-05-08 14:14:26 +00004891 pNew->rSetup = 0;
4892 pNew->wsFlags = WHERE_VIRTUALTABLE;
drh4efc9292013-06-06 23:02:03 +00004893 pNew->nLTerm = 0;
drh5346e952013-05-08 14:14:26 +00004894 pNew->u.vtab.needFree = 0;
4895 pUsage = pIdxInfo->aConstraintUsage;
drh4efc9292013-06-06 23:02:03 +00004896 nConstraint = pIdxInfo->nConstraint;
drh7963b0e2013-06-17 21:37:40 +00004897 if( whereLoopResize(db, pNew, nConstraint) ){
4898 sqlite3DbFree(db, pIdxInfo);
4899 return SQLITE_NOMEM;
4900 }
drh5346e952013-05-08 14:14:26 +00004901
drh0823c892013-05-11 00:06:23 +00004902 for(iPhase=0; iPhase<=3; iPhase++){
drh5346e952013-05-08 14:14:26 +00004903 if( !seenIn && (iPhase&1)!=0 ){
4904 iPhase++;
4905 if( iPhase>3 ) break;
4906 }
4907 if( !seenVar && iPhase>1 ) break;
4908 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
4909 for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
4910 j = pIdxCons->iTermOffset;
4911 pTerm = &pWC->a[j];
4912 switch( iPhase ){
4913 case 0: /* Constants without IN operator */
4914 pIdxCons->usable = 0;
4915 if( (pTerm->eOperator & WO_IN)!=0 ){
4916 seenIn = 1;
drh7963b0e2013-06-17 21:37:40 +00004917 }
4918 if( pTerm->prereqRight!=0 ){
drh5346e952013-05-08 14:14:26 +00004919 seenVar = 1;
drh7963b0e2013-06-17 21:37:40 +00004920 }else if( (pTerm->eOperator & WO_IN)==0 ){
drh5346e952013-05-08 14:14:26 +00004921 pIdxCons->usable = 1;
4922 }
4923 break;
4924 case 1: /* Constants with IN operators */
4925 assert( seenIn );
4926 pIdxCons->usable = (pTerm->prereqRight==0);
4927 break;
4928 case 2: /* Variables without IN */
4929 assert( seenVar );
4930 pIdxCons->usable = (pTerm->eOperator & WO_IN)==0;
4931 break;
4932 default: /* Variables with IN */
4933 assert( seenVar && seenIn );
4934 pIdxCons->usable = 1;
4935 break;
4936 }
4937 }
4938 memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
4939 if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
4940 pIdxInfo->idxStr = 0;
4941 pIdxInfo->idxNum = 0;
4942 pIdxInfo->needToFreeIdxStr = 0;
4943 pIdxInfo->orderByConsumed = 0;
drh8636e9c2013-06-11 01:50:08 +00004944 pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
dana9f58152013-11-11 19:01:33 +00004945 pIdxInfo->estimatedRows = 25;
drh5346e952013-05-08 14:14:26 +00004946 rc = vtabBestIndex(pParse, pTab, pIdxInfo);
4947 if( rc ) goto whereLoopAddVtab_exit;
4948 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
danff4b23b2013-11-12 12:17:16 +00004949 pNew->prereq = mExtra;
drhc718f1c2013-05-08 20:05:58 +00004950 mxTerm = -1;
drh4efc9292013-06-06 23:02:03 +00004951 assert( pNew->nLSlot>=nConstraint );
4952 for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
drh3bd26f02013-05-24 14:52:03 +00004953 pNew->u.vtab.omitMask = 0;
drh4efc9292013-06-06 23:02:03 +00004954 for(i=0; i<nConstraint; i++, pIdxCons++){
drh5346e952013-05-08 14:14:26 +00004955 if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
4956 j = pIdxCons->iTermOffset;
drh4efc9292013-06-06 23:02:03 +00004957 if( iTerm>=nConstraint
drh5346e952013-05-08 14:14:26 +00004958 || j<0
4959 || j>=pWC->nTerm
drh4efc9292013-06-06 23:02:03 +00004960 || pNew->aLTerm[iTerm]!=0
drh5346e952013-05-08 14:14:26 +00004961 ){
4962 rc = SQLITE_ERROR;
4963 sqlite3ErrorMsg(pParse, "%s.xBestIndex() malfunction", pTab->zName);
4964 goto whereLoopAddVtab_exit;
4965 }
drh7963b0e2013-06-17 21:37:40 +00004966 testcase( iTerm==nConstraint-1 );
4967 testcase( j==0 );
4968 testcase( j==pWC->nTerm-1 );
drh5346e952013-05-08 14:14:26 +00004969 pTerm = &pWC->a[j];
4970 pNew->prereq |= pTerm->prereqRight;
drh4efc9292013-06-06 23:02:03 +00004971 assert( iTerm<pNew->nLSlot );
4972 pNew->aLTerm[iTerm] = pTerm;
drh5346e952013-05-08 14:14:26 +00004973 if( iTerm>mxTerm ) mxTerm = iTerm;
drh7963b0e2013-06-17 21:37:40 +00004974 testcase( iTerm==15 );
4975 testcase( iTerm==16 );
drh52986302013-06-03 16:03:16 +00004976 if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm;
drh5346e952013-05-08 14:14:26 +00004977 if( (pTerm->eOperator & WO_IN)!=0 ){
4978 if( pUsage[i].omit==0 ){
4979 /* Do not attempt to use an IN constraint if the virtual table
4980 ** says that the equivalent EQ constraint cannot be safely omitted.
4981 ** If we do attempt to use such a constraint, some rows might be
4982 ** repeated in the output. */
4983 break;
4984 }
4985 /* A virtual table that is constrained by an IN clause may not
4986 ** consume the ORDER BY clause because (1) the order of IN terms
4987 ** is not necessarily related to the order of output terms and
4988 ** (2) Multiple outputs from a single IN value will not merge
4989 ** together. */
4990 pIdxInfo->orderByConsumed = 0;
4991 }
4992 }
4993 }
drh4efc9292013-06-06 23:02:03 +00004994 if( i>=nConstraint ){
4995 pNew->nLTerm = mxTerm+1;
4996 assert( pNew->nLTerm<=pNew->nLSlot );
drh5346e952013-05-08 14:14:26 +00004997 pNew->u.vtab.idxNum = pIdxInfo->idxNum;
4998 pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
4999 pIdxInfo->needToFreeIdxStr = 0;
5000 pNew->u.vtab.idxStr = pIdxInfo->idxStr;
drh0401ace2014-03-18 15:30:27 +00005001 pNew->u.vtab.isOrdered = (i8)(pIdxInfo->orderByConsumed ?
5002 pIdxInfo->nOrderBy : 0);
drhb8a8e8a2013-06-10 19:12:39 +00005003 pNew->rSetup = 0;
drhb50596d2013-10-08 20:42:41 +00005004 pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost);
dana9f58152013-11-11 19:01:33 +00005005 pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows);
drhcf8fa7a2013-05-10 20:26:22 +00005006 whereLoopInsert(pBuilder, pNew);
drh5346e952013-05-08 14:14:26 +00005007 if( pNew->u.vtab.needFree ){
5008 sqlite3_free(pNew->u.vtab.idxStr);
5009 pNew->u.vtab.needFree = 0;
5010 }
5011 }
5012 }
5013
5014whereLoopAddVtab_exit:
5015 if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
5016 sqlite3DbFree(db, pIdxInfo);
5017 return rc;
drhf1b5f5b2013-05-02 00:15:01 +00005018}
drh8636e9c2013-06-11 01:50:08 +00005019#endif /* SQLITE_OMIT_VIRTUALTABLE */
drhf1b5f5b2013-05-02 00:15:01 +00005020
5021/*
drhcf8fa7a2013-05-10 20:26:22 +00005022** Add WhereLoop entries to handle OR terms. This works for either
5023** btrees or virtual tables.
5024*/
5025static int whereLoopAddOr(WhereLoopBuilder *pBuilder, Bitmask mExtra){
drh70d18342013-06-06 19:16:33 +00005026 WhereInfo *pWInfo = pBuilder->pWInfo;
drhcf8fa7a2013-05-10 20:26:22 +00005027 WhereClause *pWC;
5028 WhereLoop *pNew;
5029 WhereTerm *pTerm, *pWCEnd;
5030 int rc = SQLITE_OK;
5031 int iCur;
5032 WhereClause tempWC;
5033 WhereLoopBuilder sSubBuild;
dan5da73e12014-04-30 18:11:55 +00005034 WhereOrSet sSum, sCur;
drhcf8fa7a2013-05-10 20:26:22 +00005035 struct SrcList_item *pItem;
5036
drhcf8fa7a2013-05-10 20:26:22 +00005037 pWC = pBuilder->pWC;
drhcf8fa7a2013-05-10 20:26:22 +00005038 pWCEnd = pWC->a + pWC->nTerm;
5039 pNew = pBuilder->pNew;
drh77dfd5b2013-08-19 11:15:48 +00005040 memset(&sSum, 0, sizeof(sSum));
drh186ad8c2013-10-08 18:40:37 +00005041 pItem = pWInfo->pTabList->a + pNew->iTab;
5042 iCur = pItem->iCursor;
drhcf8fa7a2013-05-10 20:26:22 +00005043
5044 for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
5045 if( (pTerm->eOperator & WO_OR)!=0
5046 && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
5047 ){
5048 WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
5049 WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
5050 WhereTerm *pOrTerm;
drhaa32e3c2013-07-16 21:31:23 +00005051 int once = 1;
5052 int i, j;
drh783dece2013-06-05 17:53:43 +00005053
drh783dece2013-06-05 17:53:43 +00005054 sSubBuild = *pBuilder;
5055 sSubBuild.pOrderBy = 0;
drhaa32e3c2013-07-16 21:31:23 +00005056 sSubBuild.pOrSet = &sCur;
drhcf8fa7a2013-05-10 20:26:22 +00005057
drh0a99ba32014-09-30 17:03:35 +00005058 WHERETRACE(0x200, ("Begin processing OR-clause %p\n", pTerm));
drhc7f0d222013-06-19 03:27:12 +00005059 for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
drh783dece2013-06-05 17:53:43 +00005060 if( (pOrTerm->eOperator & WO_AND)!=0 ){
drhcf8fa7a2013-05-10 20:26:22 +00005061 sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
5062 }else if( pOrTerm->leftCursor==iCur ){
drh70d18342013-06-06 19:16:33 +00005063 tempWC.pWInfo = pWC->pWInfo;
drh783dece2013-06-05 17:53:43 +00005064 tempWC.pOuter = pWC;
5065 tempWC.op = TK_AND;
drh783dece2013-06-05 17:53:43 +00005066 tempWC.nTerm = 1;
drhcf8fa7a2013-05-10 20:26:22 +00005067 tempWC.a = pOrTerm;
5068 sSubBuild.pWC = &tempWC;
5069 }else{
5070 continue;
5071 }
drhaa32e3c2013-07-16 21:31:23 +00005072 sCur.n = 0;
drh52651492014-09-30 14:14:19 +00005073#ifdef WHERETRACE_ENABLED
drh0a99ba32014-09-30 17:03:35 +00005074 WHERETRACE(0x200, ("OR-term %d of %p has %d subterms:\n",
5075 (int)(pOrTerm-pOrWC->a), pTerm, sSubBuild.pWC->nTerm));
5076 if( sqlite3WhereTrace & 0x400 ){
5077 for(i=0; i<sSubBuild.pWC->nTerm; i++){
5078 whereTermPrint(&sSubBuild.pWC->a[i], i);
5079 }
drh52651492014-09-30 14:14:19 +00005080 }
5081#endif
drh8636e9c2013-06-11 01:50:08 +00005082#ifndef SQLITE_OMIT_VIRTUALTABLE
drhcf8fa7a2013-05-10 20:26:22 +00005083 if( IsVirtual(pItem->pTab) ){
danff4b23b2013-11-12 12:17:16 +00005084 rc = whereLoopAddVirtual(&sSubBuild, mExtra);
drh8636e9c2013-06-11 01:50:08 +00005085 }else
5086#endif
5087 {
drhcf8fa7a2013-05-10 20:26:22 +00005088 rc = whereLoopAddBtree(&sSubBuild, mExtra);
5089 }
drh36be4c42014-09-30 17:31:23 +00005090 if( rc==SQLITE_OK ){
5091 rc = whereLoopAddOr(&sSubBuild, mExtra);
5092 }
drhaa32e3c2013-07-16 21:31:23 +00005093 assert( rc==SQLITE_OK || sCur.n==0 );
5094 if( sCur.n==0 ){
5095 sSum.n = 0;
5096 break;
5097 }else if( once ){
5098 whereOrMove(&sSum, &sCur);
5099 once = 0;
5100 }else{
dan5da73e12014-04-30 18:11:55 +00005101 WhereOrSet sPrev;
drhaa32e3c2013-07-16 21:31:23 +00005102 whereOrMove(&sPrev, &sSum);
5103 sSum.n = 0;
5104 for(i=0; i<sPrev.n; i++){
5105 for(j=0; j<sCur.n; j++){
5106 whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,
drhbf539c42013-10-05 18:16:02 +00005107 sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
5108 sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
drhaa32e3c2013-07-16 21:31:23 +00005109 }
5110 }
5111 }
drhcf8fa7a2013-05-10 20:26:22 +00005112 }
drhaa32e3c2013-07-16 21:31:23 +00005113 pNew->nLTerm = 1;
5114 pNew->aLTerm[0] = pTerm;
5115 pNew->wsFlags = WHERE_MULTI_OR;
5116 pNew->rSetup = 0;
5117 pNew->iSortIdx = 0;
5118 memset(&pNew->u, 0, sizeof(pNew->u));
5119 for(i=0; rc==SQLITE_OK && i<sSum.n; i++){
dan5da73e12014-04-30 18:11:55 +00005120 /* TUNING: Currently sSum.a[i].rRun is set to the sum of the costs
5121 ** of all sub-scans required by the OR-scan. However, due to rounding
5122 ** errors, it may be that the cost of the OR-scan is equal to its
5123 ** most expensive sub-scan. Add the smallest possible penalty
5124 ** (equivalent to multiplying the cost by 1.07) to ensure that
5125 ** this does not happen. Otherwise, for WHERE clauses such as the
5126 ** following where there is an index on "y":
5127 **
5128 ** WHERE likelihood(x=?, 0.99) OR y=?
5129 **
5130 ** the planner may elect to "OR" together a full-table scan and an
5131 ** index lookup. And other similarly odd results. */
5132 pNew->rRun = sSum.a[i].rRun + 1;
drhaa32e3c2013-07-16 21:31:23 +00005133 pNew->nOut = sSum.a[i].nOut;
5134 pNew->prereq = sSum.a[i].prereq;
drhfd5874d2013-06-12 14:52:39 +00005135 rc = whereLoopInsert(pBuilder, pNew);
5136 }
drh0a99ba32014-09-30 17:03:35 +00005137 WHERETRACE(0x200, ("End processing OR-clause %p\n", pTerm));
drhcf8fa7a2013-05-10 20:26:22 +00005138 }
5139 }
5140 return rc;
5141}
5142
5143/*
drhf1b5f5b2013-05-02 00:15:01 +00005144** Add all WhereLoop objects for all tables
5145*/
drh5346e952013-05-08 14:14:26 +00005146static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
drh70d18342013-06-06 19:16:33 +00005147 WhereInfo *pWInfo = pBuilder->pWInfo;
drhf1b5f5b2013-05-02 00:15:01 +00005148 Bitmask mExtra = 0;
5149 Bitmask mPrior = 0;
5150 int iTab;
drh70d18342013-06-06 19:16:33 +00005151 SrcList *pTabList = pWInfo->pTabList;
drhf1b5f5b2013-05-02 00:15:01 +00005152 struct SrcList_item *pItem;
drh70d18342013-06-06 19:16:33 +00005153 sqlite3 *db = pWInfo->pParse->db;
5154 int nTabList = pWInfo->nLevel;
drh5346e952013-05-08 14:14:26 +00005155 int rc = SQLITE_OK;
drhc63367e2013-06-10 20:46:50 +00005156 u8 priorJoinType = 0;
drhb8a8e8a2013-06-10 19:12:39 +00005157 WhereLoop *pNew;
drhf1b5f5b2013-05-02 00:15:01 +00005158
5159 /* Loop over the tables in the join, from left to right */
drhb8a8e8a2013-06-10 19:12:39 +00005160 pNew = pBuilder->pNew;
drha2014152013-06-07 00:29:23 +00005161 whereLoopInit(pNew);
drha18f3d22013-05-08 03:05:41 +00005162 for(iTab=0, pItem=pTabList->a; iTab<nTabList; iTab++, pItem++){
drhb2a90f02013-05-10 03:30:49 +00005163 pNew->iTab = iTab;
drh70d18342013-06-06 19:16:33 +00005164 pNew->maskSelf = getMask(&pWInfo->sMaskSet, pItem->iCursor);
drhc63367e2013-06-10 20:46:50 +00005165 if( ((pItem->jointype|priorJoinType) & (JT_LEFT|JT_CROSS))!=0 ){
drhf1b5f5b2013-05-02 00:15:01 +00005166 mExtra = mPrior;
5167 }
drhc63367e2013-06-10 20:46:50 +00005168 priorJoinType = pItem->jointype;
drhb2a90f02013-05-10 03:30:49 +00005169 if( IsVirtual(pItem->pTab) ){
danff4b23b2013-11-12 12:17:16 +00005170 rc = whereLoopAddVirtual(pBuilder, mExtra);
drhb2a90f02013-05-10 03:30:49 +00005171 }else{
5172 rc = whereLoopAddBtree(pBuilder, mExtra);
5173 }
drhb2a90f02013-05-10 03:30:49 +00005174 if( rc==SQLITE_OK ){
5175 rc = whereLoopAddOr(pBuilder, mExtra);
5176 }
drhb2a90f02013-05-10 03:30:49 +00005177 mPrior |= pNew->maskSelf;
drh5346e952013-05-08 14:14:26 +00005178 if( rc || db->mallocFailed ) break;
drhf1b5f5b2013-05-02 00:15:01 +00005179 }
drha2014152013-06-07 00:29:23 +00005180 whereLoopClear(db, pNew);
drh5346e952013-05-08 14:14:26 +00005181 return rc;
drhf1b5f5b2013-05-02 00:15:01 +00005182}
5183
drha18f3d22013-05-08 03:05:41 +00005184/*
drh7699d1c2013-06-04 12:42:29 +00005185** Examine a WherePath (with the addition of the extra WhereLoop of the 5th
drh319f6772013-05-14 15:31:07 +00005186** parameters) to see if it outputs rows in the requested ORDER BY
drh0401ace2014-03-18 15:30:27 +00005187** (or GROUP BY) without requiring a separate sort operation. Return N:
drh319f6772013-05-14 15:31:07 +00005188**
drh0401ace2014-03-18 15:30:27 +00005189** N>0: N terms of the ORDER BY clause are satisfied
5190** N==0: No terms of the ORDER BY clause are satisfied
5191** N<0: Unknown yet how many terms of ORDER BY might be satisfied.
drh319f6772013-05-14 15:31:07 +00005192**
drh94433422013-07-01 11:05:50 +00005193** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
5194** strict. With GROUP BY and DISTINCT the only requirement is that
5195** equivalent rows appear immediately adjacent to one another. GROUP BY
dan374cd782014-04-21 13:21:56 +00005196** and DISTINCT do not require rows to appear in any particular order as long
peter.d.reid60ec9142014-09-06 16:39:46 +00005197** as equivalent rows are grouped together. Thus for GROUP BY and DISTINCT
drh94433422013-07-01 11:05:50 +00005198** the pOrderBy terms can be matched in any order. With ORDER BY, the
5199** pOrderBy terms must be matched in strict left-to-right order.
drh6b7157b2013-05-10 02:00:35 +00005200*/
drh0401ace2014-03-18 15:30:27 +00005201static i8 wherePathSatisfiesOrderBy(
drh6b7157b2013-05-10 02:00:35 +00005202 WhereInfo *pWInfo, /* The WHERE clause */
drh4f402f22013-06-11 18:59:38 +00005203 ExprList *pOrderBy, /* ORDER BY or GROUP BY or DISTINCT clause to check */
drh6b7157b2013-05-10 02:00:35 +00005204 WherePath *pPath, /* The WherePath to check */
drh4f402f22013-06-11 18:59:38 +00005205 u16 wctrlFlags, /* Might contain WHERE_GROUPBY or WHERE_DISTINCTBY */
5206 u16 nLoop, /* Number of entries in pPath->aLoop[] */
drh319f6772013-05-14 15:31:07 +00005207 WhereLoop *pLast, /* Add this WhereLoop to the end of pPath->aLoop[] */
drh4f402f22013-06-11 18:59:38 +00005208 Bitmask *pRevMask /* OUT: Mask of WhereLoops to run in reverse order */
drh6b7157b2013-05-10 02:00:35 +00005209){
drh88da6442013-05-27 17:59:37 +00005210 u8 revSet; /* True if rev is known */
5211 u8 rev; /* Composite sort order */
5212 u8 revIdx; /* Index sort order */
drhe353ee32013-06-04 23:40:53 +00005213 u8 isOrderDistinct; /* All prior WhereLoops are order-distinct */
5214 u8 distinctColumns; /* True if the loop has UNIQUE NOT NULL columns */
5215 u8 isMatch; /* iColumn matches a term of the ORDER BY clause */
drh416846a2013-11-06 12:56:04 +00005216 u16 nKeyCol; /* Number of key columns in pIndex */
5217 u16 nColumn; /* Total number of ordered columns in the index */
drh7699d1c2013-06-04 12:42:29 +00005218 u16 nOrderBy; /* Number terms in the ORDER BY clause */
5219 int iLoop; /* Index of WhereLoop in pPath being processed */
5220 int i, j; /* Loop counters */
5221 int iCur; /* Cursor number for current WhereLoop */
5222 int iColumn; /* A column number within table iCur */
drhe8ae5832013-06-19 13:32:46 +00005223 WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
drh7699d1c2013-06-04 12:42:29 +00005224 WhereTerm *pTerm; /* A single term of the WHERE clause */
5225 Expr *pOBExpr; /* An expression from the ORDER BY clause */
5226 CollSeq *pColl; /* COLLATE function from an ORDER BY clause term */
5227 Index *pIndex; /* The index associated with pLoop */
5228 sqlite3 *db = pWInfo->pParse->db; /* Database connection */
5229 Bitmask obSat = 0; /* Mask of ORDER BY terms satisfied so far */
5230 Bitmask obDone; /* Mask of all ORDER BY terms */
drhe353ee32013-06-04 23:40:53 +00005231 Bitmask orderDistinctMask; /* Mask of all well-ordered loops */
drhb8916be2013-06-14 02:51:48 +00005232 Bitmask ready; /* Mask of inner loops */
drh319f6772013-05-14 15:31:07 +00005233
5234 /*
drh7699d1c2013-06-04 12:42:29 +00005235 ** We say the WhereLoop is "one-row" if it generates no more than one
5236 ** row of output. A WhereLoop is one-row if all of the following are true:
drh319f6772013-05-14 15:31:07 +00005237 ** (a) All index columns match with WHERE_COLUMN_EQ.
5238 ** (b) The index is unique
drh7699d1c2013-06-04 12:42:29 +00005239 ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
5240 ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
drh319f6772013-05-14 15:31:07 +00005241 **
drhe353ee32013-06-04 23:40:53 +00005242 ** We say the WhereLoop is "order-distinct" if the set of columns from
5243 ** that WhereLoop that are in the ORDER BY clause are different for every
5244 ** row of the WhereLoop. Every one-row WhereLoop is automatically
5245 ** order-distinct. A WhereLoop that has no columns in the ORDER BY clause
5246 ** is not order-distinct. To be order-distinct is not quite the same as being
5247 ** UNIQUE since a UNIQUE column or index can have multiple rows that
5248 ** are NULL and NULL values are equivalent for the purpose of order-distinct.
5249 ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
5250 **
5251 ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
5252 ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
5253 ** automatically order-distinct.
drh319f6772013-05-14 15:31:07 +00005254 */
5255
5256 assert( pOrderBy!=0 );
drh7699d1c2013-06-04 12:42:29 +00005257 if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
drh319f6772013-05-14 15:31:07 +00005258
drh319f6772013-05-14 15:31:07 +00005259 nOrderBy = pOrderBy->nExpr;
drh7963b0e2013-06-17 21:37:40 +00005260 testcase( nOrderBy==BMS-1 );
drhe353ee32013-06-04 23:40:53 +00005261 if( nOrderBy>BMS-1 ) return 0; /* Cannot optimize overly large ORDER BYs */
5262 isOrderDistinct = 1;
drh7699d1c2013-06-04 12:42:29 +00005263 obDone = MASKBIT(nOrderBy)-1;
drhe353ee32013-06-04 23:40:53 +00005264 orderDistinctMask = 0;
drhb8916be2013-06-14 02:51:48 +00005265 ready = 0;
drhe353ee32013-06-04 23:40:53 +00005266 for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
drhb8916be2013-06-14 02:51:48 +00005267 if( iLoop>0 ) ready |= pLoop->maskSelf;
drh7699d1c2013-06-04 12:42:29 +00005268 pLoop = iLoop<nLoop ? pPath->aLoop[iLoop] : pLast;
drh9dfaf622014-04-25 14:42:17 +00005269 if( pLoop->wsFlags & WHERE_VIRTUALTABLE ){
5270 if( pLoop->u.vtab.isOrdered ) obSat = obDone;
5271 break;
5272 }
drh319f6772013-05-14 15:31:07 +00005273 iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
drhb8916be2013-06-14 02:51:48 +00005274
5275 /* Mark off any ORDER BY term X that is a column in the table of
5276 ** the current loop for which there is term in the WHERE
5277 ** clause of the form X IS NULL or X=? that reference only outer
5278 ** loops.
5279 */
5280 for(i=0; i<nOrderBy; i++){
5281 if( MASKBIT(i) & obSat ) continue;
5282 pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
5283 if( pOBExpr->op!=TK_COLUMN ) continue;
5284 if( pOBExpr->iTable!=iCur ) continue;
5285 pTerm = findTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
5286 ~ready, WO_EQ|WO_ISNULL, 0);
5287 if( pTerm==0 ) continue;
drh7963b0e2013-06-17 21:37:40 +00005288 if( (pTerm->eOperator&WO_EQ)!=0 && pOBExpr->iColumn>=0 ){
drhb8916be2013-06-14 02:51:48 +00005289 const char *z1, *z2;
5290 pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
5291 if( !pColl ) pColl = db->pDfltColl;
5292 z1 = pColl->zName;
5293 pColl = sqlite3ExprCollSeq(pWInfo->pParse, pTerm->pExpr);
5294 if( !pColl ) pColl = db->pDfltColl;
5295 z2 = pColl->zName;
5296 if( sqlite3StrICmp(z1, z2)!=0 ) continue;
5297 }
5298 obSat |= MASKBIT(i);
5299 }
5300
drh7699d1c2013-06-04 12:42:29 +00005301 if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
5302 if( pLoop->wsFlags & WHERE_IPK ){
5303 pIndex = 0;
drhbbbdc832013-10-22 18:01:40 +00005304 nKeyCol = 0;
drh416846a2013-11-06 12:56:04 +00005305 nColumn = 1;
drh7699d1c2013-06-04 12:42:29 +00005306 }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
drh1b0f0262013-05-30 22:27:09 +00005307 return 0;
drh7699d1c2013-06-04 12:42:29 +00005308 }else{
drhbbbdc832013-10-22 18:01:40 +00005309 nKeyCol = pIndex->nKeyCol;
drh416846a2013-11-06 12:56:04 +00005310 nColumn = pIndex->nColumn;
5311 assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) );
5312 assert( pIndex->aiColumn[nColumn-1]==(-1) || !HasRowid(pIndex->pTable));
drh5f1d1d92014-07-31 22:59:04 +00005313 isOrderDistinct = IsUniqueIndex(pIndex);
drh1b0f0262013-05-30 22:27:09 +00005314 }
drh7699d1c2013-06-04 12:42:29 +00005315
drh7699d1c2013-06-04 12:42:29 +00005316 /* Loop through all columns of the index and deal with the ones
5317 ** that are not constrained by == or IN.
5318 */
5319 rev = revSet = 0;
drhe353ee32013-06-04 23:40:53 +00005320 distinctColumns = 0;
drh416846a2013-11-06 12:56:04 +00005321 for(j=0; j<nColumn; j++){
drh7699d1c2013-06-04 12:42:29 +00005322 u8 bOnce; /* True to run the ORDER BY search loop */
5323
drhe353ee32013-06-04 23:40:53 +00005324 /* Skip over == and IS NULL terms */
drh7699d1c2013-06-04 12:42:29 +00005325 if( j<pLoop->u.btree.nEq
drhc8bbce12014-10-21 01:05:09 +00005326 && pLoop->nSkip==0
drh4efc9292013-06-06 23:02:03 +00005327 && ((i = pLoop->aLTerm[j]->eOperator) & (WO_EQ|WO_ISNULL))!=0
drh7699d1c2013-06-04 12:42:29 +00005328 ){
drh7963b0e2013-06-17 21:37:40 +00005329 if( i & WO_ISNULL ){
5330 testcase( isOrderDistinct );
5331 isOrderDistinct = 0;
5332 }
drhe353ee32013-06-04 23:40:53 +00005333 continue;
drh7699d1c2013-06-04 12:42:29 +00005334 }
5335
drhe353ee32013-06-04 23:40:53 +00005336 /* Get the column number in the table (iColumn) and sort order
5337 ** (revIdx) for the j-th column of the index.
drh7699d1c2013-06-04 12:42:29 +00005338 */
drh416846a2013-11-06 12:56:04 +00005339 if( pIndex ){
drh7699d1c2013-06-04 12:42:29 +00005340 iColumn = pIndex->aiColumn[j];
5341 revIdx = pIndex->aSortOrder[j];
5342 if( iColumn==pIndex->pTable->iPKey ) iColumn = -1;
drhdc3cd4b2013-05-30 23:21:20 +00005343 }else{
drh7699d1c2013-06-04 12:42:29 +00005344 iColumn = -1;
5345 revIdx = 0;
drhdc3cd4b2013-05-30 23:21:20 +00005346 }
drh7699d1c2013-06-04 12:42:29 +00005347
5348 /* An unconstrained column that might be NULL means that this
drh416846a2013-11-06 12:56:04 +00005349 ** WhereLoop is not well-ordered
drh7699d1c2013-06-04 12:42:29 +00005350 */
drhe353ee32013-06-04 23:40:53 +00005351 if( isOrderDistinct
5352 && iColumn>=0
drh7699d1c2013-06-04 12:42:29 +00005353 && j>=pLoop->u.btree.nEq
5354 && pIndex->pTable->aCol[iColumn].notNull==0
5355 ){
drhe353ee32013-06-04 23:40:53 +00005356 isOrderDistinct = 0;
drh7699d1c2013-06-04 12:42:29 +00005357 }
5358
5359 /* Find the ORDER BY term that corresponds to the j-th column
dan374cd782014-04-21 13:21:56 +00005360 ** of the index and mark that ORDER BY term off
drh7699d1c2013-06-04 12:42:29 +00005361 */
5362 bOnce = 1;
drhe353ee32013-06-04 23:40:53 +00005363 isMatch = 0;
drh7699d1c2013-06-04 12:42:29 +00005364 for(i=0; bOnce && i<nOrderBy; i++){
5365 if( MASKBIT(i) & obSat ) continue;
5366 pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
drh93ec45d2013-06-17 18:20:48 +00005367 testcase( wctrlFlags & WHERE_GROUPBY );
5368 testcase( wctrlFlags & WHERE_DISTINCTBY );
drh4f402f22013-06-11 18:59:38 +00005369 if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
drhe353ee32013-06-04 23:40:53 +00005370 if( pOBExpr->op!=TK_COLUMN ) continue;
drh7699d1c2013-06-04 12:42:29 +00005371 if( pOBExpr->iTable!=iCur ) continue;
5372 if( pOBExpr->iColumn!=iColumn ) continue;
5373 if( iColumn>=0 ){
5374 pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
5375 if( !pColl ) pColl = db->pDfltColl;
5376 if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
5377 }
drhe353ee32013-06-04 23:40:53 +00005378 isMatch = 1;
drh7699d1c2013-06-04 12:42:29 +00005379 break;
5380 }
drh49290472014-10-11 02:12:58 +00005381 if( isMatch && (wctrlFlags & WHERE_GROUPBY)==0 ){
drh59b8f2e2014-03-22 00:27:14 +00005382 /* Make sure the sort order is compatible in an ORDER BY clause.
5383 ** Sort order is irrelevant for a GROUP BY clause. */
5384 if( revSet ){
5385 if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) isMatch = 0;
5386 }else{
5387 rev = revIdx ^ pOrderBy->a[i].sortOrder;
5388 if( rev ) *pRevMask |= MASKBIT(iLoop);
5389 revSet = 1;
5390 }
5391 }
drhe353ee32013-06-04 23:40:53 +00005392 if( isMatch ){
drh7963b0e2013-06-17 21:37:40 +00005393 if( iColumn<0 ){
5394 testcase( distinctColumns==0 );
5395 distinctColumns = 1;
5396 }
drh7699d1c2013-06-04 12:42:29 +00005397 obSat |= MASKBIT(i);
drh7699d1c2013-06-04 12:42:29 +00005398 }else{
5399 /* No match found */
drhbbbdc832013-10-22 18:01:40 +00005400 if( j==0 || j<nKeyCol ){
drh7963b0e2013-06-17 21:37:40 +00005401 testcase( isOrderDistinct!=0 );
5402 isOrderDistinct = 0;
5403 }
drh7699d1c2013-06-04 12:42:29 +00005404 break;
5405 }
5406 } /* end Loop over all index columns */
drh81186b42013-06-18 01:52:41 +00005407 if( distinctColumns ){
5408 testcase( isOrderDistinct==0 );
5409 isOrderDistinct = 1;
5410 }
drh7699d1c2013-06-04 12:42:29 +00005411 } /* end-if not one-row */
5412
5413 /* Mark off any other ORDER BY terms that reference pLoop */
drhe353ee32013-06-04 23:40:53 +00005414 if( isOrderDistinct ){
5415 orderDistinctMask |= pLoop->maskSelf;
drh7699d1c2013-06-04 12:42:29 +00005416 for(i=0; i<nOrderBy; i++){
5417 Expr *p;
drh434a9312014-02-26 02:26:09 +00005418 Bitmask mTerm;
drh7699d1c2013-06-04 12:42:29 +00005419 if( MASKBIT(i) & obSat ) continue;
5420 p = pOrderBy->a[i].pExpr;
drh434a9312014-02-26 02:26:09 +00005421 mTerm = exprTableUsage(&pWInfo->sMaskSet,p);
5422 if( mTerm==0 && !sqlite3ExprIsConstant(p) ) continue;
5423 if( (mTerm&~orderDistinctMask)==0 ){
drh7699d1c2013-06-04 12:42:29 +00005424 obSat |= MASKBIT(i);
5425 }
drh0afb4232013-05-31 13:36:32 +00005426 }
drh319f6772013-05-14 15:31:07 +00005427 }
drhb8916be2013-06-14 02:51:48 +00005428 } /* End the loop over all WhereLoops from outer-most down to inner-most */
drh36ed0342014-03-28 12:56:57 +00005429 if( obSat==obDone ) return (i8)nOrderBy;
drhd2de8612014-03-18 18:59:07 +00005430 if( !isOrderDistinct ){
5431 for(i=nOrderBy-1; i>0; i--){
5432 Bitmask m = MASKBIT(i) - 1;
5433 if( (obSat&m)==m ) return i;
5434 }
5435 return 0;
5436 }
drh319f6772013-05-14 15:31:07 +00005437 return -1;
drh6b7157b2013-05-10 02:00:35 +00005438}
5439
dan374cd782014-04-21 13:21:56 +00005440
5441/*
5442** If the WHERE_GROUPBY flag is set in the mask passed to sqlite3WhereBegin(),
5443** the planner assumes that the specified pOrderBy list is actually a GROUP
5444** BY clause - and so any order that groups rows as required satisfies the
5445** request.
5446**
5447** Normally, in this case it is not possible for the caller to determine
5448** whether or not the rows are really being delivered in sorted order, or
5449** just in some other order that provides the required grouping. However,
5450** if the WHERE_SORTBYGROUP flag is also passed to sqlite3WhereBegin(), then
5451** this function may be called on the returned WhereInfo object. It returns
5452** true if the rows really will be sorted in the specified order, or false
5453** otherwise.
5454**
5455** For example, assuming:
5456**
5457** CREATE INDEX i1 ON t1(x, Y);
5458**
5459** then
5460**
5461** SELECT * FROM t1 GROUP BY x,y ORDER BY x,y; -- IsSorted()==1
5462** SELECT * FROM t1 GROUP BY y,x ORDER BY y,x; -- IsSorted()==0
5463*/
5464int sqlite3WhereIsSorted(WhereInfo *pWInfo){
5465 assert( pWInfo->wctrlFlags & WHERE_GROUPBY );
5466 assert( pWInfo->wctrlFlags & WHERE_SORTBYGROUP );
5467 return pWInfo->sorted;
5468}
5469
drhd15cb172013-05-21 19:23:10 +00005470#ifdef WHERETRACE_ENABLED
5471/* For debugging use only: */
5472static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
5473 static char zName[65];
5474 int i;
5475 for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
5476 if( pLast ) zName[i++] = pLast->cId;
5477 zName[i] = 0;
5478 return zName;
5479}
5480#endif
5481
drh6b7157b2013-05-10 02:00:35 +00005482/*
dan50ae31e2014-08-08 16:52:28 +00005483** Return the cost of sorting nRow rows, assuming that the keys have
5484** nOrderby columns and that the first nSorted columns are already in
5485** order.
5486*/
5487static LogEst whereSortingCost(
5488 WhereInfo *pWInfo,
5489 LogEst nRow,
5490 int nOrderBy,
5491 int nSorted
5492){
5493 /* TUNING: Estimated cost of a full external sort, where N is
5494 ** the number of rows to sort is:
5495 **
5496 ** cost = (3.0 * N * log(N)).
5497 **
5498 ** Or, if the order-by clause has X terms but only the last Y
5499 ** terms are out of order, then block-sorting will reduce the
5500 ** sorting cost to:
5501 **
5502 ** cost = (3.0 * N * log(N)) * (Y/X)
5503 **
5504 ** The (Y/X) term is implemented using stack variable rScale
5505 ** below. */
5506 LogEst rScale, rSortCost;
5507 assert( nOrderBy>0 && 66==sqlite3LogEst(100) );
5508 rScale = sqlite3LogEst((nOrderBy-nSorted)*100/nOrderBy) - 66;
5509 rSortCost = nRow + estLog(nRow) + rScale + 16;
5510
5511 /* TUNING: The cost of implementing DISTINCT using a B-TREE is
5512 ** similar but with a larger constant of proportionality.
5513 ** Multiply by an additional factor of 3.0. */
5514 if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
5515 rSortCost += 16;
5516 }
5517
5518 return rSortCost;
5519}
5520
5521/*
dan51576f42013-07-02 10:06:15 +00005522** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
drha18f3d22013-05-08 03:05:41 +00005523** attempts to find the lowest cost path that visits each WhereLoop
5524** once. This path is then loaded into the pWInfo->a[].pWLoop fields.
5525**
drhc7f0d222013-06-19 03:27:12 +00005526** Assume that the total number of output rows that will need to be sorted
5527** will be nRowEst (in the 10*log2 representation). Or, ignore sorting
5528** costs if nRowEst==0.
5529**
drha18f3d22013-05-08 03:05:41 +00005530** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
5531** error occurs.
5532*/
drhbf539c42013-10-05 18:16:02 +00005533static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
drh783dece2013-06-05 17:53:43 +00005534 int mxChoice; /* Maximum number of simultaneous paths tracked */
drha18f3d22013-05-08 03:05:41 +00005535 int nLoop; /* Number of terms in the join */
drhe1e2e9a2013-06-13 15:16:53 +00005536 Parse *pParse; /* Parsing context */
drha18f3d22013-05-08 03:05:41 +00005537 sqlite3 *db; /* The database connection */
5538 int iLoop; /* Loop counter over the terms of the join */
5539 int ii, jj; /* Loop counters */
drhfde1e6b2013-09-06 17:45:42 +00005540 int mxI = 0; /* Index of next entry to replace */
drhd2de8612014-03-18 18:59:07 +00005541 int nOrderBy; /* Number of ORDER BY clause terms */
drhbf539c42013-10-05 18:16:02 +00005542 LogEst mxCost = 0; /* Maximum cost of a set of paths */
dan50ae31e2014-08-08 16:52:28 +00005543 LogEst mxUnsorted = 0; /* Maximum unsorted cost of a set of path */
drha18f3d22013-05-08 03:05:41 +00005544 int nTo, nFrom; /* Number of valid entries in aTo[] and aFrom[] */
5545 WherePath *aFrom; /* All nFrom paths at the previous level */
5546 WherePath *aTo; /* The nTo best paths at the current level */
5547 WherePath *pFrom; /* An element of aFrom[] that we are working on */
5548 WherePath *pTo; /* An element of aTo[] that we are working on */
5549 WhereLoop *pWLoop; /* One of the WhereLoop objects */
5550 WhereLoop **pX; /* Used to divy up the pSpace memory */
dan50ae31e2014-08-08 16:52:28 +00005551 LogEst *aSortCost = 0; /* Sorting and partial sorting costs */
drha18f3d22013-05-08 03:05:41 +00005552 char *pSpace; /* Temporary memory used by this routine */
dane2c27852014-08-08 17:25:33 +00005553 int nSpace; /* Bytes of space allocated at pSpace */
drha18f3d22013-05-08 03:05:41 +00005554
drhe1e2e9a2013-06-13 15:16:53 +00005555 pParse = pWInfo->pParse;
5556 db = pParse->db;
drha18f3d22013-05-08 03:05:41 +00005557 nLoop = pWInfo->nLevel;
drhe1e2e9a2013-06-13 15:16:53 +00005558 /* TUNING: For simple queries, only the best path is tracked.
5559 ** For 2-way joins, the 5 best paths are followed.
5560 ** For joins of 3 or more tables, track the 10 best paths */
drh2504c6c2014-06-02 11:26:33 +00005561 mxChoice = (nLoop<=1) ? 1 : (nLoop==2 ? 5 : 10);
drha18f3d22013-05-08 03:05:41 +00005562 assert( nLoop<=pWInfo->pTabList->nSrc );
drhddef5dc2014-08-07 16:50:00 +00005563 WHERETRACE(0x002, ("---- begin solver. (nRowEst=%d)\n", nRowEst));
drha18f3d22013-05-08 03:05:41 +00005564
dan50ae31e2014-08-08 16:52:28 +00005565 /* If nRowEst is zero and there is an ORDER BY clause, ignore it. In this
5566 ** case the purpose of this call is to estimate the number of rows returned
5567 ** by the overall query. Once this estimate has been obtained, the caller
5568 ** will invoke this function a second time, passing the estimate as the
5569 ** nRowEst parameter. */
5570 if( pWInfo->pOrderBy==0 || nRowEst==0 ){
5571 nOrderBy = 0;
5572 }else{
5573 nOrderBy = pWInfo->pOrderBy->nExpr;
5574 }
5575
5576 /* Allocate and initialize space for aTo, aFrom and aSortCost[] */
dane2c27852014-08-08 17:25:33 +00005577 nSpace = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
5578 nSpace += sizeof(LogEst) * nOrderBy;
5579 pSpace = sqlite3DbMallocRaw(db, nSpace);
drha18f3d22013-05-08 03:05:41 +00005580 if( pSpace==0 ) return SQLITE_NOMEM;
5581 aTo = (WherePath*)pSpace;
5582 aFrom = aTo+mxChoice;
5583 memset(aFrom, 0, sizeof(aFrom[0]));
5584 pX = (WhereLoop**)(aFrom+mxChoice);
drhe9d935a2013-06-05 16:19:59 +00005585 for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
drha18f3d22013-05-08 03:05:41 +00005586 pFrom->aLoop = pX;
5587 }
dan50ae31e2014-08-08 16:52:28 +00005588 if( nOrderBy ){
5589 /* If there is an ORDER BY clause and it is not being ignored, set up
5590 ** space for the aSortCost[] array. Each element of the aSortCost array
5591 ** is either zero - meaning it has not yet been initialized - or the
5592 ** cost of sorting nRowEst rows of data where the first X terms of
5593 ** the ORDER BY clause are already in order, where X is the array
5594 ** index. */
5595 aSortCost = (LogEst*)pX;
dane2c27852014-08-08 17:25:33 +00005596 memset(aSortCost, 0, sizeof(LogEst) * nOrderBy);
dan50ae31e2014-08-08 16:52:28 +00005597 }
dane2c27852014-08-08 17:25:33 +00005598 assert( aSortCost==0 || &pSpace[nSpace]==(char*)&aSortCost[nOrderBy] );
5599 assert( aSortCost!=0 || &pSpace[nSpace]==(char*)pX );
drha18f3d22013-05-08 03:05:41 +00005600
drhe1e2e9a2013-06-13 15:16:53 +00005601 /* Seed the search with a single WherePath containing zero WhereLoops.
5602 **
5603 ** TUNING: Do not let the number of iterations go above 25. If the cost
5604 ** of computing an automatic index is not paid back within the first 25
5605 ** rows, then do not use the automatic index. */
drhbf539c42013-10-05 18:16:02 +00005606 aFrom[0].nRow = MIN(pParse->nQueryLoop, 46); assert( 46==sqlite3LogEst(25) );
drha18f3d22013-05-08 03:05:41 +00005607 nFrom = 1;
dan50ae31e2014-08-08 16:52:28 +00005608 assert( aFrom[0].isOrdered==0 );
5609 if( nOrderBy ){
5610 /* If nLoop is zero, then there are no FROM terms in the query. Since
5611 ** in this case the query may return a maximum of one row, the results
5612 ** are already in the requested order. Set isOrdered to nOrderBy to
5613 ** indicate this. Or, if nLoop is greater than zero, set isOrdered to
5614 ** -1, indicating that the result set may or may not be ordered,
5615 ** depending on the loops added to the current plan. */
5616 aFrom[0].isOrdered = nLoop>0 ? -1 : nOrderBy;
drh6b7157b2013-05-10 02:00:35 +00005617 }
5618
5619 /* Compute successively longer WherePaths using the previous generation
5620 ** of WherePaths as the basis for the next. Keep track of the mxChoice
5621 ** best paths at each generation */
drha18f3d22013-05-08 03:05:41 +00005622 for(iLoop=0; iLoop<nLoop; iLoop++){
5623 nTo = 0;
5624 for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
5625 for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
dan50ae31e2014-08-08 16:52:28 +00005626 LogEst nOut; /* Rows visited by (pFrom+pWLoop) */
5627 LogEst rCost; /* Cost of path (pFrom+pWLoop) */
5628 LogEst rUnsorted; /* Unsorted cost of (pFrom+pWLoop) */
5629 i8 isOrdered = pFrom->isOrdered; /* isOrdered for (pFrom+pWLoop) */
5630 Bitmask maskNew; /* Mask of src visited by (..) */
5631 Bitmask revMask = 0; /* Mask of rev-order loops for (..) */
5632
drha18f3d22013-05-08 03:05:41 +00005633 if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
5634 if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
drh6b7157b2013-05-10 02:00:35 +00005635 /* At this point, pWLoop is a candidate to be the next loop.
5636 ** Compute its cost */
dan50ae31e2014-08-08 16:52:28 +00005637 rUnsorted = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
5638 rUnsorted = sqlite3LogEstAdd(rUnsorted, pFrom->rUnsorted);
drhfde1e6b2013-09-06 17:45:42 +00005639 nOut = pFrom->nRow + pWLoop->nOut;
drha18f3d22013-05-08 03:05:41 +00005640 maskNew = pFrom->maskLoop | pWLoop->maskSelf;
drh0401ace2014-03-18 15:30:27 +00005641 if( isOrdered<0 ){
5642 isOrdered = wherePathSatisfiesOrderBy(pWInfo,
drh4f402f22013-06-11 18:59:38 +00005643 pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
drh0401ace2014-03-18 15:30:27 +00005644 iLoop, pWLoop, &revMask);
drh3a5ba8b2013-06-03 15:34:48 +00005645 }else{
5646 revMask = pFrom->revLoop;
drh6b7157b2013-05-10 02:00:35 +00005647 }
dan50ae31e2014-08-08 16:52:28 +00005648 if( isOrdered>=0 && isOrdered<nOrderBy ){
5649 if( aSortCost[isOrdered]==0 ){
5650 aSortCost[isOrdered] = whereSortingCost(
5651 pWInfo, nRowEst, nOrderBy, isOrdered
5652 );
5653 }
5654 rCost = sqlite3LogEstAdd(rUnsorted, aSortCost[isOrdered]);
5655
5656 WHERETRACE(0x002,
5657 ("---- sort cost=%-3d (%d/%d) increases cost %3d to %-3d\n",
5658 aSortCost[isOrdered], (nOrderBy-isOrdered), nOrderBy,
5659 rUnsorted, rCost));
5660 }else{
5661 rCost = rUnsorted;
5662 }
5663
drhddef5dc2014-08-07 16:50:00 +00005664 /* Check to see if pWLoop should be added to the set of
5665 ** mxChoice best-so-far paths.
5666 **
5667 ** First look for an existing path among best-so-far paths
5668 ** that covers the same set of loops and has the same isOrdered
5669 ** setting as the current path candidate.
drhf2a90302014-08-07 20:37:01 +00005670 **
5671 ** The term "((pTo->isOrdered^isOrdered)&0x80)==0" is equivalent
5672 ** to (pTo->isOrdered==(-1))==(isOrdered==(-1))" for the range
5673 ** of legal values for isOrdered, -1..64.
drhddef5dc2014-08-07 16:50:00 +00005674 */
drh6b7157b2013-05-10 02:00:35 +00005675 for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
drhfde1e6b2013-09-06 17:45:42 +00005676 if( pTo->maskLoop==maskNew
drhf2a90302014-08-07 20:37:01 +00005677 && ((pTo->isOrdered^isOrdered)&0x80)==0
drhfde1e6b2013-09-06 17:45:42 +00005678 ){
drh7963b0e2013-06-17 21:37:40 +00005679 testcase( jj==nTo-1 );
drh6b7157b2013-05-10 02:00:35 +00005680 break;
5681 }
5682 }
drha18f3d22013-05-08 03:05:41 +00005683 if( jj>=nTo ){
drhddef5dc2014-08-07 16:50:00 +00005684 /* None of the existing best-so-far paths match the candidate. */
drhddef5dc2014-08-07 16:50:00 +00005685 if( nTo>=mxChoice
dan50ae31e2014-08-08 16:52:28 +00005686 && (rCost>mxCost || (rCost==mxCost && rUnsorted>=mxUnsorted))
drhddef5dc2014-08-07 16:50:00 +00005687 ){
5688 /* The current candidate is no better than any of the mxChoice
5689 ** paths currently in the best-so-far buffer. So discard
5690 ** this candidate as not viable. */
drh989578e2013-10-28 14:34:35 +00005691#ifdef WHERETRACE_ENABLED /* 0x4 */
drhae70cf12013-05-31 15:18:46 +00005692 if( sqlite3WhereTrace&0x4 ){
drhfde1e6b2013-09-06 17:45:42 +00005693 sqlite3DebugPrintf("Skip %s cost=%-3d,%3d order=%c\n",
5694 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
drh0401ace2014-03-18 15:30:27 +00005695 isOrdered>=0 ? isOrdered+'0' : '?');
drhd15cb172013-05-21 19:23:10 +00005696 }
5697#endif
5698 continue;
5699 }
drhddef5dc2014-08-07 16:50:00 +00005700 /* If we reach this points it means that the new candidate path
5701 ** needs to be added to the set of best-so-far paths. */
drha18f3d22013-05-08 03:05:41 +00005702 if( nTo<mxChoice ){
drhd15cb172013-05-21 19:23:10 +00005703 /* Increase the size of the aTo set by one */
drha18f3d22013-05-08 03:05:41 +00005704 jj = nTo++;
5705 }else{
drhd15cb172013-05-21 19:23:10 +00005706 /* New path replaces the prior worst to keep count below mxChoice */
drhfde1e6b2013-09-06 17:45:42 +00005707 jj = mxI;
drha18f3d22013-05-08 03:05:41 +00005708 }
5709 pTo = &aTo[jj];
drh989578e2013-10-28 14:34:35 +00005710#ifdef WHERETRACE_ENABLED /* 0x4 */
drhae70cf12013-05-31 15:18:46 +00005711 if( sqlite3WhereTrace&0x4 ){
drhfde1e6b2013-09-06 17:45:42 +00005712 sqlite3DebugPrintf("New %s cost=%-3d,%3d order=%c\n",
5713 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
drh0401ace2014-03-18 15:30:27 +00005714 isOrdered>=0 ? isOrdered+'0' : '?');
drhd15cb172013-05-21 19:23:10 +00005715 }
5716#endif
drhf204dac2013-05-08 03:22:07 +00005717 }else{
drhddef5dc2014-08-07 16:50:00 +00005718 /* Control reaches here if best-so-far path pTo=aTo[jj] covers the
5719 ** same set of loops and has the sam isOrdered setting as the
5720 ** candidate path. Check to see if the candidate should replace
5721 ** pTo or if the candidate should be skipped */
5722 if( pTo->rCost<rCost || (pTo->rCost==rCost && pTo->nRow<=nOut) ){
drh989578e2013-10-28 14:34:35 +00005723#ifdef WHERETRACE_ENABLED /* 0x4 */
drhae70cf12013-05-31 15:18:46 +00005724 if( sqlite3WhereTrace&0x4 ){
drhd15cb172013-05-21 19:23:10 +00005725 sqlite3DebugPrintf(
drhfde1e6b2013-09-06 17:45:42 +00005726 "Skip %s cost=%-3d,%3d order=%c",
5727 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
drh0401ace2014-03-18 15:30:27 +00005728 isOrdered>=0 ? isOrdered+'0' : '?');
drhfde1e6b2013-09-06 17:45:42 +00005729 sqlite3DebugPrintf(" vs %s cost=%-3d,%d order=%c\n",
5730 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
drh0401ace2014-03-18 15:30:27 +00005731 pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
drhd15cb172013-05-21 19:23:10 +00005732 }
5733#endif
drhddef5dc2014-08-07 16:50:00 +00005734 /* Discard the candidate path from further consideration */
drh7963b0e2013-06-17 21:37:40 +00005735 testcase( pTo->rCost==rCost );
drhd15cb172013-05-21 19:23:10 +00005736 continue;
5737 }
drh7963b0e2013-06-17 21:37:40 +00005738 testcase( pTo->rCost==rCost+1 );
drhddef5dc2014-08-07 16:50:00 +00005739 /* Control reaches here if the candidate path is better than the
5740 ** pTo path. Replace pTo with the candidate. */
drh989578e2013-10-28 14:34:35 +00005741#ifdef WHERETRACE_ENABLED /* 0x4 */
drhae70cf12013-05-31 15:18:46 +00005742 if( sqlite3WhereTrace&0x4 ){
drhd15cb172013-05-21 19:23:10 +00005743 sqlite3DebugPrintf(
drhfde1e6b2013-09-06 17:45:42 +00005744 "Update %s cost=%-3d,%3d order=%c",
5745 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
drh0401ace2014-03-18 15:30:27 +00005746 isOrdered>=0 ? isOrdered+'0' : '?');
drhfde1e6b2013-09-06 17:45:42 +00005747 sqlite3DebugPrintf(" was %s cost=%-3d,%3d order=%c\n",
5748 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
drh0401ace2014-03-18 15:30:27 +00005749 pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
drhd15cb172013-05-21 19:23:10 +00005750 }
5751#endif
drha18f3d22013-05-08 03:05:41 +00005752 }
drh6b7157b2013-05-10 02:00:35 +00005753 /* pWLoop is a winner. Add it to the set of best so far */
drha18f3d22013-05-08 03:05:41 +00005754 pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
drh319f6772013-05-14 15:31:07 +00005755 pTo->revLoop = revMask;
drhfde1e6b2013-09-06 17:45:42 +00005756 pTo->nRow = nOut;
drha18f3d22013-05-08 03:05:41 +00005757 pTo->rCost = rCost;
dan50ae31e2014-08-08 16:52:28 +00005758 pTo->rUnsorted = rUnsorted;
drh6b7157b2013-05-10 02:00:35 +00005759 pTo->isOrdered = isOrdered;
drha18f3d22013-05-08 03:05:41 +00005760 memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
5761 pTo->aLoop[iLoop] = pWLoop;
5762 if( nTo>=mxChoice ){
drhfde1e6b2013-09-06 17:45:42 +00005763 mxI = 0;
drha18f3d22013-05-08 03:05:41 +00005764 mxCost = aTo[0].rCost;
dan50ae31e2014-08-08 16:52:28 +00005765 mxUnsorted = aTo[0].nRow;
drha18f3d22013-05-08 03:05:41 +00005766 for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
dan50ae31e2014-08-08 16:52:28 +00005767 if( pTo->rCost>mxCost
5768 || (pTo->rCost==mxCost && pTo->rUnsorted>mxUnsorted)
5769 ){
drhfde1e6b2013-09-06 17:45:42 +00005770 mxCost = pTo->rCost;
dan50ae31e2014-08-08 16:52:28 +00005771 mxUnsorted = pTo->rUnsorted;
drhfde1e6b2013-09-06 17:45:42 +00005772 mxI = jj;
5773 }
drha18f3d22013-05-08 03:05:41 +00005774 }
5775 }
5776 }
5777 }
5778
drh989578e2013-10-28 14:34:35 +00005779#ifdef WHERETRACE_ENABLED /* >=2 */
drh1b131b72014-10-21 16:01:40 +00005780 if( sqlite3WhereTrace & 0x02 ){
drha50ef112013-05-22 02:06:59 +00005781 sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
drhd15cb172013-05-21 19:23:10 +00005782 for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
drhb8a8e8a2013-06-10 19:12:39 +00005783 sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
drha50ef112013-05-22 02:06:59 +00005784 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
drh0401ace2014-03-18 15:30:27 +00005785 pTo->isOrdered>=0 ? (pTo->isOrdered+'0') : '?');
5786 if( pTo->isOrdered>0 ){
drh88da6442013-05-27 17:59:37 +00005787 sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
5788 }else{
5789 sqlite3DebugPrintf("\n");
5790 }
drhf204dac2013-05-08 03:22:07 +00005791 }
5792 }
5793#endif
5794
drh6b7157b2013-05-10 02:00:35 +00005795 /* Swap the roles of aFrom and aTo for the next generation */
drha18f3d22013-05-08 03:05:41 +00005796 pFrom = aTo;
5797 aTo = aFrom;
5798 aFrom = pFrom;
5799 nFrom = nTo;
5800 }
5801
drh75b93402013-05-31 20:43:57 +00005802 if( nFrom==0 ){
drhe1e2e9a2013-06-13 15:16:53 +00005803 sqlite3ErrorMsg(pParse, "no query solution");
drh75b93402013-05-31 20:43:57 +00005804 sqlite3DbFree(db, pSpace);
5805 return SQLITE_ERROR;
5806 }
drha18f3d22013-05-08 03:05:41 +00005807
drh6b7157b2013-05-10 02:00:35 +00005808 /* Find the lowest cost path. pFrom will be left pointing to that path */
drha18f3d22013-05-08 03:05:41 +00005809 pFrom = aFrom;
5810 for(ii=1; ii<nFrom; ii++){
5811 if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
5812 }
5813 assert( pWInfo->nLevel==nLoop );
drh6b7157b2013-05-10 02:00:35 +00005814 /* Load the lowest cost path into pWInfo */
drha18f3d22013-05-08 03:05:41 +00005815 for(iLoop=0; iLoop<nLoop; iLoop++){
drh7ba39a92013-05-30 17:43:19 +00005816 WhereLevel *pLevel = pWInfo->a + iLoop;
5817 pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
drhe217efc2013-06-12 03:48:41 +00005818 pLevel->iFrom = pWLoop->iTab;
drh7ba39a92013-05-30 17:43:19 +00005819 pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
drha18f3d22013-05-08 03:05:41 +00005820 }
drhfd636c72013-06-21 02:05:06 +00005821 if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0
5822 && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
5823 && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
drh4f402f22013-06-11 18:59:38 +00005824 && nRowEst
5825 ){
5826 Bitmask notUsed;
drh6457a352013-06-21 00:35:37 +00005827 int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom,
drh93ec45d2013-06-17 18:20:48 +00005828 WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
drh0401ace2014-03-18 15:30:27 +00005829 if( rc==pWInfo->pResultSet->nExpr ){
5830 pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
5831 }
drh4f402f22013-06-11 18:59:38 +00005832 }
drh079a3072014-03-19 14:10:55 +00005833 if( pWInfo->pOrderBy ){
drh4f402f22013-06-11 18:59:38 +00005834 if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
drh079a3072014-03-19 14:10:55 +00005835 if( pFrom->isOrdered==pWInfo->pOrderBy->nExpr ){
5836 pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
5837 }
drh4f402f22013-06-11 18:59:38 +00005838 }else{
drhddba0c22014-03-18 20:33:42 +00005839 pWInfo->nOBSat = pFrom->isOrdered;
drhea6c36e2014-03-19 14:30:55 +00005840 if( pWInfo->nOBSat<0 ) pWInfo->nOBSat = 0;
drh4f402f22013-06-11 18:59:38 +00005841 pWInfo->revMask = pFrom->revLoop;
5842 }
dan374cd782014-04-21 13:21:56 +00005843 if( (pWInfo->wctrlFlags & WHERE_SORTBYGROUP)
5844 && pWInfo->nOBSat==pWInfo->pOrderBy->nExpr
5845 ){
danb6453202014-10-10 20:52:53 +00005846 Bitmask revMask = 0;
dan374cd782014-04-21 13:21:56 +00005847 int nOrder = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy,
danb6453202014-10-10 20:52:53 +00005848 pFrom, 0, nLoop-1, pFrom->aLoop[nLoop-1], &revMask
dan374cd782014-04-21 13:21:56 +00005849 );
5850 assert( pWInfo->sorted==0 );
danb6453202014-10-10 20:52:53 +00005851 if( nOrder==pWInfo->pOrderBy->nExpr ){
5852 pWInfo->sorted = 1;
5853 pWInfo->revMask = revMask;
5854 }
dan374cd782014-04-21 13:21:56 +00005855 }
drh6b7157b2013-05-10 02:00:35 +00005856 }
dan374cd782014-04-21 13:21:56 +00005857
5858
drha50ef112013-05-22 02:06:59 +00005859 pWInfo->nRowOut = pFrom->nRow;
drha18f3d22013-05-08 03:05:41 +00005860
5861 /* Free temporary memory and return success */
5862 sqlite3DbFree(db, pSpace);
5863 return SQLITE_OK;
5864}
drh75897232000-05-29 14:26:00 +00005865
5866/*
drh60c96cd2013-06-09 17:21:25 +00005867** Most queries use only a single table (they are not joins) and have
5868** simple == constraints against indexed fields. This routine attempts
5869** to plan those simple cases using much less ceremony than the
5870** general-purpose query planner, and thereby yield faster sqlite3_prepare()
5871** times for the common case.
5872**
5873** Return non-zero on success, if this query can be handled by this
5874** no-frills query planner. Return zero if this query needs the
5875** general-purpose query planner.
5876*/
drhb8a8e8a2013-06-10 19:12:39 +00005877static int whereShortCut(WhereLoopBuilder *pBuilder){
drh60c96cd2013-06-09 17:21:25 +00005878 WhereInfo *pWInfo;
5879 struct SrcList_item *pItem;
5880 WhereClause *pWC;
5881 WhereTerm *pTerm;
5882 WhereLoop *pLoop;
5883 int iCur;
drh92a121f2013-06-10 12:15:47 +00005884 int j;
drh60c96cd2013-06-09 17:21:25 +00005885 Table *pTab;
5886 Index *pIdx;
5887
5888 pWInfo = pBuilder->pWInfo;
drh5822d6f2013-06-10 23:30:09 +00005889 if( pWInfo->wctrlFlags & WHERE_FORCE_TABLE ) return 0;
drh60c96cd2013-06-09 17:21:25 +00005890 assert( pWInfo->pTabList->nSrc>=1 );
5891 pItem = pWInfo->pTabList->a;
5892 pTab = pItem->pTab;
5893 if( IsVirtual(pTab) ) return 0;
5894 if( pItem->zIndex ) return 0;
5895 iCur = pItem->iCursor;
5896 pWC = &pWInfo->sWC;
5897 pLoop = pBuilder->pNew;
drh60c96cd2013-06-09 17:21:25 +00005898 pLoop->wsFlags = 0;
drhc8bbce12014-10-21 01:05:09 +00005899 pLoop->nSkip = 0;
drh3b75ffa2013-06-10 14:56:25 +00005900 pTerm = findTerm(pWC, iCur, -1, 0, WO_EQ, 0);
drh60c96cd2013-06-09 17:21:25 +00005901 if( pTerm ){
5902 pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
5903 pLoop->aLTerm[0] = pTerm;
5904 pLoop->nLTerm = 1;
5905 pLoop->u.btree.nEq = 1;
drhe1e2e9a2013-06-13 15:16:53 +00005906 /* TUNING: Cost of a rowid lookup is 10 */
drhbf539c42013-10-05 18:16:02 +00005907 pLoop->rRun = 33; /* 33==sqlite3LogEst(10) */
drh60c96cd2013-06-09 17:21:25 +00005908 }else{
5909 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
dancd40abb2013-08-29 10:46:05 +00005910 assert( pLoop->aLTermSpace==pLoop->aLTerm );
drh5f1d1d92014-07-31 22:59:04 +00005911 if( !IsUniqueIndex(pIdx)
dancd40abb2013-08-29 10:46:05 +00005912 || pIdx->pPartIdxWhere!=0
drhbbbdc832013-10-22 18:01:40 +00005913 || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace)
dancd40abb2013-08-29 10:46:05 +00005914 ) continue;
drhbbbdc832013-10-22 18:01:40 +00005915 for(j=0; j<pIdx->nKeyCol; j++){
drh3b75ffa2013-06-10 14:56:25 +00005916 pTerm = findTerm(pWC, iCur, pIdx->aiColumn[j], 0, WO_EQ, pIdx);
drh60c96cd2013-06-09 17:21:25 +00005917 if( pTerm==0 ) break;
drh60c96cd2013-06-09 17:21:25 +00005918 pLoop->aLTerm[j] = pTerm;
5919 }
drhbbbdc832013-10-22 18:01:40 +00005920 if( j!=pIdx->nKeyCol ) continue;
drh92a121f2013-06-10 12:15:47 +00005921 pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
drhec95c442013-10-23 01:57:32 +00005922 if( pIdx->isCovering || (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){
drh92a121f2013-06-10 12:15:47 +00005923 pLoop->wsFlags |= WHERE_IDX_ONLY;
5924 }
drh60c96cd2013-06-09 17:21:25 +00005925 pLoop->nLTerm = j;
5926 pLoop->u.btree.nEq = j;
5927 pLoop->u.btree.pIndex = pIdx;
drhe1e2e9a2013-06-13 15:16:53 +00005928 /* TUNING: Cost of a unique index lookup is 15 */
drhbf539c42013-10-05 18:16:02 +00005929 pLoop->rRun = 39; /* 39==sqlite3LogEst(15) */
drh60c96cd2013-06-09 17:21:25 +00005930 break;
5931 }
5932 }
drh3b75ffa2013-06-10 14:56:25 +00005933 if( pLoop->wsFlags ){
drhbf539c42013-10-05 18:16:02 +00005934 pLoop->nOut = (LogEst)1;
drh3b75ffa2013-06-10 14:56:25 +00005935 pWInfo->a[0].pWLoop = pLoop;
5936 pLoop->maskSelf = getMask(&pWInfo->sMaskSet, iCur);
5937 pWInfo->a[0].iTabCur = iCur;
5938 pWInfo->nRowOut = 1;
drhddba0c22014-03-18 20:33:42 +00005939 if( pWInfo->pOrderBy ) pWInfo->nOBSat = pWInfo->pOrderBy->nExpr;
drh6457a352013-06-21 00:35:37 +00005940 if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
5941 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
5942 }
drh3b75ffa2013-06-10 14:56:25 +00005943#ifdef SQLITE_DEBUG
5944 pLoop->cId = '0';
5945#endif
5946 return 1;
5947 }
5948 return 0;
drh60c96cd2013-06-09 17:21:25 +00005949}
5950
5951/*
drh75897232000-05-29 14:26:00 +00005952** Generate the beginning of the loop used for WHERE clause processing.
5953** The return value is a pointer to an opaque structure that contains
5954** information needed to terminate the loop. Later, the calling routine
5955** should invoke sqlite3WhereEnd() with the return value of this function
5956** in order to complete the WHERE clause processing.
5957**
5958** If an error occurs, this routine returns NULL.
drhc27a1ce2002-06-14 20:58:45 +00005959**
5960** The basic idea is to do a nested loop, one loop for each table in
5961** the FROM clause of a select. (INSERT and UPDATE statements are the
5962** same as a SELECT with only a single table in the FROM clause.) For
5963** example, if the SQL is this:
5964**
5965** SELECT * FROM t1, t2, t3 WHERE ...;
5966**
5967** Then the code generated is conceptually like the following:
5968**
5969** foreach row1 in t1 do \ Code generated
danielk19774adee202004-05-08 08:23:19 +00005970** foreach row2 in t2 do |-- by sqlite3WhereBegin()
drhc27a1ce2002-06-14 20:58:45 +00005971** foreach row3 in t3 do /
5972** ...
5973** end \ Code generated
danielk19774adee202004-05-08 08:23:19 +00005974** end |-- by sqlite3WhereEnd()
drhc27a1ce2002-06-14 20:58:45 +00005975** end /
5976**
drh29dda4a2005-07-21 18:23:20 +00005977** Note that the loops might not be nested in the order in which they
5978** appear in the FROM clause if a different order is better able to make
drh51147ba2005-07-23 22:59:55 +00005979** use of indices. Note also that when the IN operator appears in
5980** the WHERE clause, it might result in additional nested loops for
5981** scanning through all values on the right-hand side of the IN.
drh29dda4a2005-07-21 18:23:20 +00005982**
drhc27a1ce2002-06-14 20:58:45 +00005983** There are Btree cursors associated with each table. t1 uses cursor
drh6a3ea0e2003-05-02 14:32:12 +00005984** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
5985** And so forth. This routine generates code to open those VDBE cursors
danielk19774adee202004-05-08 08:23:19 +00005986** and sqlite3WhereEnd() generates the code to close them.
drhc27a1ce2002-06-14 20:58:45 +00005987**
drhe6f85e72004-12-25 01:03:13 +00005988** The code that sqlite3WhereBegin() generates leaves the cursors named
5989** in pTabList pointing at their appropriate entries. The [...] code
drhf0863fe2005-06-12 21:35:51 +00005990** can use OP_Column and OP_Rowid opcodes on these cursors to extract
drhe6f85e72004-12-25 01:03:13 +00005991** data from the various tables of the loop.
5992**
drhc27a1ce2002-06-14 20:58:45 +00005993** If the WHERE clause is empty, the foreach loops must each scan their
5994** entire tables. Thus a three-way join is an O(N^3) operation. But if
5995** the tables have indices and there are terms in the WHERE clause that
5996** refer to those indices, a complete table scan can be avoided and the
5997** code will run much faster. Most of the work of this routine is checking
5998** to see if there are indices that can be used to speed up the loop.
5999**
6000** Terms of the WHERE clause are also used to limit which rows actually
6001** make it to the "..." in the middle of the loop. After each "foreach",
6002** terms of the WHERE clause that use only terms in that loop and outer
6003** loops are evaluated and if false a jump is made around all subsequent
6004** inner loops (or around the "..." if the test occurs within the inner-
6005** most loop)
6006**
6007** OUTER JOINS
6008**
6009** An outer join of tables t1 and t2 is conceptally coded as follows:
6010**
6011** foreach row1 in t1 do
6012** flag = 0
6013** foreach row2 in t2 do
6014** start:
6015** ...
6016** flag = 1
6017** end
drhe3184742002-06-19 14:27:05 +00006018** if flag==0 then
6019** move the row2 cursor to a null row
6020** goto start
6021** fi
drhc27a1ce2002-06-14 20:58:45 +00006022** end
6023**
drhe3184742002-06-19 14:27:05 +00006024** ORDER BY CLAUSE PROCESSING
6025**
drh94433422013-07-01 11:05:50 +00006026** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause
6027** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement
drhe3184742002-06-19 14:27:05 +00006028** if there is one. If there is no ORDER BY clause or if this routine
drh46ec5b62012-09-24 15:30:54 +00006029** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
drhfc8d4f92013-11-08 15:19:46 +00006030**
6031** The iIdxCur parameter is the cursor number of an index. If
6032** WHERE_ONETABLE_ONLY is set, iIdxCur is the cursor number of an index
6033** to use for OR clause processing. The WHERE clause should use this
6034** specific cursor. If WHERE_ONEPASS_DESIRED is set, then iIdxCur is
6035** the first cursor in an array of cursors for all indices. iIdxCur should
6036** be used to compute the appropriate cursor depending on which index is
6037** used.
drh75897232000-05-29 14:26:00 +00006038*/
danielk19774adee202004-05-08 08:23:19 +00006039WhereInfo *sqlite3WhereBegin(
danielk1977ed326d72004-11-16 15:50:19 +00006040 Parse *pParse, /* The parser context */
drh6457a352013-06-21 00:35:37 +00006041 SrcList *pTabList, /* FROM clause: A list of all tables to be scanned */
danielk1977ed326d72004-11-16 15:50:19 +00006042 Expr *pWhere, /* The WHERE clause */
drh0401ace2014-03-18 15:30:27 +00006043 ExprList *pOrderBy, /* An ORDER BY (or GROUP BY) clause, or NULL */
drh6457a352013-06-21 00:35:37 +00006044 ExprList *pResultSet, /* Result set of the query */
dan0efb72c2012-08-24 18:44:56 +00006045 u16 wctrlFlags, /* One of the WHERE_* flags defined in sqliteInt.h */
6046 int iIdxCur /* If WHERE_ONETABLE_ONLY is set, index cursor number */
drh75897232000-05-29 14:26:00 +00006047){
danielk1977be229652009-03-20 14:18:51 +00006048 int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
drhc01a3c12009-12-16 22:10:49 +00006049 int nTabList; /* Number of elements in pTabList */
drh75897232000-05-29 14:26:00 +00006050 WhereInfo *pWInfo; /* Will become the return value of this function */
6051 Vdbe *v = pParse->pVdbe; /* The virtual database engine */
drhfe05af82005-07-21 03:14:59 +00006052 Bitmask notReady; /* Cursors that are not yet positioned */
drh1c8148f2013-05-04 20:25:23 +00006053 WhereLoopBuilder sWLB; /* The WhereLoop builder */
drh111a6a72008-12-21 03:51:16 +00006054 WhereMaskSet *pMaskSet; /* The expression mask set */
drh56f1b992012-09-25 14:29:39 +00006055 WhereLevel *pLevel; /* A single level in pWInfo->a[] */
drhfd636c72013-06-21 02:05:06 +00006056 WhereLoop *pLoop; /* Pointer to a single WhereLoop object */
drh9cd1c992012-09-25 20:43:35 +00006057 int ii; /* Loop counter */
drh17435752007-08-16 04:30:38 +00006058 sqlite3 *db; /* Database connection */
drh5346e952013-05-08 14:14:26 +00006059 int rc; /* Return code */
drh75897232000-05-29 14:26:00 +00006060
drh56f1b992012-09-25 14:29:39 +00006061
6062 /* Variable initialization */
drhfd636c72013-06-21 02:05:06 +00006063 db = pParse->db;
drh1c8148f2013-05-04 20:25:23 +00006064 memset(&sWLB, 0, sizeof(sWLB));
drh0401ace2014-03-18 15:30:27 +00006065
6066 /* An ORDER/GROUP BY clause of more than 63 terms cannot be optimized */
6067 testcase( pOrderBy && pOrderBy->nExpr==BMS-1 );
6068 if( pOrderBy && pOrderBy->nExpr>=BMS ) pOrderBy = 0;
drh1c8148f2013-05-04 20:25:23 +00006069 sWLB.pOrderBy = pOrderBy;
drh56f1b992012-09-25 14:29:39 +00006070
drhfd636c72013-06-21 02:05:06 +00006071 /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
6072 ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
6073 if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
6074 wctrlFlags &= ~WHERE_WANT_DISTINCT;
6075 }
6076
drh29dda4a2005-07-21 18:23:20 +00006077 /* The number of tables in the FROM clause is limited by the number of
drh1398ad32005-01-19 23:24:50 +00006078 ** bits in a Bitmask
6079 */
drh67ae0cb2010-04-08 14:38:51 +00006080 testcase( pTabList->nSrc==BMS );
drh29dda4a2005-07-21 18:23:20 +00006081 if( pTabList->nSrc>BMS ){
6082 sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
drh1398ad32005-01-19 23:24:50 +00006083 return 0;
6084 }
6085
drhc01a3c12009-12-16 22:10:49 +00006086 /* This function normally generates a nested loop for all tables in
6087 ** pTabList. But if the WHERE_ONETABLE_ONLY flag is set, then we should
6088 ** only generate code for the first table in pTabList and assume that
6089 ** any cursors associated with subsequent tables are uninitialized.
6090 */
6091 nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
6092
drh75897232000-05-29 14:26:00 +00006093 /* Allocate and initialize the WhereInfo structure that will become the
danielk1977be229652009-03-20 14:18:51 +00006094 ** return value. A single allocation is used to store the WhereInfo
6095 ** struct, the contents of WhereInfo.a[], the WhereClause structure
6096 ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
6097 ** field (type Bitmask) it must be aligned on an 8-byte boundary on
6098 ** some architectures. Hence the ROUND8() below.
drh75897232000-05-29 14:26:00 +00006099 */
drhc01a3c12009-12-16 22:10:49 +00006100 nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
drh60c96cd2013-06-09 17:21:25 +00006101 pWInfo = sqlite3DbMallocZero(db, nByteWInfo + sizeof(WhereLoop));
drh17435752007-08-16 04:30:38 +00006102 if( db->mallocFailed ){
drh8b307fb2010-04-06 15:57:05 +00006103 sqlite3DbFree(db, pWInfo);
6104 pWInfo = 0;
danielk197785574e32008-10-06 05:32:18 +00006105 goto whereBeginError;
drh75897232000-05-29 14:26:00 +00006106 }
drhfc8d4f92013-11-08 15:19:46 +00006107 pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1;
drhc01a3c12009-12-16 22:10:49 +00006108 pWInfo->nLevel = nTabList;
drh75897232000-05-29 14:26:00 +00006109 pWInfo->pParse = pParse;
6110 pWInfo->pTabList = pTabList;
drh6b7157b2013-05-10 02:00:35 +00006111 pWInfo->pOrderBy = pOrderBy;
drh6457a352013-06-21 00:35:37 +00006112 pWInfo->pResultSet = pResultSet;
drha22a75e2014-03-21 18:16:23 +00006113 pWInfo->iBreak = pWInfo->iContinue = sqlite3VdbeMakeLabel(v);
drh6df2acd2008-12-28 16:55:25 +00006114 pWInfo->wctrlFlags = wctrlFlags;
drh8b307fb2010-04-06 15:57:05 +00006115 pWInfo->savedNQueryLoop = pParse->nQueryLoop;
drh70d18342013-06-06 19:16:33 +00006116 pMaskSet = &pWInfo->sMaskSet;
drh1c8148f2013-05-04 20:25:23 +00006117 sWLB.pWInfo = pWInfo;
drh70d18342013-06-06 19:16:33 +00006118 sWLB.pWC = &pWInfo->sWC;
drh1ac87e12013-07-18 14:50:56 +00006119 sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);
6120 assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) );
drh60c96cd2013-06-09 17:21:25 +00006121 whereLoopInit(sWLB.pNew);
drhb8a8e8a2013-06-10 19:12:39 +00006122#ifdef SQLITE_DEBUG
6123 sWLB.pNew->cId = '*';
6124#endif
drh08192d52002-04-30 19:20:28 +00006125
drh111a6a72008-12-21 03:51:16 +00006126 /* Split the WHERE clause into separate subexpressions where each
6127 ** subexpression is separated by an AND operator.
6128 */
6129 initMaskSet(pMaskSet);
drh70d18342013-06-06 19:16:33 +00006130 whereClauseInit(&pWInfo->sWC, pWInfo);
drh39759742013-08-02 23:40:45 +00006131 whereSplit(&pWInfo->sWC, pWhere, TK_AND);
drh111a6a72008-12-21 03:51:16 +00006132
drh08192d52002-04-30 19:20:28 +00006133 /* Special case: a WHERE clause that is constant. Evaluate the
6134 ** expression and either jump over all of the code or fall thru.
6135 */
drh759e8582014-01-02 21:05:10 +00006136 for(ii=0; ii<sWLB.pWC->nTerm; ii++){
6137 if( nTabList==0 || sqlite3ExprIsConstantNotJoin(sWLB.pWC->a[ii].pExpr) ){
6138 sqlite3ExprIfFalse(pParse, sWLB.pWC->a[ii].pExpr, pWInfo->iBreak,
6139 SQLITE_JUMPIFNULL);
6140 sWLB.pWC->a[ii].wtFlags |= TERM_CODED;
6141 }
drh08192d52002-04-30 19:20:28 +00006142 }
drh75897232000-05-29 14:26:00 +00006143
drh4fe425a2013-06-12 17:08:06 +00006144 /* Special case: No FROM clause
6145 */
6146 if( nTabList==0 ){
drhddba0c22014-03-18 20:33:42 +00006147 if( pOrderBy ) pWInfo->nOBSat = pOrderBy->nExpr;
drh6457a352013-06-21 00:35:37 +00006148 if( wctrlFlags & WHERE_WANT_DISTINCT ){
6149 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
6150 }
drh4fe425a2013-06-12 17:08:06 +00006151 }
6152
drh42165be2008-03-26 14:56:34 +00006153 /* Assign a bit from the bitmask to every term in the FROM clause.
6154 **
6155 ** When assigning bitmask values to FROM clause cursors, it must be
6156 ** the case that if X is the bitmask for the N-th FROM clause term then
6157 ** the bitmask for all FROM clause terms to the left of the N-th term
6158 ** is (X-1). An expression from the ON clause of a LEFT JOIN can use
6159 ** its Expr.iRightJoinTable value to find the bitmask of the right table
6160 ** of the join. Subtracting one from the right table bitmask gives a
6161 ** bitmask for all tables to the left of the join. Knowing the bitmask
6162 ** for all tables to the left of a left join is important. Ticket #3015.
danielk1977e672c8e2009-05-22 15:43:26 +00006163 **
drhc01a3c12009-12-16 22:10:49 +00006164 ** Note that bitmasks are created for all pTabList->nSrc tables in
6165 ** pTabList, not just the first nTabList tables. nTabList is normally
6166 ** equal to pTabList->nSrc but might be shortened to 1 if the
6167 ** WHERE_ONETABLE_ONLY flag is set.
drh42165be2008-03-26 14:56:34 +00006168 */
drh9cd1c992012-09-25 20:43:35 +00006169 for(ii=0; ii<pTabList->nSrc; ii++){
6170 createMask(pMaskSet, pTabList->a[ii].iCursor);
drh42165be2008-03-26 14:56:34 +00006171 }
6172#ifndef NDEBUG
6173 {
6174 Bitmask toTheLeft = 0;
drh9cd1c992012-09-25 20:43:35 +00006175 for(ii=0; ii<pTabList->nSrc; ii++){
6176 Bitmask m = getMask(pMaskSet, pTabList->a[ii].iCursor);
drh42165be2008-03-26 14:56:34 +00006177 assert( (m-1)==toTheLeft );
6178 toTheLeft |= m;
6179 }
6180 }
6181#endif
6182
drh29dda4a2005-07-21 18:23:20 +00006183 /* Analyze all of the subexpressions. Note that exprAnalyze() might
6184 ** add new virtual terms onto the end of the WHERE clause. We do not
6185 ** want to analyze these virtual terms, so start analyzing at the end
drhb6fb62d2005-09-20 08:47:20 +00006186 ** and work forward so that the added virtual terms are never processed.
drh75897232000-05-29 14:26:00 +00006187 */
drh70d18342013-06-06 19:16:33 +00006188 exprAnalyzeAll(pTabList, &pWInfo->sWC);
drh17435752007-08-16 04:30:38 +00006189 if( db->mallocFailed ){
danielk197785574e32008-10-06 05:32:18 +00006190 goto whereBeginError;
drh0bbaa1b2005-08-19 19:14:12 +00006191 }
drh75897232000-05-29 14:26:00 +00006192
drh6457a352013-06-21 00:35:37 +00006193 if( wctrlFlags & WHERE_WANT_DISTINCT ){
6194 if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){
6195 /* The DISTINCT marking is pointless. Ignore it. */
drh4f402f22013-06-11 18:59:38 +00006196 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
6197 }else if( pOrderBy==0 ){
drh6457a352013-06-21 00:35:37 +00006198 /* Try to ORDER BY the result set to make distinct processing easier */
drh4f402f22013-06-11 18:59:38 +00006199 pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
drh6457a352013-06-21 00:35:37 +00006200 pWInfo->pOrderBy = pResultSet;
drh4f402f22013-06-11 18:59:38 +00006201 }
dan38cc40c2011-06-30 20:17:15 +00006202 }
6203
drhf1b5f5b2013-05-02 00:15:01 +00006204 /* Construct the WhereLoop objects */
drh3b48e8c2013-06-12 20:18:16 +00006205 WHERETRACE(0xffff,("*** Optimizer Start ***\n"));
drhc90713d2014-09-30 13:46:49 +00006206#if defined(WHERETRACE_ENABLED)
6207 /* Display all terms of the WHERE clause */
6208 if( sqlite3WhereTrace & 0x100 ){
6209 int i;
6210 for(i=0; i<sWLB.pWC->nTerm; i++){
6211 whereTermPrint(&sWLB.pWC->a[i], i);
6212 }
6213 }
6214#endif
6215
drhb8a8e8a2013-06-10 19:12:39 +00006216 if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
drh60c96cd2013-06-09 17:21:25 +00006217 rc = whereLoopAddAll(&sWLB);
6218 if( rc ) goto whereBeginError;
6219
6220 /* Display all of the WhereLoop objects if wheretrace is enabled */
drh989578e2013-10-28 14:34:35 +00006221#ifdef WHERETRACE_ENABLED /* !=0 */
drh60c96cd2013-06-09 17:21:25 +00006222 if( sqlite3WhereTrace ){
6223 WhereLoop *p;
drhfd636c72013-06-21 02:05:06 +00006224 int i;
drh60c96cd2013-06-09 17:21:25 +00006225 static char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
6226 "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
drhfd636c72013-06-21 02:05:06 +00006227 for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
6228 p->cId = zLabel[i%sizeof(zLabel)];
drhc1ba2e72013-10-28 19:03:21 +00006229 whereLoopPrint(p, sWLB.pWC);
drh60c96cd2013-06-09 17:21:25 +00006230 }
6231 }
6232#endif
6233
drh4f402f22013-06-11 18:59:38 +00006234 wherePathSolver(pWInfo, 0);
drh60c96cd2013-06-09 17:21:25 +00006235 if( db->mallocFailed ) goto whereBeginError;
6236 if( pWInfo->pOrderBy ){
drhc7f0d222013-06-19 03:27:12 +00006237 wherePathSolver(pWInfo, pWInfo->nRowOut+1);
drh60c96cd2013-06-09 17:21:25 +00006238 if( db->mallocFailed ) goto whereBeginError;
drha18f3d22013-05-08 03:05:41 +00006239 }
6240 }
drh60c96cd2013-06-09 17:21:25 +00006241 if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
drhd84ce352013-06-04 18:27:41 +00006242 pWInfo->revMask = (Bitmask)(-1);
drha50ef112013-05-22 02:06:59 +00006243 }
drh81186b42013-06-18 01:52:41 +00006244 if( pParse->nErr || NEVER(db->mallocFailed) ){
drh75b93402013-05-31 20:43:57 +00006245 goto whereBeginError;
6246 }
drh989578e2013-10-28 14:34:35 +00006247#ifdef WHERETRACE_ENABLED /* !=0 */
drha18f3d22013-05-08 03:05:41 +00006248 if( sqlite3WhereTrace ){
6249 int ii;
drh4f402f22013-06-11 18:59:38 +00006250 sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
drhddba0c22014-03-18 20:33:42 +00006251 if( pWInfo->nOBSat>0 ){
6252 sqlite3DebugPrintf(" ORDERBY=%d,0x%llx", pWInfo->nOBSat, pWInfo->revMask);
drh319f6772013-05-14 15:31:07 +00006253 }
drh4f402f22013-06-11 18:59:38 +00006254 switch( pWInfo->eDistinct ){
6255 case WHERE_DISTINCT_UNIQUE: {
6256 sqlite3DebugPrintf(" DISTINCT=unique");
6257 break;
6258 }
6259 case WHERE_DISTINCT_ORDERED: {
6260 sqlite3DebugPrintf(" DISTINCT=ordered");
6261 break;
6262 }
6263 case WHERE_DISTINCT_UNORDERED: {
6264 sqlite3DebugPrintf(" DISTINCT=unordered");
6265 break;
6266 }
6267 }
6268 sqlite3DebugPrintf("\n");
drhfd636c72013-06-21 02:05:06 +00006269 for(ii=0; ii<pWInfo->nLevel; ii++){
drhc1ba2e72013-10-28 19:03:21 +00006270 whereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC);
drhf1b5f5b2013-05-02 00:15:01 +00006271 }
6272 }
6273#endif
drhfd636c72013-06-21 02:05:06 +00006274 /* Attempt to omit tables from the join that do not effect the result */
drh1031bd92013-06-22 15:44:26 +00006275 if( pWInfo->nLevel>=2
6276 && pResultSet!=0
6277 && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
6278 ){
drhfd636c72013-06-21 02:05:06 +00006279 Bitmask tabUsed = exprListTableUsage(pMaskSet, pResultSet);
drh67a5ec72013-09-03 14:03:47 +00006280 if( sWLB.pOrderBy ) tabUsed |= exprListTableUsage(pMaskSet, sWLB.pOrderBy);
drhfd636c72013-06-21 02:05:06 +00006281 while( pWInfo->nLevel>=2 ){
drh9d5a5792013-06-28 13:43:33 +00006282 WhereTerm *pTerm, *pEnd;
drhfd636c72013-06-21 02:05:06 +00006283 pLoop = pWInfo->a[pWInfo->nLevel-1].pWLoop;
drhbc71b1d2013-06-21 02:15:48 +00006284 if( (pWInfo->pTabList->a[pLoop->iTab].jointype & JT_LEFT)==0 ) break;
6285 if( (wctrlFlags & WHERE_WANT_DISTINCT)==0
6286 && (pLoop->wsFlags & WHERE_ONEROW)==0
drhfd636c72013-06-21 02:05:06 +00006287 ){
drhfd636c72013-06-21 02:05:06 +00006288 break;
6289 }
drhbc71b1d2013-06-21 02:15:48 +00006290 if( (tabUsed & pLoop->maskSelf)!=0 ) break;
drh9d5a5792013-06-28 13:43:33 +00006291 pEnd = sWLB.pWC->a + sWLB.pWC->nTerm;
6292 for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
6293 if( (pTerm->prereqAll & pLoop->maskSelf)!=0
6294 && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
6295 ){
6296 break;
6297 }
6298 }
6299 if( pTerm<pEnd ) break;
drhbc71b1d2013-06-21 02:15:48 +00006300 WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId));
6301 pWInfo->nLevel--;
6302 nTabList--;
drhfd636c72013-06-21 02:05:06 +00006303 }
6304 }
drh3b48e8c2013-06-12 20:18:16 +00006305 WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
drh8e23daf2013-06-11 13:30:04 +00006306 pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
drhf1b5f5b2013-05-02 00:15:01 +00006307
drh08c88eb2008-04-10 13:33:18 +00006308 /* If the caller is an UPDATE or DELETE statement that is requesting
6309 ** to use a one-pass algorithm, determine if this is appropriate.
drh24b7fe92013-09-30 19:33:06 +00006310 ** The one-pass algorithm only works if the WHERE clause constrains
drh08c88eb2008-04-10 13:33:18 +00006311 ** the statement to update a single row.
6312 */
drh165be382008-12-05 02:36:33 +00006313 assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
drh3b48e8c2013-06-12 20:18:16 +00006314 if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
6315 && (pWInfo->a[0].pWLoop->wsFlags & WHERE_ONEROW)!=0 ){
drh08c88eb2008-04-10 13:33:18 +00006316 pWInfo->okOnePass = 1;
drh702ba9f2013-11-07 21:25:13 +00006317 if( HasRowid(pTabList->a[0].pTab) ){
6318 pWInfo->a[0].pWLoop->wsFlags &= ~WHERE_IDX_ONLY;
6319 }
drh08c88eb2008-04-10 13:33:18 +00006320 }
drheb04de32013-05-10 15:16:30 +00006321
drh9012bcb2004-12-19 00:11:35 +00006322 /* Open all tables in the pTabList and any indices selected for
6323 ** searching those tables.
6324 */
drh8b307fb2010-04-06 15:57:05 +00006325 notReady = ~(Bitmask)0;
drh9cd1c992012-09-25 20:43:35 +00006326 for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
danielk1977da184232006-01-05 11:34:32 +00006327 Table *pTab; /* Table to open */
danielk1977da184232006-01-05 11:34:32 +00006328 int iDb; /* Index of database containing table/index */
drh56f1b992012-09-25 14:29:39 +00006329 struct SrcList_item *pTabItem;
drh9012bcb2004-12-19 00:11:35 +00006330
drh29dda4a2005-07-21 18:23:20 +00006331 pTabItem = &pTabList->a[pLevel->iFrom];
drh9012bcb2004-12-19 00:11:35 +00006332 pTab = pTabItem->pTab;
danielk1977595a5232009-07-24 17:58:53 +00006333 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
drh7ba39a92013-05-30 17:43:19 +00006334 pLoop = pLevel->pWLoop;
drh424aab82010-04-06 18:28:20 +00006335 if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
drh75bb9f52010-04-06 18:51:42 +00006336 /* Do nothing */
6337 }else
drh9eff6162006-06-12 21:59:13 +00006338#ifndef SQLITE_OMIT_VIRTUALTABLE
drh7ba39a92013-05-30 17:43:19 +00006339 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
danielk1977595a5232009-07-24 17:58:53 +00006340 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
danielk197793626f42006-06-20 13:07:27 +00006341 int iCur = pTabItem->iCursor;
danielk1977595a5232009-07-24 17:58:53 +00006342 sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
drhfc5e5462012-12-03 17:04:40 +00006343 }else if( IsVirtual(pTab) ){
6344 /* noop */
drh9eff6162006-06-12 21:59:13 +00006345 }else
6346#endif
drh7ba39a92013-05-30 17:43:19 +00006347 if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
drh9ef61f42011-10-07 14:40:59 +00006348 && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){
drhfc8d4f92013-11-08 15:19:46 +00006349 int op = OP_OpenRead;
6350 if( pWInfo->okOnePass ){
6351 op = OP_OpenWrite;
6352 pWInfo->aiCurOnePass[0] = pTabItem->iCursor;
6353 };
drh08c88eb2008-04-10 13:33:18 +00006354 sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
drhfc8d4f92013-11-08 15:19:46 +00006355 assert( pTabItem->iCursor==pLevel->iTabCur );
drh7963b0e2013-06-17 21:37:40 +00006356 testcase( !pWInfo->okOnePass && pTab->nCol==BMS-1 );
6357 testcase( !pWInfo->okOnePass && pTab->nCol==BMS );
drhdd9930e2013-10-23 23:37:02 +00006358 if( !pWInfo->okOnePass && pTab->nCol<BMS && HasRowid(pTab) ){
danielk19779792eef2006-01-13 15:58:43 +00006359 Bitmask b = pTabItem->colUsed;
6360 int n = 0;
drh74161702006-02-24 02:53:49 +00006361 for(; b; b=b>>1, n++){}
drh8cff69d2009-11-12 19:59:44 +00006362 sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
6363 SQLITE_INT_TO_PTR(n), P4_INT32);
danielk19779792eef2006-01-13 15:58:43 +00006364 assert( n<=pTab->nCol );
6365 }
danielk1977c00da102006-01-07 13:21:04 +00006366 }else{
6367 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
drh9012bcb2004-12-19 00:11:35 +00006368 }
drh7e47cb82013-05-31 17:55:27 +00006369 if( pLoop->wsFlags & WHERE_INDEXED ){
drh7ba39a92013-05-30 17:43:19 +00006370 Index *pIx = pLoop->u.btree.pIndex;
drhfc8d4f92013-11-08 15:19:46 +00006371 int iIndexCur;
6372 int op = OP_OpenRead;
drh4308e342013-11-11 16:55:52 +00006373 /* iIdxCur is always set if to a positive value if ONEPASS is possible */
6374 assert( iIdxCur!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 );
drh48dd1d82014-05-27 18:18:58 +00006375 if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIx)
drha3bc66a2014-05-27 17:57:32 +00006376 && (wctrlFlags & WHERE_ONETABLE_ONLY)!=0
6377 ){
6378 /* This is one term of an OR-optimization using the PRIMARY KEY of a
6379 ** WITHOUT ROWID table. No need for a separate index */
6380 iIndexCur = pLevel->iTabCur;
6381 op = 0;
6382 }else if( pWInfo->okOnePass ){
drhfc8d4f92013-11-08 15:19:46 +00006383 Index *pJ = pTabItem->pTab->pIndex;
6384 iIndexCur = iIdxCur;
6385 assert( wctrlFlags & WHERE_ONEPASS_DESIRED );
6386 while( ALWAYS(pJ) && pJ!=pIx ){
6387 iIndexCur++;
6388 pJ = pJ->pNext;
6389 }
6390 op = OP_OpenWrite;
6391 pWInfo->aiCurOnePass[1] = iIndexCur;
6392 }else if( iIdxCur && (wctrlFlags & WHERE_ONETABLE_ONLY)!=0 ){
6393 iIndexCur = iIdxCur;
drh35263192014-07-22 20:02:19 +00006394 if( wctrlFlags & WHERE_REOPEN_IDX ) op = OP_ReopenIdx;
drhfc8d4f92013-11-08 15:19:46 +00006395 }else{
6396 iIndexCur = pParse->nTab++;
6397 }
6398 pLevel->iIdxCur = iIndexCur;
danielk1977da184232006-01-05 11:34:32 +00006399 assert( pIx->pSchema==pTab->pSchema );
drhb0367fb2012-08-25 02:11:13 +00006400 assert( iIndexCur>=0 );
drha3bc66a2014-05-27 17:57:32 +00006401 if( op ){
6402 sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb);
6403 sqlite3VdbeSetP4KeyInfo(pParse, pIx);
6404 VdbeComment((v, "%s", pIx->zName));
6405 }
drh9012bcb2004-12-19 00:11:35 +00006406 }
drhaceb31b2014-02-08 01:40:27 +00006407 if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb);
drh70d18342013-06-06 19:16:33 +00006408 notReady &= ~getMask(&pWInfo->sMaskSet, pTabItem->iCursor);
drh9012bcb2004-12-19 00:11:35 +00006409 }
6410 pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
drha21a64d2010-04-06 22:33:55 +00006411 if( db->mallocFailed ) goto whereBeginError;
drh9012bcb2004-12-19 00:11:35 +00006412
drh29dda4a2005-07-21 18:23:20 +00006413 /* Generate the code to do the search. Each iteration of the for
6414 ** loop below generates code for a single nested loop of the VM
6415 ** program.
drh75897232000-05-29 14:26:00 +00006416 */
drhfe05af82005-07-21 03:14:59 +00006417 notReady = ~(Bitmask)0;
drh9cd1c992012-09-25 20:43:35 +00006418 for(ii=0; ii<nTabList; ii++){
6419 pLevel = &pWInfo->a[ii];
drhcc04afd2013-08-22 02:56:28 +00006420#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
6421 if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){
6422 constructAutomaticIndex(pParse, &pWInfo->sWC,
6423 &pTabList->a[pLevel->iFrom], notReady, pLevel);
6424 if( db->mallocFailed ) goto whereBeginError;
6425 }
6426#endif
drh9cd1c992012-09-25 20:43:35 +00006427 explainOneScan(pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags);
drhcc04afd2013-08-22 02:56:28 +00006428 pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
drh70d18342013-06-06 19:16:33 +00006429 notReady = codeOneLoopStart(pWInfo, ii, notReady);
dan4a07e3d2010-11-09 14:48:59 +00006430 pWInfo->iContinue = pLevel->addrCont;
drh75897232000-05-29 14:26:00 +00006431 }
drh7ec764a2005-07-21 03:48:20 +00006432
drh6fa978d2013-05-30 19:29:19 +00006433 /* Done. */
drh6bc69a22013-11-19 12:33:23 +00006434 VdbeModuleComment((v, "Begin WHERE-core"));
drh75897232000-05-29 14:26:00 +00006435 return pWInfo;
drhe23399f2005-07-22 00:31:39 +00006436
6437 /* Jump here if malloc fails */
danielk197785574e32008-10-06 05:32:18 +00006438whereBeginError:
drh8b307fb2010-04-06 15:57:05 +00006439 if( pWInfo ){
6440 pParse->nQueryLoop = pWInfo->savedNQueryLoop;
6441 whereInfoFree(db, pWInfo);
6442 }
drhe23399f2005-07-22 00:31:39 +00006443 return 0;
drh75897232000-05-29 14:26:00 +00006444}
6445
6446/*
drhc27a1ce2002-06-14 20:58:45 +00006447** Generate the end of the WHERE loop. See comments on
danielk19774adee202004-05-08 08:23:19 +00006448** sqlite3WhereBegin() for additional information.
drh75897232000-05-29 14:26:00 +00006449*/
danielk19774adee202004-05-08 08:23:19 +00006450void sqlite3WhereEnd(WhereInfo *pWInfo){
drh633e6d52008-07-28 19:34:53 +00006451 Parse *pParse = pWInfo->pParse;
6452 Vdbe *v = pParse->pVdbe;
drh19a775c2000-06-05 18:54:46 +00006453 int i;
drh6b563442001-11-07 16:48:26 +00006454 WhereLevel *pLevel;
drh7ba39a92013-05-30 17:43:19 +00006455 WhereLoop *pLoop;
drhad3cab52002-05-24 02:04:32 +00006456 SrcList *pTabList = pWInfo->pTabList;
drh633e6d52008-07-28 19:34:53 +00006457 sqlite3 *db = pParse->db;
drh19a775c2000-06-05 18:54:46 +00006458
drh9012bcb2004-12-19 00:11:35 +00006459 /* Generate loop termination code.
6460 */
drh6bc69a22013-11-19 12:33:23 +00006461 VdbeModuleComment((v, "End WHERE-core"));
drhceea3322009-04-23 13:22:42 +00006462 sqlite3ExprCacheClear(pParse);
drhc01a3c12009-12-16 22:10:49 +00006463 for(i=pWInfo->nLevel-1; i>=0; i--){
drhcd8629e2013-11-13 12:27:25 +00006464 int addr;
drh6b563442001-11-07 16:48:26 +00006465 pLevel = &pWInfo->a[i];
drh7ba39a92013-05-30 17:43:19 +00006466 pLoop = pLevel->pWLoop;
drhb3190c12008-12-08 21:37:14 +00006467 sqlite3VdbeResolveLabel(v, pLevel->addrCont);
drh6b563442001-11-07 16:48:26 +00006468 if( pLevel->op!=OP_Noop ){
drhe39a7322014-02-03 14:04:11 +00006469 sqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3);
drhd1d38482008-10-07 23:46:38 +00006470 sqlite3VdbeChangeP5(v, pLevel->p5);
drh688852a2014-02-17 22:40:43 +00006471 VdbeCoverage(v);
drh7d176102014-02-18 03:07:12 +00006472 VdbeCoverageIf(v, pLevel->op==OP_Next);
6473 VdbeCoverageIf(v, pLevel->op==OP_Prev);
6474 VdbeCoverageIf(v, pLevel->op==OP_VNext);
drh19a775c2000-06-05 18:54:46 +00006475 }
drh7ba39a92013-05-30 17:43:19 +00006476 if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
drh72e8fa42007-03-28 14:30:06 +00006477 struct InLoop *pIn;
drhe23399f2005-07-22 00:31:39 +00006478 int j;
drhb3190c12008-12-08 21:37:14 +00006479 sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
drh111a6a72008-12-21 03:51:16 +00006480 for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
drhb3190c12008-12-08 21:37:14 +00006481 sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
drh2d96b932013-02-08 18:48:23 +00006482 sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
drh688852a2014-02-17 22:40:43 +00006483 VdbeCoverage(v);
drh7d176102014-02-18 03:07:12 +00006484 VdbeCoverageIf(v, pIn->eEndLoopOp==OP_PrevIfOpen);
6485 VdbeCoverageIf(v, pIn->eEndLoopOp==OP_NextIfOpen);
drhb3190c12008-12-08 21:37:14 +00006486 sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
drhe23399f2005-07-22 00:31:39 +00006487 }
drh111a6a72008-12-21 03:51:16 +00006488 sqlite3DbFree(db, pLevel->u.in.aInLoop);
drhd99f7062002-06-08 23:25:08 +00006489 }
drhb3190c12008-12-08 21:37:14 +00006490 sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
drhcd8629e2013-11-13 12:27:25 +00006491 if( pLevel->addrSkip ){
drhcd8629e2013-11-13 12:27:25 +00006492 sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrSkip);
drhe084f402013-11-13 17:24:38 +00006493 VdbeComment((v, "next skip-scan on %s", pLoop->u.btree.pIndex->zName));
drh2e5ef4e2013-11-13 16:58:54 +00006494 sqlite3VdbeJumpHere(v, pLevel->addrSkip);
6495 sqlite3VdbeJumpHere(v, pLevel->addrSkip-2);
drhcd8629e2013-11-13 12:27:25 +00006496 }
drhad2d8302002-05-24 20:31:36 +00006497 if( pLevel->iLeftJoin ){
drh688852a2014-02-17 22:40:43 +00006498 addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v);
drh7ba39a92013-05-30 17:43:19 +00006499 assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
6500 || (pLoop->wsFlags & WHERE_INDEXED)!=0 );
6501 if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 ){
drh35451c62009-11-12 04:26:39 +00006502 sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
6503 }
drh76f4cfb2013-05-31 18:20:52 +00006504 if( pLoop->wsFlags & WHERE_INDEXED ){
drh3c84ddf2008-01-09 02:15:38 +00006505 sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
drh7f09b3e2002-08-13 13:15:49 +00006506 }
drh336a5302009-04-24 15:46:21 +00006507 if( pLevel->op==OP_Return ){
6508 sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
6509 }else{
6510 sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
6511 }
drhd654be82005-09-20 17:42:23 +00006512 sqlite3VdbeJumpHere(v, addr);
drhad2d8302002-05-24 20:31:36 +00006513 }
drh6bc69a22013-11-19 12:33:23 +00006514 VdbeModuleComment((v, "End WHERE-loop%d: %s", i,
drhfc8d4f92013-11-08 15:19:46 +00006515 pWInfo->pTabList->a[pLevel->iFrom].pTab->zName));
drh19a775c2000-06-05 18:54:46 +00006516 }
drh9012bcb2004-12-19 00:11:35 +00006517
6518 /* The "break" point is here, just past the end of the outer loop.
6519 ** Set it.
6520 */
danielk19774adee202004-05-08 08:23:19 +00006521 sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
drh9012bcb2004-12-19 00:11:35 +00006522
drhfd636c72013-06-21 02:05:06 +00006523 assert( pWInfo->nLevel<=pTabList->nSrc );
drhc01a3c12009-12-16 22:10:49 +00006524 for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
drh5f612292014-02-08 23:20:32 +00006525 int k, last;
6526 VdbeOp *pOp;
danbfca6a42012-08-24 10:52:35 +00006527 Index *pIdx = 0;
drh29dda4a2005-07-21 18:23:20 +00006528 struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
drh9012bcb2004-12-19 00:11:35 +00006529 Table *pTab = pTabItem->pTab;
drh5cf590c2003-04-24 01:45:04 +00006530 assert( pTab!=0 );
drh7ba39a92013-05-30 17:43:19 +00006531 pLoop = pLevel->pWLoop;
drhfc8d4f92013-11-08 15:19:46 +00006532
drh5f612292014-02-08 23:20:32 +00006533 /* For a co-routine, change all OP_Column references to the table of
6534 ** the co-routine into OP_SCopy of result contained in a register.
6535 ** OP_Rowid becomes OP_Null.
6536 */
danfbf0f0e2014-03-03 14:20:30 +00006537 if( pTabItem->viaCoroutine && !db->mallocFailed ){
drh5f612292014-02-08 23:20:32 +00006538 last = sqlite3VdbeCurrentAddr(v);
6539 k = pLevel->addrBody;
6540 pOp = sqlite3VdbeGetOp(v, k);
6541 for(; k<last; k++, pOp++){
6542 if( pOp->p1!=pLevel->iTabCur ) continue;
6543 if( pOp->opcode==OP_Column ){
drhc438df12014-04-03 16:29:31 +00006544 pOp->opcode = OP_Copy;
drh5f612292014-02-08 23:20:32 +00006545 pOp->p1 = pOp->p2 + pTabItem->regResult;
6546 pOp->p2 = pOp->p3;
6547 pOp->p3 = 0;
6548 }else if( pOp->opcode==OP_Rowid ){
6549 pOp->opcode = OP_Null;
6550 pOp->p1 = 0;
6551 pOp->p3 = 0;
6552 }
6553 }
6554 continue;
6555 }
6556
drhfc8d4f92013-11-08 15:19:46 +00006557 /* Close all of the cursors that were opened by sqlite3WhereBegin.
6558 ** Except, do not close cursors that will be reused by the OR optimization
6559 ** (WHERE_OMIT_OPEN_CLOSE). And do not close the OP_OpenWrite cursors
6560 ** created for the ONEPASS optimization.
6561 */
drh4139c992010-04-07 14:59:45 +00006562 if( (pTab->tabFlags & TF_Ephemeral)==0
6563 && pTab->pSelect==0
drh9ef61f42011-10-07 14:40:59 +00006564 && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
drh4139c992010-04-07 14:59:45 +00006565 ){
drh7ba39a92013-05-30 17:43:19 +00006566 int ws = pLoop->wsFlags;
drh8b307fb2010-04-06 15:57:05 +00006567 if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
drh6df2acd2008-12-28 16:55:25 +00006568 sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
6569 }
drhfc8d4f92013-11-08 15:19:46 +00006570 if( (ws & WHERE_INDEXED)!=0
6571 && (ws & (WHERE_IPK|WHERE_AUTO_INDEX))==0
6572 && pLevel->iIdxCur!=pWInfo->aiCurOnePass[1]
6573 ){
drh6df2acd2008-12-28 16:55:25 +00006574 sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
6575 }
drh9012bcb2004-12-19 00:11:35 +00006576 }
6577
drhf0030762013-06-14 13:27:01 +00006578 /* If this scan uses an index, make VDBE code substitutions to read data
6579 ** from the index instead of from the table where possible. In some cases
6580 ** this optimization prevents the table from ever being read, which can
6581 ** yield a significant performance boost.
drh9012bcb2004-12-19 00:11:35 +00006582 **
6583 ** Calls to the code generator in between sqlite3WhereBegin and
6584 ** sqlite3WhereEnd will have created code that references the table
6585 ** directly. This loop scans all that code looking for opcodes
6586 ** that reference the table and converts them into opcodes that
6587 ** reference the index.
6588 */
drh7ba39a92013-05-30 17:43:19 +00006589 if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
6590 pIdx = pLoop->u.btree.pIndex;
6591 }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
drhd40e2082012-08-24 23:24:15 +00006592 pIdx = pLevel->u.pCovidx;
danbfca6a42012-08-24 10:52:35 +00006593 }
drh7ba39a92013-05-30 17:43:19 +00006594 if( pIdx && !db->mallocFailed ){
drh9012bcb2004-12-19 00:11:35 +00006595 last = sqlite3VdbeCurrentAddr(v);
drhcc04afd2013-08-22 02:56:28 +00006596 k = pLevel->addrBody;
6597 pOp = sqlite3VdbeGetOp(v, k);
6598 for(; k<last; k++, pOp++){
drh9012bcb2004-12-19 00:11:35 +00006599 if( pOp->p1!=pLevel->iTabCur ) continue;
6600 if( pOp->opcode==OP_Column ){
drhee0ec8e2013-10-31 17:38:01 +00006601 int x = pOp->p2;
drh511717c2013-11-08 17:13:23 +00006602 assert( pIdx->pTable==pTab );
drhee0ec8e2013-10-31 17:38:01 +00006603 if( !HasRowid(pTab) ){
6604 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
6605 x = pPk->aiColumn[x];
6606 }
6607 x = sqlite3ColumnOfIndex(pIdx, x);
drh44156282013-10-23 22:23:03 +00006608 if( x>=0 ){
6609 pOp->p2 = x;
6610 pOp->p1 = pLevel->iIdxCur;
drh9012bcb2004-12-19 00:11:35 +00006611 }
drh44156282013-10-23 22:23:03 +00006612 assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || x>=0 );
drhf0863fe2005-06-12 21:35:51 +00006613 }else if( pOp->opcode==OP_Rowid ){
drh9012bcb2004-12-19 00:11:35 +00006614 pOp->p1 = pLevel->iIdxCur;
drhf0863fe2005-06-12 21:35:51 +00006615 pOp->opcode = OP_IdxRowid;
drh9012bcb2004-12-19 00:11:35 +00006616 }
6617 }
drh6b563442001-11-07 16:48:26 +00006618 }
drh19a775c2000-06-05 18:54:46 +00006619 }
drh9012bcb2004-12-19 00:11:35 +00006620
6621 /* Final cleanup
6622 */
drhf12cde52010-04-08 17:28:00 +00006623 pParse->nQueryLoop = pWInfo->savedNQueryLoop;
6624 whereInfoFree(db, pWInfo);
drh75897232000-05-29 14:26:00 +00006625 return;
6626}