blob: e446f6db8ce9a72b568ea3c9d831374d4b9816b6 [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
drh6f82e852015-06-06 20:12:09 +000022/* Forward declaration of methods */
23static int whereLoopResize(sqlite3*, WhereLoop*, int);
24
25/* Test variable that can be set to enable WHERE tracing */
26#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
27/***/ int sqlite3WhereTrace = 0;
28#endif
29
30
drh51147ba2005-07-23 22:59:55 +000031/*
drh6f328482013-06-05 23:39:34 +000032** Return the estimated number of output rows from a WHERE clause
33*/
drhc63367e2013-06-10 20:46:50 +000034u64 sqlite3WhereOutputRowCount(WhereInfo *pWInfo){
drhbf539c42013-10-05 18:16:02 +000035 return sqlite3LogEstToInt(pWInfo->nRowOut);
drh6f328482013-06-05 23:39:34 +000036}
37
38/*
39** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
40** WHERE clause returns outputs for DISTINCT processing.
41*/
42int sqlite3WhereIsDistinct(WhereInfo *pWInfo){
43 return pWInfo->eDistinct;
44}
45
46/*
47** Return TRUE if the WHERE clause returns rows in ORDER BY order.
48** Return FALSE if the output needs to be sorted.
49*/
50int sqlite3WhereIsOrdered(WhereInfo *pWInfo){
drhddba0c22014-03-18 20:33:42 +000051 return pWInfo->nOBSat;
drh6f328482013-06-05 23:39:34 +000052}
53
54/*
55** Return the VDBE address or label to jump to in order to continue
56** immediately with the next row of a WHERE clause.
57*/
58int sqlite3WhereContinueLabel(WhereInfo *pWInfo){
drha22a75e2014-03-21 18:16:23 +000059 assert( pWInfo->iContinue!=0 );
drh6f328482013-06-05 23:39:34 +000060 return pWInfo->iContinue;
61}
62
63/*
64** Return the VDBE address or label to jump to in order to break
65** out of a WHERE loop.
66*/
67int sqlite3WhereBreakLabel(WhereInfo *pWInfo){
68 return pWInfo->iBreak;
69}
70
71/*
72** Return TRUE if an UPDATE or DELETE statement can operate directly on
73** the rowids returned by a WHERE clause. Return FALSE if doing an
74** UPDATE or DELETE might change subsequent WHERE clause results.
drhfc8d4f92013-11-08 15:19:46 +000075**
76** If the ONEPASS optimization is used (if this routine returns true)
77** then also write the indices of open cursors used by ONEPASS
78** into aiCur[0] and aiCur[1]. iaCur[0] gets the cursor of the data
79** table and iaCur[1] gets the cursor used by an auxiliary index.
80** Either value may be -1, indicating that cursor is not used.
81** Any cursors returned will have been opened for writing.
82**
83** aiCur[0] and aiCur[1] both get -1 if the where-clause logic is
84** unable to use the ONEPASS optimization.
drh6f328482013-06-05 23:39:34 +000085*/
drhfc8d4f92013-11-08 15:19:46 +000086int sqlite3WhereOkOnePass(WhereInfo *pWInfo, int *aiCur){
87 memcpy(aiCur, pWInfo->aiCurOnePass, sizeof(int)*2);
drh6f328482013-06-05 23:39:34 +000088 return pWInfo->okOnePass;
89}
90
91/*
drhaa32e3c2013-07-16 21:31:23 +000092** Move the content of pSrc into pDest
93*/
94static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){
95 pDest->n = pSrc->n;
96 memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0]));
97}
98
99/*
100** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet.
101**
102** The new entry might overwrite an existing entry, or it might be
103** appended, or it might be discarded. Do whatever is the right thing
104** so that pSet keeps the N_OR_COST best entries seen so far.
105*/
106static int whereOrInsert(
107 WhereOrSet *pSet, /* The WhereOrSet to be updated */
108 Bitmask prereq, /* Prerequisites of the new entry */
drhbf539c42013-10-05 18:16:02 +0000109 LogEst rRun, /* Run-cost of the new entry */
110 LogEst nOut /* Number of outputs for the new entry */
drhaa32e3c2013-07-16 21:31:23 +0000111){
112 u16 i;
113 WhereOrCost *p;
114 for(i=pSet->n, p=pSet->a; i>0; i--, p++){
115 if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){
116 goto whereOrInsert_done;
117 }
118 if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){
119 return 0;
120 }
121 }
122 if( pSet->n<N_OR_COST ){
123 p = &pSet->a[pSet->n++];
124 p->nOut = nOut;
125 }else{
126 p = pSet->a;
127 for(i=1; i<pSet->n; i++){
128 if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i;
129 }
130 if( p->rRun<=rRun ) return 0;
131 }
132whereOrInsert_done:
133 p->prereq = prereq;
134 p->rRun = rRun;
135 if( p->nOut>nOut ) p->nOut = nOut;
136 return 1;
137}
138
139/*
drh0aa74ed2005-07-16 13:33:20 +0000140** Initialize a preallocated WhereClause structure.
drh75897232000-05-29 14:26:00 +0000141*/
drh7b4fc6a2007-02-06 13:26:32 +0000142static void whereClauseInit(
143 WhereClause *pWC, /* The WhereClause to be initialized */
drh70d18342013-06-06 19:16:33 +0000144 WhereInfo *pWInfo /* The WHERE processing context */
drh7b4fc6a2007-02-06 13:26:32 +0000145){
drh70d18342013-06-06 19:16:33 +0000146 pWC->pWInfo = pWInfo;
drh8871ef52011-10-07 13:33:10 +0000147 pWC->pOuter = 0;
drh0aa74ed2005-07-16 13:33:20 +0000148 pWC->nTerm = 0;
drhcad651e2007-04-20 12:22:01 +0000149 pWC->nSlot = ArraySize(pWC->aStatic);
drh0aa74ed2005-07-16 13:33:20 +0000150 pWC->a = pWC->aStatic;
151}
152
drh700a2262008-12-17 19:22:15 +0000153/* Forward reference */
154static void whereClauseClear(WhereClause*);
155
156/*
157** Deallocate all memory associated with a WhereOrInfo object.
158*/
159static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
drh5bd98ae2009-01-07 18:24:03 +0000160 whereClauseClear(&p->wc);
161 sqlite3DbFree(db, p);
drh700a2262008-12-17 19:22:15 +0000162}
163
164/*
165** Deallocate all memory associated with a WhereAndInfo object.
166*/
167static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
drh5bd98ae2009-01-07 18:24:03 +0000168 whereClauseClear(&p->wc);
169 sqlite3DbFree(db, p);
drh700a2262008-12-17 19:22:15 +0000170}
171
drh0aa74ed2005-07-16 13:33:20 +0000172/*
173** Deallocate a WhereClause structure. The WhereClause structure
174** itself is not freed. This routine is the inverse of whereClauseInit().
175*/
176static void whereClauseClear(WhereClause *pWC){
177 int i;
178 WhereTerm *a;
drh70d18342013-06-06 19:16:33 +0000179 sqlite3 *db = pWC->pWInfo->pParse->db;
drh0aa74ed2005-07-16 13:33:20 +0000180 for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
drh165be382008-12-05 02:36:33 +0000181 if( a->wtFlags & TERM_DYNAMIC ){
drh633e6d52008-07-28 19:34:53 +0000182 sqlite3ExprDelete(db, a->pExpr);
drh0aa74ed2005-07-16 13:33:20 +0000183 }
drh700a2262008-12-17 19:22:15 +0000184 if( a->wtFlags & TERM_ORINFO ){
185 whereOrInfoDelete(db, a->u.pOrInfo);
186 }else if( a->wtFlags & TERM_ANDINFO ){
187 whereAndInfoDelete(db, a->u.pAndInfo);
188 }
drh0aa74ed2005-07-16 13:33:20 +0000189 }
190 if( pWC->a!=pWC->aStatic ){
drh633e6d52008-07-28 19:34:53 +0000191 sqlite3DbFree(db, pWC->a);
drh0aa74ed2005-07-16 13:33:20 +0000192 }
193}
194
195/*
drh6a1e0712008-12-05 15:24:15 +0000196** Add a single new WhereTerm entry to the WhereClause object pWC.
197** The new WhereTerm object is constructed from Expr p and with wtFlags.
198** The index in pWC->a[] of the new WhereTerm is returned on success.
199** 0 is returned if the new WhereTerm could not be added due to a memory
200** allocation error. The memory allocation failure will be recorded in
201** the db->mallocFailed flag so that higher-level functions can detect it.
202**
203** This routine will increase the size of the pWC->a[] array as necessary.
drh9eb20282005-08-24 03:52:18 +0000204**
drh165be382008-12-05 02:36:33 +0000205** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
drh6a1e0712008-12-05 15:24:15 +0000206** for freeing the expression p is assumed by the WhereClause object pWC.
207** This is true even if this routine fails to allocate a new WhereTerm.
drhb63a53d2007-03-31 01:34:44 +0000208**
drh9eb20282005-08-24 03:52:18 +0000209** WARNING: This routine might reallocate the space used to store
drh909626d2008-05-30 14:58:37 +0000210** WhereTerms. All pointers to WhereTerms should be invalidated after
drh9eb20282005-08-24 03:52:18 +0000211** calling this routine. Such pointers may be reinitialized by referencing
212** the pWC->a[] array.
drh0aa74ed2005-07-16 13:33:20 +0000213*/
drhf07cf6e2015-03-06 16:45:16 +0000214static int whereClauseInsert(WhereClause *pWC, Expr *p, u16 wtFlags){
drh0aa74ed2005-07-16 13:33:20 +0000215 WhereTerm *pTerm;
drh9eb20282005-08-24 03:52:18 +0000216 int idx;
drh39759742013-08-02 23:40:45 +0000217 testcase( wtFlags & TERM_VIRTUAL );
drh0aa74ed2005-07-16 13:33:20 +0000218 if( pWC->nTerm>=pWC->nSlot ){
219 WhereTerm *pOld = pWC->a;
drh70d18342013-06-06 19:16:33 +0000220 sqlite3 *db = pWC->pWInfo->pParse->db;
drh633e6d52008-07-28 19:34:53 +0000221 pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
drhb63a53d2007-03-31 01:34:44 +0000222 if( pWC->a==0 ){
drh165be382008-12-05 02:36:33 +0000223 if( wtFlags & TERM_DYNAMIC ){
drh633e6d52008-07-28 19:34:53 +0000224 sqlite3ExprDelete(db, p);
drhb63a53d2007-03-31 01:34:44 +0000225 }
drhf998b732007-11-26 13:36:00 +0000226 pWC->a = pOld;
drhb63a53d2007-03-31 01:34:44 +0000227 return 0;
228 }
drh0aa74ed2005-07-16 13:33:20 +0000229 memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
230 if( pOld!=pWC->aStatic ){
drh633e6d52008-07-28 19:34:53 +0000231 sqlite3DbFree(db, pOld);
drh0aa74ed2005-07-16 13:33:20 +0000232 }
drh6a1e0712008-12-05 15:24:15 +0000233 pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
drhfe32daa2014-12-05 19:50:58 +0000234 memset(&pWC->a[pWC->nTerm], 0, sizeof(pWC->a[0])*(pWC->nSlot-pWC->nTerm));
drh0aa74ed2005-07-16 13:33:20 +0000235 }
drh6a1e0712008-12-05 15:24:15 +0000236 pTerm = &pWC->a[idx = pWC->nTerm++];
drha4c3c872013-09-12 17:29:25 +0000237 if( p && ExprHasProperty(p, EP_Unlikely) ){
drhd05ab6a2014-10-25 13:42:16 +0000238 pTerm->truthProb = sqlite3LogEst(p->iTable) - 270;
drhcca9f3d2013-09-06 15:23:29 +0000239 }else{
danaa9933c2014-04-24 20:04:49 +0000240 pTerm->truthProb = 1;
drhcca9f3d2013-09-06 15:23:29 +0000241 }
drh7ee751d2012-12-19 15:53:51 +0000242 pTerm->pExpr = sqlite3ExprSkipCollate(p);
drh165be382008-12-05 02:36:33 +0000243 pTerm->wtFlags = wtFlags;
drh0fcef5e2005-07-19 17:38:22 +0000244 pTerm->pWC = pWC;
drh45b1ee42005-08-02 17:48:22 +0000245 pTerm->iParent = -1;
drh9eb20282005-08-24 03:52:18 +0000246 return idx;
drh0aa74ed2005-07-16 13:33:20 +0000247}
drh75897232000-05-29 14:26:00 +0000248
249/*
drh51669862004-12-18 18:40:26 +0000250** This routine identifies subexpressions in the WHERE clause where
drhb6fb62d2005-09-20 08:47:20 +0000251** each subexpression is separated by the AND operator or some other
drh6c30be82005-07-29 15:10:17 +0000252** operator specified in the op parameter. The WhereClause structure
253** is filled with pointers to subexpressions. For example:
drh75897232000-05-29 14:26:00 +0000254**
drh51669862004-12-18 18:40:26 +0000255** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
256** \________/ \_______________/ \________________/
257** slot[0] slot[1] slot[2]
258**
259** The original WHERE clause in pExpr is unaltered. All this routine
drh51147ba2005-07-23 22:59:55 +0000260** does is make slot[] entries point to substructure within pExpr.
drh51669862004-12-18 18:40:26 +0000261**
drh51147ba2005-07-23 22:59:55 +0000262** In the previous sentence and in the diagram, "slot[]" refers to
drh902b9ee2008-12-05 17:17:07 +0000263** the WhereClause.a[] array. The slot[] array grows as needed to contain
drh51147ba2005-07-23 22:59:55 +0000264** all terms of the WHERE clause.
drh75897232000-05-29 14:26:00 +0000265*/
drh74f91d42013-06-19 18:01:44 +0000266static void whereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
drh0f517ea2015-04-21 02:12:13 +0000267 Expr *pE2 = sqlite3ExprSkipCollate(pExpr);
drh74f91d42013-06-19 18:01:44 +0000268 pWC->op = op;
drh0f517ea2015-04-21 02:12:13 +0000269 if( pE2==0 ) return;
270 if( pE2->op!=op ){
drh0aa74ed2005-07-16 13:33:20 +0000271 whereClauseInsert(pWC, pExpr, 0);
drh75897232000-05-29 14:26:00 +0000272 }else{
drh0f517ea2015-04-21 02:12:13 +0000273 whereSplit(pWC, pE2->pLeft, op);
274 whereSplit(pWC, pE2->pRight, op);
drh75897232000-05-29 14:26:00 +0000275 }
drh75897232000-05-29 14:26:00 +0000276}
277
278/*
drh3b48e8c2013-06-12 20:18:16 +0000279** Initialize a WhereMaskSet object
drh6a3ea0e2003-05-02 14:32:12 +0000280*/
drhfd5874d2013-06-12 14:52:39 +0000281#define initMaskSet(P) (P)->n=0
drh6a3ea0e2003-05-02 14:32:12 +0000282
283/*
drh1398ad32005-01-19 23:24:50 +0000284** Return the bitmask for the given cursor number. Return 0 if
285** iCursor is not in the set.
drh6a3ea0e2003-05-02 14:32:12 +0000286*/
drh6f82e852015-06-06 20:12:09 +0000287Bitmask sqlite3WhereGetMask(WhereMaskSet *pMaskSet, int iCursor){
drh6a3ea0e2003-05-02 14:32:12 +0000288 int i;
drhfcd71b62011-04-05 22:08:24 +0000289 assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
drh6a3ea0e2003-05-02 14:32:12 +0000290 for(i=0; i<pMaskSet->n; i++){
drh51669862004-12-18 18:40:26 +0000291 if( pMaskSet->ix[i]==iCursor ){
drh7699d1c2013-06-04 12:42:29 +0000292 return MASKBIT(i);
drh51669862004-12-18 18:40:26 +0000293 }
drh6a3ea0e2003-05-02 14:32:12 +0000294 }
drh6a3ea0e2003-05-02 14:32:12 +0000295 return 0;
296}
297
298/*
drh1398ad32005-01-19 23:24:50 +0000299** Create a new mask for cursor iCursor.
drh0fcef5e2005-07-19 17:38:22 +0000300**
301** There is one cursor per table in the FROM clause. The number of
302** tables in the FROM clause is limited by a test early in the
drhb6fb62d2005-09-20 08:47:20 +0000303** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[]
drh0fcef5e2005-07-19 17:38:22 +0000304** array will never overflow.
drh1398ad32005-01-19 23:24:50 +0000305*/
drh111a6a72008-12-21 03:51:16 +0000306static void createMask(WhereMaskSet *pMaskSet, int iCursor){
drhcad651e2007-04-20 12:22:01 +0000307 assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
drh0fcef5e2005-07-19 17:38:22 +0000308 pMaskSet->ix[pMaskSet->n++] = iCursor;
drh1398ad32005-01-19 23:24:50 +0000309}
310
311/*
drh4a6fc352013-08-07 01:18:38 +0000312** These routines walk (recursively) an expression tree and generate
drh75897232000-05-29 14:26:00 +0000313** a bitmask indicating which tables are used in that expression
drh6a3ea0e2003-05-02 14:32:12 +0000314** tree.
drh75897232000-05-29 14:26:00 +0000315*/
drh111a6a72008-12-21 03:51:16 +0000316static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
317static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
318static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
drh51669862004-12-18 18:40:26 +0000319 Bitmask mask = 0;
drh75897232000-05-29 14:26:00 +0000320 if( p==0 ) return 0;
drh967e8b72000-06-21 13:59:10 +0000321 if( p->op==TK_COLUMN ){
drh6f82e852015-06-06 20:12:09 +0000322 mask = sqlite3WhereGetMask(pMaskSet, p->iTable);
drh8feb4b12004-07-19 02:12:14 +0000323 return mask;
drh75897232000-05-29 14:26:00 +0000324 }
danielk1977b3bce662005-01-29 08:32:43 +0000325 mask = exprTableUsage(pMaskSet, p->pRight);
326 mask |= exprTableUsage(pMaskSet, p->pLeft);
danielk19776ab3a2e2009-02-19 14:39:25 +0000327 if( ExprHasProperty(p, EP_xIsSelect) ){
328 mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
329 }else{
330 mask |= exprListTableUsage(pMaskSet, p->x.pList);
331 }
danielk1977b3bce662005-01-29 08:32:43 +0000332 return mask;
333}
drh111a6a72008-12-21 03:51:16 +0000334static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
danielk1977b3bce662005-01-29 08:32:43 +0000335 int i;
336 Bitmask mask = 0;
337 if( pList ){
338 for(i=0; i<pList->nExpr; i++){
339 mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
drhdd579122002-04-02 01:58:57 +0000340 }
341 }
drh75897232000-05-29 14:26:00 +0000342 return mask;
343}
drh111a6a72008-12-21 03:51:16 +0000344static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
drha430ae82007-09-12 15:41:01 +0000345 Bitmask mask = 0;
346 while( pS ){
drha464c232011-09-16 19:04:03 +0000347 SrcList *pSrc = pS->pSrc;
drha430ae82007-09-12 15:41:01 +0000348 mask |= exprListTableUsage(pMaskSet, pS->pEList);
drhf5b11382005-09-17 13:07:13 +0000349 mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
350 mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
351 mask |= exprTableUsage(pMaskSet, pS->pWhere);
352 mask |= exprTableUsage(pMaskSet, pS->pHaving);
drha464c232011-09-16 19:04:03 +0000353 if( ALWAYS(pSrc!=0) ){
drh88501772011-09-16 17:43:06 +0000354 int i;
355 for(i=0; i<pSrc->nSrc; i++){
356 mask |= exprSelectTableUsage(pMaskSet, pSrc->a[i].pSelect);
357 mask |= exprTableUsage(pMaskSet, pSrc->a[i].pOn);
358 }
359 }
drha430ae82007-09-12 15:41:01 +0000360 pS = pS->pPrior;
drhf5b11382005-09-17 13:07:13 +0000361 }
362 return mask;
363}
drh75897232000-05-29 14:26:00 +0000364
365/*
drh487ab3c2001-11-08 00:45:21 +0000366** Return TRUE if the given operator is one of the operators that is
drh51669862004-12-18 18:40:26 +0000367** allowed for an indexable WHERE clause term. The allowed operators are
drh3b48e8c2013-06-12 20:18:16 +0000368** "=", "<", ">", "<=", ">=", "IN", and "IS NULL"
drh487ab3c2001-11-08 00:45:21 +0000369*/
370static int allowedOp(int op){
drhfe05af82005-07-21 03:14:59 +0000371 assert( TK_GT>TK_EQ && TK_GT<TK_GE );
372 assert( TK_LT>TK_EQ && TK_LT<TK_GE );
373 assert( TK_LE>TK_EQ && TK_LE<TK_GE );
374 assert( TK_GE==TK_EQ+4 );
drhfcd49532015-05-13 15:24:07 +0000375 return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL || op==TK_IS;
drh487ab3c2001-11-08 00:45:21 +0000376}
377
378/*
drh909626d2008-05-30 14:58:37 +0000379** Commute a comparison operator. Expressions of the form "X op Y"
drh0fcef5e2005-07-19 17:38:22 +0000380** are converted into "Y op X".
danielk1977eb5453d2007-07-30 14:40:48 +0000381**
mistachkin48864df2013-03-21 21:20:32 +0000382** If left/right precedence rules come into play when determining the
drh3b48e8c2013-06-12 20:18:16 +0000383** collating sequence, then COLLATE operators are adjusted to ensure
384** that the collating sequence does not change. For example:
385** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on
danielk1977eb5453d2007-07-30 14:40:48 +0000386** the left hand side of a comparison overrides any collation sequence
drhae80dde2012-12-06 21:16:43 +0000387** attached to the right. For the same reason the EP_Collate flag
danielk1977eb5453d2007-07-30 14:40:48 +0000388** is not commuted.
drh193bd772004-07-20 18:23:14 +0000389*/
drh7d10d5a2008-08-20 16:35:10 +0000390static void exprCommute(Parse *pParse, Expr *pExpr){
drhae80dde2012-12-06 21:16:43 +0000391 u16 expRight = (pExpr->pRight->flags & EP_Collate);
392 u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
drhfe05af82005-07-21 03:14:59 +0000393 assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
drhae80dde2012-12-06 21:16:43 +0000394 if( expRight==expLeft ){
395 /* Either X and Y both have COLLATE operator or neither do */
396 if( expRight ){
397 /* Both X and Y have COLLATE operators. Make sure X is always
398 ** used by clearing the EP_Collate flag from Y. */
399 pExpr->pRight->flags &= ~EP_Collate;
400 }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
401 /* Neither X nor Y have COLLATE operators, but X has a non-default
402 ** collating sequence. So add the EP_Collate marker on X to cause
403 ** it to be searched first. */
404 pExpr->pLeft->flags |= EP_Collate;
405 }
406 }
drh0fcef5e2005-07-19 17:38:22 +0000407 SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
408 if( pExpr->op>=TK_GT ){
409 assert( TK_LT==TK_GT+2 );
410 assert( TK_GE==TK_LE+2 );
411 assert( TK_GT>TK_EQ );
412 assert( TK_GT<TK_LE );
413 assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
414 pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
drh193bd772004-07-20 18:23:14 +0000415 }
drh193bd772004-07-20 18:23:14 +0000416}
417
418/*
drhfe05af82005-07-21 03:14:59 +0000419** Translate from TK_xx operator to WO_xx bitmask.
420*/
drhec1724e2008-12-09 01:32:03 +0000421static u16 operatorMask(int op){
422 u16 c;
drhfe05af82005-07-21 03:14:59 +0000423 assert( allowedOp(op) );
424 if( op==TK_IN ){
drh51147ba2005-07-23 22:59:55 +0000425 c = WO_IN;
drh50b39962006-10-28 00:28:09 +0000426 }else if( op==TK_ISNULL ){
427 c = WO_ISNULL;
drhfcd49532015-05-13 15:24:07 +0000428 }else if( op==TK_IS ){
drhe8d0c612015-05-14 01:05:25 +0000429 c = WO_IS;
drhfe05af82005-07-21 03:14:59 +0000430 }else{
drhec1724e2008-12-09 01:32:03 +0000431 assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
432 c = (u16)(WO_EQ<<(op-TK_EQ));
drhfe05af82005-07-21 03:14:59 +0000433 }
drh50b39962006-10-28 00:28:09 +0000434 assert( op!=TK_ISNULL || c==WO_ISNULL );
drh51147ba2005-07-23 22:59:55 +0000435 assert( op!=TK_IN || c==WO_IN );
436 assert( op!=TK_EQ || c==WO_EQ );
437 assert( op!=TK_LT || c==WO_LT );
438 assert( op!=TK_LE || c==WO_LE );
439 assert( op!=TK_GT || c==WO_GT );
440 assert( op!=TK_GE || c==WO_GE );
drhe8d0c612015-05-14 01:05:25 +0000441 assert( op!=TK_IS || c==WO_IS );
drh51147ba2005-07-23 22:59:55 +0000442 return c;
drhfe05af82005-07-21 03:14:59 +0000443}
444
445/*
drh1c8148f2013-05-04 20:25:23 +0000446** Advance to the next WhereTerm that matches according to the criteria
447** established when the pScan object was initialized by whereScanInit().
448** Return NULL if there are no more matching WhereTerms.
449*/
danb2cfc142013-07-05 11:10:54 +0000450static WhereTerm *whereScanNext(WhereScan *pScan){
drh1c8148f2013-05-04 20:25:23 +0000451 int iCur; /* The cursor on the LHS of the term */
452 int iColumn; /* The column on the LHS of the term. -1 for IPK */
453 Expr *pX; /* An expression being tested */
454 WhereClause *pWC; /* Shorthand for pScan->pWC */
455 WhereTerm *pTerm; /* The term being tested */
drh43b85ef2013-06-10 12:34:45 +0000456 int k = pScan->k; /* Where to start scanning */
drh1c8148f2013-05-04 20:25:23 +0000457
458 while( pScan->iEquiv<=pScan->nEquiv ){
459 iCur = pScan->aEquiv[pScan->iEquiv-2];
460 iColumn = pScan->aEquiv[pScan->iEquiv-1];
461 while( (pWC = pScan->pWC)!=0 ){
drh43b85ef2013-06-10 12:34:45 +0000462 for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
drhe1a086e2013-10-28 20:15:56 +0000463 if( pTerm->leftCursor==iCur
464 && pTerm->u.leftColumn==iColumn
465 && (pScan->iEquiv<=2 || !ExprHasProperty(pTerm->pExpr, EP_FromJoin))
466 ){
drh1c8148f2013-05-04 20:25:23 +0000467 if( (pTerm->eOperator & WO_EQUIV)!=0
468 && pScan->nEquiv<ArraySize(pScan->aEquiv)
469 ){
470 int j;
471 pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight);
472 assert( pX->op==TK_COLUMN );
473 for(j=0; j<pScan->nEquiv; j+=2){
474 if( pScan->aEquiv[j]==pX->iTable
475 && pScan->aEquiv[j+1]==pX->iColumn ){
476 break;
477 }
478 }
479 if( j==pScan->nEquiv ){
480 pScan->aEquiv[j] = pX->iTable;
481 pScan->aEquiv[j+1] = pX->iColumn;
482 pScan->nEquiv += 2;
483 }
484 }
485 if( (pTerm->eOperator & pScan->opMask)!=0 ){
486 /* Verify the affinity and collating sequence match */
487 if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
488 CollSeq *pColl;
drh70d18342013-06-06 19:16:33 +0000489 Parse *pParse = pWC->pWInfo->pParse;
drh1c8148f2013-05-04 20:25:23 +0000490 pX = pTerm->pExpr;
491 if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
492 continue;
493 }
494 assert(pX->pLeft);
drh70d18342013-06-06 19:16:33 +0000495 pColl = sqlite3BinaryCompareCollSeq(pParse,
drh1c8148f2013-05-04 20:25:23 +0000496 pX->pLeft, pX->pRight);
drh70d18342013-06-06 19:16:33 +0000497 if( pColl==0 ) pColl = pParse->db->pDfltColl;
drh1c8148f2013-05-04 20:25:23 +0000498 if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
499 continue;
500 }
501 }
drhe8d0c612015-05-14 01:05:25 +0000502 if( (pTerm->eOperator & (WO_EQ|WO_IS))!=0
drha184fb82013-05-08 04:22:59 +0000503 && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN
504 && pX->iTable==pScan->aEquiv[0]
505 && pX->iColumn==pScan->aEquiv[1]
506 ){
drhe8d0c612015-05-14 01:05:25 +0000507 testcase( pTerm->eOperator & WO_IS );
drha184fb82013-05-08 04:22:59 +0000508 continue;
509 }
drh43b85ef2013-06-10 12:34:45 +0000510 pScan->k = k+1;
drh1c8148f2013-05-04 20:25:23 +0000511 return pTerm;
512 }
513 }
514 }
drhad01d892013-06-19 13:59:49 +0000515 pScan->pWC = pScan->pWC->pOuter;
drh43b85ef2013-06-10 12:34:45 +0000516 k = 0;
drh1c8148f2013-05-04 20:25:23 +0000517 }
518 pScan->pWC = pScan->pOrigWC;
drh43b85ef2013-06-10 12:34:45 +0000519 k = 0;
drh1c8148f2013-05-04 20:25:23 +0000520 pScan->iEquiv += 2;
521 }
drh1c8148f2013-05-04 20:25:23 +0000522 return 0;
523}
524
525/*
526** Initialize a WHERE clause scanner object. Return a pointer to the
527** first match. Return NULL if there are no matches.
528**
529** The scanner will be searching the WHERE clause pWC. It will look
530** for terms of the form "X <op> <expr>" where X is column iColumn of table
531** iCur. The <op> must be one of the operators described by opMask.
532**
drh3b48e8c2013-06-12 20:18:16 +0000533** If the search is for X and the WHERE clause contains terms of the
534** form X=Y then this routine might also return terms of the form
535** "Y <op> <expr>". The number of levels of transitivity is limited,
536** but is enough to handle most commonly occurring SQL statements.
537**
drh1c8148f2013-05-04 20:25:23 +0000538** If X is not the INTEGER PRIMARY KEY then X must be compatible with
539** index pIdx.
540*/
danb2cfc142013-07-05 11:10:54 +0000541static WhereTerm *whereScanInit(
drh1c8148f2013-05-04 20:25:23 +0000542 WhereScan *pScan, /* The WhereScan object being initialized */
543 WhereClause *pWC, /* The WHERE clause to be scanned */
544 int iCur, /* Cursor to scan for */
545 int iColumn, /* Column to scan for */
546 u32 opMask, /* Operator(s) to scan for */
547 Index *pIdx /* Must be compatible with this index */
548){
549 int j;
550
drhe9d935a2013-06-05 16:19:59 +0000551 /* memset(pScan, 0, sizeof(*pScan)); */
drh1c8148f2013-05-04 20:25:23 +0000552 pScan->pOrigWC = pWC;
553 pScan->pWC = pWC;
554 if( pIdx && iColumn>=0 ){
555 pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
556 for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
dan39129ce2014-06-30 15:23:57 +0000557 if( NEVER(j>pIdx->nColumn) ) return 0;
drh1c8148f2013-05-04 20:25:23 +0000558 }
559 pScan->zCollName = pIdx->azColl[j];
drhe9d935a2013-06-05 16:19:59 +0000560 }else{
561 pScan->idxaff = 0;
562 pScan->zCollName = 0;
drh1c8148f2013-05-04 20:25:23 +0000563 }
564 pScan->opMask = opMask;
drhe9d935a2013-06-05 16:19:59 +0000565 pScan->k = 0;
drh1c8148f2013-05-04 20:25:23 +0000566 pScan->aEquiv[0] = iCur;
567 pScan->aEquiv[1] = iColumn;
568 pScan->nEquiv = 2;
569 pScan->iEquiv = 2;
570 return whereScanNext(pScan);
571}
572
573/*
drhfe05af82005-07-21 03:14:59 +0000574** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
575** where X is a reference to the iColumn of table iCur and <op> is one of
576** the WO_xx operator codes specified by the op parameter.
577** Return a pointer to the term. Return 0 if not found.
drh58eb1c02013-01-17 00:08:42 +0000578**
579** The term returned might by Y=<expr> if there is another constraint in
580** the WHERE clause that specifies that X=Y. Any such constraints will be
581** identified by the WO_EQUIV bit in the pTerm->eOperator field. The
582** aEquiv[] array holds X and all its equivalents, with each SQL variable
583** taking up two slots in aEquiv[]. The first slot is for the cursor number
584** and the second is for the column number. There are 22 slots in aEquiv[]
585** so that means we can look for X plus up to 10 other equivalent values.
586** Hence a search for X will return <expr> if X=A1 and A1=A2 and A2=A3
587** and ... and A9=A10 and A10=<expr>.
588**
589** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
590** then try for the one with no dependencies on <expr> - in other words where
591** <expr> is a constant expression of some kind. Only return entries of
592** the form "X <op> Y" where Y is a column in another table if no terms of
drh459f63e2013-03-06 01:55:27 +0000593** the form "X <op> <const-expr>" exist. If no terms with a constant RHS
594** exist, try to return a term that does not use WO_EQUIV.
drhfe05af82005-07-21 03:14:59 +0000595*/
drh6f82e852015-06-06 20:12:09 +0000596WhereTerm *sqlite3WhereFindTerm(
drhfe05af82005-07-21 03:14:59 +0000597 WhereClause *pWC, /* The WHERE clause to be searched */
598 int iCur, /* Cursor number of LHS */
599 int iColumn, /* Column number of LHS */
600 Bitmask notReady, /* RHS must not overlap with this mask */
drhec1724e2008-12-09 01:32:03 +0000601 u32 op, /* Mask of WO_xx values describing operator */
drhfe05af82005-07-21 03:14:59 +0000602 Index *pIdx /* Must be compatible with this index, if not NULL */
603){
drh1c8148f2013-05-04 20:25:23 +0000604 WhereTerm *pResult = 0;
605 WhereTerm *p;
606 WhereScan scan;
drh7a5bcc02013-01-16 17:08:58 +0000607
drh1c8148f2013-05-04 20:25:23 +0000608 p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
drhe8d0c612015-05-14 01:05:25 +0000609 op &= WO_EQ|WO_IS;
drh1c8148f2013-05-04 20:25:23 +0000610 while( p ){
611 if( (p->prereqRight & notReady)==0 ){
drhe8d0c612015-05-14 01:05:25 +0000612 if( p->prereqRight==0 && (p->eOperator&op)!=0 ){
613 testcase( p->eOperator & WO_IS );
drh1c8148f2013-05-04 20:25:23 +0000614 return p;
drhfe05af82005-07-21 03:14:59 +0000615 }
drh1c8148f2013-05-04 20:25:23 +0000616 if( pResult==0 ) pResult = p;
drhfe05af82005-07-21 03:14:59 +0000617 }
drh1c8148f2013-05-04 20:25:23 +0000618 p = whereScanNext(&scan);
drhfe05af82005-07-21 03:14:59 +0000619 }
drh7a5bcc02013-01-16 17:08:58 +0000620 return pResult;
drhfe05af82005-07-21 03:14:59 +0000621}
622
drh6c30be82005-07-29 15:10:17 +0000623/* Forward reference */
drh7b4fc6a2007-02-06 13:26:32 +0000624static void exprAnalyze(SrcList*, WhereClause*, int);
drh6c30be82005-07-29 15:10:17 +0000625
626/*
627** Call exprAnalyze on all terms in a WHERE clause.
drhb121dd12015-06-06 18:30:17 +0000628**
629** Note that exprAnalyze() might add new virtual terms onto the
630** end of the WHERE clause. We do not want to analyze these new
631** virtual terms, so start analyzing at the end and work forward
632** so that the added virtual terms are never processed.
drh6c30be82005-07-29 15:10:17 +0000633*/
634static void exprAnalyzeAll(
635 SrcList *pTabList, /* the FROM clause */
drh6c30be82005-07-29 15:10:17 +0000636 WhereClause *pWC /* the WHERE clause to be analyzed */
637){
drh6c30be82005-07-29 15:10:17 +0000638 int i;
drh9eb20282005-08-24 03:52:18 +0000639 for(i=pWC->nTerm-1; i>=0; i--){
drh7b4fc6a2007-02-06 13:26:32 +0000640 exprAnalyze(pTabList, pWC, i);
drh6c30be82005-07-29 15:10:17 +0000641 }
642}
643
drhd2687b72005-08-12 22:56:09 +0000644#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
645/*
646** Check to see if the given expression is a LIKE or GLOB operator that
647** can be optimized using inequality constraints. Return TRUE if it is
648** so and false if not.
649**
650** In order for the operator to be optimizible, the RHS must be a string
drhf07cf6e2015-03-06 16:45:16 +0000651** literal that does not begin with a wildcard. The LHS must be a column
652** that may only be NULL, a string, or a BLOB, never a number. (This means
drhe655a0e2015-05-16 18:31:44 +0000653** that virtual tables cannot participate in the LIKE optimization.) The
drhf07cf6e2015-03-06 16:45:16 +0000654** collating sequence for the column on the LHS must be appropriate for
655** the operator.
drhd2687b72005-08-12 22:56:09 +0000656*/
657static int isLikeOrGlob(
drh7d10d5a2008-08-20 16:35:10 +0000658 Parse *pParse, /* Parsing and code generating context */
drhd2687b72005-08-12 22:56:09 +0000659 Expr *pExpr, /* Test this expression */
dan937d0de2009-10-15 18:35:38 +0000660 Expr **ppPrefix, /* Pointer to TK_STRING expression with pattern prefix */
drh9f504ea2008-02-23 21:55:39 +0000661 int *pisComplete, /* True if the only wildcard is % in the last character */
662 int *pnoCase /* True if uppercase is equivalent to lowercase */
drhd2687b72005-08-12 22:56:09 +0000663){
dan937d0de2009-10-15 18:35:38 +0000664 const char *z = 0; /* String on RHS of LIKE operator */
drh5bd98ae2009-01-07 18:24:03 +0000665 Expr *pRight, *pLeft; /* Right and left size of LIKE operator */
666 ExprList *pList; /* List of operands to the LIKE operator */
667 int c; /* One character in z[] */
668 int cnt; /* Number of non-wildcard prefix characters */
669 char wc[3]; /* Wildcard characters */
drh5bd98ae2009-01-07 18:24:03 +0000670 sqlite3 *db = pParse->db; /* Database connection */
dan937d0de2009-10-15 18:35:38 +0000671 sqlite3_value *pVal = 0;
672 int op; /* Opcode of pRight */
drhd64fe2f2005-08-28 17:00:23 +0000673
drh9f504ea2008-02-23 21:55:39 +0000674 if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
drhd2687b72005-08-12 22:56:09 +0000675 return 0;
676 }
drh9f504ea2008-02-23 21:55:39 +0000677#ifdef SQLITE_EBCDIC
678 if( *pnoCase ) return 0;
679#endif
danielk19776ab3a2e2009-02-19 14:39:25 +0000680 pList = pExpr->x.pList;
drh55ef4d92005-08-14 01:20:37 +0000681 pLeft = pList->a[1].pExpr;
danc68939e2012-03-29 14:29:07 +0000682 if( pLeft->op!=TK_COLUMN
683 || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
drhf07cf6e2015-03-06 16:45:16 +0000684 || IsVirtual(pLeft->pTab) /* Value might be numeric */
danc68939e2012-03-29 14:29:07 +0000685 ){
drhd91ca492009-10-22 20:50:36 +0000686 /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
687 ** be the name of an indexed column with TEXT affinity. */
drhd2687b72005-08-12 22:56:09 +0000688 return 0;
689 }
drhd91ca492009-10-22 20:50:36 +0000690 assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
dan937d0de2009-10-15 18:35:38 +0000691
drh6ade4532014-01-16 15:31:41 +0000692 pRight = sqlite3ExprSkipCollate(pList->a[0].pExpr);
dan937d0de2009-10-15 18:35:38 +0000693 op = pRight->op;
dan937d0de2009-10-15 18:35:38 +0000694 if( op==TK_VARIABLE ){
695 Vdbe *pReprepare = pParse->pReprepare;
drha7044002010-09-14 18:22:59 +0000696 int iCol = pRight->iColumn;
drh05883a32015-06-02 15:32:08 +0000697 pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_BLOB);
dan937d0de2009-10-15 18:35:38 +0000698 if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
699 z = (char *)sqlite3_value_text(pVal);
700 }
drhf9b22ca2011-10-21 16:47:31 +0000701 sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
dan937d0de2009-10-15 18:35:38 +0000702 assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
703 }else if( op==TK_STRING ){
704 z = pRight->u.zToken;
705 }
706 if( z ){
shane85095702009-06-15 16:27:08 +0000707 cnt = 0;
drhb7916a72009-05-27 10:31:29 +0000708 while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
drh24fb6272009-05-01 21:13:36 +0000709 cnt++;
710 }
drh93ee23c2010-07-22 12:33:57 +0000711 if( cnt!=0 && 255!=(u8)z[cnt-1] ){
dan937d0de2009-10-15 18:35:38 +0000712 Expr *pPrefix;
drh93ee23c2010-07-22 12:33:57 +0000713 *pisComplete = c==wc[0] && z[cnt+1]==0;
dan937d0de2009-10-15 18:35:38 +0000714 pPrefix = sqlite3Expr(db, TK_STRING, z);
715 if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
716 *ppPrefix = pPrefix;
717 if( op==TK_VARIABLE ){
718 Vdbe *v = pParse->pVdbe;
drhf9b22ca2011-10-21 16:47:31 +0000719 sqlite3VdbeSetVarmask(v, pRight->iColumn);
dan937d0de2009-10-15 18:35:38 +0000720 if( *pisComplete && pRight->u.zToken[1] ){
721 /* If the rhs of the LIKE expression is a variable, and the current
722 ** value of the variable means there is no need to invoke the LIKE
723 ** function, then no OP_Variable will be added to the program.
724 ** This causes problems for the sqlite3_bind_parameter_name()
peter.d.reid60ec9142014-09-06 16:39:46 +0000725 ** API. To work around them, add a dummy OP_Variable here.
drhbec451f2009-10-17 13:13:02 +0000726 */
727 int r1 = sqlite3GetTempReg(pParse);
728 sqlite3ExprCodeTarget(pParse, pRight, r1);
dan937d0de2009-10-15 18:35:38 +0000729 sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
drhbec451f2009-10-17 13:13:02 +0000730 sqlite3ReleaseTempReg(pParse, r1);
dan937d0de2009-10-15 18:35:38 +0000731 }
732 }
733 }else{
734 z = 0;
shane85095702009-06-15 16:27:08 +0000735 }
drhf998b732007-11-26 13:36:00 +0000736 }
dan937d0de2009-10-15 18:35:38 +0000737
738 sqlite3ValueFree(pVal);
739 return (z!=0);
drhd2687b72005-08-12 22:56:09 +0000740}
741#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
742
drhedb193b2006-06-27 13:20:21 +0000743
744#ifndef SQLITE_OMIT_VIRTUALTABLE
drhfe05af82005-07-21 03:14:59 +0000745/*
drh7f375902006-06-13 17:38:59 +0000746** Check to see if the given expression is of the form
747**
748** column MATCH expr
749**
750** If it is then return TRUE. If not, return FALSE.
751*/
752static int isMatchOfColumn(
753 Expr *pExpr /* Test this expression */
754){
755 ExprList *pList;
756
757 if( pExpr->op!=TK_FUNCTION ){
758 return 0;
759 }
drh33e619f2009-05-28 01:00:55 +0000760 if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
drh7f375902006-06-13 17:38:59 +0000761 return 0;
762 }
danielk19776ab3a2e2009-02-19 14:39:25 +0000763 pList = pExpr->x.pList;
drh7f375902006-06-13 17:38:59 +0000764 if( pList->nExpr!=2 ){
765 return 0;
766 }
767 if( pList->a[1].pExpr->op != TK_COLUMN ){
768 return 0;
769 }
770 return 1;
771}
drhedb193b2006-06-27 13:20:21 +0000772#endif /* SQLITE_OMIT_VIRTUALTABLE */
drh7f375902006-06-13 17:38:59 +0000773
774/*
drh54a167d2005-11-26 14:08:07 +0000775** If the pBase expression originated in the ON or USING clause of
776** a join, then transfer the appropriate markings over to derived.
777*/
778static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
drhd41d39f2013-08-28 16:27:01 +0000779 if( pDerived ){
780 pDerived->flags |= pBase->flags & EP_FromJoin;
781 pDerived->iRightJoinTable = pBase->iRightJoinTable;
782 }
drh54a167d2005-11-26 14:08:07 +0000783}
784
drh9769efc2014-10-24 14:32:21 +0000785/*
786** Mark term iChild as being a child of term iParent
787*/
788static void markTermAsChild(WhereClause *pWC, int iChild, int iParent){
789 pWC->a[iChild].iParent = iParent;
790 pWC->a[iChild].truthProb = pWC->a[iParent].truthProb;
791 pWC->a[iParent].nChild++;
792}
793
drh84266362015-03-16 12:13:31 +0000794/*
795** Return the N-th AND-connected subterm of pTerm. Or if pTerm is not
796** a conjunction, then return just pTerm when N==0. If N is exceeds
797** the number of available subterms, return NULL.
798*/
799static WhereTerm *whereNthSubterm(WhereTerm *pTerm, int N){
800 if( pTerm->eOperator!=WO_AND ){
801 return N==0 ? pTerm : 0;
802 }
803 if( N<pTerm->u.pAndInfo->wc.nTerm ){
804 return &pTerm->u.pAndInfo->wc.a[N];
805 }
806 return 0;
807}
808
809/*
810** Subterms pOne and pTwo are contained within WHERE clause pWC. The
811** two subterms are in disjunction - they are OR-ed together.
812**
813** If these two terms are both of the form: "A op B" with the same
814** A and B values but different operators and if the operators are
815** compatible (if one is = and the other is <, for example) then
drhc03acf22015-03-16 13:12:34 +0000816** add a new virtual AND term to pWC that is the combination of the
drh84266362015-03-16 12:13:31 +0000817** two.
818**
819** Some examples:
820**
821** x<y OR x=y --> x<=y
822** x=y OR x=y --> x=y
823** x<=y OR x<y --> x<=y
824**
825** The following is NOT generated:
826**
827** x<y OR x>y --> x!=y
828*/
829static void whereCombineDisjuncts(
830 SrcList *pSrc, /* the FROM clause */
831 WhereClause *pWC, /* The complete WHERE clause */
832 WhereTerm *pOne, /* First disjunct */
833 WhereTerm *pTwo /* Second disjunct */
834){
835 u16 eOp = pOne->eOperator | pTwo->eOperator;
836 sqlite3 *db; /* Database connection (for malloc) */
837 Expr *pNew; /* New virtual expression */
838 int op; /* Operator for the combined expression */
839 int idxNew; /* Index in pWC of the next virtual term */
840
841 if( (pOne->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
842 if( (pTwo->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
843 if( (eOp & (WO_EQ|WO_LT|WO_LE))!=eOp
844 && (eOp & (WO_EQ|WO_GT|WO_GE))!=eOp ) return;
845 assert( pOne->pExpr->pLeft!=0 && pOne->pExpr->pRight!=0 );
846 assert( pTwo->pExpr->pLeft!=0 && pTwo->pExpr->pRight!=0 );
847 if( sqlite3ExprCompare(pOne->pExpr->pLeft, pTwo->pExpr->pLeft, -1) ) return;
848 if( sqlite3ExprCompare(pOne->pExpr->pRight, pTwo->pExpr->pRight, -1) )return;
849 /* If we reach this point, it means the two subterms can be combined */
850 if( (eOp & (eOp-1))!=0 ){
851 if( eOp & (WO_LT|WO_LE) ){
852 eOp = WO_LE;
853 }else{
854 assert( eOp & (WO_GT|WO_GE) );
855 eOp = WO_GE;
856 }
857 }
858 db = pWC->pWInfo->pParse->db;
859 pNew = sqlite3ExprDup(db, pOne->pExpr, 0);
860 if( pNew==0 ) return;
861 for(op=TK_EQ; eOp!=(WO_EQ<<(op-TK_EQ)); op++){ assert( op<TK_GE ); }
862 pNew->op = op;
863 idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
864 exprAnalyze(pSrc, pWC, idxNew);
865}
866
drh3e355802007-02-23 23:13:33 +0000867#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
868/*
drh1a58fe02008-12-20 02:06:13 +0000869** Analyze a term that consists of two or more OR-connected
870** subterms. So in:
drh3e355802007-02-23 23:13:33 +0000871**
drh1a58fe02008-12-20 02:06:13 +0000872** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
873** ^^^^^^^^^^^^^^^^^^^^
drh3e355802007-02-23 23:13:33 +0000874**
drh1a58fe02008-12-20 02:06:13 +0000875** This routine analyzes terms such as the middle term in the above example.
876** A WhereOrTerm object is computed and attached to the term under
877** analysis, regardless of the outcome of the analysis. Hence:
drh3e355802007-02-23 23:13:33 +0000878**
drh1a58fe02008-12-20 02:06:13 +0000879** WhereTerm.wtFlags |= TERM_ORINFO
880** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object
drh3e355802007-02-23 23:13:33 +0000881**
drh1a58fe02008-12-20 02:06:13 +0000882** The term being analyzed must have two or more of OR-connected subterms.
danielk1977fdc40192008-12-29 18:33:32 +0000883** A single subterm might be a set of AND-connected sub-subterms.
drh1a58fe02008-12-20 02:06:13 +0000884** Examples of terms under analysis:
drh3e355802007-02-23 23:13:33 +0000885**
drh1a58fe02008-12-20 02:06:13 +0000886** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
887** (B) x=expr1 OR expr2=x OR x=expr3
888** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
889** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
890** (E) (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
drh84266362015-03-16 12:13:31 +0000891** (F) x>A OR (x=A AND y>=B)
drh3e355802007-02-23 23:13:33 +0000892**
drh1a58fe02008-12-20 02:06:13 +0000893** CASE 1:
894**
drhc3e552f2013-02-08 16:04:19 +0000895** If all subterms are of the form T.C=expr for some single column of C and
drh1a58fe02008-12-20 02:06:13 +0000896** a single table T (as shown in example B above) then create a new virtual
897** term that is an equivalent IN expression. In other words, if the term
898** being analyzed is:
899**
900** x = expr1 OR expr2 = x OR x = expr3
901**
902** then create a new virtual term like this:
903**
904** x IN (expr1,expr2,expr3)
905**
906** CASE 2:
907**
drhb121dd12015-06-06 18:30:17 +0000908** If there are exactly two disjuncts and one side has x>A and the other side
drhc03acf22015-03-16 13:12:34 +0000909** has x=A (for the same x and A) then add a new virtual conjunct term to the
910** WHERE clause of the form "x>=A". Example:
911**
912** x>A OR (x=A AND y>B) adds: x>=A
913**
914** The added conjunct can sometimes be helpful in query planning.
drh84266362015-03-16 12:13:31 +0000915**
916** CASE 3:
917**
drh1a58fe02008-12-20 02:06:13 +0000918** If all subterms are indexable by a single table T, then set
919**
920** WhereTerm.eOperator = WO_OR
921** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T
922**
923** A subterm is "indexable" if it is of the form
924** "T.C <op> <expr>" where C is any column of table T and
925** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
926** A subterm is also indexable if it is an AND of two or more
927** subsubterms at least one of which is indexable. Indexable AND
928** subterms have their eOperator set to WO_AND and they have
929** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
930**
931** From another point of view, "indexable" means that the subterm could
932** potentially be used with an index if an appropriate index exists.
933** This analysis does not consider whether or not the index exists; that
drh4a6fc352013-08-07 01:18:38 +0000934** is decided elsewhere. This analysis only looks at whether subterms
935** appropriate for indexing exist.
drh1a58fe02008-12-20 02:06:13 +0000936**
drhb121dd12015-06-06 18:30:17 +0000937** All examples A through E above satisfy case 3. But if a term
peter.d.reid60ec9142014-09-06 16:39:46 +0000938** also satisfies case 1 (such as B) we know that the optimizer will
drhb121dd12015-06-06 18:30:17 +0000939** always prefer case 1, so in that case we pretend that case 3 is not
drh1a58fe02008-12-20 02:06:13 +0000940** satisfied.
941**
942** It might be the case that multiple tables are indexable. For example,
943** (E) above is indexable on tables P, Q, and R.
944**
drhb121dd12015-06-06 18:30:17 +0000945** Terms that satisfy case 3 are candidates for lookup by using
drh1a58fe02008-12-20 02:06:13 +0000946** separate indices to find rowids for each subterm and composing
947** the union of all rowids using a RowSet object. This is similar
948** to "bitmap indices" in other database engines.
949**
950** OTHERWISE:
951**
drhb121dd12015-06-06 18:30:17 +0000952** If none of cases 1, 2, or 3 apply, then leave the eOperator set to
drh1a58fe02008-12-20 02:06:13 +0000953** zero. This term is not useful for search.
drh3e355802007-02-23 23:13:33 +0000954*/
drh1a58fe02008-12-20 02:06:13 +0000955static void exprAnalyzeOrTerm(
956 SrcList *pSrc, /* the FROM clause */
957 WhereClause *pWC, /* the complete WHERE clause */
958 int idxTerm /* Index of the OR-term to be analyzed */
959){
drh70d18342013-06-06 19:16:33 +0000960 WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
961 Parse *pParse = pWInfo->pParse; /* Parser context */
drh1a58fe02008-12-20 02:06:13 +0000962 sqlite3 *db = pParse->db; /* Database connection */
963 WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */
964 Expr *pExpr = pTerm->pExpr; /* The expression of the term */
drh1a58fe02008-12-20 02:06:13 +0000965 int i; /* Loop counters */
966 WhereClause *pOrWc; /* Breakup of pTerm into subterms */
967 WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */
968 WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */
969 Bitmask chngToIN; /* Tables that might satisfy case 1 */
970 Bitmask indexable; /* Tables that are indexable, satisfying case 2 */
drh3e355802007-02-23 23:13:33 +0000971
drh1a58fe02008-12-20 02:06:13 +0000972 /*
973 ** Break the OR clause into its separate subterms. The subterms are
974 ** stored in a WhereClause structure containing within the WhereOrInfo
975 ** object that is attached to the original OR clause term.
976 */
977 assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
978 assert( pExpr->op==TK_OR );
drh954701a2008-12-29 23:45:07 +0000979 pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
drh1a58fe02008-12-20 02:06:13 +0000980 if( pOrInfo==0 ) return;
981 pTerm->wtFlags |= TERM_ORINFO;
982 pOrWc = &pOrInfo->wc;
drh70d18342013-06-06 19:16:33 +0000983 whereClauseInit(pOrWc, pWInfo);
drh1a58fe02008-12-20 02:06:13 +0000984 whereSplit(pOrWc, pExpr, TK_OR);
985 exprAnalyzeAll(pSrc, pOrWc);
986 if( db->mallocFailed ) return;
987 assert( pOrWc->nTerm>=2 );
988
989 /*
drhb121dd12015-06-06 18:30:17 +0000990 ** Compute the set of tables that might satisfy cases 1 or 3.
drh1a58fe02008-12-20 02:06:13 +0000991 */
danielk1977e672c8e2009-05-22 15:43:26 +0000992 indexable = ~(Bitmask)0;
drhc3e552f2013-02-08 16:04:19 +0000993 chngToIN = ~(Bitmask)0;
drh1a58fe02008-12-20 02:06:13 +0000994 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
995 if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
drh29435252008-12-28 18:35:08 +0000996 WhereAndInfo *pAndInfo;
drh29435252008-12-28 18:35:08 +0000997 assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
drh1a58fe02008-12-20 02:06:13 +0000998 chngToIN = 0;
drh29435252008-12-28 18:35:08 +0000999 pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
1000 if( pAndInfo ){
1001 WhereClause *pAndWC;
1002 WhereTerm *pAndTerm;
1003 int j;
1004 Bitmask b = 0;
1005 pOrTerm->u.pAndInfo = pAndInfo;
1006 pOrTerm->wtFlags |= TERM_ANDINFO;
1007 pOrTerm->eOperator = WO_AND;
1008 pAndWC = &pAndInfo->wc;
drh70d18342013-06-06 19:16:33 +00001009 whereClauseInit(pAndWC, pWC->pWInfo);
drh29435252008-12-28 18:35:08 +00001010 whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
1011 exprAnalyzeAll(pSrc, pAndWC);
drh8871ef52011-10-07 13:33:10 +00001012 pAndWC->pOuter = pWC;
drh7c2fbde2009-01-07 20:58:57 +00001013 testcase( db->mallocFailed );
drh96c7a7d2009-01-10 15:34:12 +00001014 if( !db->mallocFailed ){
1015 for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
1016 assert( pAndTerm->pExpr );
1017 if( allowedOp(pAndTerm->pExpr->op) ){
drh6f82e852015-06-06 20:12:09 +00001018 b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
drh96c7a7d2009-01-10 15:34:12 +00001019 }
drh29435252008-12-28 18:35:08 +00001020 }
1021 }
1022 indexable &= b;
1023 }
drh1a58fe02008-12-20 02:06:13 +00001024 }else if( pOrTerm->wtFlags & TERM_COPIED ){
1025 /* Skip this term for now. We revisit it when we process the
1026 ** corresponding TERM_VIRTUAL term */
1027 }else{
1028 Bitmask b;
drh6f82e852015-06-06 20:12:09 +00001029 b = sqlite3WhereGetMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
drh1a58fe02008-12-20 02:06:13 +00001030 if( pOrTerm->wtFlags & TERM_VIRTUAL ){
1031 WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
drh6f82e852015-06-06 20:12:09 +00001032 b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pOther->leftCursor);
drh1a58fe02008-12-20 02:06:13 +00001033 }
1034 indexable &= b;
drh7a5bcc02013-01-16 17:08:58 +00001035 if( (pOrTerm->eOperator & WO_EQ)==0 ){
drh1a58fe02008-12-20 02:06:13 +00001036 chngToIN = 0;
1037 }else{
1038 chngToIN &= b;
1039 }
1040 }
drh3e355802007-02-23 23:13:33 +00001041 }
drh1a58fe02008-12-20 02:06:13 +00001042
1043 /*
drh84266362015-03-16 12:13:31 +00001044 ** Record the set of tables that satisfy case 3. The set might be
drh111a6a72008-12-21 03:51:16 +00001045 ** empty.
drh1a58fe02008-12-20 02:06:13 +00001046 */
1047 pOrInfo->indexable = indexable;
drh111a6a72008-12-21 03:51:16 +00001048 pTerm->eOperator = indexable==0 ? 0 : WO_OR;
drh1a58fe02008-12-20 02:06:13 +00001049
drh84266362015-03-16 12:13:31 +00001050 /* For a two-way OR, attempt to implementation case 2.
1051 */
1052 if( indexable && pOrWc->nTerm==2 ){
1053 int iOne = 0;
1054 WhereTerm *pOne;
1055 while( (pOne = whereNthSubterm(&pOrWc->a[0],iOne++))!=0 ){
1056 int iTwo = 0;
1057 WhereTerm *pTwo;
1058 while( (pTwo = whereNthSubterm(&pOrWc->a[1],iTwo++))!=0 ){
1059 whereCombineDisjuncts(pSrc, pWC, pOne, pTwo);
1060 }
1061 }
1062 }
1063
drh1a58fe02008-12-20 02:06:13 +00001064 /*
1065 ** chngToIN holds a set of tables that *might* satisfy case 1. But
1066 ** we have to do some additional checking to see if case 1 really
1067 ** is satisfied.
drh4e8be3b2009-06-08 17:11:08 +00001068 **
1069 ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means
1070 ** that there is no possibility of transforming the OR clause into an
1071 ** IN operator because one or more terms in the OR clause contain
1072 ** something other than == on a column in the single table. The 1-bit
1073 ** case means that every term of the OR clause is of the form
1074 ** "table.column=expr" for some single table. The one bit that is set
1075 ** will correspond to the common table. We still need to check to make
1076 ** sure the same column is used on all terms. The 2-bit case is when
1077 ** the all terms are of the form "table1.column=table2.column". It
1078 ** might be possible to form an IN operator with either table1.column
1079 ** or table2.column as the LHS if either is common to every term of
1080 ** the OR clause.
1081 **
1082 ** Note that terms of the form "table.column1=table.column2" (the
1083 ** same table on both sizes of the ==) cannot be optimized.
drh1a58fe02008-12-20 02:06:13 +00001084 */
1085 if( chngToIN ){
1086 int okToChngToIN = 0; /* True if the conversion to IN is valid */
1087 int iColumn = -1; /* Column index on lhs of IN operator */
shane63207ab2009-02-04 01:49:30 +00001088 int iCursor = -1; /* Table cursor common to all terms */
drh1a58fe02008-12-20 02:06:13 +00001089 int j = 0; /* Loop counter */
1090
1091 /* Search for a table and column that appears on one side or the
1092 ** other of the == operator in every subterm. That table and column
1093 ** will be recorded in iCursor and iColumn. There might not be any
1094 ** such table and column. Set okToChngToIN if an appropriate table
1095 ** and column is found but leave okToChngToIN false if not found.
1096 */
1097 for(j=0; j<2 && !okToChngToIN; j++){
1098 pOrTerm = pOrWc->a;
1099 for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
drh7a5bcc02013-01-16 17:08:58 +00001100 assert( pOrTerm->eOperator & WO_EQ );
drh1a58fe02008-12-20 02:06:13 +00001101 pOrTerm->wtFlags &= ~TERM_OR_OK;
drh4e8be3b2009-06-08 17:11:08 +00001102 if( pOrTerm->leftCursor==iCursor ){
1103 /* This is the 2-bit case and we are on the second iteration and
1104 ** current term is from the first iteration. So skip this term. */
1105 assert( j==1 );
1106 continue;
1107 }
drh6f82e852015-06-06 20:12:09 +00001108 if( (chngToIN & sqlite3WhereGetMask(&pWInfo->sMaskSet, pOrTerm->leftCursor))==0 ){
drh4e8be3b2009-06-08 17:11:08 +00001109 /* This term must be of the form t1.a==t2.b where t2 is in the
peter.d.reid60ec9142014-09-06 16:39:46 +00001110 ** chngToIN set but t1 is not. This term will be either preceded
drh4e8be3b2009-06-08 17:11:08 +00001111 ** or follwed by an inverted copy (t2.b==t1.a). Skip this term
1112 ** and use its inversion. */
1113 testcase( pOrTerm->wtFlags & TERM_COPIED );
1114 testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
1115 assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
1116 continue;
1117 }
drh1a58fe02008-12-20 02:06:13 +00001118 iColumn = pOrTerm->u.leftColumn;
1119 iCursor = pOrTerm->leftCursor;
1120 break;
1121 }
1122 if( i<0 ){
drh4e8be3b2009-06-08 17:11:08 +00001123 /* No candidate table+column was found. This can only occur
1124 ** on the second iteration */
drh1a58fe02008-12-20 02:06:13 +00001125 assert( j==1 );
drh7a5bcc02013-01-16 17:08:58 +00001126 assert( IsPowerOfTwo(chngToIN) );
drh6f82e852015-06-06 20:12:09 +00001127 assert( chngToIN==sqlite3WhereGetMask(&pWInfo->sMaskSet, iCursor) );
drh1a58fe02008-12-20 02:06:13 +00001128 break;
1129 }
drh4e8be3b2009-06-08 17:11:08 +00001130 testcase( j==1 );
1131
1132 /* We have found a candidate table and column. Check to see if that
1133 ** table and column is common to every term in the OR clause */
drh1a58fe02008-12-20 02:06:13 +00001134 okToChngToIN = 1;
1135 for(; i>=0 && okToChngToIN; i--, pOrTerm++){
drh7a5bcc02013-01-16 17:08:58 +00001136 assert( pOrTerm->eOperator & WO_EQ );
drh1a58fe02008-12-20 02:06:13 +00001137 if( pOrTerm->leftCursor!=iCursor ){
1138 pOrTerm->wtFlags &= ~TERM_OR_OK;
1139 }else if( pOrTerm->u.leftColumn!=iColumn ){
1140 okToChngToIN = 0;
1141 }else{
1142 int affLeft, affRight;
1143 /* If the right-hand side is also a column, then the affinities
1144 ** of both right and left sides must be such that no type
1145 ** conversions are required on the right. (Ticket #2249)
1146 */
1147 affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
1148 affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
1149 if( affRight!=0 && affRight!=affLeft ){
1150 okToChngToIN = 0;
1151 }else{
1152 pOrTerm->wtFlags |= TERM_OR_OK;
1153 }
1154 }
1155 }
1156 }
1157
1158 /* At this point, okToChngToIN is true if original pTerm satisfies
1159 ** case 1. In that case, construct a new virtual term that is
1160 ** pTerm converted into an IN operator.
1161 */
1162 if( okToChngToIN ){
1163 Expr *pDup; /* A transient duplicate expression */
1164 ExprList *pList = 0; /* The RHS of the IN operator */
1165 Expr *pLeft = 0; /* The LHS of the IN operator */
1166 Expr *pNew; /* The complete IN operator */
1167
1168 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
1169 if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
drh7a5bcc02013-01-16 17:08:58 +00001170 assert( pOrTerm->eOperator & WO_EQ );
drh1a58fe02008-12-20 02:06:13 +00001171 assert( pOrTerm->leftCursor==iCursor );
1172 assert( pOrTerm->u.leftColumn==iColumn );
danielk19776ab3a2e2009-02-19 14:39:25 +00001173 pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
drh70d18342013-06-06 19:16:33 +00001174 pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
drh1a58fe02008-12-20 02:06:13 +00001175 pLeft = pOrTerm->pExpr->pLeft;
1176 }
1177 assert( pLeft!=0 );
danielk19776ab3a2e2009-02-19 14:39:25 +00001178 pDup = sqlite3ExprDup(db, pLeft, 0);
drhb7916a72009-05-27 10:31:29 +00001179 pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
drh1a58fe02008-12-20 02:06:13 +00001180 if( pNew ){
1181 int idxNew;
1182 transferJoinMarkings(pNew, pExpr);
danielk19776ab3a2e2009-02-19 14:39:25 +00001183 assert( !ExprHasProperty(pNew, EP_xIsSelect) );
1184 pNew->x.pList = pList;
drh1a58fe02008-12-20 02:06:13 +00001185 idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
1186 testcase( idxNew==0 );
1187 exprAnalyze(pSrc, pWC, idxNew);
1188 pTerm = &pWC->a[idxTerm];
drh9769efc2014-10-24 14:32:21 +00001189 markTermAsChild(pWC, idxNew, idxTerm);
drh1a58fe02008-12-20 02:06:13 +00001190 }else{
1191 sqlite3ExprListDelete(db, pList);
1192 }
drh84266362015-03-16 12:13:31 +00001193 pTerm->eOperator = WO_NOOP; /* case 1 trumps case 3 */
drh1a58fe02008-12-20 02:06:13 +00001194 }
drh3e355802007-02-23 23:13:33 +00001195 }
drh3e355802007-02-23 23:13:33 +00001196}
1197#endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
drh54a167d2005-11-26 14:08:07 +00001198
drh7a5bcc02013-01-16 17:08:58 +00001199/*
drh58201182015-05-16 20:51:25 +00001200** We already know that pExpr is a binary operator where both operands are
1201** column references. This routine checks to see if pExpr is an equivalence
1202** relation:
1203** 1. The SQLITE_Transitive optimization must be enabled
1204** 2. Must be either an == or an IS operator
drhb121dd12015-06-06 18:30:17 +00001205** 3. Not originating in the ON clause of an OUTER JOIN
drh58201182015-05-16 20:51:25 +00001206** 4. The affinities of A and B must be compatible
drh69c15fe2015-05-18 11:34:52 +00001207** 5a. Both operands use the same collating sequence OR
1208** 5b. The overall collating sequence is BINARY
drh58201182015-05-16 20:51:25 +00001209** If this routine returns TRUE, that means that the RHS can be substituted
1210** for the LHS anyplace else in the WHERE clause where the LHS column occurs.
1211** This is an optimization. No harm comes from returning 0. But if 1 is
1212** returned when it should not be, then incorrect answers might result.
1213*/
drh69c15fe2015-05-18 11:34:52 +00001214static int termIsEquivalence(Parse *pParse, Expr *pExpr){
drh58201182015-05-16 20:51:25 +00001215 char aff1, aff2;
drh69c15fe2015-05-18 11:34:52 +00001216 CollSeq *pColl;
drh58201182015-05-16 20:51:25 +00001217 const char *zColl1, *zColl2;
1218 if( !OptimizationEnabled(pParse->db, SQLITE_Transitive) ) return 0;
1219 if( pExpr->op!=TK_EQ && pExpr->op!=TK_IS ) return 0;
1220 if( ExprHasProperty(pExpr, EP_FromJoin) ) return 0;
1221 aff1 = sqlite3ExprAffinity(pExpr->pLeft);
1222 aff2 = sqlite3ExprAffinity(pExpr->pRight);
1223 if( aff1!=aff2
1224 && (!sqlite3IsNumericAffinity(aff1) || !sqlite3IsNumericAffinity(aff2))
1225 ){
1226 return 0;
1227 }
drh69c15fe2015-05-18 11:34:52 +00001228 pColl = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft, pExpr->pRight);
1229 if( pColl==0 || sqlite3StrICmp(pColl->zName, "BINARY")==0 ) return 1;
1230 pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
drhc4d56dd2015-05-18 12:18:37 +00001231 /* Since pLeft and pRight are both a column references, their collating
1232 ** sequence should always be defined. */
1233 zColl1 = ALWAYS(pColl) ? pColl->zName : 0;
drh69c15fe2015-05-18 11:34:52 +00001234 pColl = sqlite3ExprCollSeq(pParse, pExpr->pRight);
drhc4d56dd2015-05-18 12:18:37 +00001235 zColl2 = ALWAYS(pColl) ? pColl->zName : 0;
drh58201182015-05-16 20:51:25 +00001236 return sqlite3StrICmp(zColl1, zColl2)==0;
1237}
1238
1239/*
drh0aa74ed2005-07-16 13:33:20 +00001240** The input to this routine is an WhereTerm structure with only the
drh51147ba2005-07-23 22:59:55 +00001241** "pExpr" field filled in. The job of this routine is to analyze the
drh0aa74ed2005-07-16 13:33:20 +00001242** subexpression and populate all the other fields of the WhereTerm
drh75897232000-05-29 14:26:00 +00001243** structure.
drh51147ba2005-07-23 22:59:55 +00001244**
1245** If the expression is of the form "<expr> <op> X" it gets commuted
drh1a58fe02008-12-20 02:06:13 +00001246** to the standard form of "X <op> <expr>".
1247**
1248** If the expression is of the form "X <op> Y" where both X and Y are
1249** columns, then the original expression is unchanged and a new virtual
1250** term of the form "Y <op> X" is added to the WHERE clause and
1251** analyzed separately. The original term is marked with TERM_COPIED
1252** and the new term is marked with TERM_DYNAMIC (because it's pExpr
1253** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
1254** is a commuted copy of a prior term.) The original term has nChild=1
1255** and the copy has idxParent set to the index of the original term.
drh75897232000-05-29 14:26:00 +00001256*/
drh0fcef5e2005-07-19 17:38:22 +00001257static void exprAnalyze(
1258 SrcList *pSrc, /* the FROM clause */
drh9eb20282005-08-24 03:52:18 +00001259 WhereClause *pWC, /* the WHERE clause */
1260 int idxTerm /* Index of the term to be analyzed */
drh0fcef5e2005-07-19 17:38:22 +00001261){
drh70d18342013-06-06 19:16:33 +00001262 WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
drh1a58fe02008-12-20 02:06:13 +00001263 WhereTerm *pTerm; /* The term to be analyzed */
drh111a6a72008-12-21 03:51:16 +00001264 WhereMaskSet *pMaskSet; /* Set of table index masks */
drh1a58fe02008-12-20 02:06:13 +00001265 Expr *pExpr; /* The expression to be analyzed */
1266 Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */
1267 Bitmask prereqAll; /* Prerequesites of pExpr */
drh5e767c52010-02-25 04:15:47 +00001268 Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */
drh1d452e12009-11-01 19:26:59 +00001269 Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */
1270 int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */
drha9c18a92015-03-06 20:49:52 +00001271 int noCase = 0; /* uppercase equivalent to lowercase */
drh1a58fe02008-12-20 02:06:13 +00001272 int op; /* Top-level operator. pExpr->op */
drh70d18342013-06-06 19:16:33 +00001273 Parse *pParse = pWInfo->pParse; /* Parsing context */
drh1a58fe02008-12-20 02:06:13 +00001274 sqlite3 *db = pParse->db; /* Database connection */
drh0fcef5e2005-07-19 17:38:22 +00001275
drhf998b732007-11-26 13:36:00 +00001276 if( db->mallocFailed ){
1277 return;
1278 }
1279 pTerm = &pWC->a[idxTerm];
drh70d18342013-06-06 19:16:33 +00001280 pMaskSet = &pWInfo->sMaskSet;
drh7ee751d2012-12-19 15:53:51 +00001281 pExpr = pTerm->pExpr;
1282 assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
drh0fcef5e2005-07-19 17:38:22 +00001283 prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
drh50b39962006-10-28 00:28:09 +00001284 op = pExpr->op;
1285 if( op==TK_IN ){
drhf5b11382005-09-17 13:07:13 +00001286 assert( pExpr->pRight==0 );
danielk19776ab3a2e2009-02-19 14:39:25 +00001287 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
1288 pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
1289 }else{
1290 pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
1291 }
drh50b39962006-10-28 00:28:09 +00001292 }else if( op==TK_ISNULL ){
1293 pTerm->prereqRight = 0;
drhf5b11382005-09-17 13:07:13 +00001294 }else{
1295 pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
1296 }
drh22d6a532005-09-19 21:05:48 +00001297 prereqAll = exprTableUsage(pMaskSet, pExpr);
1298 if( ExprHasProperty(pExpr, EP_FromJoin) ){
drh6f82e852015-06-06 20:12:09 +00001299 Bitmask x = sqlite3WhereGetMask(pMaskSet, pExpr->iRightJoinTable);
drh42165be2008-03-26 14:56:34 +00001300 prereqAll |= x;
drhdafc0ce2008-04-17 19:14:02 +00001301 extraRight = x-1; /* ON clause terms may not be used with an index
1302 ** on left table of a LEFT JOIN. Ticket #3015 */
drh22d6a532005-09-19 21:05:48 +00001303 }
1304 pTerm->prereqAll = prereqAll;
drh0fcef5e2005-07-19 17:38:22 +00001305 pTerm->leftCursor = -1;
drh45b1ee42005-08-02 17:48:22 +00001306 pTerm->iParent = -1;
drhb52076c2006-01-23 13:22:09 +00001307 pTerm->eOperator = 0;
drh738fc792013-01-17 15:05:17 +00001308 if( allowedOp(op) ){
drh7a66da12012-12-07 20:31:11 +00001309 Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
1310 Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
drh738fc792013-01-17 15:05:17 +00001311 u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
drh0fcef5e2005-07-19 17:38:22 +00001312 if( pLeft->op==TK_COLUMN ){
1313 pTerm->leftCursor = pLeft->iTable;
drh700a2262008-12-17 19:22:15 +00001314 pTerm->u.leftColumn = pLeft->iColumn;
drh738fc792013-01-17 15:05:17 +00001315 pTerm->eOperator = operatorMask(op) & opMask;
drh75897232000-05-29 14:26:00 +00001316 }
drh9be18702015-05-13 19:33:41 +00001317 if( op==TK_IS ) pTerm->wtFlags |= TERM_IS;
drh0fcef5e2005-07-19 17:38:22 +00001318 if( pRight && pRight->op==TK_COLUMN ){
1319 WhereTerm *pNew;
1320 Expr *pDup;
drh7a5bcc02013-01-16 17:08:58 +00001321 u16 eExtraOp = 0; /* Extra bits for pNew->eOperator */
drh0fcef5e2005-07-19 17:38:22 +00001322 if( pTerm->leftCursor>=0 ){
drh9eb20282005-08-24 03:52:18 +00001323 int idxNew;
danielk19776ab3a2e2009-02-19 14:39:25 +00001324 pDup = sqlite3ExprDup(db, pExpr, 0);
drh17435752007-08-16 04:30:38 +00001325 if( db->mallocFailed ){
drh633e6d52008-07-28 19:34:53 +00001326 sqlite3ExprDelete(db, pDup);
drh28f45912006-10-18 23:26:38 +00001327 return;
1328 }
drh9eb20282005-08-24 03:52:18 +00001329 idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
1330 if( idxNew==0 ) return;
1331 pNew = &pWC->a[idxNew];
drh9769efc2014-10-24 14:32:21 +00001332 markTermAsChild(pWC, idxNew, idxTerm);
drhea19cc12015-05-16 19:17:17 +00001333 if( op==TK_IS ) pNew->wtFlags |= TERM_IS;
drh9eb20282005-08-24 03:52:18 +00001334 pTerm = &pWC->a[idxTerm];
drh165be382008-12-05 02:36:33 +00001335 pTerm->wtFlags |= TERM_COPIED;
drhea19cc12015-05-16 19:17:17 +00001336
drh69c15fe2015-05-18 11:34:52 +00001337 if( termIsEquivalence(pParse, pDup) ){
drh58201182015-05-16 20:51:25 +00001338 pTerm->eOperator |= WO_EQUIV;
1339 eExtraOp = WO_EQUIV;
drh7a5bcc02013-01-16 17:08:58 +00001340 }
drh0fcef5e2005-07-19 17:38:22 +00001341 }else{
1342 pDup = pExpr;
1343 pNew = pTerm;
1344 }
drh7d10d5a2008-08-20 16:35:10 +00001345 exprCommute(pParse, pDup);
drhfb76f5a2012-12-08 14:16:47 +00001346 pLeft = sqlite3ExprSkipCollate(pDup->pLeft);
drh0fcef5e2005-07-19 17:38:22 +00001347 pNew->leftCursor = pLeft->iTable;
drh700a2262008-12-17 19:22:15 +00001348 pNew->u.leftColumn = pLeft->iColumn;
drh5e767c52010-02-25 04:15:47 +00001349 testcase( (prereqLeft | extraRight) != prereqLeft );
1350 pNew->prereqRight = prereqLeft | extraRight;
drh0fcef5e2005-07-19 17:38:22 +00001351 pNew->prereqAll = prereqAll;
drh738fc792013-01-17 15:05:17 +00001352 pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
drh75897232000-05-29 14:26:00 +00001353 }
1354 }
drhed378002005-07-28 23:12:08 +00001355
drhd2687b72005-08-12 22:56:09 +00001356#ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
drhed378002005-07-28 23:12:08 +00001357 /* If a term is the BETWEEN operator, create two new virtual terms
drh1a58fe02008-12-20 02:06:13 +00001358 ** that define the range that the BETWEEN implements. For example:
1359 **
1360 ** a BETWEEN b AND c
1361 **
1362 ** is converted into:
1363 **
1364 ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
1365 **
1366 ** The two new terms are added onto the end of the WhereClause object.
1367 ** The new terms are "dynamic" and are children of the original BETWEEN
1368 ** term. That means that if the BETWEEN term is coded, the children are
1369 ** skipped. Or, if the children are satisfied by an index, the original
1370 ** BETWEEN term is skipped.
drhed378002005-07-28 23:12:08 +00001371 */
drh29435252008-12-28 18:35:08 +00001372 else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
danielk19776ab3a2e2009-02-19 14:39:25 +00001373 ExprList *pList = pExpr->x.pList;
drhed378002005-07-28 23:12:08 +00001374 int i;
1375 static const u8 ops[] = {TK_GE, TK_LE};
1376 assert( pList!=0 );
1377 assert( pList->nExpr==2 );
1378 for(i=0; i<2; i++){
1379 Expr *pNewExpr;
drh9eb20282005-08-24 03:52:18 +00001380 int idxNew;
drhb7916a72009-05-27 10:31:29 +00001381 pNewExpr = sqlite3PExpr(pParse, ops[i],
1382 sqlite3ExprDup(db, pExpr->pLeft, 0),
danielk19776ab3a2e2009-02-19 14:39:25 +00001383 sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
drhd41d39f2013-08-28 16:27:01 +00001384 transferJoinMarkings(pNewExpr, pExpr);
drh9eb20282005-08-24 03:52:18 +00001385 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
drh6a1e0712008-12-05 15:24:15 +00001386 testcase( idxNew==0 );
drh7b4fc6a2007-02-06 13:26:32 +00001387 exprAnalyze(pSrc, pWC, idxNew);
drh9eb20282005-08-24 03:52:18 +00001388 pTerm = &pWC->a[idxTerm];
drh9769efc2014-10-24 14:32:21 +00001389 markTermAsChild(pWC, idxNew, idxTerm);
drhed378002005-07-28 23:12:08 +00001390 }
drhed378002005-07-28 23:12:08 +00001391 }
drhd2687b72005-08-12 22:56:09 +00001392#endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
drhed378002005-07-28 23:12:08 +00001393
danielk19771576cd92006-01-14 08:02:28 +00001394#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
drh1a58fe02008-12-20 02:06:13 +00001395 /* Analyze a term that is composed of two or more subterms connected by
1396 ** an OR operator.
drh6c30be82005-07-29 15:10:17 +00001397 */
1398 else if( pExpr->op==TK_OR ){
drh29435252008-12-28 18:35:08 +00001399 assert( pWC->op==TK_AND );
drh1a58fe02008-12-20 02:06:13 +00001400 exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
danielk1977f51d1bd2009-07-31 06:14:51 +00001401 pTerm = &pWC->a[idxTerm];
drh6c30be82005-07-29 15:10:17 +00001402 }
drhd2687b72005-08-12 22:56:09 +00001403#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
1404
1405#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
1406 /* Add constraints to reduce the search space on a LIKE or GLOB
1407 ** operator.
drh9f504ea2008-02-23 21:55:39 +00001408 **
drha9c18a92015-03-06 20:49:52 +00001409 ** A like pattern of the form "x LIKE 'aBc%'" is changed into constraints
drh9f504ea2008-02-23 21:55:39 +00001410 **
drha9c18a92015-03-06 20:49:52 +00001411 ** x>='ABC' AND x<'abd' AND x LIKE 'aBc%'
drh9f504ea2008-02-23 21:55:39 +00001412 **
1413 ** The last character of the prefix "abc" is incremented to form the
drha9c18a92015-03-06 20:49:52 +00001414 ** termination condition "abd". If case is not significant (the default
1415 ** for LIKE) then the lower-bound is made all uppercase and the upper-
1416 ** bound is made all lowercase so that the bounds also work when comparing
1417 ** BLOBs.
drhd2687b72005-08-12 22:56:09 +00001418 */
dan937d0de2009-10-15 18:35:38 +00001419 if( pWC->op==TK_AND
1420 && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
1421 ){
drh1d452e12009-11-01 19:26:59 +00001422 Expr *pLeft; /* LHS of LIKE/GLOB operator */
1423 Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */
1424 Expr *pNewExpr1;
1425 Expr *pNewExpr2;
1426 int idxNew1;
1427 int idxNew2;
dan80103fc2015-03-20 08:43:59 +00001428 const char *zCollSeqName; /* Name of collating sequence */
drh8f1a7ed2015-03-06 19:47:38 +00001429 const u16 wtFlags = TERM_LIKEOPT | TERM_VIRTUAL | TERM_DYNAMIC;
drh9eb20282005-08-24 03:52:18 +00001430
danielk19776ab3a2e2009-02-19 14:39:25 +00001431 pLeft = pExpr->x.pList->a[1].pExpr;
danielk19776ab3a2e2009-02-19 14:39:25 +00001432 pStr2 = sqlite3ExprDup(db, pStr1, 0);
drh8f1a7ed2015-03-06 19:47:38 +00001433
1434 /* Convert the lower bound to upper-case and the upper bound to
1435 ** lower-case (upper-case is less than lower-case in ASCII) so that
1436 ** the range constraints also work for BLOBs
1437 */
1438 if( noCase && !pParse->db->mallocFailed ){
1439 int i;
1440 char c;
drha9c18a92015-03-06 20:49:52 +00001441 pTerm->wtFlags |= TERM_LIKE;
drh8f1a7ed2015-03-06 19:47:38 +00001442 for(i=0; (c = pStr1->u.zToken[i])!=0; i++){
1443 pStr1->u.zToken[i] = sqlite3Toupper(c);
1444 pStr2->u.zToken[i] = sqlite3Tolower(c);
1445 }
1446 }
1447
drhf998b732007-11-26 13:36:00 +00001448 if( !db->mallocFailed ){
drh254993e2009-06-08 19:44:36 +00001449 u8 c, *pC; /* Last character before the first wildcard */
dan937d0de2009-10-15 18:35:38 +00001450 pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
drh9f504ea2008-02-23 21:55:39 +00001451 c = *pC;
drh02a50b72008-05-26 18:33:40 +00001452 if( noCase ){
drh254993e2009-06-08 19:44:36 +00001453 /* The point is to increment the last character before the first
1454 ** wildcard. But if we increment '@', that will push it into the
1455 ** alphabetic range where case conversions will mess up the
1456 ** inequality. To avoid this, make sure to also run the full
1457 ** LIKE on all candidate expressions by clearing the isComplete flag
1458 */
drh39759742013-08-02 23:40:45 +00001459 if( c=='A'-1 ) isComplete = 0;
drh02a50b72008-05-26 18:33:40 +00001460 c = sqlite3UpperToLower[c];
1461 }
drh9f504ea2008-02-23 21:55:39 +00001462 *pC = c + 1;
drhd2687b72005-08-12 22:56:09 +00001463 }
dan80103fc2015-03-20 08:43:59 +00001464 zCollSeqName = noCase ? "NOCASE" : "BINARY";
drhae80dde2012-12-06 21:16:43 +00001465 pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
drh8f1a7ed2015-03-06 19:47:38 +00001466 pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
dan80103fc2015-03-20 08:43:59 +00001467 sqlite3ExprAddCollateString(pParse,pNewExpr1,zCollSeqName),
drhae80dde2012-12-06 21:16:43 +00001468 pStr1, 0);
drhd41d39f2013-08-28 16:27:01 +00001469 transferJoinMarkings(pNewExpr1, pExpr);
drh8f1a7ed2015-03-06 19:47:38 +00001470 idxNew1 = whereClauseInsert(pWC, pNewExpr1, wtFlags);
drh6a1e0712008-12-05 15:24:15 +00001471 testcase( idxNew1==0 );
drh7b4fc6a2007-02-06 13:26:32 +00001472 exprAnalyze(pSrc, pWC, idxNew1);
drhae80dde2012-12-06 21:16:43 +00001473 pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
drh8342e492010-07-22 17:49:52 +00001474 pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
dan80103fc2015-03-20 08:43:59 +00001475 sqlite3ExprAddCollateString(pParse,pNewExpr2,zCollSeqName),
drhae80dde2012-12-06 21:16:43 +00001476 pStr2, 0);
drhd41d39f2013-08-28 16:27:01 +00001477 transferJoinMarkings(pNewExpr2, pExpr);
drh8f1a7ed2015-03-06 19:47:38 +00001478 idxNew2 = whereClauseInsert(pWC, pNewExpr2, wtFlags);
drh6a1e0712008-12-05 15:24:15 +00001479 testcase( idxNew2==0 );
drh7b4fc6a2007-02-06 13:26:32 +00001480 exprAnalyze(pSrc, pWC, idxNew2);
drh9eb20282005-08-24 03:52:18 +00001481 pTerm = &pWC->a[idxTerm];
drhd2687b72005-08-12 22:56:09 +00001482 if( isComplete ){
drh9769efc2014-10-24 14:32:21 +00001483 markTermAsChild(pWC, idxNew1, idxTerm);
1484 markTermAsChild(pWC, idxNew2, idxTerm);
drhd2687b72005-08-12 22:56:09 +00001485 }
1486 }
1487#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
drh7f375902006-06-13 17:38:59 +00001488
1489#ifndef SQLITE_OMIT_VIRTUALTABLE
1490 /* Add a WO_MATCH auxiliary term to the constraint set if the
1491 ** current expression is of the form: column MATCH expr.
1492 ** This information is used by the xBestIndex methods of
1493 ** virtual tables. The native query optimizer does not attempt
1494 ** to do anything with MATCH functions.
1495 */
1496 if( isMatchOfColumn(pExpr) ){
1497 int idxNew;
1498 Expr *pRight, *pLeft;
1499 WhereTerm *pNewTerm;
1500 Bitmask prereqColumn, prereqExpr;
1501
danielk19776ab3a2e2009-02-19 14:39:25 +00001502 pRight = pExpr->x.pList->a[0].pExpr;
1503 pLeft = pExpr->x.pList->a[1].pExpr;
drh7f375902006-06-13 17:38:59 +00001504 prereqExpr = exprTableUsage(pMaskSet, pRight);
1505 prereqColumn = exprTableUsage(pMaskSet, pLeft);
1506 if( (prereqExpr & prereqColumn)==0 ){
drh1a90e092006-06-14 22:07:10 +00001507 Expr *pNewExpr;
drhb7916a72009-05-27 10:31:29 +00001508 pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
1509 0, sqlite3ExprDup(db, pRight, 0), 0);
drh1a90e092006-06-14 22:07:10 +00001510 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
drh6a1e0712008-12-05 15:24:15 +00001511 testcase( idxNew==0 );
drh7f375902006-06-13 17:38:59 +00001512 pNewTerm = &pWC->a[idxNew];
1513 pNewTerm->prereqRight = prereqExpr;
1514 pNewTerm->leftCursor = pLeft->iTable;
drh700a2262008-12-17 19:22:15 +00001515 pNewTerm->u.leftColumn = pLeft->iColumn;
drh7f375902006-06-13 17:38:59 +00001516 pNewTerm->eOperator = WO_MATCH;
drh9769efc2014-10-24 14:32:21 +00001517 markTermAsChild(pWC, idxNew, idxTerm);
drhd2ca60d2006-06-27 02:36:58 +00001518 pTerm = &pWC->a[idxTerm];
drh165be382008-12-05 02:36:33 +00001519 pTerm->wtFlags |= TERM_COPIED;
drh7f375902006-06-13 17:38:59 +00001520 pNewTerm->prereqAll = pTerm->prereqAll;
1521 }
1522 }
1523#endif /* SQLITE_OMIT_VIRTUALTABLE */
drhdafc0ce2008-04-17 19:14:02 +00001524
drh1435a9a2013-08-27 23:15:44 +00001525#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drhd3ed7342011-09-21 00:09:41 +00001526 /* When sqlite_stat3 histogram data is available an operator of the
drh534230c2011-01-22 00:10:45 +00001527 ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
1528 ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a
1529 ** virtual term of that form.
1530 **
drh9be18702015-05-13 19:33:41 +00001531 ** Note that the virtual term must be tagged with TERM_VNULL.
drh534230c2011-01-22 00:10:45 +00001532 */
drhea6dc442011-04-08 21:35:26 +00001533 if( pExpr->op==TK_NOTNULL
1534 && pExpr->pLeft->op==TK_COLUMN
1535 && pExpr->pLeft->iColumn>=0
drhd7d71472014-10-22 19:57:16 +00001536 && OptimizationEnabled(db, SQLITE_Stat34)
drhea6dc442011-04-08 21:35:26 +00001537 ){
drh534230c2011-01-22 00:10:45 +00001538 Expr *pNewExpr;
1539 Expr *pLeft = pExpr->pLeft;
1540 int idxNew;
1541 WhereTerm *pNewTerm;
1542
1543 pNewExpr = sqlite3PExpr(pParse, TK_GT,
1544 sqlite3ExprDup(db, pLeft, 0),
1545 sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
1546
1547 idxNew = whereClauseInsert(pWC, pNewExpr,
drh9be18702015-05-13 19:33:41 +00001548 TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
drhda91e712011-02-11 06:59:02 +00001549 if( idxNew ){
1550 pNewTerm = &pWC->a[idxNew];
1551 pNewTerm->prereqRight = 0;
1552 pNewTerm->leftCursor = pLeft->iTable;
1553 pNewTerm->u.leftColumn = pLeft->iColumn;
1554 pNewTerm->eOperator = WO_GT;
drh9769efc2014-10-24 14:32:21 +00001555 markTermAsChild(pWC, idxNew, idxTerm);
drhda91e712011-02-11 06:59:02 +00001556 pTerm = &pWC->a[idxTerm];
drhda91e712011-02-11 06:59:02 +00001557 pTerm->wtFlags |= TERM_COPIED;
1558 pNewTerm->prereqAll = pTerm->prereqAll;
1559 }
drh534230c2011-01-22 00:10:45 +00001560 }
drh1435a9a2013-08-27 23:15:44 +00001561#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
drh534230c2011-01-22 00:10:45 +00001562
drhdafc0ce2008-04-17 19:14:02 +00001563 /* Prevent ON clause terms of a LEFT JOIN from being used to drive
1564 ** an index for tables to the left of the join.
1565 */
1566 pTerm->prereqRight |= extraRight;
drh75897232000-05-29 14:26:00 +00001567}
1568
drh7b4fc6a2007-02-06 13:26:32 +00001569/*
peter.d.reid60ec9142014-09-06 16:39:46 +00001570** This function searches pList for an entry that matches the iCol-th column
drh3b48e8c2013-06-12 20:18:16 +00001571** of index pIdx.
dan6f343962011-07-01 18:26:40 +00001572**
1573** If such an expression is found, its index in pList->a[] is returned. If
1574** no expression is found, -1 is returned.
1575*/
1576static int findIndexCol(
1577 Parse *pParse, /* Parse context */
1578 ExprList *pList, /* Expression list to search */
1579 int iBase, /* Cursor for table associated with pIdx */
1580 Index *pIdx, /* Index to match column of */
1581 int iCol /* Column of index to match */
1582){
1583 int i;
1584 const char *zColl = pIdx->azColl[iCol];
1585
1586 for(i=0; i<pList->nExpr; i++){
drh580c8c12012-12-08 03:34:04 +00001587 Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
drhf1d3e322011-07-09 13:00:41 +00001588 if( p->op==TK_COLUMN
1589 && p->iColumn==pIdx->aiColumn[iCol]
1590 && p->iTable==iBase
1591 ){
drh580c8c12012-12-08 03:34:04 +00001592 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
drh65df68e2015-04-15 05:31:02 +00001593 if( pColl && 0==sqlite3StrICmp(pColl->zName, zColl) ){
dan6f343962011-07-01 18:26:40 +00001594 return i;
1595 }
1596 }
1597 }
1598
1599 return -1;
1600}
1601
1602/*
dan6f343962011-07-01 18:26:40 +00001603** Return true if the DISTINCT expression-list passed as the third argument
drh4f402f22013-06-11 18:59:38 +00001604** is redundant.
1605**
drhb121dd12015-06-06 18:30:17 +00001606** A DISTINCT list is redundant if any subset of the columns in the
1607** DISTINCT list are collectively unique and individually non-null.
dan6f343962011-07-01 18:26:40 +00001608*/
1609static int isDistinctRedundant(
drh4f402f22013-06-11 18:59:38 +00001610 Parse *pParse, /* Parsing context */
1611 SrcList *pTabList, /* The FROM clause */
1612 WhereClause *pWC, /* The WHERE clause */
1613 ExprList *pDistinct /* The result set that needs to be DISTINCT */
dan6f343962011-07-01 18:26:40 +00001614){
1615 Table *pTab;
1616 Index *pIdx;
1617 int i;
1618 int iBase;
1619
1620 /* If there is more than one table or sub-select in the FROM clause of
1621 ** this query, then it will not be possible to show that the DISTINCT
1622 ** clause is redundant. */
1623 if( pTabList->nSrc!=1 ) return 0;
1624 iBase = pTabList->a[0].iCursor;
1625 pTab = pTabList->a[0].pTab;
1626
dan94e08d92011-07-02 06:44:05 +00001627 /* If any of the expressions is an IPK column on table iBase, then return
1628 ** true. Note: The (p->iTable==iBase) part of this test may be false if the
1629 ** current SELECT is a correlated sub-query.
1630 */
dan6f343962011-07-01 18:26:40 +00001631 for(i=0; i<pDistinct->nExpr; i++){
drh580c8c12012-12-08 03:34:04 +00001632 Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
dan94e08d92011-07-02 06:44:05 +00001633 if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
dan6f343962011-07-01 18:26:40 +00001634 }
1635
1636 /* Loop through all indices on the table, checking each to see if it makes
1637 ** the DISTINCT qualifier redundant. It does so if:
1638 **
1639 ** 1. The index is itself UNIQUE, and
1640 **
1641 ** 2. All of the columns in the index are either part of the pDistinct
1642 ** list, or else the WHERE clause contains a term of the form "col=X",
1643 ** where X is a constant value. The collation sequences of the
1644 ** comparison and select-list expressions must match those of the index.
dan6a36f432012-04-20 16:59:24 +00001645 **
1646 ** 3. All of those index columns for which the WHERE clause does not
1647 ** contain a "col=X" term are subject to a NOT NULL constraint.
dan6f343962011-07-01 18:26:40 +00001648 */
1649 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
drh5f1d1d92014-07-31 22:59:04 +00001650 if( !IsUniqueIndex(pIdx) ) continue;
drhbbbdc832013-10-22 18:01:40 +00001651 for(i=0; i<pIdx->nKeyCol; i++){
1652 i16 iCol = pIdx->aiColumn[i];
drh6f82e852015-06-06 20:12:09 +00001653 if( 0==sqlite3WhereFindTerm(pWC, iBase, iCol, ~(Bitmask)0, WO_EQ, pIdx) ){
dan6a36f432012-04-20 16:59:24 +00001654 int iIdxCol = findIndexCol(pParse, pDistinct, iBase, pIdx, i);
drhbbbdc832013-10-22 18:01:40 +00001655 if( iIdxCol<0 || pTab->aCol[iCol].notNull==0 ){
dan6a36f432012-04-20 16:59:24 +00001656 break;
1657 }
dan6f343962011-07-01 18:26:40 +00001658 }
1659 }
drhbbbdc832013-10-22 18:01:40 +00001660 if( i==pIdx->nKeyCol ){
dan6f343962011-07-01 18:26:40 +00001661 /* This index implies that the DISTINCT qualifier is redundant. */
1662 return 1;
1663 }
1664 }
1665
1666 return 0;
1667}
drh0fcef5e2005-07-19 17:38:22 +00001668
drh8636e9c2013-06-11 01:50:08 +00001669
drh75897232000-05-29 14:26:00 +00001670/*
drh3b48e8c2013-06-12 20:18:16 +00001671** Estimate the logarithm of the input value to base 2.
drh28c4cf42005-07-27 20:41:43 +00001672*/
drhbf539c42013-10-05 18:16:02 +00001673static LogEst estLog(LogEst N){
drh696964d2014-06-12 15:46:46 +00001674 return N<=10 ? 0 : sqlite3LogEst(N) - 33;
drh28c4cf42005-07-27 20:41:43 +00001675}
1676
drh6d209d82006-06-27 01:54:26 +00001677/*
drh7b3aa082015-05-29 13:55:33 +00001678** Convert OP_Column opcodes to OP_Copy in previously generated code.
1679**
1680** This routine runs over generated VDBE code and translates OP_Column
1681** opcodes into OP_Copy, and OP_Rowid into OP_Null, when the table is being
1682** accessed via co-routine instead of via table lookup.
1683*/
1684static void translateColumnToCopy(
1685 Vdbe *v, /* The VDBE containing code to translate */
1686 int iStart, /* Translate from this opcode to the end */
1687 int iTabCur, /* OP_Column/OP_Rowid references to this table */
1688 int iRegister /* The first column is in this register */
1689){
1690 VdbeOp *pOp = sqlite3VdbeGetOp(v, iStart);
1691 int iEnd = sqlite3VdbeCurrentAddr(v);
1692 for(; iStart<iEnd; iStart++, pOp++){
1693 if( pOp->p1!=iTabCur ) continue;
1694 if( pOp->opcode==OP_Column ){
1695 pOp->opcode = OP_Copy;
1696 pOp->p1 = pOp->p2 + iRegister;
1697 pOp->p2 = pOp->p3;
1698 pOp->p3 = 0;
1699 }else if( pOp->opcode==OP_Rowid ){
1700 pOp->opcode = OP_Null;
1701 pOp->p1 = 0;
1702 pOp->p3 = 0;
1703 }
1704 }
1705}
1706
1707/*
drh6d209d82006-06-27 01:54:26 +00001708** Two routines for printing the content of an sqlite3_index_info
1709** structure. Used for testing and debugging only. If neither
1710** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
1711** are no-ops.
1712*/
drhd15cb172013-05-21 19:23:10 +00001713#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
drh6d209d82006-06-27 01:54:26 +00001714static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
1715 int i;
mlcreech3a00f902008-03-04 17:45:01 +00001716 if( !sqlite3WhereTrace ) return;
drh6d209d82006-06-27 01:54:26 +00001717 for(i=0; i<p->nConstraint; i++){
1718 sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
1719 i,
1720 p->aConstraint[i].iColumn,
1721 p->aConstraint[i].iTermOffset,
1722 p->aConstraint[i].op,
1723 p->aConstraint[i].usable);
1724 }
1725 for(i=0; i<p->nOrderBy; i++){
1726 sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n",
1727 i,
1728 p->aOrderBy[i].iColumn,
1729 p->aOrderBy[i].desc);
1730 }
1731}
1732static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
1733 int i;
mlcreech3a00f902008-03-04 17:45:01 +00001734 if( !sqlite3WhereTrace ) return;
drh6d209d82006-06-27 01:54:26 +00001735 for(i=0; i<p->nConstraint; i++){
1736 sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n",
1737 i,
1738 p->aConstraintUsage[i].argvIndex,
1739 p->aConstraintUsage[i].omit);
1740 }
1741 sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum);
1742 sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr);
1743 sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed);
1744 sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost);
dana9f58152013-11-11 19:01:33 +00001745 sqlite3DebugPrintf(" estimatedRows=%lld\n", p->estimatedRows);
drh6d209d82006-06-27 01:54:26 +00001746}
1747#else
1748#define TRACE_IDX_INPUTS(A)
1749#define TRACE_IDX_OUTPUTS(A)
1750#endif
1751
drhc6339082010-04-07 16:54:58 +00001752#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
drh8b307fb2010-04-06 15:57:05 +00001753/*
drh4139c992010-04-07 14:59:45 +00001754** Return TRUE if the WHERE clause term pTerm is of a form where it
1755** could be used with an index to access pSrc, assuming an appropriate
1756** index existed.
1757*/
1758static int termCanDriveIndex(
1759 WhereTerm *pTerm, /* WHERE clause term to check */
1760 struct SrcList_item *pSrc, /* Table we are trying to access */
1761 Bitmask notReady /* Tables in outer loops of the join */
1762){
1763 char aff;
1764 if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
drhe8d0c612015-05-14 01:05:25 +00001765 if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) return 0;
drh4139c992010-04-07 14:59:45 +00001766 if( (pTerm->prereqRight & notReady)!=0 ) return 0;
drh23f98da2013-05-21 15:52:07 +00001767 if( pTerm->u.leftColumn<0 ) return 0;
drh4139c992010-04-07 14:59:45 +00001768 aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
1769 if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
drhe0cc3c22015-05-13 17:54:08 +00001770 testcase( pTerm->pExpr->op==TK_IS );
drh4139c992010-04-07 14:59:45 +00001771 return 1;
1772}
drhc6339082010-04-07 16:54:58 +00001773#endif
drh4139c992010-04-07 14:59:45 +00001774
drhc6339082010-04-07 16:54:58 +00001775
1776#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
drh8b307fb2010-04-06 15:57:05 +00001777/*
drhc6339082010-04-07 16:54:58 +00001778** Generate code to construct the Index object for an automatic index
1779** and to set up the WhereLevel object pLevel so that the code generator
1780** makes use of the automatic index.
drh8b307fb2010-04-06 15:57:05 +00001781*/
drhc6339082010-04-07 16:54:58 +00001782static void constructAutomaticIndex(
drh8b307fb2010-04-06 15:57:05 +00001783 Parse *pParse, /* The parsing context */
1784 WhereClause *pWC, /* The WHERE clause */
1785 struct SrcList_item *pSrc, /* The FROM clause term to get the next index */
1786 Bitmask notReady, /* Mask of cursors that are not available */
1787 WhereLevel *pLevel /* Write new index here */
1788){
drhbbbdc832013-10-22 18:01:40 +00001789 int nKeyCol; /* Number of columns in the constructed index */
drh8b307fb2010-04-06 15:57:05 +00001790 WhereTerm *pTerm; /* A single term of the WHERE clause */
1791 WhereTerm *pWCEnd; /* End of pWC->a[] */
drh8b307fb2010-04-06 15:57:05 +00001792 Index *pIdx; /* Object describing the transient index */
1793 Vdbe *v; /* Prepared statement under construction */
drh8b307fb2010-04-06 15:57:05 +00001794 int addrInit; /* Address of the initialization bypass jump */
1795 Table *pTable; /* The table being indexed */
drh8b307fb2010-04-06 15:57:05 +00001796 int addrTop; /* Top of the index fill loop */
1797 int regRecord; /* Register holding an index record */
1798 int n; /* Column counter */
drh4139c992010-04-07 14:59:45 +00001799 int i; /* Loop counter */
1800 int mxBitCol; /* Maximum column in pSrc->colUsed */
drh424aab82010-04-06 18:28:20 +00001801 CollSeq *pColl; /* Collating sequence to on a column */
drh7ba39a92013-05-30 17:43:19 +00001802 WhereLoop *pLoop; /* The Loop object */
drh77e57df2013-10-22 14:28:02 +00001803 char *zNotUsed; /* Extra space on the end of pIdx */
drh4139c992010-04-07 14:59:45 +00001804 Bitmask idxCols; /* Bitmap of columns used for indexing */
1805 Bitmask extraCols; /* Bitmap of additional columns */
drh8d56e202013-06-28 23:55:45 +00001806 u8 sentWarning = 0; /* True if a warnning has been issued */
drh059b2d52014-10-24 19:28:09 +00001807 Expr *pPartial = 0; /* Partial Index Expression */
1808 int iContinue = 0; /* Jump here to skip excluded rows */
drh7b3aa082015-05-29 13:55:33 +00001809 struct SrcList_item *pTabItem; /* FROM clause term being indexed */
drh8b307fb2010-04-06 15:57:05 +00001810
1811 /* Generate code to skip over the creation and initialization of the
1812 ** transient index on 2nd and subsequent iterations of the loop. */
1813 v = pParse->pVdbe;
1814 assert( v!=0 );
drh7d176102014-02-18 03:07:12 +00001815 addrInit = sqlite3CodeOnce(pParse); VdbeCoverage(v);
drh8b307fb2010-04-06 15:57:05 +00001816
drh4139c992010-04-07 14:59:45 +00001817 /* Count the number of columns that will be added to the index
1818 ** and used to match WHERE clause constraints */
drhbbbdc832013-10-22 18:01:40 +00001819 nKeyCol = 0;
drh424aab82010-04-06 18:28:20 +00001820 pTable = pSrc->pTab;
drh8b307fb2010-04-06 15:57:05 +00001821 pWCEnd = &pWC->a[pWC->nTerm];
drh7ba39a92013-05-30 17:43:19 +00001822 pLoop = pLevel->pWLoop;
drh4139c992010-04-07 14:59:45 +00001823 idxCols = 0;
drh81186b42013-06-18 01:52:41 +00001824 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
drh13cc90c2015-02-25 00:24:41 +00001825 Expr *pExpr = pTerm->pExpr;
1826 assert( !ExprHasProperty(pExpr, EP_FromJoin) /* prereq always non-zero */
1827 || pExpr->iRightJoinTable!=pSrc->iCursor /* for the right-hand */
1828 || pLoop->prereq!=0 ); /* table of a LEFT JOIN */
drh059b2d52014-10-24 19:28:09 +00001829 if( pLoop->prereq==0
drh051575c2014-10-25 12:28:25 +00001830 && (pTerm->wtFlags & TERM_VIRTUAL)==0
drh13cc90c2015-02-25 00:24:41 +00001831 && !ExprHasProperty(pExpr, EP_FromJoin)
1832 && sqlite3ExprIsTableConstant(pExpr, pSrc->iCursor) ){
drh059b2d52014-10-24 19:28:09 +00001833 pPartial = sqlite3ExprAnd(pParse->db, pPartial,
drh13cc90c2015-02-25 00:24:41 +00001834 sqlite3ExprDup(pParse->db, pExpr, 0));
drh059b2d52014-10-24 19:28:09 +00001835 }
drh4139c992010-04-07 14:59:45 +00001836 if( termCanDriveIndex(pTerm, pSrc, notReady) ){
1837 int iCol = pTerm->u.leftColumn;
drh7699d1c2013-06-04 12:42:29 +00001838 Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
drh52ff8ea2010-04-08 14:15:56 +00001839 testcase( iCol==BMS );
1840 testcase( iCol==BMS-1 );
drh8d56e202013-06-28 23:55:45 +00001841 if( !sentWarning ){
1842 sqlite3_log(SQLITE_WARNING_AUTOINDEX,
1843 "automatic index on %s(%s)", pTable->zName,
1844 pTable->aCol[iCol].zName);
1845 sentWarning = 1;
1846 }
drh0013e722010-04-08 00:40:15 +00001847 if( (idxCols & cMask)==0 ){
drh059b2d52014-10-24 19:28:09 +00001848 if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ){
1849 goto end_auto_index_create;
1850 }
drhbbbdc832013-10-22 18:01:40 +00001851 pLoop->aLTerm[nKeyCol++] = pTerm;
drh0013e722010-04-08 00:40:15 +00001852 idxCols |= cMask;
1853 }
drh8b307fb2010-04-06 15:57:05 +00001854 }
1855 }
drhbbbdc832013-10-22 18:01:40 +00001856 assert( nKeyCol>0 );
1857 pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol;
drh53b52f72013-05-31 11:57:39 +00001858 pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
drh986b3872013-06-28 21:12:20 +00001859 | WHERE_AUTO_INDEX;
drh4139c992010-04-07 14:59:45 +00001860
1861 /* Count the number of additional columns needed to create a
1862 ** covering index. A "covering index" is an index that contains all
1863 ** columns that are needed by the query. With a covering index, the
1864 ** original table never needs to be accessed. Automatic indices must
1865 ** be a covering index because the index will not be updated if the
1866 ** original table changes and the index and table cannot both be used
1867 ** if they go out of sync.
1868 */
drh7699d1c2013-06-04 12:42:29 +00001869 extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
drhc3ef4fa2014-10-28 15:58:50 +00001870 mxBitCol = MIN(BMS-1,pTable->nCol);
drh52ff8ea2010-04-08 14:15:56 +00001871 testcase( pTable->nCol==BMS-1 );
1872 testcase( pTable->nCol==BMS-2 );
drh4139c992010-04-07 14:59:45 +00001873 for(i=0; i<mxBitCol; i++){
drhbbbdc832013-10-22 18:01:40 +00001874 if( extraCols & MASKBIT(i) ) nKeyCol++;
drh4139c992010-04-07 14:59:45 +00001875 }
drh7699d1c2013-06-04 12:42:29 +00001876 if( pSrc->colUsed & MASKBIT(BMS-1) ){
drhbbbdc832013-10-22 18:01:40 +00001877 nKeyCol += pTable->nCol - BMS + 1;
drh4139c992010-04-07 14:59:45 +00001878 }
drh8b307fb2010-04-06 15:57:05 +00001879
1880 /* Construct the Index object to describe this index */
drhbbbdc832013-10-22 18:01:40 +00001881 pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed);
drh059b2d52014-10-24 19:28:09 +00001882 if( pIdx==0 ) goto end_auto_index_create;
drh7ba39a92013-05-30 17:43:19 +00001883 pLoop->u.btree.pIndex = pIdx;
drh8b307fb2010-04-06 15:57:05 +00001884 pIdx->zName = "auto-index";
drh424aab82010-04-06 18:28:20 +00001885 pIdx->pTable = pTable;
drh8b307fb2010-04-06 15:57:05 +00001886 n = 0;
drh0013e722010-04-08 00:40:15 +00001887 idxCols = 0;
drh8b307fb2010-04-06 15:57:05 +00001888 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
drh4139c992010-04-07 14:59:45 +00001889 if( termCanDriveIndex(pTerm, pSrc, notReady) ){
drh0013e722010-04-08 00:40:15 +00001890 int iCol = pTerm->u.leftColumn;
drh7699d1c2013-06-04 12:42:29 +00001891 Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
drh7963b0e2013-06-17 21:37:40 +00001892 testcase( iCol==BMS-1 );
1893 testcase( iCol==BMS );
drh0013e722010-04-08 00:40:15 +00001894 if( (idxCols & cMask)==0 ){
1895 Expr *pX = pTerm->pExpr;
1896 idxCols |= cMask;
1897 pIdx->aiColumn[n] = pTerm->u.leftColumn;
1898 pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
drh29031832015-04-15 07:34:25 +00001899 pIdx->azColl[n] = pColl ? pColl->zName : "BINARY";
drh0013e722010-04-08 00:40:15 +00001900 n++;
1901 }
drh8b307fb2010-04-06 15:57:05 +00001902 }
1903 }
drh7ba39a92013-05-30 17:43:19 +00001904 assert( (u32)n==pLoop->u.btree.nEq );
drh4139c992010-04-07 14:59:45 +00001905
drhc6339082010-04-07 16:54:58 +00001906 /* Add additional columns needed to make the automatic index into
1907 ** a covering index */
drh4139c992010-04-07 14:59:45 +00001908 for(i=0; i<mxBitCol; i++){
drh7699d1c2013-06-04 12:42:29 +00001909 if( extraCols & MASKBIT(i) ){
drh4139c992010-04-07 14:59:45 +00001910 pIdx->aiColumn[n] = i;
1911 pIdx->azColl[n] = "BINARY";
1912 n++;
1913 }
1914 }
drh7699d1c2013-06-04 12:42:29 +00001915 if( pSrc->colUsed & MASKBIT(BMS-1) ){
drh4139c992010-04-07 14:59:45 +00001916 for(i=BMS-1; i<pTable->nCol; i++){
1917 pIdx->aiColumn[n] = i;
1918 pIdx->azColl[n] = "BINARY";
1919 n++;
1920 }
1921 }
drhbbbdc832013-10-22 18:01:40 +00001922 assert( n==nKeyCol );
drh44156282013-10-23 22:23:03 +00001923 pIdx->aiColumn[n] = -1;
1924 pIdx->azColl[n] = "BINARY";
drh8b307fb2010-04-06 15:57:05 +00001925
drhc6339082010-04-07 16:54:58 +00001926 /* Create the automatic index */
drh8b307fb2010-04-06 15:57:05 +00001927 assert( pLevel->iIdxCur>=0 );
drha1f41242013-05-31 20:00:58 +00001928 pLevel->iIdxCur = pParse->nTab++;
drh2ec2fb22013-11-06 19:59:23 +00001929 sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1);
1930 sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
drha21a64d2010-04-06 22:33:55 +00001931 VdbeComment((v, "for %s", pTable->zName));
drh8b307fb2010-04-06 15:57:05 +00001932
drhc6339082010-04-07 16:54:58 +00001933 /* Fill the automatic index with content */
drh059b2d52014-10-24 19:28:09 +00001934 sqlite3ExprCachePush(pParse);
drh7b3aa082015-05-29 13:55:33 +00001935 pTabItem = &pWC->pWInfo->pTabList->a[pLevel->iFrom];
1936 if( pTabItem->viaCoroutine ){
1937 int regYield = pTabItem->regReturn;
1938 sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
1939 addrTop = sqlite3VdbeAddOp1(v, OP_Yield, regYield);
1940 VdbeCoverage(v);
1941 VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
1942 }else{
1943 addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v);
1944 }
drh059b2d52014-10-24 19:28:09 +00001945 if( pPartial ){
1946 iContinue = sqlite3VdbeMakeLabel(v);
1947 sqlite3ExprIfFalse(pParse, pPartial, iContinue, SQLITE_JUMPIFNULL);
drh051575c2014-10-25 12:28:25 +00001948 pLoop->wsFlags |= WHERE_PARTIALIDX;
drh059b2d52014-10-24 19:28:09 +00001949 }
drh8b307fb2010-04-06 15:57:05 +00001950 regRecord = sqlite3GetTempReg(pParse);
drh1c2c0b72014-01-04 19:27:05 +00001951 sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0);
drh8b307fb2010-04-06 15:57:05 +00001952 sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
1953 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
drh059b2d52014-10-24 19:28:09 +00001954 if( pPartial ) sqlite3VdbeResolveLabel(v, iContinue);
drh7b3aa082015-05-29 13:55:33 +00001955 if( pTabItem->viaCoroutine ){
1956 translateColumnToCopy(v, addrTop, pLevel->iTabCur, pTabItem->regResult);
1957 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
1958 pTabItem->viaCoroutine = 0;
1959 }else{
1960 sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v);
1961 }
drha21a64d2010-04-06 22:33:55 +00001962 sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
drh8b307fb2010-04-06 15:57:05 +00001963 sqlite3VdbeJumpHere(v, addrTop);
1964 sqlite3ReleaseTempReg(pParse, regRecord);
drh059b2d52014-10-24 19:28:09 +00001965 sqlite3ExprCachePop(pParse);
drh8b307fb2010-04-06 15:57:05 +00001966
1967 /* Jump here when skipping the initialization */
1968 sqlite3VdbeJumpHere(v, addrInit);
drh059b2d52014-10-24 19:28:09 +00001969
1970end_auto_index_create:
1971 sqlite3ExprDelete(pParse->db, pPartial);
drh8b307fb2010-04-06 15:57:05 +00001972}
drhc6339082010-04-07 16:54:58 +00001973#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
drh8b307fb2010-04-06 15:57:05 +00001974
drh9eff6162006-06-12 21:59:13 +00001975#ifndef SQLITE_OMIT_VIRTUALTABLE
1976/*
danielk19771d461462009-04-21 09:02:45 +00001977** Allocate and populate an sqlite3_index_info structure. It is the
1978** responsibility of the caller to eventually release the structure
1979** by passing the pointer returned by this function to sqlite3_free().
1980*/
drh5346e952013-05-08 14:14:26 +00001981static sqlite3_index_info *allocateIndexInfo(
1982 Parse *pParse,
1983 WhereClause *pWC,
1984 struct SrcList_item *pSrc,
1985 ExprList *pOrderBy
1986){
danielk19771d461462009-04-21 09:02:45 +00001987 int i, j;
1988 int nTerm;
1989 struct sqlite3_index_constraint *pIdxCons;
1990 struct sqlite3_index_orderby *pIdxOrderBy;
1991 struct sqlite3_index_constraint_usage *pUsage;
1992 WhereTerm *pTerm;
1993 int nOrderBy;
1994 sqlite3_index_info *pIdxInfo;
1995
danielk19771d461462009-04-21 09:02:45 +00001996 /* Count the number of possible WHERE clause constraints referring
1997 ** to this virtual table */
1998 for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
1999 if( pTerm->leftCursor != pSrc->iCursor ) continue;
drh7a5bcc02013-01-16 17:08:58 +00002000 assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
2001 testcase( pTerm->eOperator & WO_IN );
2002 testcase( pTerm->eOperator & WO_ISNULL );
drhee145872015-05-14 13:18:47 +00002003 testcase( pTerm->eOperator & WO_IS );
dana4ff8252014-01-20 19:55:33 +00002004 testcase( pTerm->eOperator & WO_ALL );
drhee145872015-05-14 13:18:47 +00002005 if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV|WO_IS))==0 ) continue;
drhb4256992011-08-02 01:57:39 +00002006 if( pTerm->wtFlags & TERM_VNULL ) continue;
danielk19771d461462009-04-21 09:02:45 +00002007 nTerm++;
2008 }
2009
2010 /* If the ORDER BY clause contains only columns in the current
2011 ** virtual table then allocate space for the aOrderBy part of
2012 ** the sqlite3_index_info structure.
2013 */
2014 nOrderBy = 0;
2015 if( pOrderBy ){
drh56f1b992012-09-25 14:29:39 +00002016 int n = pOrderBy->nExpr;
2017 for(i=0; i<n; i++){
danielk19771d461462009-04-21 09:02:45 +00002018 Expr *pExpr = pOrderBy->a[i].pExpr;
2019 if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
2020 }
drh56f1b992012-09-25 14:29:39 +00002021 if( i==n){
2022 nOrderBy = n;
danielk19771d461462009-04-21 09:02:45 +00002023 }
2024 }
2025
2026 /* Allocate the sqlite3_index_info structure
2027 */
2028 pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
2029 + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
2030 + sizeof(*pIdxOrderBy)*nOrderBy );
2031 if( pIdxInfo==0 ){
2032 sqlite3ErrorMsg(pParse, "out of memory");
danielk19771d461462009-04-21 09:02:45 +00002033 return 0;
2034 }
2035
2036 /* Initialize the structure. The sqlite3_index_info structure contains
2037 ** many fields that are declared "const" to prevent xBestIndex from
2038 ** changing them. We have to do some funky casting in order to
2039 ** initialize those fields.
2040 */
2041 pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
2042 pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
2043 pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
2044 *(int*)&pIdxInfo->nConstraint = nTerm;
2045 *(int*)&pIdxInfo->nOrderBy = nOrderBy;
2046 *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
2047 *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
2048 *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
2049 pUsage;
2050
2051 for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
drh281bbe22012-10-16 23:17:14 +00002052 u8 op;
danielk19771d461462009-04-21 09:02:45 +00002053 if( pTerm->leftCursor != pSrc->iCursor ) continue;
drh7a5bcc02013-01-16 17:08:58 +00002054 assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
2055 testcase( pTerm->eOperator & WO_IN );
drhee145872015-05-14 13:18:47 +00002056 testcase( pTerm->eOperator & WO_IS );
drh7a5bcc02013-01-16 17:08:58 +00002057 testcase( pTerm->eOperator & WO_ISNULL );
dana4ff8252014-01-20 19:55:33 +00002058 testcase( pTerm->eOperator & WO_ALL );
drhe8d0c612015-05-14 01:05:25 +00002059 if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV|WO_IS))==0 ) continue;
drhb4256992011-08-02 01:57:39 +00002060 if( pTerm->wtFlags & TERM_VNULL ) continue;
danielk19771d461462009-04-21 09:02:45 +00002061 pIdxCons[j].iColumn = pTerm->u.leftColumn;
2062 pIdxCons[j].iTermOffset = i;
drh7a5bcc02013-01-16 17:08:58 +00002063 op = (u8)pTerm->eOperator & WO_ALL;
drh281bbe22012-10-16 23:17:14 +00002064 if( op==WO_IN ) op = WO_EQ;
2065 pIdxCons[j].op = op;
danielk19771d461462009-04-21 09:02:45 +00002066 /* The direct assignment in the previous line is possible only because
2067 ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The
2068 ** following asserts verify this fact. */
2069 assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
2070 assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
2071 assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
2072 assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
2073 assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
2074 assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
drh281bbe22012-10-16 23:17:14 +00002075 assert( pTerm->eOperator & (WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
danielk19771d461462009-04-21 09:02:45 +00002076 j++;
2077 }
2078 for(i=0; i<nOrderBy; i++){
2079 Expr *pExpr = pOrderBy->a[i].pExpr;
2080 pIdxOrderBy[i].iColumn = pExpr->iColumn;
2081 pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
2082 }
2083
2084 return pIdxInfo;
2085}
2086
2087/*
2088** The table object reference passed as the second argument to this function
2089** must represent a virtual table. This function invokes the xBestIndex()
drh3b48e8c2013-06-12 20:18:16 +00002090** method of the virtual table with the sqlite3_index_info object that
2091** comes in as the 3rd argument to this function.
danielk19771d461462009-04-21 09:02:45 +00002092**
2093** If an error occurs, pParse is populated with an error message and a
2094** non-zero value is returned. Otherwise, 0 is returned and the output
2095** part of the sqlite3_index_info structure is left populated.
2096**
2097** Whether or not an error is returned, it is the responsibility of the
2098** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
2099** that this is required.
2100*/
2101static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
danielk1977595a5232009-07-24 17:58:53 +00002102 sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
danielk19771d461462009-04-21 09:02:45 +00002103 int i;
2104 int rc;
2105
danielk19771d461462009-04-21 09:02:45 +00002106 TRACE_IDX_INPUTS(p);
2107 rc = pVtab->pModule->xBestIndex(pVtab, p);
2108 TRACE_IDX_OUTPUTS(p);
danielk19771d461462009-04-21 09:02:45 +00002109
2110 if( rc!=SQLITE_OK ){
2111 if( rc==SQLITE_NOMEM ){
2112 pParse->db->mallocFailed = 1;
2113 }else if( !pVtab->zErrMsg ){
2114 sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
2115 }else{
2116 sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
2117 }
2118 }
drhb9755982010-07-24 16:34:37 +00002119 sqlite3_free(pVtab->zErrMsg);
danielk19771d461462009-04-21 09:02:45 +00002120 pVtab->zErrMsg = 0;
2121
2122 for(i=0; i<p->nConstraint; i++){
2123 if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
2124 sqlite3ErrorMsg(pParse,
2125 "table %s: xBestIndex returned an invalid plan", pTab->zName);
2126 }
2127 }
2128
2129 return pParse->nErr;
2130}
drh7ba39a92013-05-30 17:43:19 +00002131#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
danielk19771d461462009-04-21 09:02:45 +00002132
drh1435a9a2013-08-27 23:15:44 +00002133#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drh28c4cf42005-07-27 20:41:43 +00002134/*
drhfaacf172011-08-12 01:51:45 +00002135** Estimate the location of a particular key among all keys in an
2136** index. Store the results in aStat as follows:
drhe847d322011-01-20 02:56:37 +00002137**
dana3d0c132015-03-14 18:59:58 +00002138** aStat[0] Est. number of rows less than pRec
2139** aStat[1] Est. number of rows equal to pRec
dan02fa4692009-08-17 17:06:58 +00002140**
drh6d3f91d2014-11-05 19:26:12 +00002141** Return the index of the sample that is the smallest sample that
dana3d0c132015-03-14 18:59:58 +00002142** is greater than or equal to pRec. Note that this index is not an index
2143** into the aSample[] array - it is an index into a virtual set of samples
2144** based on the contents of aSample[] and the number of fields in record
2145** pRec.
dan02fa4692009-08-17 17:06:58 +00002146*/
drh6d3f91d2014-11-05 19:26:12 +00002147static int whereKeyStats(
dan02fa4692009-08-17 17:06:58 +00002148 Parse *pParse, /* Database connection */
2149 Index *pIdx, /* Index to consider domain of */
dan7a419232013-08-06 20:01:43 +00002150 UnpackedRecord *pRec, /* Vector of values to consider */
drhfaacf172011-08-12 01:51:45 +00002151 int roundUp, /* Round up if true. Round down if false */
2152 tRowcnt *aStat /* OUT: stats written here */
dan02fa4692009-08-17 17:06:58 +00002153){
danf52bb8d2013-08-03 20:24:58 +00002154 IndexSample *aSample = pIdx->aSample;
drhfbc38de2013-09-03 19:26:22 +00002155 int iCol; /* Index of required stats in anEq[] etc. */
dana3d0c132015-03-14 18:59:58 +00002156 int i; /* Index of first sample >= pRec */
2157 int iSample; /* Smallest sample larger than or equal to pRec */
dan84c309b2013-08-08 16:17:12 +00002158 int iMin = 0; /* Smallest sample not yet tested */
dan84c309b2013-08-08 16:17:12 +00002159 int iTest; /* Next sample to test */
2160 int res; /* Result of comparison operation */
dana3d0c132015-03-14 18:59:58 +00002161 int nField; /* Number of fields in pRec */
2162 tRowcnt iLower = 0; /* anLt[] + anEq[] of largest sample pRec is > */
dan02fa4692009-08-17 17:06:58 +00002163
drh4f991892013-10-11 15:05:05 +00002164#ifndef SQLITE_DEBUG
2165 UNUSED_PARAMETER( pParse );
2166#endif
drh7f594752013-12-03 19:49:55 +00002167 assert( pRec!=0 );
drh5c624862011-09-22 18:46:34 +00002168 assert( pIdx->nSample>0 );
dana3d0c132015-03-14 18:59:58 +00002169 assert( pRec->nField>0 && pRec->nField<=pIdx->nSampleCol );
2170
2171 /* Do a binary search to find the first sample greater than or equal
2172 ** to pRec. If pRec contains a single field, the set of samples to search
2173 ** is simply the aSample[] array. If the samples in aSample[] contain more
2174 ** than one fields, all fields following the first are ignored.
2175 **
2176 ** If pRec contains N fields, where N is more than one, then as well as the
2177 ** samples in aSample[] (truncated to N fields), the search also has to
2178 ** consider prefixes of those samples. For example, if the set of samples
2179 ** in aSample is:
2180 **
2181 ** aSample[0] = (a, 5)
2182 ** aSample[1] = (a, 10)
2183 ** aSample[2] = (b, 5)
2184 ** aSample[3] = (c, 100)
2185 ** aSample[4] = (c, 105)
2186 **
2187 ** Then the search space should ideally be the samples above and the
2188 ** unique prefixes [a], [b] and [c]. But since that is hard to organize,
2189 ** the code actually searches this set:
2190 **
2191 ** 0: (a)
2192 ** 1: (a, 5)
2193 ** 2: (a, 10)
2194 ** 3: (a, 10)
2195 ** 4: (b)
2196 ** 5: (b, 5)
2197 ** 6: (c)
2198 ** 7: (c, 100)
2199 ** 8: (c, 105)
2200 ** 9: (c, 105)
2201 **
2202 ** For each sample in the aSample[] array, N samples are present in the
2203 ** effective sample array. In the above, samples 0 and 1 are based on
2204 ** sample aSample[0]. Samples 2 and 3 on aSample[1] etc.
2205 **
2206 ** Often, sample i of each block of N effective samples has (i+1) fields.
2207 ** Except, each sample may be extended to ensure that it is greater than or
2208 ** equal to the previous sample in the array. For example, in the above,
2209 ** sample 2 is the first sample of a block of N samples, so at first it
2210 ** appears that it should be 1 field in size. However, that would make it
2211 ** smaller than sample 1, so the binary search would not work. As a result,
2212 ** it is extended to two fields. The duplicates that this creates do not
2213 ** cause any problems.
2214 */
2215 nField = pRec->nField;
2216 iCol = 0;
2217 iSample = pIdx->nSample * nField;
dan84c309b2013-08-08 16:17:12 +00002218 do{
dana3d0c132015-03-14 18:59:58 +00002219 int iSamp; /* Index in aSample[] of test sample */
2220 int n; /* Number of fields in test sample */
2221
2222 iTest = (iMin+iSample)/2;
2223 iSamp = iTest / nField;
2224 if( iSamp>0 ){
2225 /* The proposed effective sample is a prefix of sample aSample[iSamp].
2226 ** Specifically, the shortest prefix of at least (1 + iTest%nField)
2227 ** fields that is greater than the previous effective sample. */
2228 for(n=(iTest % nField) + 1; n<nField; n++){
2229 if( aSample[iSamp-1].anLt[n-1]!=aSample[iSamp].anLt[n-1] ) break;
2230 }
dan84c309b2013-08-08 16:17:12 +00002231 }else{
dana3d0c132015-03-14 18:59:58 +00002232 n = iTest + 1;
dan02fa4692009-08-17 17:06:58 +00002233 }
dana3d0c132015-03-14 18:59:58 +00002234
2235 pRec->nField = n;
2236 res = sqlite3VdbeRecordCompare(aSample[iSamp].n, aSample[iSamp].p, pRec);
2237 if( res<0 ){
2238 iLower = aSample[iSamp].anLt[n-1] + aSample[iSamp].anEq[n-1];
2239 iMin = iTest+1;
2240 }else if( res==0 && n<nField ){
2241 iLower = aSample[iSamp].anLt[n-1];
2242 iMin = iTest+1;
2243 res = -1;
2244 }else{
2245 iSample = iTest;
2246 iCol = n-1;
2247 }
2248 }while( res && iMin<iSample );
2249 i = iSample / nField;
drh51147ba2005-07-23 22:59:55 +00002250
dan84c309b2013-08-08 16:17:12 +00002251#ifdef SQLITE_DEBUG
2252 /* The following assert statements check that the binary search code
2253 ** above found the right answer. This block serves no purpose other
2254 ** than to invoke the asserts. */
dana3d0c132015-03-14 18:59:58 +00002255 if( pParse->db->mallocFailed==0 ){
2256 if( res==0 ){
2257 /* If (res==0) is true, then pRec must be equal to sample i. */
2258 assert( i<pIdx->nSample );
2259 assert( iCol==nField-1 );
2260 pRec->nField = nField;
2261 assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)
2262 || pParse->db->mallocFailed
2263 );
2264 }else{
2265 /* Unless i==pIdx->nSample, indicating that pRec is larger than
2266 ** all samples in the aSample[] array, pRec must be smaller than the
2267 ** (iCol+1) field prefix of sample i. */
2268 assert( i<=pIdx->nSample && i>=0 );
2269 pRec->nField = iCol+1;
2270 assert( i==pIdx->nSample
2271 || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0
2272 || pParse->db->mallocFailed );
2273
2274 /* if i==0 and iCol==0, then record pRec is smaller than all samples
2275 ** in the aSample[] array. Otherwise, if (iCol>0) then pRec must
2276 ** be greater than or equal to the (iCol) field prefix of sample i.
2277 ** If (i>0), then pRec must also be greater than sample (i-1). */
2278 if( iCol>0 ){
2279 pRec->nField = iCol;
2280 assert( sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)<=0
2281 || pParse->db->mallocFailed );
2282 }
2283 if( i>0 ){
2284 pRec->nField = nField;
2285 assert( sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0
2286 || pParse->db->mallocFailed );
2287 }
2288 }
drhfaacf172011-08-12 01:51:45 +00002289 }
dan84c309b2013-08-08 16:17:12 +00002290#endif /* ifdef SQLITE_DEBUG */
dan02fa4692009-08-17 17:06:58 +00002291
dan84c309b2013-08-08 16:17:12 +00002292 if( res==0 ){
dana3d0c132015-03-14 18:59:58 +00002293 /* Record pRec is equal to sample i */
2294 assert( iCol==nField-1 );
daneea568d2013-08-07 19:46:15 +00002295 aStat[0] = aSample[i].anLt[iCol];
2296 aStat[1] = aSample[i].anEq[iCol];
drhfaacf172011-08-12 01:51:45 +00002297 }else{
dana3d0c132015-03-14 18:59:58 +00002298 /* At this point, the (iCol+1) field prefix of aSample[i] is the first
2299 ** sample that is greater than pRec. Or, if i==pIdx->nSample then pRec
2300 ** is larger than all samples in the array. */
2301 tRowcnt iUpper, iGap;
2302 if( i>=pIdx->nSample ){
2303 iUpper = sqlite3LogEstToInt(pIdx->aiRowLogEst[0]);
drhfaacf172011-08-12 01:51:45 +00002304 }else{
dana3d0c132015-03-14 18:59:58 +00002305 iUpper = aSample[i].anLt[iCol];
drhfaacf172011-08-12 01:51:45 +00002306 }
dana3d0c132015-03-14 18:59:58 +00002307
drhfaacf172011-08-12 01:51:45 +00002308 if( iLower>=iUpper ){
2309 iGap = 0;
2310 }else{
2311 iGap = iUpper - iLower;
drhfaacf172011-08-12 01:51:45 +00002312 }
2313 if( roundUp ){
2314 iGap = (iGap*2)/3;
2315 }else{
2316 iGap = iGap/3;
2317 }
2318 aStat[0] = iLower + iGap;
dana3d0c132015-03-14 18:59:58 +00002319 aStat[1] = pIdx->aAvgEq[iCol];
dan02fa4692009-08-17 17:06:58 +00002320 }
dana3d0c132015-03-14 18:59:58 +00002321
2322 /* Restore the pRec->nField value before returning. */
2323 pRec->nField = nField;
drh6d3f91d2014-11-05 19:26:12 +00002324 return i;
dan02fa4692009-08-17 17:06:58 +00002325}
drh1435a9a2013-08-27 23:15:44 +00002326#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
dan937d0de2009-10-15 18:35:38 +00002327
2328/*
danaa9933c2014-04-24 20:04:49 +00002329** If it is not NULL, pTerm is a term that provides an upper or lower
2330** bound on a range scan. Without considering pTerm, it is estimated
2331** that the scan will visit nNew rows. This function returns the number
2332** estimated to be visited after taking pTerm into account.
2333**
2334** If the user explicitly specified a likelihood() value for this term,
2335** then the return value is the likelihood multiplied by the number of
2336** input rows. Otherwise, this function assumes that an "IS NOT NULL" term
2337** has a likelihood of 0.50, and any other term a likelihood of 0.25.
2338*/
2339static LogEst whereRangeAdjust(WhereTerm *pTerm, LogEst nNew){
2340 LogEst nRet = nNew;
2341 if( pTerm ){
2342 if( pTerm->truthProb<=0 ){
2343 nRet += pTerm->truthProb;
dan7de2a1f2014-04-28 20:11:20 +00002344 }else if( (pTerm->wtFlags & TERM_VNULL)==0 ){
danaa9933c2014-04-24 20:04:49 +00002345 nRet -= 20; assert( 20==sqlite3LogEst(4) );
2346 }
2347 }
2348 return nRet;
2349}
2350
mistachkin2d84ac42014-06-26 21:32:09 +00002351#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
danb0b82902014-06-26 20:21:46 +00002352/*
2353** This function is called to estimate the number of rows visited by a
2354** range-scan on a skip-scan index. For example:
2355**
2356** CREATE INDEX i1 ON t1(a, b, c);
2357** SELECT * FROM t1 WHERE a=? AND c BETWEEN ? AND ?;
2358**
2359** Value pLoop->nOut is currently set to the estimated number of rows
2360** visited for scanning (a=? AND b=?). This function reduces that estimate
2361** by some factor to account for the (c BETWEEN ? AND ?) expression based
2362** on the stat4 data for the index. this scan will be peformed multiple
2363** times (once for each (a,b) combination that matches a=?) is dealt with
2364** by the caller.
2365**
2366** It does this by scanning through all stat4 samples, comparing values
2367** extracted from pLower and pUpper with the corresponding column in each
2368** sample. If L and U are the number of samples found to be less than or
2369** equal to the values extracted from pLower and pUpper respectively, and
2370** N is the total number of samples, the pLoop->nOut value is adjusted
2371** as follows:
2372**
2373** nOut = nOut * ( min(U - L, 1) / N )
2374**
2375** If pLower is NULL, or a value cannot be extracted from the term, L is
2376** set to zero. If pUpper is NULL, or a value cannot be extracted from it,
2377** U is set to N.
2378**
2379** Normally, this function sets *pbDone to 1 before returning. However,
2380** if no value can be extracted from either pLower or pUpper (and so the
2381** estimate of the number of rows delivered remains unchanged), *pbDone
2382** is left as is.
2383**
2384** If an error occurs, an SQLite error code is returned. Otherwise,
2385** SQLITE_OK.
2386*/
2387static int whereRangeSkipScanEst(
2388 Parse *pParse, /* Parsing & code generating context */
2389 WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
2390 WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
2391 WhereLoop *pLoop, /* Update the .nOut value of this loop */
2392 int *pbDone /* Set to true if at least one expr. value extracted */
2393){
2394 Index *p = pLoop->u.btree.pIndex;
2395 int nEq = pLoop->u.btree.nEq;
2396 sqlite3 *db = pParse->db;
dan4e42ba42014-06-27 20:14:25 +00002397 int nLower = -1;
2398 int nUpper = p->nSample+1;
danb0b82902014-06-26 20:21:46 +00002399 int rc = SQLITE_OK;
drhd15f87e2014-07-24 22:41:20 +00002400 int iCol = p->aiColumn[nEq];
2401 u8 aff = iCol>=0 ? p->pTable->aCol[iCol].affinity : SQLITE_AFF_INTEGER;
danb0b82902014-06-26 20:21:46 +00002402 CollSeq *pColl;
2403
2404 sqlite3_value *p1 = 0; /* Value extracted from pLower */
2405 sqlite3_value *p2 = 0; /* Value extracted from pUpper */
2406 sqlite3_value *pVal = 0; /* Value extracted from record */
2407
2408 pColl = sqlite3LocateCollSeq(pParse, p->azColl[nEq]);
2409 if( pLower ){
2410 rc = sqlite3Stat4ValueFromExpr(pParse, pLower->pExpr->pRight, aff, &p1);
dan4e42ba42014-06-27 20:14:25 +00002411 nLower = 0;
danb0b82902014-06-26 20:21:46 +00002412 }
2413 if( pUpper && rc==SQLITE_OK ){
2414 rc = sqlite3Stat4ValueFromExpr(pParse, pUpper->pExpr->pRight, aff, &p2);
dan4e42ba42014-06-27 20:14:25 +00002415 nUpper = p2 ? 0 : p->nSample;
danb0b82902014-06-26 20:21:46 +00002416 }
2417
2418 if( p1 || p2 ){
2419 int i;
2420 int nDiff;
2421 for(i=0; rc==SQLITE_OK && i<p->nSample; i++){
2422 rc = sqlite3Stat4Column(db, p->aSample[i].p, p->aSample[i].n, nEq, &pVal);
2423 if( rc==SQLITE_OK && p1 ){
2424 int res = sqlite3MemCompare(p1, pVal, pColl);
dan4e42ba42014-06-27 20:14:25 +00002425 if( res>=0 ) nLower++;
danb0b82902014-06-26 20:21:46 +00002426 }
2427 if( rc==SQLITE_OK && p2 ){
2428 int res = sqlite3MemCompare(p2, pVal, pColl);
dan4e42ba42014-06-27 20:14:25 +00002429 if( res>=0 ) nUpper++;
danb0b82902014-06-26 20:21:46 +00002430 }
2431 }
danb0b82902014-06-26 20:21:46 +00002432 nDiff = (nUpper - nLower);
2433 if( nDiff<=0 ) nDiff = 1;
dan4e42ba42014-06-27 20:14:25 +00002434
2435 /* If there is both an upper and lower bound specified, and the
2436 ** comparisons indicate that they are close together, use the fallback
2437 ** method (assume that the scan visits 1/64 of the rows) for estimating
2438 ** the number of rows visited. Otherwise, estimate the number of rows
2439 ** using the method described in the header comment for this function. */
2440 if( nDiff!=1 || pUpper==0 || pLower==0 ){
2441 int nAdjust = (sqlite3LogEst(p->nSample) - sqlite3LogEst(nDiff));
2442 pLoop->nOut -= nAdjust;
2443 *pbDone = 1;
2444 WHERETRACE(0x10, ("range skip-scan regions: %u..%u adjust=%d est=%d\n",
danfa887452014-06-28 15:26:10 +00002445 nLower, nUpper, nAdjust*-1, pLoop->nOut));
dan4e42ba42014-06-27 20:14:25 +00002446 }
2447
danb0b82902014-06-26 20:21:46 +00002448 }else{
2449 assert( *pbDone==0 );
2450 }
2451
2452 sqlite3ValueFree(p1);
2453 sqlite3ValueFree(p2);
2454 sqlite3ValueFree(pVal);
2455
2456 return rc;
2457}
mistachkin2d84ac42014-06-26 21:32:09 +00002458#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
danb0b82902014-06-26 20:21:46 +00002459
danaa9933c2014-04-24 20:04:49 +00002460/*
dan02fa4692009-08-17 17:06:58 +00002461** This function is used to estimate the number of rows that will be visited
2462** by scanning an index for a range of values. The range may have an upper
2463** bound, a lower bound, or both. The WHERE clause terms that set the upper
2464** and lower bounds are represented by pLower and pUpper respectively. For
2465** example, assuming that index p is on t1(a):
2466**
2467** ... FROM t1 WHERE a > ? AND a < ? ...
2468** |_____| |_____|
2469** | |
2470** pLower pUpper
2471**
drh98cdf622009-08-20 18:14:42 +00002472** If either of the upper or lower bound is not present, then NULL is passed in
drhcdaca552009-08-20 13:45:07 +00002473** place of the corresponding WhereTerm.
dan02fa4692009-08-17 17:06:58 +00002474**
drh6d3f91d2014-11-05 19:26:12 +00002475** The value in (pBuilder->pNew->u.btree.nEq) is the number of the index
dan6cb8d762013-08-08 11:48:57 +00002476** column subject to the range constraint. Or, equivalently, the number of
2477** equality constraints optimized by the proposed index scan. For example,
2478** assuming index p is on t1(a, b), and the SQL query is:
dan02fa4692009-08-17 17:06:58 +00002479**
2480** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
2481**
dan6cb8d762013-08-08 11:48:57 +00002482** then nEq is set to 1 (as the range restricted column, b, is the second
2483** left-most column of the index). Or, if the query is:
dan02fa4692009-08-17 17:06:58 +00002484**
2485** ... FROM t1 WHERE a > ? AND a < ? ...
2486**
dan6cb8d762013-08-08 11:48:57 +00002487** then nEq is set to 0.
dan02fa4692009-08-17 17:06:58 +00002488**
drhbf539c42013-10-05 18:16:02 +00002489** When this function is called, *pnOut is set to the sqlite3LogEst() of the
dan6cb8d762013-08-08 11:48:57 +00002490** number of rows that the index scan is expected to visit without
drh6d3f91d2014-11-05 19:26:12 +00002491** considering the range constraints. If nEq is 0, then *pnOut is the number of
dan6cb8d762013-08-08 11:48:57 +00002492** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced)
peter.d.reid60ec9142014-09-06 16:39:46 +00002493** to account for the range constraints pLower and pUpper.
dan6cb8d762013-08-08 11:48:57 +00002494**
2495** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be
drh94aa7e02014-06-06 17:09:52 +00002496** used, a single range inequality reduces the search space by a factor of 4.
2497** and a pair of constraints (x>? AND x<?) reduces the expected number of
2498** rows visited by a factor of 64.
dan02fa4692009-08-17 17:06:58 +00002499*/
2500static int whereRangeScanEst(
drhcdaca552009-08-20 13:45:07 +00002501 Parse *pParse, /* Parsing & code generating context */
dan7a419232013-08-06 20:01:43 +00002502 WhereLoopBuilder *pBuilder,
drhcdaca552009-08-20 13:45:07 +00002503 WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
2504 WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
drh186ad8c2013-10-08 18:40:37 +00002505 WhereLoop *pLoop /* Modify the .nOut and maybe .rRun fields */
dan02fa4692009-08-17 17:06:58 +00002506){
dan69188d92009-08-19 08:18:32 +00002507 int rc = SQLITE_OK;
drh186ad8c2013-10-08 18:40:37 +00002508 int nOut = pLoop->nOut;
drhbf539c42013-10-05 18:16:02 +00002509 LogEst nNew;
dan69188d92009-08-19 08:18:32 +00002510
drh1435a9a2013-08-27 23:15:44 +00002511#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drh186ad8c2013-10-08 18:40:37 +00002512 Index *p = pLoop->u.btree.pIndex;
drh4f991892013-10-11 15:05:05 +00002513 int nEq = pLoop->u.btree.nEq;
dan02fa4692009-08-17 17:06:58 +00002514
drh6d3f91d2014-11-05 19:26:12 +00002515 if( p->nSample>0 && nEq<p->nSampleCol ){
danb0b82902014-06-26 20:21:46 +00002516 if( nEq==pBuilder->nRecValid ){
2517 UnpackedRecord *pRec = pBuilder->pRec;
2518 tRowcnt a[2];
2519 u8 aff;
drh98cdf622009-08-20 18:14:42 +00002520
danb0b82902014-06-26 20:21:46 +00002521 /* Variable iLower will be set to the estimate of the number of rows in
2522 ** the index that are less than the lower bound of the range query. The
2523 ** lower bound being the concatenation of $P and $L, where $P is the
2524 ** key-prefix formed by the nEq values matched against the nEq left-most
2525 ** columns of the index, and $L is the value in pLower.
2526 **
2527 ** Or, if pLower is NULL or $L cannot be extracted from it (because it
2528 ** is not a simple variable or literal value), the lower bound of the
2529 ** range is $P. Due to a quirk in the way whereKeyStats() works, even
2530 ** if $L is available, whereKeyStats() is called for both ($P) and
drh6d3f91d2014-11-05 19:26:12 +00002531 ** ($P:$L) and the larger of the two returned values is used.
danb0b82902014-06-26 20:21:46 +00002532 **
2533 ** Similarly, iUpper is to be set to the estimate of the number of rows
2534 ** less than the upper bound of the range query. Where the upper bound
2535 ** is either ($P) or ($P:$U). Again, even if $U is available, both values
2536 ** of iUpper are requested of whereKeyStats() and the smaller used.
drh6d3f91d2014-11-05 19:26:12 +00002537 **
2538 ** The number of rows between the two bounds is then just iUpper-iLower.
danb0b82902014-06-26 20:21:46 +00002539 */
drh6d3f91d2014-11-05 19:26:12 +00002540 tRowcnt iLower; /* Rows less than the lower bound */
2541 tRowcnt iUpper; /* Rows less than the upper bound */
2542 int iLwrIdx = -2; /* aSample[] for the lower bound */
2543 int iUprIdx = -1; /* aSample[] for the upper bound */
danb3c02e22013-08-08 19:38:40 +00002544
drhb34fc5b2014-08-28 17:20:37 +00002545 if( pRec ){
2546 testcase( pRec->nField!=pBuilder->nRecValid );
2547 pRec->nField = pBuilder->nRecValid;
2548 }
danb0b82902014-06-26 20:21:46 +00002549 if( nEq==p->nKeyCol ){
2550 aff = SQLITE_AFF_INTEGER;
dan7a419232013-08-06 20:01:43 +00002551 }else{
danb0b82902014-06-26 20:21:46 +00002552 aff = p->pTable->aCol[p->aiColumn[nEq]].affinity;
drhfaacf172011-08-12 01:51:45 +00002553 }
danb0b82902014-06-26 20:21:46 +00002554 /* Determine iLower and iUpper using ($P) only. */
2555 if( nEq==0 ){
2556 iLower = 0;
drh9f07cf72014-10-22 15:27:05 +00002557 iUpper = p->nRowEst0;
danb0b82902014-06-26 20:21:46 +00002558 }else{
2559 /* Note: this call could be optimized away - since the same values must
2560 ** have been requested when testing key $P in whereEqualScanEst(). */
2561 whereKeyStats(pParse, p, pRec, 0, a);
2562 iLower = a[0];
2563 iUpper = a[0] + a[1];
dan6cb8d762013-08-08 11:48:57 +00002564 }
danb0b82902014-06-26 20:21:46 +00002565
drh69afd992014-10-08 02:53:25 +00002566 assert( pLower==0 || (pLower->eOperator & (WO_GT|WO_GE))!=0 );
2567 assert( pUpper==0 || (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
drh681fca02014-10-10 15:01:46 +00002568 assert( p->aSortOrder!=0 );
2569 if( p->aSortOrder[nEq] ){
drh69afd992014-10-08 02:53:25 +00002570 /* The roles of pLower and pUpper are swapped for a DESC index */
2571 SWAP(WhereTerm*, pLower, pUpper);
2572 }
2573
danb0b82902014-06-26 20:21:46 +00002574 /* If possible, improve on the iLower estimate using ($P:$L). */
2575 if( pLower ){
2576 int bOk; /* True if value is extracted from pExpr */
2577 Expr *pExpr = pLower->pExpr->pRight;
danb0b82902014-06-26 20:21:46 +00002578 rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
2579 if( rc==SQLITE_OK && bOk ){
2580 tRowcnt iNew;
drh6d3f91d2014-11-05 19:26:12 +00002581 iLwrIdx = whereKeyStats(pParse, p, pRec, 0, a);
drh69afd992014-10-08 02:53:25 +00002582 iNew = a[0] + ((pLower->eOperator & (WO_GT|WO_LE)) ? a[1] : 0);
danb0b82902014-06-26 20:21:46 +00002583 if( iNew>iLower ) iLower = iNew;
2584 nOut--;
danf741e042014-08-25 18:29:38 +00002585 pLower = 0;
danb0b82902014-06-26 20:21:46 +00002586 }
2587 }
2588
2589 /* If possible, improve on the iUpper estimate using ($P:$U). */
2590 if( pUpper ){
2591 int bOk; /* True if value is extracted from pExpr */
2592 Expr *pExpr = pUpper->pExpr->pRight;
danb0b82902014-06-26 20:21:46 +00002593 rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
2594 if( rc==SQLITE_OK && bOk ){
2595 tRowcnt iNew;
drh6d3f91d2014-11-05 19:26:12 +00002596 iUprIdx = whereKeyStats(pParse, p, pRec, 1, a);
drh69afd992014-10-08 02:53:25 +00002597 iNew = a[0] + ((pUpper->eOperator & (WO_GT|WO_LE)) ? a[1] : 0);
danb0b82902014-06-26 20:21:46 +00002598 if( iNew<iUpper ) iUpper = iNew;
2599 nOut--;
danf741e042014-08-25 18:29:38 +00002600 pUpper = 0;
danb0b82902014-06-26 20:21:46 +00002601 }
2602 }
2603
2604 pBuilder->pRec = pRec;
2605 if( rc==SQLITE_OK ){
2606 if( iUpper>iLower ){
2607 nNew = sqlite3LogEst(iUpper - iLower);
drh6d3f91d2014-11-05 19:26:12 +00002608 /* TUNING: If both iUpper and iLower are derived from the same
2609 ** sample, then assume they are 4x more selective. This brings
2610 ** the estimated selectivity more in line with what it would be
2611 ** if estimated without the use of STAT3/4 tables. */
2612 if( iLwrIdx==iUprIdx ) nNew -= 20; assert( 20==sqlite3LogEst(4) );
danb0b82902014-06-26 20:21:46 +00002613 }else{
2614 nNew = 10; assert( 10==sqlite3LogEst(2) );
2615 }
2616 if( nNew<nOut ){
2617 nOut = nNew;
2618 }
drhae914d72014-08-28 19:38:22 +00002619 WHERETRACE(0x10, ("STAT4 range scan: %u..%u est=%d\n",
danb0b82902014-06-26 20:21:46 +00002620 (u32)iLower, (u32)iUpper, nOut));
danb0b82902014-06-26 20:21:46 +00002621 }
2622 }else{
2623 int bDone = 0;
2624 rc = whereRangeSkipScanEst(pParse, pLower, pUpper, pLoop, &bDone);
2625 if( bDone ) return rc;
drh98cdf622009-08-20 18:14:42 +00002626 }
dan02fa4692009-08-17 17:06:58 +00002627 }
drh3f022182009-09-09 16:10:50 +00002628#else
2629 UNUSED_PARAMETER(pParse);
dan7a419232013-08-06 20:01:43 +00002630 UNUSED_PARAMETER(pBuilder);
dan02fa4692009-08-17 17:06:58 +00002631 assert( pLower || pUpper );
danf741e042014-08-25 18:29:38 +00002632#endif
dan7de2a1f2014-04-28 20:11:20 +00002633 assert( pUpper==0 || (pUpper->wtFlags & TERM_VNULL)==0 );
danaa9933c2014-04-24 20:04:49 +00002634 nNew = whereRangeAdjust(pLower, nOut);
2635 nNew = whereRangeAdjust(pUpper, nNew);
dan7de2a1f2014-04-28 20:11:20 +00002636
drh4dd96a82014-10-24 15:26:29 +00002637 /* TUNING: If there is both an upper and lower limit and neither limit
2638 ** has an application-defined likelihood(), assume the range is
dan42685f22014-04-28 19:34:06 +00002639 ** reduced by an additional 75%. This means that, by default, an open-ended
2640 ** range query (e.g. col > ?) is assumed to match 1/4 of the rows in the
2641 ** index. While a closed range (e.g. col BETWEEN ? AND ?) is estimated to
2642 ** match 1/64 of the index. */
drh4dd96a82014-10-24 15:26:29 +00002643 if( pLower && pLower->truthProb>0 && pUpper && pUpper->truthProb>0 ){
2644 nNew -= 20;
2645 }
dan7de2a1f2014-04-28 20:11:20 +00002646
danaa9933c2014-04-24 20:04:49 +00002647 nOut -= (pLower!=0) + (pUpper!=0);
drhabfa6d52013-09-11 03:53:22 +00002648 if( nNew<10 ) nNew = 10;
2649 if( nNew<nOut ) nOut = nNew;
drhae914d72014-08-28 19:38:22 +00002650#if defined(WHERETRACE_ENABLED)
2651 if( pLoop->nOut>nOut ){
2652 WHERETRACE(0x10,("Range scan lowers nOut from %d to %d\n",
2653 pLoop->nOut, nOut));
2654 }
2655#endif
drh186ad8c2013-10-08 18:40:37 +00002656 pLoop->nOut = (LogEst)nOut;
dan02fa4692009-08-17 17:06:58 +00002657 return rc;
2658}
2659
drh1435a9a2013-08-27 23:15:44 +00002660#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drh82759752011-01-20 16:52:09 +00002661/*
2662** Estimate the number of rows that will be returned based on
2663** an equality constraint x=VALUE and where that VALUE occurs in
2664** the histogram data. This only works when x is the left-most
drhfaacf172011-08-12 01:51:45 +00002665** column of an index and sqlite_stat3 histogram data is available
drhac8eb112011-03-17 01:58:21 +00002666** for that index. When pExpr==NULL that means the constraint is
2667** "x IS NULL" instead of "x=VALUE".
drh82759752011-01-20 16:52:09 +00002668**
drh0c50fa02011-01-21 16:27:18 +00002669** Write the estimated row count into *pnRow and return SQLITE_OK.
2670** If unable to make an estimate, leave *pnRow unchanged and return
2671** non-zero.
drh9b3eb0a2011-01-21 14:37:04 +00002672**
2673** This routine can fail if it is unable to load a collating sequence
2674** required for string comparison, or if unable to allocate memory
2675** for a UTF conversion required for comparison. The error is stored
2676** in the pParse structure.
drh82759752011-01-20 16:52:09 +00002677*/
drh041e09f2011-04-07 19:56:21 +00002678static int whereEqualScanEst(
drh82759752011-01-20 16:52:09 +00002679 Parse *pParse, /* Parsing & code generating context */
dan7a419232013-08-06 20:01:43 +00002680 WhereLoopBuilder *pBuilder,
drh0c50fa02011-01-21 16:27:18 +00002681 Expr *pExpr, /* Expression for VALUE in the x=VALUE constraint */
drhb8a8e8a2013-06-10 19:12:39 +00002682 tRowcnt *pnRow /* Write the revised row estimate here */
drh82759752011-01-20 16:52:09 +00002683){
dan7a419232013-08-06 20:01:43 +00002684 Index *p = pBuilder->pNew->u.btree.pIndex;
2685 int nEq = pBuilder->pNew->u.btree.nEq;
2686 UnpackedRecord *pRec = pBuilder->pRec;
drh82759752011-01-20 16:52:09 +00002687 u8 aff; /* Column affinity */
2688 int rc; /* Subfunction return code */
drhfaacf172011-08-12 01:51:45 +00002689 tRowcnt a[2]; /* Statistics */
dan7a419232013-08-06 20:01:43 +00002690 int bOk;
drh82759752011-01-20 16:52:09 +00002691
dan7a419232013-08-06 20:01:43 +00002692 assert( nEq>=1 );
danfd984b82014-06-30 18:02:20 +00002693 assert( nEq<=p->nColumn );
drh82759752011-01-20 16:52:09 +00002694 assert( p->aSample!=0 );
drh5c624862011-09-22 18:46:34 +00002695 assert( p->nSample>0 );
dan7a419232013-08-06 20:01:43 +00002696 assert( pBuilder->nRecValid<nEq );
2697
2698 /* If values are not available for all fields of the index to the left
2699 ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */
2700 if( pBuilder->nRecValid<(nEq-1) ){
2701 return SQLITE_NOTFOUND;
drh1f9c7662011-03-17 01:34:26 +00002702 }
dan7a419232013-08-06 20:01:43 +00002703
dandd6e1f12013-08-10 19:08:30 +00002704 /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue()
2705 ** below would return the same value. */
danfd984b82014-06-30 18:02:20 +00002706 if( nEq>=p->nColumn ){
dan7a419232013-08-06 20:01:43 +00002707 *pnRow = 1;
2708 return SQLITE_OK;
drh82759752011-01-20 16:52:09 +00002709 }
dan7a419232013-08-06 20:01:43 +00002710
daneea568d2013-08-07 19:46:15 +00002711 aff = p->pTable->aCol[p->aiColumn[nEq-1]].affinity;
dan87cd9322013-08-07 15:52:41 +00002712 rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq-1, &bOk);
2713 pBuilder->pRec = pRec;
dan7a419232013-08-06 20:01:43 +00002714 if( rc!=SQLITE_OK ) return rc;
2715 if( bOk==0 ) return SQLITE_NOTFOUND;
dan7a419232013-08-06 20:01:43 +00002716 pBuilder->nRecValid = nEq;
dan7a419232013-08-06 20:01:43 +00002717
danb3c02e22013-08-08 19:38:40 +00002718 whereKeyStats(pParse, p, pRec, 0, a);
drh989578e2013-10-28 14:34:35 +00002719 WHERETRACE(0x10,("equality scan regions: %d\n", (int)a[1]));
danb3c02e22013-08-08 19:38:40 +00002720 *pnRow = a[1];
daneea568d2013-08-07 19:46:15 +00002721
drh0c50fa02011-01-21 16:27:18 +00002722 return rc;
2723}
drh1435a9a2013-08-27 23:15:44 +00002724#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
drh0c50fa02011-01-21 16:27:18 +00002725
drh1435a9a2013-08-27 23:15:44 +00002726#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drh0c50fa02011-01-21 16:27:18 +00002727/*
2728** Estimate the number of rows that will be returned based on
drh5ac06072011-01-21 18:18:13 +00002729** an IN constraint where the right-hand side of the IN operator
2730** is a list of values. Example:
2731**
2732** WHERE x IN (1,2,3,4)
drh0c50fa02011-01-21 16:27:18 +00002733**
2734** Write the estimated row count into *pnRow and return SQLITE_OK.
2735** If unable to make an estimate, leave *pnRow unchanged and return
2736** non-zero.
2737**
2738** This routine can fail if it is unable to load a collating sequence
2739** required for string comparison, or if unable to allocate memory
2740** for a UTF conversion required for comparison. The error is stored
2741** in the pParse structure.
2742*/
drh041e09f2011-04-07 19:56:21 +00002743static int whereInScanEst(
drh0c50fa02011-01-21 16:27:18 +00002744 Parse *pParse, /* Parsing & code generating context */
dan7a419232013-08-06 20:01:43 +00002745 WhereLoopBuilder *pBuilder,
drh0c50fa02011-01-21 16:27:18 +00002746 ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
drhb8a8e8a2013-06-10 19:12:39 +00002747 tRowcnt *pnRow /* Write the revised row estimate here */
drh0c50fa02011-01-21 16:27:18 +00002748){
dan7a419232013-08-06 20:01:43 +00002749 Index *p = pBuilder->pNew->u.btree.pIndex;
dancfc9df72014-04-25 15:01:01 +00002750 i64 nRow0 = sqlite3LogEstToInt(p->aiRowLogEst[0]);
dan7a419232013-08-06 20:01:43 +00002751 int nRecValid = pBuilder->nRecValid;
drhb8a8e8a2013-06-10 19:12:39 +00002752 int rc = SQLITE_OK; /* Subfunction return code */
2753 tRowcnt nEst; /* Number of rows for a single term */
2754 tRowcnt nRowEst = 0; /* New estimate of the number of rows */
2755 int i; /* Loop counter */
drh0c50fa02011-01-21 16:27:18 +00002756
2757 assert( p->aSample!=0 );
drhfaacf172011-08-12 01:51:45 +00002758 for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
dancfc9df72014-04-25 15:01:01 +00002759 nEst = nRow0;
dan7a419232013-08-06 20:01:43 +00002760 rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst);
drhfaacf172011-08-12 01:51:45 +00002761 nRowEst += nEst;
dan7a419232013-08-06 20:01:43 +00002762 pBuilder->nRecValid = nRecValid;
drh0c50fa02011-01-21 16:27:18 +00002763 }
dan7a419232013-08-06 20:01:43 +00002764
drh0c50fa02011-01-21 16:27:18 +00002765 if( rc==SQLITE_OK ){
dancfc9df72014-04-25 15:01:01 +00002766 if( nRowEst > nRow0 ) nRowEst = nRow0;
drh0c50fa02011-01-21 16:27:18 +00002767 *pnRow = nRowEst;
drh5418b122014-08-28 13:42:13 +00002768 WHERETRACE(0x10,("IN row estimate: est=%d\n", nRowEst));
drh0c50fa02011-01-21 16:27:18 +00002769 }
dan7a419232013-08-06 20:01:43 +00002770 assert( pBuilder->nRecValid==nRecValid );
drh0c50fa02011-01-21 16:27:18 +00002771 return rc;
drh82759752011-01-20 16:52:09 +00002772}
drh1435a9a2013-08-27 23:15:44 +00002773#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
drh82759752011-01-20 16:52:09 +00002774
drh111a6a72008-12-21 03:51:16 +00002775
drhd15cb172013-05-21 19:23:10 +00002776#ifdef WHERETRACE_ENABLED
drha18f3d22013-05-08 03:05:41 +00002777/*
drhc90713d2014-09-30 13:46:49 +00002778** Print the content of a WhereTerm object
2779*/
2780static void whereTermPrint(WhereTerm *pTerm, int iTerm){
drh0a99ba32014-09-30 17:03:35 +00002781 if( pTerm==0 ){
2782 sqlite3DebugPrintf("TERM-%-3d NULL\n", iTerm);
2783 }else{
2784 char zType[4];
2785 memcpy(zType, "...", 4);
2786 if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V';
2787 if( pTerm->eOperator & WO_EQUIV ) zType[1] = 'E';
2788 if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) zType[2] = 'L';
drhfcd49532015-05-13 15:24:07 +00002789 sqlite3DebugPrintf(
2790 "TERM-%-3d %p %s cursor=%-3d prob=%-3d op=0x%03x wtFlags=0x%04x\n",
2791 iTerm, pTerm, zType, pTerm->leftCursor, pTerm->truthProb,
2792 pTerm->eOperator, pTerm->wtFlags);
drh0a99ba32014-09-30 17:03:35 +00002793 sqlite3TreeViewExpr(0, pTerm->pExpr, 0);
2794 }
drhc90713d2014-09-30 13:46:49 +00002795}
2796#endif
2797
2798#ifdef WHERETRACE_ENABLED
2799/*
drha18f3d22013-05-08 03:05:41 +00002800** Print a WhereLoop object for debugging purposes
2801*/
drhc1ba2e72013-10-28 19:03:21 +00002802static void whereLoopPrint(WhereLoop *p, WhereClause *pWC){
2803 WhereInfo *pWInfo = pWC->pWInfo;
drh989578e2013-10-28 14:34:35 +00002804 int nb = 1+(pWInfo->pTabList->nSrc+7)/8;
2805 struct SrcList_item *pItem = pWInfo->pTabList->a + p->iTab;
drha18f3d22013-05-08 03:05:41 +00002806 Table *pTab = pItem->pTab;
drh6457a352013-06-21 00:35:37 +00002807 sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
drha184fb82013-05-08 04:22:59 +00002808 p->iTab, nb, p->maskSelf, nb, p->prereq);
drh6457a352013-06-21 00:35:37 +00002809 sqlite3DebugPrintf(" %12s",
drha18f3d22013-05-08 03:05:41 +00002810 pItem->zAlias ? pItem->zAlias : pTab->zName);
drh5346e952013-05-08 14:14:26 +00002811 if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
drhf3f69ac2014-08-20 23:38:07 +00002812 const char *zName;
2813 if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){
drh319f6772013-05-14 15:31:07 +00002814 if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
2815 int i = sqlite3Strlen30(zName) - 1;
2816 while( zName[i]!='_' ) i--;
2817 zName += i;
2818 }
drh6457a352013-06-21 00:35:37 +00002819 sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq);
drh5346e952013-05-08 14:14:26 +00002820 }else{
drh6457a352013-06-21 00:35:37 +00002821 sqlite3DebugPrintf("%20s","");
drh5346e952013-05-08 14:14:26 +00002822 }
drha18f3d22013-05-08 03:05:41 +00002823 }else{
drh5346e952013-05-08 14:14:26 +00002824 char *z;
2825 if( p->u.vtab.idxStr ){
drh3bd26f02013-05-24 14:52:03 +00002826 z = sqlite3_mprintf("(%d,\"%s\",%x)",
2827 p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
drh5346e952013-05-08 14:14:26 +00002828 }else{
drh3bd26f02013-05-24 14:52:03 +00002829 z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
drh5346e952013-05-08 14:14:26 +00002830 }
drh6457a352013-06-21 00:35:37 +00002831 sqlite3DebugPrintf(" %-19s", z);
drh5346e952013-05-08 14:14:26 +00002832 sqlite3_free(z);
drha18f3d22013-05-08 03:05:41 +00002833 }
drhf3f69ac2014-08-20 23:38:07 +00002834 if( p->wsFlags & WHERE_SKIPSCAN ){
drhc8bbce12014-10-21 01:05:09 +00002835 sqlite3DebugPrintf(" f %05x %d-%d", p->wsFlags, p->nLTerm,p->nSkip);
drhf3f69ac2014-08-20 23:38:07 +00002836 }else{
2837 sqlite3DebugPrintf(" f %05x N %d", p->wsFlags, p->nLTerm);
2838 }
drhb8a8e8a2013-06-10 19:12:39 +00002839 sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
drhc90713d2014-09-30 13:46:49 +00002840 if( p->nLTerm && (sqlite3WhereTrace & 0x100)!=0 ){
2841 int i;
2842 for(i=0; i<p->nLTerm; i++){
drh0a99ba32014-09-30 17:03:35 +00002843 whereTermPrint(p->aLTerm[i], i);
drhc90713d2014-09-30 13:46:49 +00002844 }
2845 }
drha18f3d22013-05-08 03:05:41 +00002846}
2847#endif
2848
drhf1b5f5b2013-05-02 00:15:01 +00002849/*
drh4efc9292013-06-06 23:02:03 +00002850** Convert bulk memory into a valid WhereLoop that can be passed
2851** to whereLoopClear harmlessly.
drh5346e952013-05-08 14:14:26 +00002852*/
drh4efc9292013-06-06 23:02:03 +00002853static void whereLoopInit(WhereLoop *p){
2854 p->aLTerm = p->aLTermSpace;
2855 p->nLTerm = 0;
2856 p->nLSlot = ArraySize(p->aLTermSpace);
2857 p->wsFlags = 0;
2858}
2859
2860/*
2861** Clear the WhereLoop.u union. Leave WhereLoop.pLTerm intact.
2862*/
2863static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
drh986b3872013-06-28 21:12:20 +00002864 if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){
drh13e11b42013-06-06 23:44:25 +00002865 if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
2866 sqlite3_free(p->u.vtab.idxStr);
2867 p->u.vtab.needFree = 0;
2868 p->u.vtab.idxStr = 0;
drh986b3872013-06-28 21:12:20 +00002869 }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){
drh13e11b42013-06-06 23:44:25 +00002870 sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
2871 sqlite3DbFree(db, p->u.btree.pIndex);
2872 p->u.btree.pIndex = 0;
2873 }
drh5346e952013-05-08 14:14:26 +00002874 }
2875}
2876
drh4efc9292013-06-06 23:02:03 +00002877/*
2878** Deallocate internal memory used by a WhereLoop object
2879*/
2880static void whereLoopClear(sqlite3 *db, WhereLoop *p){
2881 if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
2882 whereLoopClearUnion(db, p);
2883 whereLoopInit(p);
2884}
2885
2886/*
2887** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
2888*/
2889static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
2890 WhereTerm **paNew;
2891 if( p->nLSlot>=n ) return SQLITE_OK;
2892 n = (n+7)&~7;
2893 paNew = sqlite3DbMallocRaw(db, sizeof(p->aLTerm[0])*n);
2894 if( paNew==0 ) return SQLITE_NOMEM;
2895 memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
2896 if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
2897 p->aLTerm = paNew;
2898 p->nLSlot = n;
2899 return SQLITE_OK;
2900}
2901
2902/*
2903** Transfer content from the second pLoop into the first.
2904*/
2905static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
drh4efc9292013-06-06 23:02:03 +00002906 whereLoopClearUnion(db, pTo);
drh0d31dc32013-09-06 00:40:59 +00002907 if( whereLoopResize(db, pTo, pFrom->nLTerm) ){
2908 memset(&pTo->u, 0, sizeof(pTo->u));
2909 return SQLITE_NOMEM;
2910 }
drha2014152013-06-07 00:29:23 +00002911 memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
2912 memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
drh4efc9292013-06-06 23:02:03 +00002913 if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
2914 pFrom->u.vtab.needFree = 0;
drh986b3872013-06-28 21:12:20 +00002915 }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){
drh4efc9292013-06-06 23:02:03 +00002916 pFrom->u.btree.pIndex = 0;
2917 }
2918 return SQLITE_OK;
2919}
2920
drh5346e952013-05-08 14:14:26 +00002921/*
drhf1b5f5b2013-05-02 00:15:01 +00002922** Delete a WhereLoop object
2923*/
2924static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
drh5346e952013-05-08 14:14:26 +00002925 whereLoopClear(db, p);
drhf1b5f5b2013-05-02 00:15:01 +00002926 sqlite3DbFree(db, p);
2927}
drh84bfda42005-07-15 13:05:21 +00002928
drh9eff6162006-06-12 21:59:13 +00002929/*
2930** Free a WhereInfo structure
2931*/
drh10fe8402008-10-11 16:47:35 +00002932static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
drh52ff8ea2010-04-08 14:15:56 +00002933 if( ALWAYS(pWInfo) ){
danf89aa472015-04-25 12:20:24 +00002934 int i;
2935 for(i=0; i<pWInfo->nLevel; i++){
2936 WhereLevel *pLevel = &pWInfo->a[i];
2937 if( pLevel->pWLoop && (pLevel->pWLoop->wsFlags & WHERE_IN_ABLE) ){
2938 sqlite3DbFree(db, pLevel->u.in.aInLoop);
2939 }
2940 }
drh70d18342013-06-06 19:16:33 +00002941 whereClauseClear(&pWInfo->sWC);
drhf1b5f5b2013-05-02 00:15:01 +00002942 while( pWInfo->pLoops ){
2943 WhereLoop *p = pWInfo->pLoops;
2944 pWInfo->pLoops = p->pNextLoop;
2945 whereLoopDelete(db, p);
2946 }
drh633e6d52008-07-28 19:34:53 +00002947 sqlite3DbFree(db, pWInfo);
drh9eff6162006-06-12 21:59:13 +00002948 }
2949}
2950
drhf1b5f5b2013-05-02 00:15:01 +00002951/*
drhe0de8762014-11-05 13:13:13 +00002952** Return TRUE if all of the following are true:
drhb355c2c2014-04-18 22:20:31 +00002953**
2954** (1) X has the same or lower cost that Y
2955** (2) X is a proper subset of Y
drhe0de8762014-11-05 13:13:13 +00002956** (3) X skips at least as many columns as Y
drhb355c2c2014-04-18 22:20:31 +00002957**
2958** By "proper subset" we mean that X uses fewer WHERE clause terms
2959** than Y and that every WHERE clause term used by X is also used
2960** by Y.
2961**
2962** If X is a proper subset of Y then Y is a better choice and ought
2963** to have a lower cost. This routine returns TRUE when that cost
drhe0de8762014-11-05 13:13:13 +00002964** relationship is inverted and needs to be adjusted. The third rule
2965** was added because if X uses skip-scan less than Y it still might
2966** deserve a lower cost even if it is a proper subset of Y.
drh3fb183d2014-03-31 19:49:00 +00002967*/
drhb355c2c2014-04-18 22:20:31 +00002968static int whereLoopCheaperProperSubset(
2969 const WhereLoop *pX, /* First WhereLoop to compare */
2970 const WhereLoop *pY /* Compare against this WhereLoop */
2971){
drh3fb183d2014-03-31 19:49:00 +00002972 int i, j;
drhc8bbce12014-10-21 01:05:09 +00002973 if( pX->nLTerm-pX->nSkip >= pY->nLTerm-pY->nSkip ){
2974 return 0; /* X is not a subset of Y */
2975 }
drhe0de8762014-11-05 13:13:13 +00002976 if( pY->nSkip > pX->nSkip ) return 0;
drhb355c2c2014-04-18 22:20:31 +00002977 if( pX->rRun >= pY->rRun ){
2978 if( pX->rRun > pY->rRun ) return 0; /* X costs more than Y */
2979 if( pX->nOut > pY->nOut ) return 0; /* X costs more than Y */
drh3fb183d2014-03-31 19:49:00 +00002980 }
drh9ee88102014-05-07 20:33:17 +00002981 for(i=pX->nLTerm-1; i>=0; i--){
drhc8bbce12014-10-21 01:05:09 +00002982 if( pX->aLTerm[i]==0 ) continue;
drhb355c2c2014-04-18 22:20:31 +00002983 for(j=pY->nLTerm-1; j>=0; j--){
2984 if( pY->aLTerm[j]==pX->aLTerm[i] ) break;
2985 }
2986 if( j<0 ) return 0; /* X not a subset of Y since term X[i] not used by Y */
2987 }
2988 return 1; /* All conditions meet */
drh3fb183d2014-03-31 19:49:00 +00002989}
2990
2991/*
2992** Try to adjust the cost of WhereLoop pTemplate upwards or downwards so
2993** that:
drh53cd10a2014-03-31 18:24:18 +00002994**
drh3fb183d2014-03-31 19:49:00 +00002995** (1) pTemplate costs less than any other WhereLoops that are a proper
2996** subset of pTemplate
drh53cd10a2014-03-31 18:24:18 +00002997**
drh3fb183d2014-03-31 19:49:00 +00002998** (2) pTemplate costs more than any other WhereLoops for which pTemplate
2999** is a proper subset.
drh53cd10a2014-03-31 18:24:18 +00003000**
drh3fb183d2014-03-31 19:49:00 +00003001** To say "WhereLoop X is a proper subset of Y" means that X uses fewer
3002** WHERE clause terms than Y and that every WHERE clause term used by X is
3003** also used by Y.
drh53cd10a2014-03-31 18:24:18 +00003004*/
3005static void whereLoopAdjustCost(const WhereLoop *p, WhereLoop *pTemplate){
3006 if( (pTemplate->wsFlags & WHERE_INDEXED)==0 ) return;
drh53cd10a2014-03-31 18:24:18 +00003007 for(; p; p=p->pNextLoop){
drh3fb183d2014-03-31 19:49:00 +00003008 if( p->iTab!=pTemplate->iTab ) continue;
3009 if( (p->wsFlags & WHERE_INDEXED)==0 ) continue;
drhb355c2c2014-04-18 22:20:31 +00003010 if( whereLoopCheaperProperSubset(p, pTemplate) ){
3011 /* Adjust pTemplate cost downward so that it is cheaper than its
drhe0de8762014-11-05 13:13:13 +00003012 ** subset p. */
drh1b131b72014-10-21 16:01:40 +00003013 WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
3014 pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut-1));
drh3fb183d2014-03-31 19:49:00 +00003015 pTemplate->rRun = p->rRun;
3016 pTemplate->nOut = p->nOut - 1;
drhb355c2c2014-04-18 22:20:31 +00003017 }else if( whereLoopCheaperProperSubset(pTemplate, p) ){
3018 /* Adjust pTemplate cost upward so that it is costlier than p since
3019 ** pTemplate is a proper subset of p */
drh1b131b72014-10-21 16:01:40 +00003020 WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
3021 pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut+1));
drh3fb183d2014-03-31 19:49:00 +00003022 pTemplate->rRun = p->rRun;
3023 pTemplate->nOut = p->nOut + 1;
drh53cd10a2014-03-31 18:24:18 +00003024 }
3025 }
3026}
3027
3028/*
drh7a4b1642014-03-29 21:16:07 +00003029** Search the list of WhereLoops in *ppPrev looking for one that can be
3030** supplanted by pTemplate.
drhf1b5f5b2013-05-02 00:15:01 +00003031**
drh7a4b1642014-03-29 21:16:07 +00003032** Return NULL if the WhereLoop list contains an entry that can supplant
3033** pTemplate, in other words if pTemplate does not belong on the list.
drh23f98da2013-05-21 15:52:07 +00003034**
drh7a4b1642014-03-29 21:16:07 +00003035** If pX is a WhereLoop that pTemplate can supplant, then return the
3036** link that points to pX.
drh23f98da2013-05-21 15:52:07 +00003037**
drh7a4b1642014-03-29 21:16:07 +00003038** If pTemplate cannot supplant any existing element of the list but needs
3039** to be added to the list, then return a pointer to the tail of the list.
drhf1b5f5b2013-05-02 00:15:01 +00003040*/
drh7a4b1642014-03-29 21:16:07 +00003041static WhereLoop **whereLoopFindLesser(
3042 WhereLoop **ppPrev,
3043 const WhereLoop *pTemplate
3044){
3045 WhereLoop *p;
3046 for(p=(*ppPrev); p; ppPrev=&p->pNextLoop, p=*ppPrev){
drhdbb80232013-06-19 12:34:13 +00003047 if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
3048 /* If either the iTab or iSortIdx values for two WhereLoop are different
3049 ** then those WhereLoops need to be considered separately. Neither is
3050 ** a candidate to replace the other. */
3051 continue;
3052 }
3053 /* In the current implementation, the rSetup value is either zero
3054 ** or the cost of building an automatic index (NlogN) and the NlogN
3055 ** is the same for compatible WhereLoops. */
3056 assert( p->rSetup==0 || pTemplate->rSetup==0
3057 || p->rSetup==pTemplate->rSetup );
3058
3059 /* whereLoopAddBtree() always generates and inserts the automatic index
3060 ** case first. Hence compatible candidate WhereLoops never have a larger
3061 ** rSetup. Call this SETUP-INVARIANT */
3062 assert( p->rSetup>=pTemplate->rSetup );
3063
drhdabe36d2014-06-17 20:16:43 +00003064 /* Any loop using an appliation-defined index (or PRIMARY KEY or
3065 ** UNIQUE constraint) with one or more == constraints is better
dan70273d02014-11-14 19:34:20 +00003066 ** than an automatic index. Unless it is a skip-scan. */
drhdabe36d2014-06-17 20:16:43 +00003067 if( (p->wsFlags & WHERE_AUTO_INDEX)!=0
dan70273d02014-11-14 19:34:20 +00003068 && (pTemplate->nSkip)==0
drhdabe36d2014-06-17 20:16:43 +00003069 && (pTemplate->wsFlags & WHERE_INDEXED)!=0
3070 && (pTemplate->wsFlags & WHERE_COLUMN_EQ)!=0
3071 && (p->prereq & pTemplate->prereq)==pTemplate->prereq
3072 ){
3073 break;
3074 }
3075
drh53cd10a2014-03-31 18:24:18 +00003076 /* If existing WhereLoop p is better than pTemplate, pTemplate can be
3077 ** discarded. WhereLoop p is better if:
3078 ** (1) p has no more dependencies than pTemplate, and
3079 ** (2) p has an equal or lower cost than pTemplate
3080 */
3081 if( (p->prereq & pTemplate->prereq)==p->prereq /* (1) */
3082 && p->rSetup<=pTemplate->rSetup /* (2a) */
3083 && p->rRun<=pTemplate->rRun /* (2b) */
3084 && p->nOut<=pTemplate->nOut /* (2c) */
drhf1b5f5b2013-05-02 00:15:01 +00003085 ){
drh53cd10a2014-03-31 18:24:18 +00003086 return 0; /* Discard pTemplate */
drhf1b5f5b2013-05-02 00:15:01 +00003087 }
drh53cd10a2014-03-31 18:24:18 +00003088
3089 /* If pTemplate is always better than p, then cause p to be overwritten
3090 ** with pTemplate. pTemplate is better than p if:
3091 ** (1) pTemplate has no more dependences than p, and
3092 ** (2) pTemplate has an equal or lower cost than p.
3093 */
3094 if( (p->prereq & pTemplate->prereq)==pTemplate->prereq /* (1) */
3095 && p->rRun>=pTemplate->rRun /* (2a) */
3096 && p->nOut>=pTemplate->nOut /* (2b) */
drhf1b5f5b2013-05-02 00:15:01 +00003097 ){
drhadd5ce32013-09-07 00:29:06 +00003098 assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */
drh53cd10a2014-03-31 18:24:18 +00003099 break; /* Cause p to be overwritten by pTemplate */
drhf1b5f5b2013-05-02 00:15:01 +00003100 }
3101 }
drh7a4b1642014-03-29 21:16:07 +00003102 return ppPrev;
3103}
3104
3105/*
drh94a11212004-09-25 13:12:14 +00003106** Insert or replace a WhereLoop entry using the template supplied.
3107**
3108** An existing WhereLoop entry might be overwritten if the new template
3109** is better and has fewer dependencies. Or the template will be ignored
3110** and no insert will occur if an existing WhereLoop is faster and has
3111** fewer dependencies than the template. Otherwise a new WhereLoop is
danielk1977b3bce662005-01-29 08:32:43 +00003112** added based on the template.
drh94a11212004-09-25 13:12:14 +00003113**
drh7a4b1642014-03-29 21:16:07 +00003114** If pBuilder->pOrSet is not NULL then we care about only the
drh94a11212004-09-25 13:12:14 +00003115** prerequisites and rRun and nOut costs of the N best loops. That
3116** information is gathered in the pBuilder->pOrSet object. This special
3117** processing mode is used only for OR clause processing.
danielk1977b3bce662005-01-29 08:32:43 +00003118**
drh94a11212004-09-25 13:12:14 +00003119** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
danielk1977b3bce662005-01-29 08:32:43 +00003120** still might overwrite similar loops with the new template if the
drh53cd10a2014-03-31 18:24:18 +00003121** new template is better. Loops may be overwritten if the following
drh94a11212004-09-25 13:12:14 +00003122** conditions are met:
3123**
3124** (1) They have the same iTab.
3125** (2) They have the same iSortIdx.
3126** (3) The template has same or fewer dependencies than the current loop
3127** (4) The template has the same or lower cost than the current loop
drh94a11212004-09-25 13:12:14 +00003128*/
3129static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
drh7a4b1642014-03-29 21:16:07 +00003130 WhereLoop **ppPrev, *p;
drh94a11212004-09-25 13:12:14 +00003131 WhereInfo *pWInfo = pBuilder->pWInfo;
3132 sqlite3 *db = pWInfo->pParse->db;
3133
3134 /* If pBuilder->pOrSet is defined, then only keep track of the costs
3135 ** and prereqs.
3136 */
3137 if( pBuilder->pOrSet!=0 ){
3138#if WHERETRACE_ENABLED
3139 u16 n = pBuilder->pOrSet->n;
3140 int x =
3141#endif
danielk1977b3bce662005-01-29 08:32:43 +00003142 whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
3143 pTemplate->nOut);
3144#if WHERETRACE_ENABLED /* 0x8 */
drh94a11212004-09-25 13:12:14 +00003145 if( sqlite3WhereTrace & 0x8 ){
danielk1977b3bce662005-01-29 08:32:43 +00003146 sqlite3DebugPrintf(x?" or-%d: ":" or-X: ", n);
drh9012bcb2004-12-19 00:11:35 +00003147 whereLoopPrint(pTemplate, pBuilder->pWC);
drh94a11212004-09-25 13:12:14 +00003148 }
3149#endif
danielk1977b3bce662005-01-29 08:32:43 +00003150 return SQLITE_OK;
drh94a11212004-09-25 13:12:14 +00003151 }
3152
drh7a4b1642014-03-29 21:16:07 +00003153 /* Look for an existing WhereLoop to replace with pTemplate
drh51669862004-12-18 18:40:26 +00003154 */
drh53cd10a2014-03-31 18:24:18 +00003155 whereLoopAdjustCost(pWInfo->pLoops, pTemplate);
drh7a4b1642014-03-29 21:16:07 +00003156 ppPrev = whereLoopFindLesser(&pWInfo->pLoops, pTemplate);
drhf1b5f5b2013-05-02 00:15:01 +00003157
drh7a4b1642014-03-29 21:16:07 +00003158 if( ppPrev==0 ){
3159 /* There already exists a WhereLoop on the list that is better
3160 ** than pTemplate, so just ignore pTemplate */
3161#if WHERETRACE_ENABLED /* 0x8 */
3162 if( sqlite3WhereTrace & 0x8 ){
drh9a7b41d2014-10-08 00:08:08 +00003163 sqlite3DebugPrintf(" skip: ");
drh7a4b1642014-03-29 21:16:07 +00003164 whereLoopPrint(pTemplate, pBuilder->pWC);
drhf1b5f5b2013-05-02 00:15:01 +00003165 }
drh7a4b1642014-03-29 21:16:07 +00003166#endif
3167 return SQLITE_OK;
3168 }else{
3169 p = *ppPrev;
drhf1b5f5b2013-05-02 00:15:01 +00003170 }
3171
3172 /* If we reach this point it means that either p[] should be overwritten
3173 ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
3174 ** WhereLoop and insert it.
3175 */
drh989578e2013-10-28 14:34:35 +00003176#if WHERETRACE_ENABLED /* 0x8 */
drhae70cf12013-05-31 15:18:46 +00003177 if( sqlite3WhereTrace & 0x8 ){
3178 if( p!=0 ){
drh9a7b41d2014-10-08 00:08:08 +00003179 sqlite3DebugPrintf("replace: ");
drhc1ba2e72013-10-28 19:03:21 +00003180 whereLoopPrint(p, pBuilder->pWC);
drhae70cf12013-05-31 15:18:46 +00003181 }
drh9a7b41d2014-10-08 00:08:08 +00003182 sqlite3DebugPrintf(" add: ");
drhc1ba2e72013-10-28 19:03:21 +00003183 whereLoopPrint(pTemplate, pBuilder->pWC);
drhae70cf12013-05-31 15:18:46 +00003184 }
3185#endif
drhf1b5f5b2013-05-02 00:15:01 +00003186 if( p==0 ){
drh7a4b1642014-03-29 21:16:07 +00003187 /* Allocate a new WhereLoop to add to the end of the list */
3188 *ppPrev = p = sqlite3DbMallocRaw(db, sizeof(WhereLoop));
drhf1b5f5b2013-05-02 00:15:01 +00003189 if( p==0 ) return SQLITE_NOMEM;
drh4efc9292013-06-06 23:02:03 +00003190 whereLoopInit(p);
drh7a4b1642014-03-29 21:16:07 +00003191 p->pNextLoop = 0;
3192 }else{
3193 /* We will be overwriting WhereLoop p[]. But before we do, first
3194 ** go through the rest of the list and delete any other entries besides
3195 ** p[] that are also supplated by pTemplate */
3196 WhereLoop **ppTail = &p->pNextLoop;
3197 WhereLoop *pToDel;
3198 while( *ppTail ){
3199 ppTail = whereLoopFindLesser(ppTail, pTemplate);
drhdabe36d2014-06-17 20:16:43 +00003200 if( ppTail==0 ) break;
drh7a4b1642014-03-29 21:16:07 +00003201 pToDel = *ppTail;
3202 if( pToDel==0 ) break;
3203 *ppTail = pToDel->pNextLoop;
3204#if WHERETRACE_ENABLED /* 0x8 */
3205 if( sqlite3WhereTrace & 0x8 ){
drh9a7b41d2014-10-08 00:08:08 +00003206 sqlite3DebugPrintf(" delete: ");
drh7a4b1642014-03-29 21:16:07 +00003207 whereLoopPrint(pToDel, pBuilder->pWC);
3208 }
3209#endif
3210 whereLoopDelete(db, pToDel);
3211 }
drhf1b5f5b2013-05-02 00:15:01 +00003212 }
drh4efc9292013-06-06 23:02:03 +00003213 whereLoopXfer(db, p, pTemplate);
drh5346e952013-05-08 14:14:26 +00003214 if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
drhef866372013-05-22 20:49:02 +00003215 Index *pIndex = p->u.btree.pIndex;
3216 if( pIndex && pIndex->tnum==0 ){
drhcf8fa7a2013-05-10 20:26:22 +00003217 p->u.btree.pIndex = 0;
3218 }
drh5346e952013-05-08 14:14:26 +00003219 }
drhf1b5f5b2013-05-02 00:15:01 +00003220 return SQLITE_OK;
3221}
3222
3223/*
drhcca9f3d2013-09-06 15:23:29 +00003224** Adjust the WhereLoop.nOut value downward to account for terms of the
3225** WHERE clause that reference the loop but which are not used by an
3226** index.
drh7a1bca72014-11-22 18:50:44 +00003227*
3228** For every WHERE clause term that is not used by the index
3229** and which has a truth probability assigned by one of the likelihood(),
3230** likely(), or unlikely() SQL functions, reduce the estimated number
3231** of output rows by the probability specified.
drhcca9f3d2013-09-06 15:23:29 +00003232**
drh7a1bca72014-11-22 18:50:44 +00003233** TUNING: For every WHERE clause term that is not used by the index
3234** and which does not have an assigned truth probability, heuristics
3235** described below are used to try to estimate the truth probability.
3236** TODO --> Perhaps this is something that could be improved by better
3237** table statistics.
3238**
drhab4624d2014-11-22 19:52:10 +00003239** Heuristic 1: Estimate the truth probability as 93.75%. The 93.75%
3240** value corresponds to -1 in LogEst notation, so this means decrement
drh7a1bca72014-11-22 18:50:44 +00003241** the WhereLoop.nOut field for every such WHERE clause term.
3242**
3243** Heuristic 2: If there exists one or more WHERE clause terms of the
3244** form "x==EXPR" and EXPR is not a constant 0 or 1, then make sure the
3245** final output row estimate is no greater than 1/4 of the total number
3246** of rows in the table. In other words, assume that x==EXPR will filter
3247** out at least 3 out of 4 rows. If EXPR is -1 or 0 or 1, then maybe the
3248** "x" column is boolean or else -1 or 0 or 1 is a common default value
3249** on the "x" column and so in that case only cap the output row estimate
3250** at 1/2 instead of 1/4.
drhcca9f3d2013-09-06 15:23:29 +00003251*/
drhd8b77e22014-09-06 01:35:57 +00003252static void whereLoopOutputAdjust(
3253 WhereClause *pWC, /* The WHERE clause */
3254 WhereLoop *pLoop, /* The loop to adjust downward */
3255 LogEst nRow /* Number of rows in the entire table */
3256){
drh7d9e7d82013-09-11 17:39:09 +00003257 WhereTerm *pTerm, *pX;
drhcca9f3d2013-09-06 15:23:29 +00003258 Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf);
drh7a1bca72014-11-22 18:50:44 +00003259 int i, j, k;
3260 LogEst iReduce = 0; /* pLoop->nOut should not exceed nRow-iReduce */
drhadd5ce32013-09-07 00:29:06 +00003261
drha3898252014-11-22 12:22:13 +00003262 assert( (pLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
drhcca9f3d2013-09-06 15:23:29 +00003263 for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){
drh7d9e7d82013-09-11 17:39:09 +00003264 if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break;
drhcca9f3d2013-09-06 15:23:29 +00003265 if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;
3266 if( (pTerm->prereqAll & notAllowed)!=0 ) continue;
drh7d9e7d82013-09-11 17:39:09 +00003267 for(j=pLoop->nLTerm-1; j>=0; j--){
3268 pX = pLoop->aLTerm[j];
drhd2447442013-11-13 19:01:41 +00003269 if( pX==0 ) continue;
drh7d9e7d82013-09-11 17:39:09 +00003270 if( pX==pTerm ) break;
3271 if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break;
3272 }
danaa9933c2014-04-24 20:04:49 +00003273 if( j<0 ){
drhd8b77e22014-09-06 01:35:57 +00003274 if( pTerm->truthProb<=0 ){
drh7a1bca72014-11-22 18:50:44 +00003275 /* If a truth probability is specified using the likelihood() hints,
3276 ** then use the probability provided by the application. */
drhd8b77e22014-09-06 01:35:57 +00003277 pLoop->nOut += pTerm->truthProb;
3278 }else{
drh7a1bca72014-11-22 18:50:44 +00003279 /* In the absence of explicit truth probabilities, use heuristics to
3280 ** guess a reasonable truth probability. */
drhd8b77e22014-09-06 01:35:57 +00003281 pLoop->nOut--;
drhe8d0c612015-05-14 01:05:25 +00003282 if( pTerm->eOperator&(WO_EQ|WO_IS) ){
drh7a1bca72014-11-22 18:50:44 +00003283 Expr *pRight = pTerm->pExpr->pRight;
drhe0cc3c22015-05-13 17:54:08 +00003284 testcase( pTerm->pExpr->op==TK_IS );
drh7a1bca72014-11-22 18:50:44 +00003285 if( sqlite3ExprIsInteger(pRight, &k) && k>=(-1) && k<=1 ){
3286 k = 10;
3287 }else{
3288 k = 20;
3289 }
3290 if( iReduce<k ) iReduce = k;
3291 }
drhd8b77e22014-09-06 01:35:57 +00003292 }
danaa9933c2014-04-24 20:04:49 +00003293 }
drhcca9f3d2013-09-06 15:23:29 +00003294 }
drh7a1bca72014-11-22 18:50:44 +00003295 if( pLoop->nOut > nRow-iReduce ) pLoop->nOut = nRow - iReduce;
drhcca9f3d2013-09-06 15:23:29 +00003296}
3297
3298/*
drhdbd94862014-07-23 23:57:42 +00003299** Adjust the cost C by the costMult facter T. This only occurs if
3300** compiled with -DSQLITE_ENABLE_COSTMULT
3301*/
3302#ifdef SQLITE_ENABLE_COSTMULT
3303# define ApplyCostMultiplier(C,T) C += T
3304#else
3305# define ApplyCostMultiplier(C,T)
3306#endif
3307
3308/*
dan4a6b8a02014-04-30 14:47:01 +00003309** We have so far matched pBuilder->pNew->u.btree.nEq terms of the
3310** index pIndex. Try to match one more.
3311**
3312** When this function is called, pBuilder->pNew->nOut contains the
3313** number of rows expected to be visited by filtering using the nEq
3314** terms only. If it is modified, this value is restored before this
3315** function returns.
drh1c8148f2013-05-04 20:25:23 +00003316**
3317** If pProbe->tnum==0, that means pIndex is a fake index used for the
3318** INTEGER PRIMARY KEY.
3319*/
drh5346e952013-05-08 14:14:26 +00003320static int whereLoopAddBtreeIndex(
drh1c8148f2013-05-04 20:25:23 +00003321 WhereLoopBuilder *pBuilder, /* The WhereLoop factory */
3322 struct SrcList_item *pSrc, /* FROM clause term being analyzed */
3323 Index *pProbe, /* An index on pSrc */
drhbf539c42013-10-05 18:16:02 +00003324 LogEst nInMul /* log(Number of iterations due to IN) */
drh1c8148f2013-05-04 20:25:23 +00003325){
drh70d18342013-06-06 19:16:33 +00003326 WhereInfo *pWInfo = pBuilder->pWInfo; /* WHERE analyse context */
3327 Parse *pParse = pWInfo->pParse; /* Parsing context */
3328 sqlite3 *db = pParse->db; /* Database connection malloc context */
drh1c8148f2013-05-04 20:25:23 +00003329 WhereLoop *pNew; /* Template WhereLoop under construction */
3330 WhereTerm *pTerm; /* A WhereTerm under consideration */
drh43fe25f2013-05-07 23:06:23 +00003331 int opMask; /* Valid operators for constraints */
drh1c8148f2013-05-04 20:25:23 +00003332 WhereScan scan; /* Iterator for WHERE terms */
drh4efc9292013-06-06 23:02:03 +00003333 Bitmask saved_prereq; /* Original value of pNew->prereq */
3334 u16 saved_nLTerm; /* Original value of pNew->nLTerm */
drhcd8629e2013-11-13 12:27:25 +00003335 u16 saved_nEq; /* Original value of pNew->u.btree.nEq */
drhc8bbce12014-10-21 01:05:09 +00003336 u16 saved_nSkip; /* Original value of pNew->nSkip */
drh4efc9292013-06-06 23:02:03 +00003337 u32 saved_wsFlags; /* Original value of pNew->wsFlags */
drhbf539c42013-10-05 18:16:02 +00003338 LogEst saved_nOut; /* Original value of pNew->nOut */
drha18f3d22013-05-08 03:05:41 +00003339 int iCol; /* Index of the column in the table */
drh5346e952013-05-08 14:14:26 +00003340 int rc = SQLITE_OK; /* Return code */
drhd8b77e22014-09-06 01:35:57 +00003341 LogEst rSize; /* Number of rows in the table */
drhbf539c42013-10-05 18:16:02 +00003342 LogEst rLogSize; /* Logarithm of table size */
drhc7f0d222013-06-19 03:27:12 +00003343 WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
drh1c8148f2013-05-04 20:25:23 +00003344
drh1c8148f2013-05-04 20:25:23 +00003345 pNew = pBuilder->pNew;
drh5346e952013-05-08 14:14:26 +00003346 if( db->mallocFailed ) return SQLITE_NOMEM;
drh1c8148f2013-05-04 20:25:23 +00003347
drh5346e952013-05-08 14:14:26 +00003348 assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
drh43fe25f2013-05-07 23:06:23 +00003349 assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
3350 if( pNew->wsFlags & WHERE_BTM_LIMIT ){
3351 opMask = WO_LT|WO_LE;
drhee145872015-05-14 13:18:47 +00003352 }else if( /*pProbe->tnum<=0 ||*/ (pSrc->jointype & JT_LEFT)!=0 ){
drh43fe25f2013-05-07 23:06:23 +00003353 opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE;
drh1c8148f2013-05-04 20:25:23 +00003354 }else{
drhe8d0c612015-05-14 01:05:25 +00003355 opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE|WO_ISNULL|WO_IS;
drh1c8148f2013-05-04 20:25:23 +00003356 }
drhef866372013-05-22 20:49:02 +00003357 if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
drh1c8148f2013-05-04 20:25:23 +00003358
dan39129ce2014-06-30 15:23:57 +00003359 assert( pNew->u.btree.nEq<pProbe->nColumn );
3360 iCol = pProbe->aiColumn[pNew->u.btree.nEq];
3361
drha18f3d22013-05-08 03:05:41 +00003362 pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, iCol,
drh0f133a42013-05-22 17:01:17 +00003363 opMask, pProbe);
drh4efc9292013-06-06 23:02:03 +00003364 saved_nEq = pNew->u.btree.nEq;
drhc8bbce12014-10-21 01:05:09 +00003365 saved_nSkip = pNew->nSkip;
drh4efc9292013-06-06 23:02:03 +00003366 saved_nLTerm = pNew->nLTerm;
3367 saved_wsFlags = pNew->wsFlags;
3368 saved_prereq = pNew->prereq;
3369 saved_nOut = pNew->nOut;
drhb8a8e8a2013-06-10 19:12:39 +00003370 pNew->rSetup = 0;
drhd8b77e22014-09-06 01:35:57 +00003371 rSize = pProbe->aiRowLogEst[0];
3372 rLogSize = estLog(rSize);
drh5346e952013-05-08 14:14:26 +00003373 for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
dan8ad1d8b2014-04-25 20:22:45 +00003374 u16 eOp = pTerm->eOperator; /* Shorthand for pTerm->eOperator */
danaa9933c2014-04-24 20:04:49 +00003375 LogEst rCostIdx;
dan8ad1d8b2014-04-25 20:22:45 +00003376 LogEst nOutUnadjusted; /* nOut before IN() and WHERE adjustments */
drhb8a8e8a2013-06-10 19:12:39 +00003377 int nIn = 0;
drh1435a9a2013-08-27 23:15:44 +00003378#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
dan7a419232013-08-06 20:01:43 +00003379 int nRecValid = pBuilder->nRecValid;
drhb5246e52013-07-08 21:12:57 +00003380#endif
dan8ad1d8b2014-04-25 20:22:45 +00003381 if( (eOp==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)
dan8bff07a2013-08-29 14:56:14 +00003382 && (iCol<0 || pSrc->pTab->aCol[iCol].notNull)
3383 ){
3384 continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */
3385 }
dan7a419232013-08-06 20:01:43 +00003386 if( pTerm->prereqRight & pNew->maskSelf ) continue;
3387
drha40da622015-03-09 12:11:56 +00003388 /* Do not allow the upper bound of a LIKE optimization range constraint
3389 ** to mix with a lower range bound from some other source */
3390 if( pTerm->wtFlags & TERM_LIKEOPT && pTerm->eOperator==WO_LT ) continue;
3391
drh4efc9292013-06-06 23:02:03 +00003392 pNew->wsFlags = saved_wsFlags;
3393 pNew->u.btree.nEq = saved_nEq;
3394 pNew->nLTerm = saved_nLTerm;
3395 if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
3396 pNew->aLTerm[pNew->nLTerm++] = pTerm;
3397 pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
dan8ad1d8b2014-04-25 20:22:45 +00003398
3399 assert( nInMul==0
3400 || (pNew->wsFlags & WHERE_COLUMN_NULL)!=0
3401 || (pNew->wsFlags & WHERE_COLUMN_IN)!=0
3402 || (pNew->wsFlags & WHERE_SKIPSCAN)!=0
3403 );
3404
3405 if( eOp & WO_IN ){
drha18f3d22013-05-08 03:05:41 +00003406 Expr *pExpr = pTerm->pExpr;
3407 pNew->wsFlags |= WHERE_COLUMN_IN;
3408 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
drhe1e2e9a2013-06-13 15:16:53 +00003409 /* "x IN (SELECT ...)": TUNING: the SELECT returns 25 rows */
drhbf539c42013-10-05 18:16:02 +00003410 nIn = 46; assert( 46==sqlite3LogEst(25) );
drha18f3d22013-05-08 03:05:41 +00003411 }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
3412 /* "x IN (value, value, ...)" */
drhbf539c42013-10-05 18:16:02 +00003413 nIn = sqlite3LogEst(pExpr->x.pList->nExpr);
drhf1645f02013-05-07 19:44:38 +00003414 }
drh2b59b3a2014-03-20 13:26:47 +00003415 assert( nIn>0 ); /* RHS always has 2 or more terms... The parser
3416 ** changes "x IN (?)" into "x=?". */
dan8ad1d8b2014-04-25 20:22:45 +00003417
drhe8d0c612015-05-14 01:05:25 +00003418 }else if( eOp & (WO_EQ|WO_IS) ){
drha18f3d22013-05-08 03:05:41 +00003419 pNew->wsFlags |= WHERE_COLUMN_EQ;
dan8ad1d8b2014-04-25 20:22:45 +00003420 if( iCol<0 || (nInMul==0 && pNew->u.btree.nEq==pProbe->nKeyCol-1) ){
dan2813bde2015-04-11 11:44:27 +00003421 if( iCol>=0 && pProbe->uniqNotNull==0 ){
drhe39a7322014-02-03 14:04:11 +00003422 pNew->wsFlags |= WHERE_UNQ_WANTED;
3423 }else{
3424 pNew->wsFlags |= WHERE_ONEROW;
3425 }
drh21f7ff72013-06-03 15:07:23 +00003426 }
dan2dd3cdc2014-04-26 20:21:14 +00003427 }else if( eOp & WO_ISNULL ){
3428 pNew->wsFlags |= WHERE_COLUMN_NULL;
dan8ad1d8b2014-04-25 20:22:45 +00003429 }else if( eOp & (WO_GT|WO_GE) ){
3430 testcase( eOp & WO_GT );
3431 testcase( eOp & WO_GE );
drha18f3d22013-05-08 03:05:41 +00003432 pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
drh6f2bfad2013-06-03 17:35:22 +00003433 pBtm = pTerm;
3434 pTop = 0;
drha40da622015-03-09 12:11:56 +00003435 if( pTerm->wtFlags & TERM_LIKEOPT ){
drh80314622015-03-09 13:01:02 +00003436 /* Range contraints that come from the LIKE optimization are
3437 ** always used in pairs. */
drha40da622015-03-09 12:11:56 +00003438 pTop = &pTerm[1];
3439 assert( (pTop-(pTerm->pWC->a))<pTerm->pWC->nTerm );
3440 assert( pTop->wtFlags & TERM_LIKEOPT );
3441 assert( pTop->eOperator==WO_LT );
3442 if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
3443 pNew->aLTerm[pNew->nLTerm++] = pTop;
3444 pNew->wsFlags |= WHERE_TOP_LIMIT;
3445 }
dan2dd3cdc2014-04-26 20:21:14 +00003446 }else{
dan8ad1d8b2014-04-25 20:22:45 +00003447 assert( eOp & (WO_LT|WO_LE) );
3448 testcase( eOp & WO_LT );
3449 testcase( eOp & WO_LE );
drha18f3d22013-05-08 03:05:41 +00003450 pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
drh6f2bfad2013-06-03 17:35:22 +00003451 pTop = pTerm;
3452 pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
drh4efc9292013-06-06 23:02:03 +00003453 pNew->aLTerm[pNew->nLTerm-2] : 0;
drh1c8148f2013-05-04 20:25:23 +00003454 }
dan8ad1d8b2014-04-25 20:22:45 +00003455
3456 /* At this point pNew->nOut is set to the number of rows expected to
3457 ** be visited by the index scan before considering term pTerm, or the
3458 ** values of nIn and nInMul. In other words, assuming that all
3459 ** "x IN(...)" terms are replaced with "x = ?". This block updates
3460 ** the value of pNew->nOut to account for pTerm (but not nIn/nInMul). */
3461 assert( pNew->nOut==saved_nOut );
drh6f2bfad2013-06-03 17:35:22 +00003462 if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
danaa9933c2014-04-24 20:04:49 +00003463 /* Adjust nOut using stat3/stat4 data. Or, if there is no stat3/stat4
3464 ** data, using some other estimate. */
drh186ad8c2013-10-08 18:40:37 +00003465 whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew);
dan8ad1d8b2014-04-25 20:22:45 +00003466 }else{
3467 int nEq = ++pNew->u.btree.nEq;
drhe8d0c612015-05-14 01:05:25 +00003468 assert( eOp & (WO_ISNULL|WO_EQ|WO_IN|WO_IS) );
dan8ad1d8b2014-04-25 20:22:45 +00003469
3470 assert( pNew->nOut==saved_nOut );
dan09e1df62014-04-29 16:10:22 +00003471 if( pTerm->truthProb<=0 && iCol>=0 ){
dan8ad1d8b2014-04-25 20:22:45 +00003472 assert( (eOp & WO_IN) || nIn==0 );
drhc5f246e2014-05-01 20:24:21 +00003473 testcase( eOp & WO_IN );
dan8ad1d8b2014-04-25 20:22:45 +00003474 pNew->nOut += pTerm->truthProb;
3475 pNew->nOut -= nIn;
dan8ad1d8b2014-04-25 20:22:45 +00003476 }else{
drh1435a9a2013-08-27 23:15:44 +00003477#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
dan8ad1d8b2014-04-25 20:22:45 +00003478 tRowcnt nOut = 0;
3479 if( nInMul==0
3480 && pProbe->nSample
3481 && pNew->u.btree.nEq<=pProbe->nSampleCol
dan8ad1d8b2014-04-25 20:22:45 +00003482 && ((eOp & WO_IN)==0 || !ExprHasProperty(pTerm->pExpr, EP_xIsSelect))
dan8ad1d8b2014-04-25 20:22:45 +00003483 ){
3484 Expr *pExpr = pTerm->pExpr;
drhe8d0c612015-05-14 01:05:25 +00003485 if( (eOp & (WO_EQ|WO_ISNULL|WO_IS))!=0 ){
3486 testcase( eOp & WO_EQ );
3487 testcase( eOp & WO_IS );
dan8ad1d8b2014-04-25 20:22:45 +00003488 testcase( eOp & WO_ISNULL );
3489 rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut);
3490 }else{
3491 rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut);
3492 }
dan8ad1d8b2014-04-25 20:22:45 +00003493 if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
3494 if( rc!=SQLITE_OK ) break; /* Jump out of the pTerm loop */
3495 if( nOut ){
3496 pNew->nOut = sqlite3LogEst(nOut);
3497 if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut;
3498 pNew->nOut -= nIn;
3499 }
3500 }
3501 if( nOut==0 )
3502#endif
3503 {
3504 pNew->nOut += (pProbe->aiRowLogEst[nEq] - pProbe->aiRowLogEst[nEq-1]);
3505 if( eOp & WO_ISNULL ){
3506 /* TUNING: If there is no likelihood() value, assume that a
3507 ** "col IS NULL" expression matches twice as many rows
3508 ** as (col=?). */
3509 pNew->nOut += 10;
3510 }
3511 }
dan6cb8d762013-08-08 11:48:57 +00003512 }
drh6f2bfad2013-06-03 17:35:22 +00003513 }
dan8ad1d8b2014-04-25 20:22:45 +00003514
danaa9933c2014-04-24 20:04:49 +00003515 /* Set rCostIdx to the cost of visiting selected rows in index. Add
3516 ** it to pNew->rRun, which is currently set to the cost of the index
3517 ** seek only. Then, if this is a non-covering index, add the cost of
3518 ** visiting the rows in the main table. */
3519 rCostIdx = pNew->nOut + 1 + (15*pProbe->szIdxRow)/pSrc->pTab->szTabRow;
dan8ad1d8b2014-04-25 20:22:45 +00003520 pNew->rRun = sqlite3LogEstAdd(rLogSize, rCostIdx);
drhe217efc2013-06-12 03:48:41 +00003521 if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
danaa9933c2014-04-24 20:04:49 +00003522 pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut + 16);
drheb04de32013-05-10 15:16:30 +00003523 }
drhdbd94862014-07-23 23:57:42 +00003524 ApplyCostMultiplier(pNew->rRun, pProbe->pTable->costMult);
danaa9933c2014-04-24 20:04:49 +00003525
dan8ad1d8b2014-04-25 20:22:45 +00003526 nOutUnadjusted = pNew->nOut;
3527 pNew->rRun += nInMul + nIn;
3528 pNew->nOut += nInMul + nIn;
drhd8b77e22014-09-06 01:35:57 +00003529 whereLoopOutputAdjust(pBuilder->pWC, pNew, rSize);
drhcf8fa7a2013-05-10 20:26:22 +00003530 rc = whereLoopInsert(pBuilder, pNew);
dan440e6ff2014-04-28 08:49:54 +00003531
3532 if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
3533 pNew->nOut = saved_nOut;
3534 }else{
3535 pNew->nOut = nOutUnadjusted;
3536 }
dan8ad1d8b2014-04-25 20:22:45 +00003537
drh5346e952013-05-08 14:14:26 +00003538 if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
dan39129ce2014-06-30 15:23:57 +00003539 && pNew->u.btree.nEq<pProbe->nColumn
drh5346e952013-05-08 14:14:26 +00003540 ){
drhb8a8e8a2013-06-10 19:12:39 +00003541 whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
drha18f3d22013-05-08 03:05:41 +00003542 }
danad45ed72013-08-08 12:21:32 +00003543 pNew->nOut = saved_nOut;
drh1435a9a2013-08-27 23:15:44 +00003544#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
dan7a419232013-08-06 20:01:43 +00003545 pBuilder->nRecValid = nRecValid;
dan7a419232013-08-06 20:01:43 +00003546#endif
drh1c8148f2013-05-04 20:25:23 +00003547 }
drh4efc9292013-06-06 23:02:03 +00003548 pNew->prereq = saved_prereq;
3549 pNew->u.btree.nEq = saved_nEq;
drhc8bbce12014-10-21 01:05:09 +00003550 pNew->nSkip = saved_nSkip;
drh4efc9292013-06-06 23:02:03 +00003551 pNew->wsFlags = saved_wsFlags;
3552 pNew->nOut = saved_nOut;
3553 pNew->nLTerm = saved_nLTerm;
drhc8bbce12014-10-21 01:05:09 +00003554
3555 /* Consider using a skip-scan if there are no WHERE clause constraints
3556 ** available for the left-most terms of the index, and if the average
3557 ** number of repeats in the left-most terms is at least 18.
3558 **
3559 ** The magic number 18 is selected on the basis that scanning 17 rows
3560 ** is almost always quicker than an index seek (even though if the index
3561 ** contains fewer than 2^17 rows we assume otherwise in other parts of
3562 ** the code). And, even if it is not, it should not be too much slower.
3563 ** On the other hand, the extra seeks could end up being significantly
3564 ** more expensive. */
3565 assert( 42==sqlite3LogEst(18) );
3566 if( saved_nEq==saved_nSkip
3567 && saved_nEq+1<pProbe->nKeyCol
drhf9df2fb2014-11-15 19:08:13 +00003568 && pProbe->noSkipScan==0
drhc8bbce12014-10-21 01:05:09 +00003569 && pProbe->aiRowLogEst[saved_nEq+1]>=42 /* TUNING: Minimum for skip-scan */
3570 && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK
3571 ){
3572 LogEst nIter;
3573 pNew->u.btree.nEq++;
3574 pNew->nSkip++;
3575 pNew->aLTerm[pNew->nLTerm++] = 0;
3576 pNew->wsFlags |= WHERE_SKIPSCAN;
3577 nIter = pProbe->aiRowLogEst[saved_nEq] - pProbe->aiRowLogEst[saved_nEq+1];
drhc8bbce12014-10-21 01:05:09 +00003578 pNew->nOut -= nIter;
3579 /* TUNING: Because uncertainties in the estimates for skip-scan queries,
3580 ** add a 1.375 fudge factor to make skip-scan slightly less likely. */
3581 nIter += 5;
3582 whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nIter + nInMul);
3583 pNew->nOut = saved_nOut;
3584 pNew->u.btree.nEq = saved_nEq;
3585 pNew->nSkip = saved_nSkip;
3586 pNew->wsFlags = saved_wsFlags;
3587 }
3588
drh5346e952013-05-08 14:14:26 +00003589 return rc;
drh1c8148f2013-05-04 20:25:23 +00003590}
3591
3592/*
drh23f98da2013-05-21 15:52:07 +00003593** Return True if it is possible that pIndex might be useful in
3594** implementing the ORDER BY clause in pBuilder.
3595**
3596** Return False if pBuilder does not contain an ORDER BY clause or
3597** if there is no way for pIndex to be useful in implementing that
3598** ORDER BY clause.
3599*/
3600static int indexMightHelpWithOrderBy(
3601 WhereLoopBuilder *pBuilder,
3602 Index *pIndex,
3603 int iCursor
3604){
3605 ExprList *pOB;
drh6d381472013-06-13 17:58:08 +00003606 int ii, jj;
drh23f98da2013-05-21 15:52:07 +00003607
drh53cfbe92013-06-13 17:28:22 +00003608 if( pIndex->bUnordered ) return 0;
drh70d18342013-06-06 19:16:33 +00003609 if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
drh23f98da2013-05-21 15:52:07 +00003610 for(ii=0; ii<pOB->nExpr; ii++){
drh45c154a2013-06-03 20:46:35 +00003611 Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr);
drh23f98da2013-05-21 15:52:07 +00003612 if( pExpr->op!=TK_COLUMN ) return 0;
3613 if( pExpr->iTable==iCursor ){
drh137fd4f2014-09-19 02:01:37 +00003614 if( pExpr->iColumn<0 ) return 1;
drhbbbdc832013-10-22 18:01:40 +00003615 for(jj=0; jj<pIndex->nKeyCol; jj++){
drh6d381472013-06-13 17:58:08 +00003616 if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
3617 }
drh23f98da2013-05-21 15:52:07 +00003618 }
3619 }
3620 return 0;
3621}
3622
3623/*
drh92a121f2013-06-10 12:15:47 +00003624** Return a bitmask where 1s indicate that the corresponding column of
3625** the table is used by an index. Only the first 63 columns are considered.
3626*/
drhfd5874d2013-06-12 14:52:39 +00003627static Bitmask columnsInIndex(Index *pIdx){
drh92a121f2013-06-10 12:15:47 +00003628 Bitmask m = 0;
3629 int j;
drhec95c442013-10-23 01:57:32 +00003630 for(j=pIdx->nColumn-1; j>=0; j--){
drh92a121f2013-06-10 12:15:47 +00003631 int x = pIdx->aiColumn[j];
drhec95c442013-10-23 01:57:32 +00003632 if( x>=0 ){
3633 testcase( x==BMS-1 );
3634 testcase( x==BMS-2 );
3635 if( x<BMS-1 ) m |= MASKBIT(x);
3636 }
drh92a121f2013-06-10 12:15:47 +00003637 }
3638 return m;
3639}
3640
drh4bd5f732013-07-31 23:22:39 +00003641/* Check to see if a partial index with pPartIndexWhere can be used
3642** in the current query. Return true if it can be and false if not.
3643*/
3644static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere){
3645 int i;
3646 WhereTerm *pTerm;
3647 for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
dan2a45cb52015-02-24 20:10:49 +00003648 Expr *pExpr = pTerm->pExpr;
3649 if( sqlite3ExprImpliesExpr(pExpr, pWhere, iTab)
3650 && (!ExprHasProperty(pExpr, EP_FromJoin) || pExpr->iRightJoinTable==iTab)
drh077f06e2015-02-24 16:48:59 +00003651 ){
3652 return 1;
3653 }
drh4bd5f732013-07-31 23:22:39 +00003654 }
3655 return 0;
3656}
drh92a121f2013-06-10 12:15:47 +00003657
3658/*
dan51576f42013-07-02 10:06:15 +00003659** Add all WhereLoop objects for a single table of the join where the table
drh0823c892013-05-11 00:06:23 +00003660** is idenfied by pBuilder->pNew->iTab. That table is guaranteed to be
3661** a b-tree table, not a virtual table.
dan81647222014-04-30 15:00:16 +00003662**
3663** The costs (WhereLoop.rRun) of the b-tree loops added by this function
3664** are calculated as follows:
3665**
3666** For a full scan, assuming the table (or index) contains nRow rows:
3667**
3668** cost = nRow * 3.0 // full-table scan
3669** cost = nRow * K // scan of covering index
3670** cost = nRow * (K+3.0) // scan of non-covering index
3671**
3672** where K is a value between 1.1 and 3.0 set based on the relative
3673** estimated average size of the index and table records.
3674**
3675** For an index scan, where nVisit is the number of index rows visited
3676** by the scan, and nSeek is the number of seek operations required on
3677** the index b-tree:
3678**
3679** cost = nSeek * (log(nRow) + K * nVisit) // covering index
3680** cost = nSeek * (log(nRow) + (K+3.0) * nVisit) // non-covering index
3681**
3682** Normally, nSeek is 1. nSeek values greater than 1 come about if the
3683** WHERE clause includes "x IN (....)" terms used in place of "x=?". Or when
3684** implicit "x IN (SELECT x FROM tbl)" terms are added for skip-scans.
drh83a305f2014-07-22 12:05:32 +00003685**
3686** The estimated values (nRow, nVisit, nSeek) often contain a large amount
3687** of uncertainty. For this reason, scoring is designed to pick plans that
3688** "do the least harm" if the estimates are inaccurate. For example, a
3689** log(nRow) factor is omitted from a non-covering index scan in order to
3690** bias the scoring in favor of using an index, since the worst-case
3691** performance of using an index is far better than the worst-case performance
3692** of a full table scan.
drhf1b5f5b2013-05-02 00:15:01 +00003693*/
drh5346e952013-05-08 14:14:26 +00003694static int whereLoopAddBtree(
drh1c8148f2013-05-04 20:25:23 +00003695 WhereLoopBuilder *pBuilder, /* WHERE clause information */
drh1c8148f2013-05-04 20:25:23 +00003696 Bitmask mExtra /* Extra prerequesites for using this table */
drhf1b5f5b2013-05-02 00:15:01 +00003697){
drh70d18342013-06-06 19:16:33 +00003698 WhereInfo *pWInfo; /* WHERE analysis context */
drh1c8148f2013-05-04 20:25:23 +00003699 Index *pProbe; /* An index we are evaluating */
drh1c8148f2013-05-04 20:25:23 +00003700 Index sPk; /* A fake index object for the primary key */
dancfc9df72014-04-25 15:01:01 +00003701 LogEst aiRowEstPk[2]; /* The aiRowLogEst[] value for the sPk index */
drhbbbdc832013-10-22 18:01:40 +00003702 i16 aiColumnPk = -1; /* The aColumn[] value for the sPk index */
drh70d18342013-06-06 19:16:33 +00003703 SrcList *pTabList; /* The FROM clause */
drh1c8148f2013-05-04 20:25:23 +00003704 struct SrcList_item *pSrc; /* The FROM clause btree term to add */
drh1c8148f2013-05-04 20:25:23 +00003705 WhereLoop *pNew; /* Template WhereLoop object */
drh5346e952013-05-08 14:14:26 +00003706 int rc = SQLITE_OK; /* Return code */
drhd044d202013-05-31 12:43:55 +00003707 int iSortIdx = 1; /* Index number */
drh23f98da2013-05-21 15:52:07 +00003708 int b; /* A boolean value */
drhbf539c42013-10-05 18:16:02 +00003709 LogEst rSize; /* number of rows in the table */
3710 LogEst rLogSize; /* Logarithm of the number of rows in the table */
drh4bd5f732013-07-31 23:22:39 +00003711 WhereClause *pWC; /* The parsed WHERE clause */
drh3495d202013-10-07 17:32:15 +00003712 Table *pTab; /* Table being queried */
drh23f98da2013-05-21 15:52:07 +00003713
drh1c8148f2013-05-04 20:25:23 +00003714 pNew = pBuilder->pNew;
drh70d18342013-06-06 19:16:33 +00003715 pWInfo = pBuilder->pWInfo;
3716 pTabList = pWInfo->pTabList;
3717 pSrc = pTabList->a + pNew->iTab;
drh3495d202013-10-07 17:32:15 +00003718 pTab = pSrc->pTab;
drh4bd5f732013-07-31 23:22:39 +00003719 pWC = pBuilder->pWC;
drh0823c892013-05-11 00:06:23 +00003720 assert( !IsVirtual(pSrc->pTab) );
drh1c8148f2013-05-04 20:25:23 +00003721
3722 if( pSrc->pIndex ){
3723 /* An INDEXED BY clause specifies a particular index to use */
3724 pProbe = pSrc->pIndex;
drhec95c442013-10-23 01:57:32 +00003725 }else if( !HasRowid(pTab) ){
3726 pProbe = pTab->pIndex;
drh1c8148f2013-05-04 20:25:23 +00003727 }else{
3728 /* There is no INDEXED BY clause. Create a fake Index object in local
3729 ** variable sPk to represent the rowid primary key index. Make this
3730 ** fake index the first in a chain of Index objects with all of the real
3731 ** indices to follow */
3732 Index *pFirst; /* First of real indices on the table */
3733 memset(&sPk, 0, sizeof(Index));
drhbbbdc832013-10-22 18:01:40 +00003734 sPk.nKeyCol = 1;
dan39129ce2014-06-30 15:23:57 +00003735 sPk.nColumn = 1;
drh1c8148f2013-05-04 20:25:23 +00003736 sPk.aiColumn = &aiColumnPk;
dancfc9df72014-04-25 15:01:01 +00003737 sPk.aiRowLogEst = aiRowEstPk;
drh1c8148f2013-05-04 20:25:23 +00003738 sPk.onError = OE_Replace;
drh3495d202013-10-07 17:32:15 +00003739 sPk.pTable = pTab;
danaa9933c2014-04-24 20:04:49 +00003740 sPk.szIdxRow = pTab->szTabRow;
dancfc9df72014-04-25 15:01:01 +00003741 aiRowEstPk[0] = pTab->nRowLogEst;
3742 aiRowEstPk[1] = 0;
drh1c8148f2013-05-04 20:25:23 +00003743 pFirst = pSrc->pTab->pIndex;
3744 if( pSrc->notIndexed==0 ){
3745 /* The real indices of the table are only considered if the
3746 ** NOT INDEXED qualifier is omitted from the FROM clause */
3747 sPk.pNext = pFirst;
3748 }
3749 pProbe = &sPk;
3750 }
dancfc9df72014-04-25 15:01:01 +00003751 rSize = pTab->nRowLogEst;
drheb04de32013-05-10 15:16:30 +00003752 rLogSize = estLog(rSize);
3753
drhfeb56e02013-08-23 17:33:46 +00003754#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
drheb04de32013-05-10 15:16:30 +00003755 /* Automatic indexes */
drhd092ed42015-05-29 14:36:30 +00003756 if( !pBuilder->pOrSet /* Not part of an OR optimization */
drh8e8e7ef2015-03-02 17:25:00 +00003757 && (pWInfo->wctrlFlags & WHERE_NO_AUTOINDEX)==0
drh4fe425a2013-06-12 17:08:06 +00003758 && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
drhd092ed42015-05-29 14:36:30 +00003759 && pSrc->pIndex==0 /* Has no INDEXED BY clause */
3760 && !pSrc->notIndexed /* Has no NOT INDEXED clause */
3761 && HasRowid(pTab) /* Is not a WITHOUT ROWID table. (FIXME: Why not?) */
3762 && !pSrc->isCorrelated /* Not a correlated subquery */
3763 && !pSrc->isRecursive /* Not a recursive common table expression. */
drheb04de32013-05-10 15:16:30 +00003764 ){
3765 /* Generate auto-index WhereLoops */
drheb04de32013-05-10 15:16:30 +00003766 WhereTerm *pTerm;
3767 WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
3768 for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
drh79a13bf2013-05-31 20:28:28 +00003769 if( pTerm->prereqRight & pNew->maskSelf ) continue;
drheb04de32013-05-10 15:16:30 +00003770 if( termCanDriveIndex(pTerm, pSrc, 0) ){
3771 pNew->u.btree.nEq = 1;
drhc8bbce12014-10-21 01:05:09 +00003772 pNew->nSkip = 0;
drhef866372013-05-22 20:49:02 +00003773 pNew->u.btree.pIndex = 0;
drh4efc9292013-06-06 23:02:03 +00003774 pNew->nLTerm = 1;
3775 pNew->aLTerm[0] = pTerm;
drhe1e2e9a2013-06-13 15:16:53 +00003776 /* TUNING: One-time cost for computing the automatic index is
drh7e074332014-09-22 14:30:51 +00003777 ** estimated to be X*N*log2(N) where N is the number of rows in
3778 ** the table being indexed and where X is 7 (LogEst=28) for normal
3779 ** tables or 1.375 (LogEst=4) for views and subqueries. The value
3780 ** of X is smaller for views and subqueries so that the query planner
3781 ** will be more aggressive about generating automatic indexes for
3782 ** those objects, since there is no opportunity to add schema
3783 ** indexes on subqueries and views. */
3784 pNew->rSetup = rLogSize + rSize + 4;
3785 if( pTab->pSelect==0 && (pTab->tabFlags & TF_Ephemeral)==0 ){
3786 pNew->rSetup += 24;
3787 }
drhdbd94862014-07-23 23:57:42 +00003788 ApplyCostMultiplier(pNew->rSetup, pTab->costMult);
drh986b3872013-06-28 21:12:20 +00003789 /* TUNING: Each index lookup yields 20 rows in the table. This
3790 ** is more than the usual guess of 10 rows, since we have no way
peter.d.reid60ec9142014-09-06 16:39:46 +00003791 ** of knowing how selective the index will ultimately be. It would
drh986b3872013-06-28 21:12:20 +00003792 ** not be unreasonable to make this value much larger. */
drhbf539c42013-10-05 18:16:02 +00003793 pNew->nOut = 43; assert( 43==sqlite3LogEst(20) );
drhb50596d2013-10-08 20:42:41 +00003794 pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut);
drh986b3872013-06-28 21:12:20 +00003795 pNew->wsFlags = WHERE_AUTO_INDEX;
drheb04de32013-05-10 15:16:30 +00003796 pNew->prereq = mExtra | pTerm->prereqRight;
drhcf8fa7a2013-05-10 20:26:22 +00003797 rc = whereLoopInsert(pBuilder, pNew);
drheb04de32013-05-10 15:16:30 +00003798 }
3799 }
3800 }
drhfeb56e02013-08-23 17:33:46 +00003801#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
drh1c8148f2013-05-04 20:25:23 +00003802
3803 /* Loop over all indices
3804 */
drh23f98da2013-05-21 15:52:07 +00003805 for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){
drh4bd5f732013-07-31 23:22:39 +00003806 if( pProbe->pPartIdxWhere!=0
dan08291692014-08-27 17:37:20 +00003807 && !whereUsablePartialIndex(pSrc->iCursor, pWC, pProbe->pPartIdxWhere) ){
3808 testcase( pNew->iTab!=pSrc->iCursor ); /* See ticket [98d973b8f5] */
drh4bd5f732013-07-31 23:22:39 +00003809 continue; /* Partial index inappropriate for this query */
3810 }
dan7de2a1f2014-04-28 20:11:20 +00003811 rSize = pProbe->aiRowLogEst[0];
drh5346e952013-05-08 14:14:26 +00003812 pNew->u.btree.nEq = 0;
drhc8bbce12014-10-21 01:05:09 +00003813 pNew->nSkip = 0;
drh4efc9292013-06-06 23:02:03 +00003814 pNew->nLTerm = 0;
drh23f98da2013-05-21 15:52:07 +00003815 pNew->iSortIdx = 0;
drhb8a8e8a2013-06-10 19:12:39 +00003816 pNew->rSetup = 0;
drh23f98da2013-05-21 15:52:07 +00003817 pNew->prereq = mExtra;
drh74f91d42013-06-19 18:01:44 +00003818 pNew->nOut = rSize;
drh23f98da2013-05-21 15:52:07 +00003819 pNew->u.btree.pIndex = pProbe;
3820 b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
drh53cfbe92013-06-13 17:28:22 +00003821 /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
3822 assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
drh43fe25f2013-05-07 23:06:23 +00003823 if( pProbe->tnum<=0 ){
3824 /* Integer primary key index */
3825 pNew->wsFlags = WHERE_IPK;
drh23f98da2013-05-21 15:52:07 +00003826
3827 /* Full table scan */
drhd044d202013-05-31 12:43:55 +00003828 pNew->iSortIdx = b ? iSortIdx : 0;
danaa9933c2014-04-24 20:04:49 +00003829 /* TUNING: Cost of full table scan is (N*3.0). */
3830 pNew->rRun = rSize + 16;
drhdbd94862014-07-23 23:57:42 +00003831 ApplyCostMultiplier(pNew->rRun, pTab->costMult);
drhd8b77e22014-09-06 01:35:57 +00003832 whereLoopOutputAdjust(pWC, pNew, rSize);
drh23f98da2013-05-21 15:52:07 +00003833 rc = whereLoopInsert(pBuilder, pNew);
drhcca9f3d2013-09-06 15:23:29 +00003834 pNew->nOut = rSize;
drh23f98da2013-05-21 15:52:07 +00003835 if( rc ) break;
drh43fe25f2013-05-07 23:06:23 +00003836 }else{
drhec95c442013-10-23 01:57:32 +00003837 Bitmask m;
3838 if( pProbe->isCovering ){
3839 pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
3840 m = 0;
3841 }else{
3842 m = pSrc->colUsed & ~columnsInIndex(pProbe);
3843 pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
3844 }
drh1c8148f2013-05-04 20:25:23 +00003845
drh23f98da2013-05-21 15:52:07 +00003846 /* Full scan via index */
drh53cfbe92013-06-13 17:28:22 +00003847 if( b
drh702ba9f2013-11-07 21:25:13 +00003848 || !HasRowid(pTab)
drh53cfbe92013-06-13 17:28:22 +00003849 || ( m==0
3850 && pProbe->bUnordered==0
drh702ba9f2013-11-07 21:25:13 +00003851 && (pProbe->szIdxRow<pTab->szTabRow)
drh53cfbe92013-06-13 17:28:22 +00003852 && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
3853 && sqlite3GlobalConfig.bUseCis
3854 && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
3855 )
drhe3b7c922013-06-03 19:17:40 +00003856 ){
drh23f98da2013-05-21 15:52:07 +00003857 pNew->iSortIdx = b ? iSortIdx : 0;
danaa9933c2014-04-24 20:04:49 +00003858
3859 /* The cost of visiting the index rows is N*K, where K is
3860 ** between 1.1 and 3.0, depending on the relative sizes of the
3861 ** index and table rows. If this is a non-covering index scan,
3862 ** also add the cost of visiting table rows (N*3.0). */
3863 pNew->rRun = rSize + 1 + (15*pProbe->szIdxRow)/pTab->szTabRow;
3864 if( m!=0 ){
3865 pNew->rRun = sqlite3LogEstAdd(pNew->rRun, rSize+16);
drhe1e2e9a2013-06-13 15:16:53 +00003866 }
drhdbd94862014-07-23 23:57:42 +00003867 ApplyCostMultiplier(pNew->rRun, pTab->costMult);
drhd8b77e22014-09-06 01:35:57 +00003868 whereLoopOutputAdjust(pWC, pNew, rSize);
drh23f98da2013-05-21 15:52:07 +00003869 rc = whereLoopInsert(pBuilder, pNew);
drhcca9f3d2013-09-06 15:23:29 +00003870 pNew->nOut = rSize;
drh23f98da2013-05-21 15:52:07 +00003871 if( rc ) break;
3872 }
3873 }
dan7a419232013-08-06 20:01:43 +00003874
drhb8a8e8a2013-06-10 19:12:39 +00003875 rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
drh1435a9a2013-08-27 23:15:44 +00003876#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
dan87cd9322013-08-07 15:52:41 +00003877 sqlite3Stat4ProbeFree(pBuilder->pRec);
3878 pBuilder->nRecValid = 0;
3879 pBuilder->pRec = 0;
danddc2d6e2013-08-06 20:15:06 +00003880#endif
drh1c8148f2013-05-04 20:25:23 +00003881
3882 /* If there was an INDEXED BY clause, then only that one index is
3883 ** considered. */
3884 if( pSrc->pIndex ) break;
3885 }
drh5346e952013-05-08 14:14:26 +00003886 return rc;
drhf1b5f5b2013-05-02 00:15:01 +00003887}
3888
drh8636e9c2013-06-11 01:50:08 +00003889#ifndef SQLITE_OMIT_VIRTUALTABLE
drhf1b5f5b2013-05-02 00:15:01 +00003890/*
drh0823c892013-05-11 00:06:23 +00003891** Add all WhereLoop objects for a table of the join identified by
3892** pBuilder->pNew->iTab. That table is guaranteed to be a virtual table.
drhf1b5f5b2013-05-02 00:15:01 +00003893*/
drh5346e952013-05-08 14:14:26 +00003894static int whereLoopAddVirtual(
danff4b23b2013-11-12 12:17:16 +00003895 WhereLoopBuilder *pBuilder, /* WHERE clause information */
3896 Bitmask mExtra
drhf1b5f5b2013-05-02 00:15:01 +00003897){
drh70d18342013-06-06 19:16:33 +00003898 WhereInfo *pWInfo; /* WHERE analysis context */
drh5346e952013-05-08 14:14:26 +00003899 Parse *pParse; /* The parsing context */
3900 WhereClause *pWC; /* The WHERE clause */
3901 struct SrcList_item *pSrc; /* The FROM clause term to search */
3902 Table *pTab;
3903 sqlite3 *db;
3904 sqlite3_index_info *pIdxInfo;
3905 struct sqlite3_index_constraint *pIdxCons;
3906 struct sqlite3_index_constraint_usage *pUsage;
3907 WhereTerm *pTerm;
3908 int i, j;
3909 int iTerm, mxTerm;
drh4efc9292013-06-06 23:02:03 +00003910 int nConstraint;
drh5346e952013-05-08 14:14:26 +00003911 int seenIn = 0; /* True if an IN operator is seen */
3912 int seenVar = 0; /* True if a non-constant constraint is seen */
3913 int iPhase; /* 0: const w/o IN, 1: const, 2: no IN, 2: IN */
3914 WhereLoop *pNew;
drh5346e952013-05-08 14:14:26 +00003915 int rc = SQLITE_OK;
3916
drh70d18342013-06-06 19:16:33 +00003917 pWInfo = pBuilder->pWInfo;
3918 pParse = pWInfo->pParse;
drh5346e952013-05-08 14:14:26 +00003919 db = pParse->db;
3920 pWC = pBuilder->pWC;
drh5346e952013-05-08 14:14:26 +00003921 pNew = pBuilder->pNew;
drh70d18342013-06-06 19:16:33 +00003922 pSrc = &pWInfo->pTabList->a[pNew->iTab];
drhb2a90f02013-05-10 03:30:49 +00003923 pTab = pSrc->pTab;
drh0823c892013-05-11 00:06:23 +00003924 assert( IsVirtual(pTab) );
drhb2a90f02013-05-10 03:30:49 +00003925 pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pBuilder->pOrderBy);
drh5346e952013-05-08 14:14:26 +00003926 if( pIdxInfo==0 ) return SQLITE_NOMEM;
drh5346e952013-05-08 14:14:26 +00003927 pNew->prereq = 0;
drh5346e952013-05-08 14:14:26 +00003928 pNew->rSetup = 0;
3929 pNew->wsFlags = WHERE_VIRTUALTABLE;
drh4efc9292013-06-06 23:02:03 +00003930 pNew->nLTerm = 0;
drh5346e952013-05-08 14:14:26 +00003931 pNew->u.vtab.needFree = 0;
3932 pUsage = pIdxInfo->aConstraintUsage;
drh4efc9292013-06-06 23:02:03 +00003933 nConstraint = pIdxInfo->nConstraint;
drh7963b0e2013-06-17 21:37:40 +00003934 if( whereLoopResize(db, pNew, nConstraint) ){
3935 sqlite3DbFree(db, pIdxInfo);
3936 return SQLITE_NOMEM;
3937 }
drh5346e952013-05-08 14:14:26 +00003938
drh0823c892013-05-11 00:06:23 +00003939 for(iPhase=0; iPhase<=3; iPhase++){
drh5346e952013-05-08 14:14:26 +00003940 if( !seenIn && (iPhase&1)!=0 ){
3941 iPhase++;
3942 if( iPhase>3 ) break;
3943 }
3944 if( !seenVar && iPhase>1 ) break;
3945 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
3946 for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
3947 j = pIdxCons->iTermOffset;
3948 pTerm = &pWC->a[j];
3949 switch( iPhase ){
3950 case 0: /* Constants without IN operator */
3951 pIdxCons->usable = 0;
3952 if( (pTerm->eOperator & WO_IN)!=0 ){
3953 seenIn = 1;
drh7963b0e2013-06-17 21:37:40 +00003954 }
3955 if( pTerm->prereqRight!=0 ){
drh5346e952013-05-08 14:14:26 +00003956 seenVar = 1;
drh7963b0e2013-06-17 21:37:40 +00003957 }else if( (pTerm->eOperator & WO_IN)==0 ){
drh5346e952013-05-08 14:14:26 +00003958 pIdxCons->usable = 1;
3959 }
3960 break;
3961 case 1: /* Constants with IN operators */
3962 assert( seenIn );
3963 pIdxCons->usable = (pTerm->prereqRight==0);
3964 break;
3965 case 2: /* Variables without IN */
3966 assert( seenVar );
3967 pIdxCons->usable = (pTerm->eOperator & WO_IN)==0;
3968 break;
3969 default: /* Variables with IN */
3970 assert( seenVar && seenIn );
3971 pIdxCons->usable = 1;
3972 break;
3973 }
3974 }
3975 memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
3976 if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
3977 pIdxInfo->idxStr = 0;
3978 pIdxInfo->idxNum = 0;
3979 pIdxInfo->needToFreeIdxStr = 0;
3980 pIdxInfo->orderByConsumed = 0;
drh8636e9c2013-06-11 01:50:08 +00003981 pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
dana9f58152013-11-11 19:01:33 +00003982 pIdxInfo->estimatedRows = 25;
drh5346e952013-05-08 14:14:26 +00003983 rc = vtabBestIndex(pParse, pTab, pIdxInfo);
3984 if( rc ) goto whereLoopAddVtab_exit;
3985 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
danff4b23b2013-11-12 12:17:16 +00003986 pNew->prereq = mExtra;
drhc718f1c2013-05-08 20:05:58 +00003987 mxTerm = -1;
drh4efc9292013-06-06 23:02:03 +00003988 assert( pNew->nLSlot>=nConstraint );
3989 for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
drh3bd26f02013-05-24 14:52:03 +00003990 pNew->u.vtab.omitMask = 0;
drh4efc9292013-06-06 23:02:03 +00003991 for(i=0; i<nConstraint; i++, pIdxCons++){
drh5346e952013-05-08 14:14:26 +00003992 if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
3993 j = pIdxCons->iTermOffset;
drh4efc9292013-06-06 23:02:03 +00003994 if( iTerm>=nConstraint
drh5346e952013-05-08 14:14:26 +00003995 || j<0
3996 || j>=pWC->nTerm
drh4efc9292013-06-06 23:02:03 +00003997 || pNew->aLTerm[iTerm]!=0
drh5346e952013-05-08 14:14:26 +00003998 ){
3999 rc = SQLITE_ERROR;
4000 sqlite3ErrorMsg(pParse, "%s.xBestIndex() malfunction", pTab->zName);
4001 goto whereLoopAddVtab_exit;
4002 }
drh7963b0e2013-06-17 21:37:40 +00004003 testcase( iTerm==nConstraint-1 );
4004 testcase( j==0 );
4005 testcase( j==pWC->nTerm-1 );
drh5346e952013-05-08 14:14:26 +00004006 pTerm = &pWC->a[j];
4007 pNew->prereq |= pTerm->prereqRight;
drh4efc9292013-06-06 23:02:03 +00004008 assert( iTerm<pNew->nLSlot );
4009 pNew->aLTerm[iTerm] = pTerm;
drh5346e952013-05-08 14:14:26 +00004010 if( iTerm>mxTerm ) mxTerm = iTerm;
drh7963b0e2013-06-17 21:37:40 +00004011 testcase( iTerm==15 );
4012 testcase( iTerm==16 );
drh52986302013-06-03 16:03:16 +00004013 if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm;
drh5346e952013-05-08 14:14:26 +00004014 if( (pTerm->eOperator & WO_IN)!=0 ){
4015 if( pUsage[i].omit==0 ){
4016 /* Do not attempt to use an IN constraint if the virtual table
4017 ** says that the equivalent EQ constraint cannot be safely omitted.
4018 ** If we do attempt to use such a constraint, some rows might be
4019 ** repeated in the output. */
4020 break;
4021 }
4022 /* A virtual table that is constrained by an IN clause may not
4023 ** consume the ORDER BY clause because (1) the order of IN terms
4024 ** is not necessarily related to the order of output terms and
4025 ** (2) Multiple outputs from a single IN value will not merge
4026 ** together. */
4027 pIdxInfo->orderByConsumed = 0;
4028 }
4029 }
4030 }
drh4efc9292013-06-06 23:02:03 +00004031 if( i>=nConstraint ){
4032 pNew->nLTerm = mxTerm+1;
4033 assert( pNew->nLTerm<=pNew->nLSlot );
drh5346e952013-05-08 14:14:26 +00004034 pNew->u.vtab.idxNum = pIdxInfo->idxNum;
4035 pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
4036 pIdxInfo->needToFreeIdxStr = 0;
4037 pNew->u.vtab.idxStr = pIdxInfo->idxStr;
drh0401ace2014-03-18 15:30:27 +00004038 pNew->u.vtab.isOrdered = (i8)(pIdxInfo->orderByConsumed ?
4039 pIdxInfo->nOrderBy : 0);
drhb8a8e8a2013-06-10 19:12:39 +00004040 pNew->rSetup = 0;
drhb50596d2013-10-08 20:42:41 +00004041 pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost);
dana9f58152013-11-11 19:01:33 +00004042 pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows);
drhcf8fa7a2013-05-10 20:26:22 +00004043 whereLoopInsert(pBuilder, pNew);
drh5346e952013-05-08 14:14:26 +00004044 if( pNew->u.vtab.needFree ){
4045 sqlite3_free(pNew->u.vtab.idxStr);
4046 pNew->u.vtab.needFree = 0;
4047 }
4048 }
4049 }
4050
4051whereLoopAddVtab_exit:
4052 if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
4053 sqlite3DbFree(db, pIdxInfo);
4054 return rc;
drhf1b5f5b2013-05-02 00:15:01 +00004055}
drh8636e9c2013-06-11 01:50:08 +00004056#endif /* SQLITE_OMIT_VIRTUALTABLE */
drhf1b5f5b2013-05-02 00:15:01 +00004057
4058/*
drhcf8fa7a2013-05-10 20:26:22 +00004059** Add WhereLoop entries to handle OR terms. This works for either
4060** btrees or virtual tables.
4061*/
4062static int whereLoopAddOr(WhereLoopBuilder *pBuilder, Bitmask mExtra){
drh70d18342013-06-06 19:16:33 +00004063 WhereInfo *pWInfo = pBuilder->pWInfo;
drhcf8fa7a2013-05-10 20:26:22 +00004064 WhereClause *pWC;
4065 WhereLoop *pNew;
4066 WhereTerm *pTerm, *pWCEnd;
4067 int rc = SQLITE_OK;
4068 int iCur;
4069 WhereClause tempWC;
4070 WhereLoopBuilder sSubBuild;
dan5da73e12014-04-30 18:11:55 +00004071 WhereOrSet sSum, sCur;
drhcf8fa7a2013-05-10 20:26:22 +00004072 struct SrcList_item *pItem;
4073
drhcf8fa7a2013-05-10 20:26:22 +00004074 pWC = pBuilder->pWC;
drhcf8fa7a2013-05-10 20:26:22 +00004075 pWCEnd = pWC->a + pWC->nTerm;
4076 pNew = pBuilder->pNew;
drh77dfd5b2013-08-19 11:15:48 +00004077 memset(&sSum, 0, sizeof(sSum));
drh186ad8c2013-10-08 18:40:37 +00004078 pItem = pWInfo->pTabList->a + pNew->iTab;
4079 iCur = pItem->iCursor;
drhcf8fa7a2013-05-10 20:26:22 +00004080
4081 for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
4082 if( (pTerm->eOperator & WO_OR)!=0
4083 && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
4084 ){
4085 WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
4086 WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
4087 WhereTerm *pOrTerm;
drhaa32e3c2013-07-16 21:31:23 +00004088 int once = 1;
4089 int i, j;
drh783dece2013-06-05 17:53:43 +00004090
drh783dece2013-06-05 17:53:43 +00004091 sSubBuild = *pBuilder;
4092 sSubBuild.pOrderBy = 0;
drhaa32e3c2013-07-16 21:31:23 +00004093 sSubBuild.pOrSet = &sCur;
drhcf8fa7a2013-05-10 20:26:22 +00004094
drh0a99ba32014-09-30 17:03:35 +00004095 WHERETRACE(0x200, ("Begin processing OR-clause %p\n", pTerm));
drhc7f0d222013-06-19 03:27:12 +00004096 for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
drh783dece2013-06-05 17:53:43 +00004097 if( (pOrTerm->eOperator & WO_AND)!=0 ){
drhcf8fa7a2013-05-10 20:26:22 +00004098 sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
4099 }else if( pOrTerm->leftCursor==iCur ){
drh70d18342013-06-06 19:16:33 +00004100 tempWC.pWInfo = pWC->pWInfo;
drh783dece2013-06-05 17:53:43 +00004101 tempWC.pOuter = pWC;
4102 tempWC.op = TK_AND;
drh783dece2013-06-05 17:53:43 +00004103 tempWC.nTerm = 1;
drhcf8fa7a2013-05-10 20:26:22 +00004104 tempWC.a = pOrTerm;
4105 sSubBuild.pWC = &tempWC;
4106 }else{
4107 continue;
4108 }
drhaa32e3c2013-07-16 21:31:23 +00004109 sCur.n = 0;
drh52651492014-09-30 14:14:19 +00004110#ifdef WHERETRACE_ENABLED
drh0a99ba32014-09-30 17:03:35 +00004111 WHERETRACE(0x200, ("OR-term %d of %p has %d subterms:\n",
4112 (int)(pOrTerm-pOrWC->a), pTerm, sSubBuild.pWC->nTerm));
4113 if( sqlite3WhereTrace & 0x400 ){
4114 for(i=0; i<sSubBuild.pWC->nTerm; i++){
4115 whereTermPrint(&sSubBuild.pWC->a[i], i);
4116 }
drh52651492014-09-30 14:14:19 +00004117 }
4118#endif
drh8636e9c2013-06-11 01:50:08 +00004119#ifndef SQLITE_OMIT_VIRTUALTABLE
drhcf8fa7a2013-05-10 20:26:22 +00004120 if( IsVirtual(pItem->pTab) ){
danff4b23b2013-11-12 12:17:16 +00004121 rc = whereLoopAddVirtual(&sSubBuild, mExtra);
drh8636e9c2013-06-11 01:50:08 +00004122 }else
4123#endif
4124 {
drhcf8fa7a2013-05-10 20:26:22 +00004125 rc = whereLoopAddBtree(&sSubBuild, mExtra);
4126 }
drh36be4c42014-09-30 17:31:23 +00004127 if( rc==SQLITE_OK ){
4128 rc = whereLoopAddOr(&sSubBuild, mExtra);
4129 }
drhaa32e3c2013-07-16 21:31:23 +00004130 assert( rc==SQLITE_OK || sCur.n==0 );
4131 if( sCur.n==0 ){
4132 sSum.n = 0;
4133 break;
4134 }else if( once ){
4135 whereOrMove(&sSum, &sCur);
4136 once = 0;
4137 }else{
dan5da73e12014-04-30 18:11:55 +00004138 WhereOrSet sPrev;
drhaa32e3c2013-07-16 21:31:23 +00004139 whereOrMove(&sPrev, &sSum);
4140 sSum.n = 0;
4141 for(i=0; i<sPrev.n; i++){
4142 for(j=0; j<sCur.n; j++){
4143 whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,
drhbf539c42013-10-05 18:16:02 +00004144 sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
4145 sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
drhaa32e3c2013-07-16 21:31:23 +00004146 }
4147 }
4148 }
drhcf8fa7a2013-05-10 20:26:22 +00004149 }
drhaa32e3c2013-07-16 21:31:23 +00004150 pNew->nLTerm = 1;
4151 pNew->aLTerm[0] = pTerm;
4152 pNew->wsFlags = WHERE_MULTI_OR;
4153 pNew->rSetup = 0;
4154 pNew->iSortIdx = 0;
4155 memset(&pNew->u, 0, sizeof(pNew->u));
4156 for(i=0; rc==SQLITE_OK && i<sSum.n; i++){
dan5da73e12014-04-30 18:11:55 +00004157 /* TUNING: Currently sSum.a[i].rRun is set to the sum of the costs
4158 ** of all sub-scans required by the OR-scan. However, due to rounding
4159 ** errors, it may be that the cost of the OR-scan is equal to its
4160 ** most expensive sub-scan. Add the smallest possible penalty
4161 ** (equivalent to multiplying the cost by 1.07) to ensure that
4162 ** this does not happen. Otherwise, for WHERE clauses such as the
4163 ** following where there is an index on "y":
4164 **
4165 ** WHERE likelihood(x=?, 0.99) OR y=?
4166 **
4167 ** the planner may elect to "OR" together a full-table scan and an
4168 ** index lookup. And other similarly odd results. */
4169 pNew->rRun = sSum.a[i].rRun + 1;
drhaa32e3c2013-07-16 21:31:23 +00004170 pNew->nOut = sSum.a[i].nOut;
4171 pNew->prereq = sSum.a[i].prereq;
drhfd5874d2013-06-12 14:52:39 +00004172 rc = whereLoopInsert(pBuilder, pNew);
4173 }
drh0a99ba32014-09-30 17:03:35 +00004174 WHERETRACE(0x200, ("End processing OR-clause %p\n", pTerm));
drhcf8fa7a2013-05-10 20:26:22 +00004175 }
4176 }
4177 return rc;
4178}
4179
4180/*
drhf1b5f5b2013-05-02 00:15:01 +00004181** Add all WhereLoop objects for all tables
4182*/
drh5346e952013-05-08 14:14:26 +00004183static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
drh70d18342013-06-06 19:16:33 +00004184 WhereInfo *pWInfo = pBuilder->pWInfo;
drhf1b5f5b2013-05-02 00:15:01 +00004185 Bitmask mExtra = 0;
4186 Bitmask mPrior = 0;
4187 int iTab;
drh70d18342013-06-06 19:16:33 +00004188 SrcList *pTabList = pWInfo->pTabList;
drhf1b5f5b2013-05-02 00:15:01 +00004189 struct SrcList_item *pItem;
drh70d18342013-06-06 19:16:33 +00004190 sqlite3 *db = pWInfo->pParse->db;
4191 int nTabList = pWInfo->nLevel;
drh5346e952013-05-08 14:14:26 +00004192 int rc = SQLITE_OK;
drhc63367e2013-06-10 20:46:50 +00004193 u8 priorJoinType = 0;
drhb8a8e8a2013-06-10 19:12:39 +00004194 WhereLoop *pNew;
drhf1b5f5b2013-05-02 00:15:01 +00004195
4196 /* Loop over the tables in the join, from left to right */
drhb8a8e8a2013-06-10 19:12:39 +00004197 pNew = pBuilder->pNew;
drha2014152013-06-07 00:29:23 +00004198 whereLoopInit(pNew);
drha18f3d22013-05-08 03:05:41 +00004199 for(iTab=0, pItem=pTabList->a; iTab<nTabList; iTab++, pItem++){
drhb2a90f02013-05-10 03:30:49 +00004200 pNew->iTab = iTab;
drh6f82e852015-06-06 20:12:09 +00004201 pNew->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, pItem->iCursor);
drhc63367e2013-06-10 20:46:50 +00004202 if( ((pItem->jointype|priorJoinType) & (JT_LEFT|JT_CROSS))!=0 ){
drhf1b5f5b2013-05-02 00:15:01 +00004203 mExtra = mPrior;
4204 }
drhc63367e2013-06-10 20:46:50 +00004205 priorJoinType = pItem->jointype;
drhb2a90f02013-05-10 03:30:49 +00004206 if( IsVirtual(pItem->pTab) ){
danff4b23b2013-11-12 12:17:16 +00004207 rc = whereLoopAddVirtual(pBuilder, mExtra);
drhb2a90f02013-05-10 03:30:49 +00004208 }else{
4209 rc = whereLoopAddBtree(pBuilder, mExtra);
4210 }
drhb2a90f02013-05-10 03:30:49 +00004211 if( rc==SQLITE_OK ){
4212 rc = whereLoopAddOr(pBuilder, mExtra);
4213 }
drhb2a90f02013-05-10 03:30:49 +00004214 mPrior |= pNew->maskSelf;
drh5346e952013-05-08 14:14:26 +00004215 if( rc || db->mallocFailed ) break;
drhf1b5f5b2013-05-02 00:15:01 +00004216 }
drha2014152013-06-07 00:29:23 +00004217 whereLoopClear(db, pNew);
drh5346e952013-05-08 14:14:26 +00004218 return rc;
drhf1b5f5b2013-05-02 00:15:01 +00004219}
4220
drha18f3d22013-05-08 03:05:41 +00004221/*
drh7699d1c2013-06-04 12:42:29 +00004222** Examine a WherePath (with the addition of the extra WhereLoop of the 5th
drh319f6772013-05-14 15:31:07 +00004223** parameters) to see if it outputs rows in the requested ORDER BY
drh0401ace2014-03-18 15:30:27 +00004224** (or GROUP BY) without requiring a separate sort operation. Return N:
drh319f6772013-05-14 15:31:07 +00004225**
drh0401ace2014-03-18 15:30:27 +00004226** N>0: N terms of the ORDER BY clause are satisfied
4227** N==0: No terms of the ORDER BY clause are satisfied
4228** N<0: Unknown yet how many terms of ORDER BY might be satisfied.
drh319f6772013-05-14 15:31:07 +00004229**
drh94433422013-07-01 11:05:50 +00004230** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
4231** strict. With GROUP BY and DISTINCT the only requirement is that
4232** equivalent rows appear immediately adjacent to one another. GROUP BY
dan374cd782014-04-21 13:21:56 +00004233** and DISTINCT do not require rows to appear in any particular order as long
peter.d.reid60ec9142014-09-06 16:39:46 +00004234** as equivalent rows are grouped together. Thus for GROUP BY and DISTINCT
drh94433422013-07-01 11:05:50 +00004235** the pOrderBy terms can be matched in any order. With ORDER BY, the
4236** pOrderBy terms must be matched in strict left-to-right order.
drh6b7157b2013-05-10 02:00:35 +00004237*/
drh0401ace2014-03-18 15:30:27 +00004238static i8 wherePathSatisfiesOrderBy(
drh6b7157b2013-05-10 02:00:35 +00004239 WhereInfo *pWInfo, /* The WHERE clause */
drh4f402f22013-06-11 18:59:38 +00004240 ExprList *pOrderBy, /* ORDER BY or GROUP BY or DISTINCT clause to check */
drh6b7157b2013-05-10 02:00:35 +00004241 WherePath *pPath, /* The WherePath to check */
drh4f402f22013-06-11 18:59:38 +00004242 u16 wctrlFlags, /* Might contain WHERE_GROUPBY or WHERE_DISTINCTBY */
4243 u16 nLoop, /* Number of entries in pPath->aLoop[] */
drh319f6772013-05-14 15:31:07 +00004244 WhereLoop *pLast, /* Add this WhereLoop to the end of pPath->aLoop[] */
drh4f402f22013-06-11 18:59:38 +00004245 Bitmask *pRevMask /* OUT: Mask of WhereLoops to run in reverse order */
drh6b7157b2013-05-10 02:00:35 +00004246){
drh88da6442013-05-27 17:59:37 +00004247 u8 revSet; /* True if rev is known */
4248 u8 rev; /* Composite sort order */
4249 u8 revIdx; /* Index sort order */
drhe353ee32013-06-04 23:40:53 +00004250 u8 isOrderDistinct; /* All prior WhereLoops are order-distinct */
4251 u8 distinctColumns; /* True if the loop has UNIQUE NOT NULL columns */
4252 u8 isMatch; /* iColumn matches a term of the ORDER BY clause */
drh416846a2013-11-06 12:56:04 +00004253 u16 nKeyCol; /* Number of key columns in pIndex */
4254 u16 nColumn; /* Total number of ordered columns in the index */
drh7699d1c2013-06-04 12:42:29 +00004255 u16 nOrderBy; /* Number terms in the ORDER BY clause */
4256 int iLoop; /* Index of WhereLoop in pPath being processed */
4257 int i, j; /* Loop counters */
4258 int iCur; /* Cursor number for current WhereLoop */
4259 int iColumn; /* A column number within table iCur */
drhe8ae5832013-06-19 13:32:46 +00004260 WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
drh7699d1c2013-06-04 12:42:29 +00004261 WhereTerm *pTerm; /* A single term of the WHERE clause */
4262 Expr *pOBExpr; /* An expression from the ORDER BY clause */
4263 CollSeq *pColl; /* COLLATE function from an ORDER BY clause term */
4264 Index *pIndex; /* The index associated with pLoop */
4265 sqlite3 *db = pWInfo->pParse->db; /* Database connection */
4266 Bitmask obSat = 0; /* Mask of ORDER BY terms satisfied so far */
4267 Bitmask obDone; /* Mask of all ORDER BY terms */
drhe353ee32013-06-04 23:40:53 +00004268 Bitmask orderDistinctMask; /* Mask of all well-ordered loops */
drhb8916be2013-06-14 02:51:48 +00004269 Bitmask ready; /* Mask of inner loops */
drh319f6772013-05-14 15:31:07 +00004270
4271 /*
drh7699d1c2013-06-04 12:42:29 +00004272 ** We say the WhereLoop is "one-row" if it generates no more than one
4273 ** row of output. A WhereLoop is one-row if all of the following are true:
drh319f6772013-05-14 15:31:07 +00004274 ** (a) All index columns match with WHERE_COLUMN_EQ.
4275 ** (b) The index is unique
drh7699d1c2013-06-04 12:42:29 +00004276 ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
4277 ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
drh319f6772013-05-14 15:31:07 +00004278 **
drhe353ee32013-06-04 23:40:53 +00004279 ** We say the WhereLoop is "order-distinct" if the set of columns from
4280 ** that WhereLoop that are in the ORDER BY clause are different for every
4281 ** row of the WhereLoop. Every one-row WhereLoop is automatically
4282 ** order-distinct. A WhereLoop that has no columns in the ORDER BY clause
4283 ** is not order-distinct. To be order-distinct is not quite the same as being
4284 ** UNIQUE since a UNIQUE column or index can have multiple rows that
4285 ** are NULL and NULL values are equivalent for the purpose of order-distinct.
4286 ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
4287 **
4288 ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
4289 ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
4290 ** automatically order-distinct.
drh319f6772013-05-14 15:31:07 +00004291 */
4292
4293 assert( pOrderBy!=0 );
drh7699d1c2013-06-04 12:42:29 +00004294 if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
drh319f6772013-05-14 15:31:07 +00004295
drh319f6772013-05-14 15:31:07 +00004296 nOrderBy = pOrderBy->nExpr;
drh7963b0e2013-06-17 21:37:40 +00004297 testcase( nOrderBy==BMS-1 );
drhe353ee32013-06-04 23:40:53 +00004298 if( nOrderBy>BMS-1 ) return 0; /* Cannot optimize overly large ORDER BYs */
4299 isOrderDistinct = 1;
drh7699d1c2013-06-04 12:42:29 +00004300 obDone = MASKBIT(nOrderBy)-1;
drhe353ee32013-06-04 23:40:53 +00004301 orderDistinctMask = 0;
drhb8916be2013-06-14 02:51:48 +00004302 ready = 0;
drhe353ee32013-06-04 23:40:53 +00004303 for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
drhb8916be2013-06-14 02:51:48 +00004304 if( iLoop>0 ) ready |= pLoop->maskSelf;
drh7699d1c2013-06-04 12:42:29 +00004305 pLoop = iLoop<nLoop ? pPath->aLoop[iLoop] : pLast;
drh9dfaf622014-04-25 14:42:17 +00004306 if( pLoop->wsFlags & WHERE_VIRTUALTABLE ){
4307 if( pLoop->u.vtab.isOrdered ) obSat = obDone;
4308 break;
4309 }
drh319f6772013-05-14 15:31:07 +00004310 iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
drhb8916be2013-06-14 02:51:48 +00004311
4312 /* Mark off any ORDER BY term X that is a column in the table of
4313 ** the current loop for which there is term in the WHERE
4314 ** clause of the form X IS NULL or X=? that reference only outer
4315 ** loops.
4316 */
4317 for(i=0; i<nOrderBy; i++){
4318 if( MASKBIT(i) & obSat ) continue;
4319 pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
4320 if( pOBExpr->op!=TK_COLUMN ) continue;
4321 if( pOBExpr->iTable!=iCur ) continue;
drh6f82e852015-06-06 20:12:09 +00004322 pTerm = sqlite3WhereFindTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
drhe8d0c612015-05-14 01:05:25 +00004323 ~ready, WO_EQ|WO_ISNULL|WO_IS, 0);
drhb8916be2013-06-14 02:51:48 +00004324 if( pTerm==0 ) continue;
drhe8d0c612015-05-14 01:05:25 +00004325 if( (pTerm->eOperator&(WO_EQ|WO_IS))!=0 && pOBExpr->iColumn>=0 ){
drhb8916be2013-06-14 02:51:48 +00004326 const char *z1, *z2;
4327 pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
4328 if( !pColl ) pColl = db->pDfltColl;
4329 z1 = pColl->zName;
4330 pColl = sqlite3ExprCollSeq(pWInfo->pParse, pTerm->pExpr);
4331 if( !pColl ) pColl = db->pDfltColl;
4332 z2 = pColl->zName;
4333 if( sqlite3StrICmp(z1, z2)!=0 ) continue;
drhe0cc3c22015-05-13 17:54:08 +00004334 testcase( pTerm->pExpr->op==TK_IS );
drhb8916be2013-06-14 02:51:48 +00004335 }
4336 obSat |= MASKBIT(i);
4337 }
4338
drh7699d1c2013-06-04 12:42:29 +00004339 if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
4340 if( pLoop->wsFlags & WHERE_IPK ){
4341 pIndex = 0;
drhbbbdc832013-10-22 18:01:40 +00004342 nKeyCol = 0;
drh416846a2013-11-06 12:56:04 +00004343 nColumn = 1;
drh7699d1c2013-06-04 12:42:29 +00004344 }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
drh1b0f0262013-05-30 22:27:09 +00004345 return 0;
drh7699d1c2013-06-04 12:42:29 +00004346 }else{
drhbbbdc832013-10-22 18:01:40 +00004347 nKeyCol = pIndex->nKeyCol;
drh416846a2013-11-06 12:56:04 +00004348 nColumn = pIndex->nColumn;
4349 assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) );
4350 assert( pIndex->aiColumn[nColumn-1]==(-1) || !HasRowid(pIndex->pTable));
drh5f1d1d92014-07-31 22:59:04 +00004351 isOrderDistinct = IsUniqueIndex(pIndex);
drh1b0f0262013-05-30 22:27:09 +00004352 }
drh7699d1c2013-06-04 12:42:29 +00004353
drh7699d1c2013-06-04 12:42:29 +00004354 /* Loop through all columns of the index and deal with the ones
4355 ** that are not constrained by == or IN.
4356 */
4357 rev = revSet = 0;
drhe353ee32013-06-04 23:40:53 +00004358 distinctColumns = 0;
drh416846a2013-11-06 12:56:04 +00004359 for(j=0; j<nColumn; j++){
drh7699d1c2013-06-04 12:42:29 +00004360 u8 bOnce; /* True to run the ORDER BY search loop */
4361
drhe353ee32013-06-04 23:40:53 +00004362 /* Skip over == and IS NULL terms */
drh7699d1c2013-06-04 12:42:29 +00004363 if( j<pLoop->u.btree.nEq
drhc8bbce12014-10-21 01:05:09 +00004364 && pLoop->nSkip==0
drhe8d0c612015-05-14 01:05:25 +00004365 && ((i = pLoop->aLTerm[j]->eOperator) & (WO_EQ|WO_ISNULL|WO_IS))!=0
drh7699d1c2013-06-04 12:42:29 +00004366 ){
drh7963b0e2013-06-17 21:37:40 +00004367 if( i & WO_ISNULL ){
4368 testcase( isOrderDistinct );
4369 isOrderDistinct = 0;
4370 }
drhe353ee32013-06-04 23:40:53 +00004371 continue;
drh7699d1c2013-06-04 12:42:29 +00004372 }
4373
drhe353ee32013-06-04 23:40:53 +00004374 /* Get the column number in the table (iColumn) and sort order
4375 ** (revIdx) for the j-th column of the index.
drh7699d1c2013-06-04 12:42:29 +00004376 */
drh416846a2013-11-06 12:56:04 +00004377 if( pIndex ){
drh7699d1c2013-06-04 12:42:29 +00004378 iColumn = pIndex->aiColumn[j];
4379 revIdx = pIndex->aSortOrder[j];
4380 if( iColumn==pIndex->pTable->iPKey ) iColumn = -1;
drhdc3cd4b2013-05-30 23:21:20 +00004381 }else{
drh7699d1c2013-06-04 12:42:29 +00004382 iColumn = -1;
4383 revIdx = 0;
drhdc3cd4b2013-05-30 23:21:20 +00004384 }
drh7699d1c2013-06-04 12:42:29 +00004385
4386 /* An unconstrained column that might be NULL means that this
drh416846a2013-11-06 12:56:04 +00004387 ** WhereLoop is not well-ordered
drh7699d1c2013-06-04 12:42:29 +00004388 */
drhe353ee32013-06-04 23:40:53 +00004389 if( isOrderDistinct
4390 && iColumn>=0
drh7699d1c2013-06-04 12:42:29 +00004391 && j>=pLoop->u.btree.nEq
4392 && pIndex->pTable->aCol[iColumn].notNull==0
4393 ){
drhe353ee32013-06-04 23:40:53 +00004394 isOrderDistinct = 0;
drh7699d1c2013-06-04 12:42:29 +00004395 }
4396
4397 /* Find the ORDER BY term that corresponds to the j-th column
dan374cd782014-04-21 13:21:56 +00004398 ** of the index and mark that ORDER BY term off
drh7699d1c2013-06-04 12:42:29 +00004399 */
4400 bOnce = 1;
drhe353ee32013-06-04 23:40:53 +00004401 isMatch = 0;
drh7699d1c2013-06-04 12:42:29 +00004402 for(i=0; bOnce && i<nOrderBy; i++){
4403 if( MASKBIT(i) & obSat ) continue;
4404 pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
drh93ec45d2013-06-17 18:20:48 +00004405 testcase( wctrlFlags & WHERE_GROUPBY );
4406 testcase( wctrlFlags & WHERE_DISTINCTBY );
drh4f402f22013-06-11 18:59:38 +00004407 if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
drhe353ee32013-06-04 23:40:53 +00004408 if( pOBExpr->op!=TK_COLUMN ) continue;
drh7699d1c2013-06-04 12:42:29 +00004409 if( pOBExpr->iTable!=iCur ) continue;
4410 if( pOBExpr->iColumn!=iColumn ) continue;
4411 if( iColumn>=0 ){
4412 pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
4413 if( !pColl ) pColl = db->pDfltColl;
4414 if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
4415 }
drhe353ee32013-06-04 23:40:53 +00004416 isMatch = 1;
drh7699d1c2013-06-04 12:42:29 +00004417 break;
4418 }
drh49290472014-10-11 02:12:58 +00004419 if( isMatch && (wctrlFlags & WHERE_GROUPBY)==0 ){
drh59b8f2e2014-03-22 00:27:14 +00004420 /* Make sure the sort order is compatible in an ORDER BY clause.
4421 ** Sort order is irrelevant for a GROUP BY clause. */
4422 if( revSet ){
4423 if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) isMatch = 0;
4424 }else{
4425 rev = revIdx ^ pOrderBy->a[i].sortOrder;
4426 if( rev ) *pRevMask |= MASKBIT(iLoop);
4427 revSet = 1;
4428 }
4429 }
drhe353ee32013-06-04 23:40:53 +00004430 if( isMatch ){
drh7963b0e2013-06-17 21:37:40 +00004431 if( iColumn<0 ){
4432 testcase( distinctColumns==0 );
4433 distinctColumns = 1;
4434 }
drh7699d1c2013-06-04 12:42:29 +00004435 obSat |= MASKBIT(i);
drh7699d1c2013-06-04 12:42:29 +00004436 }else{
4437 /* No match found */
drhbbbdc832013-10-22 18:01:40 +00004438 if( j==0 || j<nKeyCol ){
drh7963b0e2013-06-17 21:37:40 +00004439 testcase( isOrderDistinct!=0 );
4440 isOrderDistinct = 0;
4441 }
drh7699d1c2013-06-04 12:42:29 +00004442 break;
4443 }
4444 } /* end Loop over all index columns */
drh81186b42013-06-18 01:52:41 +00004445 if( distinctColumns ){
4446 testcase( isOrderDistinct==0 );
4447 isOrderDistinct = 1;
4448 }
drh7699d1c2013-06-04 12:42:29 +00004449 } /* end-if not one-row */
4450
4451 /* Mark off any other ORDER BY terms that reference pLoop */
drhe353ee32013-06-04 23:40:53 +00004452 if( isOrderDistinct ){
4453 orderDistinctMask |= pLoop->maskSelf;
drh7699d1c2013-06-04 12:42:29 +00004454 for(i=0; i<nOrderBy; i++){
4455 Expr *p;
drh434a9312014-02-26 02:26:09 +00004456 Bitmask mTerm;
drh7699d1c2013-06-04 12:42:29 +00004457 if( MASKBIT(i) & obSat ) continue;
4458 p = pOrderBy->a[i].pExpr;
drh434a9312014-02-26 02:26:09 +00004459 mTerm = exprTableUsage(&pWInfo->sMaskSet,p);
4460 if( mTerm==0 && !sqlite3ExprIsConstant(p) ) continue;
4461 if( (mTerm&~orderDistinctMask)==0 ){
drh7699d1c2013-06-04 12:42:29 +00004462 obSat |= MASKBIT(i);
4463 }
drh0afb4232013-05-31 13:36:32 +00004464 }
drh319f6772013-05-14 15:31:07 +00004465 }
drhb8916be2013-06-14 02:51:48 +00004466 } /* End the loop over all WhereLoops from outer-most down to inner-most */
drh36ed0342014-03-28 12:56:57 +00004467 if( obSat==obDone ) return (i8)nOrderBy;
drhd2de8612014-03-18 18:59:07 +00004468 if( !isOrderDistinct ){
4469 for(i=nOrderBy-1; i>0; i--){
4470 Bitmask m = MASKBIT(i) - 1;
4471 if( (obSat&m)==m ) return i;
4472 }
4473 return 0;
4474 }
drh319f6772013-05-14 15:31:07 +00004475 return -1;
drh6b7157b2013-05-10 02:00:35 +00004476}
4477
dan374cd782014-04-21 13:21:56 +00004478
4479/*
4480** If the WHERE_GROUPBY flag is set in the mask passed to sqlite3WhereBegin(),
4481** the planner assumes that the specified pOrderBy list is actually a GROUP
4482** BY clause - and so any order that groups rows as required satisfies the
4483** request.
4484**
4485** Normally, in this case it is not possible for the caller to determine
4486** whether or not the rows are really being delivered in sorted order, or
4487** just in some other order that provides the required grouping. However,
4488** if the WHERE_SORTBYGROUP flag is also passed to sqlite3WhereBegin(), then
4489** this function may be called on the returned WhereInfo object. It returns
4490** true if the rows really will be sorted in the specified order, or false
4491** otherwise.
4492**
4493** For example, assuming:
4494**
4495** CREATE INDEX i1 ON t1(x, Y);
4496**
4497** then
4498**
4499** SELECT * FROM t1 GROUP BY x,y ORDER BY x,y; -- IsSorted()==1
4500** SELECT * FROM t1 GROUP BY y,x ORDER BY y,x; -- IsSorted()==0
4501*/
4502int sqlite3WhereIsSorted(WhereInfo *pWInfo){
4503 assert( pWInfo->wctrlFlags & WHERE_GROUPBY );
4504 assert( pWInfo->wctrlFlags & WHERE_SORTBYGROUP );
4505 return pWInfo->sorted;
4506}
4507
drhd15cb172013-05-21 19:23:10 +00004508#ifdef WHERETRACE_ENABLED
4509/* For debugging use only: */
4510static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
4511 static char zName[65];
4512 int i;
4513 for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
4514 if( pLast ) zName[i++] = pLast->cId;
4515 zName[i] = 0;
4516 return zName;
4517}
4518#endif
4519
drh6b7157b2013-05-10 02:00:35 +00004520/*
dan50ae31e2014-08-08 16:52:28 +00004521** Return the cost of sorting nRow rows, assuming that the keys have
4522** nOrderby columns and that the first nSorted columns are already in
4523** order.
4524*/
4525static LogEst whereSortingCost(
4526 WhereInfo *pWInfo,
4527 LogEst nRow,
4528 int nOrderBy,
4529 int nSorted
4530){
4531 /* TUNING: Estimated cost of a full external sort, where N is
4532 ** the number of rows to sort is:
4533 **
4534 ** cost = (3.0 * N * log(N)).
4535 **
4536 ** Or, if the order-by clause has X terms but only the last Y
4537 ** terms are out of order, then block-sorting will reduce the
4538 ** sorting cost to:
4539 **
4540 ** cost = (3.0 * N * log(N)) * (Y/X)
4541 **
4542 ** The (Y/X) term is implemented using stack variable rScale
4543 ** below. */
4544 LogEst rScale, rSortCost;
4545 assert( nOrderBy>0 && 66==sqlite3LogEst(100) );
4546 rScale = sqlite3LogEst((nOrderBy-nSorted)*100/nOrderBy) - 66;
4547 rSortCost = nRow + estLog(nRow) + rScale + 16;
4548
4549 /* TUNING: The cost of implementing DISTINCT using a B-TREE is
4550 ** similar but with a larger constant of proportionality.
4551 ** Multiply by an additional factor of 3.0. */
4552 if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
4553 rSortCost += 16;
4554 }
4555
4556 return rSortCost;
4557}
4558
4559/*
dan51576f42013-07-02 10:06:15 +00004560** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
drha18f3d22013-05-08 03:05:41 +00004561** attempts to find the lowest cost path that visits each WhereLoop
4562** once. This path is then loaded into the pWInfo->a[].pWLoop fields.
4563**
drhc7f0d222013-06-19 03:27:12 +00004564** Assume that the total number of output rows that will need to be sorted
4565** will be nRowEst (in the 10*log2 representation). Or, ignore sorting
4566** costs if nRowEst==0.
4567**
drha18f3d22013-05-08 03:05:41 +00004568** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
4569** error occurs.
4570*/
drhbf539c42013-10-05 18:16:02 +00004571static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
drh783dece2013-06-05 17:53:43 +00004572 int mxChoice; /* Maximum number of simultaneous paths tracked */
drha18f3d22013-05-08 03:05:41 +00004573 int nLoop; /* Number of terms in the join */
drhe1e2e9a2013-06-13 15:16:53 +00004574 Parse *pParse; /* Parsing context */
drha18f3d22013-05-08 03:05:41 +00004575 sqlite3 *db; /* The database connection */
4576 int iLoop; /* Loop counter over the terms of the join */
4577 int ii, jj; /* Loop counters */
drhfde1e6b2013-09-06 17:45:42 +00004578 int mxI = 0; /* Index of next entry to replace */
drhd2de8612014-03-18 18:59:07 +00004579 int nOrderBy; /* Number of ORDER BY clause terms */
drhbf539c42013-10-05 18:16:02 +00004580 LogEst mxCost = 0; /* Maximum cost of a set of paths */
dan50ae31e2014-08-08 16:52:28 +00004581 LogEst mxUnsorted = 0; /* Maximum unsorted cost of a set of path */
drha18f3d22013-05-08 03:05:41 +00004582 int nTo, nFrom; /* Number of valid entries in aTo[] and aFrom[] */
4583 WherePath *aFrom; /* All nFrom paths at the previous level */
4584 WherePath *aTo; /* The nTo best paths at the current level */
4585 WherePath *pFrom; /* An element of aFrom[] that we are working on */
4586 WherePath *pTo; /* An element of aTo[] that we are working on */
4587 WhereLoop *pWLoop; /* One of the WhereLoop objects */
4588 WhereLoop **pX; /* Used to divy up the pSpace memory */
dan50ae31e2014-08-08 16:52:28 +00004589 LogEst *aSortCost = 0; /* Sorting and partial sorting costs */
drha18f3d22013-05-08 03:05:41 +00004590 char *pSpace; /* Temporary memory used by this routine */
dane2c27852014-08-08 17:25:33 +00004591 int nSpace; /* Bytes of space allocated at pSpace */
drha18f3d22013-05-08 03:05:41 +00004592
drhe1e2e9a2013-06-13 15:16:53 +00004593 pParse = pWInfo->pParse;
4594 db = pParse->db;
drha18f3d22013-05-08 03:05:41 +00004595 nLoop = pWInfo->nLevel;
drhe1e2e9a2013-06-13 15:16:53 +00004596 /* TUNING: For simple queries, only the best path is tracked.
4597 ** For 2-way joins, the 5 best paths are followed.
4598 ** For joins of 3 or more tables, track the 10 best paths */
drh2504c6c2014-06-02 11:26:33 +00004599 mxChoice = (nLoop<=1) ? 1 : (nLoop==2 ? 5 : 10);
drha18f3d22013-05-08 03:05:41 +00004600 assert( nLoop<=pWInfo->pTabList->nSrc );
drhddef5dc2014-08-07 16:50:00 +00004601 WHERETRACE(0x002, ("---- begin solver. (nRowEst=%d)\n", nRowEst));
drha18f3d22013-05-08 03:05:41 +00004602
dan50ae31e2014-08-08 16:52:28 +00004603 /* If nRowEst is zero and there is an ORDER BY clause, ignore it. In this
4604 ** case the purpose of this call is to estimate the number of rows returned
4605 ** by the overall query. Once this estimate has been obtained, the caller
4606 ** will invoke this function a second time, passing the estimate as the
4607 ** nRowEst parameter. */
4608 if( pWInfo->pOrderBy==0 || nRowEst==0 ){
4609 nOrderBy = 0;
4610 }else{
4611 nOrderBy = pWInfo->pOrderBy->nExpr;
4612 }
4613
4614 /* Allocate and initialize space for aTo, aFrom and aSortCost[] */
dane2c27852014-08-08 17:25:33 +00004615 nSpace = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
4616 nSpace += sizeof(LogEst) * nOrderBy;
4617 pSpace = sqlite3DbMallocRaw(db, nSpace);
drha18f3d22013-05-08 03:05:41 +00004618 if( pSpace==0 ) return SQLITE_NOMEM;
4619 aTo = (WherePath*)pSpace;
4620 aFrom = aTo+mxChoice;
4621 memset(aFrom, 0, sizeof(aFrom[0]));
4622 pX = (WhereLoop**)(aFrom+mxChoice);
drhe9d935a2013-06-05 16:19:59 +00004623 for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
drha18f3d22013-05-08 03:05:41 +00004624 pFrom->aLoop = pX;
4625 }
dan50ae31e2014-08-08 16:52:28 +00004626 if( nOrderBy ){
4627 /* If there is an ORDER BY clause and it is not being ignored, set up
4628 ** space for the aSortCost[] array. Each element of the aSortCost array
4629 ** is either zero - meaning it has not yet been initialized - or the
4630 ** cost of sorting nRowEst rows of data where the first X terms of
4631 ** the ORDER BY clause are already in order, where X is the array
4632 ** index. */
4633 aSortCost = (LogEst*)pX;
dane2c27852014-08-08 17:25:33 +00004634 memset(aSortCost, 0, sizeof(LogEst) * nOrderBy);
dan50ae31e2014-08-08 16:52:28 +00004635 }
dane2c27852014-08-08 17:25:33 +00004636 assert( aSortCost==0 || &pSpace[nSpace]==(char*)&aSortCost[nOrderBy] );
4637 assert( aSortCost!=0 || &pSpace[nSpace]==(char*)pX );
drha18f3d22013-05-08 03:05:41 +00004638
drhe1e2e9a2013-06-13 15:16:53 +00004639 /* Seed the search with a single WherePath containing zero WhereLoops.
4640 **
danf104abb2015-03-16 20:40:00 +00004641 ** TUNING: Do not let the number of iterations go above 28. If the cost
4642 ** of computing an automatic index is not paid back within the first 28
drhe1e2e9a2013-06-13 15:16:53 +00004643 ** rows, then do not use the automatic index. */
danf104abb2015-03-16 20:40:00 +00004644 aFrom[0].nRow = MIN(pParse->nQueryLoop, 48); assert( 48==sqlite3LogEst(28) );
drha18f3d22013-05-08 03:05:41 +00004645 nFrom = 1;
dan50ae31e2014-08-08 16:52:28 +00004646 assert( aFrom[0].isOrdered==0 );
4647 if( nOrderBy ){
4648 /* If nLoop is zero, then there are no FROM terms in the query. Since
4649 ** in this case the query may return a maximum of one row, the results
4650 ** are already in the requested order. Set isOrdered to nOrderBy to
4651 ** indicate this. Or, if nLoop is greater than zero, set isOrdered to
4652 ** -1, indicating that the result set may or may not be ordered,
4653 ** depending on the loops added to the current plan. */
4654 aFrom[0].isOrdered = nLoop>0 ? -1 : nOrderBy;
drh6b7157b2013-05-10 02:00:35 +00004655 }
4656
4657 /* Compute successively longer WherePaths using the previous generation
4658 ** of WherePaths as the basis for the next. Keep track of the mxChoice
4659 ** best paths at each generation */
drha18f3d22013-05-08 03:05:41 +00004660 for(iLoop=0; iLoop<nLoop; iLoop++){
4661 nTo = 0;
4662 for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
4663 for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
dan50ae31e2014-08-08 16:52:28 +00004664 LogEst nOut; /* Rows visited by (pFrom+pWLoop) */
4665 LogEst rCost; /* Cost of path (pFrom+pWLoop) */
4666 LogEst rUnsorted; /* Unsorted cost of (pFrom+pWLoop) */
4667 i8 isOrdered = pFrom->isOrdered; /* isOrdered for (pFrom+pWLoop) */
4668 Bitmask maskNew; /* Mask of src visited by (..) */
4669 Bitmask revMask = 0; /* Mask of rev-order loops for (..) */
4670
drha18f3d22013-05-08 03:05:41 +00004671 if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
4672 if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
drh6b7157b2013-05-10 02:00:35 +00004673 /* At this point, pWLoop is a candidate to be the next loop.
4674 ** Compute its cost */
dan50ae31e2014-08-08 16:52:28 +00004675 rUnsorted = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
4676 rUnsorted = sqlite3LogEstAdd(rUnsorted, pFrom->rUnsorted);
drhfde1e6b2013-09-06 17:45:42 +00004677 nOut = pFrom->nRow + pWLoop->nOut;
drha18f3d22013-05-08 03:05:41 +00004678 maskNew = pFrom->maskLoop | pWLoop->maskSelf;
drh0401ace2014-03-18 15:30:27 +00004679 if( isOrdered<0 ){
4680 isOrdered = wherePathSatisfiesOrderBy(pWInfo,
drh4f402f22013-06-11 18:59:38 +00004681 pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
drh0401ace2014-03-18 15:30:27 +00004682 iLoop, pWLoop, &revMask);
drh3a5ba8b2013-06-03 15:34:48 +00004683 }else{
4684 revMask = pFrom->revLoop;
drh6b7157b2013-05-10 02:00:35 +00004685 }
dan50ae31e2014-08-08 16:52:28 +00004686 if( isOrdered>=0 && isOrdered<nOrderBy ){
4687 if( aSortCost[isOrdered]==0 ){
4688 aSortCost[isOrdered] = whereSortingCost(
4689 pWInfo, nRowEst, nOrderBy, isOrdered
4690 );
4691 }
4692 rCost = sqlite3LogEstAdd(rUnsorted, aSortCost[isOrdered]);
4693
4694 WHERETRACE(0x002,
4695 ("---- sort cost=%-3d (%d/%d) increases cost %3d to %-3d\n",
4696 aSortCost[isOrdered], (nOrderBy-isOrdered), nOrderBy,
4697 rUnsorted, rCost));
4698 }else{
4699 rCost = rUnsorted;
4700 }
4701
drhddef5dc2014-08-07 16:50:00 +00004702 /* Check to see if pWLoop should be added to the set of
4703 ** mxChoice best-so-far paths.
4704 **
4705 ** First look for an existing path among best-so-far paths
4706 ** that covers the same set of loops and has the same isOrdered
4707 ** setting as the current path candidate.
drhf2a90302014-08-07 20:37:01 +00004708 **
4709 ** The term "((pTo->isOrdered^isOrdered)&0x80)==0" is equivalent
4710 ** to (pTo->isOrdered==(-1))==(isOrdered==(-1))" for the range
4711 ** of legal values for isOrdered, -1..64.
drhddef5dc2014-08-07 16:50:00 +00004712 */
drh6b7157b2013-05-10 02:00:35 +00004713 for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
drhfde1e6b2013-09-06 17:45:42 +00004714 if( pTo->maskLoop==maskNew
drhf2a90302014-08-07 20:37:01 +00004715 && ((pTo->isOrdered^isOrdered)&0x80)==0
drhfde1e6b2013-09-06 17:45:42 +00004716 ){
drh7963b0e2013-06-17 21:37:40 +00004717 testcase( jj==nTo-1 );
drh6b7157b2013-05-10 02:00:35 +00004718 break;
4719 }
4720 }
drha18f3d22013-05-08 03:05:41 +00004721 if( jj>=nTo ){
drhddef5dc2014-08-07 16:50:00 +00004722 /* None of the existing best-so-far paths match the candidate. */
drhddef5dc2014-08-07 16:50:00 +00004723 if( nTo>=mxChoice
dan50ae31e2014-08-08 16:52:28 +00004724 && (rCost>mxCost || (rCost==mxCost && rUnsorted>=mxUnsorted))
drhddef5dc2014-08-07 16:50:00 +00004725 ){
4726 /* The current candidate is no better than any of the mxChoice
4727 ** paths currently in the best-so-far buffer. So discard
4728 ** this candidate as not viable. */
drh989578e2013-10-28 14:34:35 +00004729#ifdef WHERETRACE_ENABLED /* 0x4 */
drhae70cf12013-05-31 15:18:46 +00004730 if( sqlite3WhereTrace&0x4 ){
drhfde1e6b2013-09-06 17:45:42 +00004731 sqlite3DebugPrintf("Skip %s cost=%-3d,%3d order=%c\n",
4732 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
drh0401ace2014-03-18 15:30:27 +00004733 isOrdered>=0 ? isOrdered+'0' : '?');
drhd15cb172013-05-21 19:23:10 +00004734 }
4735#endif
4736 continue;
4737 }
drhddef5dc2014-08-07 16:50:00 +00004738 /* If we reach this points it means that the new candidate path
4739 ** needs to be added to the set of best-so-far paths. */
drha18f3d22013-05-08 03:05:41 +00004740 if( nTo<mxChoice ){
drhd15cb172013-05-21 19:23:10 +00004741 /* Increase the size of the aTo set by one */
drha18f3d22013-05-08 03:05:41 +00004742 jj = nTo++;
4743 }else{
drhd15cb172013-05-21 19:23:10 +00004744 /* New path replaces the prior worst to keep count below mxChoice */
drhfde1e6b2013-09-06 17:45:42 +00004745 jj = mxI;
drha18f3d22013-05-08 03:05:41 +00004746 }
4747 pTo = &aTo[jj];
drh989578e2013-10-28 14:34:35 +00004748#ifdef WHERETRACE_ENABLED /* 0x4 */
drhae70cf12013-05-31 15:18:46 +00004749 if( sqlite3WhereTrace&0x4 ){
drhfde1e6b2013-09-06 17:45:42 +00004750 sqlite3DebugPrintf("New %s cost=%-3d,%3d order=%c\n",
4751 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
drh0401ace2014-03-18 15:30:27 +00004752 isOrdered>=0 ? isOrdered+'0' : '?');
drhd15cb172013-05-21 19:23:10 +00004753 }
4754#endif
drhf204dac2013-05-08 03:22:07 +00004755 }else{
drhddef5dc2014-08-07 16:50:00 +00004756 /* Control reaches here if best-so-far path pTo=aTo[jj] covers the
4757 ** same set of loops and has the sam isOrdered setting as the
4758 ** candidate path. Check to see if the candidate should replace
4759 ** pTo or if the candidate should be skipped */
4760 if( pTo->rCost<rCost || (pTo->rCost==rCost && pTo->nRow<=nOut) ){
drh989578e2013-10-28 14:34:35 +00004761#ifdef WHERETRACE_ENABLED /* 0x4 */
drhae70cf12013-05-31 15:18:46 +00004762 if( sqlite3WhereTrace&0x4 ){
drhd15cb172013-05-21 19:23:10 +00004763 sqlite3DebugPrintf(
drhfde1e6b2013-09-06 17:45:42 +00004764 "Skip %s cost=%-3d,%3d order=%c",
4765 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
drh0401ace2014-03-18 15:30:27 +00004766 isOrdered>=0 ? isOrdered+'0' : '?');
drhfde1e6b2013-09-06 17:45:42 +00004767 sqlite3DebugPrintf(" vs %s cost=%-3d,%d order=%c\n",
4768 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
drh0401ace2014-03-18 15:30:27 +00004769 pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
drhd15cb172013-05-21 19:23:10 +00004770 }
4771#endif
drhddef5dc2014-08-07 16:50:00 +00004772 /* Discard the candidate path from further consideration */
drh7963b0e2013-06-17 21:37:40 +00004773 testcase( pTo->rCost==rCost );
drhd15cb172013-05-21 19:23:10 +00004774 continue;
4775 }
drh7963b0e2013-06-17 21:37:40 +00004776 testcase( pTo->rCost==rCost+1 );
drhddef5dc2014-08-07 16:50:00 +00004777 /* Control reaches here if the candidate path is better than the
4778 ** pTo path. Replace pTo with the candidate. */
drh989578e2013-10-28 14:34:35 +00004779#ifdef WHERETRACE_ENABLED /* 0x4 */
drhae70cf12013-05-31 15:18:46 +00004780 if( sqlite3WhereTrace&0x4 ){
drhd15cb172013-05-21 19:23:10 +00004781 sqlite3DebugPrintf(
drhfde1e6b2013-09-06 17:45:42 +00004782 "Update %s cost=%-3d,%3d order=%c",
4783 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
drh0401ace2014-03-18 15:30:27 +00004784 isOrdered>=0 ? isOrdered+'0' : '?');
drhfde1e6b2013-09-06 17:45:42 +00004785 sqlite3DebugPrintf(" was %s cost=%-3d,%3d order=%c\n",
4786 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
drh0401ace2014-03-18 15:30:27 +00004787 pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
drhd15cb172013-05-21 19:23:10 +00004788 }
4789#endif
drha18f3d22013-05-08 03:05:41 +00004790 }
drh6b7157b2013-05-10 02:00:35 +00004791 /* pWLoop is a winner. Add it to the set of best so far */
drha18f3d22013-05-08 03:05:41 +00004792 pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
drh319f6772013-05-14 15:31:07 +00004793 pTo->revLoop = revMask;
drhfde1e6b2013-09-06 17:45:42 +00004794 pTo->nRow = nOut;
drha18f3d22013-05-08 03:05:41 +00004795 pTo->rCost = rCost;
dan50ae31e2014-08-08 16:52:28 +00004796 pTo->rUnsorted = rUnsorted;
drh6b7157b2013-05-10 02:00:35 +00004797 pTo->isOrdered = isOrdered;
drha18f3d22013-05-08 03:05:41 +00004798 memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
4799 pTo->aLoop[iLoop] = pWLoop;
4800 if( nTo>=mxChoice ){
drhfde1e6b2013-09-06 17:45:42 +00004801 mxI = 0;
drha18f3d22013-05-08 03:05:41 +00004802 mxCost = aTo[0].rCost;
dan50ae31e2014-08-08 16:52:28 +00004803 mxUnsorted = aTo[0].nRow;
drha18f3d22013-05-08 03:05:41 +00004804 for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
dan50ae31e2014-08-08 16:52:28 +00004805 if( pTo->rCost>mxCost
4806 || (pTo->rCost==mxCost && pTo->rUnsorted>mxUnsorted)
4807 ){
drhfde1e6b2013-09-06 17:45:42 +00004808 mxCost = pTo->rCost;
dan50ae31e2014-08-08 16:52:28 +00004809 mxUnsorted = pTo->rUnsorted;
drhfde1e6b2013-09-06 17:45:42 +00004810 mxI = jj;
4811 }
drha18f3d22013-05-08 03:05:41 +00004812 }
4813 }
4814 }
4815 }
4816
drh989578e2013-10-28 14:34:35 +00004817#ifdef WHERETRACE_ENABLED /* >=2 */
drh1b131b72014-10-21 16:01:40 +00004818 if( sqlite3WhereTrace & 0x02 ){
drha50ef112013-05-22 02:06:59 +00004819 sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
drhd15cb172013-05-21 19:23:10 +00004820 for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
drhb8a8e8a2013-06-10 19:12:39 +00004821 sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
drha50ef112013-05-22 02:06:59 +00004822 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
drh0401ace2014-03-18 15:30:27 +00004823 pTo->isOrdered>=0 ? (pTo->isOrdered+'0') : '?');
4824 if( pTo->isOrdered>0 ){
drh88da6442013-05-27 17:59:37 +00004825 sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
4826 }else{
4827 sqlite3DebugPrintf("\n");
4828 }
drhf204dac2013-05-08 03:22:07 +00004829 }
4830 }
4831#endif
4832
drh6b7157b2013-05-10 02:00:35 +00004833 /* Swap the roles of aFrom and aTo for the next generation */
drha18f3d22013-05-08 03:05:41 +00004834 pFrom = aTo;
4835 aTo = aFrom;
4836 aFrom = pFrom;
4837 nFrom = nTo;
4838 }
4839
drh75b93402013-05-31 20:43:57 +00004840 if( nFrom==0 ){
drhe1e2e9a2013-06-13 15:16:53 +00004841 sqlite3ErrorMsg(pParse, "no query solution");
drh75b93402013-05-31 20:43:57 +00004842 sqlite3DbFree(db, pSpace);
4843 return SQLITE_ERROR;
4844 }
drha18f3d22013-05-08 03:05:41 +00004845
drh6b7157b2013-05-10 02:00:35 +00004846 /* Find the lowest cost path. pFrom will be left pointing to that path */
drha18f3d22013-05-08 03:05:41 +00004847 pFrom = aFrom;
4848 for(ii=1; ii<nFrom; ii++){
4849 if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
4850 }
4851 assert( pWInfo->nLevel==nLoop );
drh6b7157b2013-05-10 02:00:35 +00004852 /* Load the lowest cost path into pWInfo */
drha18f3d22013-05-08 03:05:41 +00004853 for(iLoop=0; iLoop<nLoop; iLoop++){
drh7ba39a92013-05-30 17:43:19 +00004854 WhereLevel *pLevel = pWInfo->a + iLoop;
4855 pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
drhe217efc2013-06-12 03:48:41 +00004856 pLevel->iFrom = pWLoop->iTab;
drh7ba39a92013-05-30 17:43:19 +00004857 pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
drha18f3d22013-05-08 03:05:41 +00004858 }
drhfd636c72013-06-21 02:05:06 +00004859 if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0
4860 && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
4861 && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
drh4f402f22013-06-11 18:59:38 +00004862 && nRowEst
4863 ){
4864 Bitmask notUsed;
drh6457a352013-06-21 00:35:37 +00004865 int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom,
drh93ec45d2013-06-17 18:20:48 +00004866 WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
drh0401ace2014-03-18 15:30:27 +00004867 if( rc==pWInfo->pResultSet->nExpr ){
4868 pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
4869 }
drh4f402f22013-06-11 18:59:38 +00004870 }
drh079a3072014-03-19 14:10:55 +00004871 if( pWInfo->pOrderBy ){
drh4f402f22013-06-11 18:59:38 +00004872 if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
drh079a3072014-03-19 14:10:55 +00004873 if( pFrom->isOrdered==pWInfo->pOrderBy->nExpr ){
4874 pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
4875 }
drh4f402f22013-06-11 18:59:38 +00004876 }else{
drhddba0c22014-03-18 20:33:42 +00004877 pWInfo->nOBSat = pFrom->isOrdered;
drhea6c36e2014-03-19 14:30:55 +00004878 if( pWInfo->nOBSat<0 ) pWInfo->nOBSat = 0;
drh4f402f22013-06-11 18:59:38 +00004879 pWInfo->revMask = pFrom->revLoop;
4880 }
dan374cd782014-04-21 13:21:56 +00004881 if( (pWInfo->wctrlFlags & WHERE_SORTBYGROUP)
drh11b04812015-04-12 01:22:04 +00004882 && pWInfo->nOBSat==pWInfo->pOrderBy->nExpr && nLoop>0
dan374cd782014-04-21 13:21:56 +00004883 ){
danb6453202014-10-10 20:52:53 +00004884 Bitmask revMask = 0;
dan374cd782014-04-21 13:21:56 +00004885 int nOrder = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy,
danb6453202014-10-10 20:52:53 +00004886 pFrom, 0, nLoop-1, pFrom->aLoop[nLoop-1], &revMask
dan374cd782014-04-21 13:21:56 +00004887 );
4888 assert( pWInfo->sorted==0 );
danb6453202014-10-10 20:52:53 +00004889 if( nOrder==pWInfo->pOrderBy->nExpr ){
4890 pWInfo->sorted = 1;
4891 pWInfo->revMask = revMask;
4892 }
dan374cd782014-04-21 13:21:56 +00004893 }
drh6b7157b2013-05-10 02:00:35 +00004894 }
dan374cd782014-04-21 13:21:56 +00004895
4896
drha50ef112013-05-22 02:06:59 +00004897 pWInfo->nRowOut = pFrom->nRow;
drha18f3d22013-05-08 03:05:41 +00004898
4899 /* Free temporary memory and return success */
4900 sqlite3DbFree(db, pSpace);
4901 return SQLITE_OK;
4902}
drh94a11212004-09-25 13:12:14 +00004903
4904/*
drh60c96cd2013-06-09 17:21:25 +00004905** Most queries use only a single table (they are not joins) and have
4906** simple == constraints against indexed fields. This routine attempts
4907** to plan those simple cases using much less ceremony than the
4908** general-purpose query planner, and thereby yield faster sqlite3_prepare()
4909** times for the common case.
4910**
4911** Return non-zero on success, if this query can be handled by this
4912** no-frills query planner. Return zero if this query needs the
4913** general-purpose query planner.
4914*/
drhb8a8e8a2013-06-10 19:12:39 +00004915static int whereShortCut(WhereLoopBuilder *pBuilder){
drh60c96cd2013-06-09 17:21:25 +00004916 WhereInfo *pWInfo;
4917 struct SrcList_item *pItem;
4918 WhereClause *pWC;
4919 WhereTerm *pTerm;
4920 WhereLoop *pLoop;
4921 int iCur;
drh92a121f2013-06-10 12:15:47 +00004922 int j;
drh60c96cd2013-06-09 17:21:25 +00004923 Table *pTab;
4924 Index *pIdx;
4925
4926 pWInfo = pBuilder->pWInfo;
drh5822d6f2013-06-10 23:30:09 +00004927 if( pWInfo->wctrlFlags & WHERE_FORCE_TABLE ) return 0;
drh60c96cd2013-06-09 17:21:25 +00004928 assert( pWInfo->pTabList->nSrc>=1 );
4929 pItem = pWInfo->pTabList->a;
4930 pTab = pItem->pTab;
4931 if( IsVirtual(pTab) ) return 0;
drhd62fbb52015-06-04 12:08:53 +00004932 if( pItem->zIndexedBy ) return 0;
drh60c96cd2013-06-09 17:21:25 +00004933 iCur = pItem->iCursor;
4934 pWC = &pWInfo->sWC;
4935 pLoop = pBuilder->pNew;
drh60c96cd2013-06-09 17:21:25 +00004936 pLoop->wsFlags = 0;
drhc8bbce12014-10-21 01:05:09 +00004937 pLoop->nSkip = 0;
drh6f82e852015-06-06 20:12:09 +00004938 pTerm = sqlite3WhereFindTerm(pWC, iCur, -1, 0, WO_EQ|WO_IS, 0);
drh60c96cd2013-06-09 17:21:25 +00004939 if( pTerm ){
drhe8d0c612015-05-14 01:05:25 +00004940 testcase( pTerm->eOperator & WO_IS );
drh60c96cd2013-06-09 17:21:25 +00004941 pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
4942 pLoop->aLTerm[0] = pTerm;
4943 pLoop->nLTerm = 1;
4944 pLoop->u.btree.nEq = 1;
drhe1e2e9a2013-06-13 15:16:53 +00004945 /* TUNING: Cost of a rowid lookup is 10 */
drhbf539c42013-10-05 18:16:02 +00004946 pLoop->rRun = 33; /* 33==sqlite3LogEst(10) */
drh60c96cd2013-06-09 17:21:25 +00004947 }else{
4948 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
mistachkin4e5bef82015-05-15 20:14:00 +00004949 int opMask;
dancd40abb2013-08-29 10:46:05 +00004950 assert( pLoop->aLTermSpace==pLoop->aLTerm );
drh5f1d1d92014-07-31 22:59:04 +00004951 if( !IsUniqueIndex(pIdx)
dancd40abb2013-08-29 10:46:05 +00004952 || pIdx->pPartIdxWhere!=0
drhbbbdc832013-10-22 18:01:40 +00004953 || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace)
dancd40abb2013-08-29 10:46:05 +00004954 ) continue;
mistachkin4e5bef82015-05-15 20:14:00 +00004955 opMask = pIdx->uniqNotNull ? (WO_EQ|WO_IS) : WO_EQ;
drhbbbdc832013-10-22 18:01:40 +00004956 for(j=0; j<pIdx->nKeyCol; j++){
drh6f82e852015-06-06 20:12:09 +00004957 pTerm = sqlite3WhereFindTerm(pWC, iCur, pIdx->aiColumn[j], 0, opMask, pIdx);
drh60c96cd2013-06-09 17:21:25 +00004958 if( pTerm==0 ) break;
dan3072b532015-05-15 19:59:23 +00004959 testcase( pTerm->eOperator & WO_IS );
drh60c96cd2013-06-09 17:21:25 +00004960 pLoop->aLTerm[j] = pTerm;
4961 }
drhbbbdc832013-10-22 18:01:40 +00004962 if( j!=pIdx->nKeyCol ) continue;
drh92a121f2013-06-10 12:15:47 +00004963 pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
drhec95c442013-10-23 01:57:32 +00004964 if( pIdx->isCovering || (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){
drh92a121f2013-06-10 12:15:47 +00004965 pLoop->wsFlags |= WHERE_IDX_ONLY;
4966 }
drh60c96cd2013-06-09 17:21:25 +00004967 pLoop->nLTerm = j;
4968 pLoop->u.btree.nEq = j;
4969 pLoop->u.btree.pIndex = pIdx;
drhe1e2e9a2013-06-13 15:16:53 +00004970 /* TUNING: Cost of a unique index lookup is 15 */
drhbf539c42013-10-05 18:16:02 +00004971 pLoop->rRun = 39; /* 39==sqlite3LogEst(15) */
drh60c96cd2013-06-09 17:21:25 +00004972 break;
4973 }
4974 }
drh3b75ffa2013-06-10 14:56:25 +00004975 if( pLoop->wsFlags ){
drhbf539c42013-10-05 18:16:02 +00004976 pLoop->nOut = (LogEst)1;
drh3b75ffa2013-06-10 14:56:25 +00004977 pWInfo->a[0].pWLoop = pLoop;
drh6f82e852015-06-06 20:12:09 +00004978 pLoop->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur);
drh3b75ffa2013-06-10 14:56:25 +00004979 pWInfo->a[0].iTabCur = iCur;
4980 pWInfo->nRowOut = 1;
drhddba0c22014-03-18 20:33:42 +00004981 if( pWInfo->pOrderBy ) pWInfo->nOBSat = pWInfo->pOrderBy->nExpr;
drh6457a352013-06-21 00:35:37 +00004982 if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
4983 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
4984 }
drh3b75ffa2013-06-10 14:56:25 +00004985#ifdef SQLITE_DEBUG
4986 pLoop->cId = '0';
4987#endif
4988 return 1;
4989 }
4990 return 0;
drh60c96cd2013-06-09 17:21:25 +00004991}
4992
4993/*
drhe3184742002-06-19 14:27:05 +00004994** Generate the beginning of the loop used for WHERE clause processing.
drhacf3b982005-01-03 01:27:18 +00004995** The return value is a pointer to an opaque structure that contains
drh75897232000-05-29 14:26:00 +00004996** information needed to terminate the loop. Later, the calling routine
danielk19774adee202004-05-08 08:23:19 +00004997** should invoke sqlite3WhereEnd() with the return value of this function
drh75897232000-05-29 14:26:00 +00004998** in order to complete the WHERE clause processing.
4999**
5000** If an error occurs, this routine returns NULL.
drhc27a1ce2002-06-14 20:58:45 +00005001**
5002** The basic idea is to do a nested loop, one loop for each table in
5003** the FROM clause of a select. (INSERT and UPDATE statements are the
5004** same as a SELECT with only a single table in the FROM clause.) For
5005** example, if the SQL is this:
5006**
5007** SELECT * FROM t1, t2, t3 WHERE ...;
5008**
5009** Then the code generated is conceptually like the following:
5010**
5011** foreach row1 in t1 do \ Code generated
danielk19774adee202004-05-08 08:23:19 +00005012** foreach row2 in t2 do |-- by sqlite3WhereBegin()
drhc27a1ce2002-06-14 20:58:45 +00005013** foreach row3 in t3 do /
5014** ...
5015** end \ Code generated
danielk19774adee202004-05-08 08:23:19 +00005016** end |-- by sqlite3WhereEnd()
drhc27a1ce2002-06-14 20:58:45 +00005017** end /
5018**
drh29dda4a2005-07-21 18:23:20 +00005019** Note that the loops might not be nested in the order in which they
5020** appear in the FROM clause if a different order is better able to make
drh51147ba2005-07-23 22:59:55 +00005021** use of indices. Note also that when the IN operator appears in
5022** the WHERE clause, it might result in additional nested loops for
5023** scanning through all values on the right-hand side of the IN.
drh29dda4a2005-07-21 18:23:20 +00005024**
drhc27a1ce2002-06-14 20:58:45 +00005025** There are Btree cursors associated with each table. t1 uses cursor
drh6a3ea0e2003-05-02 14:32:12 +00005026** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
5027** And so forth. This routine generates code to open those VDBE cursors
danielk19774adee202004-05-08 08:23:19 +00005028** and sqlite3WhereEnd() generates the code to close them.
drhc27a1ce2002-06-14 20:58:45 +00005029**
drhe6f85e72004-12-25 01:03:13 +00005030** The code that sqlite3WhereBegin() generates leaves the cursors named
5031** in pTabList pointing at their appropriate entries. The [...] code
drhf0863fe2005-06-12 21:35:51 +00005032** can use OP_Column and OP_Rowid opcodes on these cursors to extract
drhe6f85e72004-12-25 01:03:13 +00005033** data from the various tables of the loop.
5034**
drhc27a1ce2002-06-14 20:58:45 +00005035** If the WHERE clause is empty, the foreach loops must each scan their
5036** entire tables. Thus a three-way join is an O(N^3) operation. But if
5037** the tables have indices and there are terms in the WHERE clause that
5038** refer to those indices, a complete table scan can be avoided and the
5039** code will run much faster. Most of the work of this routine is checking
5040** to see if there are indices that can be used to speed up the loop.
5041**
5042** Terms of the WHERE clause are also used to limit which rows actually
5043** make it to the "..." in the middle of the loop. After each "foreach",
5044** terms of the WHERE clause that use only terms in that loop and outer
5045** loops are evaluated and if false a jump is made around all subsequent
5046** inner loops (or around the "..." if the test occurs within the inner-
5047** most loop)
5048**
5049** OUTER JOINS
5050**
5051** An outer join of tables t1 and t2 is conceptally coded as follows:
5052**
5053** foreach row1 in t1 do
5054** flag = 0
5055** foreach row2 in t2 do
5056** start:
5057** ...
5058** flag = 1
5059** end
drhe3184742002-06-19 14:27:05 +00005060** if flag==0 then
5061** move the row2 cursor to a null row
5062** goto start
5063** fi
drhc27a1ce2002-06-14 20:58:45 +00005064** end
5065**
drhe3184742002-06-19 14:27:05 +00005066** ORDER BY CLAUSE PROCESSING
5067**
drh94433422013-07-01 11:05:50 +00005068** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause
5069** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement
drhe3184742002-06-19 14:27:05 +00005070** if there is one. If there is no ORDER BY clause or if this routine
drh46ec5b62012-09-24 15:30:54 +00005071** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
drhfc8d4f92013-11-08 15:19:46 +00005072**
5073** The iIdxCur parameter is the cursor number of an index. If
5074** WHERE_ONETABLE_ONLY is set, iIdxCur is the cursor number of an index
5075** to use for OR clause processing. The WHERE clause should use this
5076** specific cursor. If WHERE_ONEPASS_DESIRED is set, then iIdxCur is
5077** the first cursor in an array of cursors for all indices. iIdxCur should
5078** be used to compute the appropriate cursor depending on which index is
5079** used.
drh75897232000-05-29 14:26:00 +00005080*/
danielk19774adee202004-05-08 08:23:19 +00005081WhereInfo *sqlite3WhereBegin(
danielk1977ed326d72004-11-16 15:50:19 +00005082 Parse *pParse, /* The parser context */
drh6457a352013-06-21 00:35:37 +00005083 SrcList *pTabList, /* FROM clause: A list of all tables to be scanned */
danielk1977ed326d72004-11-16 15:50:19 +00005084 Expr *pWhere, /* The WHERE clause */
drh0401ace2014-03-18 15:30:27 +00005085 ExprList *pOrderBy, /* An ORDER BY (or GROUP BY) clause, or NULL */
drh6457a352013-06-21 00:35:37 +00005086 ExprList *pResultSet, /* Result set of the query */
dan0efb72c2012-08-24 18:44:56 +00005087 u16 wctrlFlags, /* One of the WHERE_* flags defined in sqliteInt.h */
5088 int iIdxCur /* If WHERE_ONETABLE_ONLY is set, index cursor number */
drh75897232000-05-29 14:26:00 +00005089){
danielk1977be229652009-03-20 14:18:51 +00005090 int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
drhc01a3c12009-12-16 22:10:49 +00005091 int nTabList; /* Number of elements in pTabList */
drh75897232000-05-29 14:26:00 +00005092 WhereInfo *pWInfo; /* Will become the return value of this function */
5093 Vdbe *v = pParse->pVdbe; /* The virtual database engine */
drhfe05af82005-07-21 03:14:59 +00005094 Bitmask notReady; /* Cursors that are not yet positioned */
drh1c8148f2013-05-04 20:25:23 +00005095 WhereLoopBuilder sWLB; /* The WhereLoop builder */
drh111a6a72008-12-21 03:51:16 +00005096 WhereMaskSet *pMaskSet; /* The expression mask set */
drh56f1b992012-09-25 14:29:39 +00005097 WhereLevel *pLevel; /* A single level in pWInfo->a[] */
drhfd636c72013-06-21 02:05:06 +00005098 WhereLoop *pLoop; /* Pointer to a single WhereLoop object */
drh9cd1c992012-09-25 20:43:35 +00005099 int ii; /* Loop counter */
drh17435752007-08-16 04:30:38 +00005100 sqlite3 *db; /* Database connection */
drh5346e952013-05-08 14:14:26 +00005101 int rc; /* Return code */
drh75897232000-05-29 14:26:00 +00005102
drh56f1b992012-09-25 14:29:39 +00005103
5104 /* Variable initialization */
drhfd636c72013-06-21 02:05:06 +00005105 db = pParse->db;
drh1c8148f2013-05-04 20:25:23 +00005106 memset(&sWLB, 0, sizeof(sWLB));
drh0401ace2014-03-18 15:30:27 +00005107
5108 /* An ORDER/GROUP BY clause of more than 63 terms cannot be optimized */
5109 testcase( pOrderBy && pOrderBy->nExpr==BMS-1 );
5110 if( pOrderBy && pOrderBy->nExpr>=BMS ) pOrderBy = 0;
drh1c8148f2013-05-04 20:25:23 +00005111 sWLB.pOrderBy = pOrderBy;
drh56f1b992012-09-25 14:29:39 +00005112
drhfd636c72013-06-21 02:05:06 +00005113 /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
5114 ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
5115 if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
5116 wctrlFlags &= ~WHERE_WANT_DISTINCT;
5117 }
5118
drh29dda4a2005-07-21 18:23:20 +00005119 /* The number of tables in the FROM clause is limited by the number of
drh1398ad32005-01-19 23:24:50 +00005120 ** bits in a Bitmask
5121 */
drh67ae0cb2010-04-08 14:38:51 +00005122 testcase( pTabList->nSrc==BMS );
drh29dda4a2005-07-21 18:23:20 +00005123 if( pTabList->nSrc>BMS ){
5124 sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
drh1398ad32005-01-19 23:24:50 +00005125 return 0;
5126 }
5127
drhc01a3c12009-12-16 22:10:49 +00005128 /* This function normally generates a nested loop for all tables in
5129 ** pTabList. But if the WHERE_ONETABLE_ONLY flag is set, then we should
5130 ** only generate code for the first table in pTabList and assume that
5131 ** any cursors associated with subsequent tables are uninitialized.
5132 */
5133 nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
5134
drh75897232000-05-29 14:26:00 +00005135 /* Allocate and initialize the WhereInfo structure that will become the
danielk1977be229652009-03-20 14:18:51 +00005136 ** return value. A single allocation is used to store the WhereInfo
5137 ** struct, the contents of WhereInfo.a[], the WhereClause structure
5138 ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
5139 ** field (type Bitmask) it must be aligned on an 8-byte boundary on
5140 ** some architectures. Hence the ROUND8() below.
drh75897232000-05-29 14:26:00 +00005141 */
drhc01a3c12009-12-16 22:10:49 +00005142 nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
drh60c96cd2013-06-09 17:21:25 +00005143 pWInfo = sqlite3DbMallocZero(db, nByteWInfo + sizeof(WhereLoop));
drh17435752007-08-16 04:30:38 +00005144 if( db->mallocFailed ){
drh8b307fb2010-04-06 15:57:05 +00005145 sqlite3DbFree(db, pWInfo);
5146 pWInfo = 0;
danielk197785574e32008-10-06 05:32:18 +00005147 goto whereBeginError;
drh75897232000-05-29 14:26:00 +00005148 }
drhfc8d4f92013-11-08 15:19:46 +00005149 pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1;
drhc01a3c12009-12-16 22:10:49 +00005150 pWInfo->nLevel = nTabList;
drh75897232000-05-29 14:26:00 +00005151 pWInfo->pParse = pParse;
5152 pWInfo->pTabList = pTabList;
drh6b7157b2013-05-10 02:00:35 +00005153 pWInfo->pOrderBy = pOrderBy;
drh6457a352013-06-21 00:35:37 +00005154 pWInfo->pResultSet = pResultSet;
drha22a75e2014-03-21 18:16:23 +00005155 pWInfo->iBreak = pWInfo->iContinue = sqlite3VdbeMakeLabel(v);
drh6df2acd2008-12-28 16:55:25 +00005156 pWInfo->wctrlFlags = wctrlFlags;
drh8b307fb2010-04-06 15:57:05 +00005157 pWInfo->savedNQueryLoop = pParse->nQueryLoop;
drh70d18342013-06-06 19:16:33 +00005158 pMaskSet = &pWInfo->sMaskSet;
drh1c8148f2013-05-04 20:25:23 +00005159 sWLB.pWInfo = pWInfo;
drh70d18342013-06-06 19:16:33 +00005160 sWLB.pWC = &pWInfo->sWC;
drh1ac87e12013-07-18 14:50:56 +00005161 sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);
5162 assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) );
drh60c96cd2013-06-09 17:21:25 +00005163 whereLoopInit(sWLB.pNew);
drhb8a8e8a2013-06-10 19:12:39 +00005164#ifdef SQLITE_DEBUG
5165 sWLB.pNew->cId = '*';
5166#endif
drh08192d52002-04-30 19:20:28 +00005167
drh111a6a72008-12-21 03:51:16 +00005168 /* Split the WHERE clause into separate subexpressions where each
5169 ** subexpression is separated by an AND operator.
5170 */
5171 initMaskSet(pMaskSet);
drh70d18342013-06-06 19:16:33 +00005172 whereClauseInit(&pWInfo->sWC, pWInfo);
drh39759742013-08-02 23:40:45 +00005173 whereSplit(&pWInfo->sWC, pWhere, TK_AND);
drh111a6a72008-12-21 03:51:16 +00005174
drh08192d52002-04-30 19:20:28 +00005175 /* Special case: a WHERE clause that is constant. Evaluate the
5176 ** expression and either jump over all of the code or fall thru.
5177 */
drh759e8582014-01-02 21:05:10 +00005178 for(ii=0; ii<sWLB.pWC->nTerm; ii++){
5179 if( nTabList==0 || sqlite3ExprIsConstantNotJoin(sWLB.pWC->a[ii].pExpr) ){
5180 sqlite3ExprIfFalse(pParse, sWLB.pWC->a[ii].pExpr, pWInfo->iBreak,
5181 SQLITE_JUMPIFNULL);
5182 sWLB.pWC->a[ii].wtFlags |= TERM_CODED;
5183 }
drh08192d52002-04-30 19:20:28 +00005184 }
drh75897232000-05-29 14:26:00 +00005185
drh4fe425a2013-06-12 17:08:06 +00005186 /* Special case: No FROM clause
5187 */
5188 if( nTabList==0 ){
drhddba0c22014-03-18 20:33:42 +00005189 if( pOrderBy ) pWInfo->nOBSat = pOrderBy->nExpr;
drh6457a352013-06-21 00:35:37 +00005190 if( wctrlFlags & WHERE_WANT_DISTINCT ){
5191 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
5192 }
drh4fe425a2013-06-12 17:08:06 +00005193 }
5194
drh42165be2008-03-26 14:56:34 +00005195 /* Assign a bit from the bitmask to every term in the FROM clause.
5196 **
5197 ** When assigning bitmask values to FROM clause cursors, it must be
5198 ** the case that if X is the bitmask for the N-th FROM clause term then
5199 ** the bitmask for all FROM clause terms to the left of the N-th term
5200 ** is (X-1). An expression from the ON clause of a LEFT JOIN can use
5201 ** its Expr.iRightJoinTable value to find the bitmask of the right table
5202 ** of the join. Subtracting one from the right table bitmask gives a
5203 ** bitmask for all tables to the left of the join. Knowing the bitmask
5204 ** for all tables to the left of a left join is important. Ticket #3015.
danielk1977e672c8e2009-05-22 15:43:26 +00005205 **
drhc01a3c12009-12-16 22:10:49 +00005206 ** Note that bitmasks are created for all pTabList->nSrc tables in
5207 ** pTabList, not just the first nTabList tables. nTabList is normally
5208 ** equal to pTabList->nSrc but might be shortened to 1 if the
5209 ** WHERE_ONETABLE_ONLY flag is set.
drh42165be2008-03-26 14:56:34 +00005210 */
drh9cd1c992012-09-25 20:43:35 +00005211 for(ii=0; ii<pTabList->nSrc; ii++){
5212 createMask(pMaskSet, pTabList->a[ii].iCursor);
drh42165be2008-03-26 14:56:34 +00005213 }
5214#ifndef NDEBUG
5215 {
5216 Bitmask toTheLeft = 0;
drh9cd1c992012-09-25 20:43:35 +00005217 for(ii=0; ii<pTabList->nSrc; ii++){
drh6f82e852015-06-06 20:12:09 +00005218 Bitmask m = sqlite3WhereGetMask(pMaskSet, pTabList->a[ii].iCursor);
drh42165be2008-03-26 14:56:34 +00005219 assert( (m-1)==toTheLeft );
5220 toTheLeft |= m;
5221 }
5222 }
5223#endif
5224
drhb121dd12015-06-06 18:30:17 +00005225 /* Analyze all of the subexpressions. */
drh70d18342013-06-06 19:16:33 +00005226 exprAnalyzeAll(pTabList, &pWInfo->sWC);
drhb121dd12015-06-06 18:30:17 +00005227 if( db->mallocFailed ) goto whereBeginError;
drh75897232000-05-29 14:26:00 +00005228
drh6457a352013-06-21 00:35:37 +00005229 if( wctrlFlags & WHERE_WANT_DISTINCT ){
5230 if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){
5231 /* The DISTINCT marking is pointless. Ignore it. */
drh4f402f22013-06-11 18:59:38 +00005232 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
5233 }else if( pOrderBy==0 ){
drh6457a352013-06-21 00:35:37 +00005234 /* Try to ORDER BY the result set to make distinct processing easier */
drh4f402f22013-06-11 18:59:38 +00005235 pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
drh6457a352013-06-21 00:35:37 +00005236 pWInfo->pOrderBy = pResultSet;
drh4f402f22013-06-11 18:59:38 +00005237 }
dan38cc40c2011-06-30 20:17:15 +00005238 }
5239
drhf1b5f5b2013-05-02 00:15:01 +00005240 /* Construct the WhereLoop objects */
drh3b48e8c2013-06-12 20:18:16 +00005241 WHERETRACE(0xffff,("*** Optimizer Start ***\n"));
drhc90713d2014-09-30 13:46:49 +00005242#if defined(WHERETRACE_ENABLED)
drhb121dd12015-06-06 18:30:17 +00005243 if( sqlite3WhereTrace & 0x100 ){ /* Display all terms of the WHERE clause */
drhc90713d2014-09-30 13:46:49 +00005244 int i;
5245 for(i=0; i<sWLB.pWC->nTerm; i++){
5246 whereTermPrint(&sWLB.pWC->a[i], i);
5247 }
5248 }
5249#endif
5250
drhb8a8e8a2013-06-10 19:12:39 +00005251 if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
drh60c96cd2013-06-09 17:21:25 +00005252 rc = whereLoopAddAll(&sWLB);
5253 if( rc ) goto whereBeginError;
5254
drhb121dd12015-06-06 18:30:17 +00005255#ifdef WHERETRACE_ENABLED
5256 if( sqlite3WhereTrace ){ /* Display all of the WhereLoop objects */
drh60c96cd2013-06-09 17:21:25 +00005257 WhereLoop *p;
drhfd636c72013-06-21 02:05:06 +00005258 int i;
drhb121dd12015-06-06 18:30:17 +00005259 static const char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
5260 "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
drhfd636c72013-06-21 02:05:06 +00005261 for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
5262 p->cId = zLabel[i%sizeof(zLabel)];
drhc1ba2e72013-10-28 19:03:21 +00005263 whereLoopPrint(p, sWLB.pWC);
drh60c96cd2013-06-09 17:21:25 +00005264 }
5265 }
5266#endif
5267
drh4f402f22013-06-11 18:59:38 +00005268 wherePathSolver(pWInfo, 0);
drh60c96cd2013-06-09 17:21:25 +00005269 if( db->mallocFailed ) goto whereBeginError;
5270 if( pWInfo->pOrderBy ){
drhc7f0d222013-06-19 03:27:12 +00005271 wherePathSolver(pWInfo, pWInfo->nRowOut+1);
drh60c96cd2013-06-09 17:21:25 +00005272 if( db->mallocFailed ) goto whereBeginError;
drha18f3d22013-05-08 03:05:41 +00005273 }
5274 }
drh60c96cd2013-06-09 17:21:25 +00005275 if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
drhd84ce352013-06-04 18:27:41 +00005276 pWInfo->revMask = (Bitmask)(-1);
drha50ef112013-05-22 02:06:59 +00005277 }
drh81186b42013-06-18 01:52:41 +00005278 if( pParse->nErr || NEVER(db->mallocFailed) ){
drh75b93402013-05-31 20:43:57 +00005279 goto whereBeginError;
5280 }
drhb121dd12015-06-06 18:30:17 +00005281#ifdef WHERETRACE_ENABLED
drha18f3d22013-05-08 03:05:41 +00005282 if( sqlite3WhereTrace ){
drh4f402f22013-06-11 18:59:38 +00005283 sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
drhddba0c22014-03-18 20:33:42 +00005284 if( pWInfo->nOBSat>0 ){
5285 sqlite3DebugPrintf(" ORDERBY=%d,0x%llx", pWInfo->nOBSat, pWInfo->revMask);
drh319f6772013-05-14 15:31:07 +00005286 }
drh4f402f22013-06-11 18:59:38 +00005287 switch( pWInfo->eDistinct ){
5288 case WHERE_DISTINCT_UNIQUE: {
5289 sqlite3DebugPrintf(" DISTINCT=unique");
5290 break;
5291 }
5292 case WHERE_DISTINCT_ORDERED: {
5293 sqlite3DebugPrintf(" DISTINCT=ordered");
5294 break;
5295 }
5296 case WHERE_DISTINCT_UNORDERED: {
5297 sqlite3DebugPrintf(" DISTINCT=unordered");
5298 break;
5299 }
5300 }
5301 sqlite3DebugPrintf("\n");
drhfd636c72013-06-21 02:05:06 +00005302 for(ii=0; ii<pWInfo->nLevel; ii++){
drhc1ba2e72013-10-28 19:03:21 +00005303 whereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC);
drhf1b5f5b2013-05-02 00:15:01 +00005304 }
5305 }
5306#endif
drhfd636c72013-06-21 02:05:06 +00005307 /* Attempt to omit tables from the join that do not effect the result */
drh1031bd92013-06-22 15:44:26 +00005308 if( pWInfo->nLevel>=2
5309 && pResultSet!=0
5310 && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
5311 ){
drhfd636c72013-06-21 02:05:06 +00005312 Bitmask tabUsed = exprListTableUsage(pMaskSet, pResultSet);
drh67a5ec72013-09-03 14:03:47 +00005313 if( sWLB.pOrderBy ) tabUsed |= exprListTableUsage(pMaskSet, sWLB.pOrderBy);
drhfd636c72013-06-21 02:05:06 +00005314 while( pWInfo->nLevel>=2 ){
drh9d5a5792013-06-28 13:43:33 +00005315 WhereTerm *pTerm, *pEnd;
drhfd636c72013-06-21 02:05:06 +00005316 pLoop = pWInfo->a[pWInfo->nLevel-1].pWLoop;
drhbc71b1d2013-06-21 02:15:48 +00005317 if( (pWInfo->pTabList->a[pLoop->iTab].jointype & JT_LEFT)==0 ) break;
5318 if( (wctrlFlags & WHERE_WANT_DISTINCT)==0
5319 && (pLoop->wsFlags & WHERE_ONEROW)==0
drhfd636c72013-06-21 02:05:06 +00005320 ){
drhfd636c72013-06-21 02:05:06 +00005321 break;
5322 }
drhbc71b1d2013-06-21 02:15:48 +00005323 if( (tabUsed & pLoop->maskSelf)!=0 ) break;
drh9d5a5792013-06-28 13:43:33 +00005324 pEnd = sWLB.pWC->a + sWLB.pWC->nTerm;
5325 for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
5326 if( (pTerm->prereqAll & pLoop->maskSelf)!=0
5327 && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
5328 ){
5329 break;
5330 }
5331 }
5332 if( pTerm<pEnd ) break;
drhbc71b1d2013-06-21 02:15:48 +00005333 WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId));
5334 pWInfo->nLevel--;
5335 nTabList--;
drhfd636c72013-06-21 02:05:06 +00005336 }
5337 }
drh3b48e8c2013-06-12 20:18:16 +00005338 WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
drh8e23daf2013-06-11 13:30:04 +00005339 pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
drhf1b5f5b2013-05-02 00:15:01 +00005340
drh08c88eb2008-04-10 13:33:18 +00005341 /* If the caller is an UPDATE or DELETE statement that is requesting
5342 ** to use a one-pass algorithm, determine if this is appropriate.
drh24b7fe92013-09-30 19:33:06 +00005343 ** The one-pass algorithm only works if the WHERE clause constrains
drhb121dd12015-06-06 18:30:17 +00005344 ** the statement to update or delete a single row.
drh08c88eb2008-04-10 13:33:18 +00005345 */
drh165be382008-12-05 02:36:33 +00005346 assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
drh3b48e8c2013-06-12 20:18:16 +00005347 if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
5348 && (pWInfo->a[0].pWLoop->wsFlags & WHERE_ONEROW)!=0 ){
drh08c88eb2008-04-10 13:33:18 +00005349 pWInfo->okOnePass = 1;
drh702ba9f2013-11-07 21:25:13 +00005350 if( HasRowid(pTabList->a[0].pTab) ){
5351 pWInfo->a[0].pWLoop->wsFlags &= ~WHERE_IDX_ONLY;
5352 }
drh08c88eb2008-04-10 13:33:18 +00005353 }
drheb04de32013-05-10 15:16:30 +00005354
drh9012bcb2004-12-19 00:11:35 +00005355 /* Open all tables in the pTabList and any indices selected for
5356 ** searching those tables.
5357 */
drh9cd1c992012-09-25 20:43:35 +00005358 for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
danielk1977da184232006-01-05 11:34:32 +00005359 Table *pTab; /* Table to open */
danielk1977da184232006-01-05 11:34:32 +00005360 int iDb; /* Index of database containing table/index */
drh56f1b992012-09-25 14:29:39 +00005361 struct SrcList_item *pTabItem;
drh9012bcb2004-12-19 00:11:35 +00005362
drh29dda4a2005-07-21 18:23:20 +00005363 pTabItem = &pTabList->a[pLevel->iFrom];
drh9012bcb2004-12-19 00:11:35 +00005364 pTab = pTabItem->pTab;
danielk1977595a5232009-07-24 17:58:53 +00005365 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
drh7ba39a92013-05-30 17:43:19 +00005366 pLoop = pLevel->pWLoop;
drh424aab82010-04-06 18:28:20 +00005367 if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
drh75bb9f52010-04-06 18:51:42 +00005368 /* Do nothing */
5369 }else
drh9eff6162006-06-12 21:59:13 +00005370#ifndef SQLITE_OMIT_VIRTUALTABLE
drh7ba39a92013-05-30 17:43:19 +00005371 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
danielk1977595a5232009-07-24 17:58:53 +00005372 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
danielk197793626f42006-06-20 13:07:27 +00005373 int iCur = pTabItem->iCursor;
danielk1977595a5232009-07-24 17:58:53 +00005374 sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
drhfc5e5462012-12-03 17:04:40 +00005375 }else if( IsVirtual(pTab) ){
5376 /* noop */
drh9eff6162006-06-12 21:59:13 +00005377 }else
5378#endif
drh7ba39a92013-05-30 17:43:19 +00005379 if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
drh9ef61f42011-10-07 14:40:59 +00005380 && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){
drhfc8d4f92013-11-08 15:19:46 +00005381 int op = OP_OpenRead;
5382 if( pWInfo->okOnePass ){
5383 op = OP_OpenWrite;
5384 pWInfo->aiCurOnePass[0] = pTabItem->iCursor;
5385 };
drh08c88eb2008-04-10 13:33:18 +00005386 sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
drhfc8d4f92013-11-08 15:19:46 +00005387 assert( pTabItem->iCursor==pLevel->iTabCur );
drh7963b0e2013-06-17 21:37:40 +00005388 testcase( !pWInfo->okOnePass && pTab->nCol==BMS-1 );
5389 testcase( !pWInfo->okOnePass && pTab->nCol==BMS );
drhdd9930e2013-10-23 23:37:02 +00005390 if( !pWInfo->okOnePass && pTab->nCol<BMS && HasRowid(pTab) ){
danielk19779792eef2006-01-13 15:58:43 +00005391 Bitmask b = pTabItem->colUsed;
5392 int n = 0;
drh74161702006-02-24 02:53:49 +00005393 for(; b; b=b>>1, n++){}
drh8cff69d2009-11-12 19:59:44 +00005394 sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
5395 SQLITE_INT_TO_PTR(n), P4_INT32);
danielk19779792eef2006-01-13 15:58:43 +00005396 assert( n<=pTab->nCol );
5397 }
danielk1977c00da102006-01-07 13:21:04 +00005398 }else{
5399 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
drh9012bcb2004-12-19 00:11:35 +00005400 }
drh7e47cb82013-05-31 17:55:27 +00005401 if( pLoop->wsFlags & WHERE_INDEXED ){
drh7ba39a92013-05-30 17:43:19 +00005402 Index *pIx = pLoop->u.btree.pIndex;
drhfc8d4f92013-11-08 15:19:46 +00005403 int iIndexCur;
5404 int op = OP_OpenRead;
drh4308e342013-11-11 16:55:52 +00005405 /* iIdxCur is always set if to a positive value if ONEPASS is possible */
5406 assert( iIdxCur!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 );
drh48dd1d82014-05-27 18:18:58 +00005407 if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIx)
drha3bc66a2014-05-27 17:57:32 +00005408 && (wctrlFlags & WHERE_ONETABLE_ONLY)!=0
5409 ){
5410 /* This is one term of an OR-optimization using the PRIMARY KEY of a
5411 ** WITHOUT ROWID table. No need for a separate index */
5412 iIndexCur = pLevel->iTabCur;
5413 op = 0;
5414 }else if( pWInfo->okOnePass ){
drhfc8d4f92013-11-08 15:19:46 +00005415 Index *pJ = pTabItem->pTab->pIndex;
5416 iIndexCur = iIdxCur;
5417 assert( wctrlFlags & WHERE_ONEPASS_DESIRED );
5418 while( ALWAYS(pJ) && pJ!=pIx ){
5419 iIndexCur++;
5420 pJ = pJ->pNext;
5421 }
5422 op = OP_OpenWrite;
5423 pWInfo->aiCurOnePass[1] = iIndexCur;
5424 }else if( iIdxCur && (wctrlFlags & WHERE_ONETABLE_ONLY)!=0 ){
5425 iIndexCur = iIdxCur;
drh35263192014-07-22 20:02:19 +00005426 if( wctrlFlags & WHERE_REOPEN_IDX ) op = OP_ReopenIdx;
drhfc8d4f92013-11-08 15:19:46 +00005427 }else{
5428 iIndexCur = pParse->nTab++;
5429 }
5430 pLevel->iIdxCur = iIndexCur;
danielk1977da184232006-01-05 11:34:32 +00005431 assert( pIx->pSchema==pTab->pSchema );
drhb0367fb2012-08-25 02:11:13 +00005432 assert( iIndexCur>=0 );
drha3bc66a2014-05-27 17:57:32 +00005433 if( op ){
5434 sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb);
5435 sqlite3VdbeSetP4KeyInfo(pParse, pIx);
drhe0997b32015-03-20 14:57:50 +00005436 if( (pLoop->wsFlags & WHERE_CONSTRAINT)!=0
5437 && (pLoop->wsFlags & (WHERE_COLUMN_RANGE|WHERE_SKIPSCAN))==0
5438 && (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0
5439 ){
5440 sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ); /* Hint to COMDB2 */
5441 }
drha3bc66a2014-05-27 17:57:32 +00005442 VdbeComment((v, "%s", pIx->zName));
5443 }
drh9012bcb2004-12-19 00:11:35 +00005444 }
drhaceb31b2014-02-08 01:40:27 +00005445 if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb);
drh9012bcb2004-12-19 00:11:35 +00005446 }
5447 pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
drha21a64d2010-04-06 22:33:55 +00005448 if( db->mallocFailed ) goto whereBeginError;
drh9012bcb2004-12-19 00:11:35 +00005449
drh29dda4a2005-07-21 18:23:20 +00005450 /* Generate the code to do the search. Each iteration of the for
5451 ** loop below generates code for a single nested loop of the VM
5452 ** program.
drh75897232000-05-29 14:26:00 +00005453 */
drhfe05af82005-07-21 03:14:59 +00005454 notReady = ~(Bitmask)0;
drh9cd1c992012-09-25 20:43:35 +00005455 for(ii=0; ii<nTabList; ii++){
dan6f9702e2014-11-01 20:38:06 +00005456 int addrExplain;
5457 int wsFlags;
drh9cd1c992012-09-25 20:43:35 +00005458 pLevel = &pWInfo->a[ii];
dan6f9702e2014-11-01 20:38:06 +00005459 wsFlags = pLevel->pWLoop->wsFlags;
drhcc04afd2013-08-22 02:56:28 +00005460#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
5461 if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){
5462 constructAutomaticIndex(pParse, &pWInfo->sWC,
5463 &pTabList->a[pLevel->iFrom], notReady, pLevel);
5464 if( db->mallocFailed ) goto whereBeginError;
5465 }
5466#endif
drh6f82e852015-06-06 20:12:09 +00005467 addrExplain = sqlite3WhereExplainOneScan(
dan6f9702e2014-11-01 20:38:06 +00005468 pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags
5469 );
drhcc04afd2013-08-22 02:56:28 +00005470 pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
drh6f82e852015-06-06 20:12:09 +00005471 notReady = sqlite3WhereCodeOneLoopStart(pWInfo, ii, notReady);
dan4a07e3d2010-11-09 14:48:59 +00005472 pWInfo->iContinue = pLevel->addrCont;
dan6f9702e2014-11-01 20:38:06 +00005473 if( (wsFlags&WHERE_MULTI_OR)==0 && (wctrlFlags&WHERE_ONETABLE_ONLY)==0 ){
drh6f82e852015-06-06 20:12:09 +00005474 sqlite3WhereAddScanStatus(v, pTabList, pLevel, addrExplain);
dan6f9702e2014-11-01 20:38:06 +00005475 }
drh75897232000-05-29 14:26:00 +00005476 }
drh7ec764a2005-07-21 03:48:20 +00005477
drh6fa978d2013-05-30 19:29:19 +00005478 /* Done. */
drh6bc69a22013-11-19 12:33:23 +00005479 VdbeModuleComment((v, "Begin WHERE-core"));
drh75897232000-05-29 14:26:00 +00005480 return pWInfo;
drhe23399f2005-07-22 00:31:39 +00005481
5482 /* Jump here if malloc fails */
danielk197785574e32008-10-06 05:32:18 +00005483whereBeginError:
drh8b307fb2010-04-06 15:57:05 +00005484 if( pWInfo ){
5485 pParse->nQueryLoop = pWInfo->savedNQueryLoop;
5486 whereInfoFree(db, pWInfo);
5487 }
drhe23399f2005-07-22 00:31:39 +00005488 return 0;
drh75897232000-05-29 14:26:00 +00005489}
5490
5491/*
drhc27a1ce2002-06-14 20:58:45 +00005492** Generate the end of the WHERE loop. See comments on
danielk19774adee202004-05-08 08:23:19 +00005493** sqlite3WhereBegin() for additional information.
drh75897232000-05-29 14:26:00 +00005494*/
danielk19774adee202004-05-08 08:23:19 +00005495void sqlite3WhereEnd(WhereInfo *pWInfo){
drh633e6d52008-07-28 19:34:53 +00005496 Parse *pParse = pWInfo->pParse;
5497 Vdbe *v = pParse->pVdbe;
drh19a775c2000-06-05 18:54:46 +00005498 int i;
drh6b563442001-11-07 16:48:26 +00005499 WhereLevel *pLevel;
drh7ba39a92013-05-30 17:43:19 +00005500 WhereLoop *pLoop;
drhad3cab52002-05-24 02:04:32 +00005501 SrcList *pTabList = pWInfo->pTabList;
drh633e6d52008-07-28 19:34:53 +00005502 sqlite3 *db = pParse->db;
drh19a775c2000-06-05 18:54:46 +00005503
drh9012bcb2004-12-19 00:11:35 +00005504 /* Generate loop termination code.
5505 */
drh6bc69a22013-11-19 12:33:23 +00005506 VdbeModuleComment((v, "End WHERE-core"));
drhceea3322009-04-23 13:22:42 +00005507 sqlite3ExprCacheClear(pParse);
drhc01a3c12009-12-16 22:10:49 +00005508 for(i=pWInfo->nLevel-1; i>=0; i--){
drhcd8629e2013-11-13 12:27:25 +00005509 int addr;
drh6b563442001-11-07 16:48:26 +00005510 pLevel = &pWInfo->a[i];
drh7ba39a92013-05-30 17:43:19 +00005511 pLoop = pLevel->pWLoop;
drhb3190c12008-12-08 21:37:14 +00005512 sqlite3VdbeResolveLabel(v, pLevel->addrCont);
drh6b563442001-11-07 16:48:26 +00005513 if( pLevel->op!=OP_Noop ){
drhe39a7322014-02-03 14:04:11 +00005514 sqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3);
drhd1d38482008-10-07 23:46:38 +00005515 sqlite3VdbeChangeP5(v, pLevel->p5);
drh688852a2014-02-17 22:40:43 +00005516 VdbeCoverage(v);
drh7d176102014-02-18 03:07:12 +00005517 VdbeCoverageIf(v, pLevel->op==OP_Next);
5518 VdbeCoverageIf(v, pLevel->op==OP_Prev);
5519 VdbeCoverageIf(v, pLevel->op==OP_VNext);
drh19a775c2000-06-05 18:54:46 +00005520 }
drh7ba39a92013-05-30 17:43:19 +00005521 if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
drh72e8fa42007-03-28 14:30:06 +00005522 struct InLoop *pIn;
drhe23399f2005-07-22 00:31:39 +00005523 int j;
drhb3190c12008-12-08 21:37:14 +00005524 sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
drh111a6a72008-12-21 03:51:16 +00005525 for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
drhb3190c12008-12-08 21:37:14 +00005526 sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
drh2d96b932013-02-08 18:48:23 +00005527 sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
drh688852a2014-02-17 22:40:43 +00005528 VdbeCoverage(v);
drh7d176102014-02-18 03:07:12 +00005529 VdbeCoverageIf(v, pIn->eEndLoopOp==OP_PrevIfOpen);
5530 VdbeCoverageIf(v, pIn->eEndLoopOp==OP_NextIfOpen);
drhb3190c12008-12-08 21:37:14 +00005531 sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
drhe23399f2005-07-22 00:31:39 +00005532 }
drhd99f7062002-06-08 23:25:08 +00005533 }
drhb3190c12008-12-08 21:37:14 +00005534 sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
drhcd8629e2013-11-13 12:27:25 +00005535 if( pLevel->addrSkip ){
drhcd8629e2013-11-13 12:27:25 +00005536 sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrSkip);
drhe084f402013-11-13 17:24:38 +00005537 VdbeComment((v, "next skip-scan on %s", pLoop->u.btree.pIndex->zName));
drh2e5ef4e2013-11-13 16:58:54 +00005538 sqlite3VdbeJumpHere(v, pLevel->addrSkip);
5539 sqlite3VdbeJumpHere(v, pLevel->addrSkip-2);
drhcd8629e2013-11-13 12:27:25 +00005540 }
drhf07cf6e2015-03-06 16:45:16 +00005541 if( pLevel->addrLikeRep ){
drhb7c60ba2015-03-07 02:51:59 +00005542 int op;
5543 if( sqlite3VdbeGetOp(v, pLevel->addrLikeRep-1)->p1 ){
5544 op = OP_DecrJumpZero;
5545 }else{
5546 op = OP_JumpZeroIncr;
5547 }
5548 sqlite3VdbeAddOp2(v, op, pLevel->iLikeRepCntr, pLevel->addrLikeRep);
drhf07cf6e2015-03-06 16:45:16 +00005549 VdbeCoverage(v);
drhf07cf6e2015-03-06 16:45:16 +00005550 }
drhad2d8302002-05-24 20:31:36 +00005551 if( pLevel->iLeftJoin ){
drh688852a2014-02-17 22:40:43 +00005552 addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v);
drh7ba39a92013-05-30 17:43:19 +00005553 assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
5554 || (pLoop->wsFlags & WHERE_INDEXED)!=0 );
5555 if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 ){
drh35451c62009-11-12 04:26:39 +00005556 sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
5557 }
drh76f4cfb2013-05-31 18:20:52 +00005558 if( pLoop->wsFlags & WHERE_INDEXED ){
drh3c84ddf2008-01-09 02:15:38 +00005559 sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
drh7f09b3e2002-08-13 13:15:49 +00005560 }
drh336a5302009-04-24 15:46:21 +00005561 if( pLevel->op==OP_Return ){
5562 sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
5563 }else{
5564 sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
5565 }
drhd654be82005-09-20 17:42:23 +00005566 sqlite3VdbeJumpHere(v, addr);
drhad2d8302002-05-24 20:31:36 +00005567 }
drh6bc69a22013-11-19 12:33:23 +00005568 VdbeModuleComment((v, "End WHERE-loop%d: %s", i,
drhfc8d4f92013-11-08 15:19:46 +00005569 pWInfo->pTabList->a[pLevel->iFrom].pTab->zName));
drh19a775c2000-06-05 18:54:46 +00005570 }
drh9012bcb2004-12-19 00:11:35 +00005571
5572 /* The "break" point is here, just past the end of the outer loop.
5573 ** Set it.
5574 */
danielk19774adee202004-05-08 08:23:19 +00005575 sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
drh9012bcb2004-12-19 00:11:35 +00005576
drhfd636c72013-06-21 02:05:06 +00005577 assert( pWInfo->nLevel<=pTabList->nSrc );
drhc01a3c12009-12-16 22:10:49 +00005578 for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
drh5f612292014-02-08 23:20:32 +00005579 int k, last;
5580 VdbeOp *pOp;
danbfca6a42012-08-24 10:52:35 +00005581 Index *pIdx = 0;
drh29dda4a2005-07-21 18:23:20 +00005582 struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
drh9012bcb2004-12-19 00:11:35 +00005583 Table *pTab = pTabItem->pTab;
drh5cf590c2003-04-24 01:45:04 +00005584 assert( pTab!=0 );
drh7ba39a92013-05-30 17:43:19 +00005585 pLoop = pLevel->pWLoop;
drhfc8d4f92013-11-08 15:19:46 +00005586
drh5f612292014-02-08 23:20:32 +00005587 /* For a co-routine, change all OP_Column references to the table of
drh7b3aa082015-05-29 13:55:33 +00005588 ** the co-routine into OP_Copy of result contained in a register.
drh5f612292014-02-08 23:20:32 +00005589 ** OP_Rowid becomes OP_Null.
5590 */
danfbf0f0e2014-03-03 14:20:30 +00005591 if( pTabItem->viaCoroutine && !db->mallocFailed ){
drh7b3aa082015-05-29 13:55:33 +00005592 translateColumnToCopy(v, pLevel->addrBody, pLevel->iTabCur,
5593 pTabItem->regResult);
drh5f612292014-02-08 23:20:32 +00005594 continue;
5595 }
5596
drhfc8d4f92013-11-08 15:19:46 +00005597 /* Close all of the cursors that were opened by sqlite3WhereBegin.
5598 ** Except, do not close cursors that will be reused by the OR optimization
5599 ** (WHERE_OMIT_OPEN_CLOSE). And do not close the OP_OpenWrite cursors
5600 ** created for the ONEPASS optimization.
5601 */
drh4139c992010-04-07 14:59:45 +00005602 if( (pTab->tabFlags & TF_Ephemeral)==0
5603 && pTab->pSelect==0
drh9ef61f42011-10-07 14:40:59 +00005604 && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
drh4139c992010-04-07 14:59:45 +00005605 ){
drh7ba39a92013-05-30 17:43:19 +00005606 int ws = pLoop->wsFlags;
drh8b307fb2010-04-06 15:57:05 +00005607 if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
drh6df2acd2008-12-28 16:55:25 +00005608 sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
5609 }
drhfc8d4f92013-11-08 15:19:46 +00005610 if( (ws & WHERE_INDEXED)!=0
5611 && (ws & (WHERE_IPK|WHERE_AUTO_INDEX))==0
5612 && pLevel->iIdxCur!=pWInfo->aiCurOnePass[1]
5613 ){
drh6df2acd2008-12-28 16:55:25 +00005614 sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
5615 }
drh9012bcb2004-12-19 00:11:35 +00005616 }
5617
drhf0030762013-06-14 13:27:01 +00005618 /* If this scan uses an index, make VDBE code substitutions to read data
5619 ** from the index instead of from the table where possible. In some cases
5620 ** this optimization prevents the table from ever being read, which can
5621 ** yield a significant performance boost.
drh9012bcb2004-12-19 00:11:35 +00005622 **
5623 ** Calls to the code generator in between sqlite3WhereBegin and
5624 ** sqlite3WhereEnd will have created code that references the table
5625 ** directly. This loop scans all that code looking for opcodes
5626 ** that reference the table and converts them into opcodes that
5627 ** reference the index.
5628 */
drh7ba39a92013-05-30 17:43:19 +00005629 if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
5630 pIdx = pLoop->u.btree.pIndex;
5631 }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
drhd40e2082012-08-24 23:24:15 +00005632 pIdx = pLevel->u.pCovidx;
danbfca6a42012-08-24 10:52:35 +00005633 }
drh7ba39a92013-05-30 17:43:19 +00005634 if( pIdx && !db->mallocFailed ){
drh9012bcb2004-12-19 00:11:35 +00005635 last = sqlite3VdbeCurrentAddr(v);
drhcc04afd2013-08-22 02:56:28 +00005636 k = pLevel->addrBody;
5637 pOp = sqlite3VdbeGetOp(v, k);
5638 for(; k<last; k++, pOp++){
drh9012bcb2004-12-19 00:11:35 +00005639 if( pOp->p1!=pLevel->iTabCur ) continue;
5640 if( pOp->opcode==OP_Column ){
drhee0ec8e2013-10-31 17:38:01 +00005641 int x = pOp->p2;
drh511717c2013-11-08 17:13:23 +00005642 assert( pIdx->pTable==pTab );
drhee0ec8e2013-10-31 17:38:01 +00005643 if( !HasRowid(pTab) ){
5644 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
5645 x = pPk->aiColumn[x];
5646 }
5647 x = sqlite3ColumnOfIndex(pIdx, x);
drh44156282013-10-23 22:23:03 +00005648 if( x>=0 ){
5649 pOp->p2 = x;
5650 pOp->p1 = pLevel->iIdxCur;
drh9012bcb2004-12-19 00:11:35 +00005651 }
drh44156282013-10-23 22:23:03 +00005652 assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || x>=0 );
drhf0863fe2005-06-12 21:35:51 +00005653 }else if( pOp->opcode==OP_Rowid ){
drh9012bcb2004-12-19 00:11:35 +00005654 pOp->p1 = pLevel->iIdxCur;
drhf0863fe2005-06-12 21:35:51 +00005655 pOp->opcode = OP_IdxRowid;
drh9012bcb2004-12-19 00:11:35 +00005656 }
5657 }
drh6b563442001-11-07 16:48:26 +00005658 }
drh19a775c2000-06-05 18:54:46 +00005659 }
drh9012bcb2004-12-19 00:11:35 +00005660
5661 /* Final cleanup
5662 */
drhf12cde52010-04-08 17:28:00 +00005663 pParse->nQueryLoop = pWInfo->savedNQueryLoop;
5664 whereInfoFree(db, pWInfo);
drh75897232000-05-29 14:26:00 +00005665 return;
5666}