blob: ec7a908b1a24e6059291eb77d7edfdb05c7b2f75 [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) ){
drhbf539c42013-10-05 18:16:02 +0000228 pTerm->truthProb = sqlite3LogEst(p->iTable) - 99;
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/*
drh902b9ee2008-12-05 17:17:07 +0000368** Swap two objects of type TYPE.
drh193bd772004-07-20 18:23:14 +0000369*/
370#define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
371
372/*
drh909626d2008-05-30 14:58:37 +0000373** Commute a comparison operator. Expressions of the form "X op Y"
drh0fcef5e2005-07-19 17:38:22 +0000374** are converted into "Y op X".
danielk1977eb5453d2007-07-30 14:40:48 +0000375**
mistachkin48864df2013-03-21 21:20:32 +0000376** If left/right precedence rules come into play when determining the
drh3b48e8c2013-06-12 20:18:16 +0000377** collating sequence, then COLLATE operators are adjusted to ensure
378** that the collating sequence does not change. For example:
379** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on
danielk1977eb5453d2007-07-30 14:40:48 +0000380** the left hand side of a comparison overrides any collation sequence
drhae80dde2012-12-06 21:16:43 +0000381** attached to the right. For the same reason the EP_Collate flag
danielk1977eb5453d2007-07-30 14:40:48 +0000382** is not commuted.
drh193bd772004-07-20 18:23:14 +0000383*/
drh7d10d5a2008-08-20 16:35:10 +0000384static void exprCommute(Parse *pParse, Expr *pExpr){
drhae80dde2012-12-06 21:16:43 +0000385 u16 expRight = (pExpr->pRight->flags & EP_Collate);
386 u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
drhfe05af82005-07-21 03:14:59 +0000387 assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
drhae80dde2012-12-06 21:16:43 +0000388 if( expRight==expLeft ){
389 /* Either X and Y both have COLLATE operator or neither do */
390 if( expRight ){
391 /* Both X and Y have COLLATE operators. Make sure X is always
392 ** used by clearing the EP_Collate flag from Y. */
393 pExpr->pRight->flags &= ~EP_Collate;
394 }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
395 /* Neither X nor Y have COLLATE operators, but X has a non-default
396 ** collating sequence. So add the EP_Collate marker on X to cause
397 ** it to be searched first. */
398 pExpr->pLeft->flags |= EP_Collate;
399 }
400 }
drh0fcef5e2005-07-19 17:38:22 +0000401 SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
402 if( pExpr->op>=TK_GT ){
403 assert( TK_LT==TK_GT+2 );
404 assert( TK_GE==TK_LE+2 );
405 assert( TK_GT>TK_EQ );
406 assert( TK_GT<TK_LE );
407 assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
408 pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
drh193bd772004-07-20 18:23:14 +0000409 }
drh193bd772004-07-20 18:23:14 +0000410}
411
412/*
drhfe05af82005-07-21 03:14:59 +0000413** Translate from TK_xx operator to WO_xx bitmask.
414*/
drhec1724e2008-12-09 01:32:03 +0000415static u16 operatorMask(int op){
416 u16 c;
drhfe05af82005-07-21 03:14:59 +0000417 assert( allowedOp(op) );
418 if( op==TK_IN ){
drh51147ba2005-07-23 22:59:55 +0000419 c = WO_IN;
drh50b39962006-10-28 00:28:09 +0000420 }else if( op==TK_ISNULL ){
421 c = WO_ISNULL;
drhfe05af82005-07-21 03:14:59 +0000422 }else{
drhec1724e2008-12-09 01:32:03 +0000423 assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
424 c = (u16)(WO_EQ<<(op-TK_EQ));
drhfe05af82005-07-21 03:14:59 +0000425 }
drh50b39962006-10-28 00:28:09 +0000426 assert( op!=TK_ISNULL || c==WO_ISNULL );
drh51147ba2005-07-23 22:59:55 +0000427 assert( op!=TK_IN || c==WO_IN );
428 assert( op!=TK_EQ || c==WO_EQ );
429 assert( op!=TK_LT || c==WO_LT );
430 assert( op!=TK_LE || c==WO_LE );
431 assert( op!=TK_GT || c==WO_GT );
432 assert( op!=TK_GE || c==WO_GE );
433 return c;
drhfe05af82005-07-21 03:14:59 +0000434}
435
436/*
drh1c8148f2013-05-04 20:25:23 +0000437** Advance to the next WhereTerm that matches according to the criteria
438** established when the pScan object was initialized by whereScanInit().
439** Return NULL if there are no more matching WhereTerms.
440*/
danb2cfc142013-07-05 11:10:54 +0000441static WhereTerm *whereScanNext(WhereScan *pScan){
drh1c8148f2013-05-04 20:25:23 +0000442 int iCur; /* The cursor on the LHS of the term */
443 int iColumn; /* The column on the LHS of the term. -1 for IPK */
444 Expr *pX; /* An expression being tested */
445 WhereClause *pWC; /* Shorthand for pScan->pWC */
446 WhereTerm *pTerm; /* The term being tested */
drh43b85ef2013-06-10 12:34:45 +0000447 int k = pScan->k; /* Where to start scanning */
drh1c8148f2013-05-04 20:25:23 +0000448
449 while( pScan->iEquiv<=pScan->nEquiv ){
450 iCur = pScan->aEquiv[pScan->iEquiv-2];
451 iColumn = pScan->aEquiv[pScan->iEquiv-1];
452 while( (pWC = pScan->pWC)!=0 ){
drh43b85ef2013-06-10 12:34:45 +0000453 for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
drhe1a086e2013-10-28 20:15:56 +0000454 if( pTerm->leftCursor==iCur
455 && pTerm->u.leftColumn==iColumn
456 && (pScan->iEquiv<=2 || !ExprHasProperty(pTerm->pExpr, EP_FromJoin))
457 ){
drh1c8148f2013-05-04 20:25:23 +0000458 if( (pTerm->eOperator & WO_EQUIV)!=0
459 && pScan->nEquiv<ArraySize(pScan->aEquiv)
460 ){
461 int j;
462 pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight);
463 assert( pX->op==TK_COLUMN );
464 for(j=0; j<pScan->nEquiv; j+=2){
465 if( pScan->aEquiv[j]==pX->iTable
466 && pScan->aEquiv[j+1]==pX->iColumn ){
467 break;
468 }
469 }
470 if( j==pScan->nEquiv ){
471 pScan->aEquiv[j] = pX->iTable;
472 pScan->aEquiv[j+1] = pX->iColumn;
473 pScan->nEquiv += 2;
474 }
475 }
476 if( (pTerm->eOperator & pScan->opMask)!=0 ){
477 /* Verify the affinity and collating sequence match */
478 if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
479 CollSeq *pColl;
drh70d18342013-06-06 19:16:33 +0000480 Parse *pParse = pWC->pWInfo->pParse;
drh1c8148f2013-05-04 20:25:23 +0000481 pX = pTerm->pExpr;
482 if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
483 continue;
484 }
485 assert(pX->pLeft);
drh70d18342013-06-06 19:16:33 +0000486 pColl = sqlite3BinaryCompareCollSeq(pParse,
drh1c8148f2013-05-04 20:25:23 +0000487 pX->pLeft, pX->pRight);
drh70d18342013-06-06 19:16:33 +0000488 if( pColl==0 ) pColl = pParse->db->pDfltColl;
drh1c8148f2013-05-04 20:25:23 +0000489 if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
490 continue;
491 }
492 }
drha184fb82013-05-08 04:22:59 +0000493 if( (pTerm->eOperator & WO_EQ)!=0
494 && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN
495 && pX->iTable==pScan->aEquiv[0]
496 && pX->iColumn==pScan->aEquiv[1]
497 ){
498 continue;
499 }
drh43b85ef2013-06-10 12:34:45 +0000500 pScan->k = k+1;
drh1c8148f2013-05-04 20:25:23 +0000501 return pTerm;
502 }
503 }
504 }
drhad01d892013-06-19 13:59:49 +0000505 pScan->pWC = pScan->pWC->pOuter;
drh43b85ef2013-06-10 12:34:45 +0000506 k = 0;
drh1c8148f2013-05-04 20:25:23 +0000507 }
508 pScan->pWC = pScan->pOrigWC;
drh43b85ef2013-06-10 12:34:45 +0000509 k = 0;
drh1c8148f2013-05-04 20:25:23 +0000510 pScan->iEquiv += 2;
511 }
drh1c8148f2013-05-04 20:25:23 +0000512 return 0;
513}
514
515/*
516** Initialize a WHERE clause scanner object. Return a pointer to the
517** first match. Return NULL if there are no matches.
518**
519** The scanner will be searching the WHERE clause pWC. It will look
520** for terms of the form "X <op> <expr>" where X is column iColumn of table
521** iCur. The <op> must be one of the operators described by opMask.
522**
drh3b48e8c2013-06-12 20:18:16 +0000523** If the search is for X and the WHERE clause contains terms of the
524** form X=Y then this routine might also return terms of the form
525** "Y <op> <expr>". The number of levels of transitivity is limited,
526** but is enough to handle most commonly occurring SQL statements.
527**
drh1c8148f2013-05-04 20:25:23 +0000528** If X is not the INTEGER PRIMARY KEY then X must be compatible with
529** index pIdx.
530*/
danb2cfc142013-07-05 11:10:54 +0000531static WhereTerm *whereScanInit(
drh1c8148f2013-05-04 20:25:23 +0000532 WhereScan *pScan, /* The WhereScan object being initialized */
533 WhereClause *pWC, /* The WHERE clause to be scanned */
534 int iCur, /* Cursor to scan for */
535 int iColumn, /* Column to scan for */
536 u32 opMask, /* Operator(s) to scan for */
537 Index *pIdx /* Must be compatible with this index */
538){
539 int j;
540
drhe9d935a2013-06-05 16:19:59 +0000541 /* memset(pScan, 0, sizeof(*pScan)); */
drh1c8148f2013-05-04 20:25:23 +0000542 pScan->pOrigWC = pWC;
543 pScan->pWC = pWC;
544 if( pIdx && iColumn>=0 ){
545 pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
546 for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
drhbbbdc832013-10-22 18:01:40 +0000547 if( NEVER(j>=pIdx->nKeyCol) ) return 0;
drh1c8148f2013-05-04 20:25:23 +0000548 }
549 pScan->zCollName = pIdx->azColl[j];
drhe9d935a2013-06-05 16:19:59 +0000550 }else{
551 pScan->idxaff = 0;
552 pScan->zCollName = 0;
drh1c8148f2013-05-04 20:25:23 +0000553 }
554 pScan->opMask = opMask;
drhe9d935a2013-06-05 16:19:59 +0000555 pScan->k = 0;
drh1c8148f2013-05-04 20:25:23 +0000556 pScan->aEquiv[0] = iCur;
557 pScan->aEquiv[1] = iColumn;
558 pScan->nEquiv = 2;
559 pScan->iEquiv = 2;
560 return whereScanNext(pScan);
561}
562
563/*
drhfe05af82005-07-21 03:14:59 +0000564** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
565** where X is a reference to the iColumn of table iCur and <op> is one of
566** the WO_xx operator codes specified by the op parameter.
567** Return a pointer to the term. Return 0 if not found.
drh58eb1c02013-01-17 00:08:42 +0000568**
569** The term returned might by Y=<expr> if there is another constraint in
570** the WHERE clause that specifies that X=Y. Any such constraints will be
571** identified by the WO_EQUIV bit in the pTerm->eOperator field. The
572** aEquiv[] array holds X and all its equivalents, with each SQL variable
573** taking up two slots in aEquiv[]. The first slot is for the cursor number
574** and the second is for the column number. There are 22 slots in aEquiv[]
575** so that means we can look for X plus up to 10 other equivalent values.
576** Hence a search for X will return <expr> if X=A1 and A1=A2 and A2=A3
577** and ... and A9=A10 and A10=<expr>.
578**
579** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
580** then try for the one with no dependencies on <expr> - in other words where
581** <expr> is a constant expression of some kind. Only return entries of
582** the form "X <op> Y" where Y is a column in another table if no terms of
drh459f63e2013-03-06 01:55:27 +0000583** the form "X <op> <const-expr>" exist. If no terms with a constant RHS
584** exist, try to return a term that does not use WO_EQUIV.
drhfe05af82005-07-21 03:14:59 +0000585*/
586static WhereTerm *findTerm(
587 WhereClause *pWC, /* The WHERE clause to be searched */
588 int iCur, /* Cursor number of LHS */
589 int iColumn, /* Column number of LHS */
590 Bitmask notReady, /* RHS must not overlap with this mask */
drhec1724e2008-12-09 01:32:03 +0000591 u32 op, /* Mask of WO_xx values describing operator */
drhfe05af82005-07-21 03:14:59 +0000592 Index *pIdx /* Must be compatible with this index, if not NULL */
593){
drh1c8148f2013-05-04 20:25:23 +0000594 WhereTerm *pResult = 0;
595 WhereTerm *p;
596 WhereScan scan;
drh7a5bcc02013-01-16 17:08:58 +0000597
drh1c8148f2013-05-04 20:25:23 +0000598 p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
599 while( p ){
600 if( (p->prereqRight & notReady)==0 ){
601 if( p->prereqRight==0 && (p->eOperator&WO_EQ)!=0 ){
602 return p;
drhfe05af82005-07-21 03:14:59 +0000603 }
drh1c8148f2013-05-04 20:25:23 +0000604 if( pResult==0 ) pResult = p;
drhfe05af82005-07-21 03:14:59 +0000605 }
drh1c8148f2013-05-04 20:25:23 +0000606 p = whereScanNext(&scan);
drhfe05af82005-07-21 03:14:59 +0000607 }
drh7a5bcc02013-01-16 17:08:58 +0000608 return pResult;
drhfe05af82005-07-21 03:14:59 +0000609}
610
drh6c30be82005-07-29 15:10:17 +0000611/* Forward reference */
drh7b4fc6a2007-02-06 13:26:32 +0000612static void exprAnalyze(SrcList*, WhereClause*, int);
drh6c30be82005-07-29 15:10:17 +0000613
614/*
615** Call exprAnalyze on all terms in a WHERE clause.
drh6c30be82005-07-29 15:10:17 +0000616*/
617static void exprAnalyzeAll(
618 SrcList *pTabList, /* the FROM clause */
drh6c30be82005-07-29 15:10:17 +0000619 WhereClause *pWC /* the WHERE clause to be analyzed */
620){
drh6c30be82005-07-29 15:10:17 +0000621 int i;
drh9eb20282005-08-24 03:52:18 +0000622 for(i=pWC->nTerm-1; i>=0; i--){
drh7b4fc6a2007-02-06 13:26:32 +0000623 exprAnalyze(pTabList, pWC, i);
drh6c30be82005-07-29 15:10:17 +0000624 }
625}
626
drhd2687b72005-08-12 22:56:09 +0000627#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
628/*
629** Check to see if the given expression is a LIKE or GLOB operator that
630** can be optimized using inequality constraints. Return TRUE if it is
631** so and false if not.
632**
633** In order for the operator to be optimizible, the RHS must be a string
634** literal that does not begin with a wildcard.
635*/
636static int isLikeOrGlob(
drh7d10d5a2008-08-20 16:35:10 +0000637 Parse *pParse, /* Parsing and code generating context */
drhd2687b72005-08-12 22:56:09 +0000638 Expr *pExpr, /* Test this expression */
dan937d0de2009-10-15 18:35:38 +0000639 Expr **ppPrefix, /* Pointer to TK_STRING expression with pattern prefix */
drh9f504ea2008-02-23 21:55:39 +0000640 int *pisComplete, /* True if the only wildcard is % in the last character */
641 int *pnoCase /* True if uppercase is equivalent to lowercase */
drhd2687b72005-08-12 22:56:09 +0000642){
dan937d0de2009-10-15 18:35:38 +0000643 const char *z = 0; /* String on RHS of LIKE operator */
drh5bd98ae2009-01-07 18:24:03 +0000644 Expr *pRight, *pLeft; /* Right and left size of LIKE operator */
645 ExprList *pList; /* List of operands to the LIKE operator */
646 int c; /* One character in z[] */
647 int cnt; /* Number of non-wildcard prefix characters */
648 char wc[3]; /* Wildcard characters */
drh5bd98ae2009-01-07 18:24:03 +0000649 sqlite3 *db = pParse->db; /* Database connection */
dan937d0de2009-10-15 18:35:38 +0000650 sqlite3_value *pVal = 0;
651 int op; /* Opcode of pRight */
drhd64fe2f2005-08-28 17:00:23 +0000652
drh9f504ea2008-02-23 21:55:39 +0000653 if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
drhd2687b72005-08-12 22:56:09 +0000654 return 0;
655 }
drh9f504ea2008-02-23 21:55:39 +0000656#ifdef SQLITE_EBCDIC
657 if( *pnoCase ) return 0;
658#endif
danielk19776ab3a2e2009-02-19 14:39:25 +0000659 pList = pExpr->x.pList;
drh55ef4d92005-08-14 01:20:37 +0000660 pLeft = pList->a[1].pExpr;
danc68939e2012-03-29 14:29:07 +0000661 if( pLeft->op!=TK_COLUMN
662 || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
663 || IsVirtual(pLeft->pTab)
664 ){
drhd91ca492009-10-22 20:50:36 +0000665 /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
666 ** be the name of an indexed column with TEXT affinity. */
drhd2687b72005-08-12 22:56:09 +0000667 return 0;
668 }
drhd91ca492009-10-22 20:50:36 +0000669 assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
dan937d0de2009-10-15 18:35:38 +0000670
drh6ade4532014-01-16 15:31:41 +0000671 pRight = sqlite3ExprSkipCollate(pList->a[0].pExpr);
dan937d0de2009-10-15 18:35:38 +0000672 op = pRight->op;
dan937d0de2009-10-15 18:35:38 +0000673 if( op==TK_VARIABLE ){
674 Vdbe *pReprepare = pParse->pReprepare;
drha7044002010-09-14 18:22:59 +0000675 int iCol = pRight->iColumn;
drhcf0fd4a2013-08-01 12:21:58 +0000676 pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_NONE);
dan937d0de2009-10-15 18:35:38 +0000677 if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
678 z = (char *)sqlite3_value_text(pVal);
679 }
drhf9b22ca2011-10-21 16:47:31 +0000680 sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
dan937d0de2009-10-15 18:35:38 +0000681 assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
682 }else if( op==TK_STRING ){
683 z = pRight->u.zToken;
684 }
685 if( z ){
shane85095702009-06-15 16:27:08 +0000686 cnt = 0;
drhb7916a72009-05-27 10:31:29 +0000687 while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
drh24fb6272009-05-01 21:13:36 +0000688 cnt++;
689 }
drh93ee23c2010-07-22 12:33:57 +0000690 if( cnt!=0 && 255!=(u8)z[cnt-1] ){
dan937d0de2009-10-15 18:35:38 +0000691 Expr *pPrefix;
drh93ee23c2010-07-22 12:33:57 +0000692 *pisComplete = c==wc[0] && z[cnt+1]==0;
dan937d0de2009-10-15 18:35:38 +0000693 pPrefix = sqlite3Expr(db, TK_STRING, z);
694 if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
695 *ppPrefix = pPrefix;
696 if( op==TK_VARIABLE ){
697 Vdbe *v = pParse->pVdbe;
drhf9b22ca2011-10-21 16:47:31 +0000698 sqlite3VdbeSetVarmask(v, pRight->iColumn);
dan937d0de2009-10-15 18:35:38 +0000699 if( *pisComplete && pRight->u.zToken[1] ){
700 /* If the rhs of the LIKE expression is a variable, and the current
701 ** value of the variable means there is no need to invoke the LIKE
702 ** function, then no OP_Variable will be added to the program.
703 ** This causes problems for the sqlite3_bind_parameter_name()
drhbec451f2009-10-17 13:13:02 +0000704 ** API. To workaround them, add a dummy OP_Variable here.
705 */
706 int r1 = sqlite3GetTempReg(pParse);
707 sqlite3ExprCodeTarget(pParse, pRight, r1);
dan937d0de2009-10-15 18:35:38 +0000708 sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
drhbec451f2009-10-17 13:13:02 +0000709 sqlite3ReleaseTempReg(pParse, r1);
dan937d0de2009-10-15 18:35:38 +0000710 }
711 }
712 }else{
713 z = 0;
shane85095702009-06-15 16:27:08 +0000714 }
drhf998b732007-11-26 13:36:00 +0000715 }
dan937d0de2009-10-15 18:35:38 +0000716
717 sqlite3ValueFree(pVal);
718 return (z!=0);
drhd2687b72005-08-12 22:56:09 +0000719}
720#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
721
drhedb193b2006-06-27 13:20:21 +0000722
723#ifndef SQLITE_OMIT_VIRTUALTABLE
drhfe05af82005-07-21 03:14:59 +0000724/*
drh7f375902006-06-13 17:38:59 +0000725** Check to see if the given expression is of the form
726**
727** column MATCH expr
728**
729** If it is then return TRUE. If not, return FALSE.
730*/
731static int isMatchOfColumn(
732 Expr *pExpr /* Test this expression */
733){
734 ExprList *pList;
735
736 if( pExpr->op!=TK_FUNCTION ){
737 return 0;
738 }
drh33e619f2009-05-28 01:00:55 +0000739 if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
drh7f375902006-06-13 17:38:59 +0000740 return 0;
741 }
danielk19776ab3a2e2009-02-19 14:39:25 +0000742 pList = pExpr->x.pList;
drh7f375902006-06-13 17:38:59 +0000743 if( pList->nExpr!=2 ){
744 return 0;
745 }
746 if( pList->a[1].pExpr->op != TK_COLUMN ){
747 return 0;
748 }
749 return 1;
750}
drhedb193b2006-06-27 13:20:21 +0000751#endif /* SQLITE_OMIT_VIRTUALTABLE */
drh7f375902006-06-13 17:38:59 +0000752
753/*
drh54a167d2005-11-26 14:08:07 +0000754** If the pBase expression originated in the ON or USING clause of
755** a join, then transfer the appropriate markings over to derived.
756*/
757static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
drhd41d39f2013-08-28 16:27:01 +0000758 if( pDerived ){
759 pDerived->flags |= pBase->flags & EP_FromJoin;
760 pDerived->iRightJoinTable = pBase->iRightJoinTable;
761 }
drh54a167d2005-11-26 14:08:07 +0000762}
763
drh3e355802007-02-23 23:13:33 +0000764#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
765/*
drh1a58fe02008-12-20 02:06:13 +0000766** Analyze a term that consists of two or more OR-connected
767** subterms. So in:
drh3e355802007-02-23 23:13:33 +0000768**
drh1a58fe02008-12-20 02:06:13 +0000769** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
770** ^^^^^^^^^^^^^^^^^^^^
drh3e355802007-02-23 23:13:33 +0000771**
drh1a58fe02008-12-20 02:06:13 +0000772** This routine analyzes terms such as the middle term in the above example.
773** A WhereOrTerm object is computed and attached to the term under
774** analysis, regardless of the outcome of the analysis. Hence:
drh3e355802007-02-23 23:13:33 +0000775**
drh1a58fe02008-12-20 02:06:13 +0000776** WhereTerm.wtFlags |= TERM_ORINFO
777** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object
drh3e355802007-02-23 23:13:33 +0000778**
drh1a58fe02008-12-20 02:06:13 +0000779** The term being analyzed must have two or more of OR-connected subterms.
danielk1977fdc40192008-12-29 18:33:32 +0000780** A single subterm might be a set of AND-connected sub-subterms.
drh1a58fe02008-12-20 02:06:13 +0000781** Examples of terms under analysis:
drh3e355802007-02-23 23:13:33 +0000782**
drh1a58fe02008-12-20 02:06:13 +0000783** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
784** (B) x=expr1 OR expr2=x OR x=expr3
785** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
786** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
787** (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 +0000788**
drh1a58fe02008-12-20 02:06:13 +0000789** CASE 1:
790**
drhc3e552f2013-02-08 16:04:19 +0000791** If all subterms are of the form T.C=expr for some single column of C and
drh1a58fe02008-12-20 02:06:13 +0000792** a single table T (as shown in example B above) then create a new virtual
793** term that is an equivalent IN expression. In other words, if the term
794** being analyzed is:
795**
796** x = expr1 OR expr2 = x OR x = expr3
797**
798** then create a new virtual term like this:
799**
800** x IN (expr1,expr2,expr3)
801**
802** CASE 2:
803**
804** If all subterms are indexable by a single table T, then set
805**
806** WhereTerm.eOperator = WO_OR
807** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T
808**
809** A subterm is "indexable" if it is of the form
810** "T.C <op> <expr>" where C is any column of table T and
811** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
812** A subterm is also indexable if it is an AND of two or more
813** subsubterms at least one of which is indexable. Indexable AND
814** subterms have their eOperator set to WO_AND and they have
815** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
816**
817** From another point of view, "indexable" means that the subterm could
818** potentially be used with an index if an appropriate index exists.
819** This analysis does not consider whether or not the index exists; that
drh4a6fc352013-08-07 01:18:38 +0000820** is decided elsewhere. This analysis only looks at whether subterms
821** appropriate for indexing exist.
drh1a58fe02008-12-20 02:06:13 +0000822**
drh4a6fc352013-08-07 01:18:38 +0000823** All examples A through E above satisfy case 2. But if a term
drh1a58fe02008-12-20 02:06:13 +0000824** also statisfies case 1 (such as B) we know that the optimizer will
825** always prefer case 1, so in that case we pretend that case 2 is not
826** satisfied.
827**
828** It might be the case that multiple tables are indexable. For example,
829** (E) above is indexable on tables P, Q, and R.
830**
831** Terms that satisfy case 2 are candidates for lookup by using
832** separate indices to find rowids for each subterm and composing
833** the union of all rowids using a RowSet object. This is similar
834** to "bitmap indices" in other database engines.
835**
836** OTHERWISE:
837**
838** If neither case 1 nor case 2 apply, then leave the eOperator set to
839** zero. This term is not useful for search.
drh3e355802007-02-23 23:13:33 +0000840*/
drh1a58fe02008-12-20 02:06:13 +0000841static void exprAnalyzeOrTerm(
842 SrcList *pSrc, /* the FROM clause */
843 WhereClause *pWC, /* the complete WHERE clause */
844 int idxTerm /* Index of the OR-term to be analyzed */
845){
drh70d18342013-06-06 19:16:33 +0000846 WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
847 Parse *pParse = pWInfo->pParse; /* Parser context */
drh1a58fe02008-12-20 02:06:13 +0000848 sqlite3 *db = pParse->db; /* Database connection */
849 WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */
850 Expr *pExpr = pTerm->pExpr; /* The expression of the term */
drh1a58fe02008-12-20 02:06:13 +0000851 int i; /* Loop counters */
852 WhereClause *pOrWc; /* Breakup of pTerm into subterms */
853 WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */
854 WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */
855 Bitmask chngToIN; /* Tables that might satisfy case 1 */
856 Bitmask indexable; /* Tables that are indexable, satisfying case 2 */
drh3e355802007-02-23 23:13:33 +0000857
drh1a58fe02008-12-20 02:06:13 +0000858 /*
859 ** Break the OR clause into its separate subterms. The subterms are
860 ** stored in a WhereClause structure containing within the WhereOrInfo
861 ** object that is attached to the original OR clause term.
862 */
863 assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
864 assert( pExpr->op==TK_OR );
drh954701a2008-12-29 23:45:07 +0000865 pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
drh1a58fe02008-12-20 02:06:13 +0000866 if( pOrInfo==0 ) return;
867 pTerm->wtFlags |= TERM_ORINFO;
868 pOrWc = &pOrInfo->wc;
drh70d18342013-06-06 19:16:33 +0000869 whereClauseInit(pOrWc, pWInfo);
drh1a58fe02008-12-20 02:06:13 +0000870 whereSplit(pOrWc, pExpr, TK_OR);
871 exprAnalyzeAll(pSrc, pOrWc);
872 if( db->mallocFailed ) return;
873 assert( pOrWc->nTerm>=2 );
874
875 /*
876 ** Compute the set of tables that might satisfy cases 1 or 2.
877 */
danielk1977e672c8e2009-05-22 15:43:26 +0000878 indexable = ~(Bitmask)0;
drhc3e552f2013-02-08 16:04:19 +0000879 chngToIN = ~(Bitmask)0;
drh1a58fe02008-12-20 02:06:13 +0000880 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
881 if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
drh29435252008-12-28 18:35:08 +0000882 WhereAndInfo *pAndInfo;
drh29435252008-12-28 18:35:08 +0000883 assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
drh1a58fe02008-12-20 02:06:13 +0000884 chngToIN = 0;
drh29435252008-12-28 18:35:08 +0000885 pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
886 if( pAndInfo ){
887 WhereClause *pAndWC;
888 WhereTerm *pAndTerm;
889 int j;
890 Bitmask b = 0;
891 pOrTerm->u.pAndInfo = pAndInfo;
892 pOrTerm->wtFlags |= TERM_ANDINFO;
893 pOrTerm->eOperator = WO_AND;
894 pAndWC = &pAndInfo->wc;
drh70d18342013-06-06 19:16:33 +0000895 whereClauseInit(pAndWC, pWC->pWInfo);
drh29435252008-12-28 18:35:08 +0000896 whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
897 exprAnalyzeAll(pSrc, pAndWC);
drh8871ef52011-10-07 13:33:10 +0000898 pAndWC->pOuter = pWC;
drh7c2fbde2009-01-07 20:58:57 +0000899 testcase( db->mallocFailed );
drh96c7a7d2009-01-10 15:34:12 +0000900 if( !db->mallocFailed ){
901 for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
902 assert( pAndTerm->pExpr );
903 if( allowedOp(pAndTerm->pExpr->op) ){
drh70d18342013-06-06 19:16:33 +0000904 b |= getMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
drh96c7a7d2009-01-10 15:34:12 +0000905 }
drh29435252008-12-28 18:35:08 +0000906 }
907 }
908 indexable &= b;
909 }
drh1a58fe02008-12-20 02:06:13 +0000910 }else if( pOrTerm->wtFlags & TERM_COPIED ){
911 /* Skip this term for now. We revisit it when we process the
912 ** corresponding TERM_VIRTUAL term */
913 }else{
914 Bitmask b;
drh70d18342013-06-06 19:16:33 +0000915 b = getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
drh1a58fe02008-12-20 02:06:13 +0000916 if( pOrTerm->wtFlags & TERM_VIRTUAL ){
917 WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
drh70d18342013-06-06 19:16:33 +0000918 b |= getMask(&pWInfo->sMaskSet, pOther->leftCursor);
drh1a58fe02008-12-20 02:06:13 +0000919 }
920 indexable &= b;
drh7a5bcc02013-01-16 17:08:58 +0000921 if( (pOrTerm->eOperator & WO_EQ)==0 ){
drh1a58fe02008-12-20 02:06:13 +0000922 chngToIN = 0;
923 }else{
924 chngToIN &= b;
925 }
926 }
drh3e355802007-02-23 23:13:33 +0000927 }
drh1a58fe02008-12-20 02:06:13 +0000928
929 /*
930 ** Record the set of tables that satisfy case 2. The set might be
drh111a6a72008-12-21 03:51:16 +0000931 ** empty.
drh1a58fe02008-12-20 02:06:13 +0000932 */
933 pOrInfo->indexable = indexable;
drh111a6a72008-12-21 03:51:16 +0000934 pTerm->eOperator = indexable==0 ? 0 : WO_OR;
drh1a58fe02008-12-20 02:06:13 +0000935
936 /*
937 ** chngToIN holds a set of tables that *might* satisfy case 1. But
938 ** we have to do some additional checking to see if case 1 really
939 ** is satisfied.
drh4e8be3b2009-06-08 17:11:08 +0000940 **
941 ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means
942 ** that there is no possibility of transforming the OR clause into an
943 ** IN operator because one or more terms in the OR clause contain
944 ** something other than == on a column in the single table. The 1-bit
945 ** case means that every term of the OR clause is of the form
946 ** "table.column=expr" for some single table. The one bit that is set
947 ** will correspond to the common table. We still need to check to make
948 ** sure the same column is used on all terms. The 2-bit case is when
949 ** the all terms are of the form "table1.column=table2.column". It
950 ** might be possible to form an IN operator with either table1.column
951 ** or table2.column as the LHS if either is common to every term of
952 ** the OR clause.
953 **
954 ** Note that terms of the form "table.column1=table.column2" (the
955 ** same table on both sizes of the ==) cannot be optimized.
drh1a58fe02008-12-20 02:06:13 +0000956 */
957 if( chngToIN ){
958 int okToChngToIN = 0; /* True if the conversion to IN is valid */
959 int iColumn = -1; /* Column index on lhs of IN operator */
shane63207ab2009-02-04 01:49:30 +0000960 int iCursor = -1; /* Table cursor common to all terms */
drh1a58fe02008-12-20 02:06:13 +0000961 int j = 0; /* Loop counter */
962
963 /* Search for a table and column that appears on one side or the
964 ** other of the == operator in every subterm. That table and column
965 ** will be recorded in iCursor and iColumn. There might not be any
966 ** such table and column. Set okToChngToIN if an appropriate table
967 ** and column is found but leave okToChngToIN false if not found.
968 */
969 for(j=0; j<2 && !okToChngToIN; j++){
970 pOrTerm = pOrWc->a;
971 for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
drh7a5bcc02013-01-16 17:08:58 +0000972 assert( pOrTerm->eOperator & WO_EQ );
drh1a58fe02008-12-20 02:06:13 +0000973 pOrTerm->wtFlags &= ~TERM_OR_OK;
drh4e8be3b2009-06-08 17:11:08 +0000974 if( pOrTerm->leftCursor==iCursor ){
975 /* This is the 2-bit case and we are on the second iteration and
976 ** current term is from the first iteration. So skip this term. */
977 assert( j==1 );
978 continue;
979 }
drh70d18342013-06-06 19:16:33 +0000980 if( (chngToIN & getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor))==0 ){
drh4e8be3b2009-06-08 17:11:08 +0000981 /* This term must be of the form t1.a==t2.b where t2 is in the
982 ** chngToIN set but t1 is not. This term will be either preceeded
983 ** or follwed by an inverted copy (t2.b==t1.a). Skip this term
984 ** and use its inversion. */
985 testcase( pOrTerm->wtFlags & TERM_COPIED );
986 testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
987 assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
988 continue;
989 }
drh1a58fe02008-12-20 02:06:13 +0000990 iColumn = pOrTerm->u.leftColumn;
991 iCursor = pOrTerm->leftCursor;
992 break;
993 }
994 if( i<0 ){
drh4e8be3b2009-06-08 17:11:08 +0000995 /* No candidate table+column was found. This can only occur
996 ** on the second iteration */
drh1a58fe02008-12-20 02:06:13 +0000997 assert( j==1 );
drh7a5bcc02013-01-16 17:08:58 +0000998 assert( IsPowerOfTwo(chngToIN) );
drh70d18342013-06-06 19:16:33 +0000999 assert( chngToIN==getMask(&pWInfo->sMaskSet, iCursor) );
drh1a58fe02008-12-20 02:06:13 +00001000 break;
1001 }
drh4e8be3b2009-06-08 17:11:08 +00001002 testcase( j==1 );
1003
1004 /* We have found a candidate table and column. Check to see if that
1005 ** table and column is common to every term in the OR clause */
drh1a58fe02008-12-20 02:06:13 +00001006 okToChngToIN = 1;
1007 for(; i>=0 && okToChngToIN; i--, pOrTerm++){
drh7a5bcc02013-01-16 17:08:58 +00001008 assert( pOrTerm->eOperator & WO_EQ );
drh1a58fe02008-12-20 02:06:13 +00001009 if( pOrTerm->leftCursor!=iCursor ){
1010 pOrTerm->wtFlags &= ~TERM_OR_OK;
1011 }else if( pOrTerm->u.leftColumn!=iColumn ){
1012 okToChngToIN = 0;
1013 }else{
1014 int affLeft, affRight;
1015 /* If the right-hand side is also a column, then the affinities
1016 ** of both right and left sides must be such that no type
1017 ** conversions are required on the right. (Ticket #2249)
1018 */
1019 affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
1020 affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
1021 if( affRight!=0 && affRight!=affLeft ){
1022 okToChngToIN = 0;
1023 }else{
1024 pOrTerm->wtFlags |= TERM_OR_OK;
1025 }
1026 }
1027 }
1028 }
1029
1030 /* At this point, okToChngToIN is true if original pTerm satisfies
1031 ** case 1. In that case, construct a new virtual term that is
1032 ** pTerm converted into an IN operator.
1033 */
1034 if( okToChngToIN ){
1035 Expr *pDup; /* A transient duplicate expression */
1036 ExprList *pList = 0; /* The RHS of the IN operator */
1037 Expr *pLeft = 0; /* The LHS of the IN operator */
1038 Expr *pNew; /* The complete IN operator */
1039
1040 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
1041 if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
drh7a5bcc02013-01-16 17:08:58 +00001042 assert( pOrTerm->eOperator & WO_EQ );
drh1a58fe02008-12-20 02:06:13 +00001043 assert( pOrTerm->leftCursor==iCursor );
1044 assert( pOrTerm->u.leftColumn==iColumn );
danielk19776ab3a2e2009-02-19 14:39:25 +00001045 pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
drh70d18342013-06-06 19:16:33 +00001046 pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
drh1a58fe02008-12-20 02:06:13 +00001047 pLeft = pOrTerm->pExpr->pLeft;
1048 }
1049 assert( pLeft!=0 );
danielk19776ab3a2e2009-02-19 14:39:25 +00001050 pDup = sqlite3ExprDup(db, pLeft, 0);
drhb7916a72009-05-27 10:31:29 +00001051 pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
drh1a58fe02008-12-20 02:06:13 +00001052 if( pNew ){
1053 int idxNew;
1054 transferJoinMarkings(pNew, pExpr);
danielk19776ab3a2e2009-02-19 14:39:25 +00001055 assert( !ExprHasProperty(pNew, EP_xIsSelect) );
1056 pNew->x.pList = pList;
drh1a58fe02008-12-20 02:06:13 +00001057 idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
1058 testcase( idxNew==0 );
1059 exprAnalyze(pSrc, pWC, idxNew);
1060 pTerm = &pWC->a[idxTerm];
1061 pWC->a[idxNew].iParent = idxTerm;
1062 pTerm->nChild = 1;
1063 }else{
1064 sqlite3ExprListDelete(db, pList);
1065 }
drh534230c2011-01-22 00:10:45 +00001066 pTerm->eOperator = WO_NOOP; /* case 1 trumps case 2 */
drh1a58fe02008-12-20 02:06:13 +00001067 }
drh3e355802007-02-23 23:13:33 +00001068 }
drh3e355802007-02-23 23:13:33 +00001069}
1070#endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
drh54a167d2005-11-26 14:08:07 +00001071
drh7a5bcc02013-01-16 17:08:58 +00001072/*
drh0aa74ed2005-07-16 13:33:20 +00001073** The input to this routine is an WhereTerm structure with only the
drh51147ba2005-07-23 22:59:55 +00001074** "pExpr" field filled in. The job of this routine is to analyze the
drh0aa74ed2005-07-16 13:33:20 +00001075** subexpression and populate all the other fields of the WhereTerm
drh75897232000-05-29 14:26:00 +00001076** structure.
drh51147ba2005-07-23 22:59:55 +00001077**
1078** If the expression is of the form "<expr> <op> X" it gets commuted
drh1a58fe02008-12-20 02:06:13 +00001079** to the standard form of "X <op> <expr>".
1080**
1081** If the expression is of the form "X <op> Y" where both X and Y are
1082** columns, then the original expression is unchanged and a new virtual
1083** term of the form "Y <op> X" is added to the WHERE clause and
1084** analyzed separately. The original term is marked with TERM_COPIED
1085** and the new term is marked with TERM_DYNAMIC (because it's pExpr
1086** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
1087** is a commuted copy of a prior term.) The original term has nChild=1
1088** and the copy has idxParent set to the index of the original term.
drh75897232000-05-29 14:26:00 +00001089*/
drh0fcef5e2005-07-19 17:38:22 +00001090static void exprAnalyze(
1091 SrcList *pSrc, /* the FROM clause */
drh9eb20282005-08-24 03:52:18 +00001092 WhereClause *pWC, /* the WHERE clause */
1093 int idxTerm /* Index of the term to be analyzed */
drh0fcef5e2005-07-19 17:38:22 +00001094){
drh70d18342013-06-06 19:16:33 +00001095 WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
drh1a58fe02008-12-20 02:06:13 +00001096 WhereTerm *pTerm; /* The term to be analyzed */
drh111a6a72008-12-21 03:51:16 +00001097 WhereMaskSet *pMaskSet; /* Set of table index masks */
drh1a58fe02008-12-20 02:06:13 +00001098 Expr *pExpr; /* The expression to be analyzed */
1099 Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */
1100 Bitmask prereqAll; /* Prerequesites of pExpr */
drh5e767c52010-02-25 04:15:47 +00001101 Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */
drh1d452e12009-11-01 19:26:59 +00001102 Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */
1103 int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */
1104 int noCase = 0; /* LIKE/GLOB distinguishes case */
drh1a58fe02008-12-20 02:06:13 +00001105 int op; /* Top-level operator. pExpr->op */
drh70d18342013-06-06 19:16:33 +00001106 Parse *pParse = pWInfo->pParse; /* Parsing context */
drh1a58fe02008-12-20 02:06:13 +00001107 sqlite3 *db = pParse->db; /* Database connection */
drh0fcef5e2005-07-19 17:38:22 +00001108
drhf998b732007-11-26 13:36:00 +00001109 if( db->mallocFailed ){
1110 return;
1111 }
1112 pTerm = &pWC->a[idxTerm];
drh70d18342013-06-06 19:16:33 +00001113 pMaskSet = &pWInfo->sMaskSet;
drh7ee751d2012-12-19 15:53:51 +00001114 pExpr = pTerm->pExpr;
1115 assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
drh0fcef5e2005-07-19 17:38:22 +00001116 prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
drh50b39962006-10-28 00:28:09 +00001117 op = pExpr->op;
1118 if( op==TK_IN ){
drhf5b11382005-09-17 13:07:13 +00001119 assert( pExpr->pRight==0 );
danielk19776ab3a2e2009-02-19 14:39:25 +00001120 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
1121 pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
1122 }else{
1123 pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
1124 }
drh50b39962006-10-28 00:28:09 +00001125 }else if( op==TK_ISNULL ){
1126 pTerm->prereqRight = 0;
drhf5b11382005-09-17 13:07:13 +00001127 }else{
1128 pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
1129 }
drh22d6a532005-09-19 21:05:48 +00001130 prereqAll = exprTableUsage(pMaskSet, pExpr);
1131 if( ExprHasProperty(pExpr, EP_FromJoin) ){
drh42165be2008-03-26 14:56:34 +00001132 Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
1133 prereqAll |= x;
drhdafc0ce2008-04-17 19:14:02 +00001134 extraRight = x-1; /* ON clause terms may not be used with an index
1135 ** on left table of a LEFT JOIN. Ticket #3015 */
drh22d6a532005-09-19 21:05:48 +00001136 }
1137 pTerm->prereqAll = prereqAll;
drh0fcef5e2005-07-19 17:38:22 +00001138 pTerm->leftCursor = -1;
drh45b1ee42005-08-02 17:48:22 +00001139 pTerm->iParent = -1;
drhb52076c2006-01-23 13:22:09 +00001140 pTerm->eOperator = 0;
drh738fc792013-01-17 15:05:17 +00001141 if( allowedOp(op) ){
drh7a66da12012-12-07 20:31:11 +00001142 Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
1143 Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
drh738fc792013-01-17 15:05:17 +00001144 u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
drh0fcef5e2005-07-19 17:38:22 +00001145 if( pLeft->op==TK_COLUMN ){
1146 pTerm->leftCursor = pLeft->iTable;
drh700a2262008-12-17 19:22:15 +00001147 pTerm->u.leftColumn = pLeft->iColumn;
drh738fc792013-01-17 15:05:17 +00001148 pTerm->eOperator = operatorMask(op) & opMask;
drh75897232000-05-29 14:26:00 +00001149 }
drh0fcef5e2005-07-19 17:38:22 +00001150 if( pRight && pRight->op==TK_COLUMN ){
1151 WhereTerm *pNew;
1152 Expr *pDup;
drh7a5bcc02013-01-16 17:08:58 +00001153 u16 eExtraOp = 0; /* Extra bits for pNew->eOperator */
drh0fcef5e2005-07-19 17:38:22 +00001154 if( pTerm->leftCursor>=0 ){
drh9eb20282005-08-24 03:52:18 +00001155 int idxNew;
danielk19776ab3a2e2009-02-19 14:39:25 +00001156 pDup = sqlite3ExprDup(db, pExpr, 0);
drh17435752007-08-16 04:30:38 +00001157 if( db->mallocFailed ){
drh633e6d52008-07-28 19:34:53 +00001158 sqlite3ExprDelete(db, pDup);
drh28f45912006-10-18 23:26:38 +00001159 return;
1160 }
drh9eb20282005-08-24 03:52:18 +00001161 idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
1162 if( idxNew==0 ) return;
1163 pNew = &pWC->a[idxNew];
1164 pNew->iParent = idxTerm;
1165 pTerm = &pWC->a[idxTerm];
drh45b1ee42005-08-02 17:48:22 +00001166 pTerm->nChild = 1;
drh165be382008-12-05 02:36:33 +00001167 pTerm->wtFlags |= TERM_COPIED;
drheb5bc922013-01-17 16:43:33 +00001168 if( pExpr->op==TK_EQ
1169 && !ExprHasProperty(pExpr, EP_FromJoin)
1170 && OptimizationEnabled(db, SQLITE_Transitive)
1171 ){
drh7a5bcc02013-01-16 17:08:58 +00001172 pTerm->eOperator |= WO_EQUIV;
1173 eExtraOp = WO_EQUIV;
1174 }
drh0fcef5e2005-07-19 17:38:22 +00001175 }else{
1176 pDup = pExpr;
1177 pNew = pTerm;
1178 }
drh7d10d5a2008-08-20 16:35:10 +00001179 exprCommute(pParse, pDup);
drhfb76f5a2012-12-08 14:16:47 +00001180 pLeft = sqlite3ExprSkipCollate(pDup->pLeft);
drh0fcef5e2005-07-19 17:38:22 +00001181 pNew->leftCursor = pLeft->iTable;
drh700a2262008-12-17 19:22:15 +00001182 pNew->u.leftColumn = pLeft->iColumn;
drh5e767c52010-02-25 04:15:47 +00001183 testcase( (prereqLeft | extraRight) != prereqLeft );
1184 pNew->prereqRight = prereqLeft | extraRight;
drh0fcef5e2005-07-19 17:38:22 +00001185 pNew->prereqAll = prereqAll;
drh738fc792013-01-17 15:05:17 +00001186 pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
drh75897232000-05-29 14:26:00 +00001187 }
1188 }
drhed378002005-07-28 23:12:08 +00001189
drhd2687b72005-08-12 22:56:09 +00001190#ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
drhed378002005-07-28 23:12:08 +00001191 /* If a term is the BETWEEN operator, create two new virtual terms
drh1a58fe02008-12-20 02:06:13 +00001192 ** that define the range that the BETWEEN implements. For example:
1193 **
1194 ** a BETWEEN b AND c
1195 **
1196 ** is converted into:
1197 **
1198 ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
1199 **
1200 ** The two new terms are added onto the end of the WhereClause object.
1201 ** The new terms are "dynamic" and are children of the original BETWEEN
1202 ** term. That means that if the BETWEEN term is coded, the children are
1203 ** skipped. Or, if the children are satisfied by an index, the original
1204 ** BETWEEN term is skipped.
drhed378002005-07-28 23:12:08 +00001205 */
drh29435252008-12-28 18:35:08 +00001206 else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
danielk19776ab3a2e2009-02-19 14:39:25 +00001207 ExprList *pList = pExpr->x.pList;
drhed378002005-07-28 23:12:08 +00001208 int i;
1209 static const u8 ops[] = {TK_GE, TK_LE};
1210 assert( pList!=0 );
1211 assert( pList->nExpr==2 );
1212 for(i=0; i<2; i++){
1213 Expr *pNewExpr;
drh9eb20282005-08-24 03:52:18 +00001214 int idxNew;
drhb7916a72009-05-27 10:31:29 +00001215 pNewExpr = sqlite3PExpr(pParse, ops[i],
1216 sqlite3ExprDup(db, pExpr->pLeft, 0),
danielk19776ab3a2e2009-02-19 14:39:25 +00001217 sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
drhd41d39f2013-08-28 16:27:01 +00001218 transferJoinMarkings(pNewExpr, pExpr);
drh9eb20282005-08-24 03:52:18 +00001219 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
drh6a1e0712008-12-05 15:24:15 +00001220 testcase( idxNew==0 );
drh7b4fc6a2007-02-06 13:26:32 +00001221 exprAnalyze(pSrc, pWC, idxNew);
drh9eb20282005-08-24 03:52:18 +00001222 pTerm = &pWC->a[idxTerm];
1223 pWC->a[idxNew].iParent = idxTerm;
drhed378002005-07-28 23:12:08 +00001224 }
drh45b1ee42005-08-02 17:48:22 +00001225 pTerm->nChild = 2;
drhed378002005-07-28 23:12:08 +00001226 }
drhd2687b72005-08-12 22:56:09 +00001227#endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
drhed378002005-07-28 23:12:08 +00001228
danielk19771576cd92006-01-14 08:02:28 +00001229#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
drh1a58fe02008-12-20 02:06:13 +00001230 /* Analyze a term that is composed of two or more subterms connected by
1231 ** an OR operator.
drh6c30be82005-07-29 15:10:17 +00001232 */
1233 else if( pExpr->op==TK_OR ){
drh29435252008-12-28 18:35:08 +00001234 assert( pWC->op==TK_AND );
drh1a58fe02008-12-20 02:06:13 +00001235 exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
danielk1977f51d1bd2009-07-31 06:14:51 +00001236 pTerm = &pWC->a[idxTerm];
drh6c30be82005-07-29 15:10:17 +00001237 }
drhd2687b72005-08-12 22:56:09 +00001238#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
1239
1240#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
1241 /* Add constraints to reduce the search space on a LIKE or GLOB
1242 ** operator.
drh9f504ea2008-02-23 21:55:39 +00001243 **
1244 ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
1245 **
1246 ** x>='abc' AND x<'abd' AND x LIKE 'abc%'
1247 **
1248 ** The last character of the prefix "abc" is incremented to form the
shane7bc71e52008-05-28 18:01:44 +00001249 ** termination condition "abd".
drhd2687b72005-08-12 22:56:09 +00001250 */
dan937d0de2009-10-15 18:35:38 +00001251 if( pWC->op==TK_AND
1252 && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
1253 ){
drh1d452e12009-11-01 19:26:59 +00001254 Expr *pLeft; /* LHS of LIKE/GLOB operator */
1255 Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */
1256 Expr *pNewExpr1;
1257 Expr *pNewExpr2;
1258 int idxNew1;
1259 int idxNew2;
drhae80dde2012-12-06 21:16:43 +00001260 Token sCollSeqName; /* Name of collating sequence */
drh9eb20282005-08-24 03:52:18 +00001261
danielk19776ab3a2e2009-02-19 14:39:25 +00001262 pLeft = pExpr->x.pList->a[1].pExpr;
danielk19776ab3a2e2009-02-19 14:39:25 +00001263 pStr2 = sqlite3ExprDup(db, pStr1, 0);
drhf998b732007-11-26 13:36:00 +00001264 if( !db->mallocFailed ){
drh254993e2009-06-08 19:44:36 +00001265 u8 c, *pC; /* Last character before the first wildcard */
dan937d0de2009-10-15 18:35:38 +00001266 pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
drh9f504ea2008-02-23 21:55:39 +00001267 c = *pC;
drh02a50b72008-05-26 18:33:40 +00001268 if( noCase ){
drh254993e2009-06-08 19:44:36 +00001269 /* The point is to increment the last character before the first
1270 ** wildcard. But if we increment '@', that will push it into the
1271 ** alphabetic range where case conversions will mess up the
1272 ** inequality. To avoid this, make sure to also run the full
1273 ** LIKE on all candidate expressions by clearing the isComplete flag
1274 */
drh39759742013-08-02 23:40:45 +00001275 if( c=='A'-1 ) isComplete = 0;
drh02a50b72008-05-26 18:33:40 +00001276 c = sqlite3UpperToLower[c];
1277 }
drh9f504ea2008-02-23 21:55:39 +00001278 *pC = c + 1;
drhd2687b72005-08-12 22:56:09 +00001279 }
drhae80dde2012-12-06 21:16:43 +00001280 sCollSeqName.z = noCase ? "NOCASE" : "BINARY";
1281 sCollSeqName.n = 6;
1282 pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
drh8342e492010-07-22 17:49:52 +00001283 pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
drh0a8a4062012-12-07 18:38:16 +00001284 sqlite3ExprAddCollateToken(pParse,pNewExpr1,&sCollSeqName),
drhae80dde2012-12-06 21:16:43 +00001285 pStr1, 0);
drhd41d39f2013-08-28 16:27:01 +00001286 transferJoinMarkings(pNewExpr1, pExpr);
drh9eb20282005-08-24 03:52:18 +00001287 idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
drh6a1e0712008-12-05 15:24:15 +00001288 testcase( idxNew1==0 );
drh7b4fc6a2007-02-06 13:26:32 +00001289 exprAnalyze(pSrc, pWC, idxNew1);
drhae80dde2012-12-06 21:16:43 +00001290 pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
drh8342e492010-07-22 17:49:52 +00001291 pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
drh0a8a4062012-12-07 18:38:16 +00001292 sqlite3ExprAddCollateToken(pParse,pNewExpr2,&sCollSeqName),
drhae80dde2012-12-06 21:16:43 +00001293 pStr2, 0);
drhd41d39f2013-08-28 16:27:01 +00001294 transferJoinMarkings(pNewExpr2, pExpr);
drh9eb20282005-08-24 03:52:18 +00001295 idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
drh6a1e0712008-12-05 15:24:15 +00001296 testcase( idxNew2==0 );
drh7b4fc6a2007-02-06 13:26:32 +00001297 exprAnalyze(pSrc, pWC, idxNew2);
drh9eb20282005-08-24 03:52:18 +00001298 pTerm = &pWC->a[idxTerm];
drhd2687b72005-08-12 22:56:09 +00001299 if( isComplete ){
drh9eb20282005-08-24 03:52:18 +00001300 pWC->a[idxNew1].iParent = idxTerm;
1301 pWC->a[idxNew2].iParent = idxTerm;
drhd2687b72005-08-12 22:56:09 +00001302 pTerm->nChild = 2;
1303 }
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;
1335 pNewTerm->iParent = idxTerm;
drhd2ca60d2006-06-27 02:36:58 +00001336 pTerm = &pWC->a[idxTerm];
drh7f375902006-06-13 17:38:59 +00001337 pTerm->nChild = 1;
drh165be382008-12-05 02:36:33 +00001338 pTerm->wtFlags |= TERM_COPIED;
drh7f375902006-06-13 17:38:59 +00001339 pNewTerm->prereqAll = pTerm->prereqAll;
1340 }
1341 }
1342#endif /* SQLITE_OMIT_VIRTUALTABLE */
drhdafc0ce2008-04-17 19:14:02 +00001343
drh1435a9a2013-08-27 23:15:44 +00001344#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drhd3ed7342011-09-21 00:09:41 +00001345 /* When sqlite_stat3 histogram data is available an operator of the
drh534230c2011-01-22 00:10:45 +00001346 ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
1347 ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a
1348 ** virtual term of that form.
1349 **
1350 ** Note that the virtual term must be tagged with TERM_VNULL. This
1351 ** TERM_VNULL tag will suppress the not-null check at the beginning
1352 ** of the loop. Without the TERM_VNULL flag, the not-null check at
1353 ** the start of the loop will prevent any results from being returned.
1354 */
drhea6dc442011-04-08 21:35:26 +00001355 if( pExpr->op==TK_NOTNULL
1356 && pExpr->pLeft->op==TK_COLUMN
1357 && pExpr->pLeft->iColumn>=0
drh40aa9362013-06-28 17:29:25 +00001358 && OptimizationEnabled(db, SQLITE_Stat3)
drhea6dc442011-04-08 21:35:26 +00001359 ){
drh534230c2011-01-22 00:10:45 +00001360 Expr *pNewExpr;
1361 Expr *pLeft = pExpr->pLeft;
1362 int idxNew;
1363 WhereTerm *pNewTerm;
1364
1365 pNewExpr = sqlite3PExpr(pParse, TK_GT,
1366 sqlite3ExprDup(db, pLeft, 0),
1367 sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
1368
1369 idxNew = whereClauseInsert(pWC, pNewExpr,
1370 TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
drhda91e712011-02-11 06:59:02 +00001371 if( idxNew ){
1372 pNewTerm = &pWC->a[idxNew];
1373 pNewTerm->prereqRight = 0;
1374 pNewTerm->leftCursor = pLeft->iTable;
1375 pNewTerm->u.leftColumn = pLeft->iColumn;
1376 pNewTerm->eOperator = WO_GT;
1377 pNewTerm->iParent = idxTerm;
1378 pTerm = &pWC->a[idxTerm];
1379 pTerm->nChild = 1;
1380 pTerm->wtFlags |= TERM_COPIED;
1381 pNewTerm->prereqAll = pTerm->prereqAll;
1382 }
drh534230c2011-01-22 00:10:45 +00001383 }
drh1435a9a2013-08-27 23:15:44 +00001384#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
drh534230c2011-01-22 00:10:45 +00001385
drhdafc0ce2008-04-17 19:14:02 +00001386 /* Prevent ON clause terms of a LEFT JOIN from being used to drive
1387 ** an index for tables to the left of the join.
1388 */
1389 pTerm->prereqRight |= extraRight;
drh75897232000-05-29 14:26:00 +00001390}
1391
drh7b4fc6a2007-02-06 13:26:32 +00001392/*
drh3b48e8c2013-06-12 20:18:16 +00001393** This function searches pList for a entry that matches the iCol-th column
1394** of index pIdx.
dan6f343962011-07-01 18:26:40 +00001395**
1396** If such an expression is found, its index in pList->a[] is returned. If
1397** no expression is found, -1 is returned.
1398*/
1399static int findIndexCol(
1400 Parse *pParse, /* Parse context */
1401 ExprList *pList, /* Expression list to search */
1402 int iBase, /* Cursor for table associated with pIdx */
1403 Index *pIdx, /* Index to match column of */
1404 int iCol /* Column of index to match */
1405){
1406 int i;
1407 const char *zColl = pIdx->azColl[iCol];
1408
1409 for(i=0; i<pList->nExpr; i++){
drh580c8c12012-12-08 03:34:04 +00001410 Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
drhf1d3e322011-07-09 13:00:41 +00001411 if( p->op==TK_COLUMN
1412 && p->iColumn==pIdx->aiColumn[iCol]
1413 && p->iTable==iBase
1414 ){
drh580c8c12012-12-08 03:34:04 +00001415 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
drhf1d3e322011-07-09 13:00:41 +00001416 if( ALWAYS(pColl) && 0==sqlite3StrICmp(pColl->zName, zColl) ){
dan6f343962011-07-01 18:26:40 +00001417 return i;
1418 }
1419 }
1420 }
1421
1422 return -1;
1423}
1424
1425/*
dan6f343962011-07-01 18:26:40 +00001426** Return true if the DISTINCT expression-list passed as the third argument
drh4f402f22013-06-11 18:59:38 +00001427** is redundant.
1428**
drh3b48e8c2013-06-12 20:18:16 +00001429** A DISTINCT list is redundant if the database contains some subset of
drh4f402f22013-06-11 18:59:38 +00001430** columns that are unique and non-null.
dan6f343962011-07-01 18:26:40 +00001431*/
1432static int isDistinctRedundant(
drh4f402f22013-06-11 18:59:38 +00001433 Parse *pParse, /* Parsing context */
1434 SrcList *pTabList, /* The FROM clause */
1435 WhereClause *pWC, /* The WHERE clause */
1436 ExprList *pDistinct /* The result set that needs to be DISTINCT */
dan6f343962011-07-01 18:26:40 +00001437){
1438 Table *pTab;
1439 Index *pIdx;
1440 int i;
1441 int iBase;
1442
1443 /* If there is more than one table or sub-select in the FROM clause of
1444 ** this query, then it will not be possible to show that the DISTINCT
1445 ** clause is redundant. */
1446 if( pTabList->nSrc!=1 ) return 0;
1447 iBase = pTabList->a[0].iCursor;
1448 pTab = pTabList->a[0].pTab;
1449
dan94e08d92011-07-02 06:44:05 +00001450 /* If any of the expressions is an IPK column on table iBase, then return
1451 ** true. Note: The (p->iTable==iBase) part of this test may be false if the
1452 ** current SELECT is a correlated sub-query.
1453 */
dan6f343962011-07-01 18:26:40 +00001454 for(i=0; i<pDistinct->nExpr; i++){
drh580c8c12012-12-08 03:34:04 +00001455 Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
dan94e08d92011-07-02 06:44:05 +00001456 if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
dan6f343962011-07-01 18:26:40 +00001457 }
1458
1459 /* Loop through all indices on the table, checking each to see if it makes
1460 ** the DISTINCT qualifier redundant. It does so if:
1461 **
1462 ** 1. The index is itself UNIQUE, and
1463 **
1464 ** 2. All of the columns in the index are either part of the pDistinct
1465 ** list, or else the WHERE clause contains a term of the form "col=X",
1466 ** where X is a constant value. The collation sequences of the
1467 ** comparison and select-list expressions must match those of the index.
dan6a36f432012-04-20 16:59:24 +00001468 **
1469 ** 3. All of those index columns for which the WHERE clause does not
1470 ** contain a "col=X" term are subject to a NOT NULL constraint.
dan6f343962011-07-01 18:26:40 +00001471 */
1472 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1473 if( pIdx->onError==OE_None ) continue;
drhbbbdc832013-10-22 18:01:40 +00001474 for(i=0; i<pIdx->nKeyCol; i++){
1475 i16 iCol = pIdx->aiColumn[i];
dan6a36f432012-04-20 16:59:24 +00001476 if( 0==findTerm(pWC, iBase, iCol, ~(Bitmask)0, WO_EQ, pIdx) ){
1477 int iIdxCol = findIndexCol(pParse, pDistinct, iBase, pIdx, i);
drhbbbdc832013-10-22 18:01:40 +00001478 if( iIdxCol<0 || pTab->aCol[iCol].notNull==0 ){
dan6a36f432012-04-20 16:59:24 +00001479 break;
1480 }
dan6f343962011-07-01 18:26:40 +00001481 }
1482 }
drhbbbdc832013-10-22 18:01:40 +00001483 if( i==pIdx->nKeyCol ){
dan6f343962011-07-01 18:26:40 +00001484 /* This index implies that the DISTINCT qualifier is redundant. */
1485 return 1;
1486 }
1487 }
1488
1489 return 0;
1490}
drh0fcef5e2005-07-19 17:38:22 +00001491
drh8636e9c2013-06-11 01:50:08 +00001492
drh75897232000-05-29 14:26:00 +00001493/*
drh3b48e8c2013-06-12 20:18:16 +00001494** Estimate the logarithm of the input value to base 2.
drh28c4cf42005-07-27 20:41:43 +00001495*/
drhbf539c42013-10-05 18:16:02 +00001496static LogEst estLog(LogEst N){
1497 LogEst x = sqlite3LogEst(N);
drh4fe425a2013-06-12 17:08:06 +00001498 return x>33 ? x - 33 : 0;
drh28c4cf42005-07-27 20:41:43 +00001499}
1500
drh6d209d82006-06-27 01:54:26 +00001501/*
1502** Two routines for printing the content of an sqlite3_index_info
1503** structure. Used for testing and debugging only. If neither
1504** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
1505** are no-ops.
1506*/
drhd15cb172013-05-21 19:23:10 +00001507#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
drh6d209d82006-06-27 01:54:26 +00001508static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
1509 int i;
mlcreech3a00f902008-03-04 17:45:01 +00001510 if( !sqlite3WhereTrace ) return;
drh6d209d82006-06-27 01:54:26 +00001511 for(i=0; i<p->nConstraint; i++){
1512 sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
1513 i,
1514 p->aConstraint[i].iColumn,
1515 p->aConstraint[i].iTermOffset,
1516 p->aConstraint[i].op,
1517 p->aConstraint[i].usable);
1518 }
1519 for(i=0; i<p->nOrderBy; i++){
1520 sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n",
1521 i,
1522 p->aOrderBy[i].iColumn,
1523 p->aOrderBy[i].desc);
1524 }
1525}
1526static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
1527 int i;
mlcreech3a00f902008-03-04 17:45:01 +00001528 if( !sqlite3WhereTrace ) return;
drh6d209d82006-06-27 01:54:26 +00001529 for(i=0; i<p->nConstraint; i++){
1530 sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n",
1531 i,
1532 p->aConstraintUsage[i].argvIndex,
1533 p->aConstraintUsage[i].omit);
1534 }
1535 sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum);
1536 sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr);
1537 sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed);
1538 sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost);
dana9f58152013-11-11 19:01:33 +00001539 sqlite3DebugPrintf(" estimatedRows=%lld\n", p->estimatedRows);
drh6d209d82006-06-27 01:54:26 +00001540}
1541#else
1542#define TRACE_IDX_INPUTS(A)
1543#define TRACE_IDX_OUTPUTS(A)
1544#endif
1545
drhc6339082010-04-07 16:54:58 +00001546#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
drh8b307fb2010-04-06 15:57:05 +00001547/*
drh4139c992010-04-07 14:59:45 +00001548** Return TRUE if the WHERE clause term pTerm is of a form where it
1549** could be used with an index to access pSrc, assuming an appropriate
1550** index existed.
1551*/
1552static int termCanDriveIndex(
1553 WhereTerm *pTerm, /* WHERE clause term to check */
1554 struct SrcList_item *pSrc, /* Table we are trying to access */
1555 Bitmask notReady /* Tables in outer loops of the join */
1556){
1557 char aff;
1558 if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
drh7a5bcc02013-01-16 17:08:58 +00001559 if( (pTerm->eOperator & WO_EQ)==0 ) return 0;
drh4139c992010-04-07 14:59:45 +00001560 if( (pTerm->prereqRight & notReady)!=0 ) return 0;
drh23f98da2013-05-21 15:52:07 +00001561 if( pTerm->u.leftColumn<0 ) return 0;
drh4139c992010-04-07 14:59:45 +00001562 aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
1563 if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
1564 return 1;
1565}
drhc6339082010-04-07 16:54:58 +00001566#endif
drh4139c992010-04-07 14:59:45 +00001567
drhc6339082010-04-07 16:54:58 +00001568
1569#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
drh8b307fb2010-04-06 15:57:05 +00001570/*
drhc6339082010-04-07 16:54:58 +00001571** Generate code to construct the Index object for an automatic index
1572** and to set up the WhereLevel object pLevel so that the code generator
1573** makes use of the automatic index.
drh8b307fb2010-04-06 15:57:05 +00001574*/
drhc6339082010-04-07 16:54:58 +00001575static void constructAutomaticIndex(
drh8b307fb2010-04-06 15:57:05 +00001576 Parse *pParse, /* The parsing context */
1577 WhereClause *pWC, /* The WHERE clause */
1578 struct SrcList_item *pSrc, /* The FROM clause term to get the next index */
1579 Bitmask notReady, /* Mask of cursors that are not available */
1580 WhereLevel *pLevel /* Write new index here */
1581){
drhbbbdc832013-10-22 18:01:40 +00001582 int nKeyCol; /* Number of columns in the constructed index */
drh8b307fb2010-04-06 15:57:05 +00001583 WhereTerm *pTerm; /* A single term of the WHERE clause */
1584 WhereTerm *pWCEnd; /* End of pWC->a[] */
drh8b307fb2010-04-06 15:57:05 +00001585 Index *pIdx; /* Object describing the transient index */
1586 Vdbe *v; /* Prepared statement under construction */
drh8b307fb2010-04-06 15:57:05 +00001587 int addrInit; /* Address of the initialization bypass jump */
1588 Table *pTable; /* The table being indexed */
drh8b307fb2010-04-06 15:57:05 +00001589 int addrTop; /* Top of the index fill loop */
1590 int regRecord; /* Register holding an index record */
1591 int n; /* Column counter */
drh4139c992010-04-07 14:59:45 +00001592 int i; /* Loop counter */
1593 int mxBitCol; /* Maximum column in pSrc->colUsed */
drh424aab82010-04-06 18:28:20 +00001594 CollSeq *pColl; /* Collating sequence to on a column */
drh7ba39a92013-05-30 17:43:19 +00001595 WhereLoop *pLoop; /* The Loop object */
drh77e57df2013-10-22 14:28:02 +00001596 char *zNotUsed; /* Extra space on the end of pIdx */
drh4139c992010-04-07 14:59:45 +00001597 Bitmask idxCols; /* Bitmap of columns used for indexing */
1598 Bitmask extraCols; /* Bitmap of additional columns */
drh8d56e202013-06-28 23:55:45 +00001599 u8 sentWarning = 0; /* True if a warnning has been issued */
drh8b307fb2010-04-06 15:57:05 +00001600
1601 /* Generate code to skip over the creation and initialization of the
1602 ** transient index on 2nd and subsequent iterations of the loop. */
1603 v = pParse->pVdbe;
1604 assert( v!=0 );
drh7d176102014-02-18 03:07:12 +00001605 addrInit = sqlite3CodeOnce(pParse); VdbeCoverage(v);
drh8b307fb2010-04-06 15:57:05 +00001606
drh4139c992010-04-07 14:59:45 +00001607 /* Count the number of columns that will be added to the index
1608 ** and used to match WHERE clause constraints */
drhbbbdc832013-10-22 18:01:40 +00001609 nKeyCol = 0;
drh424aab82010-04-06 18:28:20 +00001610 pTable = pSrc->pTab;
drh8b307fb2010-04-06 15:57:05 +00001611 pWCEnd = &pWC->a[pWC->nTerm];
drh7ba39a92013-05-30 17:43:19 +00001612 pLoop = pLevel->pWLoop;
drh4139c992010-04-07 14:59:45 +00001613 idxCols = 0;
drh81186b42013-06-18 01:52:41 +00001614 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
drh4139c992010-04-07 14:59:45 +00001615 if( termCanDriveIndex(pTerm, pSrc, notReady) ){
1616 int iCol = pTerm->u.leftColumn;
drh7699d1c2013-06-04 12:42:29 +00001617 Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
drh52ff8ea2010-04-08 14:15:56 +00001618 testcase( iCol==BMS );
1619 testcase( iCol==BMS-1 );
drh8d56e202013-06-28 23:55:45 +00001620 if( !sentWarning ){
1621 sqlite3_log(SQLITE_WARNING_AUTOINDEX,
1622 "automatic index on %s(%s)", pTable->zName,
1623 pTable->aCol[iCol].zName);
1624 sentWarning = 1;
1625 }
drh0013e722010-04-08 00:40:15 +00001626 if( (idxCols & cMask)==0 ){
drhbbbdc832013-10-22 18:01:40 +00001627 if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ) return;
1628 pLoop->aLTerm[nKeyCol++] = pTerm;
drh0013e722010-04-08 00:40:15 +00001629 idxCols |= cMask;
1630 }
drh8b307fb2010-04-06 15:57:05 +00001631 }
1632 }
drhbbbdc832013-10-22 18:01:40 +00001633 assert( nKeyCol>0 );
1634 pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol;
drh53b52f72013-05-31 11:57:39 +00001635 pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
drh986b3872013-06-28 21:12:20 +00001636 | WHERE_AUTO_INDEX;
drh4139c992010-04-07 14:59:45 +00001637
1638 /* Count the number of additional columns needed to create a
1639 ** covering index. A "covering index" is an index that contains all
1640 ** columns that are needed by the query. With a covering index, the
1641 ** original table never needs to be accessed. Automatic indices must
1642 ** be a covering index because the index will not be updated if the
1643 ** original table changes and the index and table cannot both be used
1644 ** if they go out of sync.
1645 */
drh7699d1c2013-06-04 12:42:29 +00001646 extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
drh4139c992010-04-07 14:59:45 +00001647 mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol;
drh52ff8ea2010-04-08 14:15:56 +00001648 testcase( pTable->nCol==BMS-1 );
1649 testcase( pTable->nCol==BMS-2 );
drh4139c992010-04-07 14:59:45 +00001650 for(i=0; i<mxBitCol; i++){
drhbbbdc832013-10-22 18:01:40 +00001651 if( extraCols & MASKBIT(i) ) nKeyCol++;
drh4139c992010-04-07 14:59:45 +00001652 }
drh7699d1c2013-06-04 12:42:29 +00001653 if( pSrc->colUsed & MASKBIT(BMS-1) ){
drhbbbdc832013-10-22 18:01:40 +00001654 nKeyCol += pTable->nCol - BMS + 1;
drh4139c992010-04-07 14:59:45 +00001655 }
drh7ba39a92013-05-30 17:43:19 +00001656 pLoop->wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY;
drh8b307fb2010-04-06 15:57:05 +00001657
1658 /* Construct the Index object to describe this index */
drhbbbdc832013-10-22 18:01:40 +00001659 pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed);
drh8b307fb2010-04-06 15:57:05 +00001660 if( pIdx==0 ) return;
drh7ba39a92013-05-30 17:43:19 +00001661 pLoop->u.btree.pIndex = pIdx;
drh8b307fb2010-04-06 15:57:05 +00001662 pIdx->zName = "auto-index";
drh424aab82010-04-06 18:28:20 +00001663 pIdx->pTable = pTable;
drh8b307fb2010-04-06 15:57:05 +00001664 n = 0;
drh0013e722010-04-08 00:40:15 +00001665 idxCols = 0;
drh8b307fb2010-04-06 15:57:05 +00001666 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
drh4139c992010-04-07 14:59:45 +00001667 if( termCanDriveIndex(pTerm, pSrc, notReady) ){
drh0013e722010-04-08 00:40:15 +00001668 int iCol = pTerm->u.leftColumn;
drh7699d1c2013-06-04 12:42:29 +00001669 Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
drh7963b0e2013-06-17 21:37:40 +00001670 testcase( iCol==BMS-1 );
1671 testcase( iCol==BMS );
drh0013e722010-04-08 00:40:15 +00001672 if( (idxCols & cMask)==0 ){
1673 Expr *pX = pTerm->pExpr;
1674 idxCols |= cMask;
1675 pIdx->aiColumn[n] = pTerm->u.leftColumn;
1676 pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
drh6f2e6c02011-02-17 13:33:15 +00001677 pIdx->azColl[n] = ALWAYS(pColl) ? pColl->zName : "BINARY";
drh0013e722010-04-08 00:40:15 +00001678 n++;
1679 }
drh8b307fb2010-04-06 15:57:05 +00001680 }
1681 }
drh7ba39a92013-05-30 17:43:19 +00001682 assert( (u32)n==pLoop->u.btree.nEq );
drh4139c992010-04-07 14:59:45 +00001683
drhc6339082010-04-07 16:54:58 +00001684 /* Add additional columns needed to make the automatic index into
1685 ** a covering index */
drh4139c992010-04-07 14:59:45 +00001686 for(i=0; i<mxBitCol; i++){
drh7699d1c2013-06-04 12:42:29 +00001687 if( extraCols & MASKBIT(i) ){
drh4139c992010-04-07 14:59:45 +00001688 pIdx->aiColumn[n] = i;
1689 pIdx->azColl[n] = "BINARY";
1690 n++;
1691 }
1692 }
drh7699d1c2013-06-04 12:42:29 +00001693 if( pSrc->colUsed & MASKBIT(BMS-1) ){
drh4139c992010-04-07 14:59:45 +00001694 for(i=BMS-1; i<pTable->nCol; i++){
1695 pIdx->aiColumn[n] = i;
1696 pIdx->azColl[n] = "BINARY";
1697 n++;
1698 }
1699 }
drhbbbdc832013-10-22 18:01:40 +00001700 assert( n==nKeyCol );
drh44156282013-10-23 22:23:03 +00001701 pIdx->aiColumn[n] = -1;
1702 pIdx->azColl[n] = "BINARY";
drh8b307fb2010-04-06 15:57:05 +00001703
drhc6339082010-04-07 16:54:58 +00001704 /* Create the automatic index */
drh8b307fb2010-04-06 15:57:05 +00001705 assert( pLevel->iIdxCur>=0 );
drha1f41242013-05-31 20:00:58 +00001706 pLevel->iIdxCur = pParse->nTab++;
drh2ec2fb22013-11-06 19:59:23 +00001707 sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1);
1708 sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
drha21a64d2010-04-06 22:33:55 +00001709 VdbeComment((v, "for %s", pTable->zName));
drh8b307fb2010-04-06 15:57:05 +00001710
drhc6339082010-04-07 16:54:58 +00001711 /* Fill the automatic index with content */
drh688852a2014-02-17 22:40:43 +00001712 addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v);
drh8b307fb2010-04-06 15:57:05 +00001713 regRecord = sqlite3GetTempReg(pParse);
drh1c2c0b72014-01-04 19:27:05 +00001714 sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0);
drh8b307fb2010-04-06 15:57:05 +00001715 sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
1716 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
drh688852a2014-02-17 22:40:43 +00001717 sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v);
drha21a64d2010-04-06 22:33:55 +00001718 sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
drh8b307fb2010-04-06 15:57:05 +00001719 sqlite3VdbeJumpHere(v, addrTop);
1720 sqlite3ReleaseTempReg(pParse, regRecord);
1721
1722 /* Jump here when skipping the initialization */
1723 sqlite3VdbeJumpHere(v, addrInit);
1724}
drhc6339082010-04-07 16:54:58 +00001725#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
drh8b307fb2010-04-06 15:57:05 +00001726
drh9eff6162006-06-12 21:59:13 +00001727#ifndef SQLITE_OMIT_VIRTUALTABLE
1728/*
danielk19771d461462009-04-21 09:02:45 +00001729** Allocate and populate an sqlite3_index_info structure. It is the
1730** responsibility of the caller to eventually release the structure
1731** by passing the pointer returned by this function to sqlite3_free().
1732*/
drh5346e952013-05-08 14:14:26 +00001733static sqlite3_index_info *allocateIndexInfo(
1734 Parse *pParse,
1735 WhereClause *pWC,
1736 struct SrcList_item *pSrc,
1737 ExprList *pOrderBy
1738){
danielk19771d461462009-04-21 09:02:45 +00001739 int i, j;
1740 int nTerm;
1741 struct sqlite3_index_constraint *pIdxCons;
1742 struct sqlite3_index_orderby *pIdxOrderBy;
1743 struct sqlite3_index_constraint_usage *pUsage;
1744 WhereTerm *pTerm;
1745 int nOrderBy;
1746 sqlite3_index_info *pIdxInfo;
1747
danielk19771d461462009-04-21 09:02:45 +00001748 /* Count the number of possible WHERE clause constraints referring
1749 ** to this virtual table */
1750 for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
1751 if( pTerm->leftCursor != pSrc->iCursor ) continue;
drh7a5bcc02013-01-16 17:08:58 +00001752 assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
1753 testcase( pTerm->eOperator & WO_IN );
1754 testcase( pTerm->eOperator & WO_ISNULL );
dana4ff8252014-01-20 19:55:33 +00001755 testcase( pTerm->eOperator & WO_ALL );
1756 if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV))==0 ) continue;
drhb4256992011-08-02 01:57:39 +00001757 if( pTerm->wtFlags & TERM_VNULL ) continue;
danielk19771d461462009-04-21 09:02:45 +00001758 nTerm++;
1759 }
1760
1761 /* If the ORDER BY clause contains only columns in the current
1762 ** virtual table then allocate space for the aOrderBy part of
1763 ** the sqlite3_index_info structure.
1764 */
1765 nOrderBy = 0;
1766 if( pOrderBy ){
drh56f1b992012-09-25 14:29:39 +00001767 int n = pOrderBy->nExpr;
1768 for(i=0; i<n; i++){
danielk19771d461462009-04-21 09:02:45 +00001769 Expr *pExpr = pOrderBy->a[i].pExpr;
1770 if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
1771 }
drh56f1b992012-09-25 14:29:39 +00001772 if( i==n){
1773 nOrderBy = n;
danielk19771d461462009-04-21 09:02:45 +00001774 }
1775 }
1776
1777 /* Allocate the sqlite3_index_info structure
1778 */
1779 pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
1780 + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
1781 + sizeof(*pIdxOrderBy)*nOrderBy );
1782 if( pIdxInfo==0 ){
1783 sqlite3ErrorMsg(pParse, "out of memory");
danielk19771d461462009-04-21 09:02:45 +00001784 return 0;
1785 }
1786
1787 /* Initialize the structure. The sqlite3_index_info structure contains
1788 ** many fields that are declared "const" to prevent xBestIndex from
1789 ** changing them. We have to do some funky casting in order to
1790 ** initialize those fields.
1791 */
1792 pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
1793 pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
1794 pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
1795 *(int*)&pIdxInfo->nConstraint = nTerm;
1796 *(int*)&pIdxInfo->nOrderBy = nOrderBy;
1797 *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
1798 *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
1799 *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
1800 pUsage;
1801
1802 for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
drh281bbe22012-10-16 23:17:14 +00001803 u8 op;
danielk19771d461462009-04-21 09:02:45 +00001804 if( pTerm->leftCursor != pSrc->iCursor ) continue;
drh7a5bcc02013-01-16 17:08:58 +00001805 assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
1806 testcase( pTerm->eOperator & WO_IN );
1807 testcase( pTerm->eOperator & WO_ISNULL );
dana4ff8252014-01-20 19:55:33 +00001808 testcase( pTerm->eOperator & WO_ALL );
1809 if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV))==0 ) continue;
drhb4256992011-08-02 01:57:39 +00001810 if( pTerm->wtFlags & TERM_VNULL ) continue;
danielk19771d461462009-04-21 09:02:45 +00001811 pIdxCons[j].iColumn = pTerm->u.leftColumn;
1812 pIdxCons[j].iTermOffset = i;
drh7a5bcc02013-01-16 17:08:58 +00001813 op = (u8)pTerm->eOperator & WO_ALL;
drh281bbe22012-10-16 23:17:14 +00001814 if( op==WO_IN ) op = WO_EQ;
1815 pIdxCons[j].op = op;
danielk19771d461462009-04-21 09:02:45 +00001816 /* The direct assignment in the previous line is possible only because
1817 ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The
1818 ** following asserts verify this fact. */
1819 assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
1820 assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
1821 assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
1822 assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
1823 assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
1824 assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
drh281bbe22012-10-16 23:17:14 +00001825 assert( pTerm->eOperator & (WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
danielk19771d461462009-04-21 09:02:45 +00001826 j++;
1827 }
1828 for(i=0; i<nOrderBy; i++){
1829 Expr *pExpr = pOrderBy->a[i].pExpr;
1830 pIdxOrderBy[i].iColumn = pExpr->iColumn;
1831 pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
1832 }
1833
1834 return pIdxInfo;
1835}
1836
1837/*
1838** The table object reference passed as the second argument to this function
1839** must represent a virtual table. This function invokes the xBestIndex()
drh3b48e8c2013-06-12 20:18:16 +00001840** method of the virtual table with the sqlite3_index_info object that
1841** comes in as the 3rd argument to this function.
danielk19771d461462009-04-21 09:02:45 +00001842**
1843** If an error occurs, pParse is populated with an error message and a
1844** non-zero value is returned. Otherwise, 0 is returned and the output
1845** part of the sqlite3_index_info structure is left populated.
1846**
1847** Whether or not an error is returned, it is the responsibility of the
1848** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
1849** that this is required.
1850*/
1851static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
danielk1977595a5232009-07-24 17:58:53 +00001852 sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
danielk19771d461462009-04-21 09:02:45 +00001853 int i;
1854 int rc;
1855
danielk19771d461462009-04-21 09:02:45 +00001856 TRACE_IDX_INPUTS(p);
1857 rc = pVtab->pModule->xBestIndex(pVtab, p);
1858 TRACE_IDX_OUTPUTS(p);
danielk19771d461462009-04-21 09:02:45 +00001859
1860 if( rc!=SQLITE_OK ){
1861 if( rc==SQLITE_NOMEM ){
1862 pParse->db->mallocFailed = 1;
1863 }else if( !pVtab->zErrMsg ){
1864 sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
1865 }else{
1866 sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
1867 }
1868 }
drhb9755982010-07-24 16:34:37 +00001869 sqlite3_free(pVtab->zErrMsg);
danielk19771d461462009-04-21 09:02:45 +00001870 pVtab->zErrMsg = 0;
1871
1872 for(i=0; i<p->nConstraint; i++){
1873 if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
1874 sqlite3ErrorMsg(pParse,
1875 "table %s: xBestIndex returned an invalid plan", pTab->zName);
1876 }
1877 }
1878
1879 return pParse->nErr;
1880}
drh7ba39a92013-05-30 17:43:19 +00001881#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
danielk19771d461462009-04-21 09:02:45 +00001882
1883
drh1435a9a2013-08-27 23:15:44 +00001884#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drh28c4cf42005-07-27 20:41:43 +00001885/*
drhfaacf172011-08-12 01:51:45 +00001886** Estimate the location of a particular key among all keys in an
1887** index. Store the results in aStat as follows:
drhe847d322011-01-20 02:56:37 +00001888**
drhfaacf172011-08-12 01:51:45 +00001889** aStat[0] Est. number of rows less than pVal
1890** aStat[1] Est. number of rows equal to pVal
dan02fa4692009-08-17 17:06:58 +00001891**
drhfaacf172011-08-12 01:51:45 +00001892** Return SQLITE_OK on success.
dan02fa4692009-08-17 17:06:58 +00001893*/
danb3c02e22013-08-08 19:38:40 +00001894static void whereKeyStats(
dan02fa4692009-08-17 17:06:58 +00001895 Parse *pParse, /* Database connection */
1896 Index *pIdx, /* Index to consider domain of */
dan7a419232013-08-06 20:01:43 +00001897 UnpackedRecord *pRec, /* Vector of values to consider */
drhfaacf172011-08-12 01:51:45 +00001898 int roundUp, /* Round up if true. Round down if false */
1899 tRowcnt *aStat /* OUT: stats written here */
dan02fa4692009-08-17 17:06:58 +00001900){
danf52bb8d2013-08-03 20:24:58 +00001901 IndexSample *aSample = pIdx->aSample;
drhfbc38de2013-09-03 19:26:22 +00001902 int iCol; /* Index of required stats in anEq[] etc. */
dan84c309b2013-08-08 16:17:12 +00001903 int iMin = 0; /* Smallest sample not yet tested */
1904 int i = pIdx->nSample; /* Smallest sample larger than or equal to pRec */
1905 int iTest; /* Next sample to test */
1906 int res; /* Result of comparison operation */
dan02fa4692009-08-17 17:06:58 +00001907
drh4f991892013-10-11 15:05:05 +00001908#ifndef SQLITE_DEBUG
1909 UNUSED_PARAMETER( pParse );
1910#endif
drh7f594752013-12-03 19:49:55 +00001911 assert( pRec!=0 );
drhfbc38de2013-09-03 19:26:22 +00001912 iCol = pRec->nField - 1;
drh5c624862011-09-22 18:46:34 +00001913 assert( pIdx->nSample>0 );
dan8ad169a2013-08-12 20:14:04 +00001914 assert( pRec->nField>0 && iCol<pIdx->nSampleCol );
dan84c309b2013-08-08 16:17:12 +00001915 do{
1916 iTest = (iMin+i)/2;
dan3833e932014-03-01 19:44:56 +00001917 res = sqlite3VdbeRecordCompare(aSample[iTest].n, aSample[iTest].p, pRec, 0);
dan84c309b2013-08-08 16:17:12 +00001918 if( res<0 ){
1919 iMin = iTest+1;
1920 }else{
1921 i = iTest;
dan02fa4692009-08-17 17:06:58 +00001922 }
dan84c309b2013-08-08 16:17:12 +00001923 }while( res && iMin<i );
drh51147ba2005-07-23 22:59:55 +00001924
dan84c309b2013-08-08 16:17:12 +00001925#ifdef SQLITE_DEBUG
1926 /* The following assert statements check that the binary search code
1927 ** above found the right answer. This block serves no purpose other
1928 ** than to invoke the asserts. */
1929 if( res==0 ){
1930 /* If (res==0) is true, then sample $i must be equal to pRec */
1931 assert( i<pIdx->nSample );
dan3833e932014-03-01 19:44:56 +00001932 assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec, 0)
drh0e1f0022013-08-16 14:49:00 +00001933 || pParse->db->mallocFailed );
dan02fa4692009-08-17 17:06:58 +00001934 }else{
dan84c309b2013-08-08 16:17:12 +00001935 /* Otherwise, pRec must be smaller than sample $i and larger than
1936 ** sample ($i-1). */
1937 assert( i==pIdx->nSample
dan3833e932014-03-01 19:44:56 +00001938 || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec, 0)>0
drh0e1f0022013-08-16 14:49:00 +00001939 || pParse->db->mallocFailed );
dan84c309b2013-08-08 16:17:12 +00001940 assert( i==0
dan3833e932014-03-01 19:44:56 +00001941 || sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec, 0)<0
drh0e1f0022013-08-16 14:49:00 +00001942 || pParse->db->mallocFailed );
drhfaacf172011-08-12 01:51:45 +00001943 }
dan84c309b2013-08-08 16:17:12 +00001944#endif /* ifdef SQLITE_DEBUG */
dan02fa4692009-08-17 17:06:58 +00001945
drhfaacf172011-08-12 01:51:45 +00001946 /* At this point, aSample[i] is the first sample that is greater than
1947 ** or equal to pVal. Or if i==pIdx->nSample, then all samples are less
dan84c309b2013-08-08 16:17:12 +00001948 ** than pVal. If aSample[i]==pVal, then res==0.
drhfaacf172011-08-12 01:51:45 +00001949 */
dan84c309b2013-08-08 16:17:12 +00001950 if( res==0 ){
daneea568d2013-08-07 19:46:15 +00001951 aStat[0] = aSample[i].anLt[iCol];
1952 aStat[1] = aSample[i].anEq[iCol];
drhfaacf172011-08-12 01:51:45 +00001953 }else{
1954 tRowcnt iLower, iUpper, iGap;
1955 if( i==0 ){
1956 iLower = 0;
daneea568d2013-08-07 19:46:15 +00001957 iUpper = aSample[0].anLt[iCol];
drhfaacf172011-08-12 01:51:45 +00001958 }else{
dancfc9df72014-04-25 15:01:01 +00001959 i64 nRow0 = sqlite3LogEstToInt(pIdx->aiRowLogEst[0]);
1960 iUpper = i>=pIdx->nSample ? nRow0 : aSample[i].anLt[iCol];
daneea568d2013-08-07 19:46:15 +00001961 iLower = aSample[i-1].anEq[iCol] + aSample[i-1].anLt[iCol];
drhfaacf172011-08-12 01:51:45 +00001962 }
drhbbbdc832013-10-22 18:01:40 +00001963 aStat[1] = (pIdx->nKeyCol>iCol ? pIdx->aAvgEq[iCol] : 1);
drhfaacf172011-08-12 01:51:45 +00001964 if( iLower>=iUpper ){
1965 iGap = 0;
1966 }else{
1967 iGap = iUpper - iLower;
drhfaacf172011-08-12 01:51:45 +00001968 }
1969 if( roundUp ){
1970 iGap = (iGap*2)/3;
1971 }else{
1972 iGap = iGap/3;
1973 }
1974 aStat[0] = iLower + iGap;
dan02fa4692009-08-17 17:06:58 +00001975 }
dan02fa4692009-08-17 17:06:58 +00001976}
drh1435a9a2013-08-27 23:15:44 +00001977#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
dan937d0de2009-10-15 18:35:38 +00001978
1979/*
danaa9933c2014-04-24 20:04:49 +00001980** If it is not NULL, pTerm is a term that provides an upper or lower
1981** bound on a range scan. Without considering pTerm, it is estimated
1982** that the scan will visit nNew rows. This function returns the number
1983** estimated to be visited after taking pTerm into account.
1984**
1985** If the user explicitly specified a likelihood() value for this term,
1986** then the return value is the likelihood multiplied by the number of
1987** input rows. Otherwise, this function assumes that an "IS NOT NULL" term
1988** has a likelihood of 0.50, and any other term a likelihood of 0.25.
1989*/
1990static LogEst whereRangeAdjust(WhereTerm *pTerm, LogEst nNew){
1991 LogEst nRet = nNew;
1992 if( pTerm ){
1993 if( pTerm->truthProb<=0 ){
1994 nRet += pTerm->truthProb;
dan7de2a1f2014-04-28 20:11:20 +00001995 }else if( (pTerm->wtFlags & TERM_VNULL)==0 ){
danaa9933c2014-04-24 20:04:49 +00001996 nRet -= 20; assert( 20==sqlite3LogEst(4) );
1997 }
1998 }
1999 return nRet;
2000}
2001
2002/*
dan02fa4692009-08-17 17:06:58 +00002003** This function is used to estimate the number of rows that will be visited
2004** by scanning an index for a range of values. The range may have an upper
2005** bound, a lower bound, or both. The WHERE clause terms that set the upper
2006** and lower bounds are represented by pLower and pUpper respectively. For
2007** example, assuming that index p is on t1(a):
2008**
2009** ... FROM t1 WHERE a > ? AND a < ? ...
2010** |_____| |_____|
2011** | |
2012** pLower pUpper
2013**
drh98cdf622009-08-20 18:14:42 +00002014** If either of the upper or lower bound is not present, then NULL is passed in
drhcdaca552009-08-20 13:45:07 +00002015** place of the corresponding WhereTerm.
dan02fa4692009-08-17 17:06:58 +00002016**
dan6cb8d762013-08-08 11:48:57 +00002017** The value in (pBuilder->pNew->u.btree.nEq) is the index of the index
2018** column subject to the range constraint. Or, equivalently, the number of
2019** equality constraints optimized by the proposed index scan. For example,
2020** assuming index p is on t1(a, b), and the SQL query is:
dan02fa4692009-08-17 17:06:58 +00002021**
2022** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
2023**
dan6cb8d762013-08-08 11:48:57 +00002024** then nEq is set to 1 (as the range restricted column, b, is the second
2025** left-most column of the index). Or, if the query is:
dan02fa4692009-08-17 17:06:58 +00002026**
2027** ... FROM t1 WHERE a > ? AND a < ? ...
2028**
dan6cb8d762013-08-08 11:48:57 +00002029** then nEq is set to 0.
dan02fa4692009-08-17 17:06:58 +00002030**
drhbf539c42013-10-05 18:16:02 +00002031** When this function is called, *pnOut is set to the sqlite3LogEst() of the
dan6cb8d762013-08-08 11:48:57 +00002032** number of rows that the index scan is expected to visit without
2033** considering the range constraints. If nEq is 0, this is the number of
2034** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced)
2035** to account for the range contraints pLower and pUpper.
2036**
2037** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be
2038** used, each range inequality reduces the search space by a factor of 4.
2039** Hence a pair of constraints (x>? AND x<?) reduces the expected number of
2040** rows visited by a factor of 16.
dan02fa4692009-08-17 17:06:58 +00002041*/
2042static int whereRangeScanEst(
drhcdaca552009-08-20 13:45:07 +00002043 Parse *pParse, /* Parsing & code generating context */
dan7a419232013-08-06 20:01:43 +00002044 WhereLoopBuilder *pBuilder,
drhcdaca552009-08-20 13:45:07 +00002045 WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
2046 WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
drh186ad8c2013-10-08 18:40:37 +00002047 WhereLoop *pLoop /* Modify the .nOut and maybe .rRun fields */
dan02fa4692009-08-17 17:06:58 +00002048){
dan69188d92009-08-19 08:18:32 +00002049 int rc = SQLITE_OK;
drh186ad8c2013-10-08 18:40:37 +00002050 int nOut = pLoop->nOut;
drhbf539c42013-10-05 18:16:02 +00002051 LogEst nNew;
dan69188d92009-08-19 08:18:32 +00002052
drh1435a9a2013-08-27 23:15:44 +00002053#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drh186ad8c2013-10-08 18:40:37 +00002054 Index *p = pLoop->u.btree.pIndex;
drh4f991892013-10-11 15:05:05 +00002055 int nEq = pLoop->u.btree.nEq;
dan02fa4692009-08-17 17:06:58 +00002056
drh74dade22013-09-04 18:14:53 +00002057 if( p->nSample>0
2058 && nEq==pBuilder->nRecValid
dan8ad169a2013-08-12 20:14:04 +00002059 && nEq<p->nSampleCol
dan7a419232013-08-06 20:01:43 +00002060 && OptimizationEnabled(pParse->db, SQLITE_Stat3)
2061 ){
2062 UnpackedRecord *pRec = pBuilder->pRec;
drhfaacf172011-08-12 01:51:45 +00002063 tRowcnt a[2];
dan575ab2f2013-09-02 07:16:40 +00002064 u8 aff;
drh98cdf622009-08-20 18:14:42 +00002065
danb3c02e22013-08-08 19:38:40 +00002066 /* Variable iLower will be set to the estimate of the number of rows in
2067 ** the index that are less than the lower bound of the range query. The
2068 ** lower bound being the concatenation of $P and $L, where $P is the
2069 ** key-prefix formed by the nEq values matched against the nEq left-most
2070 ** columns of the index, and $L is the value in pLower.
2071 **
2072 ** Or, if pLower is NULL or $L cannot be extracted from it (because it
2073 ** is not a simple variable or literal value), the lower bound of the
2074 ** range is $P. Due to a quirk in the way whereKeyStats() works, even
2075 ** if $L is available, whereKeyStats() is called for both ($P) and
2076 ** ($P:$L) and the larger of the two returned values used.
2077 **
2078 ** Similarly, iUpper is to be set to the estimate of the number of rows
2079 ** less than the upper bound of the range query. Where the upper bound
2080 ** is either ($P) or ($P:$U). Again, even if $U is available, both values
2081 ** of iUpper are requested of whereKeyStats() and the smaller used.
2082 */
2083 tRowcnt iLower;
2084 tRowcnt iUpper;
2085
drhbbbdc832013-10-22 18:01:40 +00002086 if( nEq==p->nKeyCol ){
mistachkinc2cfb512013-09-04 04:04:08 +00002087 aff = SQLITE_AFF_INTEGER;
2088 }else{
2089 aff = p->pTable->aCol[p->aiColumn[nEq]].affinity;
2090 }
danb3c02e22013-08-08 19:38:40 +00002091 /* Determine iLower and iUpper using ($P) only. */
2092 if( nEq==0 ){
2093 iLower = 0;
dancfc9df72014-04-25 15:01:01 +00002094 iUpper = sqlite3LogEstToInt(p->aiRowLogEst[0]);
danb3c02e22013-08-08 19:38:40 +00002095 }else{
2096 /* Note: this call could be optimized away - since the same values must
2097 ** have been requested when testing key $P in whereEqualScanEst(). */
2098 whereKeyStats(pParse, p, pRec, 0, a);
2099 iLower = a[0];
2100 iUpper = a[0] + a[1];
2101 }
2102
2103 /* If possible, improve on the iLower estimate using ($P:$L). */
dan02fa4692009-08-17 17:06:58 +00002104 if( pLower ){
dan7a419232013-08-06 20:01:43 +00002105 int bOk; /* True if value is extracted from pExpr */
dan02fa4692009-08-17 17:06:58 +00002106 Expr *pExpr = pLower->pExpr->pRight;
drh7a5bcc02013-01-16 17:08:58 +00002107 assert( (pLower->eOperator & (WO_GT|WO_GE))!=0 );
dan87cd9322013-08-07 15:52:41 +00002108 rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
danb3c02e22013-08-08 19:38:40 +00002109 if( rc==SQLITE_OK && bOk ){
2110 tRowcnt iNew;
2111 whereKeyStats(pParse, p, pRec, 0, a);
2112 iNew = a[0] + ((pLower->eOperator & WO_GT) ? a[1] : 0);
2113 if( iNew>iLower ) iLower = iNew;
drhabfa6d52013-09-11 03:53:22 +00002114 nOut--;
drhfaacf172011-08-12 01:51:45 +00002115 }
dan02fa4692009-08-17 17:06:58 +00002116 }
danb3c02e22013-08-08 19:38:40 +00002117
2118 /* If possible, improve on the iUpper estimate using ($P:$U). */
2119 if( pUpper ){
dan7a419232013-08-06 20:01:43 +00002120 int bOk; /* True if value is extracted from pExpr */
dan02fa4692009-08-17 17:06:58 +00002121 Expr *pExpr = pUpper->pExpr->pRight;
drh7a5bcc02013-01-16 17:08:58 +00002122 assert( (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
dan87cd9322013-08-07 15:52:41 +00002123 rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
danb3c02e22013-08-08 19:38:40 +00002124 if( rc==SQLITE_OK && bOk ){
2125 tRowcnt iNew;
2126 whereKeyStats(pParse, p, pRec, 1, a);
2127 iNew = a[0] + ((pUpper->eOperator & WO_LE) ? a[1] : 0);
2128 if( iNew<iUpper ) iUpper = iNew;
drhabfa6d52013-09-11 03:53:22 +00002129 nOut--;
dan02fa4692009-08-17 17:06:58 +00002130 }
2131 }
danb3c02e22013-08-08 19:38:40 +00002132
dan87cd9322013-08-07 15:52:41 +00002133 pBuilder->pRec = pRec;
drhfaacf172011-08-12 01:51:45 +00002134 if( rc==SQLITE_OK ){
drhb8a8e8a2013-06-10 19:12:39 +00002135 if( iUpper>iLower ){
drhbf539c42013-10-05 18:16:02 +00002136 nNew = sqlite3LogEst(iUpper - iLower);
dan7a419232013-08-06 20:01:43 +00002137 }else{
drhbf539c42013-10-05 18:16:02 +00002138 nNew = 10; assert( 10==sqlite3LogEst(2) );
drhfaacf172011-08-12 01:51:45 +00002139 }
dan6cb8d762013-08-08 11:48:57 +00002140 if( nNew<nOut ){
2141 nOut = nNew;
2142 }
drh186ad8c2013-10-08 18:40:37 +00002143 pLoop->nOut = (LogEst)nOut;
drh989578e2013-10-28 14:34:35 +00002144 WHERETRACE(0x10, ("range scan regions: %u..%u est=%d\n",
dan6cb8d762013-08-08 11:48:57 +00002145 (u32)iLower, (u32)iUpper, nOut));
drhfaacf172011-08-12 01:51:45 +00002146 return SQLITE_OK;
drh98cdf622009-08-20 18:14:42 +00002147 }
dan02fa4692009-08-17 17:06:58 +00002148 }
drh3f022182009-09-09 16:10:50 +00002149#else
2150 UNUSED_PARAMETER(pParse);
dan7a419232013-08-06 20:01:43 +00002151 UNUSED_PARAMETER(pBuilder);
dan69188d92009-08-19 08:18:32 +00002152#endif
dan02fa4692009-08-17 17:06:58 +00002153 assert( pLower || pUpper );
dan7de2a1f2014-04-28 20:11:20 +00002154 assert( pUpper==0 || (pUpper->wtFlags & TERM_VNULL)==0 );
danaa9933c2014-04-24 20:04:49 +00002155 nNew = whereRangeAdjust(pLower, nOut);
2156 nNew = whereRangeAdjust(pUpper, nNew);
dan7de2a1f2014-04-28 20:11:20 +00002157
dan42685f22014-04-28 19:34:06 +00002158 /* TUNING: If there is both an upper and lower limit, assume the range is
2159 ** reduced by an additional 75%. This means that, by default, an open-ended
2160 ** range query (e.g. col > ?) is assumed to match 1/4 of the rows in the
2161 ** index. While a closed range (e.g. col BETWEEN ? AND ?) is estimated to
2162 ** match 1/64 of the index. */
2163 if( pLower && pUpper ) nNew -= 20;
dan7de2a1f2014-04-28 20:11:20 +00002164
danaa9933c2014-04-24 20:04:49 +00002165 nOut -= (pLower!=0) + (pUpper!=0);
drhabfa6d52013-09-11 03:53:22 +00002166 if( nNew<10 ) nNew = 10;
2167 if( nNew<nOut ) nOut = nNew;
drh186ad8c2013-10-08 18:40:37 +00002168 pLoop->nOut = (LogEst)nOut;
dan02fa4692009-08-17 17:06:58 +00002169 return rc;
2170}
2171
drh1435a9a2013-08-27 23:15:44 +00002172#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drh82759752011-01-20 16:52:09 +00002173/*
2174** Estimate the number of rows that will be returned based on
2175** an equality constraint x=VALUE and where that VALUE occurs in
2176** the histogram data. This only works when x is the left-most
drhfaacf172011-08-12 01:51:45 +00002177** column of an index and sqlite_stat3 histogram data is available
drhac8eb112011-03-17 01:58:21 +00002178** for that index. When pExpr==NULL that means the constraint is
2179** "x IS NULL" instead of "x=VALUE".
drh82759752011-01-20 16:52:09 +00002180**
drh0c50fa02011-01-21 16:27:18 +00002181** Write the estimated row count into *pnRow and return SQLITE_OK.
2182** If unable to make an estimate, leave *pnRow unchanged and return
2183** non-zero.
drh9b3eb0a2011-01-21 14:37:04 +00002184**
2185** This routine can fail if it is unable to load a collating sequence
2186** required for string comparison, or if unable to allocate memory
2187** for a UTF conversion required for comparison. The error is stored
2188** in the pParse structure.
drh82759752011-01-20 16:52:09 +00002189*/
drh041e09f2011-04-07 19:56:21 +00002190static int whereEqualScanEst(
drh82759752011-01-20 16:52:09 +00002191 Parse *pParse, /* Parsing & code generating context */
dan7a419232013-08-06 20:01:43 +00002192 WhereLoopBuilder *pBuilder,
drh0c50fa02011-01-21 16:27:18 +00002193 Expr *pExpr, /* Expression for VALUE in the x=VALUE constraint */
drhb8a8e8a2013-06-10 19:12:39 +00002194 tRowcnt *pnRow /* Write the revised row estimate here */
drh82759752011-01-20 16:52:09 +00002195){
dan7a419232013-08-06 20:01:43 +00002196 Index *p = pBuilder->pNew->u.btree.pIndex;
2197 int nEq = pBuilder->pNew->u.btree.nEq;
2198 UnpackedRecord *pRec = pBuilder->pRec;
drh82759752011-01-20 16:52:09 +00002199 u8 aff; /* Column affinity */
2200 int rc; /* Subfunction return code */
drhfaacf172011-08-12 01:51:45 +00002201 tRowcnt a[2]; /* Statistics */
dan7a419232013-08-06 20:01:43 +00002202 int bOk;
drh82759752011-01-20 16:52:09 +00002203
dan7a419232013-08-06 20:01:43 +00002204 assert( nEq>=1 );
drhbbbdc832013-10-22 18:01:40 +00002205 assert( nEq<=(p->nKeyCol+1) );
drh82759752011-01-20 16:52:09 +00002206 assert( p->aSample!=0 );
drh5c624862011-09-22 18:46:34 +00002207 assert( p->nSample>0 );
dan7a419232013-08-06 20:01:43 +00002208 assert( pBuilder->nRecValid<nEq );
2209
2210 /* If values are not available for all fields of the index to the left
2211 ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */
2212 if( pBuilder->nRecValid<(nEq-1) ){
2213 return SQLITE_NOTFOUND;
drh1f9c7662011-03-17 01:34:26 +00002214 }
dan7a419232013-08-06 20:01:43 +00002215
dandd6e1f12013-08-10 19:08:30 +00002216 /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue()
2217 ** below would return the same value. */
drhbbbdc832013-10-22 18:01:40 +00002218 if( nEq>p->nKeyCol ){
dan7a419232013-08-06 20:01:43 +00002219 *pnRow = 1;
2220 return SQLITE_OK;
drh82759752011-01-20 16:52:09 +00002221 }
dan7a419232013-08-06 20:01:43 +00002222
daneea568d2013-08-07 19:46:15 +00002223 aff = p->pTable->aCol[p->aiColumn[nEq-1]].affinity;
dan87cd9322013-08-07 15:52:41 +00002224 rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq-1, &bOk);
2225 pBuilder->pRec = pRec;
dan7a419232013-08-06 20:01:43 +00002226 if( rc!=SQLITE_OK ) return rc;
2227 if( bOk==0 ) return SQLITE_NOTFOUND;
dan7a419232013-08-06 20:01:43 +00002228 pBuilder->nRecValid = nEq;
dan7a419232013-08-06 20:01:43 +00002229
danb3c02e22013-08-08 19:38:40 +00002230 whereKeyStats(pParse, p, pRec, 0, a);
drh989578e2013-10-28 14:34:35 +00002231 WHERETRACE(0x10,("equality scan regions: %d\n", (int)a[1]));
danb3c02e22013-08-08 19:38:40 +00002232 *pnRow = a[1];
daneea568d2013-08-07 19:46:15 +00002233
drh0c50fa02011-01-21 16:27:18 +00002234 return rc;
2235}
drh1435a9a2013-08-27 23:15:44 +00002236#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
drh0c50fa02011-01-21 16:27:18 +00002237
drh1435a9a2013-08-27 23:15:44 +00002238#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drh0c50fa02011-01-21 16:27:18 +00002239/*
2240** Estimate the number of rows that will be returned based on
drh5ac06072011-01-21 18:18:13 +00002241** an IN constraint where the right-hand side of the IN operator
2242** is a list of values. Example:
2243**
2244** WHERE x IN (1,2,3,4)
drh0c50fa02011-01-21 16:27:18 +00002245**
2246** Write the estimated row count into *pnRow and return SQLITE_OK.
2247** If unable to make an estimate, leave *pnRow unchanged and return
2248** non-zero.
2249**
2250** This routine can fail if it is unable to load a collating sequence
2251** required for string comparison, or if unable to allocate memory
2252** for a UTF conversion required for comparison. The error is stored
2253** in the pParse structure.
2254*/
drh041e09f2011-04-07 19:56:21 +00002255static int whereInScanEst(
drh0c50fa02011-01-21 16:27:18 +00002256 Parse *pParse, /* Parsing & code generating context */
dan7a419232013-08-06 20:01:43 +00002257 WhereLoopBuilder *pBuilder,
drh0c50fa02011-01-21 16:27:18 +00002258 ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
drhb8a8e8a2013-06-10 19:12:39 +00002259 tRowcnt *pnRow /* Write the revised row estimate here */
drh0c50fa02011-01-21 16:27:18 +00002260){
dan7a419232013-08-06 20:01:43 +00002261 Index *p = pBuilder->pNew->u.btree.pIndex;
dancfc9df72014-04-25 15:01:01 +00002262 i64 nRow0 = sqlite3LogEstToInt(p->aiRowLogEst[0]);
dan7a419232013-08-06 20:01:43 +00002263 int nRecValid = pBuilder->nRecValid;
drhb8a8e8a2013-06-10 19:12:39 +00002264 int rc = SQLITE_OK; /* Subfunction return code */
2265 tRowcnt nEst; /* Number of rows for a single term */
2266 tRowcnt nRowEst = 0; /* New estimate of the number of rows */
2267 int i; /* Loop counter */
drh0c50fa02011-01-21 16:27:18 +00002268
2269 assert( p->aSample!=0 );
drhfaacf172011-08-12 01:51:45 +00002270 for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
dancfc9df72014-04-25 15:01:01 +00002271 nEst = nRow0;
dan7a419232013-08-06 20:01:43 +00002272 rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst);
drhfaacf172011-08-12 01:51:45 +00002273 nRowEst += nEst;
dan7a419232013-08-06 20:01:43 +00002274 pBuilder->nRecValid = nRecValid;
drh0c50fa02011-01-21 16:27:18 +00002275 }
dan7a419232013-08-06 20:01:43 +00002276
drh0c50fa02011-01-21 16:27:18 +00002277 if( rc==SQLITE_OK ){
dancfc9df72014-04-25 15:01:01 +00002278 if( nRowEst > nRow0 ) nRowEst = nRow0;
drh0c50fa02011-01-21 16:27:18 +00002279 *pnRow = nRowEst;
drh989578e2013-10-28 14:34:35 +00002280 WHERETRACE(0x10,("IN row estimate: est=%g\n", nRowEst));
drh0c50fa02011-01-21 16:27:18 +00002281 }
dan7a419232013-08-06 20:01:43 +00002282 assert( pBuilder->nRecValid==nRecValid );
drh0c50fa02011-01-21 16:27:18 +00002283 return rc;
drh82759752011-01-20 16:52:09 +00002284}
drh1435a9a2013-08-27 23:15:44 +00002285#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
drh82759752011-01-20 16:52:09 +00002286
drh46c35f92012-09-26 23:17:01 +00002287/*
drh2ffb1182004-07-19 19:14:01 +00002288** Disable a term in the WHERE clause. Except, do not disable the term
2289** if it controls a LEFT OUTER JOIN and it did not originate in the ON
2290** or USING clause of that join.
2291**
2292** Consider the term t2.z='ok' in the following queries:
2293**
2294** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
2295** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
2296** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
2297**
drh23bf66d2004-12-14 03:34:34 +00002298** The t2.z='ok' is disabled in the in (2) because it originates
drh2ffb1182004-07-19 19:14:01 +00002299** in the ON clause. The term is disabled in (3) because it is not part
2300** of a LEFT OUTER JOIN. In (1), the term is not disabled.
2301**
2302** Disabling a term causes that term to not be tested in the inner loop
drhb6fb62d2005-09-20 08:47:20 +00002303** of the join. Disabling is an optimization. When terms are satisfied
2304** by indices, we disable them to prevent redundant tests in the inner
2305** loop. We would get the correct results if nothing were ever disabled,
2306** but joins might run a little slower. The trick is to disable as much
2307** as we can without disabling too much. If we disabled in (1), we'd get
2308** the wrong answer. See ticket #813.
drh2ffb1182004-07-19 19:14:01 +00002309*/
drh0fcef5e2005-07-19 17:38:22 +00002310static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
2311 if( pTerm
drhbe837bd2010-04-30 21:03:24 +00002312 && (pTerm->wtFlags & TERM_CODED)==0
drh0fcef5e2005-07-19 17:38:22 +00002313 && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
drh0259bc32013-09-09 19:37:46 +00002314 && (pLevel->notReady & pTerm->prereqAll)==0
drh0fcef5e2005-07-19 17:38:22 +00002315 ){
drh165be382008-12-05 02:36:33 +00002316 pTerm->wtFlags |= TERM_CODED;
drh45b1ee42005-08-02 17:48:22 +00002317 if( pTerm->iParent>=0 ){
2318 WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
2319 if( (--pOther->nChild)==0 ){
drhed378002005-07-28 23:12:08 +00002320 disableTerm(pLevel, pOther);
2321 }
drh0fcef5e2005-07-19 17:38:22 +00002322 }
drh2ffb1182004-07-19 19:14:01 +00002323 }
2324}
2325
2326/*
dan69f8bb92009-08-13 19:21:16 +00002327** Code an OP_Affinity opcode to apply the column affinity string zAff
2328** to the n registers starting at base.
2329**
drh039fc322009-11-17 18:31:47 +00002330** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
2331** beginning and end of zAff are ignored. If all entries in zAff are
2332** SQLITE_AFF_NONE, then no code gets generated.
2333**
2334** This routine makes its own copy of zAff so that the caller is free
2335** to modify zAff after this routine returns.
drh94a11212004-09-25 13:12:14 +00002336*/
dan69f8bb92009-08-13 19:21:16 +00002337static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
2338 Vdbe *v = pParse->pVdbe;
drh039fc322009-11-17 18:31:47 +00002339 if( zAff==0 ){
2340 assert( pParse->db->mallocFailed );
2341 return;
2342 }
dan69f8bb92009-08-13 19:21:16 +00002343 assert( v!=0 );
drh039fc322009-11-17 18:31:47 +00002344
2345 /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
2346 ** and end of the affinity string.
2347 */
2348 while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
2349 n--;
2350 base++;
2351 zAff++;
2352 }
2353 while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
2354 n--;
2355 }
2356
2357 /* Code the OP_Affinity opcode if there is anything left to do. */
2358 if( n>0 ){
2359 sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
2360 sqlite3VdbeChangeP4(v, -1, zAff, n);
2361 sqlite3ExprCacheAffinityChange(pParse, base, n);
2362 }
drh94a11212004-09-25 13:12:14 +00002363}
2364
drhe8b97272005-07-19 22:22:12 +00002365
2366/*
drh51147ba2005-07-23 22:59:55 +00002367** Generate code for a single equality term of the WHERE clause. An equality
2368** term can be either X=expr or X IN (...). pTerm is the term to be
2369** coded.
2370**
drh1db639c2008-01-17 02:36:28 +00002371** The current value for the constraint is left in register iReg.
drh51147ba2005-07-23 22:59:55 +00002372**
2373** For a constraint of the form X=expr, the expression is evaluated and its
2374** result is left on the stack. For constraints of the form X IN (...)
2375** this routine sets up a loop that will iterate over all values of X.
drh94a11212004-09-25 13:12:14 +00002376*/
drh678ccce2008-03-31 18:19:54 +00002377static int codeEqualityTerm(
drh94a11212004-09-25 13:12:14 +00002378 Parse *pParse, /* The parsing context */
drhe23399f2005-07-22 00:31:39 +00002379 WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
drh0fe456b2013-03-12 18:34:50 +00002380 WhereLevel *pLevel, /* The level of the FROM clause we are working on */
2381 int iEq, /* Index of the equality term within this level */
drh7ba39a92013-05-30 17:43:19 +00002382 int bRev, /* True for reverse-order IN operations */
drh678ccce2008-03-31 18:19:54 +00002383 int iTarget /* Attempt to leave results in this register */
drh94a11212004-09-25 13:12:14 +00002384){
drh0fcef5e2005-07-19 17:38:22 +00002385 Expr *pX = pTerm->pExpr;
drh50b39962006-10-28 00:28:09 +00002386 Vdbe *v = pParse->pVdbe;
drh678ccce2008-03-31 18:19:54 +00002387 int iReg; /* Register holding results */
drh1db639c2008-01-17 02:36:28 +00002388
danielk19772d605492008-10-01 08:43:03 +00002389 assert( iTarget>0 );
drh50b39962006-10-28 00:28:09 +00002390 if( pX->op==TK_EQ ){
drh678ccce2008-03-31 18:19:54 +00002391 iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
drh50b39962006-10-28 00:28:09 +00002392 }else if( pX->op==TK_ISNULL ){
drh678ccce2008-03-31 18:19:54 +00002393 iReg = iTarget;
drh1db639c2008-01-17 02:36:28 +00002394 sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
danielk1977b3bce662005-01-29 08:32:43 +00002395#ifndef SQLITE_OMIT_SUBQUERY
drh94a11212004-09-25 13:12:14 +00002396 }else{
danielk19779a96b662007-11-29 17:05:18 +00002397 int eType;
danielk1977b3bce662005-01-29 08:32:43 +00002398 int iTab;
drh72e8fa42007-03-28 14:30:06 +00002399 struct InLoop *pIn;
drh7ba39a92013-05-30 17:43:19 +00002400 WhereLoop *pLoop = pLevel->pWLoop;
danielk1977b3bce662005-01-29 08:32:43 +00002401
drh7ba39a92013-05-30 17:43:19 +00002402 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
2403 && pLoop->u.btree.pIndex!=0
2404 && pLoop->u.btree.pIndex->aSortOrder[iEq]
drhd3832162013-03-12 18:49:25 +00002405 ){
drh725e1ae2013-03-12 23:58:42 +00002406 testcase( iEq==0 );
drh725e1ae2013-03-12 23:58:42 +00002407 testcase( bRev );
drh1ccce442013-03-12 20:38:51 +00002408 bRev = !bRev;
drh0fe456b2013-03-12 18:34:50 +00002409 }
drh50b39962006-10-28 00:28:09 +00002410 assert( pX->op==TK_IN );
drh678ccce2008-03-31 18:19:54 +00002411 iReg = iTarget;
danielk19770cdc0222008-06-26 18:04:03 +00002412 eType = sqlite3FindInIndex(pParse, pX, 0);
drh725e1ae2013-03-12 23:58:42 +00002413 if( eType==IN_INDEX_INDEX_DESC ){
2414 testcase( bRev );
2415 bRev = !bRev;
2416 }
danielk1977b3bce662005-01-29 08:32:43 +00002417 iTab = pX->iTable;
drh7d176102014-02-18 03:07:12 +00002418 sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
2419 VdbeCoverageIf(v, bRev);
2420 VdbeCoverageIf(v, !bRev);
drh6fa978d2013-05-30 19:29:19 +00002421 assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
2422 pLoop->wsFlags |= WHERE_IN_ABLE;
drh111a6a72008-12-21 03:51:16 +00002423 if( pLevel->u.in.nIn==0 ){
drhb3190c12008-12-08 21:37:14 +00002424 pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
drh72e8fa42007-03-28 14:30:06 +00002425 }
drh111a6a72008-12-21 03:51:16 +00002426 pLevel->u.in.nIn++;
2427 pLevel->u.in.aInLoop =
2428 sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
2429 sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
2430 pIn = pLevel->u.in.aInLoop;
drh72e8fa42007-03-28 14:30:06 +00002431 if( pIn ){
drh111a6a72008-12-21 03:51:16 +00002432 pIn += pLevel->u.in.nIn - 1;
drh72e8fa42007-03-28 14:30:06 +00002433 pIn->iCur = iTab;
drh1db639c2008-01-17 02:36:28 +00002434 if( eType==IN_INDEX_ROWID ){
drhb3190c12008-12-08 21:37:14 +00002435 pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
drh1db639c2008-01-17 02:36:28 +00002436 }else{
drhb3190c12008-12-08 21:37:14 +00002437 pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
drh1db639c2008-01-17 02:36:28 +00002438 }
drhf93cd942013-11-21 03:12:25 +00002439 pIn->eEndLoopOp = bRev ? OP_PrevIfOpen : OP_NextIfOpen;
drh688852a2014-02-17 22:40:43 +00002440 sqlite3VdbeAddOp1(v, OP_IsNull, iReg); VdbeCoverage(v);
drha6110402005-07-28 20:51:19 +00002441 }else{
drh111a6a72008-12-21 03:51:16 +00002442 pLevel->u.in.nIn = 0;
drhe23399f2005-07-22 00:31:39 +00002443 }
danielk1977b3bce662005-01-29 08:32:43 +00002444#endif
drh94a11212004-09-25 13:12:14 +00002445 }
drh0fcef5e2005-07-19 17:38:22 +00002446 disableTerm(pLevel, pTerm);
drh678ccce2008-03-31 18:19:54 +00002447 return iReg;
drh94a11212004-09-25 13:12:14 +00002448}
2449
drh51147ba2005-07-23 22:59:55 +00002450/*
2451** Generate code that will evaluate all == and IN constraints for an
drhcd8629e2013-11-13 12:27:25 +00002452** index scan.
drh51147ba2005-07-23 22:59:55 +00002453**
2454** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
2455** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
2456** The index has as many as three equality constraints, but in this
2457** example, the third "c" value is an inequality. So only two
2458** constraints are coded. This routine will generate code to evaluate
drh6df2acd2008-12-28 16:55:25 +00002459** a==5 and b IN (1,2,3). The current values for a and b will be stored
2460** in consecutive registers and the index of the first register is returned.
drh51147ba2005-07-23 22:59:55 +00002461**
2462** In the example above nEq==2. But this subroutine works for any value
2463** of nEq including 0. If nEq==0, this routine is nearly a no-op.
drh039fc322009-11-17 18:31:47 +00002464** The only thing it does is allocate the pLevel->iMem memory cell and
2465** compute the affinity string.
drh51147ba2005-07-23 22:59:55 +00002466**
drhcd8629e2013-11-13 12:27:25 +00002467** The nExtraReg parameter is 0 or 1. It is 0 if all WHERE clause constraints
2468** are == or IN and are covered by the nEq. nExtraReg is 1 if there is
2469** an inequality constraint (such as the "c>=5 AND c<10" in the example) that
2470** occurs after the nEq quality constraints.
2471**
2472** This routine allocates a range of nEq+nExtraReg memory cells and returns
2473** the index of the first memory cell in that range. The code that
2474** calls this routine will use that memory range to store keys for
2475** start and termination conditions of the loop.
drh51147ba2005-07-23 22:59:55 +00002476** key value of the loop. If one or more IN operators appear, then
2477** this routine allocates an additional nEq memory cells for internal
2478** use.
dan69f8bb92009-08-13 19:21:16 +00002479**
2480** Before returning, *pzAff is set to point to a buffer containing a
2481** copy of the column affinity string of the index allocated using
2482** sqlite3DbMalloc(). Except, entries in the copy of the string associated
2483** with equality constraints that use NONE affinity are set to
2484** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
2485**
2486** CREATE TABLE t1(a TEXT PRIMARY KEY, b);
2487** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
2488**
2489** In the example above, the index on t1(a) has TEXT affinity. But since
2490** the right hand side of the equality constraint (t2.b) has NONE affinity,
2491** no conversion should be attempted before using a t2.b value as part of
2492** a key to search the index. Hence the first byte in the returned affinity
2493** string in this example would be set to SQLITE_AFF_NONE.
drh51147ba2005-07-23 22:59:55 +00002494*/
drh1db639c2008-01-17 02:36:28 +00002495static int codeAllEqualityTerms(
drh51147ba2005-07-23 22:59:55 +00002496 Parse *pParse, /* Parsing context */
2497 WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
drh7ba39a92013-05-30 17:43:19 +00002498 int bRev, /* Reverse the order of IN operators */
dan69f8bb92009-08-13 19:21:16 +00002499 int nExtraReg, /* Number of extra registers to allocate */
2500 char **pzAff /* OUT: Set to point to affinity string */
drh51147ba2005-07-23 22:59:55 +00002501){
drhcd8629e2013-11-13 12:27:25 +00002502 u16 nEq; /* The number of == or IN constraints to code */
2503 u16 nSkip; /* Number of left-most columns to skip */
drh111a6a72008-12-21 03:51:16 +00002504 Vdbe *v = pParse->pVdbe; /* The vm under construction */
2505 Index *pIdx; /* The index being used for this loop */
drh51147ba2005-07-23 22:59:55 +00002506 WhereTerm *pTerm; /* A single constraint term */
drh7ba39a92013-05-30 17:43:19 +00002507 WhereLoop *pLoop; /* The WhereLoop object */
drh51147ba2005-07-23 22:59:55 +00002508 int j; /* Loop counter */
drh1db639c2008-01-17 02:36:28 +00002509 int regBase; /* Base register */
drh6df2acd2008-12-28 16:55:25 +00002510 int nReg; /* Number of registers to allocate */
dan69f8bb92009-08-13 19:21:16 +00002511 char *zAff; /* Affinity string to return */
drh51147ba2005-07-23 22:59:55 +00002512
drh111a6a72008-12-21 03:51:16 +00002513 /* This module is only called on query plans that use an index. */
drh7ba39a92013-05-30 17:43:19 +00002514 pLoop = pLevel->pWLoop;
2515 assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
2516 nEq = pLoop->u.btree.nEq;
drhcd8629e2013-11-13 12:27:25 +00002517 nSkip = pLoop->u.btree.nSkip;
drh7ba39a92013-05-30 17:43:19 +00002518 pIdx = pLoop->u.btree.pIndex;
2519 assert( pIdx!=0 );
drh111a6a72008-12-21 03:51:16 +00002520
drh51147ba2005-07-23 22:59:55 +00002521 /* Figure out how many memory cells we will need then allocate them.
drh51147ba2005-07-23 22:59:55 +00002522 */
drh700a2262008-12-17 19:22:15 +00002523 regBase = pParse->nMem + 1;
drh7ba39a92013-05-30 17:43:19 +00002524 nReg = pLoop->u.btree.nEq + nExtraReg;
drh6df2acd2008-12-28 16:55:25 +00002525 pParse->nMem += nReg;
drh51147ba2005-07-23 22:59:55 +00002526
dan69f8bb92009-08-13 19:21:16 +00002527 zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
2528 if( !zAff ){
2529 pParse->db->mallocFailed = 1;
2530 }
2531
drhcd8629e2013-11-13 12:27:25 +00002532 if( nSkip ){
2533 int iIdxCur = pLevel->iIdxCur;
drh7d176102014-02-18 03:07:12 +00002534 sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur);
2535 VdbeCoverageIf(v, bRev==0);
2536 VdbeCoverageIf(v, bRev!=0);
drhe084f402013-11-13 17:24:38 +00002537 VdbeComment((v, "begin skip-scan on %s", pIdx->zName));
drh2e5ef4e2013-11-13 16:58:54 +00002538 j = sqlite3VdbeAddOp0(v, OP_Goto);
drh4a1d3652014-02-14 15:13:36 +00002539 pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT),
drh7d176102014-02-18 03:07:12 +00002540 iIdxCur, 0, regBase, nSkip);
2541 VdbeCoverageIf(v, bRev==0);
2542 VdbeCoverageIf(v, bRev!=0);
drh2e5ef4e2013-11-13 16:58:54 +00002543 sqlite3VdbeJumpHere(v, j);
drhcd8629e2013-11-13 12:27:25 +00002544 for(j=0; j<nSkip; j++){
2545 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, j, regBase+j);
2546 assert( pIdx->aiColumn[j]>=0 );
2547 VdbeComment((v, "%s", pIdx->pTable->aCol[pIdx->aiColumn[j]].zName));
2548 }
2549 }
2550
drh51147ba2005-07-23 22:59:55 +00002551 /* Evaluate the equality constraints
2552 */
mistachkinf6418892013-08-28 01:54:12 +00002553 assert( zAff==0 || (int)strlen(zAff)>=nEq );
drhcd8629e2013-11-13 12:27:25 +00002554 for(j=nSkip; j<nEq; j++){
drh678ccce2008-03-31 18:19:54 +00002555 int r1;
drh4efc9292013-06-06 23:02:03 +00002556 pTerm = pLoop->aLTerm[j];
drh7ba39a92013-05-30 17:43:19 +00002557 assert( pTerm!=0 );
drhcd8629e2013-11-13 12:27:25 +00002558 /* The following testcase is true for indices with redundant columns.
drhbe837bd2010-04-30 21:03:24 +00002559 ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
2560 testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
drh39759742013-08-02 23:40:45 +00002561 testcase( pTerm->wtFlags & TERM_VIRTUAL );
drh7ba39a92013-05-30 17:43:19 +00002562 r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
drh678ccce2008-03-31 18:19:54 +00002563 if( r1!=regBase+j ){
drh6df2acd2008-12-28 16:55:25 +00002564 if( nReg==1 ){
2565 sqlite3ReleaseTempReg(pParse, regBase);
2566 regBase = r1;
2567 }else{
2568 sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
2569 }
drh678ccce2008-03-31 18:19:54 +00002570 }
drh981642f2008-04-19 14:40:43 +00002571 testcase( pTerm->eOperator & WO_ISNULL );
2572 testcase( pTerm->eOperator & WO_IN );
drh72e8fa42007-03-28 14:30:06 +00002573 if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
drh039fc322009-11-17 18:31:47 +00002574 Expr *pRight = pTerm->pExpr->pRight;
drh7d176102014-02-18 03:07:12 +00002575 if( sqlite3ExprCanBeNull(pRight) ){
2576 sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk);
2577 VdbeCoverage(v);
2578 }
drh039fc322009-11-17 18:31:47 +00002579 if( zAff ){
2580 if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
2581 zAff[j] = SQLITE_AFF_NONE;
2582 }
2583 if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
2584 zAff[j] = SQLITE_AFF_NONE;
2585 }
dan69f8bb92009-08-13 19:21:16 +00002586 }
drh51147ba2005-07-23 22:59:55 +00002587 }
2588 }
dan69f8bb92009-08-13 19:21:16 +00002589 *pzAff = zAff;
drh1db639c2008-01-17 02:36:28 +00002590 return regBase;
drh51147ba2005-07-23 22:59:55 +00002591}
2592
dan2ce22452010-11-08 19:01:16 +00002593#ifndef SQLITE_OMIT_EXPLAIN
dan17c0bc02010-11-09 17:35:19 +00002594/*
drh69174c42010-11-12 15:35:59 +00002595** This routine is a helper for explainIndexRange() below
2596**
2597** pStr holds the text of an expression that we are building up one term
2598** at a time. This routine adds a new term to the end of the expression.
2599** Terms are separated by AND so add the "AND" text for second and subsequent
2600** terms only.
2601*/
2602static void explainAppendTerm(
2603 StrAccum *pStr, /* The text expression being built */
2604 int iTerm, /* Index of this term. First is zero */
2605 const char *zColumn, /* Name of the column */
2606 const char *zOp /* Name of the operator */
2607){
2608 if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
drha6353a32013-12-09 19:03:26 +00002609 sqlite3StrAccumAppendAll(pStr, zColumn);
drh69174c42010-11-12 15:35:59 +00002610 sqlite3StrAccumAppend(pStr, zOp, 1);
2611 sqlite3StrAccumAppend(pStr, "?", 1);
2612}
2613
2614/*
dan17c0bc02010-11-09 17:35:19 +00002615** Argument pLevel describes a strategy for scanning table pTab. This
2616** function returns a pointer to a string buffer containing a description
2617** of the subset of table rows scanned by the strategy in the form of an
2618** SQL expression. Or, if all rows are scanned, NULL is returned.
2619**
2620** For example, if the query:
2621**
2622** SELECT * FROM t1 WHERE a=1 AND b>2;
2623**
2624** is run and there is an index on (a, b), then this function returns a
2625** string similar to:
2626**
2627** "a=? AND b>?"
2628**
2629** The returned pointer points to memory obtained from sqlite3DbMalloc().
2630** It is the responsibility of the caller to free the buffer when it is
2631** no longer required.
2632*/
drhef866372013-05-22 20:49:02 +00002633static char *explainIndexRange(sqlite3 *db, WhereLoop *pLoop, Table *pTab){
2634 Index *pIndex = pLoop->u.btree.pIndex;
drhcd8629e2013-11-13 12:27:25 +00002635 u16 nEq = pLoop->u.btree.nEq;
2636 u16 nSkip = pLoop->u.btree.nSkip;
drh69174c42010-11-12 15:35:59 +00002637 int i, j;
2638 Column *aCol = pTab->aCol;
drhbbbdc832013-10-22 18:01:40 +00002639 i16 *aiColumn = pIndex->aiColumn;
drh69174c42010-11-12 15:35:59 +00002640 StrAccum txt;
dan2ce22452010-11-08 19:01:16 +00002641
drhef866372013-05-22 20:49:02 +00002642 if( nEq==0 && (pLoop->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ){
drh69174c42010-11-12 15:35:59 +00002643 return 0;
2644 }
2645 sqlite3StrAccumInit(&txt, 0, 0, SQLITE_MAX_LENGTH);
drh03b6df12010-11-15 16:29:30 +00002646 txt.db = db;
drh69174c42010-11-12 15:35:59 +00002647 sqlite3StrAccumAppend(&txt, " (", 2);
dan2ce22452010-11-08 19:01:16 +00002648 for(i=0; i<nEq; i++){
drhbbbdc832013-10-22 18:01:40 +00002649 char *z = (i==pIndex->nKeyCol ) ? "rowid" : aCol[aiColumn[i]].zName;
drhcd8629e2013-11-13 12:27:25 +00002650 if( i>=nSkip ){
2651 explainAppendTerm(&txt, i, z, "=");
2652 }else{
2653 if( i ) sqlite3StrAccumAppend(&txt, " AND ", 5);
2654 sqlite3StrAccumAppend(&txt, "ANY(", 4);
drha6353a32013-12-09 19:03:26 +00002655 sqlite3StrAccumAppendAll(&txt, z);
drhcd8629e2013-11-13 12:27:25 +00002656 sqlite3StrAccumAppend(&txt, ")", 1);
2657 }
dan2ce22452010-11-08 19:01:16 +00002658 }
2659
drh69174c42010-11-12 15:35:59 +00002660 j = i;
drhef866372013-05-22 20:49:02 +00002661 if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
drhbbbdc832013-10-22 18:01:40 +00002662 char *z = (j==pIndex->nKeyCol ) ? "rowid" : aCol[aiColumn[j]].zName;
dan0c733f62011-11-16 15:27:09 +00002663 explainAppendTerm(&txt, i++, z, ">");
dan2ce22452010-11-08 19:01:16 +00002664 }
drhef866372013-05-22 20:49:02 +00002665 if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
drhbbbdc832013-10-22 18:01:40 +00002666 char *z = (j==pIndex->nKeyCol ) ? "rowid" : aCol[aiColumn[j]].zName;
dan0c733f62011-11-16 15:27:09 +00002667 explainAppendTerm(&txt, i, z, "<");
dan2ce22452010-11-08 19:01:16 +00002668 }
drh69174c42010-11-12 15:35:59 +00002669 sqlite3StrAccumAppend(&txt, ")", 1);
2670 return sqlite3StrAccumFinish(&txt);
dan2ce22452010-11-08 19:01:16 +00002671}
2672
dan17c0bc02010-11-09 17:35:19 +00002673/*
2674** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
2675** command. If the query being compiled is an EXPLAIN QUERY PLAN, a single
2676** record is added to the output to describe the table scan strategy in
2677** pLevel.
2678*/
2679static void explainOneScan(
dan2ce22452010-11-08 19:01:16 +00002680 Parse *pParse, /* Parse context */
2681 SrcList *pTabList, /* Table list this loop refers to */
2682 WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
2683 int iLevel, /* Value for "level" column of output */
dan4a07e3d2010-11-09 14:48:59 +00002684 int iFrom, /* Value for "from" column of output */
2685 u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
dan2ce22452010-11-08 19:01:16 +00002686){
drh84e55a82013-11-13 17:58:23 +00002687#ifndef SQLITE_DEBUG
2688 if( pParse->explain==2 )
2689#endif
2690 {
dan2ce22452010-11-08 19:01:16 +00002691 struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
dan17c0bc02010-11-09 17:35:19 +00002692 Vdbe *v = pParse->pVdbe; /* VM being constructed */
2693 sqlite3 *db = pParse->db; /* Database handle */
2694 char *zMsg; /* Text to add to EQP output */
dan4a07e3d2010-11-09 14:48:59 +00002695 int iId = pParse->iSelectId; /* Select id (left-most output column) */
dan4bc39fa2010-11-13 16:42:27 +00002696 int isSearch; /* True for a SEARCH. False for SCAN. */
drhef866372013-05-22 20:49:02 +00002697 WhereLoop *pLoop; /* The controlling WhereLoop object */
2698 u32 flags; /* Flags that describe this loop */
dan2ce22452010-11-08 19:01:16 +00002699
drhef866372013-05-22 20:49:02 +00002700 pLoop = pLevel->pWLoop;
2701 flags = pLoop->wsFlags;
dan4a07e3d2010-11-09 14:48:59 +00002702 if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return;
dan2ce22452010-11-08 19:01:16 +00002703
drhef866372013-05-22 20:49:02 +00002704 isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
2705 || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
2706 || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
dan4bc39fa2010-11-13 16:42:27 +00002707
2708 zMsg = sqlite3MPrintf(db, "%s", isSearch?"SEARCH":"SCAN");
dan4a07e3d2010-11-09 14:48:59 +00002709 if( pItem->pSelect ){
dan4bc39fa2010-11-13 16:42:27 +00002710 zMsg = sqlite3MAppendf(db, zMsg, "%s SUBQUERY %d", zMsg,pItem->iSelectId);
dan4a07e3d2010-11-09 14:48:59 +00002711 }else{
dan4bc39fa2010-11-13 16:42:27 +00002712 zMsg = sqlite3MAppendf(db, zMsg, "%s TABLE %s", zMsg, pItem->zName);
dan4a07e3d2010-11-09 14:48:59 +00002713 }
2714
dan2ce22452010-11-08 19:01:16 +00002715 if( pItem->zAlias ){
2716 zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
2717 }
drhef866372013-05-22 20:49:02 +00002718 if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0
drh7963b0e2013-06-17 21:37:40 +00002719 && ALWAYS(pLoop->u.btree.pIndex!=0)
drhef866372013-05-22 20:49:02 +00002720 ){
2721 char *zWhere = explainIndexRange(db, pLoop, pItem->pTab);
drh986b3872013-06-28 21:12:20 +00002722 zMsg = sqlite3MAppendf(db, zMsg,
2723 ((flags & WHERE_AUTO_INDEX) ?
2724 "%s USING AUTOMATIC %sINDEX%.0s%s" :
2725 "%s USING %sINDEX %s%s"),
2726 zMsg, ((flags & WHERE_IDX_ONLY) ? "COVERING " : ""),
2727 pLoop->u.btree.pIndex->zName, zWhere);
dan2ce22452010-11-08 19:01:16 +00002728 sqlite3DbFree(db, zWhere);
drhef71c1f2013-06-04 12:58:02 +00002729 }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
dan4bc39fa2010-11-13 16:42:27 +00002730 zMsg = sqlite3MAppendf(db, zMsg, "%s USING INTEGER PRIMARY KEY", zMsg);
dan2ce22452010-11-08 19:01:16 +00002731
drh8e23daf2013-06-11 13:30:04 +00002732 if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
dan2ce22452010-11-08 19:01:16 +00002733 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid=?)", zMsg);
drh04098e62010-11-15 21:50:19 +00002734 }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
dan2ce22452010-11-08 19:01:16 +00002735 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>? AND rowid<?)", zMsg);
2736 }else if( flags&WHERE_BTM_LIMIT ){
2737 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>?)", zMsg);
drh7963b0e2013-06-17 21:37:40 +00002738 }else if( ALWAYS(flags&WHERE_TOP_LIMIT) ){
dan2ce22452010-11-08 19:01:16 +00002739 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid<?)", zMsg);
2740 }
2741 }
2742#ifndef SQLITE_OMIT_VIRTUALTABLE
2743 else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
dan2ce22452010-11-08 19:01:16 +00002744 zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
drhef866372013-05-22 20:49:02 +00002745 pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
dan2ce22452010-11-08 19:01:16 +00002746 }
2747#endif
drhb8a8e8a2013-06-10 19:12:39 +00002748 zMsg = sqlite3MAppendf(db, zMsg, "%s", zMsg);
dan4a07e3d2010-11-09 14:48:59 +00002749 sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg, P4_DYNAMIC);
dan2ce22452010-11-08 19:01:16 +00002750 }
2751}
2752#else
dan17c0bc02010-11-09 17:35:19 +00002753# define explainOneScan(u,v,w,x,y,z)
dan2ce22452010-11-08 19:01:16 +00002754#endif /* SQLITE_OMIT_EXPLAIN */
2755
2756
drh111a6a72008-12-21 03:51:16 +00002757/*
2758** Generate code for the start of the iLevel-th loop in the WHERE clause
2759** implementation described by pWInfo.
2760*/
2761static Bitmask codeOneLoopStart(
2762 WhereInfo *pWInfo, /* Complete information about the WHERE clause */
2763 int iLevel, /* Which level of pWInfo->a[] should be coded */
drh7a484802012-03-16 00:28:11 +00002764 Bitmask notReady /* Which tables are currently available */
drh111a6a72008-12-21 03:51:16 +00002765){
2766 int j, k; /* Loop counters */
2767 int iCur; /* The VDBE cursor for the table */
2768 int addrNxt; /* Where to jump to continue with the next IN case */
2769 int omitTable; /* True if we use the index only */
2770 int bRev; /* True if we need to scan in reverse order */
2771 WhereLevel *pLevel; /* The where level to be coded */
drh7ba39a92013-05-30 17:43:19 +00002772 WhereLoop *pLoop; /* The WhereLoop object being coded */
drh111a6a72008-12-21 03:51:16 +00002773 WhereClause *pWC; /* Decomposition of the entire WHERE clause */
2774 WhereTerm *pTerm; /* A WHERE clause term */
2775 Parse *pParse; /* Parsing context */
drh6b36e822013-07-30 15:10:32 +00002776 sqlite3 *db; /* Database connection */
drh111a6a72008-12-21 03:51:16 +00002777 Vdbe *v; /* The prepared stmt under constructions */
2778 struct SrcList_item *pTabItem; /* FROM clause term being coded */
drh23d04d52008-12-23 23:56:22 +00002779 int addrBrk; /* Jump here to break out of the loop */
2780 int addrCont; /* Jump here to continue with next cycle */
drh61495262009-04-22 15:32:59 +00002781 int iRowidReg = 0; /* Rowid is stored in this register, if not zero */
2782 int iReleaseReg = 0; /* Temp register to free before returning */
drh111a6a72008-12-21 03:51:16 +00002783
2784 pParse = pWInfo->pParse;
2785 v = pParse->pVdbe;
drh70d18342013-06-06 19:16:33 +00002786 pWC = &pWInfo->sWC;
drh6b36e822013-07-30 15:10:32 +00002787 db = pParse->db;
drh111a6a72008-12-21 03:51:16 +00002788 pLevel = &pWInfo->a[iLevel];
drh7ba39a92013-05-30 17:43:19 +00002789 pLoop = pLevel->pWLoop;
drh111a6a72008-12-21 03:51:16 +00002790 pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
2791 iCur = pTabItem->iCursor;
drh0259bc32013-09-09 19:37:46 +00002792 pLevel->notReady = notReady & ~getMask(&pWInfo->sMaskSet, iCur);
drh7ba39a92013-05-30 17:43:19 +00002793 bRev = (pWInfo->revMask>>iLevel)&1;
2794 omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
drh70d18342013-06-06 19:16:33 +00002795 && (pWInfo->wctrlFlags & WHERE_FORCE_TABLE)==0;
drh6bc69a22013-11-19 12:33:23 +00002796 VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName));
drh111a6a72008-12-21 03:51:16 +00002797
2798 /* Create labels for the "break" and "continue" instructions
2799 ** for the current loop. Jump to addrBrk to break out of a loop.
2800 ** Jump to cont to go immediately to the next iteration of the
2801 ** loop.
2802 **
2803 ** When there is an IN operator, we also have a "addrNxt" label that
2804 ** means to continue with the next IN value combination. When
2805 ** there are no IN operators in the constraints, the "addrNxt" label
2806 ** is the same as "addrBrk".
2807 */
2808 addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
2809 addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
2810
2811 /* If this is the right table of a LEFT OUTER JOIN, allocate and
2812 ** initialize a memory cell that records if this table matches any
2813 ** row of the left table of the join.
2814 */
2815 if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
2816 pLevel->iLeftJoin = ++pParse->nMem;
2817 sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
2818 VdbeComment((v, "init LEFT JOIN no-match flag"));
2819 }
2820
drh21172c42012-10-30 00:29:07 +00002821 /* Special case of a FROM clause subquery implemented as a co-routine */
2822 if( pTabItem->viaCoroutine ){
2823 int regYield = pTabItem->regReturn;
drhed71a832014-02-07 19:18:10 +00002824 sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
drh81cf13e2014-02-07 18:27:53 +00002825 pLevel->p2 = sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk);
drh688852a2014-02-17 22:40:43 +00002826 VdbeCoverage(v);
drh725de292014-02-08 13:12:19 +00002827 VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
drh21172c42012-10-30 00:29:07 +00002828 pLevel->op = OP_Goto;
2829 }else
2830
drh111a6a72008-12-21 03:51:16 +00002831#ifndef SQLITE_OMIT_VIRTUALTABLE
drh7ba39a92013-05-30 17:43:19 +00002832 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
2833 /* Case 1: The table is a virtual-table. Use the VFilter and VNext
drh111a6a72008-12-21 03:51:16 +00002834 ** to access the data.
2835 */
2836 int iReg; /* P3 Value for OP_VFilter */
drh281bbe22012-10-16 23:17:14 +00002837 int addrNotFound;
drh4efc9292013-06-06 23:02:03 +00002838 int nConstraint = pLoop->nLTerm;
drh111a6a72008-12-21 03:51:16 +00002839
drha62bb8d2009-11-23 21:23:45 +00002840 sqlite3ExprCachePush(pParse);
drh111a6a72008-12-21 03:51:16 +00002841 iReg = sqlite3GetTempRange(pParse, nConstraint+2);
drh281bbe22012-10-16 23:17:14 +00002842 addrNotFound = pLevel->addrBrk;
drh111a6a72008-12-21 03:51:16 +00002843 for(j=0; j<nConstraint; j++){
drhe2250172013-05-31 18:13:50 +00002844 int iTarget = iReg+j+2;
drh4efc9292013-06-06 23:02:03 +00002845 pTerm = pLoop->aLTerm[j];
drh95ed68d2013-06-12 17:55:50 +00002846 if( pTerm==0 ) continue;
drh7ba39a92013-05-30 17:43:19 +00002847 if( pTerm->eOperator & WO_IN ){
2848 codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
2849 addrNotFound = pLevel->addrNxt;
2850 }else{
2851 sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget);
2852 }
2853 }
2854 sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
drh7e47cb82013-05-31 17:55:27 +00002855 sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
drh7ba39a92013-05-30 17:43:19 +00002856 sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
2857 pLoop->u.vtab.idxStr,
2858 pLoop->u.vtab.needFree ? P4_MPRINTF : P4_STATIC);
drh688852a2014-02-17 22:40:43 +00002859 VdbeCoverage(v);
drh7ba39a92013-05-30 17:43:19 +00002860 pLoop->u.vtab.needFree = 0;
2861 for(j=0; j<nConstraint && j<16; j++){
2862 if( (pLoop->u.vtab.omitMask>>j)&1 ){
drh4efc9292013-06-06 23:02:03 +00002863 disableTerm(pLevel, pLoop->aLTerm[j]);
drh111a6a72008-12-21 03:51:16 +00002864 }
2865 }
2866 pLevel->op = OP_VNext;
2867 pLevel->p1 = iCur;
2868 pLevel->p2 = sqlite3VdbeCurrentAddr(v);
drh23d04d52008-12-23 23:56:22 +00002869 sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
drhd2490902014-04-13 19:28:15 +00002870 sqlite3ExprCachePop(pParse);
drh111a6a72008-12-21 03:51:16 +00002871 }else
2872#endif /* SQLITE_OMIT_VIRTUALTABLE */
2873
drh7ba39a92013-05-30 17:43:19 +00002874 if( (pLoop->wsFlags & WHERE_IPK)!=0
2875 && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
2876 ){
2877 /* Case 2: We can directly reference a single row using an
drh111a6a72008-12-21 03:51:16 +00002878 ** equality comparison against the ROWID field. Or
2879 ** we reference multiple rows using a "rowid IN (...)"
2880 ** construct.
2881 */
drh7ba39a92013-05-30 17:43:19 +00002882 assert( pLoop->u.btree.nEq==1 );
drh4efc9292013-06-06 23:02:03 +00002883 pTerm = pLoop->aLTerm[0];
drh111a6a72008-12-21 03:51:16 +00002884 assert( pTerm!=0 );
2885 assert( pTerm->pExpr!=0 );
drh111a6a72008-12-21 03:51:16 +00002886 assert( omitTable==0 );
drh39759742013-08-02 23:40:45 +00002887 testcase( pTerm->wtFlags & TERM_VIRTUAL );
drh0baa0352014-02-25 21:55:16 +00002888 iReleaseReg = ++pParse->nMem;
drh7ba39a92013-05-30 17:43:19 +00002889 iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
drh0baa0352014-02-25 21:55:16 +00002890 if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg);
drh111a6a72008-12-21 03:51:16 +00002891 addrNxt = pLevel->addrNxt;
drh688852a2014-02-17 22:40:43 +00002892 sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt); VdbeCoverage(v);
danielk19771d461462009-04-21 09:02:45 +00002893 sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
drh688852a2014-02-17 22:40:43 +00002894 VdbeCoverage(v);
drh459f63e2013-03-06 01:55:27 +00002895 sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
drhceea3322009-04-23 13:22:42 +00002896 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
drh111a6a72008-12-21 03:51:16 +00002897 VdbeComment((v, "pk"));
2898 pLevel->op = OP_Noop;
drh7ba39a92013-05-30 17:43:19 +00002899 }else if( (pLoop->wsFlags & WHERE_IPK)!=0
2900 && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
2901 ){
2902 /* Case 3: We have an inequality comparison against the ROWID field.
drh111a6a72008-12-21 03:51:16 +00002903 */
2904 int testOp = OP_Noop;
2905 int start;
2906 int memEndValue = 0;
2907 WhereTerm *pStart, *pEnd;
2908
2909 assert( omitTable==0 );
drh7ba39a92013-05-30 17:43:19 +00002910 j = 0;
2911 pStart = pEnd = 0;
drh4efc9292013-06-06 23:02:03 +00002912 if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
2913 if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
drh81186b42013-06-18 01:52:41 +00002914 assert( pStart!=0 || pEnd!=0 );
drh111a6a72008-12-21 03:51:16 +00002915 if( bRev ){
2916 pTerm = pStart;
2917 pStart = pEnd;
2918 pEnd = pTerm;
2919 }
2920 if( pStart ){
2921 Expr *pX; /* The expression that defines the start bound */
2922 int r1, rTemp; /* Registers for holding the start boundary */
2923
2924 /* The following constant maps TK_xx codes into corresponding
2925 ** seek opcodes. It depends on a particular ordering of TK_xx
2926 */
2927 const u8 aMoveOp[] = {
drh4a1d3652014-02-14 15:13:36 +00002928 /* TK_GT */ OP_SeekGT,
2929 /* TK_LE */ OP_SeekLE,
2930 /* TK_LT */ OP_SeekLT,
2931 /* TK_GE */ OP_SeekGE
drh111a6a72008-12-21 03:51:16 +00002932 };
2933 assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */
2934 assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */
2935 assert( TK_GE==TK_GT+3 ); /* ... is correcct. */
2936
drhb5246e52013-07-08 21:12:57 +00002937 assert( (pStart->wtFlags & TERM_VNULL)==0 );
drh39759742013-08-02 23:40:45 +00002938 testcase( pStart->wtFlags & TERM_VIRTUAL );
drh111a6a72008-12-21 03:51:16 +00002939 pX = pStart->pExpr;
2940 assert( pX!=0 );
drhb5246e52013-07-08 21:12:57 +00002941 testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
drh111a6a72008-12-21 03:51:16 +00002942 r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
2943 sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
drh7d176102014-02-18 03:07:12 +00002944 VdbeComment((v, "pk"));
2945 VdbeCoverageIf(v, pX->op==TK_GT);
2946 VdbeCoverageIf(v, pX->op==TK_LE);
2947 VdbeCoverageIf(v, pX->op==TK_LT);
2948 VdbeCoverageIf(v, pX->op==TK_GE);
drh111a6a72008-12-21 03:51:16 +00002949 sqlite3ExprCacheAffinityChange(pParse, r1, 1);
2950 sqlite3ReleaseTempReg(pParse, rTemp);
2951 disableTerm(pLevel, pStart);
2952 }else{
2953 sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
drh7d176102014-02-18 03:07:12 +00002954 VdbeCoverageIf(v, bRev==0);
2955 VdbeCoverageIf(v, bRev!=0);
drh111a6a72008-12-21 03:51:16 +00002956 }
2957 if( pEnd ){
2958 Expr *pX;
2959 pX = pEnd->pExpr;
2960 assert( pX!=0 );
drhb5246e52013-07-08 21:12:57 +00002961 assert( (pEnd->wtFlags & TERM_VNULL)==0 );
2962 testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
drh39759742013-08-02 23:40:45 +00002963 testcase( pEnd->wtFlags & TERM_VIRTUAL );
drh111a6a72008-12-21 03:51:16 +00002964 memEndValue = ++pParse->nMem;
2965 sqlite3ExprCode(pParse, pX->pRight, memEndValue);
2966 if( pX->op==TK_LT || pX->op==TK_GT ){
2967 testOp = bRev ? OP_Le : OP_Ge;
2968 }else{
2969 testOp = bRev ? OP_Lt : OP_Gt;
2970 }
2971 disableTerm(pLevel, pEnd);
2972 }
2973 start = sqlite3VdbeCurrentAddr(v);
2974 pLevel->op = bRev ? OP_Prev : OP_Next;
2975 pLevel->p1 = iCur;
2976 pLevel->p2 = start;
drh81186b42013-06-18 01:52:41 +00002977 assert( pLevel->p5==0 );
danielk19771d461462009-04-21 09:02:45 +00002978 if( testOp!=OP_Noop ){
drh0baa0352014-02-25 21:55:16 +00002979 iRowidReg = ++pParse->nMem;
danielk19771d461462009-04-21 09:02:45 +00002980 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
drhceea3322009-04-23 13:22:42 +00002981 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
danielk19771d461462009-04-21 09:02:45 +00002982 sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
drh7d176102014-02-18 03:07:12 +00002983 VdbeCoverageIf(v, testOp==OP_Le);
2984 VdbeCoverageIf(v, testOp==OP_Lt);
2985 VdbeCoverageIf(v, testOp==OP_Ge);
2986 VdbeCoverageIf(v, testOp==OP_Gt);
danielk19771d461462009-04-21 09:02:45 +00002987 sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
drh111a6a72008-12-21 03:51:16 +00002988 }
drh1b0f0262013-05-30 22:27:09 +00002989 }else if( pLoop->wsFlags & WHERE_INDEXED ){
drh7ba39a92013-05-30 17:43:19 +00002990 /* Case 4: A scan using an index.
drh111a6a72008-12-21 03:51:16 +00002991 **
2992 ** The WHERE clause may contain zero or more equality
2993 ** terms ("==" or "IN" operators) that refer to the N
2994 ** left-most columns of the index. It may also contain
2995 ** inequality constraints (>, <, >= or <=) on the indexed
2996 ** column that immediately follows the N equalities. Only
2997 ** the right-most column can be an inequality - the rest must
2998 ** use the "==" and "IN" operators. For example, if the
2999 ** index is on (x,y,z), then the following clauses are all
3000 ** optimized:
3001 **
3002 ** x=5
3003 ** x=5 AND y=10
3004 ** x=5 AND y<10
3005 ** x=5 AND y>5 AND y<10
3006 ** x=5 AND y=5 AND z<=10
3007 **
3008 ** The z<10 term of the following cannot be used, only
3009 ** the x=5 term:
3010 **
3011 ** x=5 AND z<10
3012 **
3013 ** N may be zero if there are inequality constraints.
3014 ** If there are no inequality constraints, then N is at
3015 ** least one.
3016 **
3017 ** This case is also used when there are no WHERE clause
3018 ** constraints but an index is selected anyway, in order
3019 ** to force the output order to conform to an ORDER BY.
3020 */
drh3bb9b932010-08-06 02:10:00 +00003021 static const u8 aStartOp[] = {
drh111a6a72008-12-21 03:51:16 +00003022 0,
3023 0,
3024 OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */
3025 OP_Last, /* 3: (!start_constraints && startEq && bRev) */
drh4a1d3652014-02-14 15:13:36 +00003026 OP_SeekGT, /* 4: (start_constraints && !startEq && !bRev) */
3027 OP_SeekLT, /* 5: (start_constraints && !startEq && bRev) */
3028 OP_SeekGE, /* 6: (start_constraints && startEq && !bRev) */
3029 OP_SeekLE /* 7: (start_constraints && startEq && bRev) */
drh111a6a72008-12-21 03:51:16 +00003030 };
drh3bb9b932010-08-06 02:10:00 +00003031 static const u8 aEndOp[] = {
drh4a1d3652014-02-14 15:13:36 +00003032 OP_IdxGE, /* 0: (end_constraints && !bRev && !endEq) */
3033 OP_IdxGT, /* 1: (end_constraints && !bRev && endEq) */
3034 OP_IdxLE, /* 2: (end_constraints && bRev && !endEq) */
3035 OP_IdxLT, /* 3: (end_constraints && bRev && endEq) */
drh111a6a72008-12-21 03:51:16 +00003036 };
drhcd8629e2013-11-13 12:27:25 +00003037 u16 nEq = pLoop->u.btree.nEq; /* Number of == or IN terms */
drh111a6a72008-12-21 03:51:16 +00003038 int regBase; /* Base register holding constraint values */
drh111a6a72008-12-21 03:51:16 +00003039 WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */
3040 WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */
3041 int startEq; /* True if range start uses ==, >= or <= */
3042 int endEq; /* True if range end uses ==, >= or <= */
3043 int start_constraints; /* Start of range is constrained */
3044 int nConstraint; /* Number of constraint terms */
drh3bb9b932010-08-06 02:10:00 +00003045 Index *pIdx; /* The index we will be using */
3046 int iIdxCur; /* The VDBE cursor for the index */
3047 int nExtraReg = 0; /* Number of extra registers needed */
3048 int op; /* Instruction opcode */
dan6ac43392010-06-09 15:47:11 +00003049 char *zStartAff; /* Affinity for start of range constraint */
drh33cad2f2013-11-15 12:41:01 +00003050 char cEndAff = 0; /* Affinity for end of range constraint */
drhcfc6ca42014-02-14 23:49:13 +00003051 u8 bSeekPastNull = 0; /* True to seek past initial nulls */
3052 u8 bStopAtNull = 0; /* Add condition to terminate at NULLs */
drh111a6a72008-12-21 03:51:16 +00003053
drh7ba39a92013-05-30 17:43:19 +00003054 pIdx = pLoop->u.btree.pIndex;
drh111a6a72008-12-21 03:51:16 +00003055 iIdxCur = pLevel->iIdxCur;
drh052e6a82013-11-14 19:34:10 +00003056 assert( nEq>=pLoop->u.btree.nSkip );
drh111a6a72008-12-21 03:51:16 +00003057
drh111a6a72008-12-21 03:51:16 +00003058 /* If this loop satisfies a sort order (pOrderBy) request that
3059 ** was passed to this function to implement a "SELECT min(x) ..."
3060 ** query, then the caller will only allow the loop to run for
3061 ** a single iteration. This means that the first row returned
3062 ** should not have a NULL value stored in 'x'. If column 'x' is
3063 ** the first one after the nEq equality constraints in the index,
3064 ** this requires some special handling.
3065 */
drhddba0c22014-03-18 20:33:42 +00003066 assert( pWInfo->pOrderBy==0
3067 || pWInfo->pOrderBy->nExpr==1
3068 || (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0 );
drh70d18342013-06-06 19:16:33 +00003069 if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
drhddba0c22014-03-18 20:33:42 +00003070 && pWInfo->nOBSat>0
drhbbbdc832013-10-22 18:01:40 +00003071 && (pIdx->nKeyCol>nEq)
drh111a6a72008-12-21 03:51:16 +00003072 ){
drh052e6a82013-11-14 19:34:10 +00003073 assert( pLoop->u.btree.nSkip==0 );
drhcfc6ca42014-02-14 23:49:13 +00003074 bSeekPastNull = 1;
drh6df2acd2008-12-28 16:55:25 +00003075 nExtraReg = 1;
drh111a6a72008-12-21 03:51:16 +00003076 }
3077
3078 /* Find any inequality constraint terms for the start and end
3079 ** of the range.
3080 */
drh7ba39a92013-05-30 17:43:19 +00003081 j = nEq;
3082 if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
drh4efc9292013-06-06 23:02:03 +00003083 pRangeStart = pLoop->aLTerm[j++];
drh6df2acd2008-12-28 16:55:25 +00003084 nExtraReg = 1;
drh111a6a72008-12-21 03:51:16 +00003085 }
drh7ba39a92013-05-30 17:43:19 +00003086 if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
drh4efc9292013-06-06 23:02:03 +00003087 pRangeEnd = pLoop->aLTerm[j++];
drh6df2acd2008-12-28 16:55:25 +00003088 nExtraReg = 1;
drhcfc6ca42014-02-14 23:49:13 +00003089 if( pRangeStart==0
drhcfc6ca42014-02-14 23:49:13 +00003090 && (j = pIdx->aiColumn[nEq])>=0
3091 && pIdx->pTable->aCol[j].notNull==0
3092 ){
3093 bSeekPastNull = 1;
3094 }
drh111a6a72008-12-21 03:51:16 +00003095 }
dan0df163a2014-03-06 12:36:26 +00003096 assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 );
drh111a6a72008-12-21 03:51:16 +00003097
drh6df2acd2008-12-28 16:55:25 +00003098 /* Generate code to evaluate all constraint terms using == or IN
3099 ** and store the values of those terms in an array of registers
3100 ** starting at regBase.
3101 */
drh613ba1e2013-06-15 15:11:45 +00003102 regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
drh33cad2f2013-11-15 12:41:01 +00003103 assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq );
3104 if( zStartAff ) cEndAff = zStartAff[nEq];
drh6df2acd2008-12-28 16:55:25 +00003105 addrNxt = pLevel->addrNxt;
3106
drh111a6a72008-12-21 03:51:16 +00003107 /* If we are doing a reverse order scan on an ascending index, or
3108 ** a forward order scan on a descending index, interchange the
3109 ** start and end terms (pRangeStart and pRangeEnd).
3110 */
drhbbbdc832013-10-22 18:01:40 +00003111 if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
3112 || (bRev && pIdx->nKeyCol==nEq)
dan0c733f62011-11-16 15:27:09 +00003113 ){
drh111a6a72008-12-21 03:51:16 +00003114 SWAP(WhereTerm *, pRangeEnd, pRangeStart);
drhcfc6ca42014-02-14 23:49:13 +00003115 SWAP(u8, bSeekPastNull, bStopAtNull);
drh111a6a72008-12-21 03:51:16 +00003116 }
3117
drh7963b0e2013-06-17 21:37:40 +00003118 testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
3119 testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
3120 testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
3121 testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
drh111a6a72008-12-21 03:51:16 +00003122 startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
3123 endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
3124 start_constraints = pRangeStart || nEq>0;
3125
3126 /* Seek the index cursor to the start of the range. */
3127 nConstraint = nEq;
3128 if( pRangeStart ){
dan69f8bb92009-08-13 19:21:16 +00003129 Expr *pRight = pRangeStart->pExpr->pRight;
3130 sqlite3ExprCode(pParse, pRight, regBase+nEq);
drh7d176102014-02-18 03:07:12 +00003131 if( (pRangeStart->wtFlags & TERM_VNULL)==0
3132 && sqlite3ExprCanBeNull(pRight)
3133 ){
3134 sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
3135 VdbeCoverage(v);
drh534230c2011-01-22 00:10:45 +00003136 }
dan6ac43392010-06-09 15:47:11 +00003137 if( zStartAff ){
3138 if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
drh039fc322009-11-17 18:31:47 +00003139 /* Since the comparison is to be performed with no conversions
3140 ** applied to the operands, set the affinity to apply to pRight to
3141 ** SQLITE_AFF_NONE. */
dan6ac43392010-06-09 15:47:11 +00003142 zStartAff[nEq] = SQLITE_AFF_NONE;
drh039fc322009-11-17 18:31:47 +00003143 }
dan6ac43392010-06-09 15:47:11 +00003144 if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
3145 zStartAff[nEq] = SQLITE_AFF_NONE;
drh039fc322009-11-17 18:31:47 +00003146 }
3147 }
drh111a6a72008-12-21 03:51:16 +00003148 nConstraint++;
drh39759742013-08-02 23:40:45 +00003149 testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
drhcfc6ca42014-02-14 23:49:13 +00003150 }else if( bSeekPastNull ){
drh111a6a72008-12-21 03:51:16 +00003151 sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
3152 nConstraint++;
3153 startEq = 0;
3154 start_constraints = 1;
3155 }
drhcfc6ca42014-02-14 23:49:13 +00003156 codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff);
drh111a6a72008-12-21 03:51:16 +00003157 op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
3158 assert( op!=0 );
drh8cff69d2009-11-12 19:59:44 +00003159 sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
drh688852a2014-02-17 22:40:43 +00003160 VdbeCoverage(v);
drh7d176102014-02-18 03:07:12 +00003161 VdbeCoverageIf(v, op==OP_Rewind); testcase( op==OP_Rewind );
3162 VdbeCoverageIf(v, op==OP_Last); testcase( op==OP_Last );
3163 VdbeCoverageIf(v, op==OP_SeekGT); testcase( op==OP_SeekGT );
3164 VdbeCoverageIf(v, op==OP_SeekGE); testcase( op==OP_SeekGE );
3165 VdbeCoverageIf(v, op==OP_SeekLE); testcase( op==OP_SeekLE );
3166 VdbeCoverageIf(v, op==OP_SeekLT); testcase( op==OP_SeekLT );
drh111a6a72008-12-21 03:51:16 +00003167
3168 /* Load the value for the inequality constraint at the end of the
3169 ** range (if any).
3170 */
3171 nConstraint = nEq;
3172 if( pRangeEnd ){
dan69f8bb92009-08-13 19:21:16 +00003173 Expr *pRight = pRangeEnd->pExpr->pRight;
drhf49f3522009-12-30 14:12:38 +00003174 sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
dan69f8bb92009-08-13 19:21:16 +00003175 sqlite3ExprCode(pParse, pRight, regBase+nEq);
drh7d176102014-02-18 03:07:12 +00003176 if( (pRangeEnd->wtFlags & TERM_VNULL)==0
3177 && sqlite3ExprCanBeNull(pRight)
3178 ){
3179 sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
3180 VdbeCoverage(v);
drh534230c2011-01-22 00:10:45 +00003181 }
drh33cad2f2013-11-15 12:41:01 +00003182 if( sqlite3CompareAffinity(pRight, cEndAff)!=SQLITE_AFF_NONE
3183 && !sqlite3ExprNeedsNoAffinityChange(pRight, cEndAff)
3184 ){
3185 codeApplyAffinity(pParse, regBase+nEq, 1, &cEndAff);
3186 }
drh111a6a72008-12-21 03:51:16 +00003187 nConstraint++;
drh39759742013-08-02 23:40:45 +00003188 testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
drhcfc6ca42014-02-14 23:49:13 +00003189 }else if( bStopAtNull ){
3190 sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
3191 endEq = 0;
3192 nConstraint++;
drh111a6a72008-12-21 03:51:16 +00003193 }
drh6b36e822013-07-30 15:10:32 +00003194 sqlite3DbFree(db, zStartAff);
drh111a6a72008-12-21 03:51:16 +00003195
3196 /* Top of the loop body */
3197 pLevel->p2 = sqlite3VdbeCurrentAddr(v);
3198
3199 /* Check if the index cursor is past the end of the range. */
drhcfc6ca42014-02-14 23:49:13 +00003200 if( nConstraint ){
drh4a1d3652014-02-14 15:13:36 +00003201 op = aEndOp[bRev*2 + endEq];
drh8cff69d2009-11-12 19:59:44 +00003202 sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
drh7d176102014-02-18 03:07:12 +00003203 testcase( op==OP_IdxGT ); VdbeCoverageIf(v, op==OP_IdxGT );
3204 testcase( op==OP_IdxGE ); VdbeCoverageIf(v, op==OP_IdxGE );
3205 testcase( op==OP_IdxLT ); VdbeCoverageIf(v, op==OP_IdxLT );
3206 testcase( op==OP_IdxLE ); VdbeCoverageIf(v, op==OP_IdxLE );
drh6df2acd2008-12-28 16:55:25 +00003207 }
drh111a6a72008-12-21 03:51:16 +00003208
drh111a6a72008-12-21 03:51:16 +00003209 /* Seek the table cursor, if required */
drh23d04d52008-12-23 23:56:22 +00003210 disableTerm(pLevel, pRangeStart);
3211 disableTerm(pLevel, pRangeEnd);
drh85c1c552013-10-24 00:18:18 +00003212 if( omitTable ){
3213 /* pIdx is a covering index. No need to access the main table. */
3214 }else if( HasRowid(pIdx->pTable) ){
drh0baa0352014-02-25 21:55:16 +00003215 iRowidReg = ++pParse->nMem;
danielk19771d461462009-04-21 09:02:45 +00003216 sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
drhceea3322009-04-23 13:22:42 +00003217 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
danielk19771d461462009-04-21 09:02:45 +00003218 sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg); /* Deferred seek */
drh85c1c552013-10-24 00:18:18 +00003219 }else{
3220 Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
3221 iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol);
3222 for(j=0; j<pPk->nKeyCol; j++){
3223 k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
3224 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j);
3225 }
drh261c02d2013-10-25 14:46:15 +00003226 sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont,
drh688852a2014-02-17 22:40:43 +00003227 iRowidReg, pPk->nKeyCol); VdbeCoverage(v);
drh111a6a72008-12-21 03:51:16 +00003228 }
drh111a6a72008-12-21 03:51:16 +00003229
3230 /* Record the instruction used to terminate the loop. Disable
3231 ** WHERE clause terms made redundant by the index range scan.
3232 */
drh7699d1c2013-06-04 12:42:29 +00003233 if( pLoop->wsFlags & WHERE_ONEROW ){
drh95e037b2011-03-09 21:02:31 +00003234 pLevel->op = OP_Noop;
3235 }else if( bRev ){
3236 pLevel->op = OP_Prev;
3237 }else{
3238 pLevel->op = OP_Next;
3239 }
drh111a6a72008-12-21 03:51:16 +00003240 pLevel->p1 = iIdxCur;
drh0c8a9342014-03-20 12:17:35 +00003241 pLevel->p3 = (pLoop->wsFlags&WHERE_UNQ_WANTED)!=0 ? 1:0;
drh53cfbe92013-06-13 17:28:22 +00003242 if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
drh3f4d1d12012-09-15 18:45:54 +00003243 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
3244 }else{
3245 assert( pLevel->p5==0 );
3246 }
drhdd5f5a62008-12-23 13:35:23 +00003247 }else
3248
drh23d04d52008-12-23 23:56:22 +00003249#ifndef SQLITE_OMIT_OR_OPTIMIZATION
drh7ba39a92013-05-30 17:43:19 +00003250 if( pLoop->wsFlags & WHERE_MULTI_OR ){
3251 /* Case 5: Two or more separately indexed terms connected by OR
drh111a6a72008-12-21 03:51:16 +00003252 **
3253 ** Example:
3254 **
3255 ** CREATE TABLE t1(a,b,c,d);
3256 ** CREATE INDEX i1 ON t1(a);
3257 ** CREATE INDEX i2 ON t1(b);
3258 ** CREATE INDEX i3 ON t1(c);
3259 **
3260 ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
3261 **
3262 ** In the example, there are three indexed terms connected by OR.
danielk19771d461462009-04-21 09:02:45 +00003263 ** The top of the loop looks like this:
drh111a6a72008-12-21 03:51:16 +00003264 **
drh1b26c7c2009-04-22 02:15:47 +00003265 ** Null 1 # Zero the rowset in reg 1
drh111a6a72008-12-21 03:51:16 +00003266 **
danielk19771d461462009-04-21 09:02:45 +00003267 ** Then, for each indexed term, the following. The arguments to
drh1b26c7c2009-04-22 02:15:47 +00003268 ** RowSetTest are such that the rowid of the current row is inserted
3269 ** into the RowSet. If it is already present, control skips the
danielk19771d461462009-04-21 09:02:45 +00003270 ** Gosub opcode and jumps straight to the code generated by WhereEnd().
drh111a6a72008-12-21 03:51:16 +00003271 **
danielk19771d461462009-04-21 09:02:45 +00003272 ** sqlite3WhereBegin(<term>)
drh1b26c7c2009-04-22 02:15:47 +00003273 ** RowSetTest # Insert rowid into rowset
danielk19771d461462009-04-21 09:02:45 +00003274 ** Gosub 2 A
3275 ** sqlite3WhereEnd()
3276 **
3277 ** Following the above, code to terminate the loop. Label A, the target
3278 ** of the Gosub above, jumps to the instruction right after the Goto.
3279 **
drh1b26c7c2009-04-22 02:15:47 +00003280 ** Null 1 # Zero the rowset in reg 1
danielk19771d461462009-04-21 09:02:45 +00003281 ** Goto B # The loop is finished.
3282 **
3283 ** A: <loop body> # Return data, whatever.
3284 **
3285 ** Return 2 # Jump back to the Gosub
3286 **
3287 ** B: <after the loop>
3288 **
drh111a6a72008-12-21 03:51:16 +00003289 */
drh111a6a72008-12-21 03:51:16 +00003290 WhereClause *pOrWc; /* The OR-clause broken out into subterms */
drhc01a3c12009-12-16 22:10:49 +00003291 SrcList *pOrTab; /* Shortened table list or OR-clause generation */
dan0efb72c2012-08-24 18:44:56 +00003292 Index *pCov = 0; /* Potential covering index (or NULL) */
3293 int iCovCur = pParse->nTab++; /* Cursor used for index scans (if any) */
danielk19771d461462009-04-21 09:02:45 +00003294
3295 int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */
shane85095702009-06-15 16:27:08 +00003296 int regRowset = 0; /* Register for RowSet object */
3297 int regRowid = 0; /* Register holding rowid */
danielk19771d461462009-04-21 09:02:45 +00003298 int iLoopBody = sqlite3VdbeMakeLabel(v); /* Start of loop body */
3299 int iRetInit; /* Address of regReturn init */
drhc01a3c12009-12-16 22:10:49 +00003300 int untestedTerms = 0; /* Some terms not completely tested */
drh8871ef52011-10-07 13:33:10 +00003301 int ii; /* Loop counter */
3302 Expr *pAndExpr = 0; /* An ".. AND (...)" expression */
drh111a6a72008-12-21 03:51:16 +00003303
drh4efc9292013-06-06 23:02:03 +00003304 pTerm = pLoop->aLTerm[0];
drh111a6a72008-12-21 03:51:16 +00003305 assert( pTerm!=0 );
drh7a5bcc02013-01-16 17:08:58 +00003306 assert( pTerm->eOperator & WO_OR );
drh111a6a72008-12-21 03:51:16 +00003307 assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
3308 pOrWc = &pTerm->u.pOrInfo->wc;
drhc01a3c12009-12-16 22:10:49 +00003309 pLevel->op = OP_Return;
3310 pLevel->p1 = regReturn;
drh23d04d52008-12-23 23:56:22 +00003311
danbfca6a42012-08-24 10:52:35 +00003312 /* Set up a new SrcList in pOrTab containing the table being scanned
drhc01a3c12009-12-16 22:10:49 +00003313 ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
3314 ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
3315 */
3316 if( pWInfo->nLevel>1 ){
3317 int nNotReady; /* The number of notReady tables */
3318 struct SrcList_item *origSrc; /* Original list of tables */
3319 nNotReady = pWInfo->nLevel - iLevel - 1;
drh6b36e822013-07-30 15:10:32 +00003320 pOrTab = sqlite3StackAllocRaw(db,
drhc01a3c12009-12-16 22:10:49 +00003321 sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
3322 if( pOrTab==0 ) return notReady;
drhad01d892013-06-19 13:59:49 +00003323 pOrTab->nAlloc = (u8)(nNotReady + 1);
shaneh46aae3c2009-12-31 19:06:23 +00003324 pOrTab->nSrc = pOrTab->nAlloc;
drhc01a3c12009-12-16 22:10:49 +00003325 memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
3326 origSrc = pWInfo->pTabList->a;
3327 for(k=1; k<=nNotReady; k++){
3328 memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
3329 }
3330 }else{
3331 pOrTab = pWInfo->pTabList;
3332 }
danielk19771d461462009-04-21 09:02:45 +00003333
drh1b26c7c2009-04-22 02:15:47 +00003334 /* Initialize the rowset register to contain NULL. An SQL NULL is
3335 ** equivalent to an empty rowset.
danielk19771d461462009-04-21 09:02:45 +00003336 **
3337 ** Also initialize regReturn to contain the address of the instruction
3338 ** immediately following the OP_Return at the bottom of the loop. This
3339 ** is required in a few obscure LEFT JOIN cases where control jumps
3340 ** over the top of the loop into the body of it. In this case the
3341 ** correct response for the end-of-loop code (the OP_Return) is to
3342 ** fall through to the next instruction, just as an OP_Next does if
3343 ** called on an uninitialized cursor.
3344 */
drh70d18342013-06-06 19:16:33 +00003345 if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
drh336a5302009-04-24 15:46:21 +00003346 regRowset = ++pParse->nMem;
3347 regRowid = ++pParse->nMem;
3348 sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
3349 }
danielk19771d461462009-04-21 09:02:45 +00003350 iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
3351
drh8871ef52011-10-07 13:33:10 +00003352 /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y
3353 ** Then for every term xN, evaluate as the subexpression: xN AND z
3354 ** That way, terms in y that are factored into the disjunction will
3355 ** be picked up by the recursive calls to sqlite3WhereBegin() below.
drh331b67c2012-03-09 22:02:08 +00003356 **
3357 ** Actually, each subexpression is converted to "xN AND w" where w is
3358 ** the "interesting" terms of z - terms that did not originate in the
3359 ** ON or USING clause of a LEFT JOIN, and terms that are usable as
3360 ** indices.
drhb3129fa2013-05-09 14:20:11 +00003361 **
3362 ** This optimization also only applies if the (x1 OR x2 OR ...) term
3363 ** is not contained in the ON clause of a LEFT JOIN.
3364 ** See ticket http://www.sqlite.org/src/info/f2369304e4
drh8871ef52011-10-07 13:33:10 +00003365 */
3366 if( pWC->nTerm>1 ){
drh7a484802012-03-16 00:28:11 +00003367 int iTerm;
3368 for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
3369 Expr *pExpr = pWC->a[iTerm].pExpr;
drhaa32e3c2013-07-16 21:31:23 +00003370 if( &pWC->a[iTerm] == pTerm ) continue;
drh331b67c2012-03-09 22:02:08 +00003371 if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
drh7c328062014-02-11 01:50:29 +00003372 testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO );
3373 testcase( pWC->a[iTerm].wtFlags & TERM_VIRTUAL );
3374 if( pWC->a[iTerm].wtFlags & (TERM_ORINFO|TERM_VIRTUAL) ) continue;
drh7a484802012-03-16 00:28:11 +00003375 if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
drh6b36e822013-07-30 15:10:32 +00003376 pExpr = sqlite3ExprDup(db, pExpr, 0);
3377 pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr);
drh331b67c2012-03-09 22:02:08 +00003378 }
3379 if( pAndExpr ){
3380 pAndExpr = sqlite3PExpr(pParse, TK_AND, 0, pAndExpr, 0);
3381 }
drh8871ef52011-10-07 13:33:10 +00003382 }
3383
danielk19771d461462009-04-21 09:02:45 +00003384 for(ii=0; ii<pOrWc->nTerm; ii++){
3385 WhereTerm *pOrTerm = &pOrWc->a[ii];
drh7a5bcc02013-01-16 17:08:58 +00003386 if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
danielk19771d461462009-04-21 09:02:45 +00003387 WhereInfo *pSubWInfo; /* Info for single OR-term scan */
drh8871ef52011-10-07 13:33:10 +00003388 Expr *pOrExpr = pOrTerm->pExpr;
drhb3129fa2013-05-09 14:20:11 +00003389 if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){
drh8871ef52011-10-07 13:33:10 +00003390 pAndExpr->pLeft = pOrExpr;
3391 pOrExpr = pAndExpr;
3392 }
danielk19771d461462009-04-21 09:02:45 +00003393 /* Loop through table entries that match term pOrTerm. */
drh8871ef52011-10-07 13:33:10 +00003394 pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
drh9ef61f42011-10-07 14:40:59 +00003395 WHERE_OMIT_OPEN_CLOSE | WHERE_AND_ONLY |
dan0efb72c2012-08-24 18:44:56 +00003396 WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY, iCovCur);
drh6b36e822013-07-30 15:10:32 +00003397 assert( pSubWInfo || pParse->nErr || db->mallocFailed );
danielk19771d461462009-04-21 09:02:45 +00003398 if( pSubWInfo ){
drh7ba39a92013-05-30 17:43:19 +00003399 WhereLoop *pSubLoop;
dan17c0bc02010-11-09 17:35:19 +00003400 explainOneScan(
dan4a07e3d2010-11-09 14:48:59 +00003401 pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
dan2ce22452010-11-08 19:01:16 +00003402 );
drh70d18342013-06-06 19:16:33 +00003403 if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
drh336a5302009-04-24 15:46:21 +00003404 int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
3405 int r;
3406 r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur,
drha748fdc2012-03-28 01:34:47 +00003407 regRowid, 0);
drh8cff69d2009-11-12 19:59:44 +00003408 sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset,
3409 sqlite3VdbeCurrentAddr(v)+2, r, iSet);
drh688852a2014-02-17 22:40:43 +00003410 VdbeCoverage(v);
drh336a5302009-04-24 15:46:21 +00003411 }
danielk19771d461462009-04-21 09:02:45 +00003412 sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
3413
drhc01a3c12009-12-16 22:10:49 +00003414 /* The pSubWInfo->untestedTerms flag means that this OR term
3415 ** contained one or more AND term from a notReady table. The
3416 ** terms from the notReady table could not be tested and will
3417 ** need to be tested later.
3418 */
3419 if( pSubWInfo->untestedTerms ) untestedTerms = 1;
3420
danbfca6a42012-08-24 10:52:35 +00003421 /* If all of the OR-connected terms are optimized using the same
3422 ** index, and the index is opened using the same cursor number
3423 ** by each call to sqlite3WhereBegin() made by this loop, it may
3424 ** be possible to use that index as a covering index.
3425 **
3426 ** If the call to sqlite3WhereBegin() above resulted in a scan that
3427 ** uses an index, and this is either the first OR-connected term
3428 ** processed or the index is the same as that used by all previous
dan0efb72c2012-08-24 18:44:56 +00003429 ** terms, set pCov to the candidate covering index. Otherwise, set
3430 ** pCov to NULL to indicate that no candidate covering index will
3431 ** be available.
danbfca6a42012-08-24 10:52:35 +00003432 */
drh7ba39a92013-05-30 17:43:19 +00003433 pSubLoop = pSubWInfo->a[0].pWLoop;
drh986b3872013-06-28 21:12:20 +00003434 assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
drh7ba39a92013-05-30 17:43:19 +00003435 if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
drh7ba39a92013-05-30 17:43:19 +00003436 && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
danbfca6a42012-08-24 10:52:35 +00003437 ){
drh7ba39a92013-05-30 17:43:19 +00003438 assert( pSubWInfo->a[0].iIdxCur==iCovCur );
drh907717f2013-06-04 18:03:22 +00003439 pCov = pSubLoop->u.btree.pIndex;
danbfca6a42012-08-24 10:52:35 +00003440 }else{
3441 pCov = 0;
3442 }
3443
danielk19771d461462009-04-21 09:02:45 +00003444 /* Finish the loop through table entries that match term pOrTerm. */
3445 sqlite3WhereEnd(pSubWInfo);
3446 }
drhdd5f5a62008-12-23 13:35:23 +00003447 }
3448 }
drhd40e2082012-08-24 23:24:15 +00003449 pLevel->u.pCovidx = pCov;
drh90abfd02012-10-09 21:07:23 +00003450 if( pCov ) pLevel->iIdxCur = iCovCur;
drh331b67c2012-03-09 22:02:08 +00003451 if( pAndExpr ){
3452 pAndExpr->pLeft = 0;
drh6b36e822013-07-30 15:10:32 +00003453 sqlite3ExprDelete(db, pAndExpr);
drh331b67c2012-03-09 22:02:08 +00003454 }
danielk19771d461462009-04-21 09:02:45 +00003455 sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
danielk19771d461462009-04-21 09:02:45 +00003456 sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
3457 sqlite3VdbeResolveLabel(v, iLoopBody);
3458
drh6b36e822013-07-30 15:10:32 +00003459 if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab);
drhc01a3c12009-12-16 22:10:49 +00003460 if( !untestedTerms ) disableTerm(pLevel, pTerm);
drhdd5f5a62008-12-23 13:35:23 +00003461 }else
drh23d04d52008-12-23 23:56:22 +00003462#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
drhdd5f5a62008-12-23 13:35:23 +00003463
3464 {
drh7ba39a92013-05-30 17:43:19 +00003465 /* Case 6: There is no usable index. We must do a complete
drh111a6a72008-12-21 03:51:16 +00003466 ** scan of the entire table.
3467 */
drh699b3d42009-02-23 16:52:07 +00003468 static const u8 aStep[] = { OP_Next, OP_Prev };
3469 static const u8 aStart[] = { OP_Rewind, OP_Last };
3470 assert( bRev==0 || bRev==1 );
drhe73f0592014-01-21 22:25:45 +00003471 if( pTabItem->isRecursive ){
drh340309f2014-01-22 00:23:49 +00003472 /* Tables marked isRecursive have only a single row that is stored in
dan41028152014-01-22 10:22:25 +00003473 ** a pseudo-cursor. No need to Rewind or Next such cursors. */
drhe73f0592014-01-21 22:25:45 +00003474 pLevel->op = OP_Noop;
3475 }else{
3476 pLevel->op = aStep[bRev];
3477 pLevel->p1 = iCur;
3478 pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
drh7d176102014-02-18 03:07:12 +00003479 VdbeCoverageIf(v, bRev==0);
3480 VdbeCoverageIf(v, bRev!=0);
drhe73f0592014-01-21 22:25:45 +00003481 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
3482 }
drh111a6a72008-12-21 03:51:16 +00003483 }
drh111a6a72008-12-21 03:51:16 +00003484
3485 /* Insert code to test every subexpression that can be completely
3486 ** computed using the current set of tables.
3487 */
drh111a6a72008-12-21 03:51:16 +00003488 for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
3489 Expr *pE;
drh39759742013-08-02 23:40:45 +00003490 testcase( pTerm->wtFlags & TERM_VIRTUAL );
drh111a6a72008-12-21 03:51:16 +00003491 testcase( pTerm->wtFlags & TERM_CODED );
3492 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
drh0259bc32013-09-09 19:37:46 +00003493 if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
drhc01a3c12009-12-16 22:10:49 +00003494 testcase( pWInfo->untestedTerms==0
3495 && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
3496 pWInfo->untestedTerms = 1;
3497 continue;
3498 }
drh111a6a72008-12-21 03:51:16 +00003499 pE = pTerm->pExpr;
3500 assert( pE!=0 );
3501 if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
3502 continue;
3503 }
drh111a6a72008-12-21 03:51:16 +00003504 sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
drh111a6a72008-12-21 03:51:16 +00003505 pTerm->wtFlags |= TERM_CODED;
3506 }
3507
drh0c41d222013-04-22 02:39:10 +00003508 /* Insert code to test for implied constraints based on transitivity
3509 ** of the "==" operator.
3510 **
3511 ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
3512 ** and we are coding the t1 loop and the t2 loop has not yet coded,
3513 ** then we cannot use the "t1.a=t2.b" constraint, but we can code
3514 ** the implied "t1.a=123" constraint.
3515 */
3516 for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
drh6b36e822013-07-30 15:10:32 +00003517 Expr *pE, *pEAlt;
drh0c41d222013-04-22 02:39:10 +00003518 WhereTerm *pAlt;
drh0c41d222013-04-22 02:39:10 +00003519 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
3520 if( pTerm->eOperator!=(WO_EQUIV|WO_EQ) ) continue;
3521 if( pTerm->leftCursor!=iCur ) continue;
drhcdc2e432013-07-01 17:27:19 +00003522 if( pLevel->iLeftJoin ) continue;
drh0c41d222013-04-22 02:39:10 +00003523 pE = pTerm->pExpr;
3524 assert( !ExprHasProperty(pE, EP_FromJoin) );
drh0259bc32013-09-09 19:37:46 +00003525 assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
drh0c41d222013-04-22 02:39:10 +00003526 pAlt = findTerm(pWC, iCur, pTerm->u.leftColumn, notReady, WO_EQ|WO_IN, 0);
3527 if( pAlt==0 ) continue;
drh5c10f3b2013-05-01 17:22:38 +00003528 if( pAlt->wtFlags & (TERM_CODED) ) continue;
drh7963b0e2013-06-17 21:37:40 +00003529 testcase( pAlt->eOperator & WO_EQ );
3530 testcase( pAlt->eOperator & WO_IN );
drh6bc69a22013-11-19 12:33:23 +00003531 VdbeModuleComment((v, "begin transitive constraint"));
drh6b36e822013-07-30 15:10:32 +00003532 pEAlt = sqlite3StackAllocRaw(db, sizeof(*pEAlt));
3533 if( pEAlt ){
3534 *pEAlt = *pAlt->pExpr;
3535 pEAlt->pLeft = pE->pLeft;
3536 sqlite3ExprIfFalse(pParse, pEAlt, addrCont, SQLITE_JUMPIFNULL);
3537 sqlite3StackFree(db, pEAlt);
3538 }
drh0c41d222013-04-22 02:39:10 +00003539 }
3540
drh111a6a72008-12-21 03:51:16 +00003541 /* For a LEFT OUTER JOIN, generate code that will record the fact that
3542 ** at least one row of the right table has matched the left table.
3543 */
3544 if( pLevel->iLeftJoin ){
3545 pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
3546 sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
3547 VdbeComment((v, "record LEFT JOIN hit"));
drhceea3322009-04-23 13:22:42 +00003548 sqlite3ExprCacheClear(pParse);
drh111a6a72008-12-21 03:51:16 +00003549 for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
drh39759742013-08-02 23:40:45 +00003550 testcase( pTerm->wtFlags & TERM_VIRTUAL );
drh111a6a72008-12-21 03:51:16 +00003551 testcase( pTerm->wtFlags & TERM_CODED );
3552 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
drh0259bc32013-09-09 19:37:46 +00003553 if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
drhb057e562009-12-16 23:43:55 +00003554 assert( pWInfo->untestedTerms );
drhc01a3c12009-12-16 22:10:49 +00003555 continue;
3556 }
drh111a6a72008-12-21 03:51:16 +00003557 assert( pTerm->pExpr );
3558 sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
3559 pTerm->wtFlags |= TERM_CODED;
3560 }
3561 }
drh23d04d52008-12-23 23:56:22 +00003562
drh0259bc32013-09-09 19:37:46 +00003563 return pLevel->notReady;
drh111a6a72008-12-21 03:51:16 +00003564}
3565
drhf4e9cb02013-10-28 19:59:59 +00003566#if defined(WHERETRACE_ENABLED) && defined(SQLITE_ENABLE_TREE_EXPLAIN)
3567/*
3568** Generate "Explanation" text for a WhereTerm.
3569*/
3570static void whereExplainTerm(Vdbe *v, WhereTerm *pTerm){
3571 char zType[4];
3572 memcpy(zType, "...", 4);
3573 if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V';
3574 if( pTerm->eOperator & WO_EQUIV ) zType[1] = 'E';
3575 if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) zType[2] = 'L';
3576 sqlite3ExplainPrintf(v, "%s ", zType);
drhf4e9cb02013-10-28 19:59:59 +00003577 sqlite3ExplainExpr(v, pTerm->pExpr);
3578}
3579#endif /* WHERETRACE_ENABLED && SQLITE_ENABLE_TREE_EXPLAIN */
3580
3581
drhd15cb172013-05-21 19:23:10 +00003582#ifdef WHERETRACE_ENABLED
drha18f3d22013-05-08 03:05:41 +00003583/*
3584** Print a WhereLoop object for debugging purposes
3585*/
drhc1ba2e72013-10-28 19:03:21 +00003586static void whereLoopPrint(WhereLoop *p, WhereClause *pWC){
3587 WhereInfo *pWInfo = pWC->pWInfo;
drh989578e2013-10-28 14:34:35 +00003588 int nb = 1+(pWInfo->pTabList->nSrc+7)/8;
3589 struct SrcList_item *pItem = pWInfo->pTabList->a + p->iTab;
drha18f3d22013-05-08 03:05:41 +00003590 Table *pTab = pItem->pTab;
drh6457a352013-06-21 00:35:37 +00003591 sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
drha184fb82013-05-08 04:22:59 +00003592 p->iTab, nb, p->maskSelf, nb, p->prereq);
drh6457a352013-06-21 00:35:37 +00003593 sqlite3DebugPrintf(" %12s",
drha18f3d22013-05-08 03:05:41 +00003594 pItem->zAlias ? pItem->zAlias : pTab->zName);
drh5346e952013-05-08 14:14:26 +00003595 if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
drhc1ba2e72013-10-28 19:03:21 +00003596 const char *zName;
3597 if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){
drh319f6772013-05-14 15:31:07 +00003598 if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
3599 int i = sqlite3Strlen30(zName) - 1;
3600 while( zName[i]!='_' ) i--;
3601 zName += i;
3602 }
drh6457a352013-06-21 00:35:37 +00003603 sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq);
drh5346e952013-05-08 14:14:26 +00003604 }else{
drh6457a352013-06-21 00:35:37 +00003605 sqlite3DebugPrintf("%20s","");
drh5346e952013-05-08 14:14:26 +00003606 }
drha18f3d22013-05-08 03:05:41 +00003607 }else{
drh5346e952013-05-08 14:14:26 +00003608 char *z;
3609 if( p->u.vtab.idxStr ){
drh3bd26f02013-05-24 14:52:03 +00003610 z = sqlite3_mprintf("(%d,\"%s\",%x)",
3611 p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
drh5346e952013-05-08 14:14:26 +00003612 }else{
drh3bd26f02013-05-24 14:52:03 +00003613 z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
drh5346e952013-05-08 14:14:26 +00003614 }
drh6457a352013-06-21 00:35:37 +00003615 sqlite3DebugPrintf(" %-19s", z);
drh5346e952013-05-08 14:14:26 +00003616 sqlite3_free(z);
drha18f3d22013-05-08 03:05:41 +00003617 }
drh6457a352013-06-21 00:35:37 +00003618 sqlite3DebugPrintf(" f %04x N %d", p->wsFlags, p->nLTerm);
drhb8a8e8a2013-06-10 19:12:39 +00003619 sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
drh989578e2013-10-28 14:34:35 +00003620#ifdef SQLITE_ENABLE_TREE_EXPLAIN
3621 /* If the 0x100 bit of wheretracing is set, then show all of the constraint
3622 ** expressions in the WhereLoop.aLTerm[] array.
3623 */
3624 if( p->nLTerm && (sqlite3WhereTrace & 0x100)!=0 ){ /* WHERETRACE 0x100 */
3625 int i;
3626 Vdbe *v = pWInfo->pParse->pVdbe;
3627 sqlite3ExplainBegin(v);
3628 for(i=0; i<p->nLTerm; i++){
drhc1ba2e72013-10-28 19:03:21 +00003629 WhereTerm *pTerm = p->aLTerm[i];
drhcd8629e2013-11-13 12:27:25 +00003630 if( pTerm==0 ) continue;
drh7afc8b02013-10-28 22:33:36 +00003631 sqlite3ExplainPrintf(v, " (%d) #%-2d ", i+1, (int)(pTerm-pWC->a));
drh989578e2013-10-28 14:34:35 +00003632 sqlite3ExplainPush(v);
drhf4e9cb02013-10-28 19:59:59 +00003633 whereExplainTerm(v, pTerm);
drh989578e2013-10-28 14:34:35 +00003634 sqlite3ExplainPop(v);
3635 sqlite3ExplainNL(v);
3636 }
drh989578e2013-10-28 14:34:35 +00003637 sqlite3ExplainFinish(v);
drhc1ba2e72013-10-28 19:03:21 +00003638 sqlite3DebugPrintf("%s", sqlite3VdbeExplanation(v));
drh989578e2013-10-28 14:34:35 +00003639 }
3640#endif
drha18f3d22013-05-08 03:05:41 +00003641}
3642#endif
3643
drhf1b5f5b2013-05-02 00:15:01 +00003644/*
drh4efc9292013-06-06 23:02:03 +00003645** Convert bulk memory into a valid WhereLoop that can be passed
3646** to whereLoopClear harmlessly.
drh5346e952013-05-08 14:14:26 +00003647*/
drh4efc9292013-06-06 23:02:03 +00003648static void whereLoopInit(WhereLoop *p){
3649 p->aLTerm = p->aLTermSpace;
3650 p->nLTerm = 0;
3651 p->nLSlot = ArraySize(p->aLTermSpace);
3652 p->wsFlags = 0;
3653}
3654
3655/*
3656** Clear the WhereLoop.u union. Leave WhereLoop.pLTerm intact.
3657*/
3658static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
drh986b3872013-06-28 21:12:20 +00003659 if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){
drh13e11b42013-06-06 23:44:25 +00003660 if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
3661 sqlite3_free(p->u.vtab.idxStr);
3662 p->u.vtab.needFree = 0;
3663 p->u.vtab.idxStr = 0;
drh986b3872013-06-28 21:12:20 +00003664 }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){
drh13e11b42013-06-06 23:44:25 +00003665 sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
drh2ec2fb22013-11-06 19:59:23 +00003666 sqlite3KeyInfoUnref(p->u.btree.pIndex->pKeyInfo);
drh13e11b42013-06-06 23:44:25 +00003667 sqlite3DbFree(db, p->u.btree.pIndex);
3668 p->u.btree.pIndex = 0;
3669 }
drh5346e952013-05-08 14:14:26 +00003670 }
3671}
3672
drh4efc9292013-06-06 23:02:03 +00003673/*
3674** Deallocate internal memory used by a WhereLoop object
3675*/
3676static void whereLoopClear(sqlite3 *db, WhereLoop *p){
3677 if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
3678 whereLoopClearUnion(db, p);
3679 whereLoopInit(p);
3680}
3681
3682/*
3683** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
3684*/
3685static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
3686 WhereTerm **paNew;
3687 if( p->nLSlot>=n ) return SQLITE_OK;
3688 n = (n+7)&~7;
3689 paNew = sqlite3DbMallocRaw(db, sizeof(p->aLTerm[0])*n);
3690 if( paNew==0 ) return SQLITE_NOMEM;
3691 memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
3692 if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
3693 p->aLTerm = paNew;
3694 p->nLSlot = n;
3695 return SQLITE_OK;
3696}
3697
3698/*
3699** Transfer content from the second pLoop into the first.
3700*/
3701static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
drh4efc9292013-06-06 23:02:03 +00003702 whereLoopClearUnion(db, pTo);
drh0d31dc32013-09-06 00:40:59 +00003703 if( whereLoopResize(db, pTo, pFrom->nLTerm) ){
3704 memset(&pTo->u, 0, sizeof(pTo->u));
3705 return SQLITE_NOMEM;
3706 }
drha2014152013-06-07 00:29:23 +00003707 memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
3708 memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
drh4efc9292013-06-06 23:02:03 +00003709 if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
3710 pFrom->u.vtab.needFree = 0;
drh986b3872013-06-28 21:12:20 +00003711 }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){
drh4efc9292013-06-06 23:02:03 +00003712 pFrom->u.btree.pIndex = 0;
3713 }
3714 return SQLITE_OK;
3715}
3716
drh5346e952013-05-08 14:14:26 +00003717/*
drhf1b5f5b2013-05-02 00:15:01 +00003718** Delete a WhereLoop object
3719*/
3720static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
drh5346e952013-05-08 14:14:26 +00003721 whereLoopClear(db, p);
drhf1b5f5b2013-05-02 00:15:01 +00003722 sqlite3DbFree(db, p);
3723}
drh84bfda42005-07-15 13:05:21 +00003724
drh9eff6162006-06-12 21:59:13 +00003725/*
3726** Free a WhereInfo structure
3727*/
drh10fe8402008-10-11 16:47:35 +00003728static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
drh52ff8ea2010-04-08 14:15:56 +00003729 if( ALWAYS(pWInfo) ){
drh70d18342013-06-06 19:16:33 +00003730 whereClauseClear(&pWInfo->sWC);
drhf1b5f5b2013-05-02 00:15:01 +00003731 while( pWInfo->pLoops ){
3732 WhereLoop *p = pWInfo->pLoops;
3733 pWInfo->pLoops = p->pNextLoop;
3734 whereLoopDelete(db, p);
3735 }
drh633e6d52008-07-28 19:34:53 +00003736 sqlite3DbFree(db, pWInfo);
drh9eff6162006-06-12 21:59:13 +00003737 }
3738}
3739
drhf1b5f5b2013-05-02 00:15:01 +00003740/*
drhb355c2c2014-04-18 22:20:31 +00003741** Return TRUE if both of the following are true:
3742**
3743** (1) X has the same or lower cost that Y
3744** (2) X is a proper subset of Y
3745**
3746** By "proper subset" we mean that X uses fewer WHERE clause terms
3747** than Y and that every WHERE clause term used by X is also used
3748** by Y.
3749**
3750** If X is a proper subset of Y then Y is a better choice and ought
3751** to have a lower cost. This routine returns TRUE when that cost
3752** relationship is inverted and needs to be adjusted.
drh3fb183d2014-03-31 19:49:00 +00003753*/
drhb355c2c2014-04-18 22:20:31 +00003754static int whereLoopCheaperProperSubset(
3755 const WhereLoop *pX, /* First WhereLoop to compare */
3756 const WhereLoop *pY /* Compare against this WhereLoop */
3757){
drh3fb183d2014-03-31 19:49:00 +00003758 int i, j;
drhb355c2c2014-04-18 22:20:31 +00003759 if( pX->nLTerm >= pY->nLTerm ) return 0; /* X is not a subset of Y */
3760 if( pX->rRun >= pY->rRun ){
3761 if( pX->rRun > pY->rRun ) return 0; /* X costs more than Y */
3762 if( pX->nOut > pY->nOut ) return 0; /* X costs more than Y */
drh3fb183d2014-03-31 19:49:00 +00003763 }
drhb355c2c2014-04-18 22:20:31 +00003764 for(j=0, i=pX->nLTerm-1; i>=0; i--){
3765 for(j=pY->nLTerm-1; j>=0; j--){
3766 if( pY->aLTerm[j]==pX->aLTerm[i] ) break;
3767 }
3768 if( j<0 ) return 0; /* X not a subset of Y since term X[i] not used by Y */
3769 }
3770 return 1; /* All conditions meet */
drh3fb183d2014-03-31 19:49:00 +00003771}
3772
3773/*
3774** Try to adjust the cost of WhereLoop pTemplate upwards or downwards so
3775** that:
drh53cd10a2014-03-31 18:24:18 +00003776**
drh3fb183d2014-03-31 19:49:00 +00003777** (1) pTemplate costs less than any other WhereLoops that are a proper
3778** subset of pTemplate
drh53cd10a2014-03-31 18:24:18 +00003779**
drh3fb183d2014-03-31 19:49:00 +00003780** (2) pTemplate costs more than any other WhereLoops for which pTemplate
3781** is a proper subset.
drh53cd10a2014-03-31 18:24:18 +00003782**
drh3fb183d2014-03-31 19:49:00 +00003783** To say "WhereLoop X is a proper subset of Y" means that X uses fewer
3784** WHERE clause terms than Y and that every WHERE clause term used by X is
3785** also used by Y.
drh53cd10a2014-03-31 18:24:18 +00003786*/
3787static void whereLoopAdjustCost(const WhereLoop *p, WhereLoop *pTemplate){
3788 if( (pTemplate->wsFlags & WHERE_INDEXED)==0 ) return;
dane3bfbb72014-04-28 09:35:31 +00003789 if( (pTemplate->wsFlags & WHERE_SKIPSCAN)!=0 ) return;
drh53cd10a2014-03-31 18:24:18 +00003790 for(; p; p=p->pNextLoop){
drh3fb183d2014-03-31 19:49:00 +00003791 if( p->iTab!=pTemplate->iTab ) continue;
3792 if( (p->wsFlags & WHERE_INDEXED)==0 ) continue;
dane3bfbb72014-04-28 09:35:31 +00003793 if( (p->wsFlags & WHERE_SKIPSCAN)!=0 ) continue;
drhb355c2c2014-04-18 22:20:31 +00003794 if( whereLoopCheaperProperSubset(p, pTemplate) ){
3795 /* Adjust pTemplate cost downward so that it is cheaper than its
3796 ** subset p */
drh3fb183d2014-03-31 19:49:00 +00003797 pTemplate->rRun = p->rRun;
3798 pTemplate->nOut = p->nOut - 1;
drhb355c2c2014-04-18 22:20:31 +00003799 }else if( whereLoopCheaperProperSubset(pTemplate, p) ){
3800 /* Adjust pTemplate cost upward so that it is costlier than p since
3801 ** pTemplate is a proper subset of p */
drh3fb183d2014-03-31 19:49:00 +00003802 pTemplate->rRun = p->rRun;
3803 pTemplate->nOut = p->nOut + 1;
drh53cd10a2014-03-31 18:24:18 +00003804 }
3805 }
3806}
3807
3808/*
drh7a4b1642014-03-29 21:16:07 +00003809** Search the list of WhereLoops in *ppPrev looking for one that can be
3810** supplanted by pTemplate.
drhf1b5f5b2013-05-02 00:15:01 +00003811**
drh7a4b1642014-03-29 21:16:07 +00003812** Return NULL if the WhereLoop list contains an entry that can supplant
3813** pTemplate, in other words if pTemplate does not belong on the list.
drh23f98da2013-05-21 15:52:07 +00003814**
drh7a4b1642014-03-29 21:16:07 +00003815** If pX is a WhereLoop that pTemplate can supplant, then return the
3816** link that points to pX.
drh23f98da2013-05-21 15:52:07 +00003817**
drh7a4b1642014-03-29 21:16:07 +00003818** If pTemplate cannot supplant any existing element of the list but needs
3819** to be added to the list, then return a pointer to the tail of the list.
drhf1b5f5b2013-05-02 00:15:01 +00003820*/
drh7a4b1642014-03-29 21:16:07 +00003821static WhereLoop **whereLoopFindLesser(
3822 WhereLoop **ppPrev,
3823 const WhereLoop *pTemplate
3824){
3825 WhereLoop *p;
3826 for(p=(*ppPrev); p; ppPrev=&p->pNextLoop, p=*ppPrev){
drhdbb80232013-06-19 12:34:13 +00003827 if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
3828 /* If either the iTab or iSortIdx values for two WhereLoop are different
3829 ** then those WhereLoops need to be considered separately. Neither is
3830 ** a candidate to replace the other. */
3831 continue;
3832 }
3833 /* In the current implementation, the rSetup value is either zero
3834 ** or the cost of building an automatic index (NlogN) and the NlogN
3835 ** is the same for compatible WhereLoops. */
3836 assert( p->rSetup==0 || pTemplate->rSetup==0
3837 || p->rSetup==pTemplate->rSetup );
3838
3839 /* whereLoopAddBtree() always generates and inserts the automatic index
3840 ** case first. Hence compatible candidate WhereLoops never have a larger
3841 ** rSetup. Call this SETUP-INVARIANT */
3842 assert( p->rSetup>=pTemplate->rSetup );
3843
drh53cd10a2014-03-31 18:24:18 +00003844 /* If existing WhereLoop p is better than pTemplate, pTemplate can be
3845 ** discarded. WhereLoop p is better if:
3846 ** (1) p has no more dependencies than pTemplate, and
3847 ** (2) p has an equal or lower cost than pTemplate
3848 */
3849 if( (p->prereq & pTemplate->prereq)==p->prereq /* (1) */
3850 && p->rSetup<=pTemplate->rSetup /* (2a) */
3851 && p->rRun<=pTemplate->rRun /* (2b) */
3852 && p->nOut<=pTemplate->nOut /* (2c) */
drhf1b5f5b2013-05-02 00:15:01 +00003853 ){
drh53cd10a2014-03-31 18:24:18 +00003854 return 0; /* Discard pTemplate */
drhf1b5f5b2013-05-02 00:15:01 +00003855 }
drh53cd10a2014-03-31 18:24:18 +00003856
3857 /* If pTemplate is always better than p, then cause p to be overwritten
3858 ** with pTemplate. pTemplate is better than p if:
3859 ** (1) pTemplate has no more dependences than p, and
3860 ** (2) pTemplate has an equal or lower cost than p.
3861 */
3862 if( (p->prereq & pTemplate->prereq)==pTemplate->prereq /* (1) */
3863 && p->rRun>=pTemplate->rRun /* (2a) */
3864 && p->nOut>=pTemplate->nOut /* (2b) */
drhf1b5f5b2013-05-02 00:15:01 +00003865 ){
drhadd5ce32013-09-07 00:29:06 +00003866 assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */
drh53cd10a2014-03-31 18:24:18 +00003867 break; /* Cause p to be overwritten by pTemplate */
drhf1b5f5b2013-05-02 00:15:01 +00003868 }
3869 }
drh7a4b1642014-03-29 21:16:07 +00003870 return ppPrev;
3871}
3872
3873/*
drh94a11212004-09-25 13:12:14 +00003874** Insert or replace a WhereLoop entry using the template supplied.
3875**
3876** An existing WhereLoop entry might be overwritten if the new template
3877** is better and has fewer dependencies. Or the template will be ignored
3878** and no insert will occur if an existing WhereLoop is faster and has
3879** fewer dependencies than the template. Otherwise a new WhereLoop is
3880** added based on the template.
drh51669862004-12-18 18:40:26 +00003881**
drh7a4b1642014-03-29 21:16:07 +00003882** If pBuilder->pOrSet is not NULL then we care about only the
drh94a11212004-09-25 13:12:14 +00003883** prerequisites and rRun and nOut costs of the N best loops. That
3884** information is gathered in the pBuilder->pOrSet object. This special
drh51669862004-12-18 18:40:26 +00003885** processing mode is used only for OR clause processing.
3886**
3887** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
3888** still might overwrite similar loops with the new template if the
drh53cd10a2014-03-31 18:24:18 +00003889** new template is better. Loops may be overwritten if the following
drh94a11212004-09-25 13:12:14 +00003890** conditions are met:
3891**
3892** (1) They have the same iTab.
3893** (2) They have the same iSortIdx.
3894** (3) The template has same or fewer dependencies than the current loop
3895** (4) The template has the same or lower cost than the current loop
drh94a11212004-09-25 13:12:14 +00003896*/
3897static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
drh7a4b1642014-03-29 21:16:07 +00003898 WhereLoop **ppPrev, *p;
drh94a11212004-09-25 13:12:14 +00003899 WhereInfo *pWInfo = pBuilder->pWInfo;
3900 sqlite3 *db = pWInfo->pParse->db;
3901
3902 /* If pBuilder->pOrSet is defined, then only keep track of the costs
3903 ** and prereqs.
3904 */
3905 if( pBuilder->pOrSet!=0 ){
3906#if WHERETRACE_ENABLED
drh51669862004-12-18 18:40:26 +00003907 u16 n = pBuilder->pOrSet->n;
3908 int x =
3909#endif
3910 whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
3911 pTemplate->nOut);
drh94a11212004-09-25 13:12:14 +00003912#if WHERETRACE_ENABLED /* 0x8 */
3913 if( sqlite3WhereTrace & 0x8 ){
drhe3184742002-06-19 14:27:05 +00003914 sqlite3DebugPrintf(x?" or-%d: ":" or-X: ", n);
drhacf3b982005-01-03 01:27:18 +00003915 whereLoopPrint(pTemplate, pBuilder->pWC);
drh75897232000-05-29 14:26:00 +00003916 }
danielk19774adee202004-05-08 08:23:19 +00003917#endif
drh75897232000-05-29 14:26:00 +00003918 return SQLITE_OK;
3919 }
3920
drh7a4b1642014-03-29 21:16:07 +00003921 /* Look for an existing WhereLoop to replace with pTemplate
drh75897232000-05-29 14:26:00 +00003922 */
drh53cd10a2014-03-31 18:24:18 +00003923 whereLoopAdjustCost(pWInfo->pLoops, pTemplate);
drh7a4b1642014-03-29 21:16:07 +00003924 ppPrev = whereLoopFindLesser(&pWInfo->pLoops, pTemplate);
drhf1b5f5b2013-05-02 00:15:01 +00003925
drh7a4b1642014-03-29 21:16:07 +00003926 if( ppPrev==0 ){
3927 /* There already exists a WhereLoop on the list that is better
3928 ** than pTemplate, so just ignore pTemplate */
3929#if WHERETRACE_ENABLED /* 0x8 */
3930 if( sqlite3WhereTrace & 0x8 ){
3931 sqlite3DebugPrintf("ins-noop: ");
3932 whereLoopPrint(pTemplate, pBuilder->pWC);
drhf1b5f5b2013-05-02 00:15:01 +00003933 }
drh7a4b1642014-03-29 21:16:07 +00003934#endif
3935 return SQLITE_OK;
3936 }else{
3937 p = *ppPrev;
drhf1b5f5b2013-05-02 00:15:01 +00003938 }
3939
3940 /* If we reach this point it means that either p[] should be overwritten
3941 ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
3942 ** WhereLoop and insert it.
3943 */
drh989578e2013-10-28 14:34:35 +00003944#if WHERETRACE_ENABLED /* 0x8 */
drhae70cf12013-05-31 15:18:46 +00003945 if( sqlite3WhereTrace & 0x8 ){
3946 if( p!=0 ){
3947 sqlite3DebugPrintf("ins-del: ");
drhc1ba2e72013-10-28 19:03:21 +00003948 whereLoopPrint(p, pBuilder->pWC);
drhae70cf12013-05-31 15:18:46 +00003949 }
3950 sqlite3DebugPrintf("ins-new: ");
drhc1ba2e72013-10-28 19:03:21 +00003951 whereLoopPrint(pTemplate, pBuilder->pWC);
drhae70cf12013-05-31 15:18:46 +00003952 }
3953#endif
drhf1b5f5b2013-05-02 00:15:01 +00003954 if( p==0 ){
drh7a4b1642014-03-29 21:16:07 +00003955 /* Allocate a new WhereLoop to add to the end of the list */
3956 *ppPrev = p = sqlite3DbMallocRaw(db, sizeof(WhereLoop));
drhf1b5f5b2013-05-02 00:15:01 +00003957 if( p==0 ) return SQLITE_NOMEM;
drh4efc9292013-06-06 23:02:03 +00003958 whereLoopInit(p);
drh7a4b1642014-03-29 21:16:07 +00003959 p->pNextLoop = 0;
3960 }else{
3961 /* We will be overwriting WhereLoop p[]. But before we do, first
3962 ** go through the rest of the list and delete any other entries besides
3963 ** p[] that are also supplated by pTemplate */
3964 WhereLoop **ppTail = &p->pNextLoop;
3965 WhereLoop *pToDel;
3966 while( *ppTail ){
3967 ppTail = whereLoopFindLesser(ppTail, pTemplate);
3968 if( NEVER(ppTail==0) ) break;
3969 pToDel = *ppTail;
3970 if( pToDel==0 ) break;
3971 *ppTail = pToDel->pNextLoop;
3972#if WHERETRACE_ENABLED /* 0x8 */
3973 if( sqlite3WhereTrace & 0x8 ){
3974 sqlite3DebugPrintf("ins-del: ");
3975 whereLoopPrint(pToDel, pBuilder->pWC);
3976 }
3977#endif
3978 whereLoopDelete(db, pToDel);
3979 }
drhf1b5f5b2013-05-02 00:15:01 +00003980 }
drh4efc9292013-06-06 23:02:03 +00003981 whereLoopXfer(db, p, pTemplate);
drh5346e952013-05-08 14:14:26 +00003982 if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
drhef866372013-05-22 20:49:02 +00003983 Index *pIndex = p->u.btree.pIndex;
3984 if( pIndex && pIndex->tnum==0 ){
drhcf8fa7a2013-05-10 20:26:22 +00003985 p->u.btree.pIndex = 0;
3986 }
drh5346e952013-05-08 14:14:26 +00003987 }
drhf1b5f5b2013-05-02 00:15:01 +00003988 return SQLITE_OK;
3989}
3990
3991/*
drhcca9f3d2013-09-06 15:23:29 +00003992** Adjust the WhereLoop.nOut value downward to account for terms of the
3993** WHERE clause that reference the loop but which are not used by an
3994** index.
3995**
3996** In the current implementation, the first extra WHERE clause term reduces
3997** the number of output rows by a factor of 10 and each additional term
3998** reduces the number of output rows by sqrt(2).
3999*/
drh4f991892013-10-11 15:05:05 +00004000static void whereLoopOutputAdjust(WhereClause *pWC, WhereLoop *pLoop){
drh7d9e7d82013-09-11 17:39:09 +00004001 WhereTerm *pTerm, *pX;
drhcca9f3d2013-09-06 15:23:29 +00004002 Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf);
drh7d9e7d82013-09-11 17:39:09 +00004003 int i, j;
drhadd5ce32013-09-07 00:29:06 +00004004
4005 if( !OptimizationEnabled(pWC->pWInfo->pParse->db, SQLITE_AdjustOutEst) ){
4006 return;
4007 }
drhcca9f3d2013-09-06 15:23:29 +00004008 for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){
drh7d9e7d82013-09-11 17:39:09 +00004009 if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break;
drhcca9f3d2013-09-06 15:23:29 +00004010 if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;
4011 if( (pTerm->prereqAll & notAllowed)!=0 ) continue;
drh7d9e7d82013-09-11 17:39:09 +00004012 for(j=pLoop->nLTerm-1; j>=0; j--){
4013 pX = pLoop->aLTerm[j];
drhd2447442013-11-13 19:01:41 +00004014 if( pX==0 ) continue;
drh7d9e7d82013-09-11 17:39:09 +00004015 if( pX==pTerm ) break;
4016 if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break;
4017 }
danaa9933c2014-04-24 20:04:49 +00004018 if( j<0 ){
4019 pLoop->nOut += (pTerm->truthProb<=0 ? pTerm->truthProb : -1);
4020 }
drhcca9f3d2013-09-06 15:23:29 +00004021 }
drhcca9f3d2013-09-06 15:23:29 +00004022}
4023
4024/*
dan4a6b8a02014-04-30 14:47:01 +00004025** We have so far matched pBuilder->pNew->u.btree.nEq terms of the
4026** index pIndex. Try to match one more.
4027**
4028** When this function is called, pBuilder->pNew->nOut contains the
4029** number of rows expected to be visited by filtering using the nEq
4030** terms only. If it is modified, this value is restored before this
4031** function returns.
drh1c8148f2013-05-04 20:25:23 +00004032**
4033** If pProbe->tnum==0, that means pIndex is a fake index used for the
4034** INTEGER PRIMARY KEY.
4035*/
drh5346e952013-05-08 14:14:26 +00004036static int whereLoopAddBtreeIndex(
drh1c8148f2013-05-04 20:25:23 +00004037 WhereLoopBuilder *pBuilder, /* The WhereLoop factory */
4038 struct SrcList_item *pSrc, /* FROM clause term being analyzed */
4039 Index *pProbe, /* An index on pSrc */
drhbf539c42013-10-05 18:16:02 +00004040 LogEst nInMul /* log(Number of iterations due to IN) */
drh1c8148f2013-05-04 20:25:23 +00004041){
drh70d18342013-06-06 19:16:33 +00004042 WhereInfo *pWInfo = pBuilder->pWInfo; /* WHERE analyse context */
4043 Parse *pParse = pWInfo->pParse; /* Parsing context */
4044 sqlite3 *db = pParse->db; /* Database connection malloc context */
drh1c8148f2013-05-04 20:25:23 +00004045 WhereLoop *pNew; /* Template WhereLoop under construction */
4046 WhereTerm *pTerm; /* A WhereTerm under consideration */
drh43fe25f2013-05-07 23:06:23 +00004047 int opMask; /* Valid operators for constraints */
drh1c8148f2013-05-04 20:25:23 +00004048 WhereScan scan; /* Iterator for WHERE terms */
drh4efc9292013-06-06 23:02:03 +00004049 Bitmask saved_prereq; /* Original value of pNew->prereq */
4050 u16 saved_nLTerm; /* Original value of pNew->nLTerm */
drhcd8629e2013-11-13 12:27:25 +00004051 u16 saved_nEq; /* Original value of pNew->u.btree.nEq */
4052 u16 saved_nSkip; /* Original value of pNew->u.btree.nSkip */
drh4efc9292013-06-06 23:02:03 +00004053 u32 saved_wsFlags; /* Original value of pNew->wsFlags */
drhbf539c42013-10-05 18:16:02 +00004054 LogEst saved_nOut; /* Original value of pNew->nOut */
drha18f3d22013-05-08 03:05:41 +00004055 int iCol; /* Index of the column in the table */
drh5346e952013-05-08 14:14:26 +00004056 int rc = SQLITE_OK; /* Return code */
drhbf539c42013-10-05 18:16:02 +00004057 LogEst rLogSize; /* Logarithm of table size */
drhc7f0d222013-06-19 03:27:12 +00004058 WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
drh1c8148f2013-05-04 20:25:23 +00004059
drh1c8148f2013-05-04 20:25:23 +00004060 pNew = pBuilder->pNew;
drh5346e952013-05-08 14:14:26 +00004061 if( db->mallocFailed ) return SQLITE_NOMEM;
drh1c8148f2013-05-04 20:25:23 +00004062
drh5346e952013-05-08 14:14:26 +00004063 assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
drh43fe25f2013-05-07 23:06:23 +00004064 assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
4065 if( pNew->wsFlags & WHERE_BTM_LIMIT ){
4066 opMask = WO_LT|WO_LE;
4067 }else if( pProbe->tnum<=0 || (pSrc->jointype & JT_LEFT)!=0 ){
4068 opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE;
drh1c8148f2013-05-04 20:25:23 +00004069 }else{
drh43fe25f2013-05-07 23:06:23 +00004070 opMask = WO_EQ|WO_IN|WO_ISNULL|WO_GT|WO_GE|WO_LT|WO_LE;
drh1c8148f2013-05-04 20:25:23 +00004071 }
drhef866372013-05-22 20:49:02 +00004072 if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
drh1c8148f2013-05-04 20:25:23 +00004073
drhbbbdc832013-10-22 18:01:40 +00004074 assert( pNew->u.btree.nEq<=pProbe->nKeyCol );
4075 if( pNew->u.btree.nEq < pProbe->nKeyCol ){
drh0f133a42013-05-22 17:01:17 +00004076 iCol = pProbe->aiColumn[pNew->u.btree.nEq];
drh0f133a42013-05-22 17:01:17 +00004077 }else{
4078 iCol = -1;
drh0f133a42013-05-22 17:01:17 +00004079 }
drha18f3d22013-05-08 03:05:41 +00004080 pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, iCol,
drh0f133a42013-05-22 17:01:17 +00004081 opMask, pProbe);
drh4efc9292013-06-06 23:02:03 +00004082 saved_nEq = pNew->u.btree.nEq;
drhcd8629e2013-11-13 12:27:25 +00004083 saved_nSkip = pNew->u.btree.nSkip;
drh4efc9292013-06-06 23:02:03 +00004084 saved_nLTerm = pNew->nLTerm;
4085 saved_wsFlags = pNew->wsFlags;
4086 saved_prereq = pNew->prereq;
4087 saved_nOut = pNew->nOut;
drhb8a8e8a2013-06-10 19:12:39 +00004088 pNew->rSetup = 0;
dancfc9df72014-04-25 15:01:01 +00004089 rLogSize = estLog(pProbe->aiRowLogEst[0]);
drh64ff26f2013-11-18 19:32:15 +00004090
4091 /* Consider using a skip-scan if there are no WHERE clause constraints
4092 ** available for the left-most terms of the index, and if the average
dan4a6b8a02014-04-30 14:47:01 +00004093 ** number of repeats in the left-most terms is at least 18.
4094 **
4095 ** The magic number 18 is selected on the basis that scanning 17 rows
4096 ** is almost always quicker than an index seek (even though if the index
4097 ** contains fewer than 2^17 rows we assume otherwise in other parts of
4098 ** the code). And, even if it is not, it should not be too much slower.
4099 ** On the other hand, the extra seeks could end up being significantly
4100 ** more expensive. */
dancfc9df72014-04-25 15:01:01 +00004101 assert( 42==sqlite3LogEst(18) );
drhcd8629e2013-11-13 12:27:25 +00004102 if( pTerm==0
4103 && saved_nEq==saved_nSkip
4104 && saved_nEq+1<pProbe->nKeyCol
dancfc9df72014-04-25 15:01:01 +00004105 && pProbe->aiRowLogEst[saved_nEq+1]>=42 /* TUNING: Minimum for skip-scan */
drh6c1de302013-12-22 20:44:10 +00004106 && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK
drhcd8629e2013-11-13 12:27:25 +00004107 ){
drh2e5ef4e2013-11-13 16:58:54 +00004108 LogEst nIter;
drhcd8629e2013-11-13 12:27:25 +00004109 pNew->u.btree.nEq++;
4110 pNew->u.btree.nSkip++;
4111 pNew->aLTerm[pNew->nLTerm++] = 0;
drh2e5ef4e2013-11-13 16:58:54 +00004112 pNew->wsFlags |= WHERE_SKIPSCAN;
dan8ad1d8b2014-04-25 20:22:45 +00004113 nIter = pProbe->aiRowLogEst[saved_nEq] - pProbe->aiRowLogEst[saved_nEq+1];
4114 pNew->nOut -= nIter;
4115 whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nIter + nInMul);
drh89212fb2014-03-10 20:12:31 +00004116 pNew->nOut = saved_nOut;
drhcd8629e2013-11-13 12:27:25 +00004117 }
drh5346e952013-05-08 14:14:26 +00004118 for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
dan8ad1d8b2014-04-25 20:22:45 +00004119 u16 eOp = pTerm->eOperator; /* Shorthand for pTerm->eOperator */
danaa9933c2014-04-24 20:04:49 +00004120 LogEst rCostIdx;
dan8ad1d8b2014-04-25 20:22:45 +00004121 LogEst nOutUnadjusted; /* nOut before IN() and WHERE adjustments */
drhb8a8e8a2013-06-10 19:12:39 +00004122 int nIn = 0;
drh1435a9a2013-08-27 23:15:44 +00004123#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
dan7a419232013-08-06 20:01:43 +00004124 int nRecValid = pBuilder->nRecValid;
drhb5246e52013-07-08 21:12:57 +00004125#endif
dan8ad1d8b2014-04-25 20:22:45 +00004126 if( (eOp==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)
dan8bff07a2013-08-29 14:56:14 +00004127 && (iCol<0 || pSrc->pTab->aCol[iCol].notNull)
4128 ){
4129 continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */
4130 }
dan7a419232013-08-06 20:01:43 +00004131 if( pTerm->prereqRight & pNew->maskSelf ) continue;
4132
drh4efc9292013-06-06 23:02:03 +00004133 pNew->wsFlags = saved_wsFlags;
4134 pNew->u.btree.nEq = saved_nEq;
4135 pNew->nLTerm = saved_nLTerm;
4136 if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
4137 pNew->aLTerm[pNew->nLTerm++] = pTerm;
4138 pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
dan8ad1d8b2014-04-25 20:22:45 +00004139
4140 assert( nInMul==0
4141 || (pNew->wsFlags & WHERE_COLUMN_NULL)!=0
4142 || (pNew->wsFlags & WHERE_COLUMN_IN)!=0
4143 || (pNew->wsFlags & WHERE_SKIPSCAN)!=0
4144 );
4145
4146 if( eOp & WO_IN ){
drha18f3d22013-05-08 03:05:41 +00004147 Expr *pExpr = pTerm->pExpr;
4148 pNew->wsFlags |= WHERE_COLUMN_IN;
4149 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
drhe1e2e9a2013-06-13 15:16:53 +00004150 /* "x IN (SELECT ...)": TUNING: the SELECT returns 25 rows */
drhbf539c42013-10-05 18:16:02 +00004151 nIn = 46; assert( 46==sqlite3LogEst(25) );
drha18f3d22013-05-08 03:05:41 +00004152 }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
4153 /* "x IN (value, value, ...)" */
drhbf539c42013-10-05 18:16:02 +00004154 nIn = sqlite3LogEst(pExpr->x.pList->nExpr);
drhf1645f02013-05-07 19:44:38 +00004155 }
drh2b59b3a2014-03-20 13:26:47 +00004156 assert( nIn>0 ); /* RHS always has 2 or more terms... The parser
4157 ** changes "x IN (?)" into "x=?". */
dan8ad1d8b2014-04-25 20:22:45 +00004158
4159 }else if( eOp & (WO_EQ) ){
drha18f3d22013-05-08 03:05:41 +00004160 pNew->wsFlags |= WHERE_COLUMN_EQ;
dan8ad1d8b2014-04-25 20:22:45 +00004161 if( iCol<0 || (nInMul==0 && pNew->u.btree.nEq==pProbe->nKeyCol-1) ){
drhe39a7322014-02-03 14:04:11 +00004162 if( iCol>=0 && pProbe->onError==OE_None ){
4163 pNew->wsFlags |= WHERE_UNQ_WANTED;
4164 }else{
4165 pNew->wsFlags |= WHERE_ONEROW;
4166 }
drh21f7ff72013-06-03 15:07:23 +00004167 }
dan2dd3cdc2014-04-26 20:21:14 +00004168 }else if( eOp & WO_ISNULL ){
4169 pNew->wsFlags |= WHERE_COLUMN_NULL;
dan8ad1d8b2014-04-25 20:22:45 +00004170 }else if( eOp & (WO_GT|WO_GE) ){
4171 testcase( eOp & WO_GT );
4172 testcase( eOp & WO_GE );
drha18f3d22013-05-08 03:05:41 +00004173 pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
drh6f2bfad2013-06-03 17:35:22 +00004174 pBtm = pTerm;
4175 pTop = 0;
dan2dd3cdc2014-04-26 20:21:14 +00004176 }else{
dan8ad1d8b2014-04-25 20:22:45 +00004177 assert( eOp & (WO_LT|WO_LE) );
4178 testcase( eOp & WO_LT );
4179 testcase( eOp & WO_LE );
drha18f3d22013-05-08 03:05:41 +00004180 pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
drh6f2bfad2013-06-03 17:35:22 +00004181 pTop = pTerm;
4182 pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
drh4efc9292013-06-06 23:02:03 +00004183 pNew->aLTerm[pNew->nLTerm-2] : 0;
drh1c8148f2013-05-04 20:25:23 +00004184 }
dan8ad1d8b2014-04-25 20:22:45 +00004185
4186 /* At this point pNew->nOut is set to the number of rows expected to
4187 ** be visited by the index scan before considering term pTerm, or the
4188 ** values of nIn and nInMul. In other words, assuming that all
4189 ** "x IN(...)" terms are replaced with "x = ?". This block updates
4190 ** the value of pNew->nOut to account for pTerm (but not nIn/nInMul). */
4191 assert( pNew->nOut==saved_nOut );
drh6f2bfad2013-06-03 17:35:22 +00004192 if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
danaa9933c2014-04-24 20:04:49 +00004193 /* Adjust nOut using stat3/stat4 data. Or, if there is no stat3/stat4
4194 ** data, using some other estimate. */
drh186ad8c2013-10-08 18:40:37 +00004195 whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew);
dan8ad1d8b2014-04-25 20:22:45 +00004196 }else{
4197 int nEq = ++pNew->u.btree.nEq;
4198 assert( eOp & (WO_ISNULL|WO_EQ|WO_IN) );
4199
4200 assert( pNew->nOut==saved_nOut );
dan09e1df62014-04-29 16:10:22 +00004201 if( pTerm->truthProb<=0 && iCol>=0 ){
dan8ad1d8b2014-04-25 20:22:45 +00004202 assert( (eOp & WO_IN) || nIn==0 );
4203 pNew->nOut += pTerm->truthProb;
4204 pNew->nOut -= nIn;
4205 pNew->wsFlags |= WHERE_LIKELIHOOD;
4206 }else{
drh1435a9a2013-08-27 23:15:44 +00004207#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
dan8ad1d8b2014-04-25 20:22:45 +00004208 tRowcnt nOut = 0;
4209 if( nInMul==0
4210 && pProbe->nSample
4211 && pNew->u.btree.nEq<=pProbe->nSampleCol
4212 && OptimizationEnabled(db, SQLITE_Stat3)
4213 && ((eOp & WO_IN)==0 || !ExprHasProperty(pTerm->pExpr, EP_xIsSelect))
4214 && (pNew->wsFlags & WHERE_LIKELIHOOD)==0
4215 ){
4216 Expr *pExpr = pTerm->pExpr;
4217 if( (eOp & (WO_EQ|WO_ISNULL))!=0 ){
4218 testcase( eOp & WO_EQ );
4219 testcase( eOp & WO_ISNULL );
4220 rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut);
4221 }else{
4222 rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut);
4223 }
4224 assert( rc!=SQLITE_OK || nOut>0 );
4225 if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
4226 if( rc!=SQLITE_OK ) break; /* Jump out of the pTerm loop */
4227 if( nOut ){
4228 pNew->nOut = sqlite3LogEst(nOut);
4229 if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut;
4230 pNew->nOut -= nIn;
4231 }
4232 }
4233 if( nOut==0 )
4234#endif
4235 {
4236 pNew->nOut += (pProbe->aiRowLogEst[nEq] - pProbe->aiRowLogEst[nEq-1]);
4237 if( eOp & WO_ISNULL ){
4238 /* TUNING: If there is no likelihood() value, assume that a
4239 ** "col IS NULL" expression matches twice as many rows
4240 ** as (col=?). */
4241 pNew->nOut += 10;
4242 }
4243 }
dan6cb8d762013-08-08 11:48:57 +00004244 }
drh6f2bfad2013-06-03 17:35:22 +00004245 }
dan8ad1d8b2014-04-25 20:22:45 +00004246
danaa9933c2014-04-24 20:04:49 +00004247 /* Set rCostIdx to the cost of visiting selected rows in index. Add
4248 ** it to pNew->rRun, which is currently set to the cost of the index
4249 ** seek only. Then, if this is a non-covering index, add the cost of
4250 ** visiting the rows in the main table. */
4251 rCostIdx = pNew->nOut + 1 + (15*pProbe->szIdxRow)/pSrc->pTab->szTabRow;
dan8ad1d8b2014-04-25 20:22:45 +00004252 pNew->rRun = sqlite3LogEstAdd(rLogSize, rCostIdx);
drhe217efc2013-06-12 03:48:41 +00004253 if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
danaa9933c2014-04-24 20:04:49 +00004254 pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut + 16);
drheb04de32013-05-10 15:16:30 +00004255 }
danaa9933c2014-04-24 20:04:49 +00004256
dan8ad1d8b2014-04-25 20:22:45 +00004257 nOutUnadjusted = pNew->nOut;
4258 pNew->rRun += nInMul + nIn;
4259 pNew->nOut += nInMul + nIn;
drh4f991892013-10-11 15:05:05 +00004260 whereLoopOutputAdjust(pBuilder->pWC, pNew);
drhcf8fa7a2013-05-10 20:26:22 +00004261 rc = whereLoopInsert(pBuilder, pNew);
dan440e6ff2014-04-28 08:49:54 +00004262
4263 if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
4264 pNew->nOut = saved_nOut;
4265 }else{
4266 pNew->nOut = nOutUnadjusted;
4267 }
dan8ad1d8b2014-04-25 20:22:45 +00004268
drh5346e952013-05-08 14:14:26 +00004269 if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
drhbbbdc832013-10-22 18:01:40 +00004270 && pNew->u.btree.nEq<(pProbe->nKeyCol + (pProbe->zName!=0))
drh5346e952013-05-08 14:14:26 +00004271 ){
drhb8a8e8a2013-06-10 19:12:39 +00004272 whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
drha18f3d22013-05-08 03:05:41 +00004273 }
danad45ed72013-08-08 12:21:32 +00004274 pNew->nOut = saved_nOut;
drh1435a9a2013-08-27 23:15:44 +00004275#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
dan7a419232013-08-06 20:01:43 +00004276 pBuilder->nRecValid = nRecValid;
dan7a419232013-08-06 20:01:43 +00004277#endif
drh1c8148f2013-05-04 20:25:23 +00004278 }
drh4efc9292013-06-06 23:02:03 +00004279 pNew->prereq = saved_prereq;
4280 pNew->u.btree.nEq = saved_nEq;
drhcd8629e2013-11-13 12:27:25 +00004281 pNew->u.btree.nSkip = saved_nSkip;
drh4efc9292013-06-06 23:02:03 +00004282 pNew->wsFlags = saved_wsFlags;
4283 pNew->nOut = saved_nOut;
4284 pNew->nLTerm = saved_nLTerm;
drh5346e952013-05-08 14:14:26 +00004285 return rc;
drh1c8148f2013-05-04 20:25:23 +00004286}
4287
4288/*
drh23f98da2013-05-21 15:52:07 +00004289** Return True if it is possible that pIndex might be useful in
4290** implementing the ORDER BY clause in pBuilder.
4291**
4292** Return False if pBuilder does not contain an ORDER BY clause or
4293** if there is no way for pIndex to be useful in implementing that
4294** ORDER BY clause.
4295*/
4296static int indexMightHelpWithOrderBy(
4297 WhereLoopBuilder *pBuilder,
4298 Index *pIndex,
4299 int iCursor
4300){
4301 ExprList *pOB;
drh6d381472013-06-13 17:58:08 +00004302 int ii, jj;
drh23f98da2013-05-21 15:52:07 +00004303
drh53cfbe92013-06-13 17:28:22 +00004304 if( pIndex->bUnordered ) return 0;
drh70d18342013-06-06 19:16:33 +00004305 if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
drh23f98da2013-05-21 15:52:07 +00004306 for(ii=0; ii<pOB->nExpr; ii++){
drh45c154a2013-06-03 20:46:35 +00004307 Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr);
drh23f98da2013-05-21 15:52:07 +00004308 if( pExpr->op!=TK_COLUMN ) return 0;
4309 if( pExpr->iTable==iCursor ){
drhbbbdc832013-10-22 18:01:40 +00004310 for(jj=0; jj<pIndex->nKeyCol; jj++){
drh6d381472013-06-13 17:58:08 +00004311 if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
4312 }
drh23f98da2013-05-21 15:52:07 +00004313 }
4314 }
4315 return 0;
4316}
4317
4318/*
drh92a121f2013-06-10 12:15:47 +00004319** Return a bitmask where 1s indicate that the corresponding column of
4320** the table is used by an index. Only the first 63 columns are considered.
4321*/
drhfd5874d2013-06-12 14:52:39 +00004322static Bitmask columnsInIndex(Index *pIdx){
drh92a121f2013-06-10 12:15:47 +00004323 Bitmask m = 0;
4324 int j;
drhec95c442013-10-23 01:57:32 +00004325 for(j=pIdx->nColumn-1; j>=0; j--){
drh92a121f2013-06-10 12:15:47 +00004326 int x = pIdx->aiColumn[j];
drhec95c442013-10-23 01:57:32 +00004327 if( x>=0 ){
4328 testcase( x==BMS-1 );
4329 testcase( x==BMS-2 );
4330 if( x<BMS-1 ) m |= MASKBIT(x);
4331 }
drh92a121f2013-06-10 12:15:47 +00004332 }
4333 return m;
4334}
4335
drh4bd5f732013-07-31 23:22:39 +00004336/* Check to see if a partial index with pPartIndexWhere can be used
4337** in the current query. Return true if it can be and false if not.
4338*/
4339static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere){
4340 int i;
4341 WhereTerm *pTerm;
4342 for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
4343 if( sqlite3ExprImpliesExpr(pTerm->pExpr, pWhere, iTab) ) return 1;
4344 }
4345 return 0;
4346}
drh92a121f2013-06-10 12:15:47 +00004347
4348/*
dan51576f42013-07-02 10:06:15 +00004349** Add all WhereLoop objects for a single table of the join where the table
drh0823c892013-05-11 00:06:23 +00004350** is idenfied by pBuilder->pNew->iTab. That table is guaranteed to be
4351** a b-tree table, not a virtual table.
drhf1b5f5b2013-05-02 00:15:01 +00004352*/
drh5346e952013-05-08 14:14:26 +00004353static int whereLoopAddBtree(
drh1c8148f2013-05-04 20:25:23 +00004354 WhereLoopBuilder *pBuilder, /* WHERE clause information */
drh1c8148f2013-05-04 20:25:23 +00004355 Bitmask mExtra /* Extra prerequesites for using this table */
drhf1b5f5b2013-05-02 00:15:01 +00004356){
drh70d18342013-06-06 19:16:33 +00004357 WhereInfo *pWInfo; /* WHERE analysis context */
drh1c8148f2013-05-04 20:25:23 +00004358 Index *pProbe; /* An index we are evaluating */
drh1c8148f2013-05-04 20:25:23 +00004359 Index sPk; /* A fake index object for the primary key */
dancfc9df72014-04-25 15:01:01 +00004360 LogEst aiRowEstPk[2]; /* The aiRowLogEst[] value for the sPk index */
drhbbbdc832013-10-22 18:01:40 +00004361 i16 aiColumnPk = -1; /* The aColumn[] value for the sPk index */
drh70d18342013-06-06 19:16:33 +00004362 SrcList *pTabList; /* The FROM clause */
drh1c8148f2013-05-04 20:25:23 +00004363 struct SrcList_item *pSrc; /* The FROM clause btree term to add */
drh1c8148f2013-05-04 20:25:23 +00004364 WhereLoop *pNew; /* Template WhereLoop object */
drh5346e952013-05-08 14:14:26 +00004365 int rc = SQLITE_OK; /* Return code */
drhd044d202013-05-31 12:43:55 +00004366 int iSortIdx = 1; /* Index number */
drh23f98da2013-05-21 15:52:07 +00004367 int b; /* A boolean value */
drhbf539c42013-10-05 18:16:02 +00004368 LogEst rSize; /* number of rows in the table */
4369 LogEst rLogSize; /* Logarithm of the number of rows in the table */
drh4bd5f732013-07-31 23:22:39 +00004370 WhereClause *pWC; /* The parsed WHERE clause */
drh3495d202013-10-07 17:32:15 +00004371 Table *pTab; /* Table being queried */
drh23f98da2013-05-21 15:52:07 +00004372
drh1c8148f2013-05-04 20:25:23 +00004373 pNew = pBuilder->pNew;
drh70d18342013-06-06 19:16:33 +00004374 pWInfo = pBuilder->pWInfo;
4375 pTabList = pWInfo->pTabList;
4376 pSrc = pTabList->a + pNew->iTab;
drh3495d202013-10-07 17:32:15 +00004377 pTab = pSrc->pTab;
drh4bd5f732013-07-31 23:22:39 +00004378 pWC = pBuilder->pWC;
drh0823c892013-05-11 00:06:23 +00004379 assert( !IsVirtual(pSrc->pTab) );
drh1c8148f2013-05-04 20:25:23 +00004380
4381 if( pSrc->pIndex ){
4382 /* An INDEXED BY clause specifies a particular index to use */
4383 pProbe = pSrc->pIndex;
drhec95c442013-10-23 01:57:32 +00004384 }else if( !HasRowid(pTab) ){
4385 pProbe = pTab->pIndex;
drh1c8148f2013-05-04 20:25:23 +00004386 }else{
4387 /* There is no INDEXED BY clause. Create a fake Index object in local
4388 ** variable sPk to represent the rowid primary key index. Make this
4389 ** fake index the first in a chain of Index objects with all of the real
4390 ** indices to follow */
4391 Index *pFirst; /* First of real indices on the table */
4392 memset(&sPk, 0, sizeof(Index));
drhbbbdc832013-10-22 18:01:40 +00004393 sPk.nKeyCol = 1;
drh1c8148f2013-05-04 20:25:23 +00004394 sPk.aiColumn = &aiColumnPk;
dancfc9df72014-04-25 15:01:01 +00004395 sPk.aiRowLogEst = aiRowEstPk;
drh1c8148f2013-05-04 20:25:23 +00004396 sPk.onError = OE_Replace;
drh3495d202013-10-07 17:32:15 +00004397 sPk.pTable = pTab;
danaa9933c2014-04-24 20:04:49 +00004398 sPk.szIdxRow = pTab->szTabRow;
dancfc9df72014-04-25 15:01:01 +00004399 aiRowEstPk[0] = pTab->nRowLogEst;
4400 aiRowEstPk[1] = 0;
drh1c8148f2013-05-04 20:25:23 +00004401 pFirst = pSrc->pTab->pIndex;
4402 if( pSrc->notIndexed==0 ){
4403 /* The real indices of the table are only considered if the
4404 ** NOT INDEXED qualifier is omitted from the FROM clause */
4405 sPk.pNext = pFirst;
4406 }
4407 pProbe = &sPk;
4408 }
dancfc9df72014-04-25 15:01:01 +00004409 rSize = pTab->nRowLogEst;
drheb04de32013-05-10 15:16:30 +00004410 rLogSize = estLog(rSize);
4411
drhfeb56e02013-08-23 17:33:46 +00004412#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
drheb04de32013-05-10 15:16:30 +00004413 /* Automatic indexes */
drhaa32e3c2013-07-16 21:31:23 +00004414 if( !pBuilder->pOrSet
drh4fe425a2013-06-12 17:08:06 +00004415 && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
4416 && pSrc->pIndex==0
drheb04de32013-05-10 15:16:30 +00004417 && !pSrc->viaCoroutine
4418 && !pSrc->notIndexed
drhec95c442013-10-23 01:57:32 +00004419 && HasRowid(pTab)
drheb04de32013-05-10 15:16:30 +00004420 && !pSrc->isCorrelated
dan62ba4e42014-01-15 18:21:41 +00004421 && !pSrc->isRecursive
drheb04de32013-05-10 15:16:30 +00004422 ){
4423 /* Generate auto-index WhereLoops */
drheb04de32013-05-10 15:16:30 +00004424 WhereTerm *pTerm;
4425 WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
4426 for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
drh79a13bf2013-05-31 20:28:28 +00004427 if( pTerm->prereqRight & pNew->maskSelf ) continue;
drheb04de32013-05-10 15:16:30 +00004428 if( termCanDriveIndex(pTerm, pSrc, 0) ){
4429 pNew->u.btree.nEq = 1;
drhcd8629e2013-11-13 12:27:25 +00004430 pNew->u.btree.nSkip = 0;
drhef866372013-05-22 20:49:02 +00004431 pNew->u.btree.pIndex = 0;
drh4efc9292013-06-06 23:02:03 +00004432 pNew->nLTerm = 1;
4433 pNew->aLTerm[0] = pTerm;
drhe1e2e9a2013-06-13 15:16:53 +00004434 /* TUNING: One-time cost for computing the automatic index is
drh986b3872013-06-28 21:12:20 +00004435 ** approximately 7*N*log2(N) where N is the number of rows in
drhe1e2e9a2013-06-13 15:16:53 +00004436 ** the table being indexed. */
drhbf539c42013-10-05 18:16:02 +00004437 pNew->rSetup = rLogSize + rSize + 28; assert( 28==sqlite3LogEst(7) );
drh986b3872013-06-28 21:12:20 +00004438 /* TUNING: Each index lookup yields 20 rows in the table. This
4439 ** is more than the usual guess of 10 rows, since we have no way
4440 ** of knowning how selective the index will ultimately be. It would
4441 ** not be unreasonable to make this value much larger. */
drhbf539c42013-10-05 18:16:02 +00004442 pNew->nOut = 43; assert( 43==sqlite3LogEst(20) );
drhb50596d2013-10-08 20:42:41 +00004443 pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut);
drh986b3872013-06-28 21:12:20 +00004444 pNew->wsFlags = WHERE_AUTO_INDEX;
drheb04de32013-05-10 15:16:30 +00004445 pNew->prereq = mExtra | pTerm->prereqRight;
drhcf8fa7a2013-05-10 20:26:22 +00004446 rc = whereLoopInsert(pBuilder, pNew);
drheb04de32013-05-10 15:16:30 +00004447 }
4448 }
4449 }
drhfeb56e02013-08-23 17:33:46 +00004450#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
drh1c8148f2013-05-04 20:25:23 +00004451
4452 /* Loop over all indices
4453 */
drh23f98da2013-05-21 15:52:07 +00004454 for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){
drh4bd5f732013-07-31 23:22:39 +00004455 if( pProbe->pPartIdxWhere!=0
4456 && !whereUsablePartialIndex(pNew->iTab, pWC, pProbe->pPartIdxWhere) ){
4457 continue; /* Partial index inappropriate for this query */
4458 }
dan7de2a1f2014-04-28 20:11:20 +00004459 rSize = pProbe->aiRowLogEst[0];
drh5346e952013-05-08 14:14:26 +00004460 pNew->u.btree.nEq = 0;
drhcd8629e2013-11-13 12:27:25 +00004461 pNew->u.btree.nSkip = 0;
drh4efc9292013-06-06 23:02:03 +00004462 pNew->nLTerm = 0;
drh23f98da2013-05-21 15:52:07 +00004463 pNew->iSortIdx = 0;
drhb8a8e8a2013-06-10 19:12:39 +00004464 pNew->rSetup = 0;
drh23f98da2013-05-21 15:52:07 +00004465 pNew->prereq = mExtra;
drh74f91d42013-06-19 18:01:44 +00004466 pNew->nOut = rSize;
drh23f98da2013-05-21 15:52:07 +00004467 pNew->u.btree.pIndex = pProbe;
4468 b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
drh53cfbe92013-06-13 17:28:22 +00004469 /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
4470 assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
drh43fe25f2013-05-07 23:06:23 +00004471 if( pProbe->tnum<=0 ){
4472 /* Integer primary key index */
4473 pNew->wsFlags = WHERE_IPK;
drh23f98da2013-05-21 15:52:07 +00004474
4475 /* Full table scan */
drhd044d202013-05-31 12:43:55 +00004476 pNew->iSortIdx = b ? iSortIdx : 0;
danaa9933c2014-04-24 20:04:49 +00004477 /* TUNING: Cost of full table scan is (N*3.0). */
4478 pNew->rRun = rSize + 16;
drh4f991892013-10-11 15:05:05 +00004479 whereLoopOutputAdjust(pWC, pNew);
drh23f98da2013-05-21 15:52:07 +00004480 rc = whereLoopInsert(pBuilder, pNew);
drhcca9f3d2013-09-06 15:23:29 +00004481 pNew->nOut = rSize;
drh23f98da2013-05-21 15:52:07 +00004482 if( rc ) break;
drh43fe25f2013-05-07 23:06:23 +00004483 }else{
drhec95c442013-10-23 01:57:32 +00004484 Bitmask m;
4485 if( pProbe->isCovering ){
4486 pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
4487 m = 0;
4488 }else{
4489 m = pSrc->colUsed & ~columnsInIndex(pProbe);
4490 pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
4491 }
drh1c8148f2013-05-04 20:25:23 +00004492
drh23f98da2013-05-21 15:52:07 +00004493 /* Full scan via index */
drh53cfbe92013-06-13 17:28:22 +00004494 if( b
drh702ba9f2013-11-07 21:25:13 +00004495 || !HasRowid(pTab)
drh53cfbe92013-06-13 17:28:22 +00004496 || ( m==0
4497 && pProbe->bUnordered==0
drh702ba9f2013-11-07 21:25:13 +00004498 && (pProbe->szIdxRow<pTab->szTabRow)
drh53cfbe92013-06-13 17:28:22 +00004499 && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
4500 && sqlite3GlobalConfig.bUseCis
4501 && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
4502 )
drhe3b7c922013-06-03 19:17:40 +00004503 ){
drh23f98da2013-05-21 15:52:07 +00004504 pNew->iSortIdx = b ? iSortIdx : 0;
danaa9933c2014-04-24 20:04:49 +00004505
4506 /* The cost of visiting the index rows is N*K, where K is
4507 ** between 1.1 and 3.0, depending on the relative sizes of the
4508 ** index and table rows. If this is a non-covering index scan,
4509 ** also add the cost of visiting table rows (N*3.0). */
4510 pNew->rRun = rSize + 1 + (15*pProbe->szIdxRow)/pTab->szTabRow;
4511 if( m!=0 ){
4512 pNew->rRun = sqlite3LogEstAdd(pNew->rRun, rSize+16);
drhe1e2e9a2013-06-13 15:16:53 +00004513 }
danaa9933c2014-04-24 20:04:49 +00004514
drh4f991892013-10-11 15:05:05 +00004515 whereLoopOutputAdjust(pWC, pNew);
drh23f98da2013-05-21 15:52:07 +00004516 rc = whereLoopInsert(pBuilder, pNew);
drhcca9f3d2013-09-06 15:23:29 +00004517 pNew->nOut = rSize;
drh23f98da2013-05-21 15:52:07 +00004518 if( rc ) break;
4519 }
4520 }
dan7a419232013-08-06 20:01:43 +00004521
drhb8a8e8a2013-06-10 19:12:39 +00004522 rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
drh1435a9a2013-08-27 23:15:44 +00004523#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
dan87cd9322013-08-07 15:52:41 +00004524 sqlite3Stat4ProbeFree(pBuilder->pRec);
4525 pBuilder->nRecValid = 0;
4526 pBuilder->pRec = 0;
danddc2d6e2013-08-06 20:15:06 +00004527#endif
drh1c8148f2013-05-04 20:25:23 +00004528
4529 /* If there was an INDEXED BY clause, then only that one index is
4530 ** considered. */
4531 if( pSrc->pIndex ) break;
4532 }
drh5346e952013-05-08 14:14:26 +00004533 return rc;
drhf1b5f5b2013-05-02 00:15:01 +00004534}
4535
drh8636e9c2013-06-11 01:50:08 +00004536#ifndef SQLITE_OMIT_VIRTUALTABLE
drhf1b5f5b2013-05-02 00:15:01 +00004537/*
drh0823c892013-05-11 00:06:23 +00004538** Add all WhereLoop objects for a table of the join identified by
4539** pBuilder->pNew->iTab. That table is guaranteed to be a virtual table.
drhf1b5f5b2013-05-02 00:15:01 +00004540*/
drh5346e952013-05-08 14:14:26 +00004541static int whereLoopAddVirtual(
danff4b23b2013-11-12 12:17:16 +00004542 WhereLoopBuilder *pBuilder, /* WHERE clause information */
4543 Bitmask mExtra
drhf1b5f5b2013-05-02 00:15:01 +00004544){
drh70d18342013-06-06 19:16:33 +00004545 WhereInfo *pWInfo; /* WHERE analysis context */
drh5346e952013-05-08 14:14:26 +00004546 Parse *pParse; /* The parsing context */
4547 WhereClause *pWC; /* The WHERE clause */
4548 struct SrcList_item *pSrc; /* The FROM clause term to search */
4549 Table *pTab;
4550 sqlite3 *db;
4551 sqlite3_index_info *pIdxInfo;
4552 struct sqlite3_index_constraint *pIdxCons;
4553 struct sqlite3_index_constraint_usage *pUsage;
4554 WhereTerm *pTerm;
4555 int i, j;
4556 int iTerm, mxTerm;
drh4efc9292013-06-06 23:02:03 +00004557 int nConstraint;
drh5346e952013-05-08 14:14:26 +00004558 int seenIn = 0; /* True if an IN operator is seen */
4559 int seenVar = 0; /* True if a non-constant constraint is seen */
4560 int iPhase; /* 0: const w/o IN, 1: const, 2: no IN, 2: IN */
4561 WhereLoop *pNew;
drh5346e952013-05-08 14:14:26 +00004562 int rc = SQLITE_OK;
4563
drh70d18342013-06-06 19:16:33 +00004564 pWInfo = pBuilder->pWInfo;
4565 pParse = pWInfo->pParse;
drh5346e952013-05-08 14:14:26 +00004566 db = pParse->db;
4567 pWC = pBuilder->pWC;
drh5346e952013-05-08 14:14:26 +00004568 pNew = pBuilder->pNew;
drh70d18342013-06-06 19:16:33 +00004569 pSrc = &pWInfo->pTabList->a[pNew->iTab];
drhb2a90f02013-05-10 03:30:49 +00004570 pTab = pSrc->pTab;
drh0823c892013-05-11 00:06:23 +00004571 assert( IsVirtual(pTab) );
drhb2a90f02013-05-10 03:30:49 +00004572 pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pBuilder->pOrderBy);
drh5346e952013-05-08 14:14:26 +00004573 if( pIdxInfo==0 ) return SQLITE_NOMEM;
drh5346e952013-05-08 14:14:26 +00004574 pNew->prereq = 0;
drh5346e952013-05-08 14:14:26 +00004575 pNew->rSetup = 0;
4576 pNew->wsFlags = WHERE_VIRTUALTABLE;
drh4efc9292013-06-06 23:02:03 +00004577 pNew->nLTerm = 0;
drh5346e952013-05-08 14:14:26 +00004578 pNew->u.vtab.needFree = 0;
4579 pUsage = pIdxInfo->aConstraintUsage;
drh4efc9292013-06-06 23:02:03 +00004580 nConstraint = pIdxInfo->nConstraint;
drh7963b0e2013-06-17 21:37:40 +00004581 if( whereLoopResize(db, pNew, nConstraint) ){
4582 sqlite3DbFree(db, pIdxInfo);
4583 return SQLITE_NOMEM;
4584 }
drh5346e952013-05-08 14:14:26 +00004585
drh0823c892013-05-11 00:06:23 +00004586 for(iPhase=0; iPhase<=3; iPhase++){
drh5346e952013-05-08 14:14:26 +00004587 if( !seenIn && (iPhase&1)!=0 ){
4588 iPhase++;
4589 if( iPhase>3 ) break;
4590 }
4591 if( !seenVar && iPhase>1 ) break;
4592 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
4593 for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
4594 j = pIdxCons->iTermOffset;
4595 pTerm = &pWC->a[j];
4596 switch( iPhase ){
4597 case 0: /* Constants without IN operator */
4598 pIdxCons->usable = 0;
4599 if( (pTerm->eOperator & WO_IN)!=0 ){
4600 seenIn = 1;
drh7963b0e2013-06-17 21:37:40 +00004601 }
4602 if( pTerm->prereqRight!=0 ){
drh5346e952013-05-08 14:14:26 +00004603 seenVar = 1;
drh7963b0e2013-06-17 21:37:40 +00004604 }else if( (pTerm->eOperator & WO_IN)==0 ){
drh5346e952013-05-08 14:14:26 +00004605 pIdxCons->usable = 1;
4606 }
4607 break;
4608 case 1: /* Constants with IN operators */
4609 assert( seenIn );
4610 pIdxCons->usable = (pTerm->prereqRight==0);
4611 break;
4612 case 2: /* Variables without IN */
4613 assert( seenVar );
4614 pIdxCons->usable = (pTerm->eOperator & WO_IN)==0;
4615 break;
4616 default: /* Variables with IN */
4617 assert( seenVar && seenIn );
4618 pIdxCons->usable = 1;
4619 break;
4620 }
4621 }
4622 memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
4623 if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
4624 pIdxInfo->idxStr = 0;
4625 pIdxInfo->idxNum = 0;
4626 pIdxInfo->needToFreeIdxStr = 0;
4627 pIdxInfo->orderByConsumed = 0;
drh8636e9c2013-06-11 01:50:08 +00004628 pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
dana9f58152013-11-11 19:01:33 +00004629 pIdxInfo->estimatedRows = 25;
drh5346e952013-05-08 14:14:26 +00004630 rc = vtabBestIndex(pParse, pTab, pIdxInfo);
4631 if( rc ) goto whereLoopAddVtab_exit;
4632 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
danff4b23b2013-11-12 12:17:16 +00004633 pNew->prereq = mExtra;
drhc718f1c2013-05-08 20:05:58 +00004634 mxTerm = -1;
drh4efc9292013-06-06 23:02:03 +00004635 assert( pNew->nLSlot>=nConstraint );
4636 for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
drh3bd26f02013-05-24 14:52:03 +00004637 pNew->u.vtab.omitMask = 0;
drh4efc9292013-06-06 23:02:03 +00004638 for(i=0; i<nConstraint; i++, pIdxCons++){
drh5346e952013-05-08 14:14:26 +00004639 if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
4640 j = pIdxCons->iTermOffset;
drh4efc9292013-06-06 23:02:03 +00004641 if( iTerm>=nConstraint
drh5346e952013-05-08 14:14:26 +00004642 || j<0
4643 || j>=pWC->nTerm
drh4efc9292013-06-06 23:02:03 +00004644 || pNew->aLTerm[iTerm]!=0
drh5346e952013-05-08 14:14:26 +00004645 ){
4646 rc = SQLITE_ERROR;
4647 sqlite3ErrorMsg(pParse, "%s.xBestIndex() malfunction", pTab->zName);
4648 goto whereLoopAddVtab_exit;
4649 }
drh7963b0e2013-06-17 21:37:40 +00004650 testcase( iTerm==nConstraint-1 );
4651 testcase( j==0 );
4652 testcase( j==pWC->nTerm-1 );
drh5346e952013-05-08 14:14:26 +00004653 pTerm = &pWC->a[j];
4654 pNew->prereq |= pTerm->prereqRight;
drh4efc9292013-06-06 23:02:03 +00004655 assert( iTerm<pNew->nLSlot );
4656 pNew->aLTerm[iTerm] = pTerm;
drh5346e952013-05-08 14:14:26 +00004657 if( iTerm>mxTerm ) mxTerm = iTerm;
drh7963b0e2013-06-17 21:37:40 +00004658 testcase( iTerm==15 );
4659 testcase( iTerm==16 );
drh52986302013-06-03 16:03:16 +00004660 if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm;
drh5346e952013-05-08 14:14:26 +00004661 if( (pTerm->eOperator & WO_IN)!=0 ){
4662 if( pUsage[i].omit==0 ){
4663 /* Do not attempt to use an IN constraint if the virtual table
4664 ** says that the equivalent EQ constraint cannot be safely omitted.
4665 ** If we do attempt to use such a constraint, some rows might be
4666 ** repeated in the output. */
4667 break;
4668 }
4669 /* A virtual table that is constrained by an IN clause may not
4670 ** consume the ORDER BY clause because (1) the order of IN terms
4671 ** is not necessarily related to the order of output terms and
4672 ** (2) Multiple outputs from a single IN value will not merge
4673 ** together. */
4674 pIdxInfo->orderByConsumed = 0;
4675 }
4676 }
4677 }
drh4efc9292013-06-06 23:02:03 +00004678 if( i>=nConstraint ){
4679 pNew->nLTerm = mxTerm+1;
4680 assert( pNew->nLTerm<=pNew->nLSlot );
drh5346e952013-05-08 14:14:26 +00004681 pNew->u.vtab.idxNum = pIdxInfo->idxNum;
4682 pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
4683 pIdxInfo->needToFreeIdxStr = 0;
4684 pNew->u.vtab.idxStr = pIdxInfo->idxStr;
drh0401ace2014-03-18 15:30:27 +00004685 pNew->u.vtab.isOrdered = (i8)(pIdxInfo->orderByConsumed ?
4686 pIdxInfo->nOrderBy : 0);
drhb8a8e8a2013-06-10 19:12:39 +00004687 pNew->rSetup = 0;
drhb50596d2013-10-08 20:42:41 +00004688 pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost);
dana9f58152013-11-11 19:01:33 +00004689 pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows);
drhcf8fa7a2013-05-10 20:26:22 +00004690 whereLoopInsert(pBuilder, pNew);
drh5346e952013-05-08 14:14:26 +00004691 if( pNew->u.vtab.needFree ){
4692 sqlite3_free(pNew->u.vtab.idxStr);
4693 pNew->u.vtab.needFree = 0;
4694 }
4695 }
4696 }
4697
4698whereLoopAddVtab_exit:
4699 if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
4700 sqlite3DbFree(db, pIdxInfo);
4701 return rc;
drhf1b5f5b2013-05-02 00:15:01 +00004702}
drh8636e9c2013-06-11 01:50:08 +00004703#endif /* SQLITE_OMIT_VIRTUALTABLE */
drhf1b5f5b2013-05-02 00:15:01 +00004704
4705/*
drhcf8fa7a2013-05-10 20:26:22 +00004706** Add WhereLoop entries to handle OR terms. This works for either
4707** btrees or virtual tables.
4708*/
4709static int whereLoopAddOr(WhereLoopBuilder *pBuilder, Bitmask mExtra){
drh70d18342013-06-06 19:16:33 +00004710 WhereInfo *pWInfo = pBuilder->pWInfo;
drhcf8fa7a2013-05-10 20:26:22 +00004711 WhereClause *pWC;
4712 WhereLoop *pNew;
4713 WhereTerm *pTerm, *pWCEnd;
4714 int rc = SQLITE_OK;
4715 int iCur;
4716 WhereClause tempWC;
4717 WhereLoopBuilder sSubBuild;
drhaa32e3c2013-07-16 21:31:23 +00004718 WhereOrSet sSum, sCur, sPrev;
drhcf8fa7a2013-05-10 20:26:22 +00004719 struct SrcList_item *pItem;
4720
drhcf8fa7a2013-05-10 20:26:22 +00004721 pWC = pBuilder->pWC;
drh70d18342013-06-06 19:16:33 +00004722 if( pWInfo->wctrlFlags & WHERE_AND_ONLY ) return SQLITE_OK;
drhcf8fa7a2013-05-10 20:26:22 +00004723 pWCEnd = pWC->a + pWC->nTerm;
4724 pNew = pBuilder->pNew;
drh77dfd5b2013-08-19 11:15:48 +00004725 memset(&sSum, 0, sizeof(sSum));
drh186ad8c2013-10-08 18:40:37 +00004726 pItem = pWInfo->pTabList->a + pNew->iTab;
drhd4ddae92013-11-06 12:05:57 +00004727 if( !HasRowid(pItem->pTab) ) return SQLITE_OK;
drh186ad8c2013-10-08 18:40:37 +00004728 iCur = pItem->iCursor;
drhcf8fa7a2013-05-10 20:26:22 +00004729
4730 for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
4731 if( (pTerm->eOperator & WO_OR)!=0
4732 && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
4733 ){
4734 WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
4735 WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
4736 WhereTerm *pOrTerm;
drhaa32e3c2013-07-16 21:31:23 +00004737 int once = 1;
4738 int i, j;
drh783dece2013-06-05 17:53:43 +00004739
drh783dece2013-06-05 17:53:43 +00004740 sSubBuild = *pBuilder;
4741 sSubBuild.pOrderBy = 0;
drhaa32e3c2013-07-16 21:31:23 +00004742 sSubBuild.pOrSet = &sCur;
drhcf8fa7a2013-05-10 20:26:22 +00004743
drhc7f0d222013-06-19 03:27:12 +00004744 for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
drh783dece2013-06-05 17:53:43 +00004745 if( (pOrTerm->eOperator & WO_AND)!=0 ){
drhcf8fa7a2013-05-10 20:26:22 +00004746 sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
4747 }else if( pOrTerm->leftCursor==iCur ){
drh70d18342013-06-06 19:16:33 +00004748 tempWC.pWInfo = pWC->pWInfo;
drh783dece2013-06-05 17:53:43 +00004749 tempWC.pOuter = pWC;
4750 tempWC.op = TK_AND;
drh783dece2013-06-05 17:53:43 +00004751 tempWC.nTerm = 1;
drhcf8fa7a2013-05-10 20:26:22 +00004752 tempWC.a = pOrTerm;
4753 sSubBuild.pWC = &tempWC;
4754 }else{
4755 continue;
4756 }
drhaa32e3c2013-07-16 21:31:23 +00004757 sCur.n = 0;
drh8636e9c2013-06-11 01:50:08 +00004758#ifndef SQLITE_OMIT_VIRTUALTABLE
drhcf8fa7a2013-05-10 20:26:22 +00004759 if( IsVirtual(pItem->pTab) ){
danff4b23b2013-11-12 12:17:16 +00004760 rc = whereLoopAddVirtual(&sSubBuild, mExtra);
drh8636e9c2013-06-11 01:50:08 +00004761 }else
4762#endif
4763 {
drhcf8fa7a2013-05-10 20:26:22 +00004764 rc = whereLoopAddBtree(&sSubBuild, mExtra);
4765 }
drhaa32e3c2013-07-16 21:31:23 +00004766 assert( rc==SQLITE_OK || sCur.n==0 );
4767 if( sCur.n==0 ){
4768 sSum.n = 0;
4769 break;
4770 }else if( once ){
4771 whereOrMove(&sSum, &sCur);
4772 once = 0;
4773 }else{
4774 whereOrMove(&sPrev, &sSum);
4775 sSum.n = 0;
4776 for(i=0; i<sPrev.n; i++){
4777 for(j=0; j<sCur.n; j++){
4778 whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,
drhbf539c42013-10-05 18:16:02 +00004779 sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
4780 sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
drhaa32e3c2013-07-16 21:31:23 +00004781 }
4782 }
4783 }
drhcf8fa7a2013-05-10 20:26:22 +00004784 }
drhaa32e3c2013-07-16 21:31:23 +00004785 pNew->nLTerm = 1;
4786 pNew->aLTerm[0] = pTerm;
4787 pNew->wsFlags = WHERE_MULTI_OR;
4788 pNew->rSetup = 0;
4789 pNew->iSortIdx = 0;
4790 memset(&pNew->u, 0, sizeof(pNew->u));
4791 for(i=0; rc==SQLITE_OK && i<sSum.n; i++){
danaa9933c2014-04-24 20:04:49 +00004792 pNew->rRun = sSum.a[i].rRun;
drhaa32e3c2013-07-16 21:31:23 +00004793 pNew->nOut = sSum.a[i].nOut;
4794 pNew->prereq = sSum.a[i].prereq;
drhfd5874d2013-06-12 14:52:39 +00004795 rc = whereLoopInsert(pBuilder, pNew);
4796 }
drhcf8fa7a2013-05-10 20:26:22 +00004797 }
4798 }
4799 return rc;
4800}
4801
4802/*
drhf1b5f5b2013-05-02 00:15:01 +00004803** Add all WhereLoop objects for all tables
4804*/
drh5346e952013-05-08 14:14:26 +00004805static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
drh70d18342013-06-06 19:16:33 +00004806 WhereInfo *pWInfo = pBuilder->pWInfo;
drhf1b5f5b2013-05-02 00:15:01 +00004807 Bitmask mExtra = 0;
4808 Bitmask mPrior = 0;
4809 int iTab;
drh70d18342013-06-06 19:16:33 +00004810 SrcList *pTabList = pWInfo->pTabList;
drhf1b5f5b2013-05-02 00:15:01 +00004811 struct SrcList_item *pItem;
drh70d18342013-06-06 19:16:33 +00004812 sqlite3 *db = pWInfo->pParse->db;
4813 int nTabList = pWInfo->nLevel;
drh5346e952013-05-08 14:14:26 +00004814 int rc = SQLITE_OK;
drhc63367e2013-06-10 20:46:50 +00004815 u8 priorJoinType = 0;
drhb8a8e8a2013-06-10 19:12:39 +00004816 WhereLoop *pNew;
drhf1b5f5b2013-05-02 00:15:01 +00004817
4818 /* Loop over the tables in the join, from left to right */
drhb8a8e8a2013-06-10 19:12:39 +00004819 pNew = pBuilder->pNew;
drha2014152013-06-07 00:29:23 +00004820 whereLoopInit(pNew);
drha18f3d22013-05-08 03:05:41 +00004821 for(iTab=0, pItem=pTabList->a; iTab<nTabList; iTab++, pItem++){
drhb2a90f02013-05-10 03:30:49 +00004822 pNew->iTab = iTab;
drh70d18342013-06-06 19:16:33 +00004823 pNew->maskSelf = getMask(&pWInfo->sMaskSet, pItem->iCursor);
drhc63367e2013-06-10 20:46:50 +00004824 if( ((pItem->jointype|priorJoinType) & (JT_LEFT|JT_CROSS))!=0 ){
drhf1b5f5b2013-05-02 00:15:01 +00004825 mExtra = mPrior;
4826 }
drhc63367e2013-06-10 20:46:50 +00004827 priorJoinType = pItem->jointype;
drhb2a90f02013-05-10 03:30:49 +00004828 if( IsVirtual(pItem->pTab) ){
danff4b23b2013-11-12 12:17:16 +00004829 rc = whereLoopAddVirtual(pBuilder, mExtra);
drhb2a90f02013-05-10 03:30:49 +00004830 }else{
4831 rc = whereLoopAddBtree(pBuilder, mExtra);
4832 }
drhb2a90f02013-05-10 03:30:49 +00004833 if( rc==SQLITE_OK ){
4834 rc = whereLoopAddOr(pBuilder, mExtra);
4835 }
drhb2a90f02013-05-10 03:30:49 +00004836 mPrior |= pNew->maskSelf;
drh5346e952013-05-08 14:14:26 +00004837 if( rc || db->mallocFailed ) break;
drhf1b5f5b2013-05-02 00:15:01 +00004838 }
drha2014152013-06-07 00:29:23 +00004839 whereLoopClear(db, pNew);
drh5346e952013-05-08 14:14:26 +00004840 return rc;
drhf1b5f5b2013-05-02 00:15:01 +00004841}
4842
drha18f3d22013-05-08 03:05:41 +00004843/*
drh7699d1c2013-06-04 12:42:29 +00004844** Examine a WherePath (with the addition of the extra WhereLoop of the 5th
drh319f6772013-05-14 15:31:07 +00004845** parameters) to see if it outputs rows in the requested ORDER BY
drh0401ace2014-03-18 15:30:27 +00004846** (or GROUP BY) without requiring a separate sort operation. Return N:
drh319f6772013-05-14 15:31:07 +00004847**
drh0401ace2014-03-18 15:30:27 +00004848** N>0: N terms of the ORDER BY clause are satisfied
4849** N==0: No terms of the ORDER BY clause are satisfied
4850** N<0: Unknown yet how many terms of ORDER BY might be satisfied.
drh319f6772013-05-14 15:31:07 +00004851**
drh94433422013-07-01 11:05:50 +00004852** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
4853** strict. With GROUP BY and DISTINCT the only requirement is that
4854** equivalent rows appear immediately adjacent to one another. GROUP BY
dan374cd782014-04-21 13:21:56 +00004855** and DISTINCT do not require rows to appear in any particular order as long
drh94433422013-07-01 11:05:50 +00004856** as equivelent rows are grouped together. Thus for GROUP BY and DISTINCT
4857** the pOrderBy terms can be matched in any order. With ORDER BY, the
4858** pOrderBy terms must be matched in strict left-to-right order.
drh6b7157b2013-05-10 02:00:35 +00004859*/
drh0401ace2014-03-18 15:30:27 +00004860static i8 wherePathSatisfiesOrderBy(
drh6b7157b2013-05-10 02:00:35 +00004861 WhereInfo *pWInfo, /* The WHERE clause */
drh4f402f22013-06-11 18:59:38 +00004862 ExprList *pOrderBy, /* ORDER BY or GROUP BY or DISTINCT clause to check */
drh6b7157b2013-05-10 02:00:35 +00004863 WherePath *pPath, /* The WherePath to check */
drh4f402f22013-06-11 18:59:38 +00004864 u16 wctrlFlags, /* Might contain WHERE_GROUPBY or WHERE_DISTINCTBY */
4865 u16 nLoop, /* Number of entries in pPath->aLoop[] */
drh319f6772013-05-14 15:31:07 +00004866 WhereLoop *pLast, /* Add this WhereLoop to the end of pPath->aLoop[] */
drh4f402f22013-06-11 18:59:38 +00004867 Bitmask *pRevMask /* OUT: Mask of WhereLoops to run in reverse order */
drh6b7157b2013-05-10 02:00:35 +00004868){
drh88da6442013-05-27 17:59:37 +00004869 u8 revSet; /* True if rev is known */
4870 u8 rev; /* Composite sort order */
4871 u8 revIdx; /* Index sort order */
drhe353ee32013-06-04 23:40:53 +00004872 u8 isOrderDistinct; /* All prior WhereLoops are order-distinct */
4873 u8 distinctColumns; /* True if the loop has UNIQUE NOT NULL columns */
4874 u8 isMatch; /* iColumn matches a term of the ORDER BY clause */
drh416846a2013-11-06 12:56:04 +00004875 u16 nKeyCol; /* Number of key columns in pIndex */
4876 u16 nColumn; /* Total number of ordered columns in the index */
drh7699d1c2013-06-04 12:42:29 +00004877 u16 nOrderBy; /* Number terms in the ORDER BY clause */
4878 int iLoop; /* Index of WhereLoop in pPath being processed */
4879 int i, j; /* Loop counters */
4880 int iCur; /* Cursor number for current WhereLoop */
4881 int iColumn; /* A column number within table iCur */
drhe8ae5832013-06-19 13:32:46 +00004882 WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
drh7699d1c2013-06-04 12:42:29 +00004883 WhereTerm *pTerm; /* A single term of the WHERE clause */
4884 Expr *pOBExpr; /* An expression from the ORDER BY clause */
4885 CollSeq *pColl; /* COLLATE function from an ORDER BY clause term */
4886 Index *pIndex; /* The index associated with pLoop */
4887 sqlite3 *db = pWInfo->pParse->db; /* Database connection */
4888 Bitmask obSat = 0; /* Mask of ORDER BY terms satisfied so far */
4889 Bitmask obDone; /* Mask of all ORDER BY terms */
drhe353ee32013-06-04 23:40:53 +00004890 Bitmask orderDistinctMask; /* Mask of all well-ordered loops */
drhb8916be2013-06-14 02:51:48 +00004891 Bitmask ready; /* Mask of inner loops */
drh319f6772013-05-14 15:31:07 +00004892
4893 /*
drh7699d1c2013-06-04 12:42:29 +00004894 ** We say the WhereLoop is "one-row" if it generates no more than one
4895 ** row of output. A WhereLoop is one-row if all of the following are true:
drh319f6772013-05-14 15:31:07 +00004896 ** (a) All index columns match with WHERE_COLUMN_EQ.
4897 ** (b) The index is unique
drh7699d1c2013-06-04 12:42:29 +00004898 ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
4899 ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
drh319f6772013-05-14 15:31:07 +00004900 **
drhe353ee32013-06-04 23:40:53 +00004901 ** We say the WhereLoop is "order-distinct" if the set of columns from
4902 ** that WhereLoop that are in the ORDER BY clause are different for every
4903 ** row of the WhereLoop. Every one-row WhereLoop is automatically
4904 ** order-distinct. A WhereLoop that has no columns in the ORDER BY clause
4905 ** is not order-distinct. To be order-distinct is not quite the same as being
4906 ** UNIQUE since a UNIQUE column or index can have multiple rows that
4907 ** are NULL and NULL values are equivalent for the purpose of order-distinct.
4908 ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
4909 **
4910 ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
4911 ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
4912 ** automatically order-distinct.
drh319f6772013-05-14 15:31:07 +00004913 */
4914
4915 assert( pOrderBy!=0 );
drh7699d1c2013-06-04 12:42:29 +00004916 if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
drh319f6772013-05-14 15:31:07 +00004917
drh319f6772013-05-14 15:31:07 +00004918 nOrderBy = pOrderBy->nExpr;
drh7963b0e2013-06-17 21:37:40 +00004919 testcase( nOrderBy==BMS-1 );
drhe353ee32013-06-04 23:40:53 +00004920 if( nOrderBy>BMS-1 ) return 0; /* Cannot optimize overly large ORDER BYs */
4921 isOrderDistinct = 1;
drh7699d1c2013-06-04 12:42:29 +00004922 obDone = MASKBIT(nOrderBy)-1;
drhe353ee32013-06-04 23:40:53 +00004923 orderDistinctMask = 0;
drhb8916be2013-06-14 02:51:48 +00004924 ready = 0;
drhe353ee32013-06-04 23:40:53 +00004925 for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
drhb8916be2013-06-14 02:51:48 +00004926 if( iLoop>0 ) ready |= pLoop->maskSelf;
drh7699d1c2013-06-04 12:42:29 +00004927 pLoop = iLoop<nLoop ? pPath->aLoop[iLoop] : pLast;
drh9dfaf622014-04-25 14:42:17 +00004928 if( pLoop->wsFlags & WHERE_VIRTUALTABLE ){
4929 if( pLoop->u.vtab.isOrdered ) obSat = obDone;
4930 break;
4931 }
drh319f6772013-05-14 15:31:07 +00004932 iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
drhb8916be2013-06-14 02:51:48 +00004933
4934 /* Mark off any ORDER BY term X that is a column in the table of
4935 ** the current loop for which there is term in the WHERE
4936 ** clause of the form X IS NULL or X=? that reference only outer
4937 ** loops.
4938 */
4939 for(i=0; i<nOrderBy; i++){
4940 if( MASKBIT(i) & obSat ) continue;
4941 pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
4942 if( pOBExpr->op!=TK_COLUMN ) continue;
4943 if( pOBExpr->iTable!=iCur ) continue;
4944 pTerm = findTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
4945 ~ready, WO_EQ|WO_ISNULL, 0);
4946 if( pTerm==0 ) continue;
drh7963b0e2013-06-17 21:37:40 +00004947 if( (pTerm->eOperator&WO_EQ)!=0 && pOBExpr->iColumn>=0 ){
drhb8916be2013-06-14 02:51:48 +00004948 const char *z1, *z2;
4949 pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
4950 if( !pColl ) pColl = db->pDfltColl;
4951 z1 = pColl->zName;
4952 pColl = sqlite3ExprCollSeq(pWInfo->pParse, pTerm->pExpr);
4953 if( !pColl ) pColl = db->pDfltColl;
4954 z2 = pColl->zName;
4955 if( sqlite3StrICmp(z1, z2)!=0 ) continue;
4956 }
4957 obSat |= MASKBIT(i);
4958 }
4959
drh7699d1c2013-06-04 12:42:29 +00004960 if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
4961 if( pLoop->wsFlags & WHERE_IPK ){
4962 pIndex = 0;
drhbbbdc832013-10-22 18:01:40 +00004963 nKeyCol = 0;
drh416846a2013-11-06 12:56:04 +00004964 nColumn = 1;
drh7699d1c2013-06-04 12:42:29 +00004965 }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
drh1b0f0262013-05-30 22:27:09 +00004966 return 0;
drh7699d1c2013-06-04 12:42:29 +00004967 }else{
drhbbbdc832013-10-22 18:01:40 +00004968 nKeyCol = pIndex->nKeyCol;
drh416846a2013-11-06 12:56:04 +00004969 nColumn = pIndex->nColumn;
4970 assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) );
4971 assert( pIndex->aiColumn[nColumn-1]==(-1) || !HasRowid(pIndex->pTable));
drhe353ee32013-06-04 23:40:53 +00004972 isOrderDistinct = pIndex->onError!=OE_None;
drh1b0f0262013-05-30 22:27:09 +00004973 }
drh7699d1c2013-06-04 12:42:29 +00004974
drh7699d1c2013-06-04 12:42:29 +00004975 /* Loop through all columns of the index and deal with the ones
4976 ** that are not constrained by == or IN.
4977 */
4978 rev = revSet = 0;
drhe353ee32013-06-04 23:40:53 +00004979 distinctColumns = 0;
drh416846a2013-11-06 12:56:04 +00004980 for(j=0; j<nColumn; j++){
drh7699d1c2013-06-04 12:42:29 +00004981 u8 bOnce; /* True to run the ORDER BY search loop */
4982
drhe353ee32013-06-04 23:40:53 +00004983 /* Skip over == and IS NULL terms */
drh7699d1c2013-06-04 12:42:29 +00004984 if( j<pLoop->u.btree.nEq
drhcd8629e2013-11-13 12:27:25 +00004985 && pLoop->u.btree.nSkip==0
drh4efc9292013-06-06 23:02:03 +00004986 && ((i = pLoop->aLTerm[j]->eOperator) & (WO_EQ|WO_ISNULL))!=0
drh7699d1c2013-06-04 12:42:29 +00004987 ){
drh7963b0e2013-06-17 21:37:40 +00004988 if( i & WO_ISNULL ){
4989 testcase( isOrderDistinct );
4990 isOrderDistinct = 0;
4991 }
drhe353ee32013-06-04 23:40:53 +00004992 continue;
drh7699d1c2013-06-04 12:42:29 +00004993 }
4994
drhe353ee32013-06-04 23:40:53 +00004995 /* Get the column number in the table (iColumn) and sort order
4996 ** (revIdx) for the j-th column of the index.
drh7699d1c2013-06-04 12:42:29 +00004997 */
drh416846a2013-11-06 12:56:04 +00004998 if( pIndex ){
drh7699d1c2013-06-04 12:42:29 +00004999 iColumn = pIndex->aiColumn[j];
5000 revIdx = pIndex->aSortOrder[j];
5001 if( iColumn==pIndex->pTable->iPKey ) iColumn = -1;
drhdc3cd4b2013-05-30 23:21:20 +00005002 }else{
drh7699d1c2013-06-04 12:42:29 +00005003 iColumn = -1;
5004 revIdx = 0;
drhdc3cd4b2013-05-30 23:21:20 +00005005 }
drh7699d1c2013-06-04 12:42:29 +00005006
5007 /* An unconstrained column that might be NULL means that this
drh416846a2013-11-06 12:56:04 +00005008 ** WhereLoop is not well-ordered
drh7699d1c2013-06-04 12:42:29 +00005009 */
drhe353ee32013-06-04 23:40:53 +00005010 if( isOrderDistinct
5011 && iColumn>=0
drh7699d1c2013-06-04 12:42:29 +00005012 && j>=pLoop->u.btree.nEq
5013 && pIndex->pTable->aCol[iColumn].notNull==0
5014 ){
drhe353ee32013-06-04 23:40:53 +00005015 isOrderDistinct = 0;
drh7699d1c2013-06-04 12:42:29 +00005016 }
5017
5018 /* Find the ORDER BY term that corresponds to the j-th column
dan374cd782014-04-21 13:21:56 +00005019 ** of the index and mark that ORDER BY term off
drh7699d1c2013-06-04 12:42:29 +00005020 */
5021 bOnce = 1;
drhe353ee32013-06-04 23:40:53 +00005022 isMatch = 0;
drh7699d1c2013-06-04 12:42:29 +00005023 for(i=0; bOnce && i<nOrderBy; i++){
5024 if( MASKBIT(i) & obSat ) continue;
5025 pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
drh93ec45d2013-06-17 18:20:48 +00005026 testcase( wctrlFlags & WHERE_GROUPBY );
5027 testcase( wctrlFlags & WHERE_DISTINCTBY );
drh4f402f22013-06-11 18:59:38 +00005028 if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
drhe353ee32013-06-04 23:40:53 +00005029 if( pOBExpr->op!=TK_COLUMN ) continue;
drh7699d1c2013-06-04 12:42:29 +00005030 if( pOBExpr->iTable!=iCur ) continue;
5031 if( pOBExpr->iColumn!=iColumn ) continue;
5032 if( iColumn>=0 ){
5033 pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
5034 if( !pColl ) pColl = db->pDfltColl;
5035 if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
5036 }
drhe353ee32013-06-04 23:40:53 +00005037 isMatch = 1;
drh7699d1c2013-06-04 12:42:29 +00005038 break;
5039 }
drh59b8f2e2014-03-22 00:27:14 +00005040 if( isMatch && (pWInfo->wctrlFlags & WHERE_GROUPBY)==0 ){
5041 /* Make sure the sort order is compatible in an ORDER BY clause.
5042 ** Sort order is irrelevant for a GROUP BY clause. */
5043 if( revSet ){
5044 if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) isMatch = 0;
5045 }else{
5046 rev = revIdx ^ pOrderBy->a[i].sortOrder;
5047 if( rev ) *pRevMask |= MASKBIT(iLoop);
5048 revSet = 1;
5049 }
5050 }
drhe353ee32013-06-04 23:40:53 +00005051 if( isMatch ){
drh7963b0e2013-06-17 21:37:40 +00005052 if( iColumn<0 ){
5053 testcase( distinctColumns==0 );
5054 distinctColumns = 1;
5055 }
drh7699d1c2013-06-04 12:42:29 +00005056 obSat |= MASKBIT(i);
drh7699d1c2013-06-04 12:42:29 +00005057 }else{
5058 /* No match found */
drhbbbdc832013-10-22 18:01:40 +00005059 if( j==0 || j<nKeyCol ){
drh7963b0e2013-06-17 21:37:40 +00005060 testcase( isOrderDistinct!=0 );
5061 isOrderDistinct = 0;
5062 }
drh7699d1c2013-06-04 12:42:29 +00005063 break;
5064 }
5065 } /* end Loop over all index columns */
drh81186b42013-06-18 01:52:41 +00005066 if( distinctColumns ){
5067 testcase( isOrderDistinct==0 );
5068 isOrderDistinct = 1;
5069 }
drh7699d1c2013-06-04 12:42:29 +00005070 } /* end-if not one-row */
5071
5072 /* Mark off any other ORDER BY terms that reference pLoop */
drhe353ee32013-06-04 23:40:53 +00005073 if( isOrderDistinct ){
5074 orderDistinctMask |= pLoop->maskSelf;
drh7699d1c2013-06-04 12:42:29 +00005075 for(i=0; i<nOrderBy; i++){
5076 Expr *p;
drh434a9312014-02-26 02:26:09 +00005077 Bitmask mTerm;
drh7699d1c2013-06-04 12:42:29 +00005078 if( MASKBIT(i) & obSat ) continue;
5079 p = pOrderBy->a[i].pExpr;
drh434a9312014-02-26 02:26:09 +00005080 mTerm = exprTableUsage(&pWInfo->sMaskSet,p);
5081 if( mTerm==0 && !sqlite3ExprIsConstant(p) ) continue;
5082 if( (mTerm&~orderDistinctMask)==0 ){
drh7699d1c2013-06-04 12:42:29 +00005083 obSat |= MASKBIT(i);
5084 }
drh0afb4232013-05-31 13:36:32 +00005085 }
drh319f6772013-05-14 15:31:07 +00005086 }
drhb8916be2013-06-14 02:51:48 +00005087 } /* End the loop over all WhereLoops from outer-most down to inner-most */
drh36ed0342014-03-28 12:56:57 +00005088 if( obSat==obDone ) return (i8)nOrderBy;
drhd2de8612014-03-18 18:59:07 +00005089 if( !isOrderDistinct ){
5090 for(i=nOrderBy-1; i>0; i--){
5091 Bitmask m = MASKBIT(i) - 1;
5092 if( (obSat&m)==m ) return i;
5093 }
5094 return 0;
5095 }
drh319f6772013-05-14 15:31:07 +00005096 return -1;
drh6b7157b2013-05-10 02:00:35 +00005097}
5098
dan374cd782014-04-21 13:21:56 +00005099
5100/*
5101** If the WHERE_GROUPBY flag is set in the mask passed to sqlite3WhereBegin(),
5102** the planner assumes that the specified pOrderBy list is actually a GROUP
5103** BY clause - and so any order that groups rows as required satisfies the
5104** request.
5105**
5106** Normally, in this case it is not possible for the caller to determine
5107** whether or not the rows are really being delivered in sorted order, or
5108** just in some other order that provides the required grouping. However,
5109** if the WHERE_SORTBYGROUP flag is also passed to sqlite3WhereBegin(), then
5110** this function may be called on the returned WhereInfo object. It returns
5111** true if the rows really will be sorted in the specified order, or false
5112** otherwise.
5113**
5114** For example, assuming:
5115**
5116** CREATE INDEX i1 ON t1(x, Y);
5117**
5118** then
5119**
5120** SELECT * FROM t1 GROUP BY x,y ORDER BY x,y; -- IsSorted()==1
5121** SELECT * FROM t1 GROUP BY y,x ORDER BY y,x; -- IsSorted()==0
5122*/
5123int sqlite3WhereIsSorted(WhereInfo *pWInfo){
5124 assert( pWInfo->wctrlFlags & WHERE_GROUPBY );
5125 assert( pWInfo->wctrlFlags & WHERE_SORTBYGROUP );
5126 return pWInfo->sorted;
5127}
5128
drhd15cb172013-05-21 19:23:10 +00005129#ifdef WHERETRACE_ENABLED
5130/* For debugging use only: */
5131static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
5132 static char zName[65];
5133 int i;
5134 for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
5135 if( pLast ) zName[i++] = pLast->cId;
5136 zName[i] = 0;
5137 return zName;
5138}
5139#endif
5140
drh6b7157b2013-05-10 02:00:35 +00005141/*
dan51576f42013-07-02 10:06:15 +00005142** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
drha18f3d22013-05-08 03:05:41 +00005143** attempts to find the lowest cost path that visits each WhereLoop
5144** once. This path is then loaded into the pWInfo->a[].pWLoop fields.
5145**
drhc7f0d222013-06-19 03:27:12 +00005146** Assume that the total number of output rows that will need to be sorted
5147** will be nRowEst (in the 10*log2 representation). Or, ignore sorting
5148** costs if nRowEst==0.
5149**
drha18f3d22013-05-08 03:05:41 +00005150** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
5151** error occurs.
5152*/
drhbf539c42013-10-05 18:16:02 +00005153static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
drh783dece2013-06-05 17:53:43 +00005154 int mxChoice; /* Maximum number of simultaneous paths tracked */
drha18f3d22013-05-08 03:05:41 +00005155 int nLoop; /* Number of terms in the join */
drhe1e2e9a2013-06-13 15:16:53 +00005156 Parse *pParse; /* Parsing context */
drha18f3d22013-05-08 03:05:41 +00005157 sqlite3 *db; /* The database connection */
5158 int iLoop; /* Loop counter over the terms of the join */
5159 int ii, jj; /* Loop counters */
drhfde1e6b2013-09-06 17:45:42 +00005160 int mxI = 0; /* Index of next entry to replace */
drhd2de8612014-03-18 18:59:07 +00005161 int nOrderBy; /* Number of ORDER BY clause terms */
drhbf539c42013-10-05 18:16:02 +00005162 LogEst rCost; /* Cost of a path */
5163 LogEst nOut; /* Number of outputs */
5164 LogEst mxCost = 0; /* Maximum cost of a set of paths */
5165 LogEst mxOut = 0; /* Maximum nOut value on the set of paths */
drha18f3d22013-05-08 03:05:41 +00005166 int nTo, nFrom; /* Number of valid entries in aTo[] and aFrom[] */
5167 WherePath *aFrom; /* All nFrom paths at the previous level */
5168 WherePath *aTo; /* The nTo best paths at the current level */
5169 WherePath *pFrom; /* An element of aFrom[] that we are working on */
5170 WherePath *pTo; /* An element of aTo[] that we are working on */
5171 WhereLoop *pWLoop; /* One of the WhereLoop objects */
5172 WhereLoop **pX; /* Used to divy up the pSpace memory */
5173 char *pSpace; /* Temporary memory used by this routine */
5174
drhe1e2e9a2013-06-13 15:16:53 +00005175 pParse = pWInfo->pParse;
5176 db = pParse->db;
drha18f3d22013-05-08 03:05:41 +00005177 nLoop = pWInfo->nLevel;
drhe1e2e9a2013-06-13 15:16:53 +00005178 /* TUNING: For simple queries, only the best path is tracked.
5179 ** For 2-way joins, the 5 best paths are followed.
5180 ** For joins of 3 or more tables, track the 10 best paths */
drhe9d935a2013-06-05 16:19:59 +00005181 mxChoice = (nLoop==1) ? 1 : (nLoop==2 ? 5 : 10);
drha18f3d22013-05-08 03:05:41 +00005182 assert( nLoop<=pWInfo->pTabList->nSrc );
drh3b48e8c2013-06-12 20:18:16 +00005183 WHERETRACE(0x002, ("---- begin solver\n"));
drha18f3d22013-05-08 03:05:41 +00005184
5185 /* Allocate and initialize space for aTo and aFrom */
5186 ii = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
5187 pSpace = sqlite3DbMallocRaw(db, ii);
5188 if( pSpace==0 ) return SQLITE_NOMEM;
5189 aTo = (WherePath*)pSpace;
5190 aFrom = aTo+mxChoice;
5191 memset(aFrom, 0, sizeof(aFrom[0]));
5192 pX = (WhereLoop**)(aFrom+mxChoice);
drhe9d935a2013-06-05 16:19:59 +00005193 for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
drha18f3d22013-05-08 03:05:41 +00005194 pFrom->aLoop = pX;
5195 }
5196
drhe1e2e9a2013-06-13 15:16:53 +00005197 /* Seed the search with a single WherePath containing zero WhereLoops.
5198 **
5199 ** TUNING: Do not let the number of iterations go above 25. If the cost
5200 ** of computing an automatic index is not paid back within the first 25
5201 ** rows, then do not use the automatic index. */
drhbf539c42013-10-05 18:16:02 +00005202 aFrom[0].nRow = MIN(pParse->nQueryLoop, 46); assert( 46==sqlite3LogEst(25) );
drha18f3d22013-05-08 03:05:41 +00005203 nFrom = 1;
drh6b7157b2013-05-10 02:00:35 +00005204
5205 /* Precompute the cost of sorting the final result set, if the caller
5206 ** to sqlite3WhereBegin() was concerned about sorting */
drhb8a8e8a2013-06-10 19:12:39 +00005207 if( pWInfo->pOrderBy==0 || nRowEst==0 ){
drh0401ace2014-03-18 15:30:27 +00005208 aFrom[0].isOrdered = 0;
drhd2de8612014-03-18 18:59:07 +00005209 nOrderBy = 0;
drh6b7157b2013-05-10 02:00:35 +00005210 }else{
drh0401ace2014-03-18 15:30:27 +00005211 aFrom[0].isOrdered = -1;
drhd2de8612014-03-18 18:59:07 +00005212 nOrderBy = pWInfo->pOrderBy->nExpr;
drh6b7157b2013-05-10 02:00:35 +00005213 }
5214
5215 /* Compute successively longer WherePaths using the previous generation
5216 ** of WherePaths as the basis for the next. Keep track of the mxChoice
5217 ** best paths at each generation */
drha18f3d22013-05-08 03:05:41 +00005218 for(iLoop=0; iLoop<nLoop; iLoop++){
5219 nTo = 0;
5220 for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
5221 for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
5222 Bitmask maskNew;
drh319f6772013-05-14 15:31:07 +00005223 Bitmask revMask = 0;
drh0401ace2014-03-18 15:30:27 +00005224 i8 isOrdered = pFrom->isOrdered;
drha18f3d22013-05-08 03:05:41 +00005225 if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
5226 if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
drh6b7157b2013-05-10 02:00:35 +00005227 /* At this point, pWLoop is a candidate to be the next loop.
5228 ** Compute its cost */
drhbf539c42013-10-05 18:16:02 +00005229 rCost = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
5230 rCost = sqlite3LogEstAdd(rCost, pFrom->rCost);
drhfde1e6b2013-09-06 17:45:42 +00005231 nOut = pFrom->nRow + pWLoop->nOut;
drha18f3d22013-05-08 03:05:41 +00005232 maskNew = pFrom->maskLoop | pWLoop->maskSelf;
drh0401ace2014-03-18 15:30:27 +00005233 if( isOrdered<0 ){
5234 isOrdered = wherePathSatisfiesOrderBy(pWInfo,
drh4f402f22013-06-11 18:59:38 +00005235 pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
drh0401ace2014-03-18 15:30:27 +00005236 iLoop, pWLoop, &revMask);
drhd2de8612014-03-18 18:59:07 +00005237 if( isOrdered>=0 && isOrdered<nOrderBy ){
dan4a6b8a02014-04-30 14:47:01 +00005238 /* TUNING: Estimated cost of a full external sort, where N is
5239 ** the number of rows to sort is:
5240 **
5241 ** cost = (3.0 * N * log(N)).
5242 **
5243 ** Or, if the order-by clause has X terms but only the last Y
5244 ** terms are out of order, then block-sorting will reduce the
5245 ** sorting cost to:
5246 **
5247 ** cost = (3.0 * N * log(N)) * (Y/X)
5248 **
5249 ** The (Y/X) term is implemented using stack variable rScale
5250 ** below. */
drh27de5c52014-03-27 18:36:34 +00005251 LogEst rScale, rSortCost;
dan2dd3cdc2014-04-26 20:21:14 +00005252 assert( nOrderBy>0 && 66==sqlite3LogEst(100) );
drh27de5c52014-03-27 18:36:34 +00005253 rScale = sqlite3LogEst((nOrderBy-isOrdered)*100/nOrderBy) - 66;
dan2dd3cdc2014-04-26 20:21:14 +00005254 rSortCost = nRowEst + estLog(nRowEst) + rScale + 16;
5255
drh6284db92014-03-19 23:24:49 +00005256 /* TUNING: The cost of implementing DISTINCT using a B-TREE is
dan4a6b8a02014-04-30 14:47:01 +00005257 ** similar but with a larger constant of proportionality.
5258 ** Multiply by an additional factor of 3.0. */
drh6284db92014-03-19 23:24:49 +00005259 if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
5260 rSortCost += 16;
5261 }
drhd2de8612014-03-18 18:59:07 +00005262 WHERETRACE(0x002,
5263 ("---- sort cost=%-3d (%d/%d) increases cost %3d to %-3d\n",
5264 rSortCost, (nOrderBy-isOrdered), nOrderBy, rCost,
5265 sqlite3LogEstAdd(rCost,rSortCost)));
drh0401ace2014-03-18 15:30:27 +00005266 rCost = sqlite3LogEstAdd(rCost, rSortCost);
drh6b7157b2013-05-10 02:00:35 +00005267 }
drh3a5ba8b2013-06-03 15:34:48 +00005268 }else{
5269 revMask = pFrom->revLoop;
drh6b7157b2013-05-10 02:00:35 +00005270 }
5271 /* Check to see if pWLoop should be added to the mxChoice best so far */
5272 for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
drhfde1e6b2013-09-06 17:45:42 +00005273 if( pTo->maskLoop==maskNew
drh0401ace2014-03-18 15:30:27 +00005274 && ((pTo->isOrdered^isOrdered)&80)==0
drhfde1e6b2013-09-06 17:45:42 +00005275 && ((pTo->rCost<=rCost && pTo->nRow<=nOut) ||
5276 (pTo->rCost>=rCost && pTo->nRow>=nOut))
5277 ){
drh7963b0e2013-06-17 21:37:40 +00005278 testcase( jj==nTo-1 );
drh6b7157b2013-05-10 02:00:35 +00005279 break;
5280 }
5281 }
drha18f3d22013-05-08 03:05:41 +00005282 if( jj>=nTo ){
drh7d9e7d82013-09-11 17:39:09 +00005283 if( nTo>=mxChoice && rCost>=mxCost ){
drh989578e2013-10-28 14:34:35 +00005284#ifdef WHERETRACE_ENABLED /* 0x4 */
drhae70cf12013-05-31 15:18:46 +00005285 if( sqlite3WhereTrace&0x4 ){
drhfde1e6b2013-09-06 17:45:42 +00005286 sqlite3DebugPrintf("Skip %s cost=%-3d,%3d order=%c\n",
5287 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
drh0401ace2014-03-18 15:30:27 +00005288 isOrdered>=0 ? isOrdered+'0' : '?');
drhd15cb172013-05-21 19:23:10 +00005289 }
5290#endif
5291 continue;
5292 }
5293 /* Add a new Path to the aTo[] set */
drha18f3d22013-05-08 03:05:41 +00005294 if( nTo<mxChoice ){
drhd15cb172013-05-21 19:23:10 +00005295 /* Increase the size of the aTo set by one */
drha18f3d22013-05-08 03:05:41 +00005296 jj = nTo++;
5297 }else{
drhd15cb172013-05-21 19:23:10 +00005298 /* New path replaces the prior worst to keep count below mxChoice */
drhfde1e6b2013-09-06 17:45:42 +00005299 jj = mxI;
drha18f3d22013-05-08 03:05:41 +00005300 }
5301 pTo = &aTo[jj];
drh989578e2013-10-28 14:34:35 +00005302#ifdef WHERETRACE_ENABLED /* 0x4 */
drhae70cf12013-05-31 15:18:46 +00005303 if( sqlite3WhereTrace&0x4 ){
drhfde1e6b2013-09-06 17:45:42 +00005304 sqlite3DebugPrintf("New %s cost=%-3d,%3d order=%c\n",
5305 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
drh0401ace2014-03-18 15:30:27 +00005306 isOrdered>=0 ? isOrdered+'0' : '?');
drhd15cb172013-05-21 19:23:10 +00005307 }
5308#endif
drhf204dac2013-05-08 03:22:07 +00005309 }else{
drhfde1e6b2013-09-06 17:45:42 +00005310 if( pTo->rCost<=rCost && pTo->nRow<=nOut ){
drh989578e2013-10-28 14:34:35 +00005311#ifdef WHERETRACE_ENABLED /* 0x4 */
drhae70cf12013-05-31 15:18:46 +00005312 if( sqlite3WhereTrace&0x4 ){
drhd15cb172013-05-21 19:23:10 +00005313 sqlite3DebugPrintf(
drhfde1e6b2013-09-06 17:45:42 +00005314 "Skip %s cost=%-3d,%3d order=%c",
5315 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
drh0401ace2014-03-18 15:30:27 +00005316 isOrdered>=0 ? isOrdered+'0' : '?');
drhfde1e6b2013-09-06 17:45:42 +00005317 sqlite3DebugPrintf(" vs %s cost=%-3d,%d order=%c\n",
5318 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
drh0401ace2014-03-18 15:30:27 +00005319 pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
drhd15cb172013-05-21 19:23:10 +00005320 }
5321#endif
drh7963b0e2013-06-17 21:37:40 +00005322 testcase( pTo->rCost==rCost );
drhd15cb172013-05-21 19:23:10 +00005323 continue;
5324 }
drh7963b0e2013-06-17 21:37:40 +00005325 testcase( pTo->rCost==rCost+1 );
drhd15cb172013-05-21 19:23:10 +00005326 /* A new and better score for a previously created equivalent path */
drh989578e2013-10-28 14:34:35 +00005327#ifdef WHERETRACE_ENABLED /* 0x4 */
drhae70cf12013-05-31 15:18:46 +00005328 if( sqlite3WhereTrace&0x4 ){
drhd15cb172013-05-21 19:23:10 +00005329 sqlite3DebugPrintf(
drhfde1e6b2013-09-06 17:45:42 +00005330 "Update %s cost=%-3d,%3d order=%c",
5331 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
drh0401ace2014-03-18 15:30:27 +00005332 isOrdered>=0 ? isOrdered+'0' : '?');
drhfde1e6b2013-09-06 17:45:42 +00005333 sqlite3DebugPrintf(" was %s cost=%-3d,%3d order=%c\n",
5334 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
drh0401ace2014-03-18 15:30:27 +00005335 pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
drhd15cb172013-05-21 19:23:10 +00005336 }
5337#endif
drha18f3d22013-05-08 03:05:41 +00005338 }
drh6b7157b2013-05-10 02:00:35 +00005339 /* pWLoop is a winner. Add it to the set of best so far */
drha18f3d22013-05-08 03:05:41 +00005340 pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
drh319f6772013-05-14 15:31:07 +00005341 pTo->revLoop = revMask;
drhfde1e6b2013-09-06 17:45:42 +00005342 pTo->nRow = nOut;
drha18f3d22013-05-08 03:05:41 +00005343 pTo->rCost = rCost;
drh6b7157b2013-05-10 02:00:35 +00005344 pTo->isOrdered = isOrdered;
drha18f3d22013-05-08 03:05:41 +00005345 memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
5346 pTo->aLoop[iLoop] = pWLoop;
5347 if( nTo>=mxChoice ){
drhfde1e6b2013-09-06 17:45:42 +00005348 mxI = 0;
drha18f3d22013-05-08 03:05:41 +00005349 mxCost = aTo[0].rCost;
drhfde1e6b2013-09-06 17:45:42 +00005350 mxOut = aTo[0].nRow;
drha18f3d22013-05-08 03:05:41 +00005351 for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
drhfde1e6b2013-09-06 17:45:42 +00005352 if( pTo->rCost>mxCost || (pTo->rCost==mxCost && pTo->nRow>mxOut) ){
5353 mxCost = pTo->rCost;
5354 mxOut = pTo->nRow;
5355 mxI = jj;
5356 }
drha18f3d22013-05-08 03:05:41 +00005357 }
5358 }
5359 }
5360 }
5361
drh989578e2013-10-28 14:34:35 +00005362#ifdef WHERETRACE_ENABLED /* >=2 */
drhd15cb172013-05-21 19:23:10 +00005363 if( sqlite3WhereTrace>=2 ){
drha50ef112013-05-22 02:06:59 +00005364 sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
drhd15cb172013-05-21 19:23:10 +00005365 for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
drhb8a8e8a2013-06-10 19:12:39 +00005366 sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
drha50ef112013-05-22 02:06:59 +00005367 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
drh0401ace2014-03-18 15:30:27 +00005368 pTo->isOrdered>=0 ? (pTo->isOrdered+'0') : '?');
5369 if( pTo->isOrdered>0 ){
drh88da6442013-05-27 17:59:37 +00005370 sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
5371 }else{
5372 sqlite3DebugPrintf("\n");
5373 }
drhf204dac2013-05-08 03:22:07 +00005374 }
5375 }
5376#endif
5377
drh6b7157b2013-05-10 02:00:35 +00005378 /* Swap the roles of aFrom and aTo for the next generation */
drha18f3d22013-05-08 03:05:41 +00005379 pFrom = aTo;
5380 aTo = aFrom;
5381 aFrom = pFrom;
5382 nFrom = nTo;
5383 }
5384
drh75b93402013-05-31 20:43:57 +00005385 if( nFrom==0 ){
drhe1e2e9a2013-06-13 15:16:53 +00005386 sqlite3ErrorMsg(pParse, "no query solution");
drh75b93402013-05-31 20:43:57 +00005387 sqlite3DbFree(db, pSpace);
5388 return SQLITE_ERROR;
5389 }
drha18f3d22013-05-08 03:05:41 +00005390
drh6b7157b2013-05-10 02:00:35 +00005391 /* Find the lowest cost path. pFrom will be left pointing to that path */
drha18f3d22013-05-08 03:05:41 +00005392 pFrom = aFrom;
5393 for(ii=1; ii<nFrom; ii++){
5394 if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
5395 }
5396 assert( pWInfo->nLevel==nLoop );
drh6b7157b2013-05-10 02:00:35 +00005397 /* Load the lowest cost path into pWInfo */
drha18f3d22013-05-08 03:05:41 +00005398 for(iLoop=0; iLoop<nLoop; iLoop++){
drh7ba39a92013-05-30 17:43:19 +00005399 WhereLevel *pLevel = pWInfo->a + iLoop;
5400 pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
drhe217efc2013-06-12 03:48:41 +00005401 pLevel->iFrom = pWLoop->iTab;
drh7ba39a92013-05-30 17:43:19 +00005402 pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
drha18f3d22013-05-08 03:05:41 +00005403 }
drhfd636c72013-06-21 02:05:06 +00005404 if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0
5405 && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
5406 && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
drh4f402f22013-06-11 18:59:38 +00005407 && nRowEst
5408 ){
5409 Bitmask notUsed;
drh6457a352013-06-21 00:35:37 +00005410 int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom,
drh93ec45d2013-06-17 18:20:48 +00005411 WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
drh0401ace2014-03-18 15:30:27 +00005412 if( rc==pWInfo->pResultSet->nExpr ){
5413 pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
5414 }
drh4f402f22013-06-11 18:59:38 +00005415 }
drh079a3072014-03-19 14:10:55 +00005416 if( pWInfo->pOrderBy ){
drh4f402f22013-06-11 18:59:38 +00005417 if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
drh079a3072014-03-19 14:10:55 +00005418 if( pFrom->isOrdered==pWInfo->pOrderBy->nExpr ){
5419 pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
5420 }
drh4f402f22013-06-11 18:59:38 +00005421 }else{
drhddba0c22014-03-18 20:33:42 +00005422 pWInfo->nOBSat = pFrom->isOrdered;
drhea6c36e2014-03-19 14:30:55 +00005423 if( pWInfo->nOBSat<0 ) pWInfo->nOBSat = 0;
drh4f402f22013-06-11 18:59:38 +00005424 pWInfo->revMask = pFrom->revLoop;
5425 }
dan374cd782014-04-21 13:21:56 +00005426 if( (pWInfo->wctrlFlags & WHERE_SORTBYGROUP)
5427 && pWInfo->nOBSat==pWInfo->pOrderBy->nExpr
5428 ){
5429 Bitmask notUsed = 0;
5430 int nOrder = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy,
5431 pFrom, 0, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed
5432 );
5433 assert( pWInfo->sorted==0 );
5434 pWInfo->sorted = (nOrder==pWInfo->pOrderBy->nExpr);
5435 }
drh6b7157b2013-05-10 02:00:35 +00005436 }
dan374cd782014-04-21 13:21:56 +00005437
5438
drha50ef112013-05-22 02:06:59 +00005439 pWInfo->nRowOut = pFrom->nRow;
drha18f3d22013-05-08 03:05:41 +00005440
5441 /* Free temporary memory and return success */
5442 sqlite3DbFree(db, pSpace);
5443 return SQLITE_OK;
5444}
drh75897232000-05-29 14:26:00 +00005445
5446/*
drh60c96cd2013-06-09 17:21:25 +00005447** Most queries use only a single table (they are not joins) and have
5448** simple == constraints against indexed fields. This routine attempts
5449** to plan those simple cases using much less ceremony than the
5450** general-purpose query planner, and thereby yield faster sqlite3_prepare()
5451** times for the common case.
5452**
5453** Return non-zero on success, if this query can be handled by this
5454** no-frills query planner. Return zero if this query needs the
5455** general-purpose query planner.
5456*/
drhb8a8e8a2013-06-10 19:12:39 +00005457static int whereShortCut(WhereLoopBuilder *pBuilder){
drh60c96cd2013-06-09 17:21:25 +00005458 WhereInfo *pWInfo;
5459 struct SrcList_item *pItem;
5460 WhereClause *pWC;
5461 WhereTerm *pTerm;
5462 WhereLoop *pLoop;
5463 int iCur;
drh92a121f2013-06-10 12:15:47 +00005464 int j;
drh60c96cd2013-06-09 17:21:25 +00005465 Table *pTab;
5466 Index *pIdx;
5467
5468 pWInfo = pBuilder->pWInfo;
drh5822d6f2013-06-10 23:30:09 +00005469 if( pWInfo->wctrlFlags & WHERE_FORCE_TABLE ) return 0;
drh60c96cd2013-06-09 17:21:25 +00005470 assert( pWInfo->pTabList->nSrc>=1 );
5471 pItem = pWInfo->pTabList->a;
5472 pTab = pItem->pTab;
5473 if( IsVirtual(pTab) ) return 0;
5474 if( pItem->zIndex ) return 0;
5475 iCur = pItem->iCursor;
5476 pWC = &pWInfo->sWC;
5477 pLoop = pBuilder->pNew;
drh60c96cd2013-06-09 17:21:25 +00005478 pLoop->wsFlags = 0;
drhcd8629e2013-11-13 12:27:25 +00005479 pLoop->u.btree.nSkip = 0;
drh3b75ffa2013-06-10 14:56:25 +00005480 pTerm = findTerm(pWC, iCur, -1, 0, WO_EQ, 0);
drh60c96cd2013-06-09 17:21:25 +00005481 if( pTerm ){
5482 pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
5483 pLoop->aLTerm[0] = pTerm;
5484 pLoop->nLTerm = 1;
5485 pLoop->u.btree.nEq = 1;
drhe1e2e9a2013-06-13 15:16:53 +00005486 /* TUNING: Cost of a rowid lookup is 10 */
drhbf539c42013-10-05 18:16:02 +00005487 pLoop->rRun = 33; /* 33==sqlite3LogEst(10) */
drh60c96cd2013-06-09 17:21:25 +00005488 }else{
5489 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
dancd40abb2013-08-29 10:46:05 +00005490 assert( pLoop->aLTermSpace==pLoop->aLTerm );
5491 assert( ArraySize(pLoop->aLTermSpace)==4 );
5492 if( pIdx->onError==OE_None
5493 || pIdx->pPartIdxWhere!=0
drhbbbdc832013-10-22 18:01:40 +00005494 || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace)
dancd40abb2013-08-29 10:46:05 +00005495 ) continue;
drhbbbdc832013-10-22 18:01:40 +00005496 for(j=0; j<pIdx->nKeyCol; j++){
drh3b75ffa2013-06-10 14:56:25 +00005497 pTerm = findTerm(pWC, iCur, pIdx->aiColumn[j], 0, WO_EQ, pIdx);
drh60c96cd2013-06-09 17:21:25 +00005498 if( pTerm==0 ) break;
drh60c96cd2013-06-09 17:21:25 +00005499 pLoop->aLTerm[j] = pTerm;
5500 }
drhbbbdc832013-10-22 18:01:40 +00005501 if( j!=pIdx->nKeyCol ) continue;
drh92a121f2013-06-10 12:15:47 +00005502 pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
drhec95c442013-10-23 01:57:32 +00005503 if( pIdx->isCovering || (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){
drh92a121f2013-06-10 12:15:47 +00005504 pLoop->wsFlags |= WHERE_IDX_ONLY;
5505 }
drh60c96cd2013-06-09 17:21:25 +00005506 pLoop->nLTerm = j;
5507 pLoop->u.btree.nEq = j;
5508 pLoop->u.btree.pIndex = pIdx;
drhe1e2e9a2013-06-13 15:16:53 +00005509 /* TUNING: Cost of a unique index lookup is 15 */
drhbf539c42013-10-05 18:16:02 +00005510 pLoop->rRun = 39; /* 39==sqlite3LogEst(15) */
drh60c96cd2013-06-09 17:21:25 +00005511 break;
5512 }
5513 }
drh3b75ffa2013-06-10 14:56:25 +00005514 if( pLoop->wsFlags ){
drhbf539c42013-10-05 18:16:02 +00005515 pLoop->nOut = (LogEst)1;
drh3b75ffa2013-06-10 14:56:25 +00005516 pWInfo->a[0].pWLoop = pLoop;
5517 pLoop->maskSelf = getMask(&pWInfo->sMaskSet, iCur);
5518 pWInfo->a[0].iTabCur = iCur;
5519 pWInfo->nRowOut = 1;
drhddba0c22014-03-18 20:33:42 +00005520 if( pWInfo->pOrderBy ) pWInfo->nOBSat = pWInfo->pOrderBy->nExpr;
drh6457a352013-06-21 00:35:37 +00005521 if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
5522 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
5523 }
drh3b75ffa2013-06-10 14:56:25 +00005524#ifdef SQLITE_DEBUG
5525 pLoop->cId = '0';
5526#endif
5527 return 1;
5528 }
5529 return 0;
drh60c96cd2013-06-09 17:21:25 +00005530}
5531
5532/*
drh75897232000-05-29 14:26:00 +00005533** Generate the beginning of the loop used for WHERE clause processing.
5534** The return value is a pointer to an opaque structure that contains
5535** information needed to terminate the loop. Later, the calling routine
5536** should invoke sqlite3WhereEnd() with the return value of this function
5537** in order to complete the WHERE clause processing.
5538**
5539** If an error occurs, this routine returns NULL.
drhc27a1ce2002-06-14 20:58:45 +00005540**
5541** The basic idea is to do a nested loop, one loop for each table in
5542** the FROM clause of a select. (INSERT and UPDATE statements are the
5543** same as a SELECT with only a single table in the FROM clause.) For
5544** example, if the SQL is this:
5545**
5546** SELECT * FROM t1, t2, t3 WHERE ...;
5547**
5548** Then the code generated is conceptually like the following:
5549**
5550** foreach row1 in t1 do \ Code generated
danielk19774adee202004-05-08 08:23:19 +00005551** foreach row2 in t2 do |-- by sqlite3WhereBegin()
drhc27a1ce2002-06-14 20:58:45 +00005552** foreach row3 in t3 do /
5553** ...
5554** end \ Code generated
danielk19774adee202004-05-08 08:23:19 +00005555** end |-- by sqlite3WhereEnd()
drhc27a1ce2002-06-14 20:58:45 +00005556** end /
5557**
drh29dda4a2005-07-21 18:23:20 +00005558** Note that the loops might not be nested in the order in which they
5559** appear in the FROM clause if a different order is better able to make
drh51147ba2005-07-23 22:59:55 +00005560** use of indices. Note also that when the IN operator appears in
5561** the WHERE clause, it might result in additional nested loops for
5562** scanning through all values on the right-hand side of the IN.
drh29dda4a2005-07-21 18:23:20 +00005563**
drhc27a1ce2002-06-14 20:58:45 +00005564** There are Btree cursors associated with each table. t1 uses cursor
drh6a3ea0e2003-05-02 14:32:12 +00005565** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
5566** And so forth. This routine generates code to open those VDBE cursors
danielk19774adee202004-05-08 08:23:19 +00005567** and sqlite3WhereEnd() generates the code to close them.
drhc27a1ce2002-06-14 20:58:45 +00005568**
drhe6f85e72004-12-25 01:03:13 +00005569** The code that sqlite3WhereBegin() generates leaves the cursors named
5570** in pTabList pointing at their appropriate entries. The [...] code
drhf0863fe2005-06-12 21:35:51 +00005571** can use OP_Column and OP_Rowid opcodes on these cursors to extract
drhe6f85e72004-12-25 01:03:13 +00005572** data from the various tables of the loop.
5573**
drhc27a1ce2002-06-14 20:58:45 +00005574** If the WHERE clause is empty, the foreach loops must each scan their
5575** entire tables. Thus a three-way join is an O(N^3) operation. But if
5576** the tables have indices and there are terms in the WHERE clause that
5577** refer to those indices, a complete table scan can be avoided and the
5578** code will run much faster. Most of the work of this routine is checking
5579** to see if there are indices that can be used to speed up the loop.
5580**
5581** Terms of the WHERE clause are also used to limit which rows actually
5582** make it to the "..." in the middle of the loop. After each "foreach",
5583** terms of the WHERE clause that use only terms in that loop and outer
5584** loops are evaluated and if false a jump is made around all subsequent
5585** inner loops (or around the "..." if the test occurs within the inner-
5586** most loop)
5587**
5588** OUTER JOINS
5589**
5590** An outer join of tables t1 and t2 is conceptally coded as follows:
5591**
5592** foreach row1 in t1 do
5593** flag = 0
5594** foreach row2 in t2 do
5595** start:
5596** ...
5597** flag = 1
5598** end
drhe3184742002-06-19 14:27:05 +00005599** if flag==0 then
5600** move the row2 cursor to a null row
5601** goto start
5602** fi
drhc27a1ce2002-06-14 20:58:45 +00005603** end
5604**
drhe3184742002-06-19 14:27:05 +00005605** ORDER BY CLAUSE PROCESSING
5606**
drh94433422013-07-01 11:05:50 +00005607** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause
5608** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement
drhe3184742002-06-19 14:27:05 +00005609** if there is one. If there is no ORDER BY clause or if this routine
drh46ec5b62012-09-24 15:30:54 +00005610** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
drhfc8d4f92013-11-08 15:19:46 +00005611**
5612** The iIdxCur parameter is the cursor number of an index. If
5613** WHERE_ONETABLE_ONLY is set, iIdxCur is the cursor number of an index
5614** to use for OR clause processing. The WHERE clause should use this
5615** specific cursor. If WHERE_ONEPASS_DESIRED is set, then iIdxCur is
5616** the first cursor in an array of cursors for all indices. iIdxCur should
5617** be used to compute the appropriate cursor depending on which index is
5618** used.
drh75897232000-05-29 14:26:00 +00005619*/
danielk19774adee202004-05-08 08:23:19 +00005620WhereInfo *sqlite3WhereBegin(
danielk1977ed326d72004-11-16 15:50:19 +00005621 Parse *pParse, /* The parser context */
drh6457a352013-06-21 00:35:37 +00005622 SrcList *pTabList, /* FROM clause: A list of all tables to be scanned */
danielk1977ed326d72004-11-16 15:50:19 +00005623 Expr *pWhere, /* The WHERE clause */
drh0401ace2014-03-18 15:30:27 +00005624 ExprList *pOrderBy, /* An ORDER BY (or GROUP BY) clause, or NULL */
drh6457a352013-06-21 00:35:37 +00005625 ExprList *pResultSet, /* Result set of the query */
dan0efb72c2012-08-24 18:44:56 +00005626 u16 wctrlFlags, /* One of the WHERE_* flags defined in sqliteInt.h */
5627 int iIdxCur /* If WHERE_ONETABLE_ONLY is set, index cursor number */
drh75897232000-05-29 14:26:00 +00005628){
danielk1977be229652009-03-20 14:18:51 +00005629 int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
drhc01a3c12009-12-16 22:10:49 +00005630 int nTabList; /* Number of elements in pTabList */
drh75897232000-05-29 14:26:00 +00005631 WhereInfo *pWInfo; /* Will become the return value of this function */
5632 Vdbe *v = pParse->pVdbe; /* The virtual database engine */
drhfe05af82005-07-21 03:14:59 +00005633 Bitmask notReady; /* Cursors that are not yet positioned */
drh1c8148f2013-05-04 20:25:23 +00005634 WhereLoopBuilder sWLB; /* The WhereLoop builder */
drh111a6a72008-12-21 03:51:16 +00005635 WhereMaskSet *pMaskSet; /* The expression mask set */
drh56f1b992012-09-25 14:29:39 +00005636 WhereLevel *pLevel; /* A single level in pWInfo->a[] */
drhfd636c72013-06-21 02:05:06 +00005637 WhereLoop *pLoop; /* Pointer to a single WhereLoop object */
drh9cd1c992012-09-25 20:43:35 +00005638 int ii; /* Loop counter */
drh17435752007-08-16 04:30:38 +00005639 sqlite3 *db; /* Database connection */
drh5346e952013-05-08 14:14:26 +00005640 int rc; /* Return code */
drh75897232000-05-29 14:26:00 +00005641
drh56f1b992012-09-25 14:29:39 +00005642
5643 /* Variable initialization */
drhfd636c72013-06-21 02:05:06 +00005644 db = pParse->db;
drh1c8148f2013-05-04 20:25:23 +00005645 memset(&sWLB, 0, sizeof(sWLB));
drh0401ace2014-03-18 15:30:27 +00005646
5647 /* An ORDER/GROUP BY clause of more than 63 terms cannot be optimized */
5648 testcase( pOrderBy && pOrderBy->nExpr==BMS-1 );
5649 if( pOrderBy && pOrderBy->nExpr>=BMS ) pOrderBy = 0;
drh1c8148f2013-05-04 20:25:23 +00005650 sWLB.pOrderBy = pOrderBy;
drh56f1b992012-09-25 14:29:39 +00005651
drhfd636c72013-06-21 02:05:06 +00005652 /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
5653 ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
5654 if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
5655 wctrlFlags &= ~WHERE_WANT_DISTINCT;
5656 }
5657
drh29dda4a2005-07-21 18:23:20 +00005658 /* The number of tables in the FROM clause is limited by the number of
drh1398ad32005-01-19 23:24:50 +00005659 ** bits in a Bitmask
5660 */
drh67ae0cb2010-04-08 14:38:51 +00005661 testcase( pTabList->nSrc==BMS );
drh29dda4a2005-07-21 18:23:20 +00005662 if( pTabList->nSrc>BMS ){
5663 sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
drh1398ad32005-01-19 23:24:50 +00005664 return 0;
5665 }
5666
drhc01a3c12009-12-16 22:10:49 +00005667 /* This function normally generates a nested loop for all tables in
5668 ** pTabList. But if the WHERE_ONETABLE_ONLY flag is set, then we should
5669 ** only generate code for the first table in pTabList and assume that
5670 ** any cursors associated with subsequent tables are uninitialized.
5671 */
5672 nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
5673
drh75897232000-05-29 14:26:00 +00005674 /* Allocate and initialize the WhereInfo structure that will become the
danielk1977be229652009-03-20 14:18:51 +00005675 ** return value. A single allocation is used to store the WhereInfo
5676 ** struct, the contents of WhereInfo.a[], the WhereClause structure
5677 ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
5678 ** field (type Bitmask) it must be aligned on an 8-byte boundary on
5679 ** some architectures. Hence the ROUND8() below.
drh75897232000-05-29 14:26:00 +00005680 */
drhc01a3c12009-12-16 22:10:49 +00005681 nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
drh60c96cd2013-06-09 17:21:25 +00005682 pWInfo = sqlite3DbMallocZero(db, nByteWInfo + sizeof(WhereLoop));
drh17435752007-08-16 04:30:38 +00005683 if( db->mallocFailed ){
drh8b307fb2010-04-06 15:57:05 +00005684 sqlite3DbFree(db, pWInfo);
5685 pWInfo = 0;
danielk197785574e32008-10-06 05:32:18 +00005686 goto whereBeginError;
drh75897232000-05-29 14:26:00 +00005687 }
drhfc8d4f92013-11-08 15:19:46 +00005688 pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1;
drhc01a3c12009-12-16 22:10:49 +00005689 pWInfo->nLevel = nTabList;
drh75897232000-05-29 14:26:00 +00005690 pWInfo->pParse = pParse;
5691 pWInfo->pTabList = pTabList;
drh6b7157b2013-05-10 02:00:35 +00005692 pWInfo->pOrderBy = pOrderBy;
drh6457a352013-06-21 00:35:37 +00005693 pWInfo->pResultSet = pResultSet;
drha22a75e2014-03-21 18:16:23 +00005694 pWInfo->iBreak = pWInfo->iContinue = sqlite3VdbeMakeLabel(v);
drh6df2acd2008-12-28 16:55:25 +00005695 pWInfo->wctrlFlags = wctrlFlags;
drh8b307fb2010-04-06 15:57:05 +00005696 pWInfo->savedNQueryLoop = pParse->nQueryLoop;
drh70d18342013-06-06 19:16:33 +00005697 pMaskSet = &pWInfo->sMaskSet;
drh1c8148f2013-05-04 20:25:23 +00005698 sWLB.pWInfo = pWInfo;
drh70d18342013-06-06 19:16:33 +00005699 sWLB.pWC = &pWInfo->sWC;
drh1ac87e12013-07-18 14:50:56 +00005700 sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);
5701 assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) );
drh60c96cd2013-06-09 17:21:25 +00005702 whereLoopInit(sWLB.pNew);
drhb8a8e8a2013-06-10 19:12:39 +00005703#ifdef SQLITE_DEBUG
5704 sWLB.pNew->cId = '*';
5705#endif
drh08192d52002-04-30 19:20:28 +00005706
drh111a6a72008-12-21 03:51:16 +00005707 /* Split the WHERE clause into separate subexpressions where each
5708 ** subexpression is separated by an AND operator.
5709 */
5710 initMaskSet(pMaskSet);
drh70d18342013-06-06 19:16:33 +00005711 whereClauseInit(&pWInfo->sWC, pWInfo);
drh39759742013-08-02 23:40:45 +00005712 whereSplit(&pWInfo->sWC, pWhere, TK_AND);
drh111a6a72008-12-21 03:51:16 +00005713
drh08192d52002-04-30 19:20:28 +00005714 /* Special case: a WHERE clause that is constant. Evaluate the
5715 ** expression and either jump over all of the code or fall thru.
5716 */
drh759e8582014-01-02 21:05:10 +00005717 for(ii=0; ii<sWLB.pWC->nTerm; ii++){
5718 if( nTabList==0 || sqlite3ExprIsConstantNotJoin(sWLB.pWC->a[ii].pExpr) ){
5719 sqlite3ExprIfFalse(pParse, sWLB.pWC->a[ii].pExpr, pWInfo->iBreak,
5720 SQLITE_JUMPIFNULL);
5721 sWLB.pWC->a[ii].wtFlags |= TERM_CODED;
5722 }
drh08192d52002-04-30 19:20:28 +00005723 }
drh75897232000-05-29 14:26:00 +00005724
drh4fe425a2013-06-12 17:08:06 +00005725 /* Special case: No FROM clause
5726 */
5727 if( nTabList==0 ){
drhddba0c22014-03-18 20:33:42 +00005728 if( pOrderBy ) pWInfo->nOBSat = pOrderBy->nExpr;
drh6457a352013-06-21 00:35:37 +00005729 if( wctrlFlags & WHERE_WANT_DISTINCT ){
5730 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
5731 }
drh4fe425a2013-06-12 17:08:06 +00005732 }
5733
drh42165be2008-03-26 14:56:34 +00005734 /* Assign a bit from the bitmask to every term in the FROM clause.
5735 **
5736 ** When assigning bitmask values to FROM clause cursors, it must be
5737 ** the case that if X is the bitmask for the N-th FROM clause term then
5738 ** the bitmask for all FROM clause terms to the left of the N-th term
5739 ** is (X-1). An expression from the ON clause of a LEFT JOIN can use
5740 ** its Expr.iRightJoinTable value to find the bitmask of the right table
5741 ** of the join. Subtracting one from the right table bitmask gives a
5742 ** bitmask for all tables to the left of the join. Knowing the bitmask
5743 ** for all tables to the left of a left join is important. Ticket #3015.
danielk1977e672c8e2009-05-22 15:43:26 +00005744 **
drhc01a3c12009-12-16 22:10:49 +00005745 ** Note that bitmasks are created for all pTabList->nSrc tables in
5746 ** pTabList, not just the first nTabList tables. nTabList is normally
5747 ** equal to pTabList->nSrc but might be shortened to 1 if the
5748 ** WHERE_ONETABLE_ONLY flag is set.
drh42165be2008-03-26 14:56:34 +00005749 */
drh9cd1c992012-09-25 20:43:35 +00005750 for(ii=0; ii<pTabList->nSrc; ii++){
5751 createMask(pMaskSet, pTabList->a[ii].iCursor);
drh42165be2008-03-26 14:56:34 +00005752 }
5753#ifndef NDEBUG
5754 {
5755 Bitmask toTheLeft = 0;
drh9cd1c992012-09-25 20:43:35 +00005756 for(ii=0; ii<pTabList->nSrc; ii++){
5757 Bitmask m = getMask(pMaskSet, pTabList->a[ii].iCursor);
drh42165be2008-03-26 14:56:34 +00005758 assert( (m-1)==toTheLeft );
5759 toTheLeft |= m;
5760 }
5761 }
5762#endif
5763
drh29dda4a2005-07-21 18:23:20 +00005764 /* Analyze all of the subexpressions. Note that exprAnalyze() might
5765 ** add new virtual terms onto the end of the WHERE clause. We do not
5766 ** want to analyze these virtual terms, so start analyzing at the end
drhb6fb62d2005-09-20 08:47:20 +00005767 ** and work forward so that the added virtual terms are never processed.
drh75897232000-05-29 14:26:00 +00005768 */
drh70d18342013-06-06 19:16:33 +00005769 exprAnalyzeAll(pTabList, &pWInfo->sWC);
drh17435752007-08-16 04:30:38 +00005770 if( db->mallocFailed ){
danielk197785574e32008-10-06 05:32:18 +00005771 goto whereBeginError;
drh0bbaa1b2005-08-19 19:14:12 +00005772 }
drh75897232000-05-29 14:26:00 +00005773
drh6457a352013-06-21 00:35:37 +00005774 if( wctrlFlags & WHERE_WANT_DISTINCT ){
5775 if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){
5776 /* The DISTINCT marking is pointless. Ignore it. */
drh4f402f22013-06-11 18:59:38 +00005777 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
5778 }else if( pOrderBy==0 ){
drh6457a352013-06-21 00:35:37 +00005779 /* Try to ORDER BY the result set to make distinct processing easier */
drh4f402f22013-06-11 18:59:38 +00005780 pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
drh6457a352013-06-21 00:35:37 +00005781 pWInfo->pOrderBy = pResultSet;
drh4f402f22013-06-11 18:59:38 +00005782 }
dan38cc40c2011-06-30 20:17:15 +00005783 }
5784
drhf1b5f5b2013-05-02 00:15:01 +00005785 /* Construct the WhereLoop objects */
drh3b48e8c2013-06-12 20:18:16 +00005786 WHERETRACE(0xffff,("*** Optimizer Start ***\n"));
drhf4e9cb02013-10-28 19:59:59 +00005787 /* Display all terms of the WHERE clause */
5788#if defined(WHERETRACE_ENABLED) && defined(SQLITE_ENABLE_TREE_EXPLAIN)
5789 if( sqlite3WhereTrace & 0x100 ){
5790 int i;
5791 Vdbe *v = pParse->pVdbe;
5792 sqlite3ExplainBegin(v);
5793 for(i=0; i<sWLB.pWC->nTerm; i++){
drh7afc8b02013-10-28 22:33:36 +00005794 sqlite3ExplainPrintf(v, "#%-2d ", i);
drhf4e9cb02013-10-28 19:59:59 +00005795 sqlite3ExplainPush(v);
5796 whereExplainTerm(v, &sWLB.pWC->a[i]);
5797 sqlite3ExplainPop(v);
5798 sqlite3ExplainNL(v);
5799 }
5800 sqlite3ExplainFinish(v);
5801 sqlite3DebugPrintf("%s", sqlite3VdbeExplanation(v));
5802 }
5803#endif
drhb8a8e8a2013-06-10 19:12:39 +00005804 if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
drh60c96cd2013-06-09 17:21:25 +00005805 rc = whereLoopAddAll(&sWLB);
5806 if( rc ) goto whereBeginError;
5807
5808 /* Display all of the WhereLoop objects if wheretrace is enabled */
drh989578e2013-10-28 14:34:35 +00005809#ifdef WHERETRACE_ENABLED /* !=0 */
drh60c96cd2013-06-09 17:21:25 +00005810 if( sqlite3WhereTrace ){
5811 WhereLoop *p;
drhfd636c72013-06-21 02:05:06 +00005812 int i;
drh60c96cd2013-06-09 17:21:25 +00005813 static char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
5814 "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
drhfd636c72013-06-21 02:05:06 +00005815 for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
5816 p->cId = zLabel[i%sizeof(zLabel)];
drhc1ba2e72013-10-28 19:03:21 +00005817 whereLoopPrint(p, sWLB.pWC);
drh60c96cd2013-06-09 17:21:25 +00005818 }
5819 }
5820#endif
5821
drh4f402f22013-06-11 18:59:38 +00005822 wherePathSolver(pWInfo, 0);
drh60c96cd2013-06-09 17:21:25 +00005823 if( db->mallocFailed ) goto whereBeginError;
5824 if( pWInfo->pOrderBy ){
drhc7f0d222013-06-19 03:27:12 +00005825 wherePathSolver(pWInfo, pWInfo->nRowOut+1);
drh60c96cd2013-06-09 17:21:25 +00005826 if( db->mallocFailed ) goto whereBeginError;
drha18f3d22013-05-08 03:05:41 +00005827 }
5828 }
drh60c96cd2013-06-09 17:21:25 +00005829 if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
drhd84ce352013-06-04 18:27:41 +00005830 pWInfo->revMask = (Bitmask)(-1);
drha50ef112013-05-22 02:06:59 +00005831 }
drh81186b42013-06-18 01:52:41 +00005832 if( pParse->nErr || NEVER(db->mallocFailed) ){
drh75b93402013-05-31 20:43:57 +00005833 goto whereBeginError;
5834 }
drh989578e2013-10-28 14:34:35 +00005835#ifdef WHERETRACE_ENABLED /* !=0 */
drha18f3d22013-05-08 03:05:41 +00005836 if( sqlite3WhereTrace ){
5837 int ii;
drh4f402f22013-06-11 18:59:38 +00005838 sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
drhddba0c22014-03-18 20:33:42 +00005839 if( pWInfo->nOBSat>0 ){
5840 sqlite3DebugPrintf(" ORDERBY=%d,0x%llx", pWInfo->nOBSat, pWInfo->revMask);
drh319f6772013-05-14 15:31:07 +00005841 }
drh4f402f22013-06-11 18:59:38 +00005842 switch( pWInfo->eDistinct ){
5843 case WHERE_DISTINCT_UNIQUE: {
5844 sqlite3DebugPrintf(" DISTINCT=unique");
5845 break;
5846 }
5847 case WHERE_DISTINCT_ORDERED: {
5848 sqlite3DebugPrintf(" DISTINCT=ordered");
5849 break;
5850 }
5851 case WHERE_DISTINCT_UNORDERED: {
5852 sqlite3DebugPrintf(" DISTINCT=unordered");
5853 break;
5854 }
5855 }
5856 sqlite3DebugPrintf("\n");
drhfd636c72013-06-21 02:05:06 +00005857 for(ii=0; ii<pWInfo->nLevel; ii++){
drhc1ba2e72013-10-28 19:03:21 +00005858 whereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC);
drhf1b5f5b2013-05-02 00:15:01 +00005859 }
5860 }
5861#endif
drhfd636c72013-06-21 02:05:06 +00005862 /* Attempt to omit tables from the join that do not effect the result */
drh1031bd92013-06-22 15:44:26 +00005863 if( pWInfo->nLevel>=2
5864 && pResultSet!=0
5865 && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
5866 ){
drhfd636c72013-06-21 02:05:06 +00005867 Bitmask tabUsed = exprListTableUsage(pMaskSet, pResultSet);
drh67a5ec72013-09-03 14:03:47 +00005868 if( sWLB.pOrderBy ) tabUsed |= exprListTableUsage(pMaskSet, sWLB.pOrderBy);
drhfd636c72013-06-21 02:05:06 +00005869 while( pWInfo->nLevel>=2 ){
drh9d5a5792013-06-28 13:43:33 +00005870 WhereTerm *pTerm, *pEnd;
drhfd636c72013-06-21 02:05:06 +00005871 pLoop = pWInfo->a[pWInfo->nLevel-1].pWLoop;
drhbc71b1d2013-06-21 02:15:48 +00005872 if( (pWInfo->pTabList->a[pLoop->iTab].jointype & JT_LEFT)==0 ) break;
5873 if( (wctrlFlags & WHERE_WANT_DISTINCT)==0
5874 && (pLoop->wsFlags & WHERE_ONEROW)==0
drhfd636c72013-06-21 02:05:06 +00005875 ){
drhfd636c72013-06-21 02:05:06 +00005876 break;
5877 }
drhbc71b1d2013-06-21 02:15:48 +00005878 if( (tabUsed & pLoop->maskSelf)!=0 ) break;
drh9d5a5792013-06-28 13:43:33 +00005879 pEnd = sWLB.pWC->a + sWLB.pWC->nTerm;
5880 for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
5881 if( (pTerm->prereqAll & pLoop->maskSelf)!=0
5882 && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
5883 ){
5884 break;
5885 }
5886 }
5887 if( pTerm<pEnd ) break;
drhbc71b1d2013-06-21 02:15:48 +00005888 WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId));
5889 pWInfo->nLevel--;
5890 nTabList--;
drhfd636c72013-06-21 02:05:06 +00005891 }
5892 }
drh3b48e8c2013-06-12 20:18:16 +00005893 WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
drh8e23daf2013-06-11 13:30:04 +00005894 pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
drhf1b5f5b2013-05-02 00:15:01 +00005895
drh08c88eb2008-04-10 13:33:18 +00005896 /* If the caller is an UPDATE or DELETE statement that is requesting
5897 ** to use a one-pass algorithm, determine if this is appropriate.
drh24b7fe92013-09-30 19:33:06 +00005898 ** The one-pass algorithm only works if the WHERE clause constrains
drh08c88eb2008-04-10 13:33:18 +00005899 ** the statement to update a single row.
5900 */
drh165be382008-12-05 02:36:33 +00005901 assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
drh3b48e8c2013-06-12 20:18:16 +00005902 if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
5903 && (pWInfo->a[0].pWLoop->wsFlags & WHERE_ONEROW)!=0 ){
drh08c88eb2008-04-10 13:33:18 +00005904 pWInfo->okOnePass = 1;
drh702ba9f2013-11-07 21:25:13 +00005905 if( HasRowid(pTabList->a[0].pTab) ){
5906 pWInfo->a[0].pWLoop->wsFlags &= ~WHERE_IDX_ONLY;
5907 }
drh08c88eb2008-04-10 13:33:18 +00005908 }
drheb04de32013-05-10 15:16:30 +00005909
drh9012bcb2004-12-19 00:11:35 +00005910 /* Open all tables in the pTabList and any indices selected for
5911 ** searching those tables.
5912 */
drh8b307fb2010-04-06 15:57:05 +00005913 notReady = ~(Bitmask)0;
drh9cd1c992012-09-25 20:43:35 +00005914 for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
danielk1977da184232006-01-05 11:34:32 +00005915 Table *pTab; /* Table to open */
danielk1977da184232006-01-05 11:34:32 +00005916 int iDb; /* Index of database containing table/index */
drh56f1b992012-09-25 14:29:39 +00005917 struct SrcList_item *pTabItem;
drh9012bcb2004-12-19 00:11:35 +00005918
drh29dda4a2005-07-21 18:23:20 +00005919 pTabItem = &pTabList->a[pLevel->iFrom];
drh9012bcb2004-12-19 00:11:35 +00005920 pTab = pTabItem->pTab;
danielk1977595a5232009-07-24 17:58:53 +00005921 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
drh7ba39a92013-05-30 17:43:19 +00005922 pLoop = pLevel->pWLoop;
drh424aab82010-04-06 18:28:20 +00005923 if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
drh75bb9f52010-04-06 18:51:42 +00005924 /* Do nothing */
5925 }else
drh9eff6162006-06-12 21:59:13 +00005926#ifndef SQLITE_OMIT_VIRTUALTABLE
drh7ba39a92013-05-30 17:43:19 +00005927 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
danielk1977595a5232009-07-24 17:58:53 +00005928 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
danielk197793626f42006-06-20 13:07:27 +00005929 int iCur = pTabItem->iCursor;
danielk1977595a5232009-07-24 17:58:53 +00005930 sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
drhfc5e5462012-12-03 17:04:40 +00005931 }else if( IsVirtual(pTab) ){
5932 /* noop */
drh9eff6162006-06-12 21:59:13 +00005933 }else
5934#endif
drh7ba39a92013-05-30 17:43:19 +00005935 if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
drh9ef61f42011-10-07 14:40:59 +00005936 && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){
drhfc8d4f92013-11-08 15:19:46 +00005937 int op = OP_OpenRead;
5938 if( pWInfo->okOnePass ){
5939 op = OP_OpenWrite;
5940 pWInfo->aiCurOnePass[0] = pTabItem->iCursor;
5941 };
drh08c88eb2008-04-10 13:33:18 +00005942 sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
drhfc8d4f92013-11-08 15:19:46 +00005943 assert( pTabItem->iCursor==pLevel->iTabCur );
drh7963b0e2013-06-17 21:37:40 +00005944 testcase( !pWInfo->okOnePass && pTab->nCol==BMS-1 );
5945 testcase( !pWInfo->okOnePass && pTab->nCol==BMS );
drhdd9930e2013-10-23 23:37:02 +00005946 if( !pWInfo->okOnePass && pTab->nCol<BMS && HasRowid(pTab) ){
danielk19779792eef2006-01-13 15:58:43 +00005947 Bitmask b = pTabItem->colUsed;
5948 int n = 0;
drh74161702006-02-24 02:53:49 +00005949 for(; b; b=b>>1, n++){}
drh8cff69d2009-11-12 19:59:44 +00005950 sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
5951 SQLITE_INT_TO_PTR(n), P4_INT32);
danielk19779792eef2006-01-13 15:58:43 +00005952 assert( n<=pTab->nCol );
5953 }
danielk1977c00da102006-01-07 13:21:04 +00005954 }else{
5955 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
drh9012bcb2004-12-19 00:11:35 +00005956 }
drh7e47cb82013-05-31 17:55:27 +00005957 if( pLoop->wsFlags & WHERE_INDEXED ){
drh7ba39a92013-05-30 17:43:19 +00005958 Index *pIx = pLoop->u.btree.pIndex;
drhfc8d4f92013-11-08 15:19:46 +00005959 int iIndexCur;
5960 int op = OP_OpenRead;
drh4308e342013-11-11 16:55:52 +00005961 /* iIdxCur is always set if to a positive value if ONEPASS is possible */
5962 assert( iIdxCur!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 );
5963 if( pWInfo->okOnePass ){
drhfc8d4f92013-11-08 15:19:46 +00005964 Index *pJ = pTabItem->pTab->pIndex;
5965 iIndexCur = iIdxCur;
5966 assert( wctrlFlags & WHERE_ONEPASS_DESIRED );
5967 while( ALWAYS(pJ) && pJ!=pIx ){
5968 iIndexCur++;
5969 pJ = pJ->pNext;
5970 }
5971 op = OP_OpenWrite;
5972 pWInfo->aiCurOnePass[1] = iIndexCur;
5973 }else if( iIdxCur && (wctrlFlags & WHERE_ONETABLE_ONLY)!=0 ){
5974 iIndexCur = iIdxCur;
5975 }else{
5976 iIndexCur = pParse->nTab++;
5977 }
5978 pLevel->iIdxCur = iIndexCur;
danielk1977da184232006-01-05 11:34:32 +00005979 assert( pIx->pSchema==pTab->pSchema );
drhb0367fb2012-08-25 02:11:13 +00005980 assert( iIndexCur>=0 );
drhfc8d4f92013-11-08 15:19:46 +00005981 sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb);
drh2ec2fb22013-11-06 19:59:23 +00005982 sqlite3VdbeSetP4KeyInfo(pParse, pIx);
danielk1977207872a2008-01-03 07:54:23 +00005983 VdbeComment((v, "%s", pIx->zName));
drh9012bcb2004-12-19 00:11:35 +00005984 }
drhaceb31b2014-02-08 01:40:27 +00005985 if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb);
drh70d18342013-06-06 19:16:33 +00005986 notReady &= ~getMask(&pWInfo->sMaskSet, pTabItem->iCursor);
drh9012bcb2004-12-19 00:11:35 +00005987 }
5988 pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
drha21a64d2010-04-06 22:33:55 +00005989 if( db->mallocFailed ) goto whereBeginError;
drh9012bcb2004-12-19 00:11:35 +00005990
drh29dda4a2005-07-21 18:23:20 +00005991 /* Generate the code to do the search. Each iteration of the for
5992 ** loop below generates code for a single nested loop of the VM
5993 ** program.
drh75897232000-05-29 14:26:00 +00005994 */
drhfe05af82005-07-21 03:14:59 +00005995 notReady = ~(Bitmask)0;
drh9cd1c992012-09-25 20:43:35 +00005996 for(ii=0; ii<nTabList; ii++){
5997 pLevel = &pWInfo->a[ii];
drhcc04afd2013-08-22 02:56:28 +00005998#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
5999 if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){
6000 constructAutomaticIndex(pParse, &pWInfo->sWC,
6001 &pTabList->a[pLevel->iFrom], notReady, pLevel);
6002 if( db->mallocFailed ) goto whereBeginError;
6003 }
6004#endif
drh9cd1c992012-09-25 20:43:35 +00006005 explainOneScan(pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags);
drhcc04afd2013-08-22 02:56:28 +00006006 pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
drh70d18342013-06-06 19:16:33 +00006007 notReady = codeOneLoopStart(pWInfo, ii, notReady);
dan4a07e3d2010-11-09 14:48:59 +00006008 pWInfo->iContinue = pLevel->addrCont;
drh75897232000-05-29 14:26:00 +00006009 }
drh7ec764a2005-07-21 03:48:20 +00006010
drh6fa978d2013-05-30 19:29:19 +00006011 /* Done. */
drh6bc69a22013-11-19 12:33:23 +00006012 VdbeModuleComment((v, "Begin WHERE-core"));
drh75897232000-05-29 14:26:00 +00006013 return pWInfo;
drhe23399f2005-07-22 00:31:39 +00006014
6015 /* Jump here if malloc fails */
danielk197785574e32008-10-06 05:32:18 +00006016whereBeginError:
drh8b307fb2010-04-06 15:57:05 +00006017 if( pWInfo ){
6018 pParse->nQueryLoop = pWInfo->savedNQueryLoop;
6019 whereInfoFree(db, pWInfo);
6020 }
drhe23399f2005-07-22 00:31:39 +00006021 return 0;
drh75897232000-05-29 14:26:00 +00006022}
6023
6024/*
drhc27a1ce2002-06-14 20:58:45 +00006025** Generate the end of the WHERE loop. See comments on
danielk19774adee202004-05-08 08:23:19 +00006026** sqlite3WhereBegin() for additional information.
drh75897232000-05-29 14:26:00 +00006027*/
danielk19774adee202004-05-08 08:23:19 +00006028void sqlite3WhereEnd(WhereInfo *pWInfo){
drh633e6d52008-07-28 19:34:53 +00006029 Parse *pParse = pWInfo->pParse;
6030 Vdbe *v = pParse->pVdbe;
drh19a775c2000-06-05 18:54:46 +00006031 int i;
drh6b563442001-11-07 16:48:26 +00006032 WhereLevel *pLevel;
drh7ba39a92013-05-30 17:43:19 +00006033 WhereLoop *pLoop;
drhad3cab52002-05-24 02:04:32 +00006034 SrcList *pTabList = pWInfo->pTabList;
drh633e6d52008-07-28 19:34:53 +00006035 sqlite3 *db = pParse->db;
drh19a775c2000-06-05 18:54:46 +00006036
drh9012bcb2004-12-19 00:11:35 +00006037 /* Generate loop termination code.
6038 */
drh6bc69a22013-11-19 12:33:23 +00006039 VdbeModuleComment((v, "End WHERE-core"));
drhceea3322009-04-23 13:22:42 +00006040 sqlite3ExprCacheClear(pParse);
drhc01a3c12009-12-16 22:10:49 +00006041 for(i=pWInfo->nLevel-1; i>=0; i--){
drhcd8629e2013-11-13 12:27:25 +00006042 int addr;
drh6b563442001-11-07 16:48:26 +00006043 pLevel = &pWInfo->a[i];
drh7ba39a92013-05-30 17:43:19 +00006044 pLoop = pLevel->pWLoop;
drhb3190c12008-12-08 21:37:14 +00006045 sqlite3VdbeResolveLabel(v, pLevel->addrCont);
drh6b563442001-11-07 16:48:26 +00006046 if( pLevel->op!=OP_Noop ){
drhe39a7322014-02-03 14:04:11 +00006047 sqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3);
drhd1d38482008-10-07 23:46:38 +00006048 sqlite3VdbeChangeP5(v, pLevel->p5);
drh688852a2014-02-17 22:40:43 +00006049 VdbeCoverage(v);
drh7d176102014-02-18 03:07:12 +00006050 VdbeCoverageIf(v, pLevel->op==OP_Next);
6051 VdbeCoverageIf(v, pLevel->op==OP_Prev);
6052 VdbeCoverageIf(v, pLevel->op==OP_VNext);
drh19a775c2000-06-05 18:54:46 +00006053 }
drh7ba39a92013-05-30 17:43:19 +00006054 if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
drh72e8fa42007-03-28 14:30:06 +00006055 struct InLoop *pIn;
drhe23399f2005-07-22 00:31:39 +00006056 int j;
drhb3190c12008-12-08 21:37:14 +00006057 sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
drh111a6a72008-12-21 03:51:16 +00006058 for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
drhb3190c12008-12-08 21:37:14 +00006059 sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
drh2d96b932013-02-08 18:48:23 +00006060 sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
drh688852a2014-02-17 22:40:43 +00006061 VdbeCoverage(v);
drh7d176102014-02-18 03:07:12 +00006062 VdbeCoverageIf(v, pIn->eEndLoopOp==OP_PrevIfOpen);
6063 VdbeCoverageIf(v, pIn->eEndLoopOp==OP_NextIfOpen);
drhb3190c12008-12-08 21:37:14 +00006064 sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
drhe23399f2005-07-22 00:31:39 +00006065 }
drh111a6a72008-12-21 03:51:16 +00006066 sqlite3DbFree(db, pLevel->u.in.aInLoop);
drhd99f7062002-06-08 23:25:08 +00006067 }
drhb3190c12008-12-08 21:37:14 +00006068 sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
drhcd8629e2013-11-13 12:27:25 +00006069 if( pLevel->addrSkip ){
drhcd8629e2013-11-13 12:27:25 +00006070 sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrSkip);
drhe084f402013-11-13 17:24:38 +00006071 VdbeComment((v, "next skip-scan on %s", pLoop->u.btree.pIndex->zName));
drh2e5ef4e2013-11-13 16:58:54 +00006072 sqlite3VdbeJumpHere(v, pLevel->addrSkip);
6073 sqlite3VdbeJumpHere(v, pLevel->addrSkip-2);
drhcd8629e2013-11-13 12:27:25 +00006074 }
drhad2d8302002-05-24 20:31:36 +00006075 if( pLevel->iLeftJoin ){
drh688852a2014-02-17 22:40:43 +00006076 addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v);
drh7ba39a92013-05-30 17:43:19 +00006077 assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
6078 || (pLoop->wsFlags & WHERE_INDEXED)!=0 );
6079 if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 ){
drh35451c62009-11-12 04:26:39 +00006080 sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
6081 }
drh76f4cfb2013-05-31 18:20:52 +00006082 if( pLoop->wsFlags & WHERE_INDEXED ){
drh3c84ddf2008-01-09 02:15:38 +00006083 sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
drh7f09b3e2002-08-13 13:15:49 +00006084 }
drh336a5302009-04-24 15:46:21 +00006085 if( pLevel->op==OP_Return ){
6086 sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
6087 }else{
6088 sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
6089 }
drhd654be82005-09-20 17:42:23 +00006090 sqlite3VdbeJumpHere(v, addr);
drhad2d8302002-05-24 20:31:36 +00006091 }
drh6bc69a22013-11-19 12:33:23 +00006092 VdbeModuleComment((v, "End WHERE-loop%d: %s", i,
drhfc8d4f92013-11-08 15:19:46 +00006093 pWInfo->pTabList->a[pLevel->iFrom].pTab->zName));
drh19a775c2000-06-05 18:54:46 +00006094 }
drh9012bcb2004-12-19 00:11:35 +00006095
6096 /* The "break" point is here, just past the end of the outer loop.
6097 ** Set it.
6098 */
danielk19774adee202004-05-08 08:23:19 +00006099 sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
drh9012bcb2004-12-19 00:11:35 +00006100
drhfd636c72013-06-21 02:05:06 +00006101 assert( pWInfo->nLevel<=pTabList->nSrc );
drhc01a3c12009-12-16 22:10:49 +00006102 for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
drh5f612292014-02-08 23:20:32 +00006103 int k, last;
6104 VdbeOp *pOp;
danbfca6a42012-08-24 10:52:35 +00006105 Index *pIdx = 0;
drh29dda4a2005-07-21 18:23:20 +00006106 struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
drh9012bcb2004-12-19 00:11:35 +00006107 Table *pTab = pTabItem->pTab;
drh5cf590c2003-04-24 01:45:04 +00006108 assert( pTab!=0 );
drh7ba39a92013-05-30 17:43:19 +00006109 pLoop = pLevel->pWLoop;
drhfc8d4f92013-11-08 15:19:46 +00006110
drh5f612292014-02-08 23:20:32 +00006111 /* For a co-routine, change all OP_Column references to the table of
6112 ** the co-routine into OP_SCopy of result contained in a register.
6113 ** OP_Rowid becomes OP_Null.
6114 */
danfbf0f0e2014-03-03 14:20:30 +00006115 if( pTabItem->viaCoroutine && !db->mallocFailed ){
drh5f612292014-02-08 23:20:32 +00006116 last = sqlite3VdbeCurrentAddr(v);
6117 k = pLevel->addrBody;
6118 pOp = sqlite3VdbeGetOp(v, k);
6119 for(; k<last; k++, pOp++){
6120 if( pOp->p1!=pLevel->iTabCur ) continue;
6121 if( pOp->opcode==OP_Column ){
drhc438df12014-04-03 16:29:31 +00006122 pOp->opcode = OP_Copy;
drh5f612292014-02-08 23:20:32 +00006123 pOp->p1 = pOp->p2 + pTabItem->regResult;
6124 pOp->p2 = pOp->p3;
6125 pOp->p3 = 0;
6126 }else if( pOp->opcode==OP_Rowid ){
6127 pOp->opcode = OP_Null;
6128 pOp->p1 = 0;
6129 pOp->p3 = 0;
6130 }
6131 }
6132 continue;
6133 }
6134
drhfc8d4f92013-11-08 15:19:46 +00006135 /* Close all of the cursors that were opened by sqlite3WhereBegin.
6136 ** Except, do not close cursors that will be reused by the OR optimization
6137 ** (WHERE_OMIT_OPEN_CLOSE). And do not close the OP_OpenWrite cursors
6138 ** created for the ONEPASS optimization.
6139 */
drh4139c992010-04-07 14:59:45 +00006140 if( (pTab->tabFlags & TF_Ephemeral)==0
6141 && pTab->pSelect==0
drh9ef61f42011-10-07 14:40:59 +00006142 && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
drh4139c992010-04-07 14:59:45 +00006143 ){
drh7ba39a92013-05-30 17:43:19 +00006144 int ws = pLoop->wsFlags;
drh8b307fb2010-04-06 15:57:05 +00006145 if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
drh6df2acd2008-12-28 16:55:25 +00006146 sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
6147 }
drhfc8d4f92013-11-08 15:19:46 +00006148 if( (ws & WHERE_INDEXED)!=0
6149 && (ws & (WHERE_IPK|WHERE_AUTO_INDEX))==0
6150 && pLevel->iIdxCur!=pWInfo->aiCurOnePass[1]
6151 ){
drh6df2acd2008-12-28 16:55:25 +00006152 sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
6153 }
drh9012bcb2004-12-19 00:11:35 +00006154 }
6155
drhf0030762013-06-14 13:27:01 +00006156 /* If this scan uses an index, make VDBE code substitutions to read data
6157 ** from the index instead of from the table where possible. In some cases
6158 ** this optimization prevents the table from ever being read, which can
6159 ** yield a significant performance boost.
drh9012bcb2004-12-19 00:11:35 +00006160 **
6161 ** Calls to the code generator in between sqlite3WhereBegin and
6162 ** sqlite3WhereEnd will have created code that references the table
6163 ** directly. This loop scans all that code looking for opcodes
6164 ** that reference the table and converts them into opcodes that
6165 ** reference the index.
6166 */
drh7ba39a92013-05-30 17:43:19 +00006167 if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
6168 pIdx = pLoop->u.btree.pIndex;
6169 }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
drhd40e2082012-08-24 23:24:15 +00006170 pIdx = pLevel->u.pCovidx;
danbfca6a42012-08-24 10:52:35 +00006171 }
drh7ba39a92013-05-30 17:43:19 +00006172 if( pIdx && !db->mallocFailed ){
drh9012bcb2004-12-19 00:11:35 +00006173 last = sqlite3VdbeCurrentAddr(v);
drhcc04afd2013-08-22 02:56:28 +00006174 k = pLevel->addrBody;
6175 pOp = sqlite3VdbeGetOp(v, k);
6176 for(; k<last; k++, pOp++){
drh9012bcb2004-12-19 00:11:35 +00006177 if( pOp->p1!=pLevel->iTabCur ) continue;
6178 if( pOp->opcode==OP_Column ){
drhee0ec8e2013-10-31 17:38:01 +00006179 int x = pOp->p2;
drh511717c2013-11-08 17:13:23 +00006180 assert( pIdx->pTable==pTab );
drhee0ec8e2013-10-31 17:38:01 +00006181 if( !HasRowid(pTab) ){
6182 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
6183 x = pPk->aiColumn[x];
6184 }
6185 x = sqlite3ColumnOfIndex(pIdx, x);
drh44156282013-10-23 22:23:03 +00006186 if( x>=0 ){
6187 pOp->p2 = x;
6188 pOp->p1 = pLevel->iIdxCur;
drh9012bcb2004-12-19 00:11:35 +00006189 }
drh44156282013-10-23 22:23:03 +00006190 assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || x>=0 );
drhf0863fe2005-06-12 21:35:51 +00006191 }else if( pOp->opcode==OP_Rowid ){
drh9012bcb2004-12-19 00:11:35 +00006192 pOp->p1 = pLevel->iIdxCur;
drhf0863fe2005-06-12 21:35:51 +00006193 pOp->opcode = OP_IdxRowid;
drh9012bcb2004-12-19 00:11:35 +00006194 }
6195 }
drh6b563442001-11-07 16:48:26 +00006196 }
drh19a775c2000-06-05 18:54:46 +00006197 }
drh9012bcb2004-12-19 00:11:35 +00006198
6199 /* Final cleanup
6200 */
drhf12cde52010-04-08 17:28:00 +00006201 pParse->nQueryLoop = pWInfo->savedNQueryLoop;
6202 whereInfoFree(db, pWInfo);
drh75897232000-05-29 14:26:00 +00006203 return;
6204}