blob: 0eca517a558cf87d1dba82868fd6763e97c748d4 [file] [log] [blame]
drh75897232000-05-29 14:26:00 +00001/*
drhb19a2bc2001-09-16 00:13:26 +00002** 2001 September 15
drh75897232000-05-29 14:26:00 +00003**
drhb19a2bc2001-09-16 00:13:26 +00004** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
drh75897232000-05-29 14:26:00 +00006**
drhb19a2bc2001-09-16 00:13:26 +00007** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
drh75897232000-05-29 14:26:00 +000010**
11*************************************************************************
12** This module contains C code that generates VDBE code used to process
drh909626d2008-05-30 14:58:37 +000013** the WHERE clause of SQL statements. This module is responsible for
drh51669862004-12-18 18:40:26 +000014** generating the code that loops through a table looking for applicable
15** rows. Indices are selected and used to speed the search when doing
16** so is applicable. Because this module is responsible for selecting
17** indices, you might also think of this module as the "query optimizer".
drh75897232000-05-29 14:26:00 +000018*/
19#include "sqliteInt.h"
drhe54df422013-11-12 18:37:25 +000020#include "whereInt.h"
drh51147ba2005-07-23 22:59:55 +000021
22/*
drh6f328482013-06-05 23:39:34 +000023** Return the estimated number of output rows from a WHERE clause
24*/
drhc63367e2013-06-10 20:46:50 +000025u64 sqlite3WhereOutputRowCount(WhereInfo *pWInfo){
drhbf539c42013-10-05 18:16:02 +000026 return sqlite3LogEstToInt(pWInfo->nRowOut);
drh6f328482013-06-05 23:39:34 +000027}
28
29/*
30** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
31** WHERE clause returns outputs for DISTINCT processing.
32*/
33int sqlite3WhereIsDistinct(WhereInfo *pWInfo){
34 return pWInfo->eDistinct;
35}
36
37/*
38** Return TRUE if the WHERE clause returns rows in ORDER BY order.
39** Return FALSE if the output needs to be sorted.
40*/
41int sqlite3WhereIsOrdered(WhereInfo *pWInfo){
drhddba0c22014-03-18 20:33:42 +000042 return pWInfo->nOBSat;
drh6f328482013-06-05 23:39:34 +000043}
44
45/*
46** Return the VDBE address or label to jump to in order to continue
47** immediately with the next row of a WHERE clause.
48*/
49int sqlite3WhereContinueLabel(WhereInfo *pWInfo){
drha22a75e2014-03-21 18:16:23 +000050 assert( pWInfo->iContinue!=0 );
drh6f328482013-06-05 23:39:34 +000051 return pWInfo->iContinue;
52}
53
54/*
55** Return the VDBE address or label to jump to in order to break
56** out of a WHERE loop.
57*/
58int sqlite3WhereBreakLabel(WhereInfo *pWInfo){
59 return pWInfo->iBreak;
60}
61
62/*
63** Return TRUE if an UPDATE or DELETE statement can operate directly on
64** the rowids returned by a WHERE clause. Return FALSE if doing an
65** UPDATE or DELETE might change subsequent WHERE clause results.
drhfc8d4f92013-11-08 15:19:46 +000066**
67** If the ONEPASS optimization is used (if this routine returns true)
68** then also write the indices of open cursors used by ONEPASS
69** into aiCur[0] and aiCur[1]. iaCur[0] gets the cursor of the data
70** table and iaCur[1] gets the cursor used by an auxiliary index.
71** Either value may be -1, indicating that cursor is not used.
72** Any cursors returned will have been opened for writing.
73**
74** aiCur[0] and aiCur[1] both get -1 if the where-clause logic is
75** unable to use the ONEPASS optimization.
drh6f328482013-06-05 23:39:34 +000076*/
drhfc8d4f92013-11-08 15:19:46 +000077int sqlite3WhereOkOnePass(WhereInfo *pWInfo, int *aiCur){
78 memcpy(aiCur, pWInfo->aiCurOnePass, sizeof(int)*2);
drh6f328482013-06-05 23:39:34 +000079 return pWInfo->okOnePass;
80}
81
82/*
drhaa32e3c2013-07-16 21:31:23 +000083** Move the content of pSrc into pDest
84*/
85static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){
86 pDest->n = pSrc->n;
87 memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0]));
88}
89
90/*
91** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet.
92**
93** The new entry might overwrite an existing entry, or it might be
94** appended, or it might be discarded. Do whatever is the right thing
95** so that pSet keeps the N_OR_COST best entries seen so far.
96*/
97static int whereOrInsert(
98 WhereOrSet *pSet, /* The WhereOrSet to be updated */
99 Bitmask prereq, /* Prerequisites of the new entry */
drhbf539c42013-10-05 18:16:02 +0000100 LogEst rRun, /* Run-cost of the new entry */
101 LogEst nOut /* Number of outputs for the new entry */
drhaa32e3c2013-07-16 21:31:23 +0000102){
103 u16 i;
104 WhereOrCost *p;
105 for(i=pSet->n, p=pSet->a; i>0; i--, p++){
106 if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){
107 goto whereOrInsert_done;
108 }
109 if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){
110 return 0;
111 }
112 }
113 if( pSet->n<N_OR_COST ){
114 p = &pSet->a[pSet->n++];
115 p->nOut = nOut;
116 }else{
117 p = pSet->a;
118 for(i=1; i<pSet->n; i++){
119 if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i;
120 }
121 if( p->rRun<=rRun ) return 0;
122 }
123whereOrInsert_done:
124 p->prereq = prereq;
125 p->rRun = rRun;
126 if( p->nOut>nOut ) p->nOut = nOut;
127 return 1;
128}
129
130/*
drh0aa74ed2005-07-16 13:33:20 +0000131** Initialize a preallocated WhereClause structure.
drh75897232000-05-29 14:26:00 +0000132*/
drh7b4fc6a2007-02-06 13:26:32 +0000133static void whereClauseInit(
134 WhereClause *pWC, /* The WhereClause to be initialized */
drh70d18342013-06-06 19:16:33 +0000135 WhereInfo *pWInfo /* The WHERE processing context */
drh7b4fc6a2007-02-06 13:26:32 +0000136){
drh70d18342013-06-06 19:16:33 +0000137 pWC->pWInfo = pWInfo;
drh8871ef52011-10-07 13:33:10 +0000138 pWC->pOuter = 0;
drh0aa74ed2005-07-16 13:33:20 +0000139 pWC->nTerm = 0;
drhcad651e2007-04-20 12:22:01 +0000140 pWC->nSlot = ArraySize(pWC->aStatic);
drh0aa74ed2005-07-16 13:33:20 +0000141 pWC->a = pWC->aStatic;
142}
143
drh700a2262008-12-17 19:22:15 +0000144/* Forward reference */
145static void whereClauseClear(WhereClause*);
146
147/*
148** Deallocate all memory associated with a WhereOrInfo object.
149*/
150static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
drh5bd98ae2009-01-07 18:24:03 +0000151 whereClauseClear(&p->wc);
152 sqlite3DbFree(db, p);
drh700a2262008-12-17 19:22:15 +0000153}
154
155/*
156** Deallocate all memory associated with a WhereAndInfo object.
157*/
158static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
drh5bd98ae2009-01-07 18:24:03 +0000159 whereClauseClear(&p->wc);
160 sqlite3DbFree(db, p);
drh700a2262008-12-17 19:22:15 +0000161}
162
drh0aa74ed2005-07-16 13:33:20 +0000163/*
164** Deallocate a WhereClause structure. The WhereClause structure
165** itself is not freed. This routine is the inverse of whereClauseInit().
166*/
167static void whereClauseClear(WhereClause *pWC){
168 int i;
169 WhereTerm *a;
drh70d18342013-06-06 19:16:33 +0000170 sqlite3 *db = pWC->pWInfo->pParse->db;
drh0aa74ed2005-07-16 13:33:20 +0000171 for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
drh165be382008-12-05 02:36:33 +0000172 if( a->wtFlags & TERM_DYNAMIC ){
drh633e6d52008-07-28 19:34:53 +0000173 sqlite3ExprDelete(db, a->pExpr);
drh0aa74ed2005-07-16 13:33:20 +0000174 }
drh700a2262008-12-17 19:22:15 +0000175 if( a->wtFlags & TERM_ORINFO ){
176 whereOrInfoDelete(db, a->u.pOrInfo);
177 }else if( a->wtFlags & TERM_ANDINFO ){
178 whereAndInfoDelete(db, a->u.pAndInfo);
179 }
drh0aa74ed2005-07-16 13:33:20 +0000180 }
181 if( pWC->a!=pWC->aStatic ){
drh633e6d52008-07-28 19:34:53 +0000182 sqlite3DbFree(db, pWC->a);
drh0aa74ed2005-07-16 13:33:20 +0000183 }
184}
185
186/*
drh6a1e0712008-12-05 15:24:15 +0000187** Add a single new WhereTerm entry to the WhereClause object pWC.
188** The new WhereTerm object is constructed from Expr p and with wtFlags.
189** The index in pWC->a[] of the new WhereTerm is returned on success.
190** 0 is returned if the new WhereTerm could not be added due to a memory
191** allocation error. The memory allocation failure will be recorded in
192** the db->mallocFailed flag so that higher-level functions can detect it.
193**
194** This routine will increase the size of the pWC->a[] array as necessary.
drh9eb20282005-08-24 03:52:18 +0000195**
drh165be382008-12-05 02:36:33 +0000196** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
drh6a1e0712008-12-05 15:24:15 +0000197** for freeing the expression p is assumed by the WhereClause object pWC.
198** This is true even if this routine fails to allocate a new WhereTerm.
drhb63a53d2007-03-31 01:34:44 +0000199**
drh9eb20282005-08-24 03:52:18 +0000200** WARNING: This routine might reallocate the space used to store
drh909626d2008-05-30 14:58:37 +0000201** WhereTerms. All pointers to WhereTerms should be invalidated after
drh9eb20282005-08-24 03:52:18 +0000202** calling this routine. Such pointers may be reinitialized by referencing
203** the pWC->a[] array.
drh0aa74ed2005-07-16 13:33:20 +0000204*/
drhf07cf6e2015-03-06 16:45:16 +0000205static int whereClauseInsert(WhereClause *pWC, Expr *p, u16 wtFlags){
drh0aa74ed2005-07-16 13:33:20 +0000206 WhereTerm *pTerm;
drh9eb20282005-08-24 03:52:18 +0000207 int idx;
drh39759742013-08-02 23:40:45 +0000208 testcase( wtFlags & TERM_VIRTUAL );
drh0aa74ed2005-07-16 13:33:20 +0000209 if( pWC->nTerm>=pWC->nSlot ){
210 WhereTerm *pOld = pWC->a;
drh70d18342013-06-06 19:16:33 +0000211 sqlite3 *db = pWC->pWInfo->pParse->db;
drh633e6d52008-07-28 19:34:53 +0000212 pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
drhb63a53d2007-03-31 01:34:44 +0000213 if( pWC->a==0 ){
drh165be382008-12-05 02:36:33 +0000214 if( wtFlags & TERM_DYNAMIC ){
drh633e6d52008-07-28 19:34:53 +0000215 sqlite3ExprDelete(db, p);
drhb63a53d2007-03-31 01:34:44 +0000216 }
drhf998b732007-11-26 13:36:00 +0000217 pWC->a = pOld;
drhb63a53d2007-03-31 01:34:44 +0000218 return 0;
219 }
drh0aa74ed2005-07-16 13:33:20 +0000220 memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
221 if( pOld!=pWC->aStatic ){
drh633e6d52008-07-28 19:34:53 +0000222 sqlite3DbFree(db, pOld);
drh0aa74ed2005-07-16 13:33:20 +0000223 }
drh6a1e0712008-12-05 15:24:15 +0000224 pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
drhfe32daa2014-12-05 19:50:58 +0000225 memset(&pWC->a[pWC->nTerm], 0, sizeof(pWC->a[0])*(pWC->nSlot-pWC->nTerm));
drh0aa74ed2005-07-16 13:33:20 +0000226 }
drh6a1e0712008-12-05 15:24:15 +0000227 pTerm = &pWC->a[idx = pWC->nTerm++];
drha4c3c872013-09-12 17:29:25 +0000228 if( p && ExprHasProperty(p, EP_Unlikely) ){
drhd05ab6a2014-10-25 13:42:16 +0000229 pTerm->truthProb = sqlite3LogEst(p->iTable) - 270;
drhcca9f3d2013-09-06 15:23:29 +0000230 }else{
danaa9933c2014-04-24 20:04:49 +0000231 pTerm->truthProb = 1;
drhcca9f3d2013-09-06 15:23:29 +0000232 }
drh7ee751d2012-12-19 15:53:51 +0000233 pTerm->pExpr = sqlite3ExprSkipCollate(p);
drh165be382008-12-05 02:36:33 +0000234 pTerm->wtFlags = wtFlags;
drh0fcef5e2005-07-19 17:38:22 +0000235 pTerm->pWC = pWC;
drh45b1ee42005-08-02 17:48:22 +0000236 pTerm->iParent = -1;
drh9eb20282005-08-24 03:52:18 +0000237 return idx;
drh0aa74ed2005-07-16 13:33:20 +0000238}
drh75897232000-05-29 14:26:00 +0000239
240/*
drh51669862004-12-18 18:40:26 +0000241** This routine identifies subexpressions in the WHERE clause where
drhb6fb62d2005-09-20 08:47:20 +0000242** each subexpression is separated by the AND operator or some other
drh6c30be82005-07-29 15:10:17 +0000243** operator specified in the op parameter. The WhereClause structure
244** is filled with pointers to subexpressions. For example:
drh75897232000-05-29 14:26:00 +0000245**
drh51669862004-12-18 18:40:26 +0000246** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
247** \________/ \_______________/ \________________/
248** slot[0] slot[1] slot[2]
249**
250** The original WHERE clause in pExpr is unaltered. All this routine
drh51147ba2005-07-23 22:59:55 +0000251** does is make slot[] entries point to substructure within pExpr.
drh51669862004-12-18 18:40:26 +0000252**
drh51147ba2005-07-23 22:59:55 +0000253** In the previous sentence and in the diagram, "slot[]" refers to
drh902b9ee2008-12-05 17:17:07 +0000254** the WhereClause.a[] array. The slot[] array grows as needed to contain
drh51147ba2005-07-23 22:59:55 +0000255** all terms of the WHERE clause.
drh75897232000-05-29 14:26:00 +0000256*/
drh74f91d42013-06-19 18:01:44 +0000257static void whereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
drh0f517ea2015-04-21 02:12:13 +0000258 Expr *pE2 = sqlite3ExprSkipCollate(pExpr);
drh74f91d42013-06-19 18:01:44 +0000259 pWC->op = op;
drh0f517ea2015-04-21 02:12:13 +0000260 if( pE2==0 ) return;
261 if( pE2->op!=op ){
drh0aa74ed2005-07-16 13:33:20 +0000262 whereClauseInsert(pWC, pExpr, 0);
drh75897232000-05-29 14:26:00 +0000263 }else{
drh0f517ea2015-04-21 02:12:13 +0000264 whereSplit(pWC, pE2->pLeft, op);
265 whereSplit(pWC, pE2->pRight, op);
drh75897232000-05-29 14:26:00 +0000266 }
drh75897232000-05-29 14:26:00 +0000267}
268
269/*
drh3b48e8c2013-06-12 20:18:16 +0000270** Initialize a WhereMaskSet object
drh6a3ea0e2003-05-02 14:32:12 +0000271*/
drhfd5874d2013-06-12 14:52:39 +0000272#define initMaskSet(P) (P)->n=0
drh6a3ea0e2003-05-02 14:32:12 +0000273
274/*
drh1398ad32005-01-19 23:24:50 +0000275** Return the bitmask for the given cursor number. Return 0 if
276** iCursor is not in the set.
drh6a3ea0e2003-05-02 14:32:12 +0000277*/
drh111a6a72008-12-21 03:51:16 +0000278static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
drh6a3ea0e2003-05-02 14:32:12 +0000279 int i;
drhfcd71b62011-04-05 22:08:24 +0000280 assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
drh6a3ea0e2003-05-02 14:32:12 +0000281 for(i=0; i<pMaskSet->n; i++){
drh51669862004-12-18 18:40:26 +0000282 if( pMaskSet->ix[i]==iCursor ){
drh7699d1c2013-06-04 12:42:29 +0000283 return MASKBIT(i);
drh51669862004-12-18 18:40:26 +0000284 }
drh6a3ea0e2003-05-02 14:32:12 +0000285 }
drh6a3ea0e2003-05-02 14:32:12 +0000286 return 0;
287}
288
289/*
drh1398ad32005-01-19 23:24:50 +0000290** Create a new mask for cursor iCursor.
drh0fcef5e2005-07-19 17:38:22 +0000291**
292** There is one cursor per table in the FROM clause. The number of
293** tables in the FROM clause is limited by a test early in the
drhb6fb62d2005-09-20 08:47:20 +0000294** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[]
drh0fcef5e2005-07-19 17:38:22 +0000295** array will never overflow.
drh1398ad32005-01-19 23:24:50 +0000296*/
drh111a6a72008-12-21 03:51:16 +0000297static void createMask(WhereMaskSet *pMaskSet, int iCursor){
drhcad651e2007-04-20 12:22:01 +0000298 assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
drh0fcef5e2005-07-19 17:38:22 +0000299 pMaskSet->ix[pMaskSet->n++] = iCursor;
drh1398ad32005-01-19 23:24:50 +0000300}
301
302/*
drh4a6fc352013-08-07 01:18:38 +0000303** These routines walk (recursively) an expression tree and generate
drh75897232000-05-29 14:26:00 +0000304** a bitmask indicating which tables are used in that expression
drh6a3ea0e2003-05-02 14:32:12 +0000305** tree.
drh75897232000-05-29 14:26:00 +0000306*/
drh111a6a72008-12-21 03:51:16 +0000307static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
308static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
309static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
drh51669862004-12-18 18:40:26 +0000310 Bitmask mask = 0;
drh75897232000-05-29 14:26:00 +0000311 if( p==0 ) return 0;
drh967e8b72000-06-21 13:59:10 +0000312 if( p->op==TK_COLUMN ){
drh8feb4b12004-07-19 02:12:14 +0000313 mask = getMask(pMaskSet, p->iTable);
drh8feb4b12004-07-19 02:12:14 +0000314 return mask;
drh75897232000-05-29 14:26:00 +0000315 }
danielk1977b3bce662005-01-29 08:32:43 +0000316 mask = exprTableUsage(pMaskSet, p->pRight);
317 mask |= exprTableUsage(pMaskSet, p->pLeft);
danielk19776ab3a2e2009-02-19 14:39:25 +0000318 if( ExprHasProperty(p, EP_xIsSelect) ){
319 mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
320 }else{
321 mask |= exprListTableUsage(pMaskSet, p->x.pList);
322 }
danielk1977b3bce662005-01-29 08:32:43 +0000323 return mask;
324}
drh111a6a72008-12-21 03:51:16 +0000325static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
danielk1977b3bce662005-01-29 08:32:43 +0000326 int i;
327 Bitmask mask = 0;
328 if( pList ){
329 for(i=0; i<pList->nExpr; i++){
330 mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
drhdd579122002-04-02 01:58:57 +0000331 }
332 }
drh75897232000-05-29 14:26:00 +0000333 return mask;
334}
drh111a6a72008-12-21 03:51:16 +0000335static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
drha430ae82007-09-12 15:41:01 +0000336 Bitmask mask = 0;
337 while( pS ){
drha464c232011-09-16 19:04:03 +0000338 SrcList *pSrc = pS->pSrc;
drha430ae82007-09-12 15:41:01 +0000339 mask |= exprListTableUsage(pMaskSet, pS->pEList);
drhf5b11382005-09-17 13:07:13 +0000340 mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
341 mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
342 mask |= exprTableUsage(pMaskSet, pS->pWhere);
343 mask |= exprTableUsage(pMaskSet, pS->pHaving);
drha464c232011-09-16 19:04:03 +0000344 if( ALWAYS(pSrc!=0) ){
drh88501772011-09-16 17:43:06 +0000345 int i;
346 for(i=0; i<pSrc->nSrc; i++){
347 mask |= exprSelectTableUsage(pMaskSet, pSrc->a[i].pSelect);
348 mask |= exprTableUsage(pMaskSet, pSrc->a[i].pOn);
349 }
350 }
drha430ae82007-09-12 15:41:01 +0000351 pS = pS->pPrior;
drhf5b11382005-09-17 13:07:13 +0000352 }
353 return mask;
354}
drh75897232000-05-29 14:26:00 +0000355
356/*
drh487ab3c2001-11-08 00:45:21 +0000357** Return TRUE if the given operator is one of the operators that is
drh51669862004-12-18 18:40:26 +0000358** allowed for an indexable WHERE clause term. The allowed operators are
drh3b48e8c2013-06-12 20:18:16 +0000359** "=", "<", ">", "<=", ">=", "IN", and "IS NULL"
drh487ab3c2001-11-08 00:45:21 +0000360*/
361static int allowedOp(int op){
drhfe05af82005-07-21 03:14:59 +0000362 assert( TK_GT>TK_EQ && TK_GT<TK_GE );
363 assert( TK_LT>TK_EQ && TK_LT<TK_GE );
364 assert( TK_LE>TK_EQ && TK_LE<TK_GE );
365 assert( TK_GE==TK_EQ+4 );
drhfcd49532015-05-13 15:24:07 +0000366 return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL || op==TK_IS;
drh487ab3c2001-11-08 00:45:21 +0000367}
368
369/*
drh909626d2008-05-30 14:58:37 +0000370** Commute a comparison operator. Expressions of the form "X op Y"
drh0fcef5e2005-07-19 17:38:22 +0000371** are converted into "Y op X".
danielk1977eb5453d2007-07-30 14:40:48 +0000372**
mistachkin48864df2013-03-21 21:20:32 +0000373** If left/right precedence rules come into play when determining the
drh3b48e8c2013-06-12 20:18:16 +0000374** collating sequence, then COLLATE operators are adjusted to ensure
375** that the collating sequence does not change. For example:
376** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on
danielk1977eb5453d2007-07-30 14:40:48 +0000377** the left hand side of a comparison overrides any collation sequence
drhae80dde2012-12-06 21:16:43 +0000378** attached to the right. For the same reason the EP_Collate flag
danielk1977eb5453d2007-07-30 14:40:48 +0000379** is not commuted.
drh193bd772004-07-20 18:23:14 +0000380*/
drh7d10d5a2008-08-20 16:35:10 +0000381static void exprCommute(Parse *pParse, Expr *pExpr){
drhae80dde2012-12-06 21:16:43 +0000382 u16 expRight = (pExpr->pRight->flags & EP_Collate);
383 u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
drhfe05af82005-07-21 03:14:59 +0000384 assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
drhae80dde2012-12-06 21:16:43 +0000385 if( expRight==expLeft ){
386 /* Either X and Y both have COLLATE operator or neither do */
387 if( expRight ){
388 /* Both X and Y have COLLATE operators. Make sure X is always
389 ** used by clearing the EP_Collate flag from Y. */
390 pExpr->pRight->flags &= ~EP_Collate;
391 }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
392 /* Neither X nor Y have COLLATE operators, but X has a non-default
393 ** collating sequence. So add the EP_Collate marker on X to cause
394 ** it to be searched first. */
395 pExpr->pLeft->flags |= EP_Collate;
396 }
397 }
drh0fcef5e2005-07-19 17:38:22 +0000398 SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
399 if( pExpr->op>=TK_GT ){
400 assert( TK_LT==TK_GT+2 );
401 assert( TK_GE==TK_LE+2 );
402 assert( TK_GT>TK_EQ );
403 assert( TK_GT<TK_LE );
404 assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
405 pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
drh193bd772004-07-20 18:23:14 +0000406 }
drh193bd772004-07-20 18:23:14 +0000407}
408
409/*
drhfe05af82005-07-21 03:14:59 +0000410** Translate from TK_xx operator to WO_xx bitmask.
411*/
drhec1724e2008-12-09 01:32:03 +0000412static u16 operatorMask(int op){
413 u16 c;
drhfe05af82005-07-21 03:14:59 +0000414 assert( allowedOp(op) );
415 if( op==TK_IN ){
drh51147ba2005-07-23 22:59:55 +0000416 c = WO_IN;
drh50b39962006-10-28 00:28:09 +0000417 }else if( op==TK_ISNULL ){
418 c = WO_ISNULL;
drhfcd49532015-05-13 15:24:07 +0000419 }else if( op==TK_IS ){
drhe8d0c612015-05-14 01:05:25 +0000420 c = WO_IS;
drhfe05af82005-07-21 03:14:59 +0000421 }else{
drhec1724e2008-12-09 01:32:03 +0000422 assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
423 c = (u16)(WO_EQ<<(op-TK_EQ));
drhfe05af82005-07-21 03:14:59 +0000424 }
drh50b39962006-10-28 00:28:09 +0000425 assert( op!=TK_ISNULL || c==WO_ISNULL );
drh51147ba2005-07-23 22:59:55 +0000426 assert( op!=TK_IN || c==WO_IN );
427 assert( op!=TK_EQ || c==WO_EQ );
428 assert( op!=TK_LT || c==WO_LT );
429 assert( op!=TK_LE || c==WO_LE );
430 assert( op!=TK_GT || c==WO_GT );
431 assert( op!=TK_GE || c==WO_GE );
drhe8d0c612015-05-14 01:05:25 +0000432 assert( op!=TK_IS || c==WO_IS );
drh51147ba2005-07-23 22:59:55 +0000433 return c;
drhfe05af82005-07-21 03:14:59 +0000434}
435
436/*
drh1c8148f2013-05-04 20:25:23 +0000437** Advance to the next WhereTerm that matches according to the criteria
438** established when the pScan object was initialized by whereScanInit().
439** Return NULL if there are no more matching WhereTerms.
440*/
danb2cfc142013-07-05 11:10:54 +0000441static WhereTerm *whereScanNext(WhereScan *pScan){
drh1c8148f2013-05-04 20:25:23 +0000442 int iCur; /* The cursor on the LHS of the term */
443 int iColumn; /* The column on the LHS of the term. -1 for IPK */
444 Expr *pX; /* An expression being tested */
445 WhereClause *pWC; /* Shorthand for pScan->pWC */
446 WhereTerm *pTerm; /* The term being tested */
drh43b85ef2013-06-10 12:34:45 +0000447 int k = pScan->k; /* Where to start scanning */
drh1c8148f2013-05-04 20:25:23 +0000448
449 while( pScan->iEquiv<=pScan->nEquiv ){
450 iCur = pScan->aEquiv[pScan->iEquiv-2];
451 iColumn = pScan->aEquiv[pScan->iEquiv-1];
452 while( (pWC = pScan->pWC)!=0 ){
drh43b85ef2013-06-10 12:34:45 +0000453 for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
drhe1a086e2013-10-28 20:15:56 +0000454 if( pTerm->leftCursor==iCur
455 && pTerm->u.leftColumn==iColumn
456 && (pScan->iEquiv<=2 || !ExprHasProperty(pTerm->pExpr, EP_FromJoin))
457 ){
drh1c8148f2013-05-04 20:25:23 +0000458 if( (pTerm->eOperator & WO_EQUIV)!=0
459 && pScan->nEquiv<ArraySize(pScan->aEquiv)
460 ){
461 int j;
462 pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight);
463 assert( pX->op==TK_COLUMN );
464 for(j=0; j<pScan->nEquiv; j+=2){
465 if( pScan->aEquiv[j]==pX->iTable
466 && pScan->aEquiv[j+1]==pX->iColumn ){
467 break;
468 }
469 }
470 if( j==pScan->nEquiv ){
471 pScan->aEquiv[j] = pX->iTable;
472 pScan->aEquiv[j+1] = pX->iColumn;
473 pScan->nEquiv += 2;
474 }
475 }
476 if( (pTerm->eOperator & pScan->opMask)!=0 ){
477 /* Verify the affinity and collating sequence match */
478 if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
479 CollSeq *pColl;
drh70d18342013-06-06 19:16:33 +0000480 Parse *pParse = pWC->pWInfo->pParse;
drh1c8148f2013-05-04 20:25:23 +0000481 pX = pTerm->pExpr;
482 if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
483 continue;
484 }
485 assert(pX->pLeft);
drh70d18342013-06-06 19:16:33 +0000486 pColl = sqlite3BinaryCompareCollSeq(pParse,
drh1c8148f2013-05-04 20:25:23 +0000487 pX->pLeft, pX->pRight);
drh70d18342013-06-06 19:16:33 +0000488 if( pColl==0 ) pColl = pParse->db->pDfltColl;
drh1c8148f2013-05-04 20:25:23 +0000489 if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
490 continue;
491 }
492 }
drhe8d0c612015-05-14 01:05:25 +0000493 if( (pTerm->eOperator & (WO_EQ|WO_IS))!=0
drha184fb82013-05-08 04:22:59 +0000494 && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN
495 && pX->iTable==pScan->aEquiv[0]
496 && pX->iColumn==pScan->aEquiv[1]
497 ){
drhe8d0c612015-05-14 01:05:25 +0000498 testcase( pTerm->eOperator & WO_IS );
drha184fb82013-05-08 04:22:59 +0000499 continue;
500 }
drh43b85ef2013-06-10 12:34:45 +0000501 pScan->k = k+1;
drh1c8148f2013-05-04 20:25:23 +0000502 return pTerm;
503 }
504 }
505 }
drhad01d892013-06-19 13:59:49 +0000506 pScan->pWC = pScan->pWC->pOuter;
drh43b85ef2013-06-10 12:34:45 +0000507 k = 0;
drh1c8148f2013-05-04 20:25:23 +0000508 }
509 pScan->pWC = pScan->pOrigWC;
drh43b85ef2013-06-10 12:34:45 +0000510 k = 0;
drh1c8148f2013-05-04 20:25:23 +0000511 pScan->iEquiv += 2;
512 }
drh1c8148f2013-05-04 20:25:23 +0000513 return 0;
514}
515
516/*
517** Initialize a WHERE clause scanner object. Return a pointer to the
518** first match. Return NULL if there are no matches.
519**
520** The scanner will be searching the WHERE clause pWC. It will look
521** for terms of the form "X <op> <expr>" where X is column iColumn of table
522** iCur. The <op> must be one of the operators described by opMask.
523**
drh3b48e8c2013-06-12 20:18:16 +0000524** If the search is for X and the WHERE clause contains terms of the
525** form X=Y then this routine might also return terms of the form
526** "Y <op> <expr>". The number of levels of transitivity is limited,
527** but is enough to handle most commonly occurring SQL statements.
528**
drh1c8148f2013-05-04 20:25:23 +0000529** If X is not the INTEGER PRIMARY KEY then X must be compatible with
530** index pIdx.
531*/
danb2cfc142013-07-05 11:10:54 +0000532static WhereTerm *whereScanInit(
drh1c8148f2013-05-04 20:25:23 +0000533 WhereScan *pScan, /* The WhereScan object being initialized */
534 WhereClause *pWC, /* The WHERE clause to be scanned */
535 int iCur, /* Cursor to scan for */
536 int iColumn, /* Column to scan for */
537 u32 opMask, /* Operator(s) to scan for */
538 Index *pIdx /* Must be compatible with this index */
539){
540 int j;
541
drhe9d935a2013-06-05 16:19:59 +0000542 /* memset(pScan, 0, sizeof(*pScan)); */
drh1c8148f2013-05-04 20:25:23 +0000543 pScan->pOrigWC = pWC;
544 pScan->pWC = pWC;
545 if( pIdx && iColumn>=0 ){
546 pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
547 for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
dan39129ce2014-06-30 15:23:57 +0000548 if( NEVER(j>pIdx->nColumn) ) return 0;
drh1c8148f2013-05-04 20:25:23 +0000549 }
550 pScan->zCollName = pIdx->azColl[j];
drhe9d935a2013-06-05 16:19:59 +0000551 }else{
552 pScan->idxaff = 0;
553 pScan->zCollName = 0;
drh1c8148f2013-05-04 20:25:23 +0000554 }
555 pScan->opMask = opMask;
drhe9d935a2013-06-05 16:19:59 +0000556 pScan->k = 0;
drh1c8148f2013-05-04 20:25:23 +0000557 pScan->aEquiv[0] = iCur;
558 pScan->aEquiv[1] = iColumn;
559 pScan->nEquiv = 2;
560 pScan->iEquiv = 2;
561 return whereScanNext(pScan);
562}
563
564/*
drhfe05af82005-07-21 03:14:59 +0000565** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
566** where X is a reference to the iColumn of table iCur and <op> is one of
567** the WO_xx operator codes specified by the op parameter.
568** Return a pointer to the term. Return 0 if not found.
drh58eb1c02013-01-17 00:08:42 +0000569**
570** The term returned might by Y=<expr> if there is another constraint in
571** the WHERE clause that specifies that X=Y. Any such constraints will be
572** identified by the WO_EQUIV bit in the pTerm->eOperator field. The
573** aEquiv[] array holds X and all its equivalents, with each SQL variable
574** taking up two slots in aEquiv[]. The first slot is for the cursor number
575** and the second is for the column number. There are 22 slots in aEquiv[]
576** so that means we can look for X plus up to 10 other equivalent values.
577** Hence a search for X will return <expr> if X=A1 and A1=A2 and A2=A3
578** and ... and A9=A10 and A10=<expr>.
579**
580** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
581** then try for the one with no dependencies on <expr> - in other words where
582** <expr> is a constant expression of some kind. Only return entries of
583** the form "X <op> Y" where Y is a column in another table if no terms of
drh459f63e2013-03-06 01:55:27 +0000584** the form "X <op> <const-expr>" exist. If no terms with a constant RHS
585** exist, try to return a term that does not use WO_EQUIV.
drhfe05af82005-07-21 03:14:59 +0000586*/
587static WhereTerm *findTerm(
588 WhereClause *pWC, /* The WHERE clause to be searched */
589 int iCur, /* Cursor number of LHS */
590 int iColumn, /* Column number of LHS */
591 Bitmask notReady, /* RHS must not overlap with this mask */
drhec1724e2008-12-09 01:32:03 +0000592 u32 op, /* Mask of WO_xx values describing operator */
drhfe05af82005-07-21 03:14:59 +0000593 Index *pIdx /* Must be compatible with this index, if not NULL */
594){
drh1c8148f2013-05-04 20:25:23 +0000595 WhereTerm *pResult = 0;
596 WhereTerm *p;
597 WhereScan scan;
drh7a5bcc02013-01-16 17:08:58 +0000598
drh1c8148f2013-05-04 20:25:23 +0000599 p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
drhe8d0c612015-05-14 01:05:25 +0000600 op &= WO_EQ|WO_IS;
drh1c8148f2013-05-04 20:25:23 +0000601 while( p ){
602 if( (p->prereqRight & notReady)==0 ){
drhe8d0c612015-05-14 01:05:25 +0000603 if( p->prereqRight==0 && (p->eOperator&op)!=0 ){
604 testcase( p->eOperator & WO_IS );
drh1c8148f2013-05-04 20:25:23 +0000605 return p;
drhfe05af82005-07-21 03:14:59 +0000606 }
drh1c8148f2013-05-04 20:25:23 +0000607 if( pResult==0 ) pResult = p;
drhfe05af82005-07-21 03:14:59 +0000608 }
drh1c8148f2013-05-04 20:25:23 +0000609 p = whereScanNext(&scan);
drhfe05af82005-07-21 03:14:59 +0000610 }
drh7a5bcc02013-01-16 17:08:58 +0000611 return pResult;
drhfe05af82005-07-21 03:14:59 +0000612}
613
drh6c30be82005-07-29 15:10:17 +0000614/* Forward reference */
drh7b4fc6a2007-02-06 13:26:32 +0000615static void exprAnalyze(SrcList*, WhereClause*, int);
drh6c30be82005-07-29 15:10:17 +0000616
617/*
618** Call exprAnalyze on all terms in a WHERE clause.
drh6c30be82005-07-29 15:10:17 +0000619*/
620static void exprAnalyzeAll(
621 SrcList *pTabList, /* the FROM clause */
drh6c30be82005-07-29 15:10:17 +0000622 WhereClause *pWC /* the WHERE clause to be analyzed */
623){
drh6c30be82005-07-29 15:10:17 +0000624 int i;
drh9eb20282005-08-24 03:52:18 +0000625 for(i=pWC->nTerm-1; i>=0; i--){
drh7b4fc6a2007-02-06 13:26:32 +0000626 exprAnalyze(pTabList, pWC, i);
drh6c30be82005-07-29 15:10:17 +0000627 }
628}
629
drhd2687b72005-08-12 22:56:09 +0000630#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
631/*
632** Check to see if the given expression is a LIKE or GLOB operator that
633** can be optimized using inequality constraints. Return TRUE if it is
634** so and false if not.
635**
636** In order for the operator to be optimizible, the RHS must be a string
drhf07cf6e2015-03-06 16:45:16 +0000637** literal that does not begin with a wildcard. The LHS must be a column
638** that may only be NULL, a string, or a BLOB, never a number. (This means
639** that virtual tables cannot participate in the LIKE optimization.) If the
640** collating sequence for the column on the LHS must be appropriate for
641** the operator.
drhd2687b72005-08-12 22:56:09 +0000642*/
643static int isLikeOrGlob(
drh7d10d5a2008-08-20 16:35:10 +0000644 Parse *pParse, /* Parsing and code generating context */
drhd2687b72005-08-12 22:56:09 +0000645 Expr *pExpr, /* Test this expression */
dan937d0de2009-10-15 18:35:38 +0000646 Expr **ppPrefix, /* Pointer to TK_STRING expression with pattern prefix */
drh9f504ea2008-02-23 21:55:39 +0000647 int *pisComplete, /* True if the only wildcard is % in the last character */
648 int *pnoCase /* True if uppercase is equivalent to lowercase */
drhd2687b72005-08-12 22:56:09 +0000649){
dan937d0de2009-10-15 18:35:38 +0000650 const char *z = 0; /* String on RHS of LIKE operator */
drh5bd98ae2009-01-07 18:24:03 +0000651 Expr *pRight, *pLeft; /* Right and left size of LIKE operator */
652 ExprList *pList; /* List of operands to the LIKE operator */
653 int c; /* One character in z[] */
654 int cnt; /* Number of non-wildcard prefix characters */
655 char wc[3]; /* Wildcard characters */
drh5bd98ae2009-01-07 18:24:03 +0000656 sqlite3 *db = pParse->db; /* Database connection */
dan937d0de2009-10-15 18:35:38 +0000657 sqlite3_value *pVal = 0;
658 int op; /* Opcode of pRight */
drhd64fe2f2005-08-28 17:00:23 +0000659
drh9f504ea2008-02-23 21:55:39 +0000660 if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
drhd2687b72005-08-12 22:56:09 +0000661 return 0;
662 }
drh9f504ea2008-02-23 21:55:39 +0000663#ifdef SQLITE_EBCDIC
664 if( *pnoCase ) return 0;
665#endif
danielk19776ab3a2e2009-02-19 14:39:25 +0000666 pList = pExpr->x.pList;
drh55ef4d92005-08-14 01:20:37 +0000667 pLeft = pList->a[1].pExpr;
danc68939e2012-03-29 14:29:07 +0000668 if( pLeft->op!=TK_COLUMN
669 || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
drhf07cf6e2015-03-06 16:45:16 +0000670 || IsVirtual(pLeft->pTab) /* Value might be numeric */
danc68939e2012-03-29 14:29:07 +0000671 ){
drhd91ca492009-10-22 20:50:36 +0000672 /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
673 ** be the name of an indexed column with TEXT affinity. */
drhd2687b72005-08-12 22:56:09 +0000674 return 0;
675 }
drhd91ca492009-10-22 20:50:36 +0000676 assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
dan937d0de2009-10-15 18:35:38 +0000677
drh6ade4532014-01-16 15:31:41 +0000678 pRight = sqlite3ExprSkipCollate(pList->a[0].pExpr);
dan937d0de2009-10-15 18:35:38 +0000679 op = pRight->op;
dan937d0de2009-10-15 18:35:38 +0000680 if( op==TK_VARIABLE ){
681 Vdbe *pReprepare = pParse->pReprepare;
drha7044002010-09-14 18:22:59 +0000682 int iCol = pRight->iColumn;
drhcf0fd4a2013-08-01 12:21:58 +0000683 pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_NONE);
dan937d0de2009-10-15 18:35:38 +0000684 if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
685 z = (char *)sqlite3_value_text(pVal);
686 }
drhf9b22ca2011-10-21 16:47:31 +0000687 sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
dan937d0de2009-10-15 18:35:38 +0000688 assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
689 }else if( op==TK_STRING ){
690 z = pRight->u.zToken;
691 }
692 if( z ){
shane85095702009-06-15 16:27:08 +0000693 cnt = 0;
drhb7916a72009-05-27 10:31:29 +0000694 while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
drh24fb6272009-05-01 21:13:36 +0000695 cnt++;
696 }
drh93ee23c2010-07-22 12:33:57 +0000697 if( cnt!=0 && 255!=(u8)z[cnt-1] ){
dan937d0de2009-10-15 18:35:38 +0000698 Expr *pPrefix;
drh93ee23c2010-07-22 12:33:57 +0000699 *pisComplete = c==wc[0] && z[cnt+1]==0;
dan937d0de2009-10-15 18:35:38 +0000700 pPrefix = sqlite3Expr(db, TK_STRING, z);
701 if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
702 *ppPrefix = pPrefix;
703 if( op==TK_VARIABLE ){
704 Vdbe *v = pParse->pVdbe;
drhf9b22ca2011-10-21 16:47:31 +0000705 sqlite3VdbeSetVarmask(v, pRight->iColumn);
dan937d0de2009-10-15 18:35:38 +0000706 if( *pisComplete && pRight->u.zToken[1] ){
707 /* If the rhs of the LIKE expression is a variable, and the current
708 ** value of the variable means there is no need to invoke the LIKE
709 ** function, then no OP_Variable will be added to the program.
710 ** This causes problems for the sqlite3_bind_parameter_name()
peter.d.reid60ec9142014-09-06 16:39:46 +0000711 ** API. To work around them, add a dummy OP_Variable here.
drhbec451f2009-10-17 13:13:02 +0000712 */
713 int r1 = sqlite3GetTempReg(pParse);
714 sqlite3ExprCodeTarget(pParse, pRight, r1);
dan937d0de2009-10-15 18:35:38 +0000715 sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
drhbec451f2009-10-17 13:13:02 +0000716 sqlite3ReleaseTempReg(pParse, r1);
dan937d0de2009-10-15 18:35:38 +0000717 }
718 }
719 }else{
720 z = 0;
shane85095702009-06-15 16:27:08 +0000721 }
drhf998b732007-11-26 13:36:00 +0000722 }
dan937d0de2009-10-15 18:35:38 +0000723
724 sqlite3ValueFree(pVal);
725 return (z!=0);
drhd2687b72005-08-12 22:56:09 +0000726}
727#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
728
drhedb193b2006-06-27 13:20:21 +0000729
730#ifndef SQLITE_OMIT_VIRTUALTABLE
drhfe05af82005-07-21 03:14:59 +0000731/*
drh7f375902006-06-13 17:38:59 +0000732** Check to see if the given expression is of the form
733**
734** column MATCH expr
735**
736** If it is then return TRUE. If not, return FALSE.
737*/
738static int isMatchOfColumn(
739 Expr *pExpr /* Test this expression */
740){
741 ExprList *pList;
742
743 if( pExpr->op!=TK_FUNCTION ){
744 return 0;
745 }
drh33e619f2009-05-28 01:00:55 +0000746 if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
drh7f375902006-06-13 17:38:59 +0000747 return 0;
748 }
danielk19776ab3a2e2009-02-19 14:39:25 +0000749 pList = pExpr->x.pList;
drh7f375902006-06-13 17:38:59 +0000750 if( pList->nExpr!=2 ){
751 return 0;
752 }
753 if( pList->a[1].pExpr->op != TK_COLUMN ){
754 return 0;
755 }
756 return 1;
757}
drhedb193b2006-06-27 13:20:21 +0000758#endif /* SQLITE_OMIT_VIRTUALTABLE */
drh7f375902006-06-13 17:38:59 +0000759
760/*
drh54a167d2005-11-26 14:08:07 +0000761** If the pBase expression originated in the ON or USING clause of
762** a join, then transfer the appropriate markings over to derived.
763*/
764static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
drhd41d39f2013-08-28 16:27:01 +0000765 if( pDerived ){
766 pDerived->flags |= pBase->flags & EP_FromJoin;
767 pDerived->iRightJoinTable = pBase->iRightJoinTable;
768 }
drh54a167d2005-11-26 14:08:07 +0000769}
770
drh9769efc2014-10-24 14:32:21 +0000771/*
772** Mark term iChild as being a child of term iParent
773*/
774static void markTermAsChild(WhereClause *pWC, int iChild, int iParent){
775 pWC->a[iChild].iParent = iParent;
776 pWC->a[iChild].truthProb = pWC->a[iParent].truthProb;
777 pWC->a[iParent].nChild++;
778}
779
drh84266362015-03-16 12:13:31 +0000780/*
781** Return the N-th AND-connected subterm of pTerm. Or if pTerm is not
782** a conjunction, then return just pTerm when N==0. If N is exceeds
783** the number of available subterms, return NULL.
784*/
785static WhereTerm *whereNthSubterm(WhereTerm *pTerm, int N){
786 if( pTerm->eOperator!=WO_AND ){
787 return N==0 ? pTerm : 0;
788 }
789 if( N<pTerm->u.pAndInfo->wc.nTerm ){
790 return &pTerm->u.pAndInfo->wc.a[N];
791 }
792 return 0;
793}
794
795/*
796** Subterms pOne and pTwo are contained within WHERE clause pWC. The
797** two subterms are in disjunction - they are OR-ed together.
798**
799** If these two terms are both of the form: "A op B" with the same
800** A and B values but different operators and if the operators are
801** compatible (if one is = and the other is <, for example) then
drhc03acf22015-03-16 13:12:34 +0000802** add a new virtual AND term to pWC that is the combination of the
drh84266362015-03-16 12:13:31 +0000803** two.
804**
805** Some examples:
806**
807** x<y OR x=y --> x<=y
808** x=y OR x=y --> x=y
809** x<=y OR x<y --> x<=y
810**
811** The following is NOT generated:
812**
813** x<y OR x>y --> x!=y
814*/
815static void whereCombineDisjuncts(
816 SrcList *pSrc, /* the FROM clause */
817 WhereClause *pWC, /* The complete WHERE clause */
818 WhereTerm *pOne, /* First disjunct */
819 WhereTerm *pTwo /* Second disjunct */
820){
821 u16 eOp = pOne->eOperator | pTwo->eOperator;
822 sqlite3 *db; /* Database connection (for malloc) */
823 Expr *pNew; /* New virtual expression */
824 int op; /* Operator for the combined expression */
825 int idxNew; /* Index in pWC of the next virtual term */
826
827 if( (pOne->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
828 if( (pTwo->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
829 if( (eOp & (WO_EQ|WO_LT|WO_LE))!=eOp
830 && (eOp & (WO_EQ|WO_GT|WO_GE))!=eOp ) return;
831 assert( pOne->pExpr->pLeft!=0 && pOne->pExpr->pRight!=0 );
832 assert( pTwo->pExpr->pLeft!=0 && pTwo->pExpr->pRight!=0 );
833 if( sqlite3ExprCompare(pOne->pExpr->pLeft, pTwo->pExpr->pLeft, -1) ) return;
834 if( sqlite3ExprCompare(pOne->pExpr->pRight, pTwo->pExpr->pRight, -1) )return;
835 /* If we reach this point, it means the two subterms can be combined */
836 if( (eOp & (eOp-1))!=0 ){
837 if( eOp & (WO_LT|WO_LE) ){
838 eOp = WO_LE;
839 }else{
840 assert( eOp & (WO_GT|WO_GE) );
841 eOp = WO_GE;
842 }
843 }
844 db = pWC->pWInfo->pParse->db;
845 pNew = sqlite3ExprDup(db, pOne->pExpr, 0);
846 if( pNew==0 ) return;
847 for(op=TK_EQ; eOp!=(WO_EQ<<(op-TK_EQ)); op++){ assert( op<TK_GE ); }
848 pNew->op = op;
849 idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
850 exprAnalyze(pSrc, pWC, idxNew);
851}
852
drh3e355802007-02-23 23:13:33 +0000853#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
854/*
drh1a58fe02008-12-20 02:06:13 +0000855** Analyze a term that consists of two or more OR-connected
856** subterms. So in:
drh3e355802007-02-23 23:13:33 +0000857**
drh1a58fe02008-12-20 02:06:13 +0000858** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
859** ^^^^^^^^^^^^^^^^^^^^
drh3e355802007-02-23 23:13:33 +0000860**
drh1a58fe02008-12-20 02:06:13 +0000861** This routine analyzes terms such as the middle term in the above example.
862** A WhereOrTerm object is computed and attached to the term under
863** analysis, regardless of the outcome of the analysis. Hence:
drh3e355802007-02-23 23:13:33 +0000864**
drh1a58fe02008-12-20 02:06:13 +0000865** WhereTerm.wtFlags |= TERM_ORINFO
866** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object
drh3e355802007-02-23 23:13:33 +0000867**
drh1a58fe02008-12-20 02:06:13 +0000868** The term being analyzed must have two or more of OR-connected subterms.
danielk1977fdc40192008-12-29 18:33:32 +0000869** A single subterm might be a set of AND-connected sub-subterms.
drh1a58fe02008-12-20 02:06:13 +0000870** Examples of terms under analysis:
drh3e355802007-02-23 23:13:33 +0000871**
drh1a58fe02008-12-20 02:06:13 +0000872** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
873** (B) x=expr1 OR expr2=x OR x=expr3
874** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
875** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
876** (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 +0000877** (F) x>A OR (x=A AND y>=B)
drh3e355802007-02-23 23:13:33 +0000878**
drh1a58fe02008-12-20 02:06:13 +0000879** CASE 1:
880**
drhc3e552f2013-02-08 16:04:19 +0000881** If all subterms are of the form T.C=expr for some single column of C and
drh1a58fe02008-12-20 02:06:13 +0000882** a single table T (as shown in example B above) then create a new virtual
883** term that is an equivalent IN expression. In other words, if the term
884** being analyzed is:
885**
886** x = expr1 OR expr2 = x OR x = expr3
887**
888** then create a new virtual term like this:
889**
890** x IN (expr1,expr2,expr3)
891**
892** CASE 2:
893**
drhc03acf22015-03-16 13:12:34 +0000894** If there are exactly two disjuncts one side has x>A and the other side
895** has x=A (for the same x and A) then add a new virtual conjunct term to the
896** WHERE clause of the form "x>=A". Example:
897**
898** x>A OR (x=A AND y>B) adds: x>=A
899**
900** The added conjunct can sometimes be helpful in query planning.
drh84266362015-03-16 12:13:31 +0000901**
902** CASE 3:
903**
drh1a58fe02008-12-20 02:06:13 +0000904** If all subterms are indexable by a single table T, then set
905**
906** WhereTerm.eOperator = WO_OR
907** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T
908**
909** A subterm is "indexable" if it is of the form
910** "T.C <op> <expr>" where C is any column of table T and
911** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
912** A subterm is also indexable if it is an AND of two or more
913** subsubterms at least one of which is indexable. Indexable AND
914** subterms have their eOperator set to WO_AND and they have
915** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
916**
917** From another point of view, "indexable" means that the subterm could
918** potentially be used with an index if an appropriate index exists.
919** This analysis does not consider whether or not the index exists; that
drh4a6fc352013-08-07 01:18:38 +0000920** is decided elsewhere. This analysis only looks at whether subterms
921** appropriate for indexing exist.
drh1a58fe02008-12-20 02:06:13 +0000922**
drh4a6fc352013-08-07 01:18:38 +0000923** All examples A through E above satisfy case 2. But if a term
peter.d.reid60ec9142014-09-06 16:39:46 +0000924** also satisfies case 1 (such as B) we know that the optimizer will
drh1a58fe02008-12-20 02:06:13 +0000925** always prefer case 1, so in that case we pretend that case 2 is not
926** satisfied.
927**
928** It might be the case that multiple tables are indexable. For example,
929** (E) above is indexable on tables P, Q, and R.
930**
931** Terms that satisfy case 2 are candidates for lookup by using
932** separate indices to find rowids for each subterm and composing
933** the union of all rowids using a RowSet object. This is similar
934** to "bitmap indices" in other database engines.
935**
936** OTHERWISE:
937**
938** If neither case 1 nor case 2 apply, then leave the eOperator set to
939** zero. This term is not useful for search.
drh3e355802007-02-23 23:13:33 +0000940*/
drh1a58fe02008-12-20 02:06:13 +0000941static void exprAnalyzeOrTerm(
942 SrcList *pSrc, /* the FROM clause */
943 WhereClause *pWC, /* the complete WHERE clause */
944 int idxTerm /* Index of the OR-term to be analyzed */
945){
drh70d18342013-06-06 19:16:33 +0000946 WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
947 Parse *pParse = pWInfo->pParse; /* Parser context */
drh1a58fe02008-12-20 02:06:13 +0000948 sqlite3 *db = pParse->db; /* Database connection */
949 WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */
950 Expr *pExpr = pTerm->pExpr; /* The expression of the term */
drh1a58fe02008-12-20 02:06:13 +0000951 int i; /* Loop counters */
952 WhereClause *pOrWc; /* Breakup of pTerm into subterms */
953 WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */
954 WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */
955 Bitmask chngToIN; /* Tables that might satisfy case 1 */
956 Bitmask indexable; /* Tables that are indexable, satisfying case 2 */
drh3e355802007-02-23 23:13:33 +0000957
drh1a58fe02008-12-20 02:06:13 +0000958 /*
959 ** Break the OR clause into its separate subterms. The subterms are
960 ** stored in a WhereClause structure containing within the WhereOrInfo
961 ** object that is attached to the original OR clause term.
962 */
963 assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
964 assert( pExpr->op==TK_OR );
drh954701a2008-12-29 23:45:07 +0000965 pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
drh1a58fe02008-12-20 02:06:13 +0000966 if( pOrInfo==0 ) return;
967 pTerm->wtFlags |= TERM_ORINFO;
968 pOrWc = &pOrInfo->wc;
drh70d18342013-06-06 19:16:33 +0000969 whereClauseInit(pOrWc, pWInfo);
drh1a58fe02008-12-20 02:06:13 +0000970 whereSplit(pOrWc, pExpr, TK_OR);
971 exprAnalyzeAll(pSrc, pOrWc);
972 if( db->mallocFailed ) return;
973 assert( pOrWc->nTerm>=2 );
974
975 /*
976 ** Compute the set of tables that might satisfy cases 1 or 2.
977 */
danielk1977e672c8e2009-05-22 15:43:26 +0000978 indexable = ~(Bitmask)0;
drhc3e552f2013-02-08 16:04:19 +0000979 chngToIN = ~(Bitmask)0;
drh1a58fe02008-12-20 02:06:13 +0000980 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
981 if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
drh29435252008-12-28 18:35:08 +0000982 WhereAndInfo *pAndInfo;
drh29435252008-12-28 18:35:08 +0000983 assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
drh1a58fe02008-12-20 02:06:13 +0000984 chngToIN = 0;
drh29435252008-12-28 18:35:08 +0000985 pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
986 if( pAndInfo ){
987 WhereClause *pAndWC;
988 WhereTerm *pAndTerm;
989 int j;
990 Bitmask b = 0;
991 pOrTerm->u.pAndInfo = pAndInfo;
992 pOrTerm->wtFlags |= TERM_ANDINFO;
993 pOrTerm->eOperator = WO_AND;
994 pAndWC = &pAndInfo->wc;
drh70d18342013-06-06 19:16:33 +0000995 whereClauseInit(pAndWC, pWC->pWInfo);
drh29435252008-12-28 18:35:08 +0000996 whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
997 exprAnalyzeAll(pSrc, pAndWC);
drh8871ef52011-10-07 13:33:10 +0000998 pAndWC->pOuter = pWC;
drh7c2fbde2009-01-07 20:58:57 +0000999 testcase( db->mallocFailed );
drh96c7a7d2009-01-10 15:34:12 +00001000 if( !db->mallocFailed ){
1001 for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
1002 assert( pAndTerm->pExpr );
1003 if( allowedOp(pAndTerm->pExpr->op) ){
drh70d18342013-06-06 19:16:33 +00001004 b |= getMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
drh96c7a7d2009-01-10 15:34:12 +00001005 }
drh29435252008-12-28 18:35:08 +00001006 }
1007 }
1008 indexable &= b;
1009 }
drh1a58fe02008-12-20 02:06:13 +00001010 }else if( pOrTerm->wtFlags & TERM_COPIED ){
1011 /* Skip this term for now. We revisit it when we process the
1012 ** corresponding TERM_VIRTUAL term */
1013 }else{
1014 Bitmask b;
drh70d18342013-06-06 19:16:33 +00001015 b = getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
drh1a58fe02008-12-20 02:06:13 +00001016 if( pOrTerm->wtFlags & TERM_VIRTUAL ){
1017 WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
drh70d18342013-06-06 19:16:33 +00001018 b |= getMask(&pWInfo->sMaskSet, pOther->leftCursor);
drh1a58fe02008-12-20 02:06:13 +00001019 }
1020 indexable &= b;
drh7a5bcc02013-01-16 17:08:58 +00001021 if( (pOrTerm->eOperator & WO_EQ)==0 ){
drh1a58fe02008-12-20 02:06:13 +00001022 chngToIN = 0;
1023 }else{
1024 chngToIN &= b;
1025 }
1026 }
drh3e355802007-02-23 23:13:33 +00001027 }
drh1a58fe02008-12-20 02:06:13 +00001028
1029 /*
drh84266362015-03-16 12:13:31 +00001030 ** Record the set of tables that satisfy case 3. The set might be
drh111a6a72008-12-21 03:51:16 +00001031 ** empty.
drh1a58fe02008-12-20 02:06:13 +00001032 */
1033 pOrInfo->indexable = indexable;
drh111a6a72008-12-21 03:51:16 +00001034 pTerm->eOperator = indexable==0 ? 0 : WO_OR;
drh1a58fe02008-12-20 02:06:13 +00001035
drh84266362015-03-16 12:13:31 +00001036 /* For a two-way OR, attempt to implementation case 2.
1037 */
1038 if( indexable && pOrWc->nTerm==2 ){
1039 int iOne = 0;
1040 WhereTerm *pOne;
1041 while( (pOne = whereNthSubterm(&pOrWc->a[0],iOne++))!=0 ){
1042 int iTwo = 0;
1043 WhereTerm *pTwo;
1044 while( (pTwo = whereNthSubterm(&pOrWc->a[1],iTwo++))!=0 ){
1045 whereCombineDisjuncts(pSrc, pWC, pOne, pTwo);
1046 }
1047 }
1048 }
1049
drh1a58fe02008-12-20 02:06:13 +00001050 /*
1051 ** chngToIN holds a set of tables that *might* satisfy case 1. But
1052 ** we have to do some additional checking to see if case 1 really
1053 ** is satisfied.
drh4e8be3b2009-06-08 17:11:08 +00001054 **
1055 ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means
1056 ** that there is no possibility of transforming the OR clause into an
1057 ** IN operator because one or more terms in the OR clause contain
1058 ** something other than == on a column in the single table. The 1-bit
1059 ** case means that every term of the OR clause is of the form
1060 ** "table.column=expr" for some single table. The one bit that is set
1061 ** will correspond to the common table. We still need to check to make
1062 ** sure the same column is used on all terms. The 2-bit case is when
1063 ** the all terms are of the form "table1.column=table2.column". It
1064 ** might be possible to form an IN operator with either table1.column
1065 ** or table2.column as the LHS if either is common to every term of
1066 ** the OR clause.
1067 **
1068 ** Note that terms of the form "table.column1=table.column2" (the
1069 ** same table on both sizes of the ==) cannot be optimized.
drh1a58fe02008-12-20 02:06:13 +00001070 */
1071 if( chngToIN ){
1072 int okToChngToIN = 0; /* True if the conversion to IN is valid */
1073 int iColumn = -1; /* Column index on lhs of IN operator */
shane63207ab2009-02-04 01:49:30 +00001074 int iCursor = -1; /* Table cursor common to all terms */
drh1a58fe02008-12-20 02:06:13 +00001075 int j = 0; /* Loop counter */
1076
1077 /* Search for a table and column that appears on one side or the
1078 ** other of the == operator in every subterm. That table and column
1079 ** will be recorded in iCursor and iColumn. There might not be any
1080 ** such table and column. Set okToChngToIN if an appropriate table
1081 ** and column is found but leave okToChngToIN false if not found.
1082 */
1083 for(j=0; j<2 && !okToChngToIN; j++){
1084 pOrTerm = pOrWc->a;
1085 for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
drh7a5bcc02013-01-16 17:08:58 +00001086 assert( pOrTerm->eOperator & WO_EQ );
drh1a58fe02008-12-20 02:06:13 +00001087 pOrTerm->wtFlags &= ~TERM_OR_OK;
drh4e8be3b2009-06-08 17:11:08 +00001088 if( pOrTerm->leftCursor==iCursor ){
1089 /* This is the 2-bit case and we are on the second iteration and
1090 ** current term is from the first iteration. So skip this term. */
1091 assert( j==1 );
1092 continue;
1093 }
drh70d18342013-06-06 19:16:33 +00001094 if( (chngToIN & getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor))==0 ){
drh4e8be3b2009-06-08 17:11:08 +00001095 /* This term must be of the form t1.a==t2.b where t2 is in the
peter.d.reid60ec9142014-09-06 16:39:46 +00001096 ** chngToIN set but t1 is not. This term will be either preceded
drh4e8be3b2009-06-08 17:11:08 +00001097 ** or follwed by an inverted copy (t2.b==t1.a). Skip this term
1098 ** and use its inversion. */
1099 testcase( pOrTerm->wtFlags & TERM_COPIED );
1100 testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
1101 assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
1102 continue;
1103 }
drh1a58fe02008-12-20 02:06:13 +00001104 iColumn = pOrTerm->u.leftColumn;
1105 iCursor = pOrTerm->leftCursor;
1106 break;
1107 }
1108 if( i<0 ){
drh4e8be3b2009-06-08 17:11:08 +00001109 /* No candidate table+column was found. This can only occur
1110 ** on the second iteration */
drh1a58fe02008-12-20 02:06:13 +00001111 assert( j==1 );
drh7a5bcc02013-01-16 17:08:58 +00001112 assert( IsPowerOfTwo(chngToIN) );
drh70d18342013-06-06 19:16:33 +00001113 assert( chngToIN==getMask(&pWInfo->sMaskSet, iCursor) );
drh1a58fe02008-12-20 02:06:13 +00001114 break;
1115 }
drh4e8be3b2009-06-08 17:11:08 +00001116 testcase( j==1 );
1117
1118 /* We have found a candidate table and column. Check to see if that
1119 ** table and column is common to every term in the OR clause */
drh1a58fe02008-12-20 02:06:13 +00001120 okToChngToIN = 1;
1121 for(; i>=0 && okToChngToIN; i--, pOrTerm++){
drh7a5bcc02013-01-16 17:08:58 +00001122 assert( pOrTerm->eOperator & WO_EQ );
drh1a58fe02008-12-20 02:06:13 +00001123 if( pOrTerm->leftCursor!=iCursor ){
1124 pOrTerm->wtFlags &= ~TERM_OR_OK;
1125 }else if( pOrTerm->u.leftColumn!=iColumn ){
1126 okToChngToIN = 0;
1127 }else{
1128 int affLeft, affRight;
1129 /* If the right-hand side is also a column, then the affinities
1130 ** of both right and left sides must be such that no type
1131 ** conversions are required on the right. (Ticket #2249)
1132 */
1133 affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
1134 affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
1135 if( affRight!=0 && affRight!=affLeft ){
1136 okToChngToIN = 0;
1137 }else{
1138 pOrTerm->wtFlags |= TERM_OR_OK;
1139 }
1140 }
1141 }
1142 }
1143
1144 /* At this point, okToChngToIN is true if original pTerm satisfies
1145 ** case 1. In that case, construct a new virtual term that is
1146 ** pTerm converted into an IN operator.
1147 */
1148 if( okToChngToIN ){
1149 Expr *pDup; /* A transient duplicate expression */
1150 ExprList *pList = 0; /* The RHS of the IN operator */
1151 Expr *pLeft = 0; /* The LHS of the IN operator */
1152 Expr *pNew; /* The complete IN operator */
1153
1154 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
1155 if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
drh7a5bcc02013-01-16 17:08:58 +00001156 assert( pOrTerm->eOperator & WO_EQ );
drh1a58fe02008-12-20 02:06:13 +00001157 assert( pOrTerm->leftCursor==iCursor );
1158 assert( pOrTerm->u.leftColumn==iColumn );
danielk19776ab3a2e2009-02-19 14:39:25 +00001159 pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
drh70d18342013-06-06 19:16:33 +00001160 pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
drh1a58fe02008-12-20 02:06:13 +00001161 pLeft = pOrTerm->pExpr->pLeft;
1162 }
1163 assert( pLeft!=0 );
danielk19776ab3a2e2009-02-19 14:39:25 +00001164 pDup = sqlite3ExprDup(db, pLeft, 0);
drhb7916a72009-05-27 10:31:29 +00001165 pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
drh1a58fe02008-12-20 02:06:13 +00001166 if( pNew ){
1167 int idxNew;
1168 transferJoinMarkings(pNew, pExpr);
danielk19776ab3a2e2009-02-19 14:39:25 +00001169 assert( !ExprHasProperty(pNew, EP_xIsSelect) );
1170 pNew->x.pList = pList;
drh1a58fe02008-12-20 02:06:13 +00001171 idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
1172 testcase( idxNew==0 );
1173 exprAnalyze(pSrc, pWC, idxNew);
1174 pTerm = &pWC->a[idxTerm];
drh9769efc2014-10-24 14:32:21 +00001175 markTermAsChild(pWC, idxNew, idxTerm);
drh1a58fe02008-12-20 02:06:13 +00001176 }else{
1177 sqlite3ExprListDelete(db, pList);
1178 }
drh84266362015-03-16 12:13:31 +00001179 pTerm->eOperator = WO_NOOP; /* case 1 trumps case 3 */
drh1a58fe02008-12-20 02:06:13 +00001180 }
drh3e355802007-02-23 23:13:33 +00001181 }
drh3e355802007-02-23 23:13:33 +00001182}
1183#endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
drh54a167d2005-11-26 14:08:07 +00001184
drh7a5bcc02013-01-16 17:08:58 +00001185/*
drh0aa74ed2005-07-16 13:33:20 +00001186** The input to this routine is an WhereTerm structure with only the
drh51147ba2005-07-23 22:59:55 +00001187** "pExpr" field filled in. The job of this routine is to analyze the
drh0aa74ed2005-07-16 13:33:20 +00001188** subexpression and populate all the other fields of the WhereTerm
drh75897232000-05-29 14:26:00 +00001189** structure.
drh51147ba2005-07-23 22:59:55 +00001190**
1191** If the expression is of the form "<expr> <op> X" it gets commuted
drh1a58fe02008-12-20 02:06:13 +00001192** to the standard form of "X <op> <expr>".
1193**
1194** If the expression is of the form "X <op> Y" where both X and Y are
1195** columns, then the original expression is unchanged and a new virtual
1196** term of the form "Y <op> X" is added to the WHERE clause and
1197** analyzed separately. The original term is marked with TERM_COPIED
1198** and the new term is marked with TERM_DYNAMIC (because it's pExpr
1199** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
1200** is a commuted copy of a prior term.) The original term has nChild=1
1201** and the copy has idxParent set to the index of the original term.
drh75897232000-05-29 14:26:00 +00001202*/
drh0fcef5e2005-07-19 17:38:22 +00001203static void exprAnalyze(
1204 SrcList *pSrc, /* the FROM clause */
drh9eb20282005-08-24 03:52:18 +00001205 WhereClause *pWC, /* the WHERE clause */
1206 int idxTerm /* Index of the term to be analyzed */
drh0fcef5e2005-07-19 17:38:22 +00001207){
drh70d18342013-06-06 19:16:33 +00001208 WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
drh1a58fe02008-12-20 02:06:13 +00001209 WhereTerm *pTerm; /* The term to be analyzed */
drh111a6a72008-12-21 03:51:16 +00001210 WhereMaskSet *pMaskSet; /* Set of table index masks */
drh1a58fe02008-12-20 02:06:13 +00001211 Expr *pExpr; /* The expression to be analyzed */
1212 Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */
1213 Bitmask prereqAll; /* Prerequesites of pExpr */
drh5e767c52010-02-25 04:15:47 +00001214 Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */
drh1d452e12009-11-01 19:26:59 +00001215 Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */
1216 int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */
drha9c18a92015-03-06 20:49:52 +00001217 int noCase = 0; /* uppercase equivalent to lowercase */
drh1a58fe02008-12-20 02:06:13 +00001218 int op; /* Top-level operator. pExpr->op */
drh70d18342013-06-06 19:16:33 +00001219 Parse *pParse = pWInfo->pParse; /* Parsing context */
drh1a58fe02008-12-20 02:06:13 +00001220 sqlite3 *db = pParse->db; /* Database connection */
drh0fcef5e2005-07-19 17:38:22 +00001221
drhf998b732007-11-26 13:36:00 +00001222 if( db->mallocFailed ){
1223 return;
1224 }
1225 pTerm = &pWC->a[idxTerm];
drh70d18342013-06-06 19:16:33 +00001226 pMaskSet = &pWInfo->sMaskSet;
drh7ee751d2012-12-19 15:53:51 +00001227 pExpr = pTerm->pExpr;
1228 assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
drh0fcef5e2005-07-19 17:38:22 +00001229 prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
drh50b39962006-10-28 00:28:09 +00001230 op = pExpr->op;
1231 if( op==TK_IN ){
drhf5b11382005-09-17 13:07:13 +00001232 assert( pExpr->pRight==0 );
danielk19776ab3a2e2009-02-19 14:39:25 +00001233 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
1234 pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
1235 }else{
1236 pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
1237 }
drh50b39962006-10-28 00:28:09 +00001238 }else if( op==TK_ISNULL ){
1239 pTerm->prereqRight = 0;
drhf5b11382005-09-17 13:07:13 +00001240 }else{
1241 pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
1242 }
drh22d6a532005-09-19 21:05:48 +00001243 prereqAll = exprTableUsage(pMaskSet, pExpr);
1244 if( ExprHasProperty(pExpr, EP_FromJoin) ){
drh42165be2008-03-26 14:56:34 +00001245 Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
1246 prereqAll |= x;
drhdafc0ce2008-04-17 19:14:02 +00001247 extraRight = x-1; /* ON clause terms may not be used with an index
1248 ** on left table of a LEFT JOIN. Ticket #3015 */
drh22d6a532005-09-19 21:05:48 +00001249 }
1250 pTerm->prereqAll = prereqAll;
drh0fcef5e2005-07-19 17:38:22 +00001251 pTerm->leftCursor = -1;
drh45b1ee42005-08-02 17:48:22 +00001252 pTerm->iParent = -1;
drhb52076c2006-01-23 13:22:09 +00001253 pTerm->eOperator = 0;
drh738fc792013-01-17 15:05:17 +00001254 if( allowedOp(op) ){
drh7a66da12012-12-07 20:31:11 +00001255 Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
1256 Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
drh738fc792013-01-17 15:05:17 +00001257 u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
drh0fcef5e2005-07-19 17:38:22 +00001258 if( pLeft->op==TK_COLUMN ){
1259 pTerm->leftCursor = pLeft->iTable;
drh700a2262008-12-17 19:22:15 +00001260 pTerm->u.leftColumn = pLeft->iColumn;
drh738fc792013-01-17 15:05:17 +00001261 pTerm->eOperator = operatorMask(op) & opMask;
drh75897232000-05-29 14:26:00 +00001262 }
drh9be18702015-05-13 19:33:41 +00001263 if( op==TK_IS ) pTerm->wtFlags |= TERM_IS;
drh0fcef5e2005-07-19 17:38:22 +00001264 if( pRight && pRight->op==TK_COLUMN ){
1265 WhereTerm *pNew;
1266 Expr *pDup;
drh7a5bcc02013-01-16 17:08:58 +00001267 u16 eExtraOp = 0; /* Extra bits for pNew->eOperator */
drh0fcef5e2005-07-19 17:38:22 +00001268 if( pTerm->leftCursor>=0 ){
drh9eb20282005-08-24 03:52:18 +00001269 int idxNew;
danielk19776ab3a2e2009-02-19 14:39:25 +00001270 pDup = sqlite3ExprDup(db, pExpr, 0);
drh17435752007-08-16 04:30:38 +00001271 if( db->mallocFailed ){
drh633e6d52008-07-28 19:34:53 +00001272 sqlite3ExprDelete(db, pDup);
drh28f45912006-10-18 23:26:38 +00001273 return;
1274 }
drh9eb20282005-08-24 03:52:18 +00001275 idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
1276 if( idxNew==0 ) return;
1277 pNew = &pWC->a[idxNew];
drh9769efc2014-10-24 14:32:21 +00001278 markTermAsChild(pWC, idxNew, idxTerm);
drh9eb20282005-08-24 03:52:18 +00001279 pTerm = &pWC->a[idxTerm];
drh165be382008-12-05 02:36:33 +00001280 pTerm->wtFlags |= TERM_COPIED;
drhee145872015-05-14 13:18:47 +00001281 if( (op==TK_EQ || op==TK_IS)
drheb5bc922013-01-17 16:43:33 +00001282 && !ExprHasProperty(pExpr, EP_FromJoin)
1283 && OptimizationEnabled(db, SQLITE_Transitive)
1284 ){
drh7a5bcc02013-01-16 17:08:58 +00001285 pTerm->eOperator |= WO_EQUIV;
1286 eExtraOp = WO_EQUIV;
1287 }
drh9be18702015-05-13 19:33:41 +00001288 if( op==TK_IS ) pNew->wtFlags |= TERM_IS;
drh0fcef5e2005-07-19 17:38:22 +00001289 }else{
1290 pDup = pExpr;
1291 pNew = pTerm;
1292 }
drh7d10d5a2008-08-20 16:35:10 +00001293 exprCommute(pParse, pDup);
drhfb76f5a2012-12-08 14:16:47 +00001294 pLeft = sqlite3ExprSkipCollate(pDup->pLeft);
drh0fcef5e2005-07-19 17:38:22 +00001295 pNew->leftCursor = pLeft->iTable;
drh700a2262008-12-17 19:22:15 +00001296 pNew->u.leftColumn = pLeft->iColumn;
drh5e767c52010-02-25 04:15:47 +00001297 testcase( (prereqLeft | extraRight) != prereqLeft );
1298 pNew->prereqRight = prereqLeft | extraRight;
drh0fcef5e2005-07-19 17:38:22 +00001299 pNew->prereqAll = prereqAll;
drh738fc792013-01-17 15:05:17 +00001300 pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
drh75897232000-05-29 14:26:00 +00001301 }
1302 }
drhed378002005-07-28 23:12:08 +00001303
drhd2687b72005-08-12 22:56:09 +00001304#ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
drhed378002005-07-28 23:12:08 +00001305 /* If a term is the BETWEEN operator, create two new virtual terms
drh1a58fe02008-12-20 02:06:13 +00001306 ** that define the range that the BETWEEN implements. For example:
1307 **
1308 ** a BETWEEN b AND c
1309 **
1310 ** is converted into:
1311 **
1312 ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
1313 **
1314 ** The two new terms are added onto the end of the WhereClause object.
1315 ** The new terms are "dynamic" and are children of the original BETWEEN
1316 ** term. That means that if the BETWEEN term is coded, the children are
1317 ** skipped. Or, if the children are satisfied by an index, the original
1318 ** BETWEEN term is skipped.
drhed378002005-07-28 23:12:08 +00001319 */
drh29435252008-12-28 18:35:08 +00001320 else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
danielk19776ab3a2e2009-02-19 14:39:25 +00001321 ExprList *pList = pExpr->x.pList;
drhed378002005-07-28 23:12:08 +00001322 int i;
1323 static const u8 ops[] = {TK_GE, TK_LE};
1324 assert( pList!=0 );
1325 assert( pList->nExpr==2 );
1326 for(i=0; i<2; i++){
1327 Expr *pNewExpr;
drh9eb20282005-08-24 03:52:18 +00001328 int idxNew;
drhb7916a72009-05-27 10:31:29 +00001329 pNewExpr = sqlite3PExpr(pParse, ops[i],
1330 sqlite3ExprDup(db, pExpr->pLeft, 0),
danielk19776ab3a2e2009-02-19 14:39:25 +00001331 sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
drhd41d39f2013-08-28 16:27:01 +00001332 transferJoinMarkings(pNewExpr, pExpr);
drh9eb20282005-08-24 03:52:18 +00001333 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
drh6a1e0712008-12-05 15:24:15 +00001334 testcase( idxNew==0 );
drh7b4fc6a2007-02-06 13:26:32 +00001335 exprAnalyze(pSrc, pWC, idxNew);
drh9eb20282005-08-24 03:52:18 +00001336 pTerm = &pWC->a[idxTerm];
drh9769efc2014-10-24 14:32:21 +00001337 markTermAsChild(pWC, idxNew, idxTerm);
drhed378002005-07-28 23:12:08 +00001338 }
drhed378002005-07-28 23:12:08 +00001339 }
drhd2687b72005-08-12 22:56:09 +00001340#endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
drhed378002005-07-28 23:12:08 +00001341
danielk19771576cd92006-01-14 08:02:28 +00001342#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
drh1a58fe02008-12-20 02:06:13 +00001343 /* Analyze a term that is composed of two or more subterms connected by
1344 ** an OR operator.
drh6c30be82005-07-29 15:10:17 +00001345 */
1346 else if( pExpr->op==TK_OR ){
drh29435252008-12-28 18:35:08 +00001347 assert( pWC->op==TK_AND );
drh1a58fe02008-12-20 02:06:13 +00001348 exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
danielk1977f51d1bd2009-07-31 06:14:51 +00001349 pTerm = &pWC->a[idxTerm];
drh6c30be82005-07-29 15:10:17 +00001350 }
drhd2687b72005-08-12 22:56:09 +00001351#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
1352
1353#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
1354 /* Add constraints to reduce the search space on a LIKE or GLOB
1355 ** operator.
drh9f504ea2008-02-23 21:55:39 +00001356 **
drha9c18a92015-03-06 20:49:52 +00001357 ** A like pattern of the form "x LIKE 'aBc%'" is changed into constraints
drh9f504ea2008-02-23 21:55:39 +00001358 **
drha9c18a92015-03-06 20:49:52 +00001359 ** x>='ABC' AND x<'abd' AND x LIKE 'aBc%'
drh9f504ea2008-02-23 21:55:39 +00001360 **
1361 ** The last character of the prefix "abc" is incremented to form the
drha9c18a92015-03-06 20:49:52 +00001362 ** termination condition "abd". If case is not significant (the default
1363 ** for LIKE) then the lower-bound is made all uppercase and the upper-
1364 ** bound is made all lowercase so that the bounds also work when comparing
1365 ** BLOBs.
drhd2687b72005-08-12 22:56:09 +00001366 */
dan937d0de2009-10-15 18:35:38 +00001367 if( pWC->op==TK_AND
1368 && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
1369 ){
drh1d452e12009-11-01 19:26:59 +00001370 Expr *pLeft; /* LHS of LIKE/GLOB operator */
1371 Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */
1372 Expr *pNewExpr1;
1373 Expr *pNewExpr2;
1374 int idxNew1;
1375 int idxNew2;
dan80103fc2015-03-20 08:43:59 +00001376 const char *zCollSeqName; /* Name of collating sequence */
drh8f1a7ed2015-03-06 19:47:38 +00001377 const u16 wtFlags = TERM_LIKEOPT | TERM_VIRTUAL | TERM_DYNAMIC;
drh9eb20282005-08-24 03:52:18 +00001378
danielk19776ab3a2e2009-02-19 14:39:25 +00001379 pLeft = pExpr->x.pList->a[1].pExpr;
danielk19776ab3a2e2009-02-19 14:39:25 +00001380 pStr2 = sqlite3ExprDup(db, pStr1, 0);
drh8f1a7ed2015-03-06 19:47:38 +00001381
1382 /* Convert the lower bound to upper-case and the upper bound to
1383 ** lower-case (upper-case is less than lower-case in ASCII) so that
1384 ** the range constraints also work for BLOBs
1385 */
1386 if( noCase && !pParse->db->mallocFailed ){
1387 int i;
1388 char c;
drha9c18a92015-03-06 20:49:52 +00001389 pTerm->wtFlags |= TERM_LIKE;
drh8f1a7ed2015-03-06 19:47:38 +00001390 for(i=0; (c = pStr1->u.zToken[i])!=0; i++){
1391 pStr1->u.zToken[i] = sqlite3Toupper(c);
1392 pStr2->u.zToken[i] = sqlite3Tolower(c);
1393 }
1394 }
1395
drhf998b732007-11-26 13:36:00 +00001396 if( !db->mallocFailed ){
drh254993e2009-06-08 19:44:36 +00001397 u8 c, *pC; /* Last character before the first wildcard */
dan937d0de2009-10-15 18:35:38 +00001398 pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
drh9f504ea2008-02-23 21:55:39 +00001399 c = *pC;
drh02a50b72008-05-26 18:33:40 +00001400 if( noCase ){
drh254993e2009-06-08 19:44:36 +00001401 /* The point is to increment the last character before the first
1402 ** wildcard. But if we increment '@', that will push it into the
1403 ** alphabetic range where case conversions will mess up the
1404 ** inequality. To avoid this, make sure to also run the full
1405 ** LIKE on all candidate expressions by clearing the isComplete flag
1406 */
drh39759742013-08-02 23:40:45 +00001407 if( c=='A'-1 ) isComplete = 0;
drh02a50b72008-05-26 18:33:40 +00001408 c = sqlite3UpperToLower[c];
1409 }
drh9f504ea2008-02-23 21:55:39 +00001410 *pC = c + 1;
drhd2687b72005-08-12 22:56:09 +00001411 }
dan80103fc2015-03-20 08:43:59 +00001412 zCollSeqName = noCase ? "NOCASE" : "BINARY";
drhae80dde2012-12-06 21:16:43 +00001413 pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
drh8f1a7ed2015-03-06 19:47:38 +00001414 pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
dan80103fc2015-03-20 08:43:59 +00001415 sqlite3ExprAddCollateString(pParse,pNewExpr1,zCollSeqName),
drhae80dde2012-12-06 21:16:43 +00001416 pStr1, 0);
drhd41d39f2013-08-28 16:27:01 +00001417 transferJoinMarkings(pNewExpr1, pExpr);
drh8f1a7ed2015-03-06 19:47:38 +00001418 idxNew1 = whereClauseInsert(pWC, pNewExpr1, wtFlags);
drh6a1e0712008-12-05 15:24:15 +00001419 testcase( idxNew1==0 );
drh7b4fc6a2007-02-06 13:26:32 +00001420 exprAnalyze(pSrc, pWC, idxNew1);
drhae80dde2012-12-06 21:16:43 +00001421 pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
drh8342e492010-07-22 17:49:52 +00001422 pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
dan80103fc2015-03-20 08:43:59 +00001423 sqlite3ExprAddCollateString(pParse,pNewExpr2,zCollSeqName),
drhae80dde2012-12-06 21:16:43 +00001424 pStr2, 0);
drhd41d39f2013-08-28 16:27:01 +00001425 transferJoinMarkings(pNewExpr2, pExpr);
drh8f1a7ed2015-03-06 19:47:38 +00001426 idxNew2 = whereClauseInsert(pWC, pNewExpr2, wtFlags);
drh6a1e0712008-12-05 15:24:15 +00001427 testcase( idxNew2==0 );
drh7b4fc6a2007-02-06 13:26:32 +00001428 exprAnalyze(pSrc, pWC, idxNew2);
drh9eb20282005-08-24 03:52:18 +00001429 pTerm = &pWC->a[idxTerm];
drhd2687b72005-08-12 22:56:09 +00001430 if( isComplete ){
drh9769efc2014-10-24 14:32:21 +00001431 markTermAsChild(pWC, idxNew1, idxTerm);
1432 markTermAsChild(pWC, idxNew2, idxTerm);
drhd2687b72005-08-12 22:56:09 +00001433 }
1434 }
1435#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
drh7f375902006-06-13 17:38:59 +00001436
1437#ifndef SQLITE_OMIT_VIRTUALTABLE
1438 /* Add a WO_MATCH auxiliary term to the constraint set if the
1439 ** current expression is of the form: column MATCH expr.
1440 ** This information is used by the xBestIndex methods of
1441 ** virtual tables. The native query optimizer does not attempt
1442 ** to do anything with MATCH functions.
1443 */
1444 if( isMatchOfColumn(pExpr) ){
1445 int idxNew;
1446 Expr *pRight, *pLeft;
1447 WhereTerm *pNewTerm;
1448 Bitmask prereqColumn, prereqExpr;
1449
danielk19776ab3a2e2009-02-19 14:39:25 +00001450 pRight = pExpr->x.pList->a[0].pExpr;
1451 pLeft = pExpr->x.pList->a[1].pExpr;
drh7f375902006-06-13 17:38:59 +00001452 prereqExpr = exprTableUsage(pMaskSet, pRight);
1453 prereqColumn = exprTableUsage(pMaskSet, pLeft);
1454 if( (prereqExpr & prereqColumn)==0 ){
drh1a90e092006-06-14 22:07:10 +00001455 Expr *pNewExpr;
drhb7916a72009-05-27 10:31:29 +00001456 pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
1457 0, sqlite3ExprDup(db, pRight, 0), 0);
drh1a90e092006-06-14 22:07:10 +00001458 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
drh6a1e0712008-12-05 15:24:15 +00001459 testcase( idxNew==0 );
drh7f375902006-06-13 17:38:59 +00001460 pNewTerm = &pWC->a[idxNew];
1461 pNewTerm->prereqRight = prereqExpr;
1462 pNewTerm->leftCursor = pLeft->iTable;
drh700a2262008-12-17 19:22:15 +00001463 pNewTerm->u.leftColumn = pLeft->iColumn;
drh7f375902006-06-13 17:38:59 +00001464 pNewTerm->eOperator = WO_MATCH;
drh9769efc2014-10-24 14:32:21 +00001465 markTermAsChild(pWC, idxNew, idxTerm);
drhd2ca60d2006-06-27 02:36:58 +00001466 pTerm = &pWC->a[idxTerm];
drh165be382008-12-05 02:36:33 +00001467 pTerm->wtFlags |= TERM_COPIED;
drh7f375902006-06-13 17:38:59 +00001468 pNewTerm->prereqAll = pTerm->prereqAll;
1469 }
1470 }
1471#endif /* SQLITE_OMIT_VIRTUALTABLE */
drhdafc0ce2008-04-17 19:14:02 +00001472
drh1435a9a2013-08-27 23:15:44 +00001473#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drhd3ed7342011-09-21 00:09:41 +00001474 /* When sqlite_stat3 histogram data is available an operator of the
drh534230c2011-01-22 00:10:45 +00001475 ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
1476 ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a
1477 ** virtual term of that form.
1478 **
drh9be18702015-05-13 19:33:41 +00001479 ** Note that the virtual term must be tagged with TERM_VNULL.
drh534230c2011-01-22 00:10:45 +00001480 */
drhea6dc442011-04-08 21:35:26 +00001481 if( pExpr->op==TK_NOTNULL
1482 && pExpr->pLeft->op==TK_COLUMN
1483 && pExpr->pLeft->iColumn>=0
drhd7d71472014-10-22 19:57:16 +00001484 && OptimizationEnabled(db, SQLITE_Stat34)
drhea6dc442011-04-08 21:35:26 +00001485 ){
drh534230c2011-01-22 00:10:45 +00001486 Expr *pNewExpr;
1487 Expr *pLeft = pExpr->pLeft;
1488 int idxNew;
1489 WhereTerm *pNewTerm;
1490
1491 pNewExpr = sqlite3PExpr(pParse, TK_GT,
1492 sqlite3ExprDup(db, pLeft, 0),
1493 sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
1494
1495 idxNew = whereClauseInsert(pWC, pNewExpr,
drh9be18702015-05-13 19:33:41 +00001496 TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
drhda91e712011-02-11 06:59:02 +00001497 if( idxNew ){
1498 pNewTerm = &pWC->a[idxNew];
1499 pNewTerm->prereqRight = 0;
1500 pNewTerm->leftCursor = pLeft->iTable;
1501 pNewTerm->u.leftColumn = pLeft->iColumn;
1502 pNewTerm->eOperator = WO_GT;
drh9769efc2014-10-24 14:32:21 +00001503 markTermAsChild(pWC, idxNew, idxTerm);
drhda91e712011-02-11 06:59:02 +00001504 pTerm = &pWC->a[idxTerm];
drhda91e712011-02-11 06:59:02 +00001505 pTerm->wtFlags |= TERM_COPIED;
1506 pNewTerm->prereqAll = pTerm->prereqAll;
1507 }
drh534230c2011-01-22 00:10:45 +00001508 }
drh1435a9a2013-08-27 23:15:44 +00001509#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
drh534230c2011-01-22 00:10:45 +00001510
drhdafc0ce2008-04-17 19:14:02 +00001511 /* Prevent ON clause terms of a LEFT JOIN from being used to drive
1512 ** an index for tables to the left of the join.
1513 */
1514 pTerm->prereqRight |= extraRight;
drh75897232000-05-29 14:26:00 +00001515}
1516
drh7b4fc6a2007-02-06 13:26:32 +00001517/*
peter.d.reid60ec9142014-09-06 16:39:46 +00001518** This function searches pList for an entry that matches the iCol-th column
drh3b48e8c2013-06-12 20:18:16 +00001519** of index pIdx.
dan6f343962011-07-01 18:26:40 +00001520**
1521** If such an expression is found, its index in pList->a[] is returned. If
1522** no expression is found, -1 is returned.
1523*/
1524static int findIndexCol(
1525 Parse *pParse, /* Parse context */
1526 ExprList *pList, /* Expression list to search */
1527 int iBase, /* Cursor for table associated with pIdx */
1528 Index *pIdx, /* Index to match column of */
1529 int iCol /* Column of index to match */
1530){
1531 int i;
1532 const char *zColl = pIdx->azColl[iCol];
1533
1534 for(i=0; i<pList->nExpr; i++){
drh580c8c12012-12-08 03:34:04 +00001535 Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
drhf1d3e322011-07-09 13:00:41 +00001536 if( p->op==TK_COLUMN
1537 && p->iColumn==pIdx->aiColumn[iCol]
1538 && p->iTable==iBase
1539 ){
drh580c8c12012-12-08 03:34:04 +00001540 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
drh65df68e2015-04-15 05:31:02 +00001541 if( pColl && 0==sqlite3StrICmp(pColl->zName, zColl) ){
dan6f343962011-07-01 18:26:40 +00001542 return i;
1543 }
1544 }
1545 }
1546
1547 return -1;
1548}
1549
1550/*
dan6f343962011-07-01 18:26:40 +00001551** Return true if the DISTINCT expression-list passed as the third argument
drh4f402f22013-06-11 18:59:38 +00001552** is redundant.
1553**
drh3b48e8c2013-06-12 20:18:16 +00001554** A DISTINCT list is redundant if the database contains some subset of
drh4f402f22013-06-11 18:59:38 +00001555** columns that are unique and non-null.
dan6f343962011-07-01 18:26:40 +00001556*/
1557static int isDistinctRedundant(
drh4f402f22013-06-11 18:59:38 +00001558 Parse *pParse, /* Parsing context */
1559 SrcList *pTabList, /* The FROM clause */
1560 WhereClause *pWC, /* The WHERE clause */
1561 ExprList *pDistinct /* The result set that needs to be DISTINCT */
dan6f343962011-07-01 18:26:40 +00001562){
1563 Table *pTab;
1564 Index *pIdx;
1565 int i;
1566 int iBase;
1567
1568 /* If there is more than one table or sub-select in the FROM clause of
1569 ** this query, then it will not be possible to show that the DISTINCT
1570 ** clause is redundant. */
1571 if( pTabList->nSrc!=1 ) return 0;
1572 iBase = pTabList->a[0].iCursor;
1573 pTab = pTabList->a[0].pTab;
1574
dan94e08d92011-07-02 06:44:05 +00001575 /* If any of the expressions is an IPK column on table iBase, then return
1576 ** true. Note: The (p->iTable==iBase) part of this test may be false if the
1577 ** current SELECT is a correlated sub-query.
1578 */
dan6f343962011-07-01 18:26:40 +00001579 for(i=0; i<pDistinct->nExpr; i++){
drh580c8c12012-12-08 03:34:04 +00001580 Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
dan94e08d92011-07-02 06:44:05 +00001581 if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
dan6f343962011-07-01 18:26:40 +00001582 }
1583
1584 /* Loop through all indices on the table, checking each to see if it makes
1585 ** the DISTINCT qualifier redundant. It does so if:
1586 **
1587 ** 1. The index is itself UNIQUE, and
1588 **
1589 ** 2. All of the columns in the index are either part of the pDistinct
1590 ** list, or else the WHERE clause contains a term of the form "col=X",
1591 ** where X is a constant value. The collation sequences of the
1592 ** comparison and select-list expressions must match those of the index.
dan6a36f432012-04-20 16:59:24 +00001593 **
1594 ** 3. All of those index columns for which the WHERE clause does not
1595 ** contain a "col=X" term are subject to a NOT NULL constraint.
dan6f343962011-07-01 18:26:40 +00001596 */
1597 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
drh5f1d1d92014-07-31 22:59:04 +00001598 if( !IsUniqueIndex(pIdx) ) continue;
drhbbbdc832013-10-22 18:01:40 +00001599 for(i=0; i<pIdx->nKeyCol; i++){
1600 i16 iCol = pIdx->aiColumn[i];
dan6a36f432012-04-20 16:59:24 +00001601 if( 0==findTerm(pWC, iBase, iCol, ~(Bitmask)0, WO_EQ, pIdx) ){
1602 int iIdxCol = findIndexCol(pParse, pDistinct, iBase, pIdx, i);
drhbbbdc832013-10-22 18:01:40 +00001603 if( iIdxCol<0 || pTab->aCol[iCol].notNull==0 ){
dan6a36f432012-04-20 16:59:24 +00001604 break;
1605 }
dan6f343962011-07-01 18:26:40 +00001606 }
1607 }
drhbbbdc832013-10-22 18:01:40 +00001608 if( i==pIdx->nKeyCol ){
dan6f343962011-07-01 18:26:40 +00001609 /* This index implies that the DISTINCT qualifier is redundant. */
1610 return 1;
1611 }
1612 }
1613
1614 return 0;
1615}
drh0fcef5e2005-07-19 17:38:22 +00001616
drh8636e9c2013-06-11 01:50:08 +00001617
drh75897232000-05-29 14:26:00 +00001618/*
drh3b48e8c2013-06-12 20:18:16 +00001619** Estimate the logarithm of the input value to base 2.
drh28c4cf42005-07-27 20:41:43 +00001620*/
drhbf539c42013-10-05 18:16:02 +00001621static LogEst estLog(LogEst N){
drh696964d2014-06-12 15:46:46 +00001622 return N<=10 ? 0 : sqlite3LogEst(N) - 33;
drh28c4cf42005-07-27 20:41:43 +00001623}
1624
drh6d209d82006-06-27 01:54:26 +00001625/*
1626** Two routines for printing the content of an sqlite3_index_info
1627** structure. Used for testing and debugging only. If neither
1628** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
1629** are no-ops.
1630*/
drhd15cb172013-05-21 19:23:10 +00001631#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
drh6d209d82006-06-27 01:54:26 +00001632static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
1633 int i;
mlcreech3a00f902008-03-04 17:45:01 +00001634 if( !sqlite3WhereTrace ) return;
drh6d209d82006-06-27 01:54:26 +00001635 for(i=0; i<p->nConstraint; i++){
1636 sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
1637 i,
1638 p->aConstraint[i].iColumn,
1639 p->aConstraint[i].iTermOffset,
1640 p->aConstraint[i].op,
1641 p->aConstraint[i].usable);
1642 }
1643 for(i=0; i<p->nOrderBy; i++){
1644 sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n",
1645 i,
1646 p->aOrderBy[i].iColumn,
1647 p->aOrderBy[i].desc);
1648 }
1649}
1650static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
1651 int i;
mlcreech3a00f902008-03-04 17:45:01 +00001652 if( !sqlite3WhereTrace ) return;
drh6d209d82006-06-27 01:54:26 +00001653 for(i=0; i<p->nConstraint; i++){
1654 sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n",
1655 i,
1656 p->aConstraintUsage[i].argvIndex,
1657 p->aConstraintUsage[i].omit);
1658 }
1659 sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum);
1660 sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr);
1661 sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed);
1662 sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost);
dana9f58152013-11-11 19:01:33 +00001663 sqlite3DebugPrintf(" estimatedRows=%lld\n", p->estimatedRows);
drh6d209d82006-06-27 01:54:26 +00001664}
1665#else
1666#define TRACE_IDX_INPUTS(A)
1667#define TRACE_IDX_OUTPUTS(A)
1668#endif
1669
drhc6339082010-04-07 16:54:58 +00001670#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
drh8b307fb2010-04-06 15:57:05 +00001671/*
drh4139c992010-04-07 14:59:45 +00001672** Return TRUE if the WHERE clause term pTerm is of a form where it
1673** could be used with an index to access pSrc, assuming an appropriate
1674** index existed.
1675*/
1676static int termCanDriveIndex(
1677 WhereTerm *pTerm, /* WHERE clause term to check */
1678 struct SrcList_item *pSrc, /* Table we are trying to access */
1679 Bitmask notReady /* Tables in outer loops of the join */
1680){
1681 char aff;
1682 if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
drhe8d0c612015-05-14 01:05:25 +00001683 if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) return 0;
drh4139c992010-04-07 14:59:45 +00001684 if( (pTerm->prereqRight & notReady)!=0 ) return 0;
drh23f98da2013-05-21 15:52:07 +00001685 if( pTerm->u.leftColumn<0 ) return 0;
drh4139c992010-04-07 14:59:45 +00001686 aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
1687 if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
drhe0cc3c22015-05-13 17:54:08 +00001688 testcase( pTerm->pExpr->op==TK_IS );
drh4139c992010-04-07 14:59:45 +00001689 return 1;
1690}
drhc6339082010-04-07 16:54:58 +00001691#endif
drh4139c992010-04-07 14:59:45 +00001692
drhc6339082010-04-07 16:54:58 +00001693
1694#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
drh8b307fb2010-04-06 15:57:05 +00001695/*
drhc6339082010-04-07 16:54:58 +00001696** Generate code to construct the Index object for an automatic index
1697** and to set up the WhereLevel object pLevel so that the code generator
1698** makes use of the automatic index.
drh8b307fb2010-04-06 15:57:05 +00001699*/
drhc6339082010-04-07 16:54:58 +00001700static void constructAutomaticIndex(
drh8b307fb2010-04-06 15:57:05 +00001701 Parse *pParse, /* The parsing context */
1702 WhereClause *pWC, /* The WHERE clause */
1703 struct SrcList_item *pSrc, /* The FROM clause term to get the next index */
1704 Bitmask notReady, /* Mask of cursors that are not available */
1705 WhereLevel *pLevel /* Write new index here */
1706){
drhbbbdc832013-10-22 18:01:40 +00001707 int nKeyCol; /* Number of columns in the constructed index */
drh8b307fb2010-04-06 15:57:05 +00001708 WhereTerm *pTerm; /* A single term of the WHERE clause */
1709 WhereTerm *pWCEnd; /* End of pWC->a[] */
drh8b307fb2010-04-06 15:57:05 +00001710 Index *pIdx; /* Object describing the transient index */
1711 Vdbe *v; /* Prepared statement under construction */
drh8b307fb2010-04-06 15:57:05 +00001712 int addrInit; /* Address of the initialization bypass jump */
1713 Table *pTable; /* The table being indexed */
drh8b307fb2010-04-06 15:57:05 +00001714 int addrTop; /* Top of the index fill loop */
1715 int regRecord; /* Register holding an index record */
1716 int n; /* Column counter */
drh4139c992010-04-07 14:59:45 +00001717 int i; /* Loop counter */
1718 int mxBitCol; /* Maximum column in pSrc->colUsed */
drh424aab82010-04-06 18:28:20 +00001719 CollSeq *pColl; /* Collating sequence to on a column */
drh7ba39a92013-05-30 17:43:19 +00001720 WhereLoop *pLoop; /* The Loop object */
drh77e57df2013-10-22 14:28:02 +00001721 char *zNotUsed; /* Extra space on the end of pIdx */
drh4139c992010-04-07 14:59:45 +00001722 Bitmask idxCols; /* Bitmap of columns used for indexing */
1723 Bitmask extraCols; /* Bitmap of additional columns */
drh8d56e202013-06-28 23:55:45 +00001724 u8 sentWarning = 0; /* True if a warnning has been issued */
drh059b2d52014-10-24 19:28:09 +00001725 Expr *pPartial = 0; /* Partial Index Expression */
1726 int iContinue = 0; /* Jump here to skip excluded rows */
drh8b307fb2010-04-06 15:57:05 +00001727
1728 /* Generate code to skip over the creation and initialization of the
1729 ** transient index on 2nd and subsequent iterations of the loop. */
1730 v = pParse->pVdbe;
1731 assert( v!=0 );
drh7d176102014-02-18 03:07:12 +00001732 addrInit = sqlite3CodeOnce(pParse); VdbeCoverage(v);
drh8b307fb2010-04-06 15:57:05 +00001733
drh4139c992010-04-07 14:59:45 +00001734 /* Count the number of columns that will be added to the index
1735 ** and used to match WHERE clause constraints */
drhbbbdc832013-10-22 18:01:40 +00001736 nKeyCol = 0;
drh424aab82010-04-06 18:28:20 +00001737 pTable = pSrc->pTab;
drh8b307fb2010-04-06 15:57:05 +00001738 pWCEnd = &pWC->a[pWC->nTerm];
drh7ba39a92013-05-30 17:43:19 +00001739 pLoop = pLevel->pWLoop;
drh4139c992010-04-07 14:59:45 +00001740 idxCols = 0;
drh81186b42013-06-18 01:52:41 +00001741 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
drh13cc90c2015-02-25 00:24:41 +00001742 Expr *pExpr = pTerm->pExpr;
1743 assert( !ExprHasProperty(pExpr, EP_FromJoin) /* prereq always non-zero */
1744 || pExpr->iRightJoinTable!=pSrc->iCursor /* for the right-hand */
1745 || pLoop->prereq!=0 ); /* table of a LEFT JOIN */
drh059b2d52014-10-24 19:28:09 +00001746 if( pLoop->prereq==0
drh051575c2014-10-25 12:28:25 +00001747 && (pTerm->wtFlags & TERM_VIRTUAL)==0
drh13cc90c2015-02-25 00:24:41 +00001748 && !ExprHasProperty(pExpr, EP_FromJoin)
1749 && sqlite3ExprIsTableConstant(pExpr, pSrc->iCursor) ){
drh059b2d52014-10-24 19:28:09 +00001750 pPartial = sqlite3ExprAnd(pParse->db, pPartial,
drh13cc90c2015-02-25 00:24:41 +00001751 sqlite3ExprDup(pParse->db, pExpr, 0));
drh059b2d52014-10-24 19:28:09 +00001752 }
drh4139c992010-04-07 14:59:45 +00001753 if( termCanDriveIndex(pTerm, pSrc, notReady) ){
1754 int iCol = pTerm->u.leftColumn;
drh7699d1c2013-06-04 12:42:29 +00001755 Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
drh52ff8ea2010-04-08 14:15:56 +00001756 testcase( iCol==BMS );
1757 testcase( iCol==BMS-1 );
drh8d56e202013-06-28 23:55:45 +00001758 if( !sentWarning ){
1759 sqlite3_log(SQLITE_WARNING_AUTOINDEX,
1760 "automatic index on %s(%s)", pTable->zName,
1761 pTable->aCol[iCol].zName);
1762 sentWarning = 1;
1763 }
drh0013e722010-04-08 00:40:15 +00001764 if( (idxCols & cMask)==0 ){
drh059b2d52014-10-24 19:28:09 +00001765 if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ){
1766 goto end_auto_index_create;
1767 }
drhbbbdc832013-10-22 18:01:40 +00001768 pLoop->aLTerm[nKeyCol++] = pTerm;
drh0013e722010-04-08 00:40:15 +00001769 idxCols |= cMask;
1770 }
drh8b307fb2010-04-06 15:57:05 +00001771 }
1772 }
drhbbbdc832013-10-22 18:01:40 +00001773 assert( nKeyCol>0 );
1774 pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol;
drh53b52f72013-05-31 11:57:39 +00001775 pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
drh986b3872013-06-28 21:12:20 +00001776 | WHERE_AUTO_INDEX;
drh4139c992010-04-07 14:59:45 +00001777
1778 /* Count the number of additional columns needed to create a
1779 ** covering index. A "covering index" is an index that contains all
1780 ** columns that are needed by the query. With a covering index, the
1781 ** original table never needs to be accessed. Automatic indices must
1782 ** be a covering index because the index will not be updated if the
1783 ** original table changes and the index and table cannot both be used
1784 ** if they go out of sync.
1785 */
drh7699d1c2013-06-04 12:42:29 +00001786 extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
drhc3ef4fa2014-10-28 15:58:50 +00001787 mxBitCol = MIN(BMS-1,pTable->nCol);
drh52ff8ea2010-04-08 14:15:56 +00001788 testcase( pTable->nCol==BMS-1 );
1789 testcase( pTable->nCol==BMS-2 );
drh4139c992010-04-07 14:59:45 +00001790 for(i=0; i<mxBitCol; i++){
drhbbbdc832013-10-22 18:01:40 +00001791 if( extraCols & MASKBIT(i) ) nKeyCol++;
drh4139c992010-04-07 14:59:45 +00001792 }
drh7699d1c2013-06-04 12:42:29 +00001793 if( pSrc->colUsed & MASKBIT(BMS-1) ){
drhbbbdc832013-10-22 18:01:40 +00001794 nKeyCol += pTable->nCol - BMS + 1;
drh4139c992010-04-07 14:59:45 +00001795 }
drh8b307fb2010-04-06 15:57:05 +00001796
1797 /* Construct the Index object to describe this index */
drhbbbdc832013-10-22 18:01:40 +00001798 pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed);
drh059b2d52014-10-24 19:28:09 +00001799 if( pIdx==0 ) goto end_auto_index_create;
drh7ba39a92013-05-30 17:43:19 +00001800 pLoop->u.btree.pIndex = pIdx;
drh8b307fb2010-04-06 15:57:05 +00001801 pIdx->zName = "auto-index";
drh424aab82010-04-06 18:28:20 +00001802 pIdx->pTable = pTable;
drh8b307fb2010-04-06 15:57:05 +00001803 n = 0;
drh0013e722010-04-08 00:40:15 +00001804 idxCols = 0;
drh8b307fb2010-04-06 15:57:05 +00001805 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
drh4139c992010-04-07 14:59:45 +00001806 if( termCanDriveIndex(pTerm, pSrc, notReady) ){
drh0013e722010-04-08 00:40:15 +00001807 int iCol = pTerm->u.leftColumn;
drh7699d1c2013-06-04 12:42:29 +00001808 Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
drh7963b0e2013-06-17 21:37:40 +00001809 testcase( iCol==BMS-1 );
1810 testcase( iCol==BMS );
drh0013e722010-04-08 00:40:15 +00001811 if( (idxCols & cMask)==0 ){
1812 Expr *pX = pTerm->pExpr;
1813 idxCols |= cMask;
1814 pIdx->aiColumn[n] = pTerm->u.leftColumn;
1815 pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
drh29031832015-04-15 07:34:25 +00001816 pIdx->azColl[n] = pColl ? pColl->zName : "BINARY";
drh0013e722010-04-08 00:40:15 +00001817 n++;
1818 }
drh8b307fb2010-04-06 15:57:05 +00001819 }
1820 }
drh7ba39a92013-05-30 17:43:19 +00001821 assert( (u32)n==pLoop->u.btree.nEq );
drh4139c992010-04-07 14:59:45 +00001822
drhc6339082010-04-07 16:54:58 +00001823 /* Add additional columns needed to make the automatic index into
1824 ** a covering index */
drh4139c992010-04-07 14:59:45 +00001825 for(i=0; i<mxBitCol; i++){
drh7699d1c2013-06-04 12:42:29 +00001826 if( extraCols & MASKBIT(i) ){
drh4139c992010-04-07 14:59:45 +00001827 pIdx->aiColumn[n] = i;
1828 pIdx->azColl[n] = "BINARY";
1829 n++;
1830 }
1831 }
drh7699d1c2013-06-04 12:42:29 +00001832 if( pSrc->colUsed & MASKBIT(BMS-1) ){
drh4139c992010-04-07 14:59:45 +00001833 for(i=BMS-1; i<pTable->nCol; i++){
1834 pIdx->aiColumn[n] = i;
1835 pIdx->azColl[n] = "BINARY";
1836 n++;
1837 }
1838 }
drhbbbdc832013-10-22 18:01:40 +00001839 assert( n==nKeyCol );
drh44156282013-10-23 22:23:03 +00001840 pIdx->aiColumn[n] = -1;
1841 pIdx->azColl[n] = "BINARY";
drh8b307fb2010-04-06 15:57:05 +00001842
drhc6339082010-04-07 16:54:58 +00001843 /* Create the automatic index */
drh8b307fb2010-04-06 15:57:05 +00001844 assert( pLevel->iIdxCur>=0 );
drha1f41242013-05-31 20:00:58 +00001845 pLevel->iIdxCur = pParse->nTab++;
drh2ec2fb22013-11-06 19:59:23 +00001846 sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1);
1847 sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
drha21a64d2010-04-06 22:33:55 +00001848 VdbeComment((v, "for %s", pTable->zName));
drh8b307fb2010-04-06 15:57:05 +00001849
drhc6339082010-04-07 16:54:58 +00001850 /* Fill the automatic index with content */
drh059b2d52014-10-24 19:28:09 +00001851 sqlite3ExprCachePush(pParse);
drh688852a2014-02-17 22:40:43 +00001852 addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v);
drh059b2d52014-10-24 19:28:09 +00001853 if( pPartial ){
1854 iContinue = sqlite3VdbeMakeLabel(v);
1855 sqlite3ExprIfFalse(pParse, pPartial, iContinue, SQLITE_JUMPIFNULL);
drh051575c2014-10-25 12:28:25 +00001856 pLoop->wsFlags |= WHERE_PARTIALIDX;
drh059b2d52014-10-24 19:28:09 +00001857 }
drh8b307fb2010-04-06 15:57:05 +00001858 regRecord = sqlite3GetTempReg(pParse);
drh1c2c0b72014-01-04 19:27:05 +00001859 sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0);
drh8b307fb2010-04-06 15:57:05 +00001860 sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
1861 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
drh059b2d52014-10-24 19:28:09 +00001862 if( pPartial ) sqlite3VdbeResolveLabel(v, iContinue);
drh688852a2014-02-17 22:40:43 +00001863 sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v);
drha21a64d2010-04-06 22:33:55 +00001864 sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
drh8b307fb2010-04-06 15:57:05 +00001865 sqlite3VdbeJumpHere(v, addrTop);
1866 sqlite3ReleaseTempReg(pParse, regRecord);
drh059b2d52014-10-24 19:28:09 +00001867 sqlite3ExprCachePop(pParse);
drh8b307fb2010-04-06 15:57:05 +00001868
1869 /* Jump here when skipping the initialization */
1870 sqlite3VdbeJumpHere(v, addrInit);
drh059b2d52014-10-24 19:28:09 +00001871
1872end_auto_index_create:
1873 sqlite3ExprDelete(pParse->db, pPartial);
drh8b307fb2010-04-06 15:57:05 +00001874}
drhc6339082010-04-07 16:54:58 +00001875#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
drh8b307fb2010-04-06 15:57:05 +00001876
drh9eff6162006-06-12 21:59:13 +00001877#ifndef SQLITE_OMIT_VIRTUALTABLE
1878/*
danielk19771d461462009-04-21 09:02:45 +00001879** Allocate and populate an sqlite3_index_info structure. It is the
1880** responsibility of the caller to eventually release the structure
1881** by passing the pointer returned by this function to sqlite3_free().
1882*/
drh5346e952013-05-08 14:14:26 +00001883static sqlite3_index_info *allocateIndexInfo(
1884 Parse *pParse,
1885 WhereClause *pWC,
1886 struct SrcList_item *pSrc,
1887 ExprList *pOrderBy
1888){
danielk19771d461462009-04-21 09:02:45 +00001889 int i, j;
1890 int nTerm;
1891 struct sqlite3_index_constraint *pIdxCons;
1892 struct sqlite3_index_orderby *pIdxOrderBy;
1893 struct sqlite3_index_constraint_usage *pUsage;
1894 WhereTerm *pTerm;
1895 int nOrderBy;
1896 sqlite3_index_info *pIdxInfo;
1897
danielk19771d461462009-04-21 09:02:45 +00001898 /* Count the number of possible WHERE clause constraints referring
1899 ** to this virtual table */
1900 for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
1901 if( pTerm->leftCursor != pSrc->iCursor ) continue;
drh7a5bcc02013-01-16 17:08:58 +00001902 assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
1903 testcase( pTerm->eOperator & WO_IN );
1904 testcase( pTerm->eOperator & WO_ISNULL );
drhee145872015-05-14 13:18:47 +00001905 testcase( pTerm->eOperator & WO_IS );
dana4ff8252014-01-20 19:55:33 +00001906 testcase( pTerm->eOperator & WO_ALL );
drhee145872015-05-14 13:18:47 +00001907 if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV|WO_IS))==0 ) continue;
drhb4256992011-08-02 01:57:39 +00001908 if( pTerm->wtFlags & TERM_VNULL ) continue;
danielk19771d461462009-04-21 09:02:45 +00001909 nTerm++;
1910 }
1911
1912 /* If the ORDER BY clause contains only columns in the current
1913 ** virtual table then allocate space for the aOrderBy part of
1914 ** the sqlite3_index_info structure.
1915 */
1916 nOrderBy = 0;
1917 if( pOrderBy ){
drh56f1b992012-09-25 14:29:39 +00001918 int n = pOrderBy->nExpr;
1919 for(i=0; i<n; i++){
danielk19771d461462009-04-21 09:02:45 +00001920 Expr *pExpr = pOrderBy->a[i].pExpr;
1921 if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
1922 }
drh56f1b992012-09-25 14:29:39 +00001923 if( i==n){
1924 nOrderBy = n;
danielk19771d461462009-04-21 09:02:45 +00001925 }
1926 }
1927
1928 /* Allocate the sqlite3_index_info structure
1929 */
1930 pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
1931 + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
1932 + sizeof(*pIdxOrderBy)*nOrderBy );
1933 if( pIdxInfo==0 ){
1934 sqlite3ErrorMsg(pParse, "out of memory");
danielk19771d461462009-04-21 09:02:45 +00001935 return 0;
1936 }
1937
1938 /* Initialize the structure. The sqlite3_index_info structure contains
1939 ** many fields that are declared "const" to prevent xBestIndex from
1940 ** changing them. We have to do some funky casting in order to
1941 ** initialize those fields.
1942 */
1943 pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
1944 pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
1945 pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
1946 *(int*)&pIdxInfo->nConstraint = nTerm;
1947 *(int*)&pIdxInfo->nOrderBy = nOrderBy;
1948 *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
1949 *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
1950 *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
1951 pUsage;
1952
1953 for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
drh281bbe22012-10-16 23:17:14 +00001954 u8 op;
danielk19771d461462009-04-21 09:02:45 +00001955 if( pTerm->leftCursor != pSrc->iCursor ) continue;
drh7a5bcc02013-01-16 17:08:58 +00001956 assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
1957 testcase( pTerm->eOperator & WO_IN );
drhee145872015-05-14 13:18:47 +00001958 testcase( pTerm->eOperator & WO_IS );
drh7a5bcc02013-01-16 17:08:58 +00001959 testcase( pTerm->eOperator & WO_ISNULL );
dana4ff8252014-01-20 19:55:33 +00001960 testcase( pTerm->eOperator & WO_ALL );
drhe8d0c612015-05-14 01:05:25 +00001961 if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV|WO_IS))==0 ) continue;
drhb4256992011-08-02 01:57:39 +00001962 if( pTerm->wtFlags & TERM_VNULL ) continue;
danielk19771d461462009-04-21 09:02:45 +00001963 pIdxCons[j].iColumn = pTerm->u.leftColumn;
1964 pIdxCons[j].iTermOffset = i;
drh7a5bcc02013-01-16 17:08:58 +00001965 op = (u8)pTerm->eOperator & WO_ALL;
drh281bbe22012-10-16 23:17:14 +00001966 if( op==WO_IN ) op = WO_EQ;
1967 pIdxCons[j].op = op;
danielk19771d461462009-04-21 09:02:45 +00001968 /* The direct assignment in the previous line is possible only because
1969 ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The
1970 ** following asserts verify this fact. */
1971 assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
1972 assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
1973 assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
1974 assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
1975 assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
1976 assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
drh281bbe22012-10-16 23:17:14 +00001977 assert( pTerm->eOperator & (WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
danielk19771d461462009-04-21 09:02:45 +00001978 j++;
1979 }
1980 for(i=0; i<nOrderBy; i++){
1981 Expr *pExpr = pOrderBy->a[i].pExpr;
1982 pIdxOrderBy[i].iColumn = pExpr->iColumn;
1983 pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
1984 }
1985
1986 return pIdxInfo;
1987}
1988
1989/*
1990** The table object reference passed as the second argument to this function
1991** must represent a virtual table. This function invokes the xBestIndex()
drh3b48e8c2013-06-12 20:18:16 +00001992** method of the virtual table with the sqlite3_index_info object that
1993** comes in as the 3rd argument to this function.
danielk19771d461462009-04-21 09:02:45 +00001994**
1995** If an error occurs, pParse is populated with an error message and a
1996** non-zero value is returned. Otherwise, 0 is returned and the output
1997** part of the sqlite3_index_info structure is left populated.
1998**
1999** Whether or not an error is returned, it is the responsibility of the
2000** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
2001** that this is required.
2002*/
2003static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
danielk1977595a5232009-07-24 17:58:53 +00002004 sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
danielk19771d461462009-04-21 09:02:45 +00002005 int i;
2006 int rc;
2007
danielk19771d461462009-04-21 09:02:45 +00002008 TRACE_IDX_INPUTS(p);
2009 rc = pVtab->pModule->xBestIndex(pVtab, p);
2010 TRACE_IDX_OUTPUTS(p);
danielk19771d461462009-04-21 09:02:45 +00002011
2012 if( rc!=SQLITE_OK ){
2013 if( rc==SQLITE_NOMEM ){
2014 pParse->db->mallocFailed = 1;
2015 }else if( !pVtab->zErrMsg ){
2016 sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
2017 }else{
2018 sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
2019 }
2020 }
drhb9755982010-07-24 16:34:37 +00002021 sqlite3_free(pVtab->zErrMsg);
danielk19771d461462009-04-21 09:02:45 +00002022 pVtab->zErrMsg = 0;
2023
2024 for(i=0; i<p->nConstraint; i++){
2025 if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
2026 sqlite3ErrorMsg(pParse,
2027 "table %s: xBestIndex returned an invalid plan", pTab->zName);
2028 }
2029 }
2030
2031 return pParse->nErr;
2032}
drh7ba39a92013-05-30 17:43:19 +00002033#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
danielk19771d461462009-04-21 09:02:45 +00002034
drh1435a9a2013-08-27 23:15:44 +00002035#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drh28c4cf42005-07-27 20:41:43 +00002036/*
drhfaacf172011-08-12 01:51:45 +00002037** Estimate the location of a particular key among all keys in an
2038** index. Store the results in aStat as follows:
drhe847d322011-01-20 02:56:37 +00002039**
dana3d0c132015-03-14 18:59:58 +00002040** aStat[0] Est. number of rows less than pRec
2041** aStat[1] Est. number of rows equal to pRec
dan02fa4692009-08-17 17:06:58 +00002042**
drh6d3f91d2014-11-05 19:26:12 +00002043** Return the index of the sample that is the smallest sample that
dana3d0c132015-03-14 18:59:58 +00002044** is greater than or equal to pRec. Note that this index is not an index
2045** into the aSample[] array - it is an index into a virtual set of samples
2046** based on the contents of aSample[] and the number of fields in record
2047** pRec.
dan02fa4692009-08-17 17:06:58 +00002048*/
drh6d3f91d2014-11-05 19:26:12 +00002049static int whereKeyStats(
dan02fa4692009-08-17 17:06:58 +00002050 Parse *pParse, /* Database connection */
2051 Index *pIdx, /* Index to consider domain of */
dan7a419232013-08-06 20:01:43 +00002052 UnpackedRecord *pRec, /* Vector of values to consider */
drhfaacf172011-08-12 01:51:45 +00002053 int roundUp, /* Round up if true. Round down if false */
2054 tRowcnt *aStat /* OUT: stats written here */
dan02fa4692009-08-17 17:06:58 +00002055){
danf52bb8d2013-08-03 20:24:58 +00002056 IndexSample *aSample = pIdx->aSample;
drhfbc38de2013-09-03 19:26:22 +00002057 int iCol; /* Index of required stats in anEq[] etc. */
dana3d0c132015-03-14 18:59:58 +00002058 int i; /* Index of first sample >= pRec */
2059 int iSample; /* Smallest sample larger than or equal to pRec */
dan84c309b2013-08-08 16:17:12 +00002060 int iMin = 0; /* Smallest sample not yet tested */
dan84c309b2013-08-08 16:17:12 +00002061 int iTest; /* Next sample to test */
2062 int res; /* Result of comparison operation */
dana3d0c132015-03-14 18:59:58 +00002063 int nField; /* Number of fields in pRec */
2064 tRowcnt iLower = 0; /* anLt[] + anEq[] of largest sample pRec is > */
dan02fa4692009-08-17 17:06:58 +00002065
drh4f991892013-10-11 15:05:05 +00002066#ifndef SQLITE_DEBUG
2067 UNUSED_PARAMETER( pParse );
2068#endif
drh7f594752013-12-03 19:49:55 +00002069 assert( pRec!=0 );
drh5c624862011-09-22 18:46:34 +00002070 assert( pIdx->nSample>0 );
dana3d0c132015-03-14 18:59:58 +00002071 assert( pRec->nField>0 && pRec->nField<=pIdx->nSampleCol );
2072
2073 /* Do a binary search to find the first sample greater than or equal
2074 ** to pRec. If pRec contains a single field, the set of samples to search
2075 ** is simply the aSample[] array. If the samples in aSample[] contain more
2076 ** than one fields, all fields following the first are ignored.
2077 **
2078 ** If pRec contains N fields, where N is more than one, then as well as the
2079 ** samples in aSample[] (truncated to N fields), the search also has to
2080 ** consider prefixes of those samples. For example, if the set of samples
2081 ** in aSample is:
2082 **
2083 ** aSample[0] = (a, 5)
2084 ** aSample[1] = (a, 10)
2085 ** aSample[2] = (b, 5)
2086 ** aSample[3] = (c, 100)
2087 ** aSample[4] = (c, 105)
2088 **
2089 ** Then the search space should ideally be the samples above and the
2090 ** unique prefixes [a], [b] and [c]. But since that is hard to organize,
2091 ** the code actually searches this set:
2092 **
2093 ** 0: (a)
2094 ** 1: (a, 5)
2095 ** 2: (a, 10)
2096 ** 3: (a, 10)
2097 ** 4: (b)
2098 ** 5: (b, 5)
2099 ** 6: (c)
2100 ** 7: (c, 100)
2101 ** 8: (c, 105)
2102 ** 9: (c, 105)
2103 **
2104 ** For each sample in the aSample[] array, N samples are present in the
2105 ** effective sample array. In the above, samples 0 and 1 are based on
2106 ** sample aSample[0]. Samples 2 and 3 on aSample[1] etc.
2107 **
2108 ** Often, sample i of each block of N effective samples has (i+1) fields.
2109 ** Except, each sample may be extended to ensure that it is greater than or
2110 ** equal to the previous sample in the array. For example, in the above,
2111 ** sample 2 is the first sample of a block of N samples, so at first it
2112 ** appears that it should be 1 field in size. However, that would make it
2113 ** smaller than sample 1, so the binary search would not work. As a result,
2114 ** it is extended to two fields. The duplicates that this creates do not
2115 ** cause any problems.
2116 */
2117 nField = pRec->nField;
2118 iCol = 0;
2119 iSample = pIdx->nSample * nField;
dan84c309b2013-08-08 16:17:12 +00002120 do{
dana3d0c132015-03-14 18:59:58 +00002121 int iSamp; /* Index in aSample[] of test sample */
2122 int n; /* Number of fields in test sample */
2123
2124 iTest = (iMin+iSample)/2;
2125 iSamp = iTest / nField;
2126 if( iSamp>0 ){
2127 /* The proposed effective sample is a prefix of sample aSample[iSamp].
2128 ** Specifically, the shortest prefix of at least (1 + iTest%nField)
2129 ** fields that is greater than the previous effective sample. */
2130 for(n=(iTest % nField) + 1; n<nField; n++){
2131 if( aSample[iSamp-1].anLt[n-1]!=aSample[iSamp].anLt[n-1] ) break;
2132 }
dan84c309b2013-08-08 16:17:12 +00002133 }else{
dana3d0c132015-03-14 18:59:58 +00002134 n = iTest + 1;
dan02fa4692009-08-17 17:06:58 +00002135 }
dana3d0c132015-03-14 18:59:58 +00002136
2137 pRec->nField = n;
2138 res = sqlite3VdbeRecordCompare(aSample[iSamp].n, aSample[iSamp].p, pRec);
2139 if( res<0 ){
2140 iLower = aSample[iSamp].anLt[n-1] + aSample[iSamp].anEq[n-1];
2141 iMin = iTest+1;
2142 }else if( res==0 && n<nField ){
2143 iLower = aSample[iSamp].anLt[n-1];
2144 iMin = iTest+1;
2145 res = -1;
2146 }else{
2147 iSample = iTest;
2148 iCol = n-1;
2149 }
2150 }while( res && iMin<iSample );
2151 i = iSample / nField;
drh51147ba2005-07-23 22:59:55 +00002152
dan84c309b2013-08-08 16:17:12 +00002153#ifdef SQLITE_DEBUG
2154 /* The following assert statements check that the binary search code
2155 ** above found the right answer. This block serves no purpose other
2156 ** than to invoke the asserts. */
dana3d0c132015-03-14 18:59:58 +00002157 if( pParse->db->mallocFailed==0 ){
2158 if( res==0 ){
2159 /* If (res==0) is true, then pRec must be equal to sample i. */
2160 assert( i<pIdx->nSample );
2161 assert( iCol==nField-1 );
2162 pRec->nField = nField;
2163 assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)
2164 || pParse->db->mallocFailed
2165 );
2166 }else{
2167 /* Unless i==pIdx->nSample, indicating that pRec is larger than
2168 ** all samples in the aSample[] array, pRec must be smaller than the
2169 ** (iCol+1) field prefix of sample i. */
2170 assert( i<=pIdx->nSample && i>=0 );
2171 pRec->nField = iCol+1;
2172 assert( i==pIdx->nSample
2173 || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0
2174 || pParse->db->mallocFailed );
2175
2176 /* if i==0 and iCol==0, then record pRec is smaller than all samples
2177 ** in the aSample[] array. Otherwise, if (iCol>0) then pRec must
2178 ** be greater than or equal to the (iCol) field prefix of sample i.
2179 ** If (i>0), then pRec must also be greater than sample (i-1). */
2180 if( iCol>0 ){
2181 pRec->nField = iCol;
2182 assert( sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)<=0
2183 || pParse->db->mallocFailed );
2184 }
2185 if( i>0 ){
2186 pRec->nField = nField;
2187 assert( sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0
2188 || pParse->db->mallocFailed );
2189 }
2190 }
drhfaacf172011-08-12 01:51:45 +00002191 }
dan84c309b2013-08-08 16:17:12 +00002192#endif /* ifdef SQLITE_DEBUG */
dan02fa4692009-08-17 17:06:58 +00002193
dan84c309b2013-08-08 16:17:12 +00002194 if( res==0 ){
dana3d0c132015-03-14 18:59:58 +00002195 /* Record pRec is equal to sample i */
2196 assert( iCol==nField-1 );
daneea568d2013-08-07 19:46:15 +00002197 aStat[0] = aSample[i].anLt[iCol];
2198 aStat[1] = aSample[i].anEq[iCol];
drhfaacf172011-08-12 01:51:45 +00002199 }else{
dana3d0c132015-03-14 18:59:58 +00002200 /* At this point, the (iCol+1) field prefix of aSample[i] is the first
2201 ** sample that is greater than pRec. Or, if i==pIdx->nSample then pRec
2202 ** is larger than all samples in the array. */
2203 tRowcnt iUpper, iGap;
2204 if( i>=pIdx->nSample ){
2205 iUpper = sqlite3LogEstToInt(pIdx->aiRowLogEst[0]);
drhfaacf172011-08-12 01:51:45 +00002206 }else{
dana3d0c132015-03-14 18:59:58 +00002207 iUpper = aSample[i].anLt[iCol];
drhfaacf172011-08-12 01:51:45 +00002208 }
dana3d0c132015-03-14 18:59:58 +00002209
drhfaacf172011-08-12 01:51:45 +00002210 if( iLower>=iUpper ){
2211 iGap = 0;
2212 }else{
2213 iGap = iUpper - iLower;
drhfaacf172011-08-12 01:51:45 +00002214 }
2215 if( roundUp ){
2216 iGap = (iGap*2)/3;
2217 }else{
2218 iGap = iGap/3;
2219 }
2220 aStat[0] = iLower + iGap;
dana3d0c132015-03-14 18:59:58 +00002221 aStat[1] = pIdx->aAvgEq[iCol];
dan02fa4692009-08-17 17:06:58 +00002222 }
dana3d0c132015-03-14 18:59:58 +00002223
2224 /* Restore the pRec->nField value before returning. */
2225 pRec->nField = nField;
drh6d3f91d2014-11-05 19:26:12 +00002226 return i;
dan02fa4692009-08-17 17:06:58 +00002227}
drh1435a9a2013-08-27 23:15:44 +00002228#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
dan937d0de2009-10-15 18:35:38 +00002229
2230/*
danaa9933c2014-04-24 20:04:49 +00002231** If it is not NULL, pTerm is a term that provides an upper or lower
2232** bound on a range scan. Without considering pTerm, it is estimated
2233** that the scan will visit nNew rows. This function returns the number
2234** estimated to be visited after taking pTerm into account.
2235**
2236** If the user explicitly specified a likelihood() value for this term,
2237** then the return value is the likelihood multiplied by the number of
2238** input rows. Otherwise, this function assumes that an "IS NOT NULL" term
2239** has a likelihood of 0.50, and any other term a likelihood of 0.25.
2240*/
2241static LogEst whereRangeAdjust(WhereTerm *pTerm, LogEst nNew){
2242 LogEst nRet = nNew;
2243 if( pTerm ){
2244 if( pTerm->truthProb<=0 ){
2245 nRet += pTerm->truthProb;
dan7de2a1f2014-04-28 20:11:20 +00002246 }else if( (pTerm->wtFlags & TERM_VNULL)==0 ){
danaa9933c2014-04-24 20:04:49 +00002247 nRet -= 20; assert( 20==sqlite3LogEst(4) );
2248 }
2249 }
2250 return nRet;
2251}
2252
mistachkin2d84ac42014-06-26 21:32:09 +00002253#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
danb0b82902014-06-26 20:21:46 +00002254/*
2255** This function is called to estimate the number of rows visited by a
2256** range-scan on a skip-scan index. For example:
2257**
2258** CREATE INDEX i1 ON t1(a, b, c);
2259** SELECT * FROM t1 WHERE a=? AND c BETWEEN ? AND ?;
2260**
2261** Value pLoop->nOut is currently set to the estimated number of rows
2262** visited for scanning (a=? AND b=?). This function reduces that estimate
2263** by some factor to account for the (c BETWEEN ? AND ?) expression based
2264** on the stat4 data for the index. this scan will be peformed multiple
2265** times (once for each (a,b) combination that matches a=?) is dealt with
2266** by the caller.
2267**
2268** It does this by scanning through all stat4 samples, comparing values
2269** extracted from pLower and pUpper with the corresponding column in each
2270** sample. If L and U are the number of samples found to be less than or
2271** equal to the values extracted from pLower and pUpper respectively, and
2272** N is the total number of samples, the pLoop->nOut value is adjusted
2273** as follows:
2274**
2275** nOut = nOut * ( min(U - L, 1) / N )
2276**
2277** If pLower is NULL, or a value cannot be extracted from the term, L is
2278** set to zero. If pUpper is NULL, or a value cannot be extracted from it,
2279** U is set to N.
2280**
2281** Normally, this function sets *pbDone to 1 before returning. However,
2282** if no value can be extracted from either pLower or pUpper (and so the
2283** estimate of the number of rows delivered remains unchanged), *pbDone
2284** is left as is.
2285**
2286** If an error occurs, an SQLite error code is returned. Otherwise,
2287** SQLITE_OK.
2288*/
2289static int whereRangeSkipScanEst(
2290 Parse *pParse, /* Parsing & code generating context */
2291 WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
2292 WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
2293 WhereLoop *pLoop, /* Update the .nOut value of this loop */
2294 int *pbDone /* Set to true if at least one expr. value extracted */
2295){
2296 Index *p = pLoop->u.btree.pIndex;
2297 int nEq = pLoop->u.btree.nEq;
2298 sqlite3 *db = pParse->db;
dan4e42ba42014-06-27 20:14:25 +00002299 int nLower = -1;
2300 int nUpper = p->nSample+1;
danb0b82902014-06-26 20:21:46 +00002301 int rc = SQLITE_OK;
drhd15f87e2014-07-24 22:41:20 +00002302 int iCol = p->aiColumn[nEq];
2303 u8 aff = iCol>=0 ? p->pTable->aCol[iCol].affinity : SQLITE_AFF_INTEGER;
danb0b82902014-06-26 20:21:46 +00002304 CollSeq *pColl;
2305
2306 sqlite3_value *p1 = 0; /* Value extracted from pLower */
2307 sqlite3_value *p2 = 0; /* Value extracted from pUpper */
2308 sqlite3_value *pVal = 0; /* Value extracted from record */
2309
2310 pColl = sqlite3LocateCollSeq(pParse, p->azColl[nEq]);
2311 if( pLower ){
2312 rc = sqlite3Stat4ValueFromExpr(pParse, pLower->pExpr->pRight, aff, &p1);
dan4e42ba42014-06-27 20:14:25 +00002313 nLower = 0;
danb0b82902014-06-26 20:21:46 +00002314 }
2315 if( pUpper && rc==SQLITE_OK ){
2316 rc = sqlite3Stat4ValueFromExpr(pParse, pUpper->pExpr->pRight, aff, &p2);
dan4e42ba42014-06-27 20:14:25 +00002317 nUpper = p2 ? 0 : p->nSample;
danb0b82902014-06-26 20:21:46 +00002318 }
2319
2320 if( p1 || p2 ){
2321 int i;
2322 int nDiff;
2323 for(i=0; rc==SQLITE_OK && i<p->nSample; i++){
2324 rc = sqlite3Stat4Column(db, p->aSample[i].p, p->aSample[i].n, nEq, &pVal);
2325 if( rc==SQLITE_OK && p1 ){
2326 int res = sqlite3MemCompare(p1, pVal, pColl);
dan4e42ba42014-06-27 20:14:25 +00002327 if( res>=0 ) nLower++;
danb0b82902014-06-26 20:21:46 +00002328 }
2329 if( rc==SQLITE_OK && p2 ){
2330 int res = sqlite3MemCompare(p2, pVal, pColl);
dan4e42ba42014-06-27 20:14:25 +00002331 if( res>=0 ) nUpper++;
danb0b82902014-06-26 20:21:46 +00002332 }
2333 }
danb0b82902014-06-26 20:21:46 +00002334 nDiff = (nUpper - nLower);
2335 if( nDiff<=0 ) nDiff = 1;
dan4e42ba42014-06-27 20:14:25 +00002336
2337 /* If there is both an upper and lower bound specified, and the
2338 ** comparisons indicate that they are close together, use the fallback
2339 ** method (assume that the scan visits 1/64 of the rows) for estimating
2340 ** the number of rows visited. Otherwise, estimate the number of rows
2341 ** using the method described in the header comment for this function. */
2342 if( nDiff!=1 || pUpper==0 || pLower==0 ){
2343 int nAdjust = (sqlite3LogEst(p->nSample) - sqlite3LogEst(nDiff));
2344 pLoop->nOut -= nAdjust;
2345 *pbDone = 1;
2346 WHERETRACE(0x10, ("range skip-scan regions: %u..%u adjust=%d est=%d\n",
danfa887452014-06-28 15:26:10 +00002347 nLower, nUpper, nAdjust*-1, pLoop->nOut));
dan4e42ba42014-06-27 20:14:25 +00002348 }
2349
danb0b82902014-06-26 20:21:46 +00002350 }else{
2351 assert( *pbDone==0 );
2352 }
2353
2354 sqlite3ValueFree(p1);
2355 sqlite3ValueFree(p2);
2356 sqlite3ValueFree(pVal);
2357
2358 return rc;
2359}
mistachkin2d84ac42014-06-26 21:32:09 +00002360#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
danb0b82902014-06-26 20:21:46 +00002361
danaa9933c2014-04-24 20:04:49 +00002362/*
dan02fa4692009-08-17 17:06:58 +00002363** This function is used to estimate the number of rows that will be visited
2364** by scanning an index for a range of values. The range may have an upper
2365** bound, a lower bound, or both. The WHERE clause terms that set the upper
2366** and lower bounds are represented by pLower and pUpper respectively. For
2367** example, assuming that index p is on t1(a):
2368**
2369** ... FROM t1 WHERE a > ? AND a < ? ...
2370** |_____| |_____|
2371** | |
2372** pLower pUpper
2373**
drh98cdf622009-08-20 18:14:42 +00002374** If either of the upper or lower bound is not present, then NULL is passed in
drhcdaca552009-08-20 13:45:07 +00002375** place of the corresponding WhereTerm.
dan02fa4692009-08-17 17:06:58 +00002376**
drh6d3f91d2014-11-05 19:26:12 +00002377** The value in (pBuilder->pNew->u.btree.nEq) is the number of the index
dan6cb8d762013-08-08 11:48:57 +00002378** column subject to the range constraint. Or, equivalently, the number of
2379** equality constraints optimized by the proposed index scan. For example,
2380** assuming index p is on t1(a, b), and the SQL query is:
dan02fa4692009-08-17 17:06:58 +00002381**
2382** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
2383**
dan6cb8d762013-08-08 11:48:57 +00002384** then nEq is set to 1 (as the range restricted column, b, is the second
2385** left-most column of the index). Or, if the query is:
dan02fa4692009-08-17 17:06:58 +00002386**
2387** ... FROM t1 WHERE a > ? AND a < ? ...
2388**
dan6cb8d762013-08-08 11:48:57 +00002389** then nEq is set to 0.
dan02fa4692009-08-17 17:06:58 +00002390**
drhbf539c42013-10-05 18:16:02 +00002391** When this function is called, *pnOut is set to the sqlite3LogEst() of the
dan6cb8d762013-08-08 11:48:57 +00002392** number of rows that the index scan is expected to visit without
drh6d3f91d2014-11-05 19:26:12 +00002393** considering the range constraints. If nEq is 0, then *pnOut is the number of
dan6cb8d762013-08-08 11:48:57 +00002394** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced)
peter.d.reid60ec9142014-09-06 16:39:46 +00002395** to account for the range constraints pLower and pUpper.
dan6cb8d762013-08-08 11:48:57 +00002396**
2397** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be
drh94aa7e02014-06-06 17:09:52 +00002398** used, a single range inequality reduces the search space by a factor of 4.
2399** and a pair of constraints (x>? AND x<?) reduces the expected number of
2400** rows visited by a factor of 64.
dan02fa4692009-08-17 17:06:58 +00002401*/
2402static int whereRangeScanEst(
drhcdaca552009-08-20 13:45:07 +00002403 Parse *pParse, /* Parsing & code generating context */
dan7a419232013-08-06 20:01:43 +00002404 WhereLoopBuilder *pBuilder,
drhcdaca552009-08-20 13:45:07 +00002405 WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
2406 WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
drh186ad8c2013-10-08 18:40:37 +00002407 WhereLoop *pLoop /* Modify the .nOut and maybe .rRun fields */
dan02fa4692009-08-17 17:06:58 +00002408){
dan69188d92009-08-19 08:18:32 +00002409 int rc = SQLITE_OK;
drh186ad8c2013-10-08 18:40:37 +00002410 int nOut = pLoop->nOut;
drhbf539c42013-10-05 18:16:02 +00002411 LogEst nNew;
dan69188d92009-08-19 08:18:32 +00002412
drh1435a9a2013-08-27 23:15:44 +00002413#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drh186ad8c2013-10-08 18:40:37 +00002414 Index *p = pLoop->u.btree.pIndex;
drh4f991892013-10-11 15:05:05 +00002415 int nEq = pLoop->u.btree.nEq;
dan02fa4692009-08-17 17:06:58 +00002416
drh6d3f91d2014-11-05 19:26:12 +00002417 if( p->nSample>0 && nEq<p->nSampleCol ){
danb0b82902014-06-26 20:21:46 +00002418 if( nEq==pBuilder->nRecValid ){
2419 UnpackedRecord *pRec = pBuilder->pRec;
2420 tRowcnt a[2];
2421 u8 aff;
drh98cdf622009-08-20 18:14:42 +00002422
danb0b82902014-06-26 20:21:46 +00002423 /* Variable iLower will be set to the estimate of the number of rows in
2424 ** the index that are less than the lower bound of the range query. The
2425 ** lower bound being the concatenation of $P and $L, where $P is the
2426 ** key-prefix formed by the nEq values matched against the nEq left-most
2427 ** columns of the index, and $L is the value in pLower.
2428 **
2429 ** Or, if pLower is NULL or $L cannot be extracted from it (because it
2430 ** is not a simple variable or literal value), the lower bound of the
2431 ** range is $P. Due to a quirk in the way whereKeyStats() works, even
2432 ** if $L is available, whereKeyStats() is called for both ($P) and
drh6d3f91d2014-11-05 19:26:12 +00002433 ** ($P:$L) and the larger of the two returned values is used.
danb0b82902014-06-26 20:21:46 +00002434 **
2435 ** Similarly, iUpper is to be set to the estimate of the number of rows
2436 ** less than the upper bound of the range query. Where the upper bound
2437 ** is either ($P) or ($P:$U). Again, even if $U is available, both values
2438 ** of iUpper are requested of whereKeyStats() and the smaller used.
drh6d3f91d2014-11-05 19:26:12 +00002439 **
2440 ** The number of rows between the two bounds is then just iUpper-iLower.
danb0b82902014-06-26 20:21:46 +00002441 */
drh6d3f91d2014-11-05 19:26:12 +00002442 tRowcnt iLower; /* Rows less than the lower bound */
2443 tRowcnt iUpper; /* Rows less than the upper bound */
2444 int iLwrIdx = -2; /* aSample[] for the lower bound */
2445 int iUprIdx = -1; /* aSample[] for the upper bound */
danb3c02e22013-08-08 19:38:40 +00002446
drhb34fc5b2014-08-28 17:20:37 +00002447 if( pRec ){
2448 testcase( pRec->nField!=pBuilder->nRecValid );
2449 pRec->nField = pBuilder->nRecValid;
2450 }
danb0b82902014-06-26 20:21:46 +00002451 if( nEq==p->nKeyCol ){
2452 aff = SQLITE_AFF_INTEGER;
dan7a419232013-08-06 20:01:43 +00002453 }else{
danb0b82902014-06-26 20:21:46 +00002454 aff = p->pTable->aCol[p->aiColumn[nEq]].affinity;
drhfaacf172011-08-12 01:51:45 +00002455 }
danb0b82902014-06-26 20:21:46 +00002456 /* Determine iLower and iUpper using ($P) only. */
2457 if( nEq==0 ){
2458 iLower = 0;
drh9f07cf72014-10-22 15:27:05 +00002459 iUpper = p->nRowEst0;
danb0b82902014-06-26 20:21:46 +00002460 }else{
2461 /* Note: this call could be optimized away - since the same values must
2462 ** have been requested when testing key $P in whereEqualScanEst(). */
2463 whereKeyStats(pParse, p, pRec, 0, a);
2464 iLower = a[0];
2465 iUpper = a[0] + a[1];
dan6cb8d762013-08-08 11:48:57 +00002466 }
danb0b82902014-06-26 20:21:46 +00002467
drh69afd992014-10-08 02:53:25 +00002468 assert( pLower==0 || (pLower->eOperator & (WO_GT|WO_GE))!=0 );
2469 assert( pUpper==0 || (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
drh681fca02014-10-10 15:01:46 +00002470 assert( p->aSortOrder!=0 );
2471 if( p->aSortOrder[nEq] ){
drh69afd992014-10-08 02:53:25 +00002472 /* The roles of pLower and pUpper are swapped for a DESC index */
2473 SWAP(WhereTerm*, pLower, pUpper);
2474 }
2475
danb0b82902014-06-26 20:21:46 +00002476 /* If possible, improve on the iLower estimate using ($P:$L). */
2477 if( pLower ){
2478 int bOk; /* True if value is extracted from pExpr */
2479 Expr *pExpr = pLower->pExpr->pRight;
danb0b82902014-06-26 20:21:46 +00002480 rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
2481 if( rc==SQLITE_OK && bOk ){
2482 tRowcnt iNew;
drh6d3f91d2014-11-05 19:26:12 +00002483 iLwrIdx = whereKeyStats(pParse, p, pRec, 0, a);
drh69afd992014-10-08 02:53:25 +00002484 iNew = a[0] + ((pLower->eOperator & (WO_GT|WO_LE)) ? a[1] : 0);
danb0b82902014-06-26 20:21:46 +00002485 if( iNew>iLower ) iLower = iNew;
2486 nOut--;
danf741e042014-08-25 18:29:38 +00002487 pLower = 0;
danb0b82902014-06-26 20:21:46 +00002488 }
2489 }
2490
2491 /* If possible, improve on the iUpper estimate using ($P:$U). */
2492 if( pUpper ){
2493 int bOk; /* True if value is extracted from pExpr */
2494 Expr *pExpr = pUpper->pExpr->pRight;
danb0b82902014-06-26 20:21:46 +00002495 rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
2496 if( rc==SQLITE_OK && bOk ){
2497 tRowcnt iNew;
drh6d3f91d2014-11-05 19:26:12 +00002498 iUprIdx = whereKeyStats(pParse, p, pRec, 1, a);
drh69afd992014-10-08 02:53:25 +00002499 iNew = a[0] + ((pUpper->eOperator & (WO_GT|WO_LE)) ? a[1] : 0);
danb0b82902014-06-26 20:21:46 +00002500 if( iNew<iUpper ) iUpper = iNew;
2501 nOut--;
danf741e042014-08-25 18:29:38 +00002502 pUpper = 0;
danb0b82902014-06-26 20:21:46 +00002503 }
2504 }
2505
2506 pBuilder->pRec = pRec;
2507 if( rc==SQLITE_OK ){
2508 if( iUpper>iLower ){
2509 nNew = sqlite3LogEst(iUpper - iLower);
drh6d3f91d2014-11-05 19:26:12 +00002510 /* TUNING: If both iUpper and iLower are derived from the same
2511 ** sample, then assume they are 4x more selective. This brings
2512 ** the estimated selectivity more in line with what it would be
2513 ** if estimated without the use of STAT3/4 tables. */
2514 if( iLwrIdx==iUprIdx ) nNew -= 20; assert( 20==sqlite3LogEst(4) );
danb0b82902014-06-26 20:21:46 +00002515 }else{
2516 nNew = 10; assert( 10==sqlite3LogEst(2) );
2517 }
2518 if( nNew<nOut ){
2519 nOut = nNew;
2520 }
drhae914d72014-08-28 19:38:22 +00002521 WHERETRACE(0x10, ("STAT4 range scan: %u..%u est=%d\n",
danb0b82902014-06-26 20:21:46 +00002522 (u32)iLower, (u32)iUpper, nOut));
danb0b82902014-06-26 20:21:46 +00002523 }
2524 }else{
2525 int bDone = 0;
2526 rc = whereRangeSkipScanEst(pParse, pLower, pUpper, pLoop, &bDone);
2527 if( bDone ) return rc;
drh98cdf622009-08-20 18:14:42 +00002528 }
dan02fa4692009-08-17 17:06:58 +00002529 }
drh3f022182009-09-09 16:10:50 +00002530#else
2531 UNUSED_PARAMETER(pParse);
dan7a419232013-08-06 20:01:43 +00002532 UNUSED_PARAMETER(pBuilder);
dan02fa4692009-08-17 17:06:58 +00002533 assert( pLower || pUpper );
danf741e042014-08-25 18:29:38 +00002534#endif
dan7de2a1f2014-04-28 20:11:20 +00002535 assert( pUpper==0 || (pUpper->wtFlags & TERM_VNULL)==0 );
danaa9933c2014-04-24 20:04:49 +00002536 nNew = whereRangeAdjust(pLower, nOut);
2537 nNew = whereRangeAdjust(pUpper, nNew);
dan7de2a1f2014-04-28 20:11:20 +00002538
drh4dd96a82014-10-24 15:26:29 +00002539 /* TUNING: If there is both an upper and lower limit and neither limit
2540 ** has an application-defined likelihood(), assume the range is
dan42685f22014-04-28 19:34:06 +00002541 ** reduced by an additional 75%. This means that, by default, an open-ended
2542 ** range query (e.g. col > ?) is assumed to match 1/4 of the rows in the
2543 ** index. While a closed range (e.g. col BETWEEN ? AND ?) is estimated to
2544 ** match 1/64 of the index. */
drh4dd96a82014-10-24 15:26:29 +00002545 if( pLower && pLower->truthProb>0 && pUpper && pUpper->truthProb>0 ){
2546 nNew -= 20;
2547 }
dan7de2a1f2014-04-28 20:11:20 +00002548
danaa9933c2014-04-24 20:04:49 +00002549 nOut -= (pLower!=0) + (pUpper!=0);
drhabfa6d52013-09-11 03:53:22 +00002550 if( nNew<10 ) nNew = 10;
2551 if( nNew<nOut ) nOut = nNew;
drhae914d72014-08-28 19:38:22 +00002552#if defined(WHERETRACE_ENABLED)
2553 if( pLoop->nOut>nOut ){
2554 WHERETRACE(0x10,("Range scan lowers nOut from %d to %d\n",
2555 pLoop->nOut, nOut));
2556 }
2557#endif
drh186ad8c2013-10-08 18:40:37 +00002558 pLoop->nOut = (LogEst)nOut;
dan02fa4692009-08-17 17:06:58 +00002559 return rc;
2560}
2561
drh1435a9a2013-08-27 23:15:44 +00002562#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drh82759752011-01-20 16:52:09 +00002563/*
2564** Estimate the number of rows that will be returned based on
2565** an equality constraint x=VALUE and where that VALUE occurs in
2566** the histogram data. This only works when x is the left-most
drhfaacf172011-08-12 01:51:45 +00002567** column of an index and sqlite_stat3 histogram data is available
drhac8eb112011-03-17 01:58:21 +00002568** for that index. When pExpr==NULL that means the constraint is
2569** "x IS NULL" instead of "x=VALUE".
drh82759752011-01-20 16:52:09 +00002570**
drh0c50fa02011-01-21 16:27:18 +00002571** Write the estimated row count into *pnRow and return SQLITE_OK.
2572** If unable to make an estimate, leave *pnRow unchanged and return
2573** non-zero.
drh9b3eb0a2011-01-21 14:37:04 +00002574**
2575** This routine can fail if it is unable to load a collating sequence
2576** required for string comparison, or if unable to allocate memory
2577** for a UTF conversion required for comparison. The error is stored
2578** in the pParse structure.
drh82759752011-01-20 16:52:09 +00002579*/
drh041e09f2011-04-07 19:56:21 +00002580static int whereEqualScanEst(
drh82759752011-01-20 16:52:09 +00002581 Parse *pParse, /* Parsing & code generating context */
dan7a419232013-08-06 20:01:43 +00002582 WhereLoopBuilder *pBuilder,
drh0c50fa02011-01-21 16:27:18 +00002583 Expr *pExpr, /* Expression for VALUE in the x=VALUE constraint */
drhb8a8e8a2013-06-10 19:12:39 +00002584 tRowcnt *pnRow /* Write the revised row estimate here */
drh82759752011-01-20 16:52:09 +00002585){
dan7a419232013-08-06 20:01:43 +00002586 Index *p = pBuilder->pNew->u.btree.pIndex;
2587 int nEq = pBuilder->pNew->u.btree.nEq;
2588 UnpackedRecord *pRec = pBuilder->pRec;
drh82759752011-01-20 16:52:09 +00002589 u8 aff; /* Column affinity */
2590 int rc; /* Subfunction return code */
drhfaacf172011-08-12 01:51:45 +00002591 tRowcnt a[2]; /* Statistics */
dan7a419232013-08-06 20:01:43 +00002592 int bOk;
drh82759752011-01-20 16:52:09 +00002593
dan7a419232013-08-06 20:01:43 +00002594 assert( nEq>=1 );
danfd984b82014-06-30 18:02:20 +00002595 assert( nEq<=p->nColumn );
drh82759752011-01-20 16:52:09 +00002596 assert( p->aSample!=0 );
drh5c624862011-09-22 18:46:34 +00002597 assert( p->nSample>0 );
dan7a419232013-08-06 20:01:43 +00002598 assert( pBuilder->nRecValid<nEq );
2599
2600 /* If values are not available for all fields of the index to the left
2601 ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */
2602 if( pBuilder->nRecValid<(nEq-1) ){
2603 return SQLITE_NOTFOUND;
drh1f9c7662011-03-17 01:34:26 +00002604 }
dan7a419232013-08-06 20:01:43 +00002605
dandd6e1f12013-08-10 19:08:30 +00002606 /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue()
2607 ** below would return the same value. */
danfd984b82014-06-30 18:02:20 +00002608 if( nEq>=p->nColumn ){
dan7a419232013-08-06 20:01:43 +00002609 *pnRow = 1;
2610 return SQLITE_OK;
drh82759752011-01-20 16:52:09 +00002611 }
dan7a419232013-08-06 20:01:43 +00002612
daneea568d2013-08-07 19:46:15 +00002613 aff = p->pTable->aCol[p->aiColumn[nEq-1]].affinity;
dan87cd9322013-08-07 15:52:41 +00002614 rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq-1, &bOk);
2615 pBuilder->pRec = pRec;
dan7a419232013-08-06 20:01:43 +00002616 if( rc!=SQLITE_OK ) return rc;
2617 if( bOk==0 ) return SQLITE_NOTFOUND;
dan7a419232013-08-06 20:01:43 +00002618 pBuilder->nRecValid = nEq;
dan7a419232013-08-06 20:01:43 +00002619
danb3c02e22013-08-08 19:38:40 +00002620 whereKeyStats(pParse, p, pRec, 0, a);
drh989578e2013-10-28 14:34:35 +00002621 WHERETRACE(0x10,("equality scan regions: %d\n", (int)a[1]));
danb3c02e22013-08-08 19:38:40 +00002622 *pnRow = a[1];
daneea568d2013-08-07 19:46:15 +00002623
drh0c50fa02011-01-21 16:27:18 +00002624 return rc;
2625}
drh1435a9a2013-08-27 23:15:44 +00002626#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
drh0c50fa02011-01-21 16:27:18 +00002627
drh1435a9a2013-08-27 23:15:44 +00002628#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drh0c50fa02011-01-21 16:27:18 +00002629/*
2630** Estimate the number of rows that will be returned based on
drh5ac06072011-01-21 18:18:13 +00002631** an IN constraint where the right-hand side of the IN operator
2632** is a list of values. Example:
2633**
2634** WHERE x IN (1,2,3,4)
drh0c50fa02011-01-21 16:27:18 +00002635**
2636** Write the estimated row count into *pnRow and return SQLITE_OK.
2637** If unable to make an estimate, leave *pnRow unchanged and return
2638** non-zero.
2639**
2640** This routine can fail if it is unable to load a collating sequence
2641** required for string comparison, or if unable to allocate memory
2642** for a UTF conversion required for comparison. The error is stored
2643** in the pParse structure.
2644*/
drh041e09f2011-04-07 19:56:21 +00002645static int whereInScanEst(
drh0c50fa02011-01-21 16:27:18 +00002646 Parse *pParse, /* Parsing & code generating context */
dan7a419232013-08-06 20:01:43 +00002647 WhereLoopBuilder *pBuilder,
drh0c50fa02011-01-21 16:27:18 +00002648 ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
drhb8a8e8a2013-06-10 19:12:39 +00002649 tRowcnt *pnRow /* Write the revised row estimate here */
drh0c50fa02011-01-21 16:27:18 +00002650){
dan7a419232013-08-06 20:01:43 +00002651 Index *p = pBuilder->pNew->u.btree.pIndex;
dancfc9df72014-04-25 15:01:01 +00002652 i64 nRow0 = sqlite3LogEstToInt(p->aiRowLogEst[0]);
dan7a419232013-08-06 20:01:43 +00002653 int nRecValid = pBuilder->nRecValid;
drhb8a8e8a2013-06-10 19:12:39 +00002654 int rc = SQLITE_OK; /* Subfunction return code */
2655 tRowcnt nEst; /* Number of rows for a single term */
2656 tRowcnt nRowEst = 0; /* New estimate of the number of rows */
2657 int i; /* Loop counter */
drh0c50fa02011-01-21 16:27:18 +00002658
2659 assert( p->aSample!=0 );
drhfaacf172011-08-12 01:51:45 +00002660 for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
dancfc9df72014-04-25 15:01:01 +00002661 nEst = nRow0;
dan7a419232013-08-06 20:01:43 +00002662 rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst);
drhfaacf172011-08-12 01:51:45 +00002663 nRowEst += nEst;
dan7a419232013-08-06 20:01:43 +00002664 pBuilder->nRecValid = nRecValid;
drh0c50fa02011-01-21 16:27:18 +00002665 }
dan7a419232013-08-06 20:01:43 +00002666
drh0c50fa02011-01-21 16:27:18 +00002667 if( rc==SQLITE_OK ){
dancfc9df72014-04-25 15:01:01 +00002668 if( nRowEst > nRow0 ) nRowEst = nRow0;
drh0c50fa02011-01-21 16:27:18 +00002669 *pnRow = nRowEst;
drh5418b122014-08-28 13:42:13 +00002670 WHERETRACE(0x10,("IN row estimate: est=%d\n", nRowEst));
drh0c50fa02011-01-21 16:27:18 +00002671 }
dan7a419232013-08-06 20:01:43 +00002672 assert( pBuilder->nRecValid==nRecValid );
drh0c50fa02011-01-21 16:27:18 +00002673 return rc;
drh82759752011-01-20 16:52:09 +00002674}
drh1435a9a2013-08-27 23:15:44 +00002675#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
drh82759752011-01-20 16:52:09 +00002676
drh46c35f92012-09-26 23:17:01 +00002677/*
drh2ffb1182004-07-19 19:14:01 +00002678** Disable a term in the WHERE clause. Except, do not disable the term
2679** if it controls a LEFT OUTER JOIN and it did not originate in the ON
2680** or USING clause of that join.
2681**
2682** Consider the term t2.z='ok' in the following queries:
2683**
2684** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
2685** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
2686** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
2687**
drh23bf66d2004-12-14 03:34:34 +00002688** The t2.z='ok' is disabled in the in (2) because it originates
drh2ffb1182004-07-19 19:14:01 +00002689** in the ON clause. The term is disabled in (3) because it is not part
2690** of a LEFT OUTER JOIN. In (1), the term is not disabled.
2691**
2692** Disabling a term causes that term to not be tested in the inner loop
drhb6fb62d2005-09-20 08:47:20 +00002693** of the join. Disabling is an optimization. When terms are satisfied
2694** by indices, we disable them to prevent redundant tests in the inner
2695** loop. We would get the correct results if nothing were ever disabled,
2696** but joins might run a little slower. The trick is to disable as much
2697** as we can without disabling too much. If we disabled in (1), we'd get
2698** the wrong answer. See ticket #813.
drh8f1a7ed2015-03-06 19:47:38 +00002699**
2700** If all the children of a term are disabled, then that term is also
2701** automatically disabled. In this way, terms get disabled if derived
2702** virtual terms are tested first. For example:
2703**
2704** x GLOB 'abc*' AND x>='abc' AND x<'acd'
2705** \___________/ \______/ \_____/
2706** parent child1 child2
2707**
2708** Only the parent term was in the original WHERE clause. The child1
2709** and child2 terms were added by the LIKE optimization. If both of
2710** the virtual child terms are valid, then testing of the parent can be
2711** skipped.
drha9c18a92015-03-06 20:49:52 +00002712**
2713** Usually the parent term is marked as TERM_CODED. But if the parent
2714** term was originally TERM_LIKE, then the parent gets TERM_LIKECOND instead.
2715** The TERM_LIKECOND marking indicates that the term should be coded inside
2716** a conditional such that is only evaluated on the second pass of a
2717** LIKE-optimization loop, when scanning BLOBs instead of strings.
drh2ffb1182004-07-19 19:14:01 +00002718*/
drh0fcef5e2005-07-19 17:38:22 +00002719static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
drh8f1a7ed2015-03-06 19:47:38 +00002720 int nLoop = 0;
2721 while( pTerm
drhbe837bd2010-04-30 21:03:24 +00002722 && (pTerm->wtFlags & TERM_CODED)==0
drh0fcef5e2005-07-19 17:38:22 +00002723 && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
drh0259bc32013-09-09 19:37:46 +00002724 && (pLevel->notReady & pTerm->prereqAll)==0
drh0fcef5e2005-07-19 17:38:22 +00002725 ){
drh8f1a7ed2015-03-06 19:47:38 +00002726 if( nLoop && (pTerm->wtFlags & TERM_LIKE)!=0 ){
2727 pTerm->wtFlags |= TERM_LIKECOND;
2728 }else{
2729 pTerm->wtFlags |= TERM_CODED;
drh0fcef5e2005-07-19 17:38:22 +00002730 }
drh8f1a7ed2015-03-06 19:47:38 +00002731 if( pTerm->iParent<0 ) break;
2732 pTerm = &pTerm->pWC->a[pTerm->iParent];
2733 pTerm->nChild--;
2734 if( pTerm->nChild!=0 ) break;
2735 nLoop++;
drh2ffb1182004-07-19 19:14:01 +00002736 }
2737}
2738
2739/*
dan69f8bb92009-08-13 19:21:16 +00002740** Code an OP_Affinity opcode to apply the column affinity string zAff
2741** to the n registers starting at base.
2742**
drh039fc322009-11-17 18:31:47 +00002743** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
2744** beginning and end of zAff are ignored. If all entries in zAff are
2745** SQLITE_AFF_NONE, then no code gets generated.
2746**
2747** This routine makes its own copy of zAff so that the caller is free
2748** to modify zAff after this routine returns.
drh94a11212004-09-25 13:12:14 +00002749*/
dan69f8bb92009-08-13 19:21:16 +00002750static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
2751 Vdbe *v = pParse->pVdbe;
drh039fc322009-11-17 18:31:47 +00002752 if( zAff==0 ){
2753 assert( pParse->db->mallocFailed );
2754 return;
2755 }
dan69f8bb92009-08-13 19:21:16 +00002756 assert( v!=0 );
drh039fc322009-11-17 18:31:47 +00002757
2758 /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
2759 ** and end of the affinity string.
2760 */
2761 while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
2762 n--;
2763 base++;
2764 zAff++;
2765 }
2766 while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
2767 n--;
2768 }
2769
2770 /* Code the OP_Affinity opcode if there is anything left to do. */
2771 if( n>0 ){
2772 sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
2773 sqlite3VdbeChangeP4(v, -1, zAff, n);
2774 sqlite3ExprCacheAffinityChange(pParse, base, n);
2775 }
drh94a11212004-09-25 13:12:14 +00002776}
2777
drhe8b97272005-07-19 22:22:12 +00002778
2779/*
drh51147ba2005-07-23 22:59:55 +00002780** Generate code for a single equality term of the WHERE clause. An equality
2781** term can be either X=expr or X IN (...). pTerm is the term to be
2782** coded.
2783**
drh1db639c2008-01-17 02:36:28 +00002784** The current value for the constraint is left in register iReg.
drh51147ba2005-07-23 22:59:55 +00002785**
2786** For a constraint of the form X=expr, the expression is evaluated and its
2787** result is left on the stack. For constraints of the form X IN (...)
2788** this routine sets up a loop that will iterate over all values of X.
drh94a11212004-09-25 13:12:14 +00002789*/
drh678ccce2008-03-31 18:19:54 +00002790static int codeEqualityTerm(
drh94a11212004-09-25 13:12:14 +00002791 Parse *pParse, /* The parsing context */
drhe23399f2005-07-22 00:31:39 +00002792 WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
drh0fe456b2013-03-12 18:34:50 +00002793 WhereLevel *pLevel, /* The level of the FROM clause we are working on */
2794 int iEq, /* Index of the equality term within this level */
drh7ba39a92013-05-30 17:43:19 +00002795 int bRev, /* True for reverse-order IN operations */
drh678ccce2008-03-31 18:19:54 +00002796 int iTarget /* Attempt to leave results in this register */
drh94a11212004-09-25 13:12:14 +00002797){
drh0fcef5e2005-07-19 17:38:22 +00002798 Expr *pX = pTerm->pExpr;
drh50b39962006-10-28 00:28:09 +00002799 Vdbe *v = pParse->pVdbe;
drh678ccce2008-03-31 18:19:54 +00002800 int iReg; /* Register holding results */
drh1db639c2008-01-17 02:36:28 +00002801
danielk19772d605492008-10-01 08:43:03 +00002802 assert( iTarget>0 );
drhfcd49532015-05-13 15:24:07 +00002803 if( pX->op==TK_EQ || pX->op==TK_IS ){
drh678ccce2008-03-31 18:19:54 +00002804 iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
drh50b39962006-10-28 00:28:09 +00002805 }else if( pX->op==TK_ISNULL ){
drh678ccce2008-03-31 18:19:54 +00002806 iReg = iTarget;
drh1db639c2008-01-17 02:36:28 +00002807 sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
danielk1977b3bce662005-01-29 08:32:43 +00002808#ifndef SQLITE_OMIT_SUBQUERY
drh94a11212004-09-25 13:12:14 +00002809 }else{
danielk19779a96b662007-11-29 17:05:18 +00002810 int eType;
danielk1977b3bce662005-01-29 08:32:43 +00002811 int iTab;
drh72e8fa42007-03-28 14:30:06 +00002812 struct InLoop *pIn;
drh7ba39a92013-05-30 17:43:19 +00002813 WhereLoop *pLoop = pLevel->pWLoop;
danielk1977b3bce662005-01-29 08:32:43 +00002814
drh7ba39a92013-05-30 17:43:19 +00002815 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
2816 && pLoop->u.btree.pIndex!=0
2817 && pLoop->u.btree.pIndex->aSortOrder[iEq]
drhd3832162013-03-12 18:49:25 +00002818 ){
drh725e1ae2013-03-12 23:58:42 +00002819 testcase( iEq==0 );
drh725e1ae2013-03-12 23:58:42 +00002820 testcase( bRev );
drh1ccce442013-03-12 20:38:51 +00002821 bRev = !bRev;
drh0fe456b2013-03-12 18:34:50 +00002822 }
drh50b39962006-10-28 00:28:09 +00002823 assert( pX->op==TK_IN );
drh678ccce2008-03-31 18:19:54 +00002824 iReg = iTarget;
drh3a856252014-08-01 14:46:57 +00002825 eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0);
drh725e1ae2013-03-12 23:58:42 +00002826 if( eType==IN_INDEX_INDEX_DESC ){
2827 testcase( bRev );
2828 bRev = !bRev;
2829 }
danielk1977b3bce662005-01-29 08:32:43 +00002830 iTab = pX->iTable;
drh7d176102014-02-18 03:07:12 +00002831 sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
2832 VdbeCoverageIf(v, bRev);
2833 VdbeCoverageIf(v, !bRev);
drh6fa978d2013-05-30 19:29:19 +00002834 assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
2835 pLoop->wsFlags |= WHERE_IN_ABLE;
drh111a6a72008-12-21 03:51:16 +00002836 if( pLevel->u.in.nIn==0 ){
drhb3190c12008-12-08 21:37:14 +00002837 pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
drh72e8fa42007-03-28 14:30:06 +00002838 }
drh111a6a72008-12-21 03:51:16 +00002839 pLevel->u.in.nIn++;
2840 pLevel->u.in.aInLoop =
2841 sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
2842 sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
2843 pIn = pLevel->u.in.aInLoop;
drh72e8fa42007-03-28 14:30:06 +00002844 if( pIn ){
drh111a6a72008-12-21 03:51:16 +00002845 pIn += pLevel->u.in.nIn - 1;
drh72e8fa42007-03-28 14:30:06 +00002846 pIn->iCur = iTab;
drh1db639c2008-01-17 02:36:28 +00002847 if( eType==IN_INDEX_ROWID ){
drhb3190c12008-12-08 21:37:14 +00002848 pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
drh1db639c2008-01-17 02:36:28 +00002849 }else{
drhb3190c12008-12-08 21:37:14 +00002850 pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
drh1db639c2008-01-17 02:36:28 +00002851 }
drhf93cd942013-11-21 03:12:25 +00002852 pIn->eEndLoopOp = bRev ? OP_PrevIfOpen : OP_NextIfOpen;
drh688852a2014-02-17 22:40:43 +00002853 sqlite3VdbeAddOp1(v, OP_IsNull, iReg); VdbeCoverage(v);
drha6110402005-07-28 20:51:19 +00002854 }else{
drh111a6a72008-12-21 03:51:16 +00002855 pLevel->u.in.nIn = 0;
drhe23399f2005-07-22 00:31:39 +00002856 }
danielk1977b3bce662005-01-29 08:32:43 +00002857#endif
drh94a11212004-09-25 13:12:14 +00002858 }
drh0fcef5e2005-07-19 17:38:22 +00002859 disableTerm(pLevel, pTerm);
drh678ccce2008-03-31 18:19:54 +00002860 return iReg;
drh94a11212004-09-25 13:12:14 +00002861}
2862
drh51147ba2005-07-23 22:59:55 +00002863/*
2864** Generate code that will evaluate all == and IN constraints for an
drhcd8629e2013-11-13 12:27:25 +00002865** index scan.
drh51147ba2005-07-23 22:59:55 +00002866**
2867** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
2868** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
2869** The index has as many as three equality constraints, but in this
2870** example, the third "c" value is an inequality. So only two
2871** constraints are coded. This routine will generate code to evaluate
drh6df2acd2008-12-28 16:55:25 +00002872** a==5 and b IN (1,2,3). The current values for a and b will be stored
2873** in consecutive registers and the index of the first register is returned.
drh51147ba2005-07-23 22:59:55 +00002874**
2875** In the example above nEq==2. But this subroutine works for any value
2876** of nEq including 0. If nEq==0, this routine is nearly a no-op.
drh039fc322009-11-17 18:31:47 +00002877** The only thing it does is allocate the pLevel->iMem memory cell and
2878** compute the affinity string.
drh51147ba2005-07-23 22:59:55 +00002879**
drhcd8629e2013-11-13 12:27:25 +00002880** The nExtraReg parameter is 0 or 1. It is 0 if all WHERE clause constraints
2881** are == or IN and are covered by the nEq. nExtraReg is 1 if there is
2882** an inequality constraint (such as the "c>=5 AND c<10" in the example) that
2883** occurs after the nEq quality constraints.
2884**
2885** This routine allocates a range of nEq+nExtraReg memory cells and returns
2886** the index of the first memory cell in that range. The code that
2887** calls this routine will use that memory range to store keys for
2888** start and termination conditions of the loop.
drh51147ba2005-07-23 22:59:55 +00002889** key value of the loop. If one or more IN operators appear, then
2890** this routine allocates an additional nEq memory cells for internal
2891** use.
dan69f8bb92009-08-13 19:21:16 +00002892**
2893** Before returning, *pzAff is set to point to a buffer containing a
2894** copy of the column affinity string of the index allocated using
2895** sqlite3DbMalloc(). Except, entries in the copy of the string associated
2896** with equality constraints that use NONE affinity are set to
2897** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
2898**
2899** CREATE TABLE t1(a TEXT PRIMARY KEY, b);
2900** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
2901**
2902** In the example above, the index on t1(a) has TEXT affinity. But since
2903** the right hand side of the equality constraint (t2.b) has NONE affinity,
2904** no conversion should be attempted before using a t2.b value as part of
2905** a key to search the index. Hence the first byte in the returned affinity
2906** string in this example would be set to SQLITE_AFF_NONE.
drh51147ba2005-07-23 22:59:55 +00002907*/
drh1db639c2008-01-17 02:36:28 +00002908static int codeAllEqualityTerms(
drh51147ba2005-07-23 22:59:55 +00002909 Parse *pParse, /* Parsing context */
2910 WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
drh7ba39a92013-05-30 17:43:19 +00002911 int bRev, /* Reverse the order of IN operators */
dan69f8bb92009-08-13 19:21:16 +00002912 int nExtraReg, /* Number of extra registers to allocate */
2913 char **pzAff /* OUT: Set to point to affinity string */
drh51147ba2005-07-23 22:59:55 +00002914){
drhcd8629e2013-11-13 12:27:25 +00002915 u16 nEq; /* The number of == or IN constraints to code */
2916 u16 nSkip; /* Number of left-most columns to skip */
drh111a6a72008-12-21 03:51:16 +00002917 Vdbe *v = pParse->pVdbe; /* The vm under construction */
2918 Index *pIdx; /* The index being used for this loop */
drh51147ba2005-07-23 22:59:55 +00002919 WhereTerm *pTerm; /* A single constraint term */
drh7ba39a92013-05-30 17:43:19 +00002920 WhereLoop *pLoop; /* The WhereLoop object */
drh51147ba2005-07-23 22:59:55 +00002921 int j; /* Loop counter */
drh1db639c2008-01-17 02:36:28 +00002922 int regBase; /* Base register */
drh6df2acd2008-12-28 16:55:25 +00002923 int nReg; /* Number of registers to allocate */
dan69f8bb92009-08-13 19:21:16 +00002924 char *zAff; /* Affinity string to return */
drh51147ba2005-07-23 22:59:55 +00002925
drh111a6a72008-12-21 03:51:16 +00002926 /* This module is only called on query plans that use an index. */
drh7ba39a92013-05-30 17:43:19 +00002927 pLoop = pLevel->pWLoop;
2928 assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
2929 nEq = pLoop->u.btree.nEq;
drhc8bbce12014-10-21 01:05:09 +00002930 nSkip = pLoop->nSkip;
drh7ba39a92013-05-30 17:43:19 +00002931 pIdx = pLoop->u.btree.pIndex;
2932 assert( pIdx!=0 );
drh111a6a72008-12-21 03:51:16 +00002933
drh51147ba2005-07-23 22:59:55 +00002934 /* Figure out how many memory cells we will need then allocate them.
drh51147ba2005-07-23 22:59:55 +00002935 */
drh700a2262008-12-17 19:22:15 +00002936 regBase = pParse->nMem + 1;
drh7ba39a92013-05-30 17:43:19 +00002937 nReg = pLoop->u.btree.nEq + nExtraReg;
drh6df2acd2008-12-28 16:55:25 +00002938 pParse->nMem += nReg;
drh51147ba2005-07-23 22:59:55 +00002939
dan69f8bb92009-08-13 19:21:16 +00002940 zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
2941 if( !zAff ){
2942 pParse->db->mallocFailed = 1;
2943 }
2944
drhcd8629e2013-11-13 12:27:25 +00002945 if( nSkip ){
2946 int iIdxCur = pLevel->iIdxCur;
drh7d176102014-02-18 03:07:12 +00002947 sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur);
2948 VdbeCoverageIf(v, bRev==0);
2949 VdbeCoverageIf(v, bRev!=0);
drhe084f402013-11-13 17:24:38 +00002950 VdbeComment((v, "begin skip-scan on %s", pIdx->zName));
drh2e5ef4e2013-11-13 16:58:54 +00002951 j = sqlite3VdbeAddOp0(v, OP_Goto);
drh4a1d3652014-02-14 15:13:36 +00002952 pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT),
drh7d176102014-02-18 03:07:12 +00002953 iIdxCur, 0, regBase, nSkip);
2954 VdbeCoverageIf(v, bRev==0);
2955 VdbeCoverageIf(v, bRev!=0);
drh2e5ef4e2013-11-13 16:58:54 +00002956 sqlite3VdbeJumpHere(v, j);
drhcd8629e2013-11-13 12:27:25 +00002957 for(j=0; j<nSkip; j++){
2958 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, j, regBase+j);
2959 assert( pIdx->aiColumn[j]>=0 );
2960 VdbeComment((v, "%s", pIdx->pTable->aCol[pIdx->aiColumn[j]].zName));
2961 }
2962 }
2963
drh51147ba2005-07-23 22:59:55 +00002964 /* Evaluate the equality constraints
2965 */
mistachkinf6418892013-08-28 01:54:12 +00002966 assert( zAff==0 || (int)strlen(zAff)>=nEq );
drhcd8629e2013-11-13 12:27:25 +00002967 for(j=nSkip; j<nEq; j++){
drh678ccce2008-03-31 18:19:54 +00002968 int r1;
drh4efc9292013-06-06 23:02:03 +00002969 pTerm = pLoop->aLTerm[j];
drh7ba39a92013-05-30 17:43:19 +00002970 assert( pTerm!=0 );
drhcd8629e2013-11-13 12:27:25 +00002971 /* The following testcase is true for indices with redundant columns.
drhbe837bd2010-04-30 21:03:24 +00002972 ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
2973 testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
drh39759742013-08-02 23:40:45 +00002974 testcase( pTerm->wtFlags & TERM_VIRTUAL );
drh7ba39a92013-05-30 17:43:19 +00002975 r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
drh678ccce2008-03-31 18:19:54 +00002976 if( r1!=regBase+j ){
drh6df2acd2008-12-28 16:55:25 +00002977 if( nReg==1 ){
2978 sqlite3ReleaseTempReg(pParse, regBase);
2979 regBase = r1;
2980 }else{
2981 sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
2982 }
drh678ccce2008-03-31 18:19:54 +00002983 }
drh981642f2008-04-19 14:40:43 +00002984 testcase( pTerm->eOperator & WO_ISNULL );
2985 testcase( pTerm->eOperator & WO_IN );
drh72e8fa42007-03-28 14:30:06 +00002986 if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
drh039fc322009-11-17 18:31:47 +00002987 Expr *pRight = pTerm->pExpr->pRight;
drh9be18702015-05-13 19:33:41 +00002988 if( (pTerm->wtFlags & TERM_IS)==0 && sqlite3ExprCanBeNull(pRight) ){
drh7d176102014-02-18 03:07:12 +00002989 sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk);
2990 VdbeCoverage(v);
2991 }
drh039fc322009-11-17 18:31:47 +00002992 if( zAff ){
2993 if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
2994 zAff[j] = SQLITE_AFF_NONE;
2995 }
2996 if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
2997 zAff[j] = SQLITE_AFF_NONE;
2998 }
dan69f8bb92009-08-13 19:21:16 +00002999 }
drh51147ba2005-07-23 22:59:55 +00003000 }
3001 }
dan69f8bb92009-08-13 19:21:16 +00003002 *pzAff = zAff;
drh1db639c2008-01-17 02:36:28 +00003003 return regBase;
drh51147ba2005-07-23 22:59:55 +00003004}
3005
dan6f9702e2014-11-01 20:38:06 +00003006#ifndef SQLITE_OMIT_EXPLAIN
dan17c0bc02010-11-09 17:35:19 +00003007/*
drh69174c42010-11-12 15:35:59 +00003008** This routine is a helper for explainIndexRange() below
3009**
3010** pStr holds the text of an expression that we are building up one term
3011** at a time. This routine adds a new term to the end of the expression.
3012** Terms are separated by AND so add the "AND" text for second and subsequent
3013** terms only.
3014*/
3015static void explainAppendTerm(
3016 StrAccum *pStr, /* The text expression being built */
3017 int iTerm, /* Index of this term. First is zero */
3018 const char *zColumn, /* Name of the column */
3019 const char *zOp /* Name of the operator */
3020){
3021 if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
drha6353a32013-12-09 19:03:26 +00003022 sqlite3StrAccumAppendAll(pStr, zColumn);
drh69174c42010-11-12 15:35:59 +00003023 sqlite3StrAccumAppend(pStr, zOp, 1);
3024 sqlite3StrAccumAppend(pStr, "?", 1);
3025}
3026
3027/*
dan17c0bc02010-11-09 17:35:19 +00003028** Argument pLevel describes a strategy for scanning table pTab. This
drh6c977892014-10-10 15:47:46 +00003029** function appends text to pStr that describes the subset of table
3030** rows scanned by the strategy in the form of an SQL expression.
dan17c0bc02010-11-09 17:35:19 +00003031**
3032** For example, if the query:
3033**
3034** SELECT * FROM t1 WHERE a=1 AND b>2;
3035**
3036** is run and there is an index on (a, b), then this function returns a
3037** string similar to:
3038**
3039** "a=? AND b>?"
dan17c0bc02010-11-09 17:35:19 +00003040*/
drh1f8817c2014-10-10 19:15:35 +00003041static void explainIndexRange(StrAccum *pStr, WhereLoop *pLoop, Table *pTab){
drhef866372013-05-22 20:49:02 +00003042 Index *pIndex = pLoop->u.btree.pIndex;
drhcd8629e2013-11-13 12:27:25 +00003043 u16 nEq = pLoop->u.btree.nEq;
drhc8bbce12014-10-21 01:05:09 +00003044 u16 nSkip = pLoop->nSkip;
drh69174c42010-11-12 15:35:59 +00003045 int i, j;
3046 Column *aCol = pTab->aCol;
drhbbbdc832013-10-22 18:01:40 +00003047 i16 *aiColumn = pIndex->aiColumn;
dan2ce22452010-11-08 19:01:16 +00003048
drh6c977892014-10-10 15:47:46 +00003049 if( nEq==0 && (pLoop->wsFlags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ) return;
3050 sqlite3StrAccumAppend(pStr, " (", 2);
dan2ce22452010-11-08 19:01:16 +00003051 for(i=0; i<nEq; i++){
dan39129ce2014-06-30 15:23:57 +00003052 char *z = aiColumn[i] < 0 ? "rowid" : aCol[aiColumn[i]].zName;
drhcd8629e2013-11-13 12:27:25 +00003053 if( i>=nSkip ){
drh6c977892014-10-10 15:47:46 +00003054 explainAppendTerm(pStr, i, z, "=");
drhcd8629e2013-11-13 12:27:25 +00003055 }else{
drh6c977892014-10-10 15:47:46 +00003056 if( i ) sqlite3StrAccumAppend(pStr, " AND ", 5);
3057 sqlite3XPrintf(pStr, 0, "ANY(%s)", z);
drhcd8629e2013-11-13 12:27:25 +00003058 }
dan2ce22452010-11-08 19:01:16 +00003059 }
3060
drh69174c42010-11-12 15:35:59 +00003061 j = i;
drhef866372013-05-22 20:49:02 +00003062 if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
dan39129ce2014-06-30 15:23:57 +00003063 char *z = aiColumn[j] < 0 ? "rowid" : aCol[aiColumn[j]].zName;
drh6c977892014-10-10 15:47:46 +00003064 explainAppendTerm(pStr, i++, z, ">");
dan2ce22452010-11-08 19:01:16 +00003065 }
drhef866372013-05-22 20:49:02 +00003066 if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
dan39129ce2014-06-30 15:23:57 +00003067 char *z = aiColumn[j] < 0 ? "rowid" : aCol[aiColumn[j]].zName;
drh6c977892014-10-10 15:47:46 +00003068 explainAppendTerm(pStr, i, z, "<");
dan2ce22452010-11-08 19:01:16 +00003069 }
drh6c977892014-10-10 15:47:46 +00003070 sqlite3StrAccumAppend(pStr, ")", 1);
dan2ce22452010-11-08 19:01:16 +00003071}
3072
dan17c0bc02010-11-09 17:35:19 +00003073/*
3074** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
dan037b5322014-11-03 11:25:32 +00003075** command, or if either SQLITE_DEBUG or SQLITE_ENABLE_STMT_SCANSTATUS was
3076** defined at compile-time. If it is not a no-op, a single OP_Explain opcode
3077** is added to the output to describe the table scan strategy in pLevel.
3078**
3079** If an OP_Explain opcode is added to the VM, its address is returned.
3080** Otherwise, if no OP_Explain is coded, zero is returned.
dan17c0bc02010-11-09 17:35:19 +00003081*/
dan6f9702e2014-11-01 20:38:06 +00003082static int explainOneScan(
dan2ce22452010-11-08 19:01:16 +00003083 Parse *pParse, /* Parse context */
3084 SrcList *pTabList, /* Table list this loop refers to */
dan6f9702e2014-11-01 20:38:06 +00003085 WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
dan2ce22452010-11-08 19:01:16 +00003086 int iLevel, /* Value for "level" column of output */
dan6f9702e2014-11-01 20:38:06 +00003087 int iFrom, /* Value for "from" column of output */
dan4a07e3d2010-11-09 14:48:59 +00003088 u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
dan2ce22452010-11-08 19:01:16 +00003089){
dan6f9702e2014-11-01 20:38:06 +00003090 int ret = 0;
dan43764a82014-11-01 21:00:04 +00003091#if !defined(SQLITE_DEBUG) && !defined(SQLITE_ENABLE_STMT_SCANSTATUS)
drh84e55a82013-11-13 17:58:23 +00003092 if( pParse->explain==2 )
3093#endif
3094 {
dan2ce22452010-11-08 19:01:16 +00003095 struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
dan17c0bc02010-11-09 17:35:19 +00003096 Vdbe *v = pParse->pVdbe; /* VM being constructed */
3097 sqlite3 *db = pParse->db; /* Database handle */
dan6f9702e2014-11-01 20:38:06 +00003098 int iId = pParse->iSelectId; /* Select id (left-most output column) */
dan4bc39fa2010-11-13 16:42:27 +00003099 int isSearch; /* True for a SEARCH. False for SCAN. */
drhef866372013-05-22 20:49:02 +00003100 WhereLoop *pLoop; /* The controlling WhereLoop object */
3101 u32 flags; /* Flags that describe this loop */
dan6f9702e2014-11-01 20:38:06 +00003102 char *zMsg; /* Text to add to EQP output */
drh6c977892014-10-10 15:47:46 +00003103 StrAccum str; /* EQP output string */
3104 char zBuf[100]; /* Initial space for EQP output string */
dan2ce22452010-11-08 19:01:16 +00003105
drhef866372013-05-22 20:49:02 +00003106 pLoop = pLevel->pWLoop;
3107 flags = pLoop->wsFlags;
dan6f9702e2014-11-01 20:38:06 +00003108 if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return 0;
dan2ce22452010-11-08 19:01:16 +00003109
drhef866372013-05-22 20:49:02 +00003110 isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
3111 || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
3112 || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
dan6f9702e2014-11-01 20:38:06 +00003113
drhc0490572015-05-02 11:45:53 +00003114 sqlite3StrAccumInit(&str, db, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH);
drh6c977892014-10-10 15:47:46 +00003115 sqlite3StrAccumAppendAll(&str, isSearch ? "SEARCH" : "SCAN");
dan4a07e3d2010-11-09 14:48:59 +00003116 if( pItem->pSelect ){
drh6c977892014-10-10 15:47:46 +00003117 sqlite3XPrintf(&str, 0, " SUBQUERY %d", pItem->iSelectId);
dan4a07e3d2010-11-09 14:48:59 +00003118 }else{
drh6c977892014-10-10 15:47:46 +00003119 sqlite3XPrintf(&str, 0, " TABLE %s", pItem->zName);
dan4a07e3d2010-11-09 14:48:59 +00003120 }
3121
dan2ce22452010-11-08 19:01:16 +00003122 if( pItem->zAlias ){
drh6c977892014-10-10 15:47:46 +00003123 sqlite3XPrintf(&str, 0, " AS %s", pItem->zAlias);
dan2ce22452010-11-08 19:01:16 +00003124 }
drh6c977892014-10-10 15:47:46 +00003125 if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0 ){
3126 const char *zFmt = 0;
3127 Index *pIdx;
3128
3129 assert( pLoop->u.btree.pIndex!=0 );
3130 pIdx = pLoop->u.btree.pIndex;
dane96f2df2014-05-23 17:17:06 +00003131 assert( !(flags&WHERE_AUTO_INDEX) || (flags&WHERE_IDX_ONLY) );
drh48dd1d82014-05-27 18:18:58 +00003132 if( !HasRowid(pItem->pTab) && IsPrimaryKeyIndex(pIdx) ){
drhc631faa2014-10-11 01:22:16 +00003133 if( isSearch ){
drh6c977892014-10-10 15:47:46 +00003134 zFmt = "PRIMARY KEY";
3135 }
drh051575c2014-10-25 12:28:25 +00003136 }else if( flags & WHERE_PARTIALIDX ){
3137 zFmt = "AUTOMATIC PARTIAL COVERING INDEX";
dane96f2df2014-05-23 17:17:06 +00003138 }else if( flags & WHERE_AUTO_INDEX ){
drh6c977892014-10-10 15:47:46 +00003139 zFmt = "AUTOMATIC COVERING INDEX";
dane96f2df2014-05-23 17:17:06 +00003140 }else if( flags & WHERE_IDX_ONLY ){
drh6c977892014-10-10 15:47:46 +00003141 zFmt = "COVERING INDEX %s";
dane96f2df2014-05-23 17:17:06 +00003142 }else{
drh6c977892014-10-10 15:47:46 +00003143 zFmt = "INDEX %s";
dane96f2df2014-05-23 17:17:06 +00003144 }
drh6c977892014-10-10 15:47:46 +00003145 if( zFmt ){
3146 sqlite3StrAccumAppend(&str, " USING ", 7);
3147 sqlite3XPrintf(&str, 0, zFmt, pIdx->zName);
3148 explainIndexRange(&str, pLoop, pItem->pTab);
3149 }
drhef71c1f2013-06-04 12:58:02 +00003150 }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
drh6c977892014-10-10 15:47:46 +00003151 const char *zRange;
drh8e23daf2013-06-11 13:30:04 +00003152 if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
drh6c977892014-10-10 15:47:46 +00003153 zRange = "(rowid=?)";
drh04098e62010-11-15 21:50:19 +00003154 }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
drh6c977892014-10-10 15:47:46 +00003155 zRange = "(rowid>? AND rowid<?)";
dan2ce22452010-11-08 19:01:16 +00003156 }else if( flags&WHERE_BTM_LIMIT ){
drh6c977892014-10-10 15:47:46 +00003157 zRange = "(rowid>?)";
3158 }else{
3159 assert( flags&WHERE_TOP_LIMIT);
3160 zRange = "(rowid<?)";
dan2ce22452010-11-08 19:01:16 +00003161 }
drh6c977892014-10-10 15:47:46 +00003162 sqlite3StrAccumAppendAll(&str, " USING INTEGER PRIMARY KEY ");
3163 sqlite3StrAccumAppendAll(&str, zRange);
dan2ce22452010-11-08 19:01:16 +00003164 }
3165#ifndef SQLITE_OMIT_VIRTUALTABLE
3166 else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
drh6c977892014-10-10 15:47:46 +00003167 sqlite3XPrintf(&str, 0, " VIRTUAL TABLE INDEX %d:%s",
drhef866372013-05-22 20:49:02 +00003168 pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
dan2ce22452010-11-08 19:01:16 +00003169 }
3170#endif
drh98545bb2014-10-10 17:20:39 +00003171#ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS
dan6f9702e2014-11-01 20:38:06 +00003172 if( pLoop->nOut>=10 ){
3173 sqlite3XPrintf(&str, 0, " (~%llu rows)", sqlite3LogEstToInt(pLoop->nOut));
3174 }else{
3175 sqlite3StrAccumAppend(&str, " (~1 row)", 9);
dan04489b62014-10-31 20:11:32 +00003176 }
dan6f9702e2014-11-01 20:38:06 +00003177#endif
3178 zMsg = sqlite3StrAccumFinish(&str);
3179 ret = sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg,P4_DYNAMIC);
dan2ce22452010-11-08 19:01:16 +00003180 }
dan6f9702e2014-11-01 20:38:06 +00003181 return ret;
dan2ce22452010-11-08 19:01:16 +00003182}
3183#else
dan6f9702e2014-11-01 20:38:06 +00003184# define explainOneScan(u,v,w,x,y,z) 0
3185#endif /* SQLITE_OMIT_EXPLAIN */
3186
3187#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
dan037b5322014-11-03 11:25:32 +00003188/*
3189** Configure the VM passed as the first argument with an
3190** sqlite3_stmt_scanstatus() entry corresponding to the scan used to
3191** implement level pLvl. Argument pSrclist is a pointer to the FROM
3192** clause that the scan reads data from.
3193**
3194** If argument addrExplain is not 0, it must be the address of an
3195** OP_Explain instruction that describes the same loop.
3196*/
dan6f9702e2014-11-01 20:38:06 +00003197static void addScanStatus(
dan037b5322014-11-03 11:25:32 +00003198 Vdbe *v, /* Vdbe to add scanstatus entry to */
3199 SrcList *pSrclist, /* FROM clause pLvl reads data from */
3200 WhereLevel *pLvl, /* Level to add scanstatus() entry for */
3201 int addrExplain /* Address of OP_Explain (or 0) */
dan6f9702e2014-11-01 20:38:06 +00003202){
3203 const char *zObj = 0;
dan6f9702e2014-11-01 20:38:06 +00003204 WhereLoop *pLoop = pLvl->pWLoop;
drhcd934c32014-12-05 21:18:19 +00003205 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 && pLoop->u.btree.pIndex!=0 ){
dan6f9702e2014-11-01 20:38:06 +00003206 zObj = pLoop->u.btree.pIndex->zName;
3207 }else{
3208 zObj = pSrclist->a[pLvl->iFrom].zName;
3209 }
dan037b5322014-11-03 11:25:32 +00003210 sqlite3VdbeScanStatus(
drh518140e2014-11-06 03:55:10 +00003211 v, addrExplain, pLvl->addrBody, pLvl->addrVisit, pLoop->nOut, zObj
dan6f9702e2014-11-01 20:38:06 +00003212 );
3213}
3214#else
dane2f771b2014-11-03 15:33:17 +00003215# define addScanStatus(a, b, c, d) ((void)d)
dan6f9702e2014-11-01 20:38:06 +00003216#endif
3217
drhf07cf6e2015-03-06 16:45:16 +00003218/*
drha40da622015-03-09 12:11:56 +00003219** If the most recently coded instruction is a constant range contraint
3220** that originated from the LIKE optimization, then change the P3 to be
drhf07cf6e2015-03-06 16:45:16 +00003221** pLoop->iLikeRepCntr and set P5.
3222**
drh16897072015-03-07 00:57:37 +00003223** The LIKE optimization trys to evaluate "x LIKE 'abc%'" as a range
3224** expression: "x>='ABC' AND x<'abd'". But this requires that the range
3225** scan loop run twice, once for strings and a second time for BLOBs.
3226** The OP_String opcodes on the second pass convert the upper and lower
3227** bound string contants to blobs. This routine makes the necessary changes
3228** to the OP_String opcodes for that to happen.
drhf07cf6e2015-03-06 16:45:16 +00003229*/
drh52fc05b2015-03-07 20:32:49 +00003230static void whereLikeOptimizationStringFixup(
3231 Vdbe *v, /* prepared statement under construction */
3232 WhereLevel *pLevel, /* The loop that contains the LIKE operator */
3233 WhereTerm *pTerm /* The upper or lower bound just coded */
3234){
3235 if( pTerm->wtFlags & TERM_LIKEOPT ){
drha40da622015-03-09 12:11:56 +00003236 VdbeOp *pOp;
3237 assert( pLevel->iLikeRepCntr>0 );
3238 pOp = sqlite3VdbeGetOp(v, -1);
3239 assert( pOp!=0 );
3240 assert( pOp->opcode==OP_String8
3241 || pTerm->pWC->pWInfo->pParse->db->mallocFailed );
drhf07cf6e2015-03-06 16:45:16 +00003242 pOp->p3 = pLevel->iLikeRepCntr;
3243 pOp->p5 = 1;
3244 }
3245}
dan2ce22452010-11-08 19:01:16 +00003246
drh111a6a72008-12-21 03:51:16 +00003247/*
3248** Generate code for the start of the iLevel-th loop in the WHERE clause
3249** implementation described by pWInfo.
3250*/
3251static Bitmask codeOneLoopStart(
3252 WhereInfo *pWInfo, /* Complete information about the WHERE clause */
3253 int iLevel, /* Which level of pWInfo->a[] should be coded */
drh7a484802012-03-16 00:28:11 +00003254 Bitmask notReady /* Which tables are currently available */
drh111a6a72008-12-21 03:51:16 +00003255){
3256 int j, k; /* Loop counters */
3257 int iCur; /* The VDBE cursor for the table */
3258 int addrNxt; /* Where to jump to continue with the next IN case */
3259 int omitTable; /* True if we use the index only */
3260 int bRev; /* True if we need to scan in reverse order */
3261 WhereLevel *pLevel; /* The where level to be coded */
drh7ba39a92013-05-30 17:43:19 +00003262 WhereLoop *pLoop; /* The WhereLoop object being coded */
drh111a6a72008-12-21 03:51:16 +00003263 WhereClause *pWC; /* Decomposition of the entire WHERE clause */
3264 WhereTerm *pTerm; /* A WHERE clause term */
3265 Parse *pParse; /* Parsing context */
drh6b36e822013-07-30 15:10:32 +00003266 sqlite3 *db; /* Database connection */
drh111a6a72008-12-21 03:51:16 +00003267 Vdbe *v; /* The prepared stmt under constructions */
3268 struct SrcList_item *pTabItem; /* FROM clause term being coded */
drh23d04d52008-12-23 23:56:22 +00003269 int addrBrk; /* Jump here to break out of the loop */
3270 int addrCont; /* Jump here to continue with next cycle */
drh61495262009-04-22 15:32:59 +00003271 int iRowidReg = 0; /* Rowid is stored in this register, if not zero */
3272 int iReleaseReg = 0; /* Temp register to free before returning */
drh111a6a72008-12-21 03:51:16 +00003273
3274 pParse = pWInfo->pParse;
3275 v = pParse->pVdbe;
drh70d18342013-06-06 19:16:33 +00003276 pWC = &pWInfo->sWC;
drh6b36e822013-07-30 15:10:32 +00003277 db = pParse->db;
drh111a6a72008-12-21 03:51:16 +00003278 pLevel = &pWInfo->a[iLevel];
drh7ba39a92013-05-30 17:43:19 +00003279 pLoop = pLevel->pWLoop;
drh111a6a72008-12-21 03:51:16 +00003280 pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
3281 iCur = pTabItem->iCursor;
drh0259bc32013-09-09 19:37:46 +00003282 pLevel->notReady = notReady & ~getMask(&pWInfo->sMaskSet, iCur);
drh7ba39a92013-05-30 17:43:19 +00003283 bRev = (pWInfo->revMask>>iLevel)&1;
3284 omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
drh70d18342013-06-06 19:16:33 +00003285 && (pWInfo->wctrlFlags & WHERE_FORCE_TABLE)==0;
drh6bc69a22013-11-19 12:33:23 +00003286 VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName));
drh111a6a72008-12-21 03:51:16 +00003287
3288 /* Create labels for the "break" and "continue" instructions
3289 ** for the current loop. Jump to addrBrk to break out of a loop.
3290 ** Jump to cont to go immediately to the next iteration of the
3291 ** loop.
3292 **
3293 ** When there is an IN operator, we also have a "addrNxt" label that
3294 ** means to continue with the next IN value combination. When
3295 ** there are no IN operators in the constraints, the "addrNxt" label
3296 ** is the same as "addrBrk".
3297 */
3298 addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
3299 addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
3300
3301 /* If this is the right table of a LEFT OUTER JOIN, allocate and
3302 ** initialize a memory cell that records if this table matches any
3303 ** row of the left table of the join.
3304 */
3305 if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
3306 pLevel->iLeftJoin = ++pParse->nMem;
3307 sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
3308 VdbeComment((v, "init LEFT JOIN no-match flag"));
3309 }
3310
drh21172c42012-10-30 00:29:07 +00003311 /* Special case of a FROM clause subquery implemented as a co-routine */
3312 if( pTabItem->viaCoroutine ){
3313 int regYield = pTabItem->regReturn;
drhed71a832014-02-07 19:18:10 +00003314 sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
drh81cf13e2014-02-07 18:27:53 +00003315 pLevel->p2 = sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk);
drh688852a2014-02-17 22:40:43 +00003316 VdbeCoverage(v);
drh725de292014-02-08 13:12:19 +00003317 VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
drh21172c42012-10-30 00:29:07 +00003318 pLevel->op = OP_Goto;
3319 }else
3320
drh111a6a72008-12-21 03:51:16 +00003321#ifndef SQLITE_OMIT_VIRTUALTABLE
drh7ba39a92013-05-30 17:43:19 +00003322 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
3323 /* Case 1: The table is a virtual-table. Use the VFilter and VNext
drh111a6a72008-12-21 03:51:16 +00003324 ** to access the data.
3325 */
3326 int iReg; /* P3 Value for OP_VFilter */
drh281bbe22012-10-16 23:17:14 +00003327 int addrNotFound;
drh4efc9292013-06-06 23:02:03 +00003328 int nConstraint = pLoop->nLTerm;
drh111a6a72008-12-21 03:51:16 +00003329
drha62bb8d2009-11-23 21:23:45 +00003330 sqlite3ExprCachePush(pParse);
drh111a6a72008-12-21 03:51:16 +00003331 iReg = sqlite3GetTempRange(pParse, nConstraint+2);
drh281bbe22012-10-16 23:17:14 +00003332 addrNotFound = pLevel->addrBrk;
drh111a6a72008-12-21 03:51:16 +00003333 for(j=0; j<nConstraint; j++){
drhe2250172013-05-31 18:13:50 +00003334 int iTarget = iReg+j+2;
drh4efc9292013-06-06 23:02:03 +00003335 pTerm = pLoop->aLTerm[j];
drh95ed68d2013-06-12 17:55:50 +00003336 if( pTerm==0 ) continue;
drh7ba39a92013-05-30 17:43:19 +00003337 if( pTerm->eOperator & WO_IN ){
3338 codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
3339 addrNotFound = pLevel->addrNxt;
3340 }else{
3341 sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget);
3342 }
3343 }
3344 sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
drh7e47cb82013-05-31 17:55:27 +00003345 sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
drh7ba39a92013-05-30 17:43:19 +00003346 sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
3347 pLoop->u.vtab.idxStr,
3348 pLoop->u.vtab.needFree ? P4_MPRINTF : P4_STATIC);
drh688852a2014-02-17 22:40:43 +00003349 VdbeCoverage(v);
drh7ba39a92013-05-30 17:43:19 +00003350 pLoop->u.vtab.needFree = 0;
3351 for(j=0; j<nConstraint && j<16; j++){
3352 if( (pLoop->u.vtab.omitMask>>j)&1 ){
drh4efc9292013-06-06 23:02:03 +00003353 disableTerm(pLevel, pLoop->aLTerm[j]);
drh111a6a72008-12-21 03:51:16 +00003354 }
3355 }
3356 pLevel->op = OP_VNext;
3357 pLevel->p1 = iCur;
3358 pLevel->p2 = sqlite3VdbeCurrentAddr(v);
drh23d04d52008-12-23 23:56:22 +00003359 sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
drhd2490902014-04-13 19:28:15 +00003360 sqlite3ExprCachePop(pParse);
drh111a6a72008-12-21 03:51:16 +00003361 }else
3362#endif /* SQLITE_OMIT_VIRTUALTABLE */
3363
drh7ba39a92013-05-30 17:43:19 +00003364 if( (pLoop->wsFlags & WHERE_IPK)!=0
3365 && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
3366 ){
3367 /* Case 2: We can directly reference a single row using an
drh111a6a72008-12-21 03:51:16 +00003368 ** equality comparison against the ROWID field. Or
3369 ** we reference multiple rows using a "rowid IN (...)"
3370 ** construct.
3371 */
drh7ba39a92013-05-30 17:43:19 +00003372 assert( pLoop->u.btree.nEq==1 );
drh4efc9292013-06-06 23:02:03 +00003373 pTerm = pLoop->aLTerm[0];
drh111a6a72008-12-21 03:51:16 +00003374 assert( pTerm!=0 );
3375 assert( pTerm->pExpr!=0 );
drh111a6a72008-12-21 03:51:16 +00003376 assert( omitTable==0 );
drh39759742013-08-02 23:40:45 +00003377 testcase( pTerm->wtFlags & TERM_VIRTUAL );
drh0baa0352014-02-25 21:55:16 +00003378 iReleaseReg = ++pParse->nMem;
drh7ba39a92013-05-30 17:43:19 +00003379 iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
drh0baa0352014-02-25 21:55:16 +00003380 if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg);
drh111a6a72008-12-21 03:51:16 +00003381 addrNxt = pLevel->addrNxt;
drh688852a2014-02-17 22:40:43 +00003382 sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt); VdbeCoverage(v);
danielk19771d461462009-04-21 09:02:45 +00003383 sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
drh688852a2014-02-17 22:40:43 +00003384 VdbeCoverage(v);
drh459f63e2013-03-06 01:55:27 +00003385 sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
drhceea3322009-04-23 13:22:42 +00003386 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
drh111a6a72008-12-21 03:51:16 +00003387 VdbeComment((v, "pk"));
3388 pLevel->op = OP_Noop;
drh7ba39a92013-05-30 17:43:19 +00003389 }else if( (pLoop->wsFlags & WHERE_IPK)!=0
3390 && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
3391 ){
3392 /* Case 3: We have an inequality comparison against the ROWID field.
drh111a6a72008-12-21 03:51:16 +00003393 */
3394 int testOp = OP_Noop;
3395 int start;
3396 int memEndValue = 0;
3397 WhereTerm *pStart, *pEnd;
3398
3399 assert( omitTable==0 );
drh7ba39a92013-05-30 17:43:19 +00003400 j = 0;
3401 pStart = pEnd = 0;
drh4efc9292013-06-06 23:02:03 +00003402 if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
3403 if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
drh81186b42013-06-18 01:52:41 +00003404 assert( pStart!=0 || pEnd!=0 );
drh111a6a72008-12-21 03:51:16 +00003405 if( bRev ){
3406 pTerm = pStart;
3407 pStart = pEnd;
3408 pEnd = pTerm;
3409 }
3410 if( pStart ){
3411 Expr *pX; /* The expression that defines the start bound */
3412 int r1, rTemp; /* Registers for holding the start boundary */
3413
3414 /* The following constant maps TK_xx codes into corresponding
3415 ** seek opcodes. It depends on a particular ordering of TK_xx
3416 */
3417 const u8 aMoveOp[] = {
drh4a1d3652014-02-14 15:13:36 +00003418 /* TK_GT */ OP_SeekGT,
3419 /* TK_LE */ OP_SeekLE,
3420 /* TK_LT */ OP_SeekLT,
3421 /* TK_GE */ OP_SeekGE
drh111a6a72008-12-21 03:51:16 +00003422 };
3423 assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */
3424 assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */
3425 assert( TK_GE==TK_GT+3 ); /* ... is correcct. */
3426
drhb5246e52013-07-08 21:12:57 +00003427 assert( (pStart->wtFlags & TERM_VNULL)==0 );
drh39759742013-08-02 23:40:45 +00003428 testcase( pStart->wtFlags & TERM_VIRTUAL );
drh111a6a72008-12-21 03:51:16 +00003429 pX = pStart->pExpr;
3430 assert( pX!=0 );
drhb5246e52013-07-08 21:12:57 +00003431 testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
drh111a6a72008-12-21 03:51:16 +00003432 r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
3433 sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
drh7d176102014-02-18 03:07:12 +00003434 VdbeComment((v, "pk"));
3435 VdbeCoverageIf(v, pX->op==TK_GT);
3436 VdbeCoverageIf(v, pX->op==TK_LE);
3437 VdbeCoverageIf(v, pX->op==TK_LT);
3438 VdbeCoverageIf(v, pX->op==TK_GE);
drh111a6a72008-12-21 03:51:16 +00003439 sqlite3ExprCacheAffinityChange(pParse, r1, 1);
3440 sqlite3ReleaseTempReg(pParse, rTemp);
3441 disableTerm(pLevel, pStart);
3442 }else{
3443 sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
drh7d176102014-02-18 03:07:12 +00003444 VdbeCoverageIf(v, bRev==0);
3445 VdbeCoverageIf(v, bRev!=0);
drh111a6a72008-12-21 03:51:16 +00003446 }
3447 if( pEnd ){
3448 Expr *pX;
3449 pX = pEnd->pExpr;
3450 assert( pX!=0 );
drhb5246e52013-07-08 21:12:57 +00003451 assert( (pEnd->wtFlags & TERM_VNULL)==0 );
3452 testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
drh39759742013-08-02 23:40:45 +00003453 testcase( pEnd->wtFlags & TERM_VIRTUAL );
drh111a6a72008-12-21 03:51:16 +00003454 memEndValue = ++pParse->nMem;
3455 sqlite3ExprCode(pParse, pX->pRight, memEndValue);
3456 if( pX->op==TK_LT || pX->op==TK_GT ){
3457 testOp = bRev ? OP_Le : OP_Ge;
3458 }else{
3459 testOp = bRev ? OP_Lt : OP_Gt;
3460 }
3461 disableTerm(pLevel, pEnd);
3462 }
3463 start = sqlite3VdbeCurrentAddr(v);
3464 pLevel->op = bRev ? OP_Prev : OP_Next;
3465 pLevel->p1 = iCur;
3466 pLevel->p2 = start;
drh81186b42013-06-18 01:52:41 +00003467 assert( pLevel->p5==0 );
danielk19771d461462009-04-21 09:02:45 +00003468 if( testOp!=OP_Noop ){
drh0baa0352014-02-25 21:55:16 +00003469 iRowidReg = ++pParse->nMem;
danielk19771d461462009-04-21 09:02:45 +00003470 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
drhceea3322009-04-23 13:22:42 +00003471 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
danielk19771d461462009-04-21 09:02:45 +00003472 sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
drh7d176102014-02-18 03:07:12 +00003473 VdbeCoverageIf(v, testOp==OP_Le);
3474 VdbeCoverageIf(v, testOp==OP_Lt);
3475 VdbeCoverageIf(v, testOp==OP_Ge);
3476 VdbeCoverageIf(v, testOp==OP_Gt);
danielk19771d461462009-04-21 09:02:45 +00003477 sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
drh111a6a72008-12-21 03:51:16 +00003478 }
drh1b0f0262013-05-30 22:27:09 +00003479 }else if( pLoop->wsFlags & WHERE_INDEXED ){
drh7ba39a92013-05-30 17:43:19 +00003480 /* Case 4: A scan using an index.
drh111a6a72008-12-21 03:51:16 +00003481 **
3482 ** The WHERE clause may contain zero or more equality
3483 ** terms ("==" or "IN" operators) that refer to the N
3484 ** left-most columns of the index. It may also contain
3485 ** inequality constraints (>, <, >= or <=) on the indexed
3486 ** column that immediately follows the N equalities. Only
3487 ** the right-most column can be an inequality - the rest must
3488 ** use the "==" and "IN" operators. For example, if the
3489 ** index is on (x,y,z), then the following clauses are all
3490 ** optimized:
3491 **
3492 ** x=5
3493 ** x=5 AND y=10
3494 ** x=5 AND y<10
3495 ** x=5 AND y>5 AND y<10
3496 ** x=5 AND y=5 AND z<=10
3497 **
3498 ** The z<10 term of the following cannot be used, only
3499 ** the x=5 term:
3500 **
3501 ** x=5 AND z<10
3502 **
3503 ** N may be zero if there are inequality constraints.
3504 ** If there are no inequality constraints, then N is at
3505 ** least one.
3506 **
3507 ** This case is also used when there are no WHERE clause
3508 ** constraints but an index is selected anyway, in order
3509 ** to force the output order to conform to an ORDER BY.
3510 */
drh3bb9b932010-08-06 02:10:00 +00003511 static const u8 aStartOp[] = {
drh111a6a72008-12-21 03:51:16 +00003512 0,
3513 0,
3514 OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */
3515 OP_Last, /* 3: (!start_constraints && startEq && bRev) */
drh4a1d3652014-02-14 15:13:36 +00003516 OP_SeekGT, /* 4: (start_constraints && !startEq && !bRev) */
3517 OP_SeekLT, /* 5: (start_constraints && !startEq && bRev) */
3518 OP_SeekGE, /* 6: (start_constraints && startEq && !bRev) */
3519 OP_SeekLE /* 7: (start_constraints && startEq && bRev) */
drh111a6a72008-12-21 03:51:16 +00003520 };
drh3bb9b932010-08-06 02:10:00 +00003521 static const u8 aEndOp[] = {
drh4a1d3652014-02-14 15:13:36 +00003522 OP_IdxGE, /* 0: (end_constraints && !bRev && !endEq) */
3523 OP_IdxGT, /* 1: (end_constraints && !bRev && endEq) */
3524 OP_IdxLE, /* 2: (end_constraints && bRev && !endEq) */
3525 OP_IdxLT, /* 3: (end_constraints && bRev && endEq) */
drh111a6a72008-12-21 03:51:16 +00003526 };
drhcd8629e2013-11-13 12:27:25 +00003527 u16 nEq = pLoop->u.btree.nEq; /* Number of == or IN terms */
drh111a6a72008-12-21 03:51:16 +00003528 int regBase; /* Base register holding constraint values */
drh111a6a72008-12-21 03:51:16 +00003529 WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */
3530 WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */
3531 int startEq; /* True if range start uses ==, >= or <= */
3532 int endEq; /* True if range end uses ==, >= or <= */
3533 int start_constraints; /* Start of range is constrained */
3534 int nConstraint; /* Number of constraint terms */
drh3bb9b932010-08-06 02:10:00 +00003535 Index *pIdx; /* The index we will be using */
3536 int iIdxCur; /* The VDBE cursor for the index */
3537 int nExtraReg = 0; /* Number of extra registers needed */
3538 int op; /* Instruction opcode */
dan6ac43392010-06-09 15:47:11 +00003539 char *zStartAff; /* Affinity for start of range constraint */
drh33cad2f2013-11-15 12:41:01 +00003540 char cEndAff = 0; /* Affinity for end of range constraint */
drhcfc6ca42014-02-14 23:49:13 +00003541 u8 bSeekPastNull = 0; /* True to seek past initial nulls */
3542 u8 bStopAtNull = 0; /* Add condition to terminate at NULLs */
drh111a6a72008-12-21 03:51:16 +00003543
drh7ba39a92013-05-30 17:43:19 +00003544 pIdx = pLoop->u.btree.pIndex;
drh111a6a72008-12-21 03:51:16 +00003545 iIdxCur = pLevel->iIdxCur;
drhc8bbce12014-10-21 01:05:09 +00003546 assert( nEq>=pLoop->nSkip );
drh111a6a72008-12-21 03:51:16 +00003547
drh111a6a72008-12-21 03:51:16 +00003548 /* If this loop satisfies a sort order (pOrderBy) request that
3549 ** was passed to this function to implement a "SELECT min(x) ..."
3550 ** query, then the caller will only allow the loop to run for
3551 ** a single iteration. This means that the first row returned
3552 ** should not have a NULL value stored in 'x'. If column 'x' is
3553 ** the first one after the nEq equality constraints in the index,
3554 ** this requires some special handling.
3555 */
drhddba0c22014-03-18 20:33:42 +00003556 assert( pWInfo->pOrderBy==0
3557 || pWInfo->pOrderBy->nExpr==1
3558 || (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0 );
drh70d18342013-06-06 19:16:33 +00003559 if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
drhddba0c22014-03-18 20:33:42 +00003560 && pWInfo->nOBSat>0
drhbbbdc832013-10-22 18:01:40 +00003561 && (pIdx->nKeyCol>nEq)
drh111a6a72008-12-21 03:51:16 +00003562 ){
drhc8bbce12014-10-21 01:05:09 +00003563 assert( pLoop->nSkip==0 );
drhcfc6ca42014-02-14 23:49:13 +00003564 bSeekPastNull = 1;
drh6df2acd2008-12-28 16:55:25 +00003565 nExtraReg = 1;
drh111a6a72008-12-21 03:51:16 +00003566 }
3567
3568 /* Find any inequality constraint terms for the start and end
3569 ** of the range.
3570 */
drh7ba39a92013-05-30 17:43:19 +00003571 j = nEq;
3572 if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
drh4efc9292013-06-06 23:02:03 +00003573 pRangeStart = pLoop->aLTerm[j++];
drh6df2acd2008-12-28 16:55:25 +00003574 nExtraReg = 1;
drh80314622015-03-09 13:01:02 +00003575 /* Like optimization range constraints always occur in pairs */
3576 assert( (pRangeStart->wtFlags & TERM_LIKEOPT)==0 ||
3577 (pLoop->wsFlags & WHERE_TOP_LIMIT)!=0 );
drh111a6a72008-12-21 03:51:16 +00003578 }
drh7ba39a92013-05-30 17:43:19 +00003579 if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
drh4efc9292013-06-06 23:02:03 +00003580 pRangeEnd = pLoop->aLTerm[j++];
drh6df2acd2008-12-28 16:55:25 +00003581 nExtraReg = 1;
drha40da622015-03-09 12:11:56 +00003582 if( (pRangeEnd->wtFlags & TERM_LIKEOPT)!=0 ){
drh80314622015-03-09 13:01:02 +00003583 assert( pRangeStart!=0 ); /* LIKE opt constraints */
3584 assert( pRangeStart->wtFlags & TERM_LIKEOPT ); /* occur in pairs */
drhf07cf6e2015-03-06 16:45:16 +00003585 pLevel->iLikeRepCntr = ++pParse->nMem;
drhb7c60ba2015-03-07 02:51:59 +00003586 testcase( bRev );
3587 testcase( pIdx->aSortOrder[nEq]==SQLITE_SO_DESC );
3588 sqlite3VdbeAddOp2(v, OP_Integer,
3589 bRev ^ (pIdx->aSortOrder[nEq]==SQLITE_SO_DESC),
3590 pLevel->iLikeRepCntr);
drh16897072015-03-07 00:57:37 +00003591 VdbeComment((v, "LIKE loop counter"));
drhf07cf6e2015-03-06 16:45:16 +00003592 pLevel->addrLikeRep = sqlite3VdbeCurrentAddr(v);
3593 }
drhcfc6ca42014-02-14 23:49:13 +00003594 if( pRangeStart==0
drhcfc6ca42014-02-14 23:49:13 +00003595 && (j = pIdx->aiColumn[nEq])>=0
3596 && pIdx->pTable->aCol[j].notNull==0
3597 ){
3598 bSeekPastNull = 1;
3599 }
drh111a6a72008-12-21 03:51:16 +00003600 }
dan0df163a2014-03-06 12:36:26 +00003601 assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 );
drh111a6a72008-12-21 03:51:16 +00003602
drh6df2acd2008-12-28 16:55:25 +00003603 /* Generate code to evaluate all constraint terms using == or IN
3604 ** and store the values of those terms in an array of registers
3605 ** starting at regBase.
3606 */
drh613ba1e2013-06-15 15:11:45 +00003607 regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
drh33cad2f2013-11-15 12:41:01 +00003608 assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq );
3609 if( zStartAff ) cEndAff = zStartAff[nEq];
drh6df2acd2008-12-28 16:55:25 +00003610 addrNxt = pLevel->addrNxt;
3611
drh111a6a72008-12-21 03:51:16 +00003612 /* If we are doing a reverse order scan on an ascending index, or
3613 ** a forward order scan on a descending index, interchange the
3614 ** start and end terms (pRangeStart and pRangeEnd).
3615 */
drhbbbdc832013-10-22 18:01:40 +00003616 if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
3617 || (bRev && pIdx->nKeyCol==nEq)
dan0c733f62011-11-16 15:27:09 +00003618 ){
drh111a6a72008-12-21 03:51:16 +00003619 SWAP(WhereTerm *, pRangeEnd, pRangeStart);
drhcfc6ca42014-02-14 23:49:13 +00003620 SWAP(u8, bSeekPastNull, bStopAtNull);
drh111a6a72008-12-21 03:51:16 +00003621 }
3622
drh7963b0e2013-06-17 21:37:40 +00003623 testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
3624 testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
3625 testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
3626 testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
drh111a6a72008-12-21 03:51:16 +00003627 startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
3628 endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
3629 start_constraints = pRangeStart || nEq>0;
3630
3631 /* Seek the index cursor to the start of the range. */
3632 nConstraint = nEq;
3633 if( pRangeStart ){
dan69f8bb92009-08-13 19:21:16 +00003634 Expr *pRight = pRangeStart->pExpr->pRight;
3635 sqlite3ExprCode(pParse, pRight, regBase+nEq);
drh52fc05b2015-03-07 20:32:49 +00003636 whereLikeOptimizationStringFixup(v, pLevel, pRangeStart);
drh9be18702015-05-13 19:33:41 +00003637 if( (pRangeStart->wtFlags & TERM_VNULL)==0
drh7d176102014-02-18 03:07:12 +00003638 && sqlite3ExprCanBeNull(pRight)
3639 ){
3640 sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
3641 VdbeCoverage(v);
drh534230c2011-01-22 00:10:45 +00003642 }
dan6ac43392010-06-09 15:47:11 +00003643 if( zStartAff ){
3644 if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
drh039fc322009-11-17 18:31:47 +00003645 /* Since the comparison is to be performed with no conversions
3646 ** applied to the operands, set the affinity to apply to pRight to
3647 ** SQLITE_AFF_NONE. */
dan6ac43392010-06-09 15:47:11 +00003648 zStartAff[nEq] = SQLITE_AFF_NONE;
drh039fc322009-11-17 18:31:47 +00003649 }
dan6ac43392010-06-09 15:47:11 +00003650 if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
3651 zStartAff[nEq] = SQLITE_AFF_NONE;
drh039fc322009-11-17 18:31:47 +00003652 }
3653 }
drh111a6a72008-12-21 03:51:16 +00003654 nConstraint++;
drh39759742013-08-02 23:40:45 +00003655 testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
drhcfc6ca42014-02-14 23:49:13 +00003656 }else if( bSeekPastNull ){
drh111a6a72008-12-21 03:51:16 +00003657 sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
3658 nConstraint++;
3659 startEq = 0;
3660 start_constraints = 1;
3661 }
drhcfc6ca42014-02-14 23:49:13 +00003662 codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff);
drh111a6a72008-12-21 03:51:16 +00003663 op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
3664 assert( op!=0 );
drh8cff69d2009-11-12 19:59:44 +00003665 sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
drh688852a2014-02-17 22:40:43 +00003666 VdbeCoverage(v);
drh7d176102014-02-18 03:07:12 +00003667 VdbeCoverageIf(v, op==OP_Rewind); testcase( op==OP_Rewind );
3668 VdbeCoverageIf(v, op==OP_Last); testcase( op==OP_Last );
3669 VdbeCoverageIf(v, op==OP_SeekGT); testcase( op==OP_SeekGT );
3670 VdbeCoverageIf(v, op==OP_SeekGE); testcase( op==OP_SeekGE );
3671 VdbeCoverageIf(v, op==OP_SeekLE); testcase( op==OP_SeekLE );
3672 VdbeCoverageIf(v, op==OP_SeekLT); testcase( op==OP_SeekLT );
drh111a6a72008-12-21 03:51:16 +00003673
3674 /* Load the value for the inequality constraint at the end of the
3675 ** range (if any).
3676 */
3677 nConstraint = nEq;
3678 if( pRangeEnd ){
dan69f8bb92009-08-13 19:21:16 +00003679 Expr *pRight = pRangeEnd->pExpr->pRight;
drhf49f3522009-12-30 14:12:38 +00003680 sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
dan69f8bb92009-08-13 19:21:16 +00003681 sqlite3ExprCode(pParse, pRight, regBase+nEq);
drh52fc05b2015-03-07 20:32:49 +00003682 whereLikeOptimizationStringFixup(v, pLevel, pRangeEnd);
drh9be18702015-05-13 19:33:41 +00003683 if( (pRangeEnd->wtFlags & TERM_VNULL)==0
drh7d176102014-02-18 03:07:12 +00003684 && sqlite3ExprCanBeNull(pRight)
3685 ){
3686 sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
3687 VdbeCoverage(v);
drh534230c2011-01-22 00:10:45 +00003688 }
drh33cad2f2013-11-15 12:41:01 +00003689 if( sqlite3CompareAffinity(pRight, cEndAff)!=SQLITE_AFF_NONE
3690 && !sqlite3ExprNeedsNoAffinityChange(pRight, cEndAff)
3691 ){
3692 codeApplyAffinity(pParse, regBase+nEq, 1, &cEndAff);
3693 }
drh111a6a72008-12-21 03:51:16 +00003694 nConstraint++;
drh39759742013-08-02 23:40:45 +00003695 testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
drhcfc6ca42014-02-14 23:49:13 +00003696 }else if( bStopAtNull ){
3697 sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
3698 endEq = 0;
3699 nConstraint++;
drh111a6a72008-12-21 03:51:16 +00003700 }
drh6b36e822013-07-30 15:10:32 +00003701 sqlite3DbFree(db, zStartAff);
drh111a6a72008-12-21 03:51:16 +00003702
3703 /* Top of the loop body */
3704 pLevel->p2 = sqlite3VdbeCurrentAddr(v);
3705
3706 /* Check if the index cursor is past the end of the range. */
drhcfc6ca42014-02-14 23:49:13 +00003707 if( nConstraint ){
drh4a1d3652014-02-14 15:13:36 +00003708 op = aEndOp[bRev*2 + endEq];
drh8cff69d2009-11-12 19:59:44 +00003709 sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
drh7d176102014-02-18 03:07:12 +00003710 testcase( op==OP_IdxGT ); VdbeCoverageIf(v, op==OP_IdxGT );
3711 testcase( op==OP_IdxGE ); VdbeCoverageIf(v, op==OP_IdxGE );
3712 testcase( op==OP_IdxLT ); VdbeCoverageIf(v, op==OP_IdxLT );
3713 testcase( op==OP_IdxLE ); VdbeCoverageIf(v, op==OP_IdxLE );
drh6df2acd2008-12-28 16:55:25 +00003714 }
drh111a6a72008-12-21 03:51:16 +00003715
drh111a6a72008-12-21 03:51:16 +00003716 /* Seek the table cursor, if required */
drh23d04d52008-12-23 23:56:22 +00003717 disableTerm(pLevel, pRangeStart);
3718 disableTerm(pLevel, pRangeEnd);
drh85c1c552013-10-24 00:18:18 +00003719 if( omitTable ){
3720 /* pIdx is a covering index. No need to access the main table. */
3721 }else if( HasRowid(pIdx->pTable) ){
drh0baa0352014-02-25 21:55:16 +00003722 iRowidReg = ++pParse->nMem;
danielk19771d461462009-04-21 09:02:45 +00003723 sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
drhceea3322009-04-23 13:22:42 +00003724 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
danielk19771d461462009-04-21 09:02:45 +00003725 sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg); /* Deferred seek */
drha3bc66a2014-05-27 17:57:32 +00003726 }else if( iCur!=iIdxCur ){
drh85c1c552013-10-24 00:18:18 +00003727 Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
3728 iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol);
3729 for(j=0; j<pPk->nKeyCol; j++){
3730 k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
3731 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j);
3732 }
drh261c02d2013-10-25 14:46:15 +00003733 sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont,
drh688852a2014-02-17 22:40:43 +00003734 iRowidReg, pPk->nKeyCol); VdbeCoverage(v);
drh111a6a72008-12-21 03:51:16 +00003735 }
drh111a6a72008-12-21 03:51:16 +00003736
3737 /* Record the instruction used to terminate the loop. Disable
3738 ** WHERE clause terms made redundant by the index range scan.
3739 */
drh7699d1c2013-06-04 12:42:29 +00003740 if( pLoop->wsFlags & WHERE_ONEROW ){
drh95e037b2011-03-09 21:02:31 +00003741 pLevel->op = OP_Noop;
3742 }else if( bRev ){
3743 pLevel->op = OP_Prev;
3744 }else{
3745 pLevel->op = OP_Next;
3746 }
drh111a6a72008-12-21 03:51:16 +00003747 pLevel->p1 = iIdxCur;
drh0c8a9342014-03-20 12:17:35 +00003748 pLevel->p3 = (pLoop->wsFlags&WHERE_UNQ_WANTED)!=0 ? 1:0;
drh53cfbe92013-06-13 17:28:22 +00003749 if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
drh3f4d1d12012-09-15 18:45:54 +00003750 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
3751 }else{
3752 assert( pLevel->p5==0 );
3753 }
drhdd5f5a62008-12-23 13:35:23 +00003754 }else
3755
drh23d04d52008-12-23 23:56:22 +00003756#ifndef SQLITE_OMIT_OR_OPTIMIZATION
drh7ba39a92013-05-30 17:43:19 +00003757 if( pLoop->wsFlags & WHERE_MULTI_OR ){
3758 /* Case 5: Two or more separately indexed terms connected by OR
drh111a6a72008-12-21 03:51:16 +00003759 **
3760 ** Example:
3761 **
3762 ** CREATE TABLE t1(a,b,c,d);
3763 ** CREATE INDEX i1 ON t1(a);
3764 ** CREATE INDEX i2 ON t1(b);
3765 ** CREATE INDEX i3 ON t1(c);
3766 **
3767 ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
3768 **
3769 ** In the example, there are three indexed terms connected by OR.
danielk19771d461462009-04-21 09:02:45 +00003770 ** The top of the loop looks like this:
drh111a6a72008-12-21 03:51:16 +00003771 **
drh1b26c7c2009-04-22 02:15:47 +00003772 ** Null 1 # Zero the rowset in reg 1
drh111a6a72008-12-21 03:51:16 +00003773 **
danielk19771d461462009-04-21 09:02:45 +00003774 ** Then, for each indexed term, the following. The arguments to
drh1b26c7c2009-04-22 02:15:47 +00003775 ** RowSetTest are such that the rowid of the current row is inserted
3776 ** into the RowSet. If it is already present, control skips the
danielk19771d461462009-04-21 09:02:45 +00003777 ** Gosub opcode and jumps straight to the code generated by WhereEnd().
drh111a6a72008-12-21 03:51:16 +00003778 **
danielk19771d461462009-04-21 09:02:45 +00003779 ** sqlite3WhereBegin(<term>)
drh1b26c7c2009-04-22 02:15:47 +00003780 ** RowSetTest # Insert rowid into rowset
danielk19771d461462009-04-21 09:02:45 +00003781 ** Gosub 2 A
3782 ** sqlite3WhereEnd()
3783 **
3784 ** Following the above, code to terminate the loop. Label A, the target
3785 ** of the Gosub above, jumps to the instruction right after the Goto.
3786 **
drh1b26c7c2009-04-22 02:15:47 +00003787 ** Null 1 # Zero the rowset in reg 1
danielk19771d461462009-04-21 09:02:45 +00003788 ** Goto B # The loop is finished.
3789 **
3790 ** A: <loop body> # Return data, whatever.
3791 **
3792 ** Return 2 # Jump back to the Gosub
3793 **
3794 ** B: <after the loop>
3795 **
drh5609baf2014-05-26 22:01:00 +00003796 ** Added 2014-05-26: If the table is a WITHOUT ROWID table, then
peter.d.reid60ec9142014-09-06 16:39:46 +00003797 ** use an ephemeral index instead of a RowSet to record the primary
drh5609baf2014-05-26 22:01:00 +00003798 ** keys of the rows we have already seen.
3799 **
drh111a6a72008-12-21 03:51:16 +00003800 */
drh111a6a72008-12-21 03:51:16 +00003801 WhereClause *pOrWc; /* The OR-clause broken out into subterms */
drhc01a3c12009-12-16 22:10:49 +00003802 SrcList *pOrTab; /* Shortened table list or OR-clause generation */
dan0efb72c2012-08-24 18:44:56 +00003803 Index *pCov = 0; /* Potential covering index (or NULL) */
3804 int iCovCur = pParse->nTab++; /* Cursor used for index scans (if any) */
danielk19771d461462009-04-21 09:02:45 +00003805
3806 int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */
shane85095702009-06-15 16:27:08 +00003807 int regRowset = 0; /* Register for RowSet object */
3808 int regRowid = 0; /* Register holding rowid */
danielk19771d461462009-04-21 09:02:45 +00003809 int iLoopBody = sqlite3VdbeMakeLabel(v); /* Start of loop body */
3810 int iRetInit; /* Address of regReturn init */
drhc01a3c12009-12-16 22:10:49 +00003811 int untestedTerms = 0; /* Some terms not completely tested */
drh8871ef52011-10-07 13:33:10 +00003812 int ii; /* Loop counter */
drh35263192014-07-22 20:02:19 +00003813 u16 wctrlFlags; /* Flags for sub-WHERE clause */
drh8871ef52011-10-07 13:33:10 +00003814 Expr *pAndExpr = 0; /* An ".. AND (...)" expression */
danf97dad82014-05-26 20:06:45 +00003815 Table *pTab = pTabItem->pTab;
drh111a6a72008-12-21 03:51:16 +00003816
drh4efc9292013-06-06 23:02:03 +00003817 pTerm = pLoop->aLTerm[0];
drh111a6a72008-12-21 03:51:16 +00003818 assert( pTerm!=0 );
drh7a5bcc02013-01-16 17:08:58 +00003819 assert( pTerm->eOperator & WO_OR );
drh111a6a72008-12-21 03:51:16 +00003820 assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
3821 pOrWc = &pTerm->u.pOrInfo->wc;
drhc01a3c12009-12-16 22:10:49 +00003822 pLevel->op = OP_Return;
3823 pLevel->p1 = regReturn;
drh23d04d52008-12-23 23:56:22 +00003824
danbfca6a42012-08-24 10:52:35 +00003825 /* Set up a new SrcList in pOrTab containing the table being scanned
drhc01a3c12009-12-16 22:10:49 +00003826 ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
3827 ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
3828 */
3829 if( pWInfo->nLevel>1 ){
3830 int nNotReady; /* The number of notReady tables */
3831 struct SrcList_item *origSrc; /* Original list of tables */
3832 nNotReady = pWInfo->nLevel - iLevel - 1;
drh6b36e822013-07-30 15:10:32 +00003833 pOrTab = sqlite3StackAllocRaw(db,
drhc01a3c12009-12-16 22:10:49 +00003834 sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
3835 if( pOrTab==0 ) return notReady;
drhad01d892013-06-19 13:59:49 +00003836 pOrTab->nAlloc = (u8)(nNotReady + 1);
shaneh46aae3c2009-12-31 19:06:23 +00003837 pOrTab->nSrc = pOrTab->nAlloc;
drhc01a3c12009-12-16 22:10:49 +00003838 memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
3839 origSrc = pWInfo->pTabList->a;
3840 for(k=1; k<=nNotReady; k++){
3841 memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
3842 }
3843 }else{
3844 pOrTab = pWInfo->pTabList;
3845 }
danielk19771d461462009-04-21 09:02:45 +00003846
drh1b26c7c2009-04-22 02:15:47 +00003847 /* Initialize the rowset register to contain NULL. An SQL NULL is
peter.d.reid60ec9142014-09-06 16:39:46 +00003848 ** equivalent to an empty rowset. Or, create an ephemeral index
drh5609baf2014-05-26 22:01:00 +00003849 ** capable of holding primary keys in the case of a WITHOUT ROWID.
danielk19771d461462009-04-21 09:02:45 +00003850 **
3851 ** Also initialize regReturn to contain the address of the instruction
3852 ** immediately following the OP_Return at the bottom of the loop. This
3853 ** is required in a few obscure LEFT JOIN cases where control jumps
3854 ** over the top of the loop into the body of it. In this case the
3855 ** correct response for the end-of-loop code (the OP_Return) is to
3856 ** fall through to the next instruction, just as an OP_Next does if
3857 ** called on an uninitialized cursor.
3858 */
drh70d18342013-06-06 19:16:33 +00003859 if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
danf97dad82014-05-26 20:06:45 +00003860 if( HasRowid(pTab) ){
3861 regRowset = ++pParse->nMem;
3862 sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
3863 }else{
3864 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
3865 regRowset = pParse->nTab++;
3866 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, regRowset, pPk->nKeyCol);
3867 sqlite3VdbeSetP4KeyInfo(pParse, pPk);
3868 }
drh336a5302009-04-24 15:46:21 +00003869 regRowid = ++pParse->nMem;
drh336a5302009-04-24 15:46:21 +00003870 }
danielk19771d461462009-04-21 09:02:45 +00003871 iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
3872
drh8871ef52011-10-07 13:33:10 +00003873 /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y
3874 ** Then for every term xN, evaluate as the subexpression: xN AND z
3875 ** That way, terms in y that are factored into the disjunction will
3876 ** be picked up by the recursive calls to sqlite3WhereBegin() below.
drh331b67c2012-03-09 22:02:08 +00003877 **
3878 ** Actually, each subexpression is converted to "xN AND w" where w is
3879 ** the "interesting" terms of z - terms that did not originate in the
3880 ** ON or USING clause of a LEFT JOIN, and terms that are usable as
3881 ** indices.
drhb3129fa2013-05-09 14:20:11 +00003882 **
3883 ** This optimization also only applies if the (x1 OR x2 OR ...) term
3884 ** is not contained in the ON clause of a LEFT JOIN.
3885 ** See ticket http://www.sqlite.org/src/info/f2369304e4
drh8871ef52011-10-07 13:33:10 +00003886 */
3887 if( pWC->nTerm>1 ){
drh7a484802012-03-16 00:28:11 +00003888 int iTerm;
3889 for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
3890 Expr *pExpr = pWC->a[iTerm].pExpr;
drhaa32e3c2013-07-16 21:31:23 +00003891 if( &pWC->a[iTerm] == pTerm ) continue;
drh331b67c2012-03-09 22:02:08 +00003892 if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
drh1d324882014-12-04 20:24:50 +00003893 if( (pWC->a[iTerm].wtFlags & TERM_VIRTUAL)!=0 ) continue;
drh7a484802012-03-16 00:28:11 +00003894 if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
drh1d324882014-12-04 20:24:50 +00003895 testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO );
drh6b36e822013-07-30 15:10:32 +00003896 pExpr = sqlite3ExprDup(db, pExpr, 0);
3897 pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr);
drh331b67c2012-03-09 22:02:08 +00003898 }
3899 if( pAndExpr ){
3900 pAndExpr = sqlite3PExpr(pParse, TK_AND, 0, pAndExpr, 0);
3901 }
drh8871ef52011-10-07 13:33:10 +00003902 }
3903
drh3fb67302014-05-27 16:41:39 +00003904 /* Run a separate WHERE clause for each term of the OR clause. After
3905 ** eliminating duplicates from other WHERE clauses, the action for each
3906 ** sub-WHERE clause is to to invoke the main loop body as a subroutine.
3907 */
drh36be4c42014-09-30 17:31:23 +00003908 wctrlFlags = WHERE_OMIT_OPEN_CLOSE
3909 | WHERE_FORCE_TABLE
drh8e8e7ef2015-03-02 17:25:00 +00003910 | WHERE_ONETABLE_ONLY
3911 | WHERE_NO_AUTOINDEX;
danielk19771d461462009-04-21 09:02:45 +00003912 for(ii=0; ii<pOrWc->nTerm; ii++){
3913 WhereTerm *pOrTerm = &pOrWc->a[ii];
drh7a5bcc02013-01-16 17:08:58 +00003914 if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
drh3fb67302014-05-27 16:41:39 +00003915 WhereInfo *pSubWInfo; /* Info for single OR-term scan */
3916 Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */
3917 int j1 = 0; /* Address of jump operation */
drhb3129fa2013-05-09 14:20:11 +00003918 if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){
drh8871ef52011-10-07 13:33:10 +00003919 pAndExpr->pLeft = pOrExpr;
3920 pOrExpr = pAndExpr;
3921 }
danielk19771d461462009-04-21 09:02:45 +00003922 /* Loop through table entries that match term pOrTerm. */
drh0a99ba32014-09-30 17:03:35 +00003923 WHERETRACE(0xffff, ("Subplan for OR-clause:\n"));
drh8871ef52011-10-07 13:33:10 +00003924 pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
drh35263192014-07-22 20:02:19 +00003925 wctrlFlags, iCovCur);
drh6b36e822013-07-30 15:10:32 +00003926 assert( pSubWInfo || pParse->nErr || db->mallocFailed );
danielk19771d461462009-04-21 09:02:45 +00003927 if( pSubWInfo ){
drh7ba39a92013-05-30 17:43:19 +00003928 WhereLoop *pSubLoop;
dan6f9702e2014-11-01 20:38:06 +00003929 int addrExplain = explainOneScan(
3930 pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
3931 );
3932 addScanStatus(v, pOrTab, &pSubWInfo->a[0], addrExplain);
dan89e71642014-11-01 18:08:04 +00003933
drh3fb67302014-05-27 16:41:39 +00003934 /* This is the sub-WHERE clause body. First skip over
3935 ** duplicate rows from prior sub-WHERE clauses, and record the
3936 ** rowid (or PRIMARY KEY) for the current row so that the same
3937 ** row will be skipped in subsequent sub-WHERE clauses.
3938 */
drh70d18342013-06-06 19:16:33 +00003939 if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
drh336a5302009-04-24 15:46:21 +00003940 int r;
danf97dad82014-05-26 20:06:45 +00003941 int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
3942 if( HasRowid(pTab) ){
3943 r = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, regRowid, 0);
drh5609baf2014-05-26 22:01:00 +00003944 j1 = sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, 0, r,iSet);
danf97dad82014-05-26 20:06:45 +00003945 VdbeCoverage(v);
3946 }else{
3947 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
3948 int nPk = pPk->nKeyCol;
3949 int iPk;
3950
3951 /* Read the PK into an array of temp registers. */
3952 r = sqlite3GetTempRange(pParse, nPk);
3953 for(iPk=0; iPk<nPk; iPk++){
3954 int iCol = pPk->aiColumn[iPk];
3955 sqlite3ExprCodeGetColumn(pParse, pTab, iCol, iCur, r+iPk, 0);
3956 }
3957
3958 /* Check if the temp table already contains this key. If so,
3959 ** the row has already been included in the result set and
3960 ** can be ignored (by jumping past the Gosub below). Otherwise,
3961 ** insert the key into the temp table and proceed with processing
3962 ** the row.
3963 **
3964 ** Use some of the same optimizations as OP_RowSetTest: If iSet
3965 ** is zero, assume that the key cannot already be present in
3966 ** the temp table. And if iSet is -1, assume that there is no
3967 ** need to insert the key into the temp table, as it will never
3968 ** be tested for. */
3969 if( iSet ){
drh5609baf2014-05-26 22:01:00 +00003970 j1 = sqlite3VdbeAddOp4Int(v, OP_Found, regRowset, 0, r, nPk);
drh68c12152014-05-26 20:25:34 +00003971 VdbeCoverage(v);
danf97dad82014-05-26 20:06:45 +00003972 }
3973 if( iSet>=0 ){
3974 sqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, regRowid);
3975 sqlite3VdbeAddOp3(v, OP_IdxInsert, regRowset, regRowid, 0);
3976 if( iSet ) sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
3977 }
3978
3979 /* Release the array of temp registers */
3980 sqlite3ReleaseTempRange(pParse, r, nPk);
3981 }
drh336a5302009-04-24 15:46:21 +00003982 }
drh3fb67302014-05-27 16:41:39 +00003983
3984 /* Invoke the main loop body as a subroutine */
danielk19771d461462009-04-21 09:02:45 +00003985 sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
drh3fb67302014-05-27 16:41:39 +00003986
3987 /* Jump here (skipping the main loop body subroutine) if the
3988 ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */
drh5609baf2014-05-26 22:01:00 +00003989 if( j1 ) sqlite3VdbeJumpHere(v, j1);
danielk19771d461462009-04-21 09:02:45 +00003990
drhc01a3c12009-12-16 22:10:49 +00003991 /* The pSubWInfo->untestedTerms flag means that this OR term
3992 ** contained one or more AND term from a notReady table. The
3993 ** terms from the notReady table could not be tested and will
3994 ** need to be tested later.
3995 */
3996 if( pSubWInfo->untestedTerms ) untestedTerms = 1;
3997
danbfca6a42012-08-24 10:52:35 +00003998 /* If all of the OR-connected terms are optimized using the same
3999 ** index, and the index is opened using the same cursor number
4000 ** by each call to sqlite3WhereBegin() made by this loop, it may
4001 ** be possible to use that index as a covering index.
4002 **
4003 ** If the call to sqlite3WhereBegin() above resulted in a scan that
4004 ** uses an index, and this is either the first OR-connected term
4005 ** processed or the index is the same as that used by all previous
dan0efb72c2012-08-24 18:44:56 +00004006 ** terms, set pCov to the candidate covering index. Otherwise, set
4007 ** pCov to NULL to indicate that no candidate covering index will
4008 ** be available.
danbfca6a42012-08-24 10:52:35 +00004009 */
drh7ba39a92013-05-30 17:43:19 +00004010 pSubLoop = pSubWInfo->a[0].pWLoop;
drh986b3872013-06-28 21:12:20 +00004011 assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
drh7ba39a92013-05-30 17:43:19 +00004012 if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
drh7ba39a92013-05-30 17:43:19 +00004013 && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
drh48dd1d82014-05-27 18:18:58 +00004014 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pSubLoop->u.btree.pIndex))
danbfca6a42012-08-24 10:52:35 +00004015 ){
drh7ba39a92013-05-30 17:43:19 +00004016 assert( pSubWInfo->a[0].iIdxCur==iCovCur );
drh907717f2013-06-04 18:03:22 +00004017 pCov = pSubLoop->u.btree.pIndex;
drh35263192014-07-22 20:02:19 +00004018 wctrlFlags |= WHERE_REOPEN_IDX;
danbfca6a42012-08-24 10:52:35 +00004019 }else{
4020 pCov = 0;
4021 }
4022
danielk19771d461462009-04-21 09:02:45 +00004023 /* Finish the loop through table entries that match term pOrTerm. */
4024 sqlite3WhereEnd(pSubWInfo);
4025 }
drhdd5f5a62008-12-23 13:35:23 +00004026 }
4027 }
drhd40e2082012-08-24 23:24:15 +00004028 pLevel->u.pCovidx = pCov;
drh90abfd02012-10-09 21:07:23 +00004029 if( pCov ) pLevel->iIdxCur = iCovCur;
drh331b67c2012-03-09 22:02:08 +00004030 if( pAndExpr ){
4031 pAndExpr->pLeft = 0;
drh6b36e822013-07-30 15:10:32 +00004032 sqlite3ExprDelete(db, pAndExpr);
drh331b67c2012-03-09 22:02:08 +00004033 }
danielk19771d461462009-04-21 09:02:45 +00004034 sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
danielk19771d461462009-04-21 09:02:45 +00004035 sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
4036 sqlite3VdbeResolveLabel(v, iLoopBody);
4037
drh6b36e822013-07-30 15:10:32 +00004038 if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab);
drhc01a3c12009-12-16 22:10:49 +00004039 if( !untestedTerms ) disableTerm(pLevel, pTerm);
drhdd5f5a62008-12-23 13:35:23 +00004040 }else
drh23d04d52008-12-23 23:56:22 +00004041#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
drhdd5f5a62008-12-23 13:35:23 +00004042
4043 {
drh7ba39a92013-05-30 17:43:19 +00004044 /* Case 6: There is no usable index. We must do a complete
drh111a6a72008-12-21 03:51:16 +00004045 ** scan of the entire table.
4046 */
drh699b3d42009-02-23 16:52:07 +00004047 static const u8 aStep[] = { OP_Next, OP_Prev };
4048 static const u8 aStart[] = { OP_Rewind, OP_Last };
4049 assert( bRev==0 || bRev==1 );
drhe73f0592014-01-21 22:25:45 +00004050 if( pTabItem->isRecursive ){
drh340309f2014-01-22 00:23:49 +00004051 /* Tables marked isRecursive have only a single row that is stored in
dan41028152014-01-22 10:22:25 +00004052 ** a pseudo-cursor. No need to Rewind or Next such cursors. */
drhe73f0592014-01-21 22:25:45 +00004053 pLevel->op = OP_Noop;
4054 }else{
4055 pLevel->op = aStep[bRev];
4056 pLevel->p1 = iCur;
4057 pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
drh7d176102014-02-18 03:07:12 +00004058 VdbeCoverageIf(v, bRev==0);
4059 VdbeCoverageIf(v, bRev!=0);
drhe73f0592014-01-21 22:25:45 +00004060 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
4061 }
drh111a6a72008-12-21 03:51:16 +00004062 }
drh111a6a72008-12-21 03:51:16 +00004063
dan6f9702e2014-11-01 20:38:06 +00004064#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
4065 pLevel->addrVisit = sqlite3VdbeCurrentAddr(v);
4066#endif
4067
drh111a6a72008-12-21 03:51:16 +00004068 /* Insert code to test every subexpression that can be completely
4069 ** computed using the current set of tables.
4070 */
drh111a6a72008-12-21 03:51:16 +00004071 for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
4072 Expr *pE;
drh8f1a7ed2015-03-06 19:47:38 +00004073 int skipLikeAddr = 0;
drh39759742013-08-02 23:40:45 +00004074 testcase( pTerm->wtFlags & TERM_VIRTUAL );
drh111a6a72008-12-21 03:51:16 +00004075 testcase( pTerm->wtFlags & TERM_CODED );
4076 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
drh0259bc32013-09-09 19:37:46 +00004077 if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
drhc01a3c12009-12-16 22:10:49 +00004078 testcase( pWInfo->untestedTerms==0
4079 && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
4080 pWInfo->untestedTerms = 1;
4081 continue;
4082 }
drh111a6a72008-12-21 03:51:16 +00004083 pE = pTerm->pExpr;
4084 assert( pE!=0 );
4085 if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
4086 continue;
4087 }
drh8f1a7ed2015-03-06 19:47:38 +00004088 if( pTerm->wtFlags & TERM_LIKECOND ){
4089 assert( pLevel->iLikeRepCntr>0 );
drh16897072015-03-07 00:57:37 +00004090 skipLikeAddr = sqlite3VdbeAddOp1(v, OP_IfNot, pLevel->iLikeRepCntr);
drh8f1a7ed2015-03-06 19:47:38 +00004091 VdbeCoverage(v);
4092 }
drh111a6a72008-12-21 03:51:16 +00004093 sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
drh8f1a7ed2015-03-06 19:47:38 +00004094 if( skipLikeAddr ) sqlite3VdbeJumpHere(v, skipLikeAddr);
drh111a6a72008-12-21 03:51:16 +00004095 pTerm->wtFlags |= TERM_CODED;
4096 }
4097
drh0c41d222013-04-22 02:39:10 +00004098 /* Insert code to test for implied constraints based on transitivity
4099 ** of the "==" operator.
4100 **
4101 ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
4102 ** and we are coding the t1 loop and the t2 loop has not yet coded,
4103 ** then we cannot use the "t1.a=t2.b" constraint, but we can code
4104 ** the implied "t1.a=123" constraint.
4105 */
4106 for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
drh6b36e822013-07-30 15:10:32 +00004107 Expr *pE, *pEAlt;
drh0c41d222013-04-22 02:39:10 +00004108 WhereTerm *pAlt;
drh0c41d222013-04-22 02:39:10 +00004109 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
drhee145872015-05-14 13:18:47 +00004110 if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) continue;
drh4a00b332015-05-14 13:41:22 +00004111 if( (pTerm->eOperator & WO_EQUIV)==0 ) continue;
drh0c41d222013-04-22 02:39:10 +00004112 if( pTerm->leftCursor!=iCur ) continue;
drhcdc2e432013-07-01 17:27:19 +00004113 if( pLevel->iLeftJoin ) continue;
drh0c41d222013-04-22 02:39:10 +00004114 pE = pTerm->pExpr;
4115 assert( !ExprHasProperty(pE, EP_FromJoin) );
drh0259bc32013-09-09 19:37:46 +00004116 assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
drhe8d0c612015-05-14 01:05:25 +00004117 pAlt = findTerm(pWC, iCur, pTerm->u.leftColumn, notReady,
4118 WO_EQ|WO_IN|WO_IS, 0);
drh0c41d222013-04-22 02:39:10 +00004119 if( pAlt==0 ) continue;
drh5c10f3b2013-05-01 17:22:38 +00004120 if( pAlt->wtFlags & (TERM_CODED) ) continue;
drhe8d0c612015-05-14 01:05:25 +00004121 testcase( pAlt->eOperator & WO_EQ );
4122 testcase( pAlt->eOperator & WO_IS );
drh7963b0e2013-06-17 21:37:40 +00004123 testcase( pAlt->eOperator & WO_IN );
drh6bc69a22013-11-19 12:33:23 +00004124 VdbeModuleComment((v, "begin transitive constraint"));
drh6b36e822013-07-30 15:10:32 +00004125 pEAlt = sqlite3StackAllocRaw(db, sizeof(*pEAlt));
4126 if( pEAlt ){
4127 *pEAlt = *pAlt->pExpr;
4128 pEAlt->pLeft = pE->pLeft;
4129 sqlite3ExprIfFalse(pParse, pEAlt, addrCont, SQLITE_JUMPIFNULL);
4130 sqlite3StackFree(db, pEAlt);
4131 }
drh0c41d222013-04-22 02:39:10 +00004132 }
4133
drh111a6a72008-12-21 03:51:16 +00004134 /* For a LEFT OUTER JOIN, generate code that will record the fact that
4135 ** at least one row of the right table has matched the left table.
4136 */
4137 if( pLevel->iLeftJoin ){
4138 pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
4139 sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
4140 VdbeComment((v, "record LEFT JOIN hit"));
drhceea3322009-04-23 13:22:42 +00004141 sqlite3ExprCacheClear(pParse);
drh111a6a72008-12-21 03:51:16 +00004142 for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
drh39759742013-08-02 23:40:45 +00004143 testcase( pTerm->wtFlags & TERM_VIRTUAL );
drh111a6a72008-12-21 03:51:16 +00004144 testcase( pTerm->wtFlags & TERM_CODED );
4145 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
drh0259bc32013-09-09 19:37:46 +00004146 if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
drhb057e562009-12-16 23:43:55 +00004147 assert( pWInfo->untestedTerms );
drhc01a3c12009-12-16 22:10:49 +00004148 continue;
4149 }
drh111a6a72008-12-21 03:51:16 +00004150 assert( pTerm->pExpr );
4151 sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
4152 pTerm->wtFlags |= TERM_CODED;
4153 }
4154 }
drh23d04d52008-12-23 23:56:22 +00004155
drh0259bc32013-09-09 19:37:46 +00004156 return pLevel->notReady;
drh111a6a72008-12-21 03:51:16 +00004157}
4158
drhd15cb172013-05-21 19:23:10 +00004159#ifdef WHERETRACE_ENABLED
drha18f3d22013-05-08 03:05:41 +00004160/*
drhc90713d2014-09-30 13:46:49 +00004161** Print the content of a WhereTerm object
4162*/
4163static void whereTermPrint(WhereTerm *pTerm, int iTerm){
drh0a99ba32014-09-30 17:03:35 +00004164 if( pTerm==0 ){
4165 sqlite3DebugPrintf("TERM-%-3d NULL\n", iTerm);
4166 }else{
4167 char zType[4];
4168 memcpy(zType, "...", 4);
4169 if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V';
4170 if( pTerm->eOperator & WO_EQUIV ) zType[1] = 'E';
4171 if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) zType[2] = 'L';
drhfcd49532015-05-13 15:24:07 +00004172 sqlite3DebugPrintf(
4173 "TERM-%-3d %p %s cursor=%-3d prob=%-3d op=0x%03x wtFlags=0x%04x\n",
4174 iTerm, pTerm, zType, pTerm->leftCursor, pTerm->truthProb,
4175 pTerm->eOperator, pTerm->wtFlags);
drh0a99ba32014-09-30 17:03:35 +00004176 sqlite3TreeViewExpr(0, pTerm->pExpr, 0);
4177 }
drhc90713d2014-09-30 13:46:49 +00004178}
4179#endif
4180
4181#ifdef WHERETRACE_ENABLED
4182/*
drha18f3d22013-05-08 03:05:41 +00004183** Print a WhereLoop object for debugging purposes
4184*/
drhc1ba2e72013-10-28 19:03:21 +00004185static void whereLoopPrint(WhereLoop *p, WhereClause *pWC){
4186 WhereInfo *pWInfo = pWC->pWInfo;
drh989578e2013-10-28 14:34:35 +00004187 int nb = 1+(pWInfo->pTabList->nSrc+7)/8;
4188 struct SrcList_item *pItem = pWInfo->pTabList->a + p->iTab;
drha18f3d22013-05-08 03:05:41 +00004189 Table *pTab = pItem->pTab;
drh6457a352013-06-21 00:35:37 +00004190 sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
drha184fb82013-05-08 04:22:59 +00004191 p->iTab, nb, p->maskSelf, nb, p->prereq);
drh6457a352013-06-21 00:35:37 +00004192 sqlite3DebugPrintf(" %12s",
drha18f3d22013-05-08 03:05:41 +00004193 pItem->zAlias ? pItem->zAlias : pTab->zName);
drh5346e952013-05-08 14:14:26 +00004194 if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
drhf3f69ac2014-08-20 23:38:07 +00004195 const char *zName;
4196 if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){
drh319f6772013-05-14 15:31:07 +00004197 if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
4198 int i = sqlite3Strlen30(zName) - 1;
4199 while( zName[i]!='_' ) i--;
4200 zName += i;
4201 }
drh6457a352013-06-21 00:35:37 +00004202 sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq);
drh5346e952013-05-08 14:14:26 +00004203 }else{
drh6457a352013-06-21 00:35:37 +00004204 sqlite3DebugPrintf("%20s","");
drh5346e952013-05-08 14:14:26 +00004205 }
drha18f3d22013-05-08 03:05:41 +00004206 }else{
drh5346e952013-05-08 14:14:26 +00004207 char *z;
4208 if( p->u.vtab.idxStr ){
drh3bd26f02013-05-24 14:52:03 +00004209 z = sqlite3_mprintf("(%d,\"%s\",%x)",
4210 p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
drh5346e952013-05-08 14:14:26 +00004211 }else{
drh3bd26f02013-05-24 14:52:03 +00004212 z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
drh5346e952013-05-08 14:14:26 +00004213 }
drh6457a352013-06-21 00:35:37 +00004214 sqlite3DebugPrintf(" %-19s", z);
drh5346e952013-05-08 14:14:26 +00004215 sqlite3_free(z);
drha18f3d22013-05-08 03:05:41 +00004216 }
drhf3f69ac2014-08-20 23:38:07 +00004217 if( p->wsFlags & WHERE_SKIPSCAN ){
drhc8bbce12014-10-21 01:05:09 +00004218 sqlite3DebugPrintf(" f %05x %d-%d", p->wsFlags, p->nLTerm,p->nSkip);
drhf3f69ac2014-08-20 23:38:07 +00004219 }else{
4220 sqlite3DebugPrintf(" f %05x N %d", p->wsFlags, p->nLTerm);
4221 }
drhb8a8e8a2013-06-10 19:12:39 +00004222 sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
drhc90713d2014-09-30 13:46:49 +00004223 if( p->nLTerm && (sqlite3WhereTrace & 0x100)!=0 ){
4224 int i;
4225 for(i=0; i<p->nLTerm; i++){
drh0a99ba32014-09-30 17:03:35 +00004226 whereTermPrint(p->aLTerm[i], i);
drhc90713d2014-09-30 13:46:49 +00004227 }
4228 }
drha18f3d22013-05-08 03:05:41 +00004229}
4230#endif
4231
drhf1b5f5b2013-05-02 00:15:01 +00004232/*
drh4efc9292013-06-06 23:02:03 +00004233** Convert bulk memory into a valid WhereLoop that can be passed
4234** to whereLoopClear harmlessly.
drh5346e952013-05-08 14:14:26 +00004235*/
drh4efc9292013-06-06 23:02:03 +00004236static void whereLoopInit(WhereLoop *p){
4237 p->aLTerm = p->aLTermSpace;
4238 p->nLTerm = 0;
4239 p->nLSlot = ArraySize(p->aLTermSpace);
4240 p->wsFlags = 0;
4241}
4242
4243/*
4244** Clear the WhereLoop.u union. Leave WhereLoop.pLTerm intact.
4245*/
4246static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
drh986b3872013-06-28 21:12:20 +00004247 if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){
drh13e11b42013-06-06 23:44:25 +00004248 if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
4249 sqlite3_free(p->u.vtab.idxStr);
4250 p->u.vtab.needFree = 0;
4251 p->u.vtab.idxStr = 0;
drh986b3872013-06-28 21:12:20 +00004252 }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){
drh13e11b42013-06-06 23:44:25 +00004253 sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
4254 sqlite3DbFree(db, p->u.btree.pIndex);
4255 p->u.btree.pIndex = 0;
4256 }
drh5346e952013-05-08 14:14:26 +00004257 }
4258}
4259
drh4efc9292013-06-06 23:02:03 +00004260/*
4261** Deallocate internal memory used by a WhereLoop object
4262*/
4263static void whereLoopClear(sqlite3 *db, WhereLoop *p){
4264 if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
4265 whereLoopClearUnion(db, p);
4266 whereLoopInit(p);
4267}
4268
4269/*
4270** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
4271*/
4272static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
4273 WhereTerm **paNew;
4274 if( p->nLSlot>=n ) return SQLITE_OK;
4275 n = (n+7)&~7;
4276 paNew = sqlite3DbMallocRaw(db, sizeof(p->aLTerm[0])*n);
4277 if( paNew==0 ) return SQLITE_NOMEM;
4278 memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
4279 if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
4280 p->aLTerm = paNew;
4281 p->nLSlot = n;
4282 return SQLITE_OK;
4283}
4284
4285/*
4286** Transfer content from the second pLoop into the first.
4287*/
4288static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
drh4efc9292013-06-06 23:02:03 +00004289 whereLoopClearUnion(db, pTo);
drh0d31dc32013-09-06 00:40:59 +00004290 if( whereLoopResize(db, pTo, pFrom->nLTerm) ){
4291 memset(&pTo->u, 0, sizeof(pTo->u));
4292 return SQLITE_NOMEM;
4293 }
drha2014152013-06-07 00:29:23 +00004294 memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
4295 memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
drh4efc9292013-06-06 23:02:03 +00004296 if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
4297 pFrom->u.vtab.needFree = 0;
drh986b3872013-06-28 21:12:20 +00004298 }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){
drh4efc9292013-06-06 23:02:03 +00004299 pFrom->u.btree.pIndex = 0;
4300 }
4301 return SQLITE_OK;
4302}
4303
drh5346e952013-05-08 14:14:26 +00004304/*
drhf1b5f5b2013-05-02 00:15:01 +00004305** Delete a WhereLoop object
4306*/
4307static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
drh5346e952013-05-08 14:14:26 +00004308 whereLoopClear(db, p);
drhf1b5f5b2013-05-02 00:15:01 +00004309 sqlite3DbFree(db, p);
4310}
drh84bfda42005-07-15 13:05:21 +00004311
drh9eff6162006-06-12 21:59:13 +00004312/*
4313** Free a WhereInfo structure
4314*/
drh10fe8402008-10-11 16:47:35 +00004315static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
drh52ff8ea2010-04-08 14:15:56 +00004316 if( ALWAYS(pWInfo) ){
danf89aa472015-04-25 12:20:24 +00004317 int i;
4318 for(i=0; i<pWInfo->nLevel; i++){
4319 WhereLevel *pLevel = &pWInfo->a[i];
4320 if( pLevel->pWLoop && (pLevel->pWLoop->wsFlags & WHERE_IN_ABLE) ){
4321 sqlite3DbFree(db, pLevel->u.in.aInLoop);
4322 }
4323 }
drh70d18342013-06-06 19:16:33 +00004324 whereClauseClear(&pWInfo->sWC);
drhf1b5f5b2013-05-02 00:15:01 +00004325 while( pWInfo->pLoops ){
4326 WhereLoop *p = pWInfo->pLoops;
4327 pWInfo->pLoops = p->pNextLoop;
4328 whereLoopDelete(db, p);
4329 }
drh633e6d52008-07-28 19:34:53 +00004330 sqlite3DbFree(db, pWInfo);
drh9eff6162006-06-12 21:59:13 +00004331 }
4332}
4333
drhf1b5f5b2013-05-02 00:15:01 +00004334/*
drhe0de8762014-11-05 13:13:13 +00004335** Return TRUE if all of the following are true:
drhb355c2c2014-04-18 22:20:31 +00004336**
4337** (1) X has the same or lower cost that Y
4338** (2) X is a proper subset of Y
drhe0de8762014-11-05 13:13:13 +00004339** (3) X skips at least as many columns as Y
drhb355c2c2014-04-18 22:20:31 +00004340**
4341** By "proper subset" we mean that X uses fewer WHERE clause terms
4342** than Y and that every WHERE clause term used by X is also used
4343** by Y.
4344**
4345** If X is a proper subset of Y then Y is a better choice and ought
4346** to have a lower cost. This routine returns TRUE when that cost
drhe0de8762014-11-05 13:13:13 +00004347** relationship is inverted and needs to be adjusted. The third rule
4348** was added because if X uses skip-scan less than Y it still might
4349** deserve a lower cost even if it is a proper subset of Y.
drh3fb183d2014-03-31 19:49:00 +00004350*/
drhb355c2c2014-04-18 22:20:31 +00004351static int whereLoopCheaperProperSubset(
4352 const WhereLoop *pX, /* First WhereLoop to compare */
4353 const WhereLoop *pY /* Compare against this WhereLoop */
4354){
drh3fb183d2014-03-31 19:49:00 +00004355 int i, j;
drhc8bbce12014-10-21 01:05:09 +00004356 if( pX->nLTerm-pX->nSkip >= pY->nLTerm-pY->nSkip ){
4357 return 0; /* X is not a subset of Y */
4358 }
drhe0de8762014-11-05 13:13:13 +00004359 if( pY->nSkip > pX->nSkip ) return 0;
drhb355c2c2014-04-18 22:20:31 +00004360 if( pX->rRun >= pY->rRun ){
4361 if( pX->rRun > pY->rRun ) return 0; /* X costs more than Y */
4362 if( pX->nOut > pY->nOut ) return 0; /* X costs more than Y */
drh3fb183d2014-03-31 19:49:00 +00004363 }
drh9ee88102014-05-07 20:33:17 +00004364 for(i=pX->nLTerm-1; i>=0; i--){
drhc8bbce12014-10-21 01:05:09 +00004365 if( pX->aLTerm[i]==0 ) continue;
drhb355c2c2014-04-18 22:20:31 +00004366 for(j=pY->nLTerm-1; j>=0; j--){
4367 if( pY->aLTerm[j]==pX->aLTerm[i] ) break;
4368 }
4369 if( j<0 ) return 0; /* X not a subset of Y since term X[i] not used by Y */
4370 }
4371 return 1; /* All conditions meet */
drh3fb183d2014-03-31 19:49:00 +00004372}
4373
4374/*
4375** Try to adjust the cost of WhereLoop pTemplate upwards or downwards so
4376** that:
drh53cd10a2014-03-31 18:24:18 +00004377**
drh3fb183d2014-03-31 19:49:00 +00004378** (1) pTemplate costs less than any other WhereLoops that are a proper
4379** subset of pTemplate
drh53cd10a2014-03-31 18:24:18 +00004380**
drh3fb183d2014-03-31 19:49:00 +00004381** (2) pTemplate costs more than any other WhereLoops for which pTemplate
4382** is a proper subset.
drh53cd10a2014-03-31 18:24:18 +00004383**
drh3fb183d2014-03-31 19:49:00 +00004384** To say "WhereLoop X is a proper subset of Y" means that X uses fewer
4385** WHERE clause terms than Y and that every WHERE clause term used by X is
4386** also used by Y.
drh53cd10a2014-03-31 18:24:18 +00004387*/
4388static void whereLoopAdjustCost(const WhereLoop *p, WhereLoop *pTemplate){
4389 if( (pTemplate->wsFlags & WHERE_INDEXED)==0 ) return;
drh53cd10a2014-03-31 18:24:18 +00004390 for(; p; p=p->pNextLoop){
drh3fb183d2014-03-31 19:49:00 +00004391 if( p->iTab!=pTemplate->iTab ) continue;
4392 if( (p->wsFlags & WHERE_INDEXED)==0 ) continue;
drhb355c2c2014-04-18 22:20:31 +00004393 if( whereLoopCheaperProperSubset(p, pTemplate) ){
4394 /* Adjust pTemplate cost downward so that it is cheaper than its
drhe0de8762014-11-05 13:13:13 +00004395 ** subset p. */
drh1b131b72014-10-21 16:01:40 +00004396 WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
4397 pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut-1));
drh3fb183d2014-03-31 19:49:00 +00004398 pTemplate->rRun = p->rRun;
4399 pTemplate->nOut = p->nOut - 1;
drhb355c2c2014-04-18 22:20:31 +00004400 }else if( whereLoopCheaperProperSubset(pTemplate, p) ){
4401 /* Adjust pTemplate cost upward so that it is costlier than p since
4402 ** pTemplate is a proper subset of p */
drh1b131b72014-10-21 16:01:40 +00004403 WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
4404 pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut+1));
drh3fb183d2014-03-31 19:49:00 +00004405 pTemplate->rRun = p->rRun;
4406 pTemplate->nOut = p->nOut + 1;
drh53cd10a2014-03-31 18:24:18 +00004407 }
4408 }
4409}
4410
4411/*
drh7a4b1642014-03-29 21:16:07 +00004412** Search the list of WhereLoops in *ppPrev looking for one that can be
4413** supplanted by pTemplate.
drhf1b5f5b2013-05-02 00:15:01 +00004414**
drh7a4b1642014-03-29 21:16:07 +00004415** Return NULL if the WhereLoop list contains an entry that can supplant
4416** pTemplate, in other words if pTemplate does not belong on the list.
drh23f98da2013-05-21 15:52:07 +00004417**
drh7a4b1642014-03-29 21:16:07 +00004418** If pX is a WhereLoop that pTemplate can supplant, then return the
4419** link that points to pX.
drh23f98da2013-05-21 15:52:07 +00004420**
drh7a4b1642014-03-29 21:16:07 +00004421** If pTemplate cannot supplant any existing element of the list but needs
4422** to be added to the list, then return a pointer to the tail of the list.
drhf1b5f5b2013-05-02 00:15:01 +00004423*/
drh7a4b1642014-03-29 21:16:07 +00004424static WhereLoop **whereLoopFindLesser(
4425 WhereLoop **ppPrev,
4426 const WhereLoop *pTemplate
4427){
4428 WhereLoop *p;
4429 for(p=(*ppPrev); p; ppPrev=&p->pNextLoop, p=*ppPrev){
drhdbb80232013-06-19 12:34:13 +00004430 if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
4431 /* If either the iTab or iSortIdx values for two WhereLoop are different
4432 ** then those WhereLoops need to be considered separately. Neither is
4433 ** a candidate to replace the other. */
4434 continue;
4435 }
4436 /* In the current implementation, the rSetup value is either zero
4437 ** or the cost of building an automatic index (NlogN) and the NlogN
4438 ** is the same for compatible WhereLoops. */
4439 assert( p->rSetup==0 || pTemplate->rSetup==0
4440 || p->rSetup==pTemplate->rSetup );
4441
4442 /* whereLoopAddBtree() always generates and inserts the automatic index
4443 ** case first. Hence compatible candidate WhereLoops never have a larger
4444 ** rSetup. Call this SETUP-INVARIANT */
4445 assert( p->rSetup>=pTemplate->rSetup );
4446
drhdabe36d2014-06-17 20:16:43 +00004447 /* Any loop using an appliation-defined index (or PRIMARY KEY or
4448 ** UNIQUE constraint) with one or more == constraints is better
dan70273d02014-11-14 19:34:20 +00004449 ** than an automatic index. Unless it is a skip-scan. */
drhdabe36d2014-06-17 20:16:43 +00004450 if( (p->wsFlags & WHERE_AUTO_INDEX)!=0
dan70273d02014-11-14 19:34:20 +00004451 && (pTemplate->nSkip)==0
drhdabe36d2014-06-17 20:16:43 +00004452 && (pTemplate->wsFlags & WHERE_INDEXED)!=0
4453 && (pTemplate->wsFlags & WHERE_COLUMN_EQ)!=0
4454 && (p->prereq & pTemplate->prereq)==pTemplate->prereq
4455 ){
4456 break;
4457 }
4458
drh53cd10a2014-03-31 18:24:18 +00004459 /* If existing WhereLoop p is better than pTemplate, pTemplate can be
4460 ** discarded. WhereLoop p is better if:
4461 ** (1) p has no more dependencies than pTemplate, and
4462 ** (2) p has an equal or lower cost than pTemplate
4463 */
4464 if( (p->prereq & pTemplate->prereq)==p->prereq /* (1) */
4465 && p->rSetup<=pTemplate->rSetup /* (2a) */
4466 && p->rRun<=pTemplate->rRun /* (2b) */
4467 && p->nOut<=pTemplate->nOut /* (2c) */
drhf1b5f5b2013-05-02 00:15:01 +00004468 ){
drh53cd10a2014-03-31 18:24:18 +00004469 return 0; /* Discard pTemplate */
drhf1b5f5b2013-05-02 00:15:01 +00004470 }
drh53cd10a2014-03-31 18:24:18 +00004471
4472 /* If pTemplate is always better than p, then cause p to be overwritten
4473 ** with pTemplate. pTemplate is better than p if:
4474 ** (1) pTemplate has no more dependences than p, and
4475 ** (2) pTemplate has an equal or lower cost than p.
4476 */
4477 if( (p->prereq & pTemplate->prereq)==pTemplate->prereq /* (1) */
4478 && p->rRun>=pTemplate->rRun /* (2a) */
4479 && p->nOut>=pTemplate->nOut /* (2b) */
drhf1b5f5b2013-05-02 00:15:01 +00004480 ){
drhadd5ce32013-09-07 00:29:06 +00004481 assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */
drh53cd10a2014-03-31 18:24:18 +00004482 break; /* Cause p to be overwritten by pTemplate */
drhf1b5f5b2013-05-02 00:15:01 +00004483 }
4484 }
drh7a4b1642014-03-29 21:16:07 +00004485 return ppPrev;
4486}
4487
4488/*
drh94a11212004-09-25 13:12:14 +00004489** Insert or replace a WhereLoop entry using the template supplied.
4490**
4491** An existing WhereLoop entry might be overwritten if the new template
4492** is better and has fewer dependencies. Or the template will be ignored
4493** and no insert will occur if an existing WhereLoop is faster and has
4494** fewer dependencies than the template. Otherwise a new WhereLoop is
4495** added based on the template.
drh51669862004-12-18 18:40:26 +00004496**
drh7a4b1642014-03-29 21:16:07 +00004497** If pBuilder->pOrSet is not NULL then we care about only the
drh94a11212004-09-25 13:12:14 +00004498** prerequisites and rRun and nOut costs of the N best loops. That
4499** information is gathered in the pBuilder->pOrSet object. This special
drh51669862004-12-18 18:40:26 +00004500** processing mode is used only for OR clause processing.
4501**
4502** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
4503** still might overwrite similar loops with the new template if the
drh53cd10a2014-03-31 18:24:18 +00004504** new template is better. Loops may be overwritten if the following
drh94a11212004-09-25 13:12:14 +00004505** conditions are met:
4506**
4507** (1) They have the same iTab.
4508** (2) They have the same iSortIdx.
4509** (3) The template has same or fewer dependencies than the current loop
4510** (4) The template has the same or lower cost than the current loop
drh94a11212004-09-25 13:12:14 +00004511*/
4512static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
drh7a4b1642014-03-29 21:16:07 +00004513 WhereLoop **ppPrev, *p;
drh94a11212004-09-25 13:12:14 +00004514 WhereInfo *pWInfo = pBuilder->pWInfo;
4515 sqlite3 *db = pWInfo->pParse->db;
4516
4517 /* If pBuilder->pOrSet is defined, then only keep track of the costs
4518 ** and prereqs.
4519 */
4520 if( pBuilder->pOrSet!=0 ){
4521#if WHERETRACE_ENABLED
drh51669862004-12-18 18:40:26 +00004522 u16 n = pBuilder->pOrSet->n;
4523 int x =
4524#endif
4525 whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
4526 pTemplate->nOut);
drh94a11212004-09-25 13:12:14 +00004527#if WHERETRACE_ENABLED /* 0x8 */
4528 if( sqlite3WhereTrace & 0x8 ){
drhe3184742002-06-19 14:27:05 +00004529 sqlite3DebugPrintf(x?" or-%d: ":" or-X: ", n);
drhacf3b982005-01-03 01:27:18 +00004530 whereLoopPrint(pTemplate, pBuilder->pWC);
drh75897232000-05-29 14:26:00 +00004531 }
danielk19774adee202004-05-08 08:23:19 +00004532#endif
drh75897232000-05-29 14:26:00 +00004533 return SQLITE_OK;
4534 }
4535
drh7a4b1642014-03-29 21:16:07 +00004536 /* Look for an existing WhereLoop to replace with pTemplate
drh75897232000-05-29 14:26:00 +00004537 */
drh53cd10a2014-03-31 18:24:18 +00004538 whereLoopAdjustCost(pWInfo->pLoops, pTemplate);
drh7a4b1642014-03-29 21:16:07 +00004539 ppPrev = whereLoopFindLesser(&pWInfo->pLoops, pTemplate);
drhf1b5f5b2013-05-02 00:15:01 +00004540
drh7a4b1642014-03-29 21:16:07 +00004541 if( ppPrev==0 ){
4542 /* There already exists a WhereLoop on the list that is better
4543 ** than pTemplate, so just ignore pTemplate */
4544#if WHERETRACE_ENABLED /* 0x8 */
4545 if( sqlite3WhereTrace & 0x8 ){
drh9a7b41d2014-10-08 00:08:08 +00004546 sqlite3DebugPrintf(" skip: ");
drh7a4b1642014-03-29 21:16:07 +00004547 whereLoopPrint(pTemplate, pBuilder->pWC);
drhf1b5f5b2013-05-02 00:15:01 +00004548 }
drh7a4b1642014-03-29 21:16:07 +00004549#endif
4550 return SQLITE_OK;
4551 }else{
4552 p = *ppPrev;
drhf1b5f5b2013-05-02 00:15:01 +00004553 }
4554
4555 /* If we reach this point it means that either p[] should be overwritten
4556 ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
4557 ** WhereLoop and insert it.
4558 */
drh989578e2013-10-28 14:34:35 +00004559#if WHERETRACE_ENABLED /* 0x8 */
drhae70cf12013-05-31 15:18:46 +00004560 if( sqlite3WhereTrace & 0x8 ){
4561 if( p!=0 ){
drh9a7b41d2014-10-08 00:08:08 +00004562 sqlite3DebugPrintf("replace: ");
drhc1ba2e72013-10-28 19:03:21 +00004563 whereLoopPrint(p, pBuilder->pWC);
drhae70cf12013-05-31 15:18:46 +00004564 }
drh9a7b41d2014-10-08 00:08:08 +00004565 sqlite3DebugPrintf(" add: ");
drhc1ba2e72013-10-28 19:03:21 +00004566 whereLoopPrint(pTemplate, pBuilder->pWC);
drhae70cf12013-05-31 15:18:46 +00004567 }
4568#endif
drhf1b5f5b2013-05-02 00:15:01 +00004569 if( p==0 ){
drh7a4b1642014-03-29 21:16:07 +00004570 /* Allocate a new WhereLoop to add to the end of the list */
4571 *ppPrev = p = sqlite3DbMallocRaw(db, sizeof(WhereLoop));
drhf1b5f5b2013-05-02 00:15:01 +00004572 if( p==0 ) return SQLITE_NOMEM;
drh4efc9292013-06-06 23:02:03 +00004573 whereLoopInit(p);
drh7a4b1642014-03-29 21:16:07 +00004574 p->pNextLoop = 0;
4575 }else{
4576 /* We will be overwriting WhereLoop p[]. But before we do, first
4577 ** go through the rest of the list and delete any other entries besides
4578 ** p[] that are also supplated by pTemplate */
4579 WhereLoop **ppTail = &p->pNextLoop;
4580 WhereLoop *pToDel;
4581 while( *ppTail ){
4582 ppTail = whereLoopFindLesser(ppTail, pTemplate);
drhdabe36d2014-06-17 20:16:43 +00004583 if( ppTail==0 ) break;
drh7a4b1642014-03-29 21:16:07 +00004584 pToDel = *ppTail;
4585 if( pToDel==0 ) break;
4586 *ppTail = pToDel->pNextLoop;
4587#if WHERETRACE_ENABLED /* 0x8 */
4588 if( sqlite3WhereTrace & 0x8 ){
drh9a7b41d2014-10-08 00:08:08 +00004589 sqlite3DebugPrintf(" delete: ");
drh7a4b1642014-03-29 21:16:07 +00004590 whereLoopPrint(pToDel, pBuilder->pWC);
4591 }
4592#endif
4593 whereLoopDelete(db, pToDel);
4594 }
drhf1b5f5b2013-05-02 00:15:01 +00004595 }
drh4efc9292013-06-06 23:02:03 +00004596 whereLoopXfer(db, p, pTemplate);
drh5346e952013-05-08 14:14:26 +00004597 if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
drhef866372013-05-22 20:49:02 +00004598 Index *pIndex = p->u.btree.pIndex;
4599 if( pIndex && pIndex->tnum==0 ){
drhcf8fa7a2013-05-10 20:26:22 +00004600 p->u.btree.pIndex = 0;
4601 }
drh5346e952013-05-08 14:14:26 +00004602 }
drhf1b5f5b2013-05-02 00:15:01 +00004603 return SQLITE_OK;
4604}
4605
4606/*
drhcca9f3d2013-09-06 15:23:29 +00004607** Adjust the WhereLoop.nOut value downward to account for terms of the
4608** WHERE clause that reference the loop but which are not used by an
4609** index.
drh7a1bca72014-11-22 18:50:44 +00004610*
4611** For every WHERE clause term that is not used by the index
4612** and which has a truth probability assigned by one of the likelihood(),
4613** likely(), or unlikely() SQL functions, reduce the estimated number
4614** of output rows by the probability specified.
drhcca9f3d2013-09-06 15:23:29 +00004615**
drh7a1bca72014-11-22 18:50:44 +00004616** TUNING: For every WHERE clause term that is not used by the index
4617** and which does not have an assigned truth probability, heuristics
4618** described below are used to try to estimate the truth probability.
4619** TODO --> Perhaps this is something that could be improved by better
4620** table statistics.
4621**
drhab4624d2014-11-22 19:52:10 +00004622** Heuristic 1: Estimate the truth probability as 93.75%. The 93.75%
4623** value corresponds to -1 in LogEst notation, so this means decrement
drh7a1bca72014-11-22 18:50:44 +00004624** the WhereLoop.nOut field for every such WHERE clause term.
4625**
4626** Heuristic 2: If there exists one or more WHERE clause terms of the
4627** form "x==EXPR" and EXPR is not a constant 0 or 1, then make sure the
4628** final output row estimate is no greater than 1/4 of the total number
4629** of rows in the table. In other words, assume that x==EXPR will filter
4630** out at least 3 out of 4 rows. If EXPR is -1 or 0 or 1, then maybe the
4631** "x" column is boolean or else -1 or 0 or 1 is a common default value
4632** on the "x" column and so in that case only cap the output row estimate
4633** at 1/2 instead of 1/4.
drhcca9f3d2013-09-06 15:23:29 +00004634*/
drhd8b77e22014-09-06 01:35:57 +00004635static void whereLoopOutputAdjust(
4636 WhereClause *pWC, /* The WHERE clause */
4637 WhereLoop *pLoop, /* The loop to adjust downward */
4638 LogEst nRow /* Number of rows in the entire table */
4639){
drh7d9e7d82013-09-11 17:39:09 +00004640 WhereTerm *pTerm, *pX;
drhcca9f3d2013-09-06 15:23:29 +00004641 Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf);
drh7a1bca72014-11-22 18:50:44 +00004642 int i, j, k;
4643 LogEst iReduce = 0; /* pLoop->nOut should not exceed nRow-iReduce */
drhadd5ce32013-09-07 00:29:06 +00004644
drha3898252014-11-22 12:22:13 +00004645 assert( (pLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
drhcca9f3d2013-09-06 15:23:29 +00004646 for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){
drh7d9e7d82013-09-11 17:39:09 +00004647 if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break;
drhcca9f3d2013-09-06 15:23:29 +00004648 if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;
4649 if( (pTerm->prereqAll & notAllowed)!=0 ) continue;
drh7d9e7d82013-09-11 17:39:09 +00004650 for(j=pLoop->nLTerm-1; j>=0; j--){
4651 pX = pLoop->aLTerm[j];
drhd2447442013-11-13 19:01:41 +00004652 if( pX==0 ) continue;
drh7d9e7d82013-09-11 17:39:09 +00004653 if( pX==pTerm ) break;
4654 if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break;
4655 }
danaa9933c2014-04-24 20:04:49 +00004656 if( j<0 ){
drhd8b77e22014-09-06 01:35:57 +00004657 if( pTerm->truthProb<=0 ){
drh7a1bca72014-11-22 18:50:44 +00004658 /* If a truth probability is specified using the likelihood() hints,
4659 ** then use the probability provided by the application. */
drhd8b77e22014-09-06 01:35:57 +00004660 pLoop->nOut += pTerm->truthProb;
4661 }else{
drh7a1bca72014-11-22 18:50:44 +00004662 /* In the absence of explicit truth probabilities, use heuristics to
4663 ** guess a reasonable truth probability. */
drhd8b77e22014-09-06 01:35:57 +00004664 pLoop->nOut--;
drhe8d0c612015-05-14 01:05:25 +00004665 if( pTerm->eOperator&(WO_EQ|WO_IS) ){
drh7a1bca72014-11-22 18:50:44 +00004666 Expr *pRight = pTerm->pExpr->pRight;
drhe0cc3c22015-05-13 17:54:08 +00004667 testcase( pTerm->pExpr->op==TK_IS );
drh7a1bca72014-11-22 18:50:44 +00004668 if( sqlite3ExprIsInteger(pRight, &k) && k>=(-1) && k<=1 ){
4669 k = 10;
4670 }else{
4671 k = 20;
4672 }
4673 if( iReduce<k ) iReduce = k;
4674 }
drhd8b77e22014-09-06 01:35:57 +00004675 }
danaa9933c2014-04-24 20:04:49 +00004676 }
drhcca9f3d2013-09-06 15:23:29 +00004677 }
drh7a1bca72014-11-22 18:50:44 +00004678 if( pLoop->nOut > nRow-iReduce ) pLoop->nOut = nRow - iReduce;
drhcca9f3d2013-09-06 15:23:29 +00004679}
4680
4681/*
drhdbd94862014-07-23 23:57:42 +00004682** Adjust the cost C by the costMult facter T. This only occurs if
4683** compiled with -DSQLITE_ENABLE_COSTMULT
4684*/
4685#ifdef SQLITE_ENABLE_COSTMULT
4686# define ApplyCostMultiplier(C,T) C += T
4687#else
4688# define ApplyCostMultiplier(C,T)
4689#endif
4690
4691/*
dan4a6b8a02014-04-30 14:47:01 +00004692** We have so far matched pBuilder->pNew->u.btree.nEq terms of the
4693** index pIndex. Try to match one more.
4694**
4695** When this function is called, pBuilder->pNew->nOut contains the
4696** number of rows expected to be visited by filtering using the nEq
4697** terms only. If it is modified, this value is restored before this
4698** function returns.
drh1c8148f2013-05-04 20:25:23 +00004699**
4700** If pProbe->tnum==0, that means pIndex is a fake index used for the
4701** INTEGER PRIMARY KEY.
4702*/
drh5346e952013-05-08 14:14:26 +00004703static int whereLoopAddBtreeIndex(
drh1c8148f2013-05-04 20:25:23 +00004704 WhereLoopBuilder *pBuilder, /* The WhereLoop factory */
4705 struct SrcList_item *pSrc, /* FROM clause term being analyzed */
4706 Index *pProbe, /* An index on pSrc */
drhbf539c42013-10-05 18:16:02 +00004707 LogEst nInMul /* log(Number of iterations due to IN) */
drh1c8148f2013-05-04 20:25:23 +00004708){
drh70d18342013-06-06 19:16:33 +00004709 WhereInfo *pWInfo = pBuilder->pWInfo; /* WHERE analyse context */
4710 Parse *pParse = pWInfo->pParse; /* Parsing context */
4711 sqlite3 *db = pParse->db; /* Database connection malloc context */
drh1c8148f2013-05-04 20:25:23 +00004712 WhereLoop *pNew; /* Template WhereLoop under construction */
4713 WhereTerm *pTerm; /* A WhereTerm under consideration */
drh43fe25f2013-05-07 23:06:23 +00004714 int opMask; /* Valid operators for constraints */
drh1c8148f2013-05-04 20:25:23 +00004715 WhereScan scan; /* Iterator for WHERE terms */
drh4efc9292013-06-06 23:02:03 +00004716 Bitmask saved_prereq; /* Original value of pNew->prereq */
4717 u16 saved_nLTerm; /* Original value of pNew->nLTerm */
drhcd8629e2013-11-13 12:27:25 +00004718 u16 saved_nEq; /* Original value of pNew->u.btree.nEq */
drhc8bbce12014-10-21 01:05:09 +00004719 u16 saved_nSkip; /* Original value of pNew->nSkip */
drh4efc9292013-06-06 23:02:03 +00004720 u32 saved_wsFlags; /* Original value of pNew->wsFlags */
drhbf539c42013-10-05 18:16:02 +00004721 LogEst saved_nOut; /* Original value of pNew->nOut */
drha18f3d22013-05-08 03:05:41 +00004722 int iCol; /* Index of the column in the table */
drh5346e952013-05-08 14:14:26 +00004723 int rc = SQLITE_OK; /* Return code */
drhd8b77e22014-09-06 01:35:57 +00004724 LogEst rSize; /* Number of rows in the table */
drhbf539c42013-10-05 18:16:02 +00004725 LogEst rLogSize; /* Logarithm of table size */
drhc7f0d222013-06-19 03:27:12 +00004726 WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
drh1c8148f2013-05-04 20:25:23 +00004727
drh1c8148f2013-05-04 20:25:23 +00004728 pNew = pBuilder->pNew;
drh5346e952013-05-08 14:14:26 +00004729 if( db->mallocFailed ) return SQLITE_NOMEM;
drh1c8148f2013-05-04 20:25:23 +00004730
drh5346e952013-05-08 14:14:26 +00004731 assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
drh43fe25f2013-05-07 23:06:23 +00004732 assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
4733 if( pNew->wsFlags & WHERE_BTM_LIMIT ){
4734 opMask = WO_LT|WO_LE;
drhee145872015-05-14 13:18:47 +00004735 }else if( /*pProbe->tnum<=0 ||*/ (pSrc->jointype & JT_LEFT)!=0 ){
drh43fe25f2013-05-07 23:06:23 +00004736 opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE;
drh1c8148f2013-05-04 20:25:23 +00004737 }else{
drhe8d0c612015-05-14 01:05:25 +00004738 opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE|WO_ISNULL|WO_IS;
drh1c8148f2013-05-04 20:25:23 +00004739 }
drhef866372013-05-22 20:49:02 +00004740 if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
drh1c8148f2013-05-04 20:25:23 +00004741
dan39129ce2014-06-30 15:23:57 +00004742 assert( pNew->u.btree.nEq<pProbe->nColumn );
4743 iCol = pProbe->aiColumn[pNew->u.btree.nEq];
4744
drha18f3d22013-05-08 03:05:41 +00004745 pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, iCol,
drh0f133a42013-05-22 17:01:17 +00004746 opMask, pProbe);
drh4efc9292013-06-06 23:02:03 +00004747 saved_nEq = pNew->u.btree.nEq;
drhc8bbce12014-10-21 01:05:09 +00004748 saved_nSkip = pNew->nSkip;
drh4efc9292013-06-06 23:02:03 +00004749 saved_nLTerm = pNew->nLTerm;
4750 saved_wsFlags = pNew->wsFlags;
4751 saved_prereq = pNew->prereq;
4752 saved_nOut = pNew->nOut;
drhb8a8e8a2013-06-10 19:12:39 +00004753 pNew->rSetup = 0;
drhd8b77e22014-09-06 01:35:57 +00004754 rSize = pProbe->aiRowLogEst[0];
4755 rLogSize = estLog(rSize);
drh5346e952013-05-08 14:14:26 +00004756 for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
dan8ad1d8b2014-04-25 20:22:45 +00004757 u16 eOp = pTerm->eOperator; /* Shorthand for pTerm->eOperator */
danaa9933c2014-04-24 20:04:49 +00004758 LogEst rCostIdx;
dan8ad1d8b2014-04-25 20:22:45 +00004759 LogEst nOutUnadjusted; /* nOut before IN() and WHERE adjustments */
drhb8a8e8a2013-06-10 19:12:39 +00004760 int nIn = 0;
drh1435a9a2013-08-27 23:15:44 +00004761#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
dan7a419232013-08-06 20:01:43 +00004762 int nRecValid = pBuilder->nRecValid;
drhb5246e52013-07-08 21:12:57 +00004763#endif
dan8ad1d8b2014-04-25 20:22:45 +00004764 if( (eOp==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)
dan8bff07a2013-08-29 14:56:14 +00004765 && (iCol<0 || pSrc->pTab->aCol[iCol].notNull)
4766 ){
4767 continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */
4768 }
dan7a419232013-08-06 20:01:43 +00004769 if( pTerm->prereqRight & pNew->maskSelf ) continue;
4770
drha40da622015-03-09 12:11:56 +00004771 /* Do not allow the upper bound of a LIKE optimization range constraint
4772 ** to mix with a lower range bound from some other source */
4773 if( pTerm->wtFlags & TERM_LIKEOPT && pTerm->eOperator==WO_LT ) continue;
4774
drh4efc9292013-06-06 23:02:03 +00004775 pNew->wsFlags = saved_wsFlags;
4776 pNew->u.btree.nEq = saved_nEq;
4777 pNew->nLTerm = saved_nLTerm;
4778 if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
4779 pNew->aLTerm[pNew->nLTerm++] = pTerm;
4780 pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
dan8ad1d8b2014-04-25 20:22:45 +00004781
4782 assert( nInMul==0
4783 || (pNew->wsFlags & WHERE_COLUMN_NULL)!=0
4784 || (pNew->wsFlags & WHERE_COLUMN_IN)!=0
4785 || (pNew->wsFlags & WHERE_SKIPSCAN)!=0
4786 );
4787
4788 if( eOp & WO_IN ){
drha18f3d22013-05-08 03:05:41 +00004789 Expr *pExpr = pTerm->pExpr;
4790 pNew->wsFlags |= WHERE_COLUMN_IN;
4791 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
drhe1e2e9a2013-06-13 15:16:53 +00004792 /* "x IN (SELECT ...)": TUNING: the SELECT returns 25 rows */
drhbf539c42013-10-05 18:16:02 +00004793 nIn = 46; assert( 46==sqlite3LogEst(25) );
drha18f3d22013-05-08 03:05:41 +00004794 }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
4795 /* "x IN (value, value, ...)" */
drhbf539c42013-10-05 18:16:02 +00004796 nIn = sqlite3LogEst(pExpr->x.pList->nExpr);
drhf1645f02013-05-07 19:44:38 +00004797 }
drh2b59b3a2014-03-20 13:26:47 +00004798 assert( nIn>0 ); /* RHS always has 2 or more terms... The parser
4799 ** changes "x IN (?)" into "x=?". */
dan8ad1d8b2014-04-25 20:22:45 +00004800
drhe8d0c612015-05-14 01:05:25 +00004801 }else if( eOp & (WO_EQ|WO_IS) ){
drha18f3d22013-05-08 03:05:41 +00004802 pNew->wsFlags |= WHERE_COLUMN_EQ;
dan8ad1d8b2014-04-25 20:22:45 +00004803 if( iCol<0 || (nInMul==0 && pNew->u.btree.nEq==pProbe->nKeyCol-1) ){
dan2813bde2015-04-11 11:44:27 +00004804 if( iCol>=0 && pProbe->uniqNotNull==0 ){
drhe39a7322014-02-03 14:04:11 +00004805 pNew->wsFlags |= WHERE_UNQ_WANTED;
4806 }else{
4807 pNew->wsFlags |= WHERE_ONEROW;
4808 }
drh21f7ff72013-06-03 15:07:23 +00004809 }
dan2dd3cdc2014-04-26 20:21:14 +00004810 }else if( eOp & WO_ISNULL ){
4811 pNew->wsFlags |= WHERE_COLUMN_NULL;
dan8ad1d8b2014-04-25 20:22:45 +00004812 }else if( eOp & (WO_GT|WO_GE) ){
4813 testcase( eOp & WO_GT );
4814 testcase( eOp & WO_GE );
drha18f3d22013-05-08 03:05:41 +00004815 pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
drh6f2bfad2013-06-03 17:35:22 +00004816 pBtm = pTerm;
4817 pTop = 0;
drha40da622015-03-09 12:11:56 +00004818 if( pTerm->wtFlags & TERM_LIKEOPT ){
drh80314622015-03-09 13:01:02 +00004819 /* Range contraints that come from the LIKE optimization are
4820 ** always used in pairs. */
drha40da622015-03-09 12:11:56 +00004821 pTop = &pTerm[1];
4822 assert( (pTop-(pTerm->pWC->a))<pTerm->pWC->nTerm );
4823 assert( pTop->wtFlags & TERM_LIKEOPT );
4824 assert( pTop->eOperator==WO_LT );
4825 if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
4826 pNew->aLTerm[pNew->nLTerm++] = pTop;
4827 pNew->wsFlags |= WHERE_TOP_LIMIT;
4828 }
dan2dd3cdc2014-04-26 20:21:14 +00004829 }else{
dan8ad1d8b2014-04-25 20:22:45 +00004830 assert( eOp & (WO_LT|WO_LE) );
4831 testcase( eOp & WO_LT );
4832 testcase( eOp & WO_LE );
drha18f3d22013-05-08 03:05:41 +00004833 pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
drh6f2bfad2013-06-03 17:35:22 +00004834 pTop = pTerm;
4835 pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
drh4efc9292013-06-06 23:02:03 +00004836 pNew->aLTerm[pNew->nLTerm-2] : 0;
drh1c8148f2013-05-04 20:25:23 +00004837 }
dan8ad1d8b2014-04-25 20:22:45 +00004838
4839 /* At this point pNew->nOut is set to the number of rows expected to
4840 ** be visited by the index scan before considering term pTerm, or the
4841 ** values of nIn and nInMul. In other words, assuming that all
4842 ** "x IN(...)" terms are replaced with "x = ?". This block updates
4843 ** the value of pNew->nOut to account for pTerm (but not nIn/nInMul). */
4844 assert( pNew->nOut==saved_nOut );
drh6f2bfad2013-06-03 17:35:22 +00004845 if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
danaa9933c2014-04-24 20:04:49 +00004846 /* Adjust nOut using stat3/stat4 data. Or, if there is no stat3/stat4
4847 ** data, using some other estimate. */
drh186ad8c2013-10-08 18:40:37 +00004848 whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew);
dan8ad1d8b2014-04-25 20:22:45 +00004849 }else{
4850 int nEq = ++pNew->u.btree.nEq;
drhe8d0c612015-05-14 01:05:25 +00004851 assert( eOp & (WO_ISNULL|WO_EQ|WO_IN|WO_IS) );
dan8ad1d8b2014-04-25 20:22:45 +00004852
4853 assert( pNew->nOut==saved_nOut );
dan09e1df62014-04-29 16:10:22 +00004854 if( pTerm->truthProb<=0 && iCol>=0 ){
dan8ad1d8b2014-04-25 20:22:45 +00004855 assert( (eOp & WO_IN) || nIn==0 );
drhc5f246e2014-05-01 20:24:21 +00004856 testcase( eOp & WO_IN );
dan8ad1d8b2014-04-25 20:22:45 +00004857 pNew->nOut += pTerm->truthProb;
4858 pNew->nOut -= nIn;
dan8ad1d8b2014-04-25 20:22:45 +00004859 }else{
drh1435a9a2013-08-27 23:15:44 +00004860#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
dan8ad1d8b2014-04-25 20:22:45 +00004861 tRowcnt nOut = 0;
4862 if( nInMul==0
4863 && pProbe->nSample
4864 && pNew->u.btree.nEq<=pProbe->nSampleCol
dan8ad1d8b2014-04-25 20:22:45 +00004865 && ((eOp & WO_IN)==0 || !ExprHasProperty(pTerm->pExpr, EP_xIsSelect))
dan8ad1d8b2014-04-25 20:22:45 +00004866 ){
4867 Expr *pExpr = pTerm->pExpr;
drhe8d0c612015-05-14 01:05:25 +00004868 if( (eOp & (WO_EQ|WO_ISNULL|WO_IS))!=0 ){
4869 testcase( eOp & WO_EQ );
4870 testcase( eOp & WO_IS );
dan8ad1d8b2014-04-25 20:22:45 +00004871 testcase( eOp & WO_ISNULL );
4872 rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut);
4873 }else{
4874 rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut);
4875 }
dan8ad1d8b2014-04-25 20:22:45 +00004876 if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
4877 if( rc!=SQLITE_OK ) break; /* Jump out of the pTerm loop */
4878 if( nOut ){
4879 pNew->nOut = sqlite3LogEst(nOut);
4880 if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut;
4881 pNew->nOut -= nIn;
4882 }
4883 }
4884 if( nOut==0 )
4885#endif
4886 {
4887 pNew->nOut += (pProbe->aiRowLogEst[nEq] - pProbe->aiRowLogEst[nEq-1]);
4888 if( eOp & WO_ISNULL ){
4889 /* TUNING: If there is no likelihood() value, assume that a
4890 ** "col IS NULL" expression matches twice as many rows
4891 ** as (col=?). */
4892 pNew->nOut += 10;
4893 }
4894 }
dan6cb8d762013-08-08 11:48:57 +00004895 }
drh6f2bfad2013-06-03 17:35:22 +00004896 }
dan8ad1d8b2014-04-25 20:22:45 +00004897
danaa9933c2014-04-24 20:04:49 +00004898 /* Set rCostIdx to the cost of visiting selected rows in index. Add
4899 ** it to pNew->rRun, which is currently set to the cost of the index
4900 ** seek only. Then, if this is a non-covering index, add the cost of
4901 ** visiting the rows in the main table. */
4902 rCostIdx = pNew->nOut + 1 + (15*pProbe->szIdxRow)/pSrc->pTab->szTabRow;
dan8ad1d8b2014-04-25 20:22:45 +00004903 pNew->rRun = sqlite3LogEstAdd(rLogSize, rCostIdx);
drhe217efc2013-06-12 03:48:41 +00004904 if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
danaa9933c2014-04-24 20:04:49 +00004905 pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut + 16);
drheb04de32013-05-10 15:16:30 +00004906 }
drhdbd94862014-07-23 23:57:42 +00004907 ApplyCostMultiplier(pNew->rRun, pProbe->pTable->costMult);
danaa9933c2014-04-24 20:04:49 +00004908
dan8ad1d8b2014-04-25 20:22:45 +00004909 nOutUnadjusted = pNew->nOut;
4910 pNew->rRun += nInMul + nIn;
4911 pNew->nOut += nInMul + nIn;
drhd8b77e22014-09-06 01:35:57 +00004912 whereLoopOutputAdjust(pBuilder->pWC, pNew, rSize);
drhcf8fa7a2013-05-10 20:26:22 +00004913 rc = whereLoopInsert(pBuilder, pNew);
dan440e6ff2014-04-28 08:49:54 +00004914
4915 if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
4916 pNew->nOut = saved_nOut;
4917 }else{
4918 pNew->nOut = nOutUnadjusted;
4919 }
dan8ad1d8b2014-04-25 20:22:45 +00004920
drh5346e952013-05-08 14:14:26 +00004921 if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
dan39129ce2014-06-30 15:23:57 +00004922 && pNew->u.btree.nEq<pProbe->nColumn
drh5346e952013-05-08 14:14:26 +00004923 ){
drhb8a8e8a2013-06-10 19:12:39 +00004924 whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
drha18f3d22013-05-08 03:05:41 +00004925 }
danad45ed72013-08-08 12:21:32 +00004926 pNew->nOut = saved_nOut;
drh1435a9a2013-08-27 23:15:44 +00004927#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
dan7a419232013-08-06 20:01:43 +00004928 pBuilder->nRecValid = nRecValid;
dan7a419232013-08-06 20:01:43 +00004929#endif
drh1c8148f2013-05-04 20:25:23 +00004930 }
drh4efc9292013-06-06 23:02:03 +00004931 pNew->prereq = saved_prereq;
4932 pNew->u.btree.nEq = saved_nEq;
drhc8bbce12014-10-21 01:05:09 +00004933 pNew->nSkip = saved_nSkip;
drh4efc9292013-06-06 23:02:03 +00004934 pNew->wsFlags = saved_wsFlags;
4935 pNew->nOut = saved_nOut;
4936 pNew->nLTerm = saved_nLTerm;
drhc8bbce12014-10-21 01:05:09 +00004937
4938 /* Consider using a skip-scan if there are no WHERE clause constraints
4939 ** available for the left-most terms of the index, and if the average
4940 ** number of repeats in the left-most terms is at least 18.
4941 **
4942 ** The magic number 18 is selected on the basis that scanning 17 rows
4943 ** is almost always quicker than an index seek (even though if the index
4944 ** contains fewer than 2^17 rows we assume otherwise in other parts of
4945 ** the code). And, even if it is not, it should not be too much slower.
4946 ** On the other hand, the extra seeks could end up being significantly
4947 ** more expensive. */
4948 assert( 42==sqlite3LogEst(18) );
4949 if( saved_nEq==saved_nSkip
4950 && saved_nEq+1<pProbe->nKeyCol
drhf9df2fb2014-11-15 19:08:13 +00004951 && pProbe->noSkipScan==0
drhc8bbce12014-10-21 01:05:09 +00004952 && pProbe->aiRowLogEst[saved_nEq+1]>=42 /* TUNING: Minimum for skip-scan */
4953 && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK
4954 ){
4955 LogEst nIter;
4956 pNew->u.btree.nEq++;
4957 pNew->nSkip++;
4958 pNew->aLTerm[pNew->nLTerm++] = 0;
4959 pNew->wsFlags |= WHERE_SKIPSCAN;
4960 nIter = pProbe->aiRowLogEst[saved_nEq] - pProbe->aiRowLogEst[saved_nEq+1];
drhc8bbce12014-10-21 01:05:09 +00004961 pNew->nOut -= nIter;
4962 /* TUNING: Because uncertainties in the estimates for skip-scan queries,
4963 ** add a 1.375 fudge factor to make skip-scan slightly less likely. */
4964 nIter += 5;
4965 whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nIter + nInMul);
4966 pNew->nOut = saved_nOut;
4967 pNew->u.btree.nEq = saved_nEq;
4968 pNew->nSkip = saved_nSkip;
4969 pNew->wsFlags = saved_wsFlags;
4970 }
4971
drh5346e952013-05-08 14:14:26 +00004972 return rc;
drh1c8148f2013-05-04 20:25:23 +00004973}
4974
4975/*
drh23f98da2013-05-21 15:52:07 +00004976** Return True if it is possible that pIndex might be useful in
4977** implementing the ORDER BY clause in pBuilder.
4978**
4979** Return False if pBuilder does not contain an ORDER BY clause or
4980** if there is no way for pIndex to be useful in implementing that
4981** ORDER BY clause.
4982*/
4983static int indexMightHelpWithOrderBy(
4984 WhereLoopBuilder *pBuilder,
4985 Index *pIndex,
4986 int iCursor
4987){
4988 ExprList *pOB;
drh6d381472013-06-13 17:58:08 +00004989 int ii, jj;
drh23f98da2013-05-21 15:52:07 +00004990
drh53cfbe92013-06-13 17:28:22 +00004991 if( pIndex->bUnordered ) return 0;
drh70d18342013-06-06 19:16:33 +00004992 if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
drh23f98da2013-05-21 15:52:07 +00004993 for(ii=0; ii<pOB->nExpr; ii++){
drh45c154a2013-06-03 20:46:35 +00004994 Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr);
drh23f98da2013-05-21 15:52:07 +00004995 if( pExpr->op!=TK_COLUMN ) return 0;
4996 if( pExpr->iTable==iCursor ){
drh137fd4f2014-09-19 02:01:37 +00004997 if( pExpr->iColumn<0 ) return 1;
drhbbbdc832013-10-22 18:01:40 +00004998 for(jj=0; jj<pIndex->nKeyCol; jj++){
drh6d381472013-06-13 17:58:08 +00004999 if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
5000 }
drh23f98da2013-05-21 15:52:07 +00005001 }
5002 }
5003 return 0;
5004}
5005
5006/*
drh92a121f2013-06-10 12:15:47 +00005007** Return a bitmask where 1s indicate that the corresponding column of
5008** the table is used by an index. Only the first 63 columns are considered.
5009*/
drhfd5874d2013-06-12 14:52:39 +00005010static Bitmask columnsInIndex(Index *pIdx){
drh92a121f2013-06-10 12:15:47 +00005011 Bitmask m = 0;
5012 int j;
drhec95c442013-10-23 01:57:32 +00005013 for(j=pIdx->nColumn-1; j>=0; j--){
drh92a121f2013-06-10 12:15:47 +00005014 int x = pIdx->aiColumn[j];
drhec95c442013-10-23 01:57:32 +00005015 if( x>=0 ){
5016 testcase( x==BMS-1 );
5017 testcase( x==BMS-2 );
5018 if( x<BMS-1 ) m |= MASKBIT(x);
5019 }
drh92a121f2013-06-10 12:15:47 +00005020 }
5021 return m;
5022}
5023
drh4bd5f732013-07-31 23:22:39 +00005024/* Check to see if a partial index with pPartIndexWhere can be used
5025** in the current query. Return true if it can be and false if not.
5026*/
5027static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere){
5028 int i;
5029 WhereTerm *pTerm;
5030 for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
dan2a45cb52015-02-24 20:10:49 +00005031 Expr *pExpr = pTerm->pExpr;
5032 if( sqlite3ExprImpliesExpr(pExpr, pWhere, iTab)
5033 && (!ExprHasProperty(pExpr, EP_FromJoin) || pExpr->iRightJoinTable==iTab)
drh077f06e2015-02-24 16:48:59 +00005034 ){
5035 return 1;
5036 }
drh4bd5f732013-07-31 23:22:39 +00005037 }
5038 return 0;
5039}
drh92a121f2013-06-10 12:15:47 +00005040
5041/*
dan51576f42013-07-02 10:06:15 +00005042** Add all WhereLoop objects for a single table of the join where the table
drh0823c892013-05-11 00:06:23 +00005043** is idenfied by pBuilder->pNew->iTab. That table is guaranteed to be
5044** a b-tree table, not a virtual table.
dan81647222014-04-30 15:00:16 +00005045**
5046** The costs (WhereLoop.rRun) of the b-tree loops added by this function
5047** are calculated as follows:
5048**
5049** For a full scan, assuming the table (or index) contains nRow rows:
5050**
5051** cost = nRow * 3.0 // full-table scan
5052** cost = nRow * K // scan of covering index
5053** cost = nRow * (K+3.0) // scan of non-covering index
5054**
5055** where K is a value between 1.1 and 3.0 set based on the relative
5056** estimated average size of the index and table records.
5057**
5058** For an index scan, where nVisit is the number of index rows visited
5059** by the scan, and nSeek is the number of seek operations required on
5060** the index b-tree:
5061**
5062** cost = nSeek * (log(nRow) + K * nVisit) // covering index
5063** cost = nSeek * (log(nRow) + (K+3.0) * nVisit) // non-covering index
5064**
5065** Normally, nSeek is 1. nSeek values greater than 1 come about if the
5066** WHERE clause includes "x IN (....)" terms used in place of "x=?". Or when
5067** implicit "x IN (SELECT x FROM tbl)" terms are added for skip-scans.
drh83a305f2014-07-22 12:05:32 +00005068**
5069** The estimated values (nRow, nVisit, nSeek) often contain a large amount
5070** of uncertainty. For this reason, scoring is designed to pick plans that
5071** "do the least harm" if the estimates are inaccurate. For example, a
5072** log(nRow) factor is omitted from a non-covering index scan in order to
5073** bias the scoring in favor of using an index, since the worst-case
5074** performance of using an index is far better than the worst-case performance
5075** of a full table scan.
drhf1b5f5b2013-05-02 00:15:01 +00005076*/
drh5346e952013-05-08 14:14:26 +00005077static int whereLoopAddBtree(
drh1c8148f2013-05-04 20:25:23 +00005078 WhereLoopBuilder *pBuilder, /* WHERE clause information */
drh1c8148f2013-05-04 20:25:23 +00005079 Bitmask mExtra /* Extra prerequesites for using this table */
drhf1b5f5b2013-05-02 00:15:01 +00005080){
drh70d18342013-06-06 19:16:33 +00005081 WhereInfo *pWInfo; /* WHERE analysis context */
drh1c8148f2013-05-04 20:25:23 +00005082 Index *pProbe; /* An index we are evaluating */
drh1c8148f2013-05-04 20:25:23 +00005083 Index sPk; /* A fake index object for the primary key */
dancfc9df72014-04-25 15:01:01 +00005084 LogEst aiRowEstPk[2]; /* The aiRowLogEst[] value for the sPk index */
drhbbbdc832013-10-22 18:01:40 +00005085 i16 aiColumnPk = -1; /* The aColumn[] value for the sPk index */
drh70d18342013-06-06 19:16:33 +00005086 SrcList *pTabList; /* The FROM clause */
drh1c8148f2013-05-04 20:25:23 +00005087 struct SrcList_item *pSrc; /* The FROM clause btree term to add */
drh1c8148f2013-05-04 20:25:23 +00005088 WhereLoop *pNew; /* Template WhereLoop object */
drh5346e952013-05-08 14:14:26 +00005089 int rc = SQLITE_OK; /* Return code */
drhd044d202013-05-31 12:43:55 +00005090 int iSortIdx = 1; /* Index number */
drh23f98da2013-05-21 15:52:07 +00005091 int b; /* A boolean value */
drhbf539c42013-10-05 18:16:02 +00005092 LogEst rSize; /* number of rows in the table */
5093 LogEst rLogSize; /* Logarithm of the number of rows in the table */
drh4bd5f732013-07-31 23:22:39 +00005094 WhereClause *pWC; /* The parsed WHERE clause */
drh3495d202013-10-07 17:32:15 +00005095 Table *pTab; /* Table being queried */
drh23f98da2013-05-21 15:52:07 +00005096
drh1c8148f2013-05-04 20:25:23 +00005097 pNew = pBuilder->pNew;
drh70d18342013-06-06 19:16:33 +00005098 pWInfo = pBuilder->pWInfo;
5099 pTabList = pWInfo->pTabList;
5100 pSrc = pTabList->a + pNew->iTab;
drh3495d202013-10-07 17:32:15 +00005101 pTab = pSrc->pTab;
drh4bd5f732013-07-31 23:22:39 +00005102 pWC = pBuilder->pWC;
drh0823c892013-05-11 00:06:23 +00005103 assert( !IsVirtual(pSrc->pTab) );
drh1c8148f2013-05-04 20:25:23 +00005104
5105 if( pSrc->pIndex ){
5106 /* An INDEXED BY clause specifies a particular index to use */
5107 pProbe = pSrc->pIndex;
drhec95c442013-10-23 01:57:32 +00005108 }else if( !HasRowid(pTab) ){
5109 pProbe = pTab->pIndex;
drh1c8148f2013-05-04 20:25:23 +00005110 }else{
5111 /* There is no INDEXED BY clause. Create a fake Index object in local
5112 ** variable sPk to represent the rowid primary key index. Make this
5113 ** fake index the first in a chain of Index objects with all of the real
5114 ** indices to follow */
5115 Index *pFirst; /* First of real indices on the table */
5116 memset(&sPk, 0, sizeof(Index));
drhbbbdc832013-10-22 18:01:40 +00005117 sPk.nKeyCol = 1;
dan39129ce2014-06-30 15:23:57 +00005118 sPk.nColumn = 1;
drh1c8148f2013-05-04 20:25:23 +00005119 sPk.aiColumn = &aiColumnPk;
dancfc9df72014-04-25 15:01:01 +00005120 sPk.aiRowLogEst = aiRowEstPk;
drh1c8148f2013-05-04 20:25:23 +00005121 sPk.onError = OE_Replace;
drh3495d202013-10-07 17:32:15 +00005122 sPk.pTable = pTab;
danaa9933c2014-04-24 20:04:49 +00005123 sPk.szIdxRow = pTab->szTabRow;
dancfc9df72014-04-25 15:01:01 +00005124 aiRowEstPk[0] = pTab->nRowLogEst;
5125 aiRowEstPk[1] = 0;
drh1c8148f2013-05-04 20:25:23 +00005126 pFirst = pSrc->pTab->pIndex;
5127 if( pSrc->notIndexed==0 ){
5128 /* The real indices of the table are only considered if the
5129 ** NOT INDEXED qualifier is omitted from the FROM clause */
5130 sPk.pNext = pFirst;
5131 }
5132 pProbe = &sPk;
5133 }
dancfc9df72014-04-25 15:01:01 +00005134 rSize = pTab->nRowLogEst;
drheb04de32013-05-10 15:16:30 +00005135 rLogSize = estLog(rSize);
5136
drhfeb56e02013-08-23 17:33:46 +00005137#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
drheb04de32013-05-10 15:16:30 +00005138 /* Automatic indexes */
drhaa32e3c2013-07-16 21:31:23 +00005139 if( !pBuilder->pOrSet
drh8e8e7ef2015-03-02 17:25:00 +00005140 && (pWInfo->wctrlFlags & WHERE_NO_AUTOINDEX)==0
drh4fe425a2013-06-12 17:08:06 +00005141 && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
5142 && pSrc->pIndex==0
drheb04de32013-05-10 15:16:30 +00005143 && !pSrc->viaCoroutine
5144 && !pSrc->notIndexed
drhec95c442013-10-23 01:57:32 +00005145 && HasRowid(pTab)
drheb04de32013-05-10 15:16:30 +00005146 && !pSrc->isCorrelated
dan62ba4e42014-01-15 18:21:41 +00005147 && !pSrc->isRecursive
drheb04de32013-05-10 15:16:30 +00005148 ){
5149 /* Generate auto-index WhereLoops */
drheb04de32013-05-10 15:16:30 +00005150 WhereTerm *pTerm;
5151 WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
5152 for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
drh79a13bf2013-05-31 20:28:28 +00005153 if( pTerm->prereqRight & pNew->maskSelf ) continue;
drheb04de32013-05-10 15:16:30 +00005154 if( termCanDriveIndex(pTerm, pSrc, 0) ){
5155 pNew->u.btree.nEq = 1;
drhc8bbce12014-10-21 01:05:09 +00005156 pNew->nSkip = 0;
drhef866372013-05-22 20:49:02 +00005157 pNew->u.btree.pIndex = 0;
drh4efc9292013-06-06 23:02:03 +00005158 pNew->nLTerm = 1;
5159 pNew->aLTerm[0] = pTerm;
drhe1e2e9a2013-06-13 15:16:53 +00005160 /* TUNING: One-time cost for computing the automatic index is
drh7e074332014-09-22 14:30:51 +00005161 ** estimated to be X*N*log2(N) where N is the number of rows in
5162 ** the table being indexed and where X is 7 (LogEst=28) for normal
5163 ** tables or 1.375 (LogEst=4) for views and subqueries. The value
5164 ** of X is smaller for views and subqueries so that the query planner
5165 ** will be more aggressive about generating automatic indexes for
5166 ** those objects, since there is no opportunity to add schema
5167 ** indexes on subqueries and views. */
5168 pNew->rSetup = rLogSize + rSize + 4;
5169 if( pTab->pSelect==0 && (pTab->tabFlags & TF_Ephemeral)==0 ){
5170 pNew->rSetup += 24;
5171 }
drhdbd94862014-07-23 23:57:42 +00005172 ApplyCostMultiplier(pNew->rSetup, pTab->costMult);
drh986b3872013-06-28 21:12:20 +00005173 /* TUNING: Each index lookup yields 20 rows in the table. This
5174 ** is more than the usual guess of 10 rows, since we have no way
peter.d.reid60ec9142014-09-06 16:39:46 +00005175 ** of knowing how selective the index will ultimately be. It would
drh986b3872013-06-28 21:12:20 +00005176 ** not be unreasonable to make this value much larger. */
drhbf539c42013-10-05 18:16:02 +00005177 pNew->nOut = 43; assert( 43==sqlite3LogEst(20) );
drhb50596d2013-10-08 20:42:41 +00005178 pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut);
drh986b3872013-06-28 21:12:20 +00005179 pNew->wsFlags = WHERE_AUTO_INDEX;
drheb04de32013-05-10 15:16:30 +00005180 pNew->prereq = mExtra | pTerm->prereqRight;
drhcf8fa7a2013-05-10 20:26:22 +00005181 rc = whereLoopInsert(pBuilder, pNew);
drheb04de32013-05-10 15:16:30 +00005182 }
5183 }
5184 }
drhfeb56e02013-08-23 17:33:46 +00005185#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
drh1c8148f2013-05-04 20:25:23 +00005186
5187 /* Loop over all indices
5188 */
drh23f98da2013-05-21 15:52:07 +00005189 for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){
drh4bd5f732013-07-31 23:22:39 +00005190 if( pProbe->pPartIdxWhere!=0
dan08291692014-08-27 17:37:20 +00005191 && !whereUsablePartialIndex(pSrc->iCursor, pWC, pProbe->pPartIdxWhere) ){
5192 testcase( pNew->iTab!=pSrc->iCursor ); /* See ticket [98d973b8f5] */
drh4bd5f732013-07-31 23:22:39 +00005193 continue; /* Partial index inappropriate for this query */
5194 }
dan7de2a1f2014-04-28 20:11:20 +00005195 rSize = pProbe->aiRowLogEst[0];
drh5346e952013-05-08 14:14:26 +00005196 pNew->u.btree.nEq = 0;
drhc8bbce12014-10-21 01:05:09 +00005197 pNew->nSkip = 0;
drh4efc9292013-06-06 23:02:03 +00005198 pNew->nLTerm = 0;
drh23f98da2013-05-21 15:52:07 +00005199 pNew->iSortIdx = 0;
drhb8a8e8a2013-06-10 19:12:39 +00005200 pNew->rSetup = 0;
drh23f98da2013-05-21 15:52:07 +00005201 pNew->prereq = mExtra;
drh74f91d42013-06-19 18:01:44 +00005202 pNew->nOut = rSize;
drh23f98da2013-05-21 15:52:07 +00005203 pNew->u.btree.pIndex = pProbe;
5204 b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
drh53cfbe92013-06-13 17:28:22 +00005205 /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
5206 assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
drh43fe25f2013-05-07 23:06:23 +00005207 if( pProbe->tnum<=0 ){
5208 /* Integer primary key index */
5209 pNew->wsFlags = WHERE_IPK;
drh23f98da2013-05-21 15:52:07 +00005210
5211 /* Full table scan */
drhd044d202013-05-31 12:43:55 +00005212 pNew->iSortIdx = b ? iSortIdx : 0;
danaa9933c2014-04-24 20:04:49 +00005213 /* TUNING: Cost of full table scan is (N*3.0). */
5214 pNew->rRun = rSize + 16;
drhdbd94862014-07-23 23:57:42 +00005215 ApplyCostMultiplier(pNew->rRun, pTab->costMult);
drhd8b77e22014-09-06 01:35:57 +00005216 whereLoopOutputAdjust(pWC, pNew, rSize);
drh23f98da2013-05-21 15:52:07 +00005217 rc = whereLoopInsert(pBuilder, pNew);
drhcca9f3d2013-09-06 15:23:29 +00005218 pNew->nOut = rSize;
drh23f98da2013-05-21 15:52:07 +00005219 if( rc ) break;
drh43fe25f2013-05-07 23:06:23 +00005220 }else{
drhec95c442013-10-23 01:57:32 +00005221 Bitmask m;
5222 if( pProbe->isCovering ){
5223 pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
5224 m = 0;
5225 }else{
5226 m = pSrc->colUsed & ~columnsInIndex(pProbe);
5227 pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
5228 }
drh1c8148f2013-05-04 20:25:23 +00005229
drh23f98da2013-05-21 15:52:07 +00005230 /* Full scan via index */
drh53cfbe92013-06-13 17:28:22 +00005231 if( b
drh702ba9f2013-11-07 21:25:13 +00005232 || !HasRowid(pTab)
drh53cfbe92013-06-13 17:28:22 +00005233 || ( m==0
5234 && pProbe->bUnordered==0
drh702ba9f2013-11-07 21:25:13 +00005235 && (pProbe->szIdxRow<pTab->szTabRow)
drh53cfbe92013-06-13 17:28:22 +00005236 && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
5237 && sqlite3GlobalConfig.bUseCis
5238 && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
5239 )
drhe3b7c922013-06-03 19:17:40 +00005240 ){
drh23f98da2013-05-21 15:52:07 +00005241 pNew->iSortIdx = b ? iSortIdx : 0;
danaa9933c2014-04-24 20:04:49 +00005242
5243 /* The cost of visiting the index rows is N*K, where K is
5244 ** between 1.1 and 3.0, depending on the relative sizes of the
5245 ** index and table rows. If this is a non-covering index scan,
5246 ** also add the cost of visiting table rows (N*3.0). */
5247 pNew->rRun = rSize + 1 + (15*pProbe->szIdxRow)/pTab->szTabRow;
5248 if( m!=0 ){
5249 pNew->rRun = sqlite3LogEstAdd(pNew->rRun, rSize+16);
drhe1e2e9a2013-06-13 15:16:53 +00005250 }
drhdbd94862014-07-23 23:57:42 +00005251 ApplyCostMultiplier(pNew->rRun, pTab->costMult);
drhd8b77e22014-09-06 01:35:57 +00005252 whereLoopOutputAdjust(pWC, pNew, rSize);
drh23f98da2013-05-21 15:52:07 +00005253 rc = whereLoopInsert(pBuilder, pNew);
drhcca9f3d2013-09-06 15:23:29 +00005254 pNew->nOut = rSize;
drh23f98da2013-05-21 15:52:07 +00005255 if( rc ) break;
5256 }
5257 }
dan7a419232013-08-06 20:01:43 +00005258
drhb8a8e8a2013-06-10 19:12:39 +00005259 rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
drh1435a9a2013-08-27 23:15:44 +00005260#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
dan87cd9322013-08-07 15:52:41 +00005261 sqlite3Stat4ProbeFree(pBuilder->pRec);
5262 pBuilder->nRecValid = 0;
5263 pBuilder->pRec = 0;
danddc2d6e2013-08-06 20:15:06 +00005264#endif
drh1c8148f2013-05-04 20:25:23 +00005265
5266 /* If there was an INDEXED BY clause, then only that one index is
5267 ** considered. */
5268 if( pSrc->pIndex ) break;
5269 }
drh5346e952013-05-08 14:14:26 +00005270 return rc;
drhf1b5f5b2013-05-02 00:15:01 +00005271}
5272
drh8636e9c2013-06-11 01:50:08 +00005273#ifndef SQLITE_OMIT_VIRTUALTABLE
drhf1b5f5b2013-05-02 00:15:01 +00005274/*
drh0823c892013-05-11 00:06:23 +00005275** Add all WhereLoop objects for a table of the join identified by
5276** pBuilder->pNew->iTab. That table is guaranteed to be a virtual table.
drhf1b5f5b2013-05-02 00:15:01 +00005277*/
drh5346e952013-05-08 14:14:26 +00005278static int whereLoopAddVirtual(
danff4b23b2013-11-12 12:17:16 +00005279 WhereLoopBuilder *pBuilder, /* WHERE clause information */
5280 Bitmask mExtra
drhf1b5f5b2013-05-02 00:15:01 +00005281){
drh70d18342013-06-06 19:16:33 +00005282 WhereInfo *pWInfo; /* WHERE analysis context */
drh5346e952013-05-08 14:14:26 +00005283 Parse *pParse; /* The parsing context */
5284 WhereClause *pWC; /* The WHERE clause */
5285 struct SrcList_item *pSrc; /* The FROM clause term to search */
5286 Table *pTab;
5287 sqlite3 *db;
5288 sqlite3_index_info *pIdxInfo;
5289 struct sqlite3_index_constraint *pIdxCons;
5290 struct sqlite3_index_constraint_usage *pUsage;
5291 WhereTerm *pTerm;
5292 int i, j;
5293 int iTerm, mxTerm;
drh4efc9292013-06-06 23:02:03 +00005294 int nConstraint;
drh5346e952013-05-08 14:14:26 +00005295 int seenIn = 0; /* True if an IN operator is seen */
5296 int seenVar = 0; /* True if a non-constant constraint is seen */
5297 int iPhase; /* 0: const w/o IN, 1: const, 2: no IN, 2: IN */
5298 WhereLoop *pNew;
drh5346e952013-05-08 14:14:26 +00005299 int rc = SQLITE_OK;
5300
drh70d18342013-06-06 19:16:33 +00005301 pWInfo = pBuilder->pWInfo;
5302 pParse = pWInfo->pParse;
drh5346e952013-05-08 14:14:26 +00005303 db = pParse->db;
5304 pWC = pBuilder->pWC;
drh5346e952013-05-08 14:14:26 +00005305 pNew = pBuilder->pNew;
drh70d18342013-06-06 19:16:33 +00005306 pSrc = &pWInfo->pTabList->a[pNew->iTab];
drhb2a90f02013-05-10 03:30:49 +00005307 pTab = pSrc->pTab;
drh0823c892013-05-11 00:06:23 +00005308 assert( IsVirtual(pTab) );
drhb2a90f02013-05-10 03:30:49 +00005309 pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pBuilder->pOrderBy);
drh5346e952013-05-08 14:14:26 +00005310 if( pIdxInfo==0 ) return SQLITE_NOMEM;
drh5346e952013-05-08 14:14:26 +00005311 pNew->prereq = 0;
drh5346e952013-05-08 14:14:26 +00005312 pNew->rSetup = 0;
5313 pNew->wsFlags = WHERE_VIRTUALTABLE;
drh4efc9292013-06-06 23:02:03 +00005314 pNew->nLTerm = 0;
drh5346e952013-05-08 14:14:26 +00005315 pNew->u.vtab.needFree = 0;
5316 pUsage = pIdxInfo->aConstraintUsage;
drh4efc9292013-06-06 23:02:03 +00005317 nConstraint = pIdxInfo->nConstraint;
drh7963b0e2013-06-17 21:37:40 +00005318 if( whereLoopResize(db, pNew, nConstraint) ){
5319 sqlite3DbFree(db, pIdxInfo);
5320 return SQLITE_NOMEM;
5321 }
drh5346e952013-05-08 14:14:26 +00005322
drh0823c892013-05-11 00:06:23 +00005323 for(iPhase=0; iPhase<=3; iPhase++){
drh5346e952013-05-08 14:14:26 +00005324 if( !seenIn && (iPhase&1)!=0 ){
5325 iPhase++;
5326 if( iPhase>3 ) break;
5327 }
5328 if( !seenVar && iPhase>1 ) break;
5329 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
5330 for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
5331 j = pIdxCons->iTermOffset;
5332 pTerm = &pWC->a[j];
5333 switch( iPhase ){
5334 case 0: /* Constants without IN operator */
5335 pIdxCons->usable = 0;
5336 if( (pTerm->eOperator & WO_IN)!=0 ){
5337 seenIn = 1;
drh7963b0e2013-06-17 21:37:40 +00005338 }
5339 if( pTerm->prereqRight!=0 ){
drh5346e952013-05-08 14:14:26 +00005340 seenVar = 1;
drh7963b0e2013-06-17 21:37:40 +00005341 }else if( (pTerm->eOperator & WO_IN)==0 ){
drh5346e952013-05-08 14:14:26 +00005342 pIdxCons->usable = 1;
5343 }
5344 break;
5345 case 1: /* Constants with IN operators */
5346 assert( seenIn );
5347 pIdxCons->usable = (pTerm->prereqRight==0);
5348 break;
5349 case 2: /* Variables without IN */
5350 assert( seenVar );
5351 pIdxCons->usable = (pTerm->eOperator & WO_IN)==0;
5352 break;
5353 default: /* Variables with IN */
5354 assert( seenVar && seenIn );
5355 pIdxCons->usable = 1;
5356 break;
5357 }
5358 }
5359 memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
5360 if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
5361 pIdxInfo->idxStr = 0;
5362 pIdxInfo->idxNum = 0;
5363 pIdxInfo->needToFreeIdxStr = 0;
5364 pIdxInfo->orderByConsumed = 0;
drh8636e9c2013-06-11 01:50:08 +00005365 pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
dana9f58152013-11-11 19:01:33 +00005366 pIdxInfo->estimatedRows = 25;
drh5346e952013-05-08 14:14:26 +00005367 rc = vtabBestIndex(pParse, pTab, pIdxInfo);
5368 if( rc ) goto whereLoopAddVtab_exit;
5369 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
danff4b23b2013-11-12 12:17:16 +00005370 pNew->prereq = mExtra;
drhc718f1c2013-05-08 20:05:58 +00005371 mxTerm = -1;
drh4efc9292013-06-06 23:02:03 +00005372 assert( pNew->nLSlot>=nConstraint );
5373 for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
drh3bd26f02013-05-24 14:52:03 +00005374 pNew->u.vtab.omitMask = 0;
drh4efc9292013-06-06 23:02:03 +00005375 for(i=0; i<nConstraint; i++, pIdxCons++){
drh5346e952013-05-08 14:14:26 +00005376 if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
5377 j = pIdxCons->iTermOffset;
drh4efc9292013-06-06 23:02:03 +00005378 if( iTerm>=nConstraint
drh5346e952013-05-08 14:14:26 +00005379 || j<0
5380 || j>=pWC->nTerm
drh4efc9292013-06-06 23:02:03 +00005381 || pNew->aLTerm[iTerm]!=0
drh5346e952013-05-08 14:14:26 +00005382 ){
5383 rc = SQLITE_ERROR;
5384 sqlite3ErrorMsg(pParse, "%s.xBestIndex() malfunction", pTab->zName);
5385 goto whereLoopAddVtab_exit;
5386 }
drh7963b0e2013-06-17 21:37:40 +00005387 testcase( iTerm==nConstraint-1 );
5388 testcase( j==0 );
5389 testcase( j==pWC->nTerm-1 );
drh5346e952013-05-08 14:14:26 +00005390 pTerm = &pWC->a[j];
5391 pNew->prereq |= pTerm->prereqRight;
drh4efc9292013-06-06 23:02:03 +00005392 assert( iTerm<pNew->nLSlot );
5393 pNew->aLTerm[iTerm] = pTerm;
drh5346e952013-05-08 14:14:26 +00005394 if( iTerm>mxTerm ) mxTerm = iTerm;
drh7963b0e2013-06-17 21:37:40 +00005395 testcase( iTerm==15 );
5396 testcase( iTerm==16 );
drh52986302013-06-03 16:03:16 +00005397 if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm;
drh5346e952013-05-08 14:14:26 +00005398 if( (pTerm->eOperator & WO_IN)!=0 ){
5399 if( pUsage[i].omit==0 ){
5400 /* Do not attempt to use an IN constraint if the virtual table
5401 ** says that the equivalent EQ constraint cannot be safely omitted.
5402 ** If we do attempt to use such a constraint, some rows might be
5403 ** repeated in the output. */
5404 break;
5405 }
5406 /* A virtual table that is constrained by an IN clause may not
5407 ** consume the ORDER BY clause because (1) the order of IN terms
5408 ** is not necessarily related to the order of output terms and
5409 ** (2) Multiple outputs from a single IN value will not merge
5410 ** together. */
5411 pIdxInfo->orderByConsumed = 0;
5412 }
5413 }
5414 }
drh4efc9292013-06-06 23:02:03 +00005415 if( i>=nConstraint ){
5416 pNew->nLTerm = mxTerm+1;
5417 assert( pNew->nLTerm<=pNew->nLSlot );
drh5346e952013-05-08 14:14:26 +00005418 pNew->u.vtab.idxNum = pIdxInfo->idxNum;
5419 pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
5420 pIdxInfo->needToFreeIdxStr = 0;
5421 pNew->u.vtab.idxStr = pIdxInfo->idxStr;
drh0401ace2014-03-18 15:30:27 +00005422 pNew->u.vtab.isOrdered = (i8)(pIdxInfo->orderByConsumed ?
5423 pIdxInfo->nOrderBy : 0);
drhb8a8e8a2013-06-10 19:12:39 +00005424 pNew->rSetup = 0;
drhb50596d2013-10-08 20:42:41 +00005425 pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost);
dana9f58152013-11-11 19:01:33 +00005426 pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows);
drhcf8fa7a2013-05-10 20:26:22 +00005427 whereLoopInsert(pBuilder, pNew);
drh5346e952013-05-08 14:14:26 +00005428 if( pNew->u.vtab.needFree ){
5429 sqlite3_free(pNew->u.vtab.idxStr);
5430 pNew->u.vtab.needFree = 0;
5431 }
5432 }
5433 }
5434
5435whereLoopAddVtab_exit:
5436 if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
5437 sqlite3DbFree(db, pIdxInfo);
5438 return rc;
drhf1b5f5b2013-05-02 00:15:01 +00005439}
drh8636e9c2013-06-11 01:50:08 +00005440#endif /* SQLITE_OMIT_VIRTUALTABLE */
drhf1b5f5b2013-05-02 00:15:01 +00005441
5442/*
drhcf8fa7a2013-05-10 20:26:22 +00005443** Add WhereLoop entries to handle OR terms. This works for either
5444** btrees or virtual tables.
5445*/
5446static int whereLoopAddOr(WhereLoopBuilder *pBuilder, Bitmask mExtra){
drh70d18342013-06-06 19:16:33 +00005447 WhereInfo *pWInfo = pBuilder->pWInfo;
drhcf8fa7a2013-05-10 20:26:22 +00005448 WhereClause *pWC;
5449 WhereLoop *pNew;
5450 WhereTerm *pTerm, *pWCEnd;
5451 int rc = SQLITE_OK;
5452 int iCur;
5453 WhereClause tempWC;
5454 WhereLoopBuilder sSubBuild;
dan5da73e12014-04-30 18:11:55 +00005455 WhereOrSet sSum, sCur;
drhcf8fa7a2013-05-10 20:26:22 +00005456 struct SrcList_item *pItem;
5457
drhcf8fa7a2013-05-10 20:26:22 +00005458 pWC = pBuilder->pWC;
drhcf8fa7a2013-05-10 20:26:22 +00005459 pWCEnd = pWC->a + pWC->nTerm;
5460 pNew = pBuilder->pNew;
drh77dfd5b2013-08-19 11:15:48 +00005461 memset(&sSum, 0, sizeof(sSum));
drh186ad8c2013-10-08 18:40:37 +00005462 pItem = pWInfo->pTabList->a + pNew->iTab;
5463 iCur = pItem->iCursor;
drhcf8fa7a2013-05-10 20:26:22 +00005464
5465 for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
5466 if( (pTerm->eOperator & WO_OR)!=0
5467 && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
5468 ){
5469 WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
5470 WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
5471 WhereTerm *pOrTerm;
drhaa32e3c2013-07-16 21:31:23 +00005472 int once = 1;
5473 int i, j;
drh783dece2013-06-05 17:53:43 +00005474
drh783dece2013-06-05 17:53:43 +00005475 sSubBuild = *pBuilder;
5476 sSubBuild.pOrderBy = 0;
drhaa32e3c2013-07-16 21:31:23 +00005477 sSubBuild.pOrSet = &sCur;
drhcf8fa7a2013-05-10 20:26:22 +00005478
drh0a99ba32014-09-30 17:03:35 +00005479 WHERETRACE(0x200, ("Begin processing OR-clause %p\n", pTerm));
drhc7f0d222013-06-19 03:27:12 +00005480 for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
drh783dece2013-06-05 17:53:43 +00005481 if( (pOrTerm->eOperator & WO_AND)!=0 ){
drhcf8fa7a2013-05-10 20:26:22 +00005482 sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
5483 }else if( pOrTerm->leftCursor==iCur ){
drh70d18342013-06-06 19:16:33 +00005484 tempWC.pWInfo = pWC->pWInfo;
drh783dece2013-06-05 17:53:43 +00005485 tempWC.pOuter = pWC;
5486 tempWC.op = TK_AND;
drh783dece2013-06-05 17:53:43 +00005487 tempWC.nTerm = 1;
drhcf8fa7a2013-05-10 20:26:22 +00005488 tempWC.a = pOrTerm;
5489 sSubBuild.pWC = &tempWC;
5490 }else{
5491 continue;
5492 }
drhaa32e3c2013-07-16 21:31:23 +00005493 sCur.n = 0;
drh52651492014-09-30 14:14:19 +00005494#ifdef WHERETRACE_ENABLED
drh0a99ba32014-09-30 17:03:35 +00005495 WHERETRACE(0x200, ("OR-term %d of %p has %d subterms:\n",
5496 (int)(pOrTerm-pOrWC->a), pTerm, sSubBuild.pWC->nTerm));
5497 if( sqlite3WhereTrace & 0x400 ){
5498 for(i=0; i<sSubBuild.pWC->nTerm; i++){
5499 whereTermPrint(&sSubBuild.pWC->a[i], i);
5500 }
drh52651492014-09-30 14:14:19 +00005501 }
5502#endif
drh8636e9c2013-06-11 01:50:08 +00005503#ifndef SQLITE_OMIT_VIRTUALTABLE
drhcf8fa7a2013-05-10 20:26:22 +00005504 if( IsVirtual(pItem->pTab) ){
danff4b23b2013-11-12 12:17:16 +00005505 rc = whereLoopAddVirtual(&sSubBuild, mExtra);
drh8636e9c2013-06-11 01:50:08 +00005506 }else
5507#endif
5508 {
drhcf8fa7a2013-05-10 20:26:22 +00005509 rc = whereLoopAddBtree(&sSubBuild, mExtra);
5510 }
drh36be4c42014-09-30 17:31:23 +00005511 if( rc==SQLITE_OK ){
5512 rc = whereLoopAddOr(&sSubBuild, mExtra);
5513 }
drhaa32e3c2013-07-16 21:31:23 +00005514 assert( rc==SQLITE_OK || sCur.n==0 );
5515 if( sCur.n==0 ){
5516 sSum.n = 0;
5517 break;
5518 }else if( once ){
5519 whereOrMove(&sSum, &sCur);
5520 once = 0;
5521 }else{
dan5da73e12014-04-30 18:11:55 +00005522 WhereOrSet sPrev;
drhaa32e3c2013-07-16 21:31:23 +00005523 whereOrMove(&sPrev, &sSum);
5524 sSum.n = 0;
5525 for(i=0; i<sPrev.n; i++){
5526 for(j=0; j<sCur.n; j++){
5527 whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,
drhbf539c42013-10-05 18:16:02 +00005528 sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
5529 sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
drhaa32e3c2013-07-16 21:31:23 +00005530 }
5531 }
5532 }
drhcf8fa7a2013-05-10 20:26:22 +00005533 }
drhaa32e3c2013-07-16 21:31:23 +00005534 pNew->nLTerm = 1;
5535 pNew->aLTerm[0] = pTerm;
5536 pNew->wsFlags = WHERE_MULTI_OR;
5537 pNew->rSetup = 0;
5538 pNew->iSortIdx = 0;
5539 memset(&pNew->u, 0, sizeof(pNew->u));
5540 for(i=0; rc==SQLITE_OK && i<sSum.n; i++){
dan5da73e12014-04-30 18:11:55 +00005541 /* TUNING: Currently sSum.a[i].rRun is set to the sum of the costs
5542 ** of all sub-scans required by the OR-scan. However, due to rounding
5543 ** errors, it may be that the cost of the OR-scan is equal to its
5544 ** most expensive sub-scan. Add the smallest possible penalty
5545 ** (equivalent to multiplying the cost by 1.07) to ensure that
5546 ** this does not happen. Otherwise, for WHERE clauses such as the
5547 ** following where there is an index on "y":
5548 **
5549 ** WHERE likelihood(x=?, 0.99) OR y=?
5550 **
5551 ** the planner may elect to "OR" together a full-table scan and an
5552 ** index lookup. And other similarly odd results. */
5553 pNew->rRun = sSum.a[i].rRun + 1;
drhaa32e3c2013-07-16 21:31:23 +00005554 pNew->nOut = sSum.a[i].nOut;
5555 pNew->prereq = sSum.a[i].prereq;
drhfd5874d2013-06-12 14:52:39 +00005556 rc = whereLoopInsert(pBuilder, pNew);
5557 }
drh0a99ba32014-09-30 17:03:35 +00005558 WHERETRACE(0x200, ("End processing OR-clause %p\n", pTerm));
drhcf8fa7a2013-05-10 20:26:22 +00005559 }
5560 }
5561 return rc;
5562}
5563
5564/*
drhf1b5f5b2013-05-02 00:15:01 +00005565** Add all WhereLoop objects for all tables
5566*/
drh5346e952013-05-08 14:14:26 +00005567static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
drh70d18342013-06-06 19:16:33 +00005568 WhereInfo *pWInfo = pBuilder->pWInfo;
drhf1b5f5b2013-05-02 00:15:01 +00005569 Bitmask mExtra = 0;
5570 Bitmask mPrior = 0;
5571 int iTab;
drh70d18342013-06-06 19:16:33 +00005572 SrcList *pTabList = pWInfo->pTabList;
drhf1b5f5b2013-05-02 00:15:01 +00005573 struct SrcList_item *pItem;
drh70d18342013-06-06 19:16:33 +00005574 sqlite3 *db = pWInfo->pParse->db;
5575 int nTabList = pWInfo->nLevel;
drh5346e952013-05-08 14:14:26 +00005576 int rc = SQLITE_OK;
drhc63367e2013-06-10 20:46:50 +00005577 u8 priorJoinType = 0;
drhb8a8e8a2013-06-10 19:12:39 +00005578 WhereLoop *pNew;
drhf1b5f5b2013-05-02 00:15:01 +00005579
5580 /* Loop over the tables in the join, from left to right */
drhb8a8e8a2013-06-10 19:12:39 +00005581 pNew = pBuilder->pNew;
drha2014152013-06-07 00:29:23 +00005582 whereLoopInit(pNew);
drha18f3d22013-05-08 03:05:41 +00005583 for(iTab=0, pItem=pTabList->a; iTab<nTabList; iTab++, pItem++){
drhb2a90f02013-05-10 03:30:49 +00005584 pNew->iTab = iTab;
drh70d18342013-06-06 19:16:33 +00005585 pNew->maskSelf = getMask(&pWInfo->sMaskSet, pItem->iCursor);
drhc63367e2013-06-10 20:46:50 +00005586 if( ((pItem->jointype|priorJoinType) & (JT_LEFT|JT_CROSS))!=0 ){
drhf1b5f5b2013-05-02 00:15:01 +00005587 mExtra = mPrior;
5588 }
drhc63367e2013-06-10 20:46:50 +00005589 priorJoinType = pItem->jointype;
drhb2a90f02013-05-10 03:30:49 +00005590 if( IsVirtual(pItem->pTab) ){
danff4b23b2013-11-12 12:17:16 +00005591 rc = whereLoopAddVirtual(pBuilder, mExtra);
drhb2a90f02013-05-10 03:30:49 +00005592 }else{
5593 rc = whereLoopAddBtree(pBuilder, mExtra);
5594 }
drhb2a90f02013-05-10 03:30:49 +00005595 if( rc==SQLITE_OK ){
5596 rc = whereLoopAddOr(pBuilder, mExtra);
5597 }
drhb2a90f02013-05-10 03:30:49 +00005598 mPrior |= pNew->maskSelf;
drh5346e952013-05-08 14:14:26 +00005599 if( rc || db->mallocFailed ) break;
drhf1b5f5b2013-05-02 00:15:01 +00005600 }
drha2014152013-06-07 00:29:23 +00005601 whereLoopClear(db, pNew);
drh5346e952013-05-08 14:14:26 +00005602 return rc;
drhf1b5f5b2013-05-02 00:15:01 +00005603}
5604
drha18f3d22013-05-08 03:05:41 +00005605/*
drh7699d1c2013-06-04 12:42:29 +00005606** Examine a WherePath (with the addition of the extra WhereLoop of the 5th
drh319f6772013-05-14 15:31:07 +00005607** parameters) to see if it outputs rows in the requested ORDER BY
drh0401ace2014-03-18 15:30:27 +00005608** (or GROUP BY) without requiring a separate sort operation. Return N:
drh319f6772013-05-14 15:31:07 +00005609**
drh0401ace2014-03-18 15:30:27 +00005610** N>0: N terms of the ORDER BY clause are satisfied
5611** N==0: No terms of the ORDER BY clause are satisfied
5612** N<0: Unknown yet how many terms of ORDER BY might be satisfied.
drh319f6772013-05-14 15:31:07 +00005613**
drh94433422013-07-01 11:05:50 +00005614** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
5615** strict. With GROUP BY and DISTINCT the only requirement is that
5616** equivalent rows appear immediately adjacent to one another. GROUP BY
dan374cd782014-04-21 13:21:56 +00005617** and DISTINCT do not require rows to appear in any particular order as long
peter.d.reid60ec9142014-09-06 16:39:46 +00005618** as equivalent rows are grouped together. Thus for GROUP BY and DISTINCT
drh94433422013-07-01 11:05:50 +00005619** the pOrderBy terms can be matched in any order. With ORDER BY, the
5620** pOrderBy terms must be matched in strict left-to-right order.
drh6b7157b2013-05-10 02:00:35 +00005621*/
drh0401ace2014-03-18 15:30:27 +00005622static i8 wherePathSatisfiesOrderBy(
drh6b7157b2013-05-10 02:00:35 +00005623 WhereInfo *pWInfo, /* The WHERE clause */
drh4f402f22013-06-11 18:59:38 +00005624 ExprList *pOrderBy, /* ORDER BY or GROUP BY or DISTINCT clause to check */
drh6b7157b2013-05-10 02:00:35 +00005625 WherePath *pPath, /* The WherePath to check */
drh4f402f22013-06-11 18:59:38 +00005626 u16 wctrlFlags, /* Might contain WHERE_GROUPBY or WHERE_DISTINCTBY */
5627 u16 nLoop, /* Number of entries in pPath->aLoop[] */
drh319f6772013-05-14 15:31:07 +00005628 WhereLoop *pLast, /* Add this WhereLoop to the end of pPath->aLoop[] */
drh4f402f22013-06-11 18:59:38 +00005629 Bitmask *pRevMask /* OUT: Mask of WhereLoops to run in reverse order */
drh6b7157b2013-05-10 02:00:35 +00005630){
drh88da6442013-05-27 17:59:37 +00005631 u8 revSet; /* True if rev is known */
5632 u8 rev; /* Composite sort order */
5633 u8 revIdx; /* Index sort order */
drhe353ee32013-06-04 23:40:53 +00005634 u8 isOrderDistinct; /* All prior WhereLoops are order-distinct */
5635 u8 distinctColumns; /* True if the loop has UNIQUE NOT NULL columns */
5636 u8 isMatch; /* iColumn matches a term of the ORDER BY clause */
drh416846a2013-11-06 12:56:04 +00005637 u16 nKeyCol; /* Number of key columns in pIndex */
5638 u16 nColumn; /* Total number of ordered columns in the index */
drh7699d1c2013-06-04 12:42:29 +00005639 u16 nOrderBy; /* Number terms in the ORDER BY clause */
5640 int iLoop; /* Index of WhereLoop in pPath being processed */
5641 int i, j; /* Loop counters */
5642 int iCur; /* Cursor number for current WhereLoop */
5643 int iColumn; /* A column number within table iCur */
drhe8ae5832013-06-19 13:32:46 +00005644 WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
drh7699d1c2013-06-04 12:42:29 +00005645 WhereTerm *pTerm; /* A single term of the WHERE clause */
5646 Expr *pOBExpr; /* An expression from the ORDER BY clause */
5647 CollSeq *pColl; /* COLLATE function from an ORDER BY clause term */
5648 Index *pIndex; /* The index associated with pLoop */
5649 sqlite3 *db = pWInfo->pParse->db; /* Database connection */
5650 Bitmask obSat = 0; /* Mask of ORDER BY terms satisfied so far */
5651 Bitmask obDone; /* Mask of all ORDER BY terms */
drhe353ee32013-06-04 23:40:53 +00005652 Bitmask orderDistinctMask; /* Mask of all well-ordered loops */
drhb8916be2013-06-14 02:51:48 +00005653 Bitmask ready; /* Mask of inner loops */
drh319f6772013-05-14 15:31:07 +00005654
5655 /*
drh7699d1c2013-06-04 12:42:29 +00005656 ** We say the WhereLoop is "one-row" if it generates no more than one
5657 ** row of output. A WhereLoop is one-row if all of the following are true:
drh319f6772013-05-14 15:31:07 +00005658 ** (a) All index columns match with WHERE_COLUMN_EQ.
5659 ** (b) The index is unique
drh7699d1c2013-06-04 12:42:29 +00005660 ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
5661 ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
drh319f6772013-05-14 15:31:07 +00005662 **
drhe353ee32013-06-04 23:40:53 +00005663 ** We say the WhereLoop is "order-distinct" if the set of columns from
5664 ** that WhereLoop that are in the ORDER BY clause are different for every
5665 ** row of the WhereLoop. Every one-row WhereLoop is automatically
5666 ** order-distinct. A WhereLoop that has no columns in the ORDER BY clause
5667 ** is not order-distinct. To be order-distinct is not quite the same as being
5668 ** UNIQUE since a UNIQUE column or index can have multiple rows that
5669 ** are NULL and NULL values are equivalent for the purpose of order-distinct.
5670 ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
5671 **
5672 ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
5673 ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
5674 ** automatically order-distinct.
drh319f6772013-05-14 15:31:07 +00005675 */
5676
5677 assert( pOrderBy!=0 );
drh7699d1c2013-06-04 12:42:29 +00005678 if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
drh319f6772013-05-14 15:31:07 +00005679
drh319f6772013-05-14 15:31:07 +00005680 nOrderBy = pOrderBy->nExpr;
drh7963b0e2013-06-17 21:37:40 +00005681 testcase( nOrderBy==BMS-1 );
drhe353ee32013-06-04 23:40:53 +00005682 if( nOrderBy>BMS-1 ) return 0; /* Cannot optimize overly large ORDER BYs */
5683 isOrderDistinct = 1;
drh7699d1c2013-06-04 12:42:29 +00005684 obDone = MASKBIT(nOrderBy)-1;
drhe353ee32013-06-04 23:40:53 +00005685 orderDistinctMask = 0;
drhb8916be2013-06-14 02:51:48 +00005686 ready = 0;
drhe353ee32013-06-04 23:40:53 +00005687 for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
drhb8916be2013-06-14 02:51:48 +00005688 if( iLoop>0 ) ready |= pLoop->maskSelf;
drh7699d1c2013-06-04 12:42:29 +00005689 pLoop = iLoop<nLoop ? pPath->aLoop[iLoop] : pLast;
drh9dfaf622014-04-25 14:42:17 +00005690 if( pLoop->wsFlags & WHERE_VIRTUALTABLE ){
5691 if( pLoop->u.vtab.isOrdered ) obSat = obDone;
5692 break;
5693 }
drh319f6772013-05-14 15:31:07 +00005694 iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
drhb8916be2013-06-14 02:51:48 +00005695
5696 /* Mark off any ORDER BY term X that is a column in the table of
5697 ** the current loop for which there is term in the WHERE
5698 ** clause of the form X IS NULL or X=? that reference only outer
5699 ** loops.
5700 */
5701 for(i=0; i<nOrderBy; i++){
5702 if( MASKBIT(i) & obSat ) continue;
5703 pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
5704 if( pOBExpr->op!=TK_COLUMN ) continue;
5705 if( pOBExpr->iTable!=iCur ) continue;
5706 pTerm = findTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
drhe8d0c612015-05-14 01:05:25 +00005707 ~ready, WO_EQ|WO_ISNULL|WO_IS, 0);
drhb8916be2013-06-14 02:51:48 +00005708 if( pTerm==0 ) continue;
drhe8d0c612015-05-14 01:05:25 +00005709 if( (pTerm->eOperator&(WO_EQ|WO_IS))!=0 && pOBExpr->iColumn>=0 ){
drhb8916be2013-06-14 02:51:48 +00005710 const char *z1, *z2;
5711 pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
5712 if( !pColl ) pColl = db->pDfltColl;
5713 z1 = pColl->zName;
5714 pColl = sqlite3ExprCollSeq(pWInfo->pParse, pTerm->pExpr);
5715 if( !pColl ) pColl = db->pDfltColl;
5716 z2 = pColl->zName;
5717 if( sqlite3StrICmp(z1, z2)!=0 ) continue;
drhe0cc3c22015-05-13 17:54:08 +00005718 testcase( pTerm->pExpr->op==TK_IS );
drhb8916be2013-06-14 02:51:48 +00005719 }
5720 obSat |= MASKBIT(i);
5721 }
5722
drh7699d1c2013-06-04 12:42:29 +00005723 if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
5724 if( pLoop->wsFlags & WHERE_IPK ){
5725 pIndex = 0;
drhbbbdc832013-10-22 18:01:40 +00005726 nKeyCol = 0;
drh416846a2013-11-06 12:56:04 +00005727 nColumn = 1;
drh7699d1c2013-06-04 12:42:29 +00005728 }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
drh1b0f0262013-05-30 22:27:09 +00005729 return 0;
drh7699d1c2013-06-04 12:42:29 +00005730 }else{
drhbbbdc832013-10-22 18:01:40 +00005731 nKeyCol = pIndex->nKeyCol;
drh416846a2013-11-06 12:56:04 +00005732 nColumn = pIndex->nColumn;
5733 assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) );
5734 assert( pIndex->aiColumn[nColumn-1]==(-1) || !HasRowid(pIndex->pTable));
drh5f1d1d92014-07-31 22:59:04 +00005735 isOrderDistinct = IsUniqueIndex(pIndex);
drh1b0f0262013-05-30 22:27:09 +00005736 }
drh7699d1c2013-06-04 12:42:29 +00005737
drh7699d1c2013-06-04 12:42:29 +00005738 /* Loop through all columns of the index and deal with the ones
5739 ** that are not constrained by == or IN.
5740 */
5741 rev = revSet = 0;
drhe353ee32013-06-04 23:40:53 +00005742 distinctColumns = 0;
drh416846a2013-11-06 12:56:04 +00005743 for(j=0; j<nColumn; j++){
drh7699d1c2013-06-04 12:42:29 +00005744 u8 bOnce; /* True to run the ORDER BY search loop */
5745
drhe353ee32013-06-04 23:40:53 +00005746 /* Skip over == and IS NULL terms */
drh7699d1c2013-06-04 12:42:29 +00005747 if( j<pLoop->u.btree.nEq
drhc8bbce12014-10-21 01:05:09 +00005748 && pLoop->nSkip==0
drhe8d0c612015-05-14 01:05:25 +00005749 && ((i = pLoop->aLTerm[j]->eOperator) & (WO_EQ|WO_ISNULL|WO_IS))!=0
drh7699d1c2013-06-04 12:42:29 +00005750 ){
drh7963b0e2013-06-17 21:37:40 +00005751 if( i & WO_ISNULL ){
5752 testcase( isOrderDistinct );
5753 isOrderDistinct = 0;
5754 }
drhe353ee32013-06-04 23:40:53 +00005755 continue;
drh7699d1c2013-06-04 12:42:29 +00005756 }
5757
drhe353ee32013-06-04 23:40:53 +00005758 /* Get the column number in the table (iColumn) and sort order
5759 ** (revIdx) for the j-th column of the index.
drh7699d1c2013-06-04 12:42:29 +00005760 */
drh416846a2013-11-06 12:56:04 +00005761 if( pIndex ){
drh7699d1c2013-06-04 12:42:29 +00005762 iColumn = pIndex->aiColumn[j];
5763 revIdx = pIndex->aSortOrder[j];
5764 if( iColumn==pIndex->pTable->iPKey ) iColumn = -1;
drhdc3cd4b2013-05-30 23:21:20 +00005765 }else{
drh7699d1c2013-06-04 12:42:29 +00005766 iColumn = -1;
5767 revIdx = 0;
drhdc3cd4b2013-05-30 23:21:20 +00005768 }
drh7699d1c2013-06-04 12:42:29 +00005769
5770 /* An unconstrained column that might be NULL means that this
drh416846a2013-11-06 12:56:04 +00005771 ** WhereLoop is not well-ordered
drh7699d1c2013-06-04 12:42:29 +00005772 */
drhe353ee32013-06-04 23:40:53 +00005773 if( isOrderDistinct
5774 && iColumn>=0
drh7699d1c2013-06-04 12:42:29 +00005775 && j>=pLoop->u.btree.nEq
5776 && pIndex->pTable->aCol[iColumn].notNull==0
5777 ){
drhe353ee32013-06-04 23:40:53 +00005778 isOrderDistinct = 0;
drh7699d1c2013-06-04 12:42:29 +00005779 }
5780
5781 /* Find the ORDER BY term that corresponds to the j-th column
dan374cd782014-04-21 13:21:56 +00005782 ** of the index and mark that ORDER BY term off
drh7699d1c2013-06-04 12:42:29 +00005783 */
5784 bOnce = 1;
drhe353ee32013-06-04 23:40:53 +00005785 isMatch = 0;
drh7699d1c2013-06-04 12:42:29 +00005786 for(i=0; bOnce && i<nOrderBy; i++){
5787 if( MASKBIT(i) & obSat ) continue;
5788 pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
drh93ec45d2013-06-17 18:20:48 +00005789 testcase( wctrlFlags & WHERE_GROUPBY );
5790 testcase( wctrlFlags & WHERE_DISTINCTBY );
drh4f402f22013-06-11 18:59:38 +00005791 if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
drhe353ee32013-06-04 23:40:53 +00005792 if( pOBExpr->op!=TK_COLUMN ) continue;
drh7699d1c2013-06-04 12:42:29 +00005793 if( pOBExpr->iTable!=iCur ) continue;
5794 if( pOBExpr->iColumn!=iColumn ) continue;
5795 if( iColumn>=0 ){
5796 pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
5797 if( !pColl ) pColl = db->pDfltColl;
5798 if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
5799 }
drhe353ee32013-06-04 23:40:53 +00005800 isMatch = 1;
drh7699d1c2013-06-04 12:42:29 +00005801 break;
5802 }
drh49290472014-10-11 02:12:58 +00005803 if( isMatch && (wctrlFlags & WHERE_GROUPBY)==0 ){
drh59b8f2e2014-03-22 00:27:14 +00005804 /* Make sure the sort order is compatible in an ORDER BY clause.
5805 ** Sort order is irrelevant for a GROUP BY clause. */
5806 if( revSet ){
5807 if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) isMatch = 0;
5808 }else{
5809 rev = revIdx ^ pOrderBy->a[i].sortOrder;
5810 if( rev ) *pRevMask |= MASKBIT(iLoop);
5811 revSet = 1;
5812 }
5813 }
drhe353ee32013-06-04 23:40:53 +00005814 if( isMatch ){
drh7963b0e2013-06-17 21:37:40 +00005815 if( iColumn<0 ){
5816 testcase( distinctColumns==0 );
5817 distinctColumns = 1;
5818 }
drh7699d1c2013-06-04 12:42:29 +00005819 obSat |= MASKBIT(i);
drh7699d1c2013-06-04 12:42:29 +00005820 }else{
5821 /* No match found */
drhbbbdc832013-10-22 18:01:40 +00005822 if( j==0 || j<nKeyCol ){
drh7963b0e2013-06-17 21:37:40 +00005823 testcase( isOrderDistinct!=0 );
5824 isOrderDistinct = 0;
5825 }
drh7699d1c2013-06-04 12:42:29 +00005826 break;
5827 }
5828 } /* end Loop over all index columns */
drh81186b42013-06-18 01:52:41 +00005829 if( distinctColumns ){
5830 testcase( isOrderDistinct==0 );
5831 isOrderDistinct = 1;
5832 }
drh7699d1c2013-06-04 12:42:29 +00005833 } /* end-if not one-row */
5834
5835 /* Mark off any other ORDER BY terms that reference pLoop */
drhe353ee32013-06-04 23:40:53 +00005836 if( isOrderDistinct ){
5837 orderDistinctMask |= pLoop->maskSelf;
drh7699d1c2013-06-04 12:42:29 +00005838 for(i=0; i<nOrderBy; i++){
5839 Expr *p;
drh434a9312014-02-26 02:26:09 +00005840 Bitmask mTerm;
drh7699d1c2013-06-04 12:42:29 +00005841 if( MASKBIT(i) & obSat ) continue;
5842 p = pOrderBy->a[i].pExpr;
drh434a9312014-02-26 02:26:09 +00005843 mTerm = exprTableUsage(&pWInfo->sMaskSet,p);
5844 if( mTerm==0 && !sqlite3ExprIsConstant(p) ) continue;
5845 if( (mTerm&~orderDistinctMask)==0 ){
drh7699d1c2013-06-04 12:42:29 +00005846 obSat |= MASKBIT(i);
5847 }
drh0afb4232013-05-31 13:36:32 +00005848 }
drh319f6772013-05-14 15:31:07 +00005849 }
drhb8916be2013-06-14 02:51:48 +00005850 } /* End the loop over all WhereLoops from outer-most down to inner-most */
drh36ed0342014-03-28 12:56:57 +00005851 if( obSat==obDone ) return (i8)nOrderBy;
drhd2de8612014-03-18 18:59:07 +00005852 if( !isOrderDistinct ){
5853 for(i=nOrderBy-1; i>0; i--){
5854 Bitmask m = MASKBIT(i) - 1;
5855 if( (obSat&m)==m ) return i;
5856 }
5857 return 0;
5858 }
drh319f6772013-05-14 15:31:07 +00005859 return -1;
drh6b7157b2013-05-10 02:00:35 +00005860}
5861
dan374cd782014-04-21 13:21:56 +00005862
5863/*
5864** If the WHERE_GROUPBY flag is set in the mask passed to sqlite3WhereBegin(),
5865** the planner assumes that the specified pOrderBy list is actually a GROUP
5866** BY clause - and so any order that groups rows as required satisfies the
5867** request.
5868**
5869** Normally, in this case it is not possible for the caller to determine
5870** whether or not the rows are really being delivered in sorted order, or
5871** just in some other order that provides the required grouping. However,
5872** if the WHERE_SORTBYGROUP flag is also passed to sqlite3WhereBegin(), then
5873** this function may be called on the returned WhereInfo object. It returns
5874** true if the rows really will be sorted in the specified order, or false
5875** otherwise.
5876**
5877** For example, assuming:
5878**
5879** CREATE INDEX i1 ON t1(x, Y);
5880**
5881** then
5882**
5883** SELECT * FROM t1 GROUP BY x,y ORDER BY x,y; -- IsSorted()==1
5884** SELECT * FROM t1 GROUP BY y,x ORDER BY y,x; -- IsSorted()==0
5885*/
5886int sqlite3WhereIsSorted(WhereInfo *pWInfo){
5887 assert( pWInfo->wctrlFlags & WHERE_GROUPBY );
5888 assert( pWInfo->wctrlFlags & WHERE_SORTBYGROUP );
5889 return pWInfo->sorted;
5890}
5891
drhd15cb172013-05-21 19:23:10 +00005892#ifdef WHERETRACE_ENABLED
5893/* For debugging use only: */
5894static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
5895 static char zName[65];
5896 int i;
5897 for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
5898 if( pLast ) zName[i++] = pLast->cId;
5899 zName[i] = 0;
5900 return zName;
5901}
5902#endif
5903
drh6b7157b2013-05-10 02:00:35 +00005904/*
dan50ae31e2014-08-08 16:52:28 +00005905** Return the cost of sorting nRow rows, assuming that the keys have
5906** nOrderby columns and that the first nSorted columns are already in
5907** order.
5908*/
5909static LogEst whereSortingCost(
5910 WhereInfo *pWInfo,
5911 LogEst nRow,
5912 int nOrderBy,
5913 int nSorted
5914){
5915 /* TUNING: Estimated cost of a full external sort, where N is
5916 ** the number of rows to sort is:
5917 **
5918 ** cost = (3.0 * N * log(N)).
5919 **
5920 ** Or, if the order-by clause has X terms but only the last Y
5921 ** terms are out of order, then block-sorting will reduce the
5922 ** sorting cost to:
5923 **
5924 ** cost = (3.0 * N * log(N)) * (Y/X)
5925 **
5926 ** The (Y/X) term is implemented using stack variable rScale
5927 ** below. */
5928 LogEst rScale, rSortCost;
5929 assert( nOrderBy>0 && 66==sqlite3LogEst(100) );
5930 rScale = sqlite3LogEst((nOrderBy-nSorted)*100/nOrderBy) - 66;
5931 rSortCost = nRow + estLog(nRow) + rScale + 16;
5932
5933 /* TUNING: The cost of implementing DISTINCT using a B-TREE is
5934 ** similar but with a larger constant of proportionality.
5935 ** Multiply by an additional factor of 3.0. */
5936 if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
5937 rSortCost += 16;
5938 }
5939
5940 return rSortCost;
5941}
5942
5943/*
dan51576f42013-07-02 10:06:15 +00005944** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
drha18f3d22013-05-08 03:05:41 +00005945** attempts to find the lowest cost path that visits each WhereLoop
5946** once. This path is then loaded into the pWInfo->a[].pWLoop fields.
5947**
drhc7f0d222013-06-19 03:27:12 +00005948** Assume that the total number of output rows that will need to be sorted
5949** will be nRowEst (in the 10*log2 representation). Or, ignore sorting
5950** costs if nRowEst==0.
5951**
drha18f3d22013-05-08 03:05:41 +00005952** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
5953** error occurs.
5954*/
drhbf539c42013-10-05 18:16:02 +00005955static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
drh783dece2013-06-05 17:53:43 +00005956 int mxChoice; /* Maximum number of simultaneous paths tracked */
drha18f3d22013-05-08 03:05:41 +00005957 int nLoop; /* Number of terms in the join */
drhe1e2e9a2013-06-13 15:16:53 +00005958 Parse *pParse; /* Parsing context */
drha18f3d22013-05-08 03:05:41 +00005959 sqlite3 *db; /* The database connection */
5960 int iLoop; /* Loop counter over the terms of the join */
5961 int ii, jj; /* Loop counters */
drhfde1e6b2013-09-06 17:45:42 +00005962 int mxI = 0; /* Index of next entry to replace */
drhd2de8612014-03-18 18:59:07 +00005963 int nOrderBy; /* Number of ORDER BY clause terms */
drhbf539c42013-10-05 18:16:02 +00005964 LogEst mxCost = 0; /* Maximum cost of a set of paths */
dan50ae31e2014-08-08 16:52:28 +00005965 LogEst mxUnsorted = 0; /* Maximum unsorted cost of a set of path */
drha18f3d22013-05-08 03:05:41 +00005966 int nTo, nFrom; /* Number of valid entries in aTo[] and aFrom[] */
5967 WherePath *aFrom; /* All nFrom paths at the previous level */
5968 WherePath *aTo; /* The nTo best paths at the current level */
5969 WherePath *pFrom; /* An element of aFrom[] that we are working on */
5970 WherePath *pTo; /* An element of aTo[] that we are working on */
5971 WhereLoop *pWLoop; /* One of the WhereLoop objects */
5972 WhereLoop **pX; /* Used to divy up the pSpace memory */
dan50ae31e2014-08-08 16:52:28 +00005973 LogEst *aSortCost = 0; /* Sorting and partial sorting costs */
drha18f3d22013-05-08 03:05:41 +00005974 char *pSpace; /* Temporary memory used by this routine */
dane2c27852014-08-08 17:25:33 +00005975 int nSpace; /* Bytes of space allocated at pSpace */
drha18f3d22013-05-08 03:05:41 +00005976
drhe1e2e9a2013-06-13 15:16:53 +00005977 pParse = pWInfo->pParse;
5978 db = pParse->db;
drha18f3d22013-05-08 03:05:41 +00005979 nLoop = pWInfo->nLevel;
drhe1e2e9a2013-06-13 15:16:53 +00005980 /* TUNING: For simple queries, only the best path is tracked.
5981 ** For 2-way joins, the 5 best paths are followed.
5982 ** For joins of 3 or more tables, track the 10 best paths */
drh2504c6c2014-06-02 11:26:33 +00005983 mxChoice = (nLoop<=1) ? 1 : (nLoop==2 ? 5 : 10);
drha18f3d22013-05-08 03:05:41 +00005984 assert( nLoop<=pWInfo->pTabList->nSrc );
drhddef5dc2014-08-07 16:50:00 +00005985 WHERETRACE(0x002, ("---- begin solver. (nRowEst=%d)\n", nRowEst));
drha18f3d22013-05-08 03:05:41 +00005986
dan50ae31e2014-08-08 16:52:28 +00005987 /* If nRowEst is zero and there is an ORDER BY clause, ignore it. In this
5988 ** case the purpose of this call is to estimate the number of rows returned
5989 ** by the overall query. Once this estimate has been obtained, the caller
5990 ** will invoke this function a second time, passing the estimate as the
5991 ** nRowEst parameter. */
5992 if( pWInfo->pOrderBy==0 || nRowEst==0 ){
5993 nOrderBy = 0;
5994 }else{
5995 nOrderBy = pWInfo->pOrderBy->nExpr;
5996 }
5997
5998 /* Allocate and initialize space for aTo, aFrom and aSortCost[] */
dane2c27852014-08-08 17:25:33 +00005999 nSpace = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
6000 nSpace += sizeof(LogEst) * nOrderBy;
6001 pSpace = sqlite3DbMallocRaw(db, nSpace);
drha18f3d22013-05-08 03:05:41 +00006002 if( pSpace==0 ) return SQLITE_NOMEM;
6003 aTo = (WherePath*)pSpace;
6004 aFrom = aTo+mxChoice;
6005 memset(aFrom, 0, sizeof(aFrom[0]));
6006 pX = (WhereLoop**)(aFrom+mxChoice);
drhe9d935a2013-06-05 16:19:59 +00006007 for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
drha18f3d22013-05-08 03:05:41 +00006008 pFrom->aLoop = pX;
6009 }
dan50ae31e2014-08-08 16:52:28 +00006010 if( nOrderBy ){
6011 /* If there is an ORDER BY clause and it is not being ignored, set up
6012 ** space for the aSortCost[] array. Each element of the aSortCost array
6013 ** is either zero - meaning it has not yet been initialized - or the
6014 ** cost of sorting nRowEst rows of data where the first X terms of
6015 ** the ORDER BY clause are already in order, where X is the array
6016 ** index. */
6017 aSortCost = (LogEst*)pX;
dane2c27852014-08-08 17:25:33 +00006018 memset(aSortCost, 0, sizeof(LogEst) * nOrderBy);
dan50ae31e2014-08-08 16:52:28 +00006019 }
dane2c27852014-08-08 17:25:33 +00006020 assert( aSortCost==0 || &pSpace[nSpace]==(char*)&aSortCost[nOrderBy] );
6021 assert( aSortCost!=0 || &pSpace[nSpace]==(char*)pX );
drha18f3d22013-05-08 03:05:41 +00006022
drhe1e2e9a2013-06-13 15:16:53 +00006023 /* Seed the search with a single WherePath containing zero WhereLoops.
6024 **
danf104abb2015-03-16 20:40:00 +00006025 ** TUNING: Do not let the number of iterations go above 28. If the cost
6026 ** of computing an automatic index is not paid back within the first 28
drhe1e2e9a2013-06-13 15:16:53 +00006027 ** rows, then do not use the automatic index. */
danf104abb2015-03-16 20:40:00 +00006028 aFrom[0].nRow = MIN(pParse->nQueryLoop, 48); assert( 48==sqlite3LogEst(28) );
drha18f3d22013-05-08 03:05:41 +00006029 nFrom = 1;
dan50ae31e2014-08-08 16:52:28 +00006030 assert( aFrom[0].isOrdered==0 );
6031 if( nOrderBy ){
6032 /* If nLoop is zero, then there are no FROM terms in the query. Since
6033 ** in this case the query may return a maximum of one row, the results
6034 ** are already in the requested order. Set isOrdered to nOrderBy to
6035 ** indicate this. Or, if nLoop is greater than zero, set isOrdered to
6036 ** -1, indicating that the result set may or may not be ordered,
6037 ** depending on the loops added to the current plan. */
6038 aFrom[0].isOrdered = nLoop>0 ? -1 : nOrderBy;
drh6b7157b2013-05-10 02:00:35 +00006039 }
6040
6041 /* Compute successively longer WherePaths using the previous generation
6042 ** of WherePaths as the basis for the next. Keep track of the mxChoice
6043 ** best paths at each generation */
drha18f3d22013-05-08 03:05:41 +00006044 for(iLoop=0; iLoop<nLoop; iLoop++){
6045 nTo = 0;
6046 for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
6047 for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
dan50ae31e2014-08-08 16:52:28 +00006048 LogEst nOut; /* Rows visited by (pFrom+pWLoop) */
6049 LogEst rCost; /* Cost of path (pFrom+pWLoop) */
6050 LogEst rUnsorted; /* Unsorted cost of (pFrom+pWLoop) */
6051 i8 isOrdered = pFrom->isOrdered; /* isOrdered for (pFrom+pWLoop) */
6052 Bitmask maskNew; /* Mask of src visited by (..) */
6053 Bitmask revMask = 0; /* Mask of rev-order loops for (..) */
6054
drha18f3d22013-05-08 03:05:41 +00006055 if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
6056 if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
drh6b7157b2013-05-10 02:00:35 +00006057 /* At this point, pWLoop is a candidate to be the next loop.
6058 ** Compute its cost */
dan50ae31e2014-08-08 16:52:28 +00006059 rUnsorted = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
6060 rUnsorted = sqlite3LogEstAdd(rUnsorted, pFrom->rUnsorted);
drhfde1e6b2013-09-06 17:45:42 +00006061 nOut = pFrom->nRow + pWLoop->nOut;
drha18f3d22013-05-08 03:05:41 +00006062 maskNew = pFrom->maskLoop | pWLoop->maskSelf;
drh0401ace2014-03-18 15:30:27 +00006063 if( isOrdered<0 ){
6064 isOrdered = wherePathSatisfiesOrderBy(pWInfo,
drh4f402f22013-06-11 18:59:38 +00006065 pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
drh0401ace2014-03-18 15:30:27 +00006066 iLoop, pWLoop, &revMask);
drh3a5ba8b2013-06-03 15:34:48 +00006067 }else{
6068 revMask = pFrom->revLoop;
drh6b7157b2013-05-10 02:00:35 +00006069 }
dan50ae31e2014-08-08 16:52:28 +00006070 if( isOrdered>=0 && isOrdered<nOrderBy ){
6071 if( aSortCost[isOrdered]==0 ){
6072 aSortCost[isOrdered] = whereSortingCost(
6073 pWInfo, nRowEst, nOrderBy, isOrdered
6074 );
6075 }
6076 rCost = sqlite3LogEstAdd(rUnsorted, aSortCost[isOrdered]);
6077
6078 WHERETRACE(0x002,
6079 ("---- sort cost=%-3d (%d/%d) increases cost %3d to %-3d\n",
6080 aSortCost[isOrdered], (nOrderBy-isOrdered), nOrderBy,
6081 rUnsorted, rCost));
6082 }else{
6083 rCost = rUnsorted;
6084 }
6085
drhddef5dc2014-08-07 16:50:00 +00006086 /* Check to see if pWLoop should be added to the set of
6087 ** mxChoice best-so-far paths.
6088 **
6089 ** First look for an existing path among best-so-far paths
6090 ** that covers the same set of loops and has the same isOrdered
6091 ** setting as the current path candidate.
drhf2a90302014-08-07 20:37:01 +00006092 **
6093 ** The term "((pTo->isOrdered^isOrdered)&0x80)==0" is equivalent
6094 ** to (pTo->isOrdered==(-1))==(isOrdered==(-1))" for the range
6095 ** of legal values for isOrdered, -1..64.
drhddef5dc2014-08-07 16:50:00 +00006096 */
drh6b7157b2013-05-10 02:00:35 +00006097 for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
drhfde1e6b2013-09-06 17:45:42 +00006098 if( pTo->maskLoop==maskNew
drhf2a90302014-08-07 20:37:01 +00006099 && ((pTo->isOrdered^isOrdered)&0x80)==0
drhfde1e6b2013-09-06 17:45:42 +00006100 ){
drh7963b0e2013-06-17 21:37:40 +00006101 testcase( jj==nTo-1 );
drh6b7157b2013-05-10 02:00:35 +00006102 break;
6103 }
6104 }
drha18f3d22013-05-08 03:05:41 +00006105 if( jj>=nTo ){
drhddef5dc2014-08-07 16:50:00 +00006106 /* None of the existing best-so-far paths match the candidate. */
drhddef5dc2014-08-07 16:50:00 +00006107 if( nTo>=mxChoice
dan50ae31e2014-08-08 16:52:28 +00006108 && (rCost>mxCost || (rCost==mxCost && rUnsorted>=mxUnsorted))
drhddef5dc2014-08-07 16:50:00 +00006109 ){
6110 /* The current candidate is no better than any of the mxChoice
6111 ** paths currently in the best-so-far buffer. So discard
6112 ** this candidate as not viable. */
drh989578e2013-10-28 14:34:35 +00006113#ifdef WHERETRACE_ENABLED /* 0x4 */
drhae70cf12013-05-31 15:18:46 +00006114 if( sqlite3WhereTrace&0x4 ){
drhfde1e6b2013-09-06 17:45:42 +00006115 sqlite3DebugPrintf("Skip %s cost=%-3d,%3d order=%c\n",
6116 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
drh0401ace2014-03-18 15:30:27 +00006117 isOrdered>=0 ? isOrdered+'0' : '?');
drhd15cb172013-05-21 19:23:10 +00006118 }
6119#endif
6120 continue;
6121 }
drhddef5dc2014-08-07 16:50:00 +00006122 /* If we reach this points it means that the new candidate path
6123 ** needs to be added to the set of best-so-far paths. */
drha18f3d22013-05-08 03:05:41 +00006124 if( nTo<mxChoice ){
drhd15cb172013-05-21 19:23:10 +00006125 /* Increase the size of the aTo set by one */
drha18f3d22013-05-08 03:05:41 +00006126 jj = nTo++;
6127 }else{
drhd15cb172013-05-21 19:23:10 +00006128 /* New path replaces the prior worst to keep count below mxChoice */
drhfde1e6b2013-09-06 17:45:42 +00006129 jj = mxI;
drha18f3d22013-05-08 03:05:41 +00006130 }
6131 pTo = &aTo[jj];
drh989578e2013-10-28 14:34:35 +00006132#ifdef WHERETRACE_ENABLED /* 0x4 */
drhae70cf12013-05-31 15:18:46 +00006133 if( sqlite3WhereTrace&0x4 ){
drhfde1e6b2013-09-06 17:45:42 +00006134 sqlite3DebugPrintf("New %s cost=%-3d,%3d order=%c\n",
6135 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
drh0401ace2014-03-18 15:30:27 +00006136 isOrdered>=0 ? isOrdered+'0' : '?');
drhd15cb172013-05-21 19:23:10 +00006137 }
6138#endif
drhf204dac2013-05-08 03:22:07 +00006139 }else{
drhddef5dc2014-08-07 16:50:00 +00006140 /* Control reaches here if best-so-far path pTo=aTo[jj] covers the
6141 ** same set of loops and has the sam isOrdered setting as the
6142 ** candidate path. Check to see if the candidate should replace
6143 ** pTo or if the candidate should be skipped */
6144 if( pTo->rCost<rCost || (pTo->rCost==rCost && pTo->nRow<=nOut) ){
drh989578e2013-10-28 14:34:35 +00006145#ifdef WHERETRACE_ENABLED /* 0x4 */
drhae70cf12013-05-31 15:18:46 +00006146 if( sqlite3WhereTrace&0x4 ){
drhd15cb172013-05-21 19:23:10 +00006147 sqlite3DebugPrintf(
drhfde1e6b2013-09-06 17:45:42 +00006148 "Skip %s cost=%-3d,%3d order=%c",
6149 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
drh0401ace2014-03-18 15:30:27 +00006150 isOrdered>=0 ? isOrdered+'0' : '?');
drhfde1e6b2013-09-06 17:45:42 +00006151 sqlite3DebugPrintf(" vs %s cost=%-3d,%d order=%c\n",
6152 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
drh0401ace2014-03-18 15:30:27 +00006153 pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
drhd15cb172013-05-21 19:23:10 +00006154 }
6155#endif
drhddef5dc2014-08-07 16:50:00 +00006156 /* Discard the candidate path from further consideration */
drh7963b0e2013-06-17 21:37:40 +00006157 testcase( pTo->rCost==rCost );
drhd15cb172013-05-21 19:23:10 +00006158 continue;
6159 }
drh7963b0e2013-06-17 21:37:40 +00006160 testcase( pTo->rCost==rCost+1 );
drhddef5dc2014-08-07 16:50:00 +00006161 /* Control reaches here if the candidate path is better than the
6162 ** pTo path. Replace pTo with the candidate. */
drh989578e2013-10-28 14:34:35 +00006163#ifdef WHERETRACE_ENABLED /* 0x4 */
drhae70cf12013-05-31 15:18:46 +00006164 if( sqlite3WhereTrace&0x4 ){
drhd15cb172013-05-21 19:23:10 +00006165 sqlite3DebugPrintf(
drhfde1e6b2013-09-06 17:45:42 +00006166 "Update %s cost=%-3d,%3d order=%c",
6167 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
drh0401ace2014-03-18 15:30:27 +00006168 isOrdered>=0 ? isOrdered+'0' : '?');
drhfde1e6b2013-09-06 17:45:42 +00006169 sqlite3DebugPrintf(" was %s cost=%-3d,%3d order=%c\n",
6170 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
drh0401ace2014-03-18 15:30:27 +00006171 pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
drhd15cb172013-05-21 19:23:10 +00006172 }
6173#endif
drha18f3d22013-05-08 03:05:41 +00006174 }
drh6b7157b2013-05-10 02:00:35 +00006175 /* pWLoop is a winner. Add it to the set of best so far */
drha18f3d22013-05-08 03:05:41 +00006176 pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
drh319f6772013-05-14 15:31:07 +00006177 pTo->revLoop = revMask;
drhfde1e6b2013-09-06 17:45:42 +00006178 pTo->nRow = nOut;
drha18f3d22013-05-08 03:05:41 +00006179 pTo->rCost = rCost;
dan50ae31e2014-08-08 16:52:28 +00006180 pTo->rUnsorted = rUnsorted;
drh6b7157b2013-05-10 02:00:35 +00006181 pTo->isOrdered = isOrdered;
drha18f3d22013-05-08 03:05:41 +00006182 memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
6183 pTo->aLoop[iLoop] = pWLoop;
6184 if( nTo>=mxChoice ){
drhfde1e6b2013-09-06 17:45:42 +00006185 mxI = 0;
drha18f3d22013-05-08 03:05:41 +00006186 mxCost = aTo[0].rCost;
dan50ae31e2014-08-08 16:52:28 +00006187 mxUnsorted = aTo[0].nRow;
drha18f3d22013-05-08 03:05:41 +00006188 for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
dan50ae31e2014-08-08 16:52:28 +00006189 if( pTo->rCost>mxCost
6190 || (pTo->rCost==mxCost && pTo->rUnsorted>mxUnsorted)
6191 ){
drhfde1e6b2013-09-06 17:45:42 +00006192 mxCost = pTo->rCost;
dan50ae31e2014-08-08 16:52:28 +00006193 mxUnsorted = pTo->rUnsorted;
drhfde1e6b2013-09-06 17:45:42 +00006194 mxI = jj;
6195 }
drha18f3d22013-05-08 03:05:41 +00006196 }
6197 }
6198 }
6199 }
6200
drh989578e2013-10-28 14:34:35 +00006201#ifdef WHERETRACE_ENABLED /* >=2 */
drh1b131b72014-10-21 16:01:40 +00006202 if( sqlite3WhereTrace & 0x02 ){
drha50ef112013-05-22 02:06:59 +00006203 sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
drhd15cb172013-05-21 19:23:10 +00006204 for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
drhb8a8e8a2013-06-10 19:12:39 +00006205 sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
drha50ef112013-05-22 02:06:59 +00006206 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
drh0401ace2014-03-18 15:30:27 +00006207 pTo->isOrdered>=0 ? (pTo->isOrdered+'0') : '?');
6208 if( pTo->isOrdered>0 ){
drh88da6442013-05-27 17:59:37 +00006209 sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
6210 }else{
6211 sqlite3DebugPrintf("\n");
6212 }
drhf204dac2013-05-08 03:22:07 +00006213 }
6214 }
6215#endif
6216
drh6b7157b2013-05-10 02:00:35 +00006217 /* Swap the roles of aFrom and aTo for the next generation */
drha18f3d22013-05-08 03:05:41 +00006218 pFrom = aTo;
6219 aTo = aFrom;
6220 aFrom = pFrom;
6221 nFrom = nTo;
6222 }
6223
drh75b93402013-05-31 20:43:57 +00006224 if( nFrom==0 ){
drhe1e2e9a2013-06-13 15:16:53 +00006225 sqlite3ErrorMsg(pParse, "no query solution");
drh75b93402013-05-31 20:43:57 +00006226 sqlite3DbFree(db, pSpace);
6227 return SQLITE_ERROR;
6228 }
drha18f3d22013-05-08 03:05:41 +00006229
drh6b7157b2013-05-10 02:00:35 +00006230 /* Find the lowest cost path. pFrom will be left pointing to that path */
drha18f3d22013-05-08 03:05:41 +00006231 pFrom = aFrom;
6232 for(ii=1; ii<nFrom; ii++){
6233 if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
6234 }
6235 assert( pWInfo->nLevel==nLoop );
drh6b7157b2013-05-10 02:00:35 +00006236 /* Load the lowest cost path into pWInfo */
drha18f3d22013-05-08 03:05:41 +00006237 for(iLoop=0; iLoop<nLoop; iLoop++){
drh7ba39a92013-05-30 17:43:19 +00006238 WhereLevel *pLevel = pWInfo->a + iLoop;
6239 pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
drhe217efc2013-06-12 03:48:41 +00006240 pLevel->iFrom = pWLoop->iTab;
drh7ba39a92013-05-30 17:43:19 +00006241 pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
drha18f3d22013-05-08 03:05:41 +00006242 }
drhfd636c72013-06-21 02:05:06 +00006243 if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0
6244 && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
6245 && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
drh4f402f22013-06-11 18:59:38 +00006246 && nRowEst
6247 ){
6248 Bitmask notUsed;
drh6457a352013-06-21 00:35:37 +00006249 int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom,
drh93ec45d2013-06-17 18:20:48 +00006250 WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
drh0401ace2014-03-18 15:30:27 +00006251 if( rc==pWInfo->pResultSet->nExpr ){
6252 pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
6253 }
drh4f402f22013-06-11 18:59:38 +00006254 }
drh079a3072014-03-19 14:10:55 +00006255 if( pWInfo->pOrderBy ){
drh4f402f22013-06-11 18:59:38 +00006256 if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
drh079a3072014-03-19 14:10:55 +00006257 if( pFrom->isOrdered==pWInfo->pOrderBy->nExpr ){
6258 pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
6259 }
drh4f402f22013-06-11 18:59:38 +00006260 }else{
drhddba0c22014-03-18 20:33:42 +00006261 pWInfo->nOBSat = pFrom->isOrdered;
drhea6c36e2014-03-19 14:30:55 +00006262 if( pWInfo->nOBSat<0 ) pWInfo->nOBSat = 0;
drh4f402f22013-06-11 18:59:38 +00006263 pWInfo->revMask = pFrom->revLoop;
6264 }
dan374cd782014-04-21 13:21:56 +00006265 if( (pWInfo->wctrlFlags & WHERE_SORTBYGROUP)
drh11b04812015-04-12 01:22:04 +00006266 && pWInfo->nOBSat==pWInfo->pOrderBy->nExpr && nLoop>0
dan374cd782014-04-21 13:21:56 +00006267 ){
danb6453202014-10-10 20:52:53 +00006268 Bitmask revMask = 0;
dan374cd782014-04-21 13:21:56 +00006269 int nOrder = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy,
danb6453202014-10-10 20:52:53 +00006270 pFrom, 0, nLoop-1, pFrom->aLoop[nLoop-1], &revMask
dan374cd782014-04-21 13:21:56 +00006271 );
6272 assert( pWInfo->sorted==0 );
danb6453202014-10-10 20:52:53 +00006273 if( nOrder==pWInfo->pOrderBy->nExpr ){
6274 pWInfo->sorted = 1;
6275 pWInfo->revMask = revMask;
6276 }
dan374cd782014-04-21 13:21:56 +00006277 }
drh6b7157b2013-05-10 02:00:35 +00006278 }
dan374cd782014-04-21 13:21:56 +00006279
6280
drha50ef112013-05-22 02:06:59 +00006281 pWInfo->nRowOut = pFrom->nRow;
drha18f3d22013-05-08 03:05:41 +00006282
6283 /* Free temporary memory and return success */
6284 sqlite3DbFree(db, pSpace);
6285 return SQLITE_OK;
6286}
drh75897232000-05-29 14:26:00 +00006287
6288/*
drh60c96cd2013-06-09 17:21:25 +00006289** Most queries use only a single table (they are not joins) and have
6290** simple == constraints against indexed fields. This routine attempts
6291** to plan those simple cases using much less ceremony than the
6292** general-purpose query planner, and thereby yield faster sqlite3_prepare()
6293** times for the common case.
6294**
6295** Return non-zero on success, if this query can be handled by this
6296** no-frills query planner. Return zero if this query needs the
6297** general-purpose query planner.
6298*/
drhb8a8e8a2013-06-10 19:12:39 +00006299static int whereShortCut(WhereLoopBuilder *pBuilder){
drh60c96cd2013-06-09 17:21:25 +00006300 WhereInfo *pWInfo;
6301 struct SrcList_item *pItem;
6302 WhereClause *pWC;
6303 WhereTerm *pTerm;
6304 WhereLoop *pLoop;
6305 int iCur;
drh92a121f2013-06-10 12:15:47 +00006306 int j;
drh60c96cd2013-06-09 17:21:25 +00006307 Table *pTab;
6308 Index *pIdx;
6309
6310 pWInfo = pBuilder->pWInfo;
drh5822d6f2013-06-10 23:30:09 +00006311 if( pWInfo->wctrlFlags & WHERE_FORCE_TABLE ) return 0;
drh60c96cd2013-06-09 17:21:25 +00006312 assert( pWInfo->pTabList->nSrc>=1 );
6313 pItem = pWInfo->pTabList->a;
6314 pTab = pItem->pTab;
6315 if( IsVirtual(pTab) ) return 0;
6316 if( pItem->zIndex ) return 0;
6317 iCur = pItem->iCursor;
6318 pWC = &pWInfo->sWC;
6319 pLoop = pBuilder->pNew;
drh60c96cd2013-06-09 17:21:25 +00006320 pLoop->wsFlags = 0;
drhc8bbce12014-10-21 01:05:09 +00006321 pLoop->nSkip = 0;
drhe8d0c612015-05-14 01:05:25 +00006322 pTerm = findTerm(pWC, iCur, -1, 0, WO_EQ|WO_IS, 0);
drh60c96cd2013-06-09 17:21:25 +00006323 if( pTerm ){
drhe8d0c612015-05-14 01:05:25 +00006324 testcase( pTerm->eOperator & WO_IS );
drh60c96cd2013-06-09 17:21:25 +00006325 pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
6326 pLoop->aLTerm[0] = pTerm;
6327 pLoop->nLTerm = 1;
6328 pLoop->u.btree.nEq = 1;
drhe1e2e9a2013-06-13 15:16:53 +00006329 /* TUNING: Cost of a rowid lookup is 10 */
drhbf539c42013-10-05 18:16:02 +00006330 pLoop->rRun = 33; /* 33==sqlite3LogEst(10) */
drh60c96cd2013-06-09 17:21:25 +00006331 }else{
6332 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
mistachkin4e5bef82015-05-15 20:14:00 +00006333 int opMask;
dancd40abb2013-08-29 10:46:05 +00006334 assert( pLoop->aLTermSpace==pLoop->aLTerm );
drh5f1d1d92014-07-31 22:59:04 +00006335 if( !IsUniqueIndex(pIdx)
dancd40abb2013-08-29 10:46:05 +00006336 || pIdx->pPartIdxWhere!=0
drhbbbdc832013-10-22 18:01:40 +00006337 || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace)
dancd40abb2013-08-29 10:46:05 +00006338 ) continue;
mistachkin4e5bef82015-05-15 20:14:00 +00006339 opMask = pIdx->uniqNotNull ? (WO_EQ|WO_IS) : WO_EQ;
drhbbbdc832013-10-22 18:01:40 +00006340 for(j=0; j<pIdx->nKeyCol; j++){
mistachkin4e5bef82015-05-15 20:14:00 +00006341 pTerm = findTerm(pWC, iCur, pIdx->aiColumn[j], 0, opMask, pIdx);
drh60c96cd2013-06-09 17:21:25 +00006342 if( pTerm==0 ) break;
dan3072b532015-05-15 19:59:23 +00006343 testcase( pTerm->eOperator & WO_IS );
drh60c96cd2013-06-09 17:21:25 +00006344 pLoop->aLTerm[j] = pTerm;
6345 }
drhbbbdc832013-10-22 18:01:40 +00006346 if( j!=pIdx->nKeyCol ) continue;
drh92a121f2013-06-10 12:15:47 +00006347 pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
drhec95c442013-10-23 01:57:32 +00006348 if( pIdx->isCovering || (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){
drh92a121f2013-06-10 12:15:47 +00006349 pLoop->wsFlags |= WHERE_IDX_ONLY;
6350 }
drh60c96cd2013-06-09 17:21:25 +00006351 pLoop->nLTerm = j;
6352 pLoop->u.btree.nEq = j;
6353 pLoop->u.btree.pIndex = pIdx;
drhe1e2e9a2013-06-13 15:16:53 +00006354 /* TUNING: Cost of a unique index lookup is 15 */
drhbf539c42013-10-05 18:16:02 +00006355 pLoop->rRun = 39; /* 39==sqlite3LogEst(15) */
drh60c96cd2013-06-09 17:21:25 +00006356 break;
6357 }
6358 }
drh3b75ffa2013-06-10 14:56:25 +00006359 if( pLoop->wsFlags ){
drhbf539c42013-10-05 18:16:02 +00006360 pLoop->nOut = (LogEst)1;
drh3b75ffa2013-06-10 14:56:25 +00006361 pWInfo->a[0].pWLoop = pLoop;
6362 pLoop->maskSelf = getMask(&pWInfo->sMaskSet, iCur);
6363 pWInfo->a[0].iTabCur = iCur;
6364 pWInfo->nRowOut = 1;
drhddba0c22014-03-18 20:33:42 +00006365 if( pWInfo->pOrderBy ) pWInfo->nOBSat = pWInfo->pOrderBy->nExpr;
drh6457a352013-06-21 00:35:37 +00006366 if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
6367 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
6368 }
drh3b75ffa2013-06-10 14:56:25 +00006369#ifdef SQLITE_DEBUG
6370 pLoop->cId = '0';
6371#endif
6372 return 1;
6373 }
6374 return 0;
drh60c96cd2013-06-09 17:21:25 +00006375}
6376
6377/*
drh75897232000-05-29 14:26:00 +00006378** Generate the beginning of the loop used for WHERE clause processing.
6379** The return value is a pointer to an opaque structure that contains
6380** information needed to terminate the loop. Later, the calling routine
6381** should invoke sqlite3WhereEnd() with the return value of this function
6382** in order to complete the WHERE clause processing.
6383**
6384** If an error occurs, this routine returns NULL.
drhc27a1ce2002-06-14 20:58:45 +00006385**
6386** The basic idea is to do a nested loop, one loop for each table in
6387** the FROM clause of a select. (INSERT and UPDATE statements are the
6388** same as a SELECT with only a single table in the FROM clause.) For
6389** example, if the SQL is this:
6390**
6391** SELECT * FROM t1, t2, t3 WHERE ...;
6392**
6393** Then the code generated is conceptually like the following:
6394**
6395** foreach row1 in t1 do \ Code generated
danielk19774adee202004-05-08 08:23:19 +00006396** foreach row2 in t2 do |-- by sqlite3WhereBegin()
drhc27a1ce2002-06-14 20:58:45 +00006397** foreach row3 in t3 do /
6398** ...
6399** end \ Code generated
danielk19774adee202004-05-08 08:23:19 +00006400** end |-- by sqlite3WhereEnd()
drhc27a1ce2002-06-14 20:58:45 +00006401** end /
6402**
drh29dda4a2005-07-21 18:23:20 +00006403** Note that the loops might not be nested in the order in which they
6404** appear in the FROM clause if a different order is better able to make
drh51147ba2005-07-23 22:59:55 +00006405** use of indices. Note also that when the IN operator appears in
6406** the WHERE clause, it might result in additional nested loops for
6407** scanning through all values on the right-hand side of the IN.
drh29dda4a2005-07-21 18:23:20 +00006408**
drhc27a1ce2002-06-14 20:58:45 +00006409** There are Btree cursors associated with each table. t1 uses cursor
drh6a3ea0e2003-05-02 14:32:12 +00006410** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
6411** And so forth. This routine generates code to open those VDBE cursors
danielk19774adee202004-05-08 08:23:19 +00006412** and sqlite3WhereEnd() generates the code to close them.
drhc27a1ce2002-06-14 20:58:45 +00006413**
drhe6f85e72004-12-25 01:03:13 +00006414** The code that sqlite3WhereBegin() generates leaves the cursors named
6415** in pTabList pointing at their appropriate entries. The [...] code
drhf0863fe2005-06-12 21:35:51 +00006416** can use OP_Column and OP_Rowid opcodes on these cursors to extract
drhe6f85e72004-12-25 01:03:13 +00006417** data from the various tables of the loop.
6418**
drhc27a1ce2002-06-14 20:58:45 +00006419** If the WHERE clause is empty, the foreach loops must each scan their
6420** entire tables. Thus a three-way join is an O(N^3) operation. But if
6421** the tables have indices and there are terms in the WHERE clause that
6422** refer to those indices, a complete table scan can be avoided and the
6423** code will run much faster. Most of the work of this routine is checking
6424** to see if there are indices that can be used to speed up the loop.
6425**
6426** Terms of the WHERE clause are also used to limit which rows actually
6427** make it to the "..." in the middle of the loop. After each "foreach",
6428** terms of the WHERE clause that use only terms in that loop and outer
6429** loops are evaluated and if false a jump is made around all subsequent
6430** inner loops (or around the "..." if the test occurs within the inner-
6431** most loop)
6432**
6433** OUTER JOINS
6434**
6435** An outer join of tables t1 and t2 is conceptally coded as follows:
6436**
6437** foreach row1 in t1 do
6438** flag = 0
6439** foreach row2 in t2 do
6440** start:
6441** ...
6442** flag = 1
6443** end
drhe3184742002-06-19 14:27:05 +00006444** if flag==0 then
6445** move the row2 cursor to a null row
6446** goto start
6447** fi
drhc27a1ce2002-06-14 20:58:45 +00006448** end
6449**
drhe3184742002-06-19 14:27:05 +00006450** ORDER BY CLAUSE PROCESSING
6451**
drh94433422013-07-01 11:05:50 +00006452** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause
6453** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement
drhe3184742002-06-19 14:27:05 +00006454** if there is one. If there is no ORDER BY clause or if this routine
drh46ec5b62012-09-24 15:30:54 +00006455** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
drhfc8d4f92013-11-08 15:19:46 +00006456**
6457** The iIdxCur parameter is the cursor number of an index. If
6458** WHERE_ONETABLE_ONLY is set, iIdxCur is the cursor number of an index
6459** to use for OR clause processing. The WHERE clause should use this
6460** specific cursor. If WHERE_ONEPASS_DESIRED is set, then iIdxCur is
6461** the first cursor in an array of cursors for all indices. iIdxCur should
6462** be used to compute the appropriate cursor depending on which index is
6463** used.
drh75897232000-05-29 14:26:00 +00006464*/
danielk19774adee202004-05-08 08:23:19 +00006465WhereInfo *sqlite3WhereBegin(
danielk1977ed326d72004-11-16 15:50:19 +00006466 Parse *pParse, /* The parser context */
drh6457a352013-06-21 00:35:37 +00006467 SrcList *pTabList, /* FROM clause: A list of all tables to be scanned */
danielk1977ed326d72004-11-16 15:50:19 +00006468 Expr *pWhere, /* The WHERE clause */
drh0401ace2014-03-18 15:30:27 +00006469 ExprList *pOrderBy, /* An ORDER BY (or GROUP BY) clause, or NULL */
drh6457a352013-06-21 00:35:37 +00006470 ExprList *pResultSet, /* Result set of the query */
dan0efb72c2012-08-24 18:44:56 +00006471 u16 wctrlFlags, /* One of the WHERE_* flags defined in sqliteInt.h */
6472 int iIdxCur /* If WHERE_ONETABLE_ONLY is set, index cursor number */
drh75897232000-05-29 14:26:00 +00006473){
danielk1977be229652009-03-20 14:18:51 +00006474 int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
drhc01a3c12009-12-16 22:10:49 +00006475 int nTabList; /* Number of elements in pTabList */
drh75897232000-05-29 14:26:00 +00006476 WhereInfo *pWInfo; /* Will become the return value of this function */
6477 Vdbe *v = pParse->pVdbe; /* The virtual database engine */
drhfe05af82005-07-21 03:14:59 +00006478 Bitmask notReady; /* Cursors that are not yet positioned */
drh1c8148f2013-05-04 20:25:23 +00006479 WhereLoopBuilder sWLB; /* The WhereLoop builder */
drh111a6a72008-12-21 03:51:16 +00006480 WhereMaskSet *pMaskSet; /* The expression mask set */
drh56f1b992012-09-25 14:29:39 +00006481 WhereLevel *pLevel; /* A single level in pWInfo->a[] */
drhfd636c72013-06-21 02:05:06 +00006482 WhereLoop *pLoop; /* Pointer to a single WhereLoop object */
drh9cd1c992012-09-25 20:43:35 +00006483 int ii; /* Loop counter */
drh17435752007-08-16 04:30:38 +00006484 sqlite3 *db; /* Database connection */
drh5346e952013-05-08 14:14:26 +00006485 int rc; /* Return code */
drh75897232000-05-29 14:26:00 +00006486
drh56f1b992012-09-25 14:29:39 +00006487
6488 /* Variable initialization */
drhfd636c72013-06-21 02:05:06 +00006489 db = pParse->db;
drh1c8148f2013-05-04 20:25:23 +00006490 memset(&sWLB, 0, sizeof(sWLB));
drh0401ace2014-03-18 15:30:27 +00006491
6492 /* An ORDER/GROUP BY clause of more than 63 terms cannot be optimized */
6493 testcase( pOrderBy && pOrderBy->nExpr==BMS-1 );
6494 if( pOrderBy && pOrderBy->nExpr>=BMS ) pOrderBy = 0;
drh1c8148f2013-05-04 20:25:23 +00006495 sWLB.pOrderBy = pOrderBy;
drh56f1b992012-09-25 14:29:39 +00006496
drhfd636c72013-06-21 02:05:06 +00006497 /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
6498 ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
6499 if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
6500 wctrlFlags &= ~WHERE_WANT_DISTINCT;
6501 }
6502
drh29dda4a2005-07-21 18:23:20 +00006503 /* The number of tables in the FROM clause is limited by the number of
drh1398ad32005-01-19 23:24:50 +00006504 ** bits in a Bitmask
6505 */
drh67ae0cb2010-04-08 14:38:51 +00006506 testcase( pTabList->nSrc==BMS );
drh29dda4a2005-07-21 18:23:20 +00006507 if( pTabList->nSrc>BMS ){
6508 sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
drh1398ad32005-01-19 23:24:50 +00006509 return 0;
6510 }
6511
drhc01a3c12009-12-16 22:10:49 +00006512 /* This function normally generates a nested loop for all tables in
6513 ** pTabList. But if the WHERE_ONETABLE_ONLY flag is set, then we should
6514 ** only generate code for the first table in pTabList and assume that
6515 ** any cursors associated with subsequent tables are uninitialized.
6516 */
6517 nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
6518
drh75897232000-05-29 14:26:00 +00006519 /* Allocate and initialize the WhereInfo structure that will become the
danielk1977be229652009-03-20 14:18:51 +00006520 ** return value. A single allocation is used to store the WhereInfo
6521 ** struct, the contents of WhereInfo.a[], the WhereClause structure
6522 ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
6523 ** field (type Bitmask) it must be aligned on an 8-byte boundary on
6524 ** some architectures. Hence the ROUND8() below.
drh75897232000-05-29 14:26:00 +00006525 */
drhc01a3c12009-12-16 22:10:49 +00006526 nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
drh60c96cd2013-06-09 17:21:25 +00006527 pWInfo = sqlite3DbMallocZero(db, nByteWInfo + sizeof(WhereLoop));
drh17435752007-08-16 04:30:38 +00006528 if( db->mallocFailed ){
drh8b307fb2010-04-06 15:57:05 +00006529 sqlite3DbFree(db, pWInfo);
6530 pWInfo = 0;
danielk197785574e32008-10-06 05:32:18 +00006531 goto whereBeginError;
drh75897232000-05-29 14:26:00 +00006532 }
drhfc8d4f92013-11-08 15:19:46 +00006533 pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1;
drhc01a3c12009-12-16 22:10:49 +00006534 pWInfo->nLevel = nTabList;
drh75897232000-05-29 14:26:00 +00006535 pWInfo->pParse = pParse;
6536 pWInfo->pTabList = pTabList;
drh6b7157b2013-05-10 02:00:35 +00006537 pWInfo->pOrderBy = pOrderBy;
drh6457a352013-06-21 00:35:37 +00006538 pWInfo->pResultSet = pResultSet;
drha22a75e2014-03-21 18:16:23 +00006539 pWInfo->iBreak = pWInfo->iContinue = sqlite3VdbeMakeLabel(v);
drh6df2acd2008-12-28 16:55:25 +00006540 pWInfo->wctrlFlags = wctrlFlags;
drh8b307fb2010-04-06 15:57:05 +00006541 pWInfo->savedNQueryLoop = pParse->nQueryLoop;
drh70d18342013-06-06 19:16:33 +00006542 pMaskSet = &pWInfo->sMaskSet;
drh1c8148f2013-05-04 20:25:23 +00006543 sWLB.pWInfo = pWInfo;
drh70d18342013-06-06 19:16:33 +00006544 sWLB.pWC = &pWInfo->sWC;
drh1ac87e12013-07-18 14:50:56 +00006545 sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);
6546 assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) );
drh60c96cd2013-06-09 17:21:25 +00006547 whereLoopInit(sWLB.pNew);
drhb8a8e8a2013-06-10 19:12:39 +00006548#ifdef SQLITE_DEBUG
6549 sWLB.pNew->cId = '*';
6550#endif
drh08192d52002-04-30 19:20:28 +00006551
drh111a6a72008-12-21 03:51:16 +00006552 /* Split the WHERE clause into separate subexpressions where each
6553 ** subexpression is separated by an AND operator.
6554 */
6555 initMaskSet(pMaskSet);
drh70d18342013-06-06 19:16:33 +00006556 whereClauseInit(&pWInfo->sWC, pWInfo);
drh39759742013-08-02 23:40:45 +00006557 whereSplit(&pWInfo->sWC, pWhere, TK_AND);
drh111a6a72008-12-21 03:51:16 +00006558
drh08192d52002-04-30 19:20:28 +00006559 /* Special case: a WHERE clause that is constant. Evaluate the
6560 ** expression and either jump over all of the code or fall thru.
6561 */
drh759e8582014-01-02 21:05:10 +00006562 for(ii=0; ii<sWLB.pWC->nTerm; ii++){
6563 if( nTabList==0 || sqlite3ExprIsConstantNotJoin(sWLB.pWC->a[ii].pExpr) ){
6564 sqlite3ExprIfFalse(pParse, sWLB.pWC->a[ii].pExpr, pWInfo->iBreak,
6565 SQLITE_JUMPIFNULL);
6566 sWLB.pWC->a[ii].wtFlags |= TERM_CODED;
6567 }
drh08192d52002-04-30 19:20:28 +00006568 }
drh75897232000-05-29 14:26:00 +00006569
drh4fe425a2013-06-12 17:08:06 +00006570 /* Special case: No FROM clause
6571 */
6572 if( nTabList==0 ){
drhddba0c22014-03-18 20:33:42 +00006573 if( pOrderBy ) pWInfo->nOBSat = pOrderBy->nExpr;
drh6457a352013-06-21 00:35:37 +00006574 if( wctrlFlags & WHERE_WANT_DISTINCT ){
6575 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
6576 }
drh4fe425a2013-06-12 17:08:06 +00006577 }
6578
drh42165be2008-03-26 14:56:34 +00006579 /* Assign a bit from the bitmask to every term in the FROM clause.
6580 **
6581 ** When assigning bitmask values to FROM clause cursors, it must be
6582 ** the case that if X is the bitmask for the N-th FROM clause term then
6583 ** the bitmask for all FROM clause terms to the left of the N-th term
6584 ** is (X-1). An expression from the ON clause of a LEFT JOIN can use
6585 ** its Expr.iRightJoinTable value to find the bitmask of the right table
6586 ** of the join. Subtracting one from the right table bitmask gives a
6587 ** bitmask for all tables to the left of the join. Knowing the bitmask
6588 ** for all tables to the left of a left join is important. Ticket #3015.
danielk1977e672c8e2009-05-22 15:43:26 +00006589 **
drhc01a3c12009-12-16 22:10:49 +00006590 ** Note that bitmasks are created for all pTabList->nSrc tables in
6591 ** pTabList, not just the first nTabList tables. nTabList is normally
6592 ** equal to pTabList->nSrc but might be shortened to 1 if the
6593 ** WHERE_ONETABLE_ONLY flag is set.
drh42165be2008-03-26 14:56:34 +00006594 */
drh9cd1c992012-09-25 20:43:35 +00006595 for(ii=0; ii<pTabList->nSrc; ii++){
6596 createMask(pMaskSet, pTabList->a[ii].iCursor);
drh42165be2008-03-26 14:56:34 +00006597 }
6598#ifndef NDEBUG
6599 {
6600 Bitmask toTheLeft = 0;
drh9cd1c992012-09-25 20:43:35 +00006601 for(ii=0; ii<pTabList->nSrc; ii++){
6602 Bitmask m = getMask(pMaskSet, pTabList->a[ii].iCursor);
drh42165be2008-03-26 14:56:34 +00006603 assert( (m-1)==toTheLeft );
6604 toTheLeft |= m;
6605 }
6606 }
6607#endif
6608
drh29dda4a2005-07-21 18:23:20 +00006609 /* Analyze all of the subexpressions. Note that exprAnalyze() might
6610 ** add new virtual terms onto the end of the WHERE clause. We do not
6611 ** want to analyze these virtual terms, so start analyzing at the end
drhb6fb62d2005-09-20 08:47:20 +00006612 ** and work forward so that the added virtual terms are never processed.
drh75897232000-05-29 14:26:00 +00006613 */
drh70d18342013-06-06 19:16:33 +00006614 exprAnalyzeAll(pTabList, &pWInfo->sWC);
drh17435752007-08-16 04:30:38 +00006615 if( db->mallocFailed ){
danielk197785574e32008-10-06 05:32:18 +00006616 goto whereBeginError;
drh0bbaa1b2005-08-19 19:14:12 +00006617 }
drh75897232000-05-29 14:26:00 +00006618
drh6457a352013-06-21 00:35:37 +00006619 if( wctrlFlags & WHERE_WANT_DISTINCT ){
6620 if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){
6621 /* The DISTINCT marking is pointless. Ignore it. */
drh4f402f22013-06-11 18:59:38 +00006622 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
6623 }else if( pOrderBy==0 ){
drh6457a352013-06-21 00:35:37 +00006624 /* Try to ORDER BY the result set to make distinct processing easier */
drh4f402f22013-06-11 18:59:38 +00006625 pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
drh6457a352013-06-21 00:35:37 +00006626 pWInfo->pOrderBy = pResultSet;
drh4f402f22013-06-11 18:59:38 +00006627 }
dan38cc40c2011-06-30 20:17:15 +00006628 }
6629
drhf1b5f5b2013-05-02 00:15:01 +00006630 /* Construct the WhereLoop objects */
drh3b48e8c2013-06-12 20:18:16 +00006631 WHERETRACE(0xffff,("*** Optimizer Start ***\n"));
drhc90713d2014-09-30 13:46:49 +00006632#if defined(WHERETRACE_ENABLED)
6633 /* Display all terms of the WHERE clause */
6634 if( sqlite3WhereTrace & 0x100 ){
6635 int i;
6636 for(i=0; i<sWLB.pWC->nTerm; i++){
6637 whereTermPrint(&sWLB.pWC->a[i], i);
6638 }
6639 }
6640#endif
6641
drhb8a8e8a2013-06-10 19:12:39 +00006642 if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
drh60c96cd2013-06-09 17:21:25 +00006643 rc = whereLoopAddAll(&sWLB);
6644 if( rc ) goto whereBeginError;
6645
6646 /* Display all of the WhereLoop objects if wheretrace is enabled */
drh989578e2013-10-28 14:34:35 +00006647#ifdef WHERETRACE_ENABLED /* !=0 */
drh60c96cd2013-06-09 17:21:25 +00006648 if( sqlite3WhereTrace ){
6649 WhereLoop *p;
drhfd636c72013-06-21 02:05:06 +00006650 int i;
drh60c96cd2013-06-09 17:21:25 +00006651 static char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
6652 "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
drhfd636c72013-06-21 02:05:06 +00006653 for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
6654 p->cId = zLabel[i%sizeof(zLabel)];
drhc1ba2e72013-10-28 19:03:21 +00006655 whereLoopPrint(p, sWLB.pWC);
drh60c96cd2013-06-09 17:21:25 +00006656 }
6657 }
6658#endif
6659
drh4f402f22013-06-11 18:59:38 +00006660 wherePathSolver(pWInfo, 0);
drh60c96cd2013-06-09 17:21:25 +00006661 if( db->mallocFailed ) goto whereBeginError;
6662 if( pWInfo->pOrderBy ){
drhc7f0d222013-06-19 03:27:12 +00006663 wherePathSolver(pWInfo, pWInfo->nRowOut+1);
drh60c96cd2013-06-09 17:21:25 +00006664 if( db->mallocFailed ) goto whereBeginError;
drha18f3d22013-05-08 03:05:41 +00006665 }
6666 }
drh60c96cd2013-06-09 17:21:25 +00006667 if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
drhd84ce352013-06-04 18:27:41 +00006668 pWInfo->revMask = (Bitmask)(-1);
drha50ef112013-05-22 02:06:59 +00006669 }
drh81186b42013-06-18 01:52:41 +00006670 if( pParse->nErr || NEVER(db->mallocFailed) ){
drh75b93402013-05-31 20:43:57 +00006671 goto whereBeginError;
6672 }
drh989578e2013-10-28 14:34:35 +00006673#ifdef WHERETRACE_ENABLED /* !=0 */
drha18f3d22013-05-08 03:05:41 +00006674 if( sqlite3WhereTrace ){
drh4f402f22013-06-11 18:59:38 +00006675 sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
drhddba0c22014-03-18 20:33:42 +00006676 if( pWInfo->nOBSat>0 ){
6677 sqlite3DebugPrintf(" ORDERBY=%d,0x%llx", pWInfo->nOBSat, pWInfo->revMask);
drh319f6772013-05-14 15:31:07 +00006678 }
drh4f402f22013-06-11 18:59:38 +00006679 switch( pWInfo->eDistinct ){
6680 case WHERE_DISTINCT_UNIQUE: {
6681 sqlite3DebugPrintf(" DISTINCT=unique");
6682 break;
6683 }
6684 case WHERE_DISTINCT_ORDERED: {
6685 sqlite3DebugPrintf(" DISTINCT=ordered");
6686 break;
6687 }
6688 case WHERE_DISTINCT_UNORDERED: {
6689 sqlite3DebugPrintf(" DISTINCT=unordered");
6690 break;
6691 }
6692 }
6693 sqlite3DebugPrintf("\n");
drhfd636c72013-06-21 02:05:06 +00006694 for(ii=0; ii<pWInfo->nLevel; ii++){
drhc1ba2e72013-10-28 19:03:21 +00006695 whereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC);
drhf1b5f5b2013-05-02 00:15:01 +00006696 }
6697 }
6698#endif
drhfd636c72013-06-21 02:05:06 +00006699 /* Attempt to omit tables from the join that do not effect the result */
drh1031bd92013-06-22 15:44:26 +00006700 if( pWInfo->nLevel>=2
6701 && pResultSet!=0
6702 && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
6703 ){
drhfd636c72013-06-21 02:05:06 +00006704 Bitmask tabUsed = exprListTableUsage(pMaskSet, pResultSet);
drh67a5ec72013-09-03 14:03:47 +00006705 if( sWLB.pOrderBy ) tabUsed |= exprListTableUsage(pMaskSet, sWLB.pOrderBy);
drhfd636c72013-06-21 02:05:06 +00006706 while( pWInfo->nLevel>=2 ){
drh9d5a5792013-06-28 13:43:33 +00006707 WhereTerm *pTerm, *pEnd;
drhfd636c72013-06-21 02:05:06 +00006708 pLoop = pWInfo->a[pWInfo->nLevel-1].pWLoop;
drhbc71b1d2013-06-21 02:15:48 +00006709 if( (pWInfo->pTabList->a[pLoop->iTab].jointype & JT_LEFT)==0 ) break;
6710 if( (wctrlFlags & WHERE_WANT_DISTINCT)==0
6711 && (pLoop->wsFlags & WHERE_ONEROW)==0
drhfd636c72013-06-21 02:05:06 +00006712 ){
drhfd636c72013-06-21 02:05:06 +00006713 break;
6714 }
drhbc71b1d2013-06-21 02:15:48 +00006715 if( (tabUsed & pLoop->maskSelf)!=0 ) break;
drh9d5a5792013-06-28 13:43:33 +00006716 pEnd = sWLB.pWC->a + sWLB.pWC->nTerm;
6717 for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
6718 if( (pTerm->prereqAll & pLoop->maskSelf)!=0
6719 && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
6720 ){
6721 break;
6722 }
6723 }
6724 if( pTerm<pEnd ) break;
drhbc71b1d2013-06-21 02:15:48 +00006725 WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId));
6726 pWInfo->nLevel--;
6727 nTabList--;
drhfd636c72013-06-21 02:05:06 +00006728 }
6729 }
drh3b48e8c2013-06-12 20:18:16 +00006730 WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
drh8e23daf2013-06-11 13:30:04 +00006731 pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
drhf1b5f5b2013-05-02 00:15:01 +00006732
drh08c88eb2008-04-10 13:33:18 +00006733 /* If the caller is an UPDATE or DELETE statement that is requesting
6734 ** to use a one-pass algorithm, determine if this is appropriate.
drh24b7fe92013-09-30 19:33:06 +00006735 ** The one-pass algorithm only works if the WHERE clause constrains
drh08c88eb2008-04-10 13:33:18 +00006736 ** the statement to update a single row.
6737 */
drh165be382008-12-05 02:36:33 +00006738 assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
drh3b48e8c2013-06-12 20:18:16 +00006739 if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
6740 && (pWInfo->a[0].pWLoop->wsFlags & WHERE_ONEROW)!=0 ){
drh08c88eb2008-04-10 13:33:18 +00006741 pWInfo->okOnePass = 1;
drh702ba9f2013-11-07 21:25:13 +00006742 if( HasRowid(pTabList->a[0].pTab) ){
6743 pWInfo->a[0].pWLoop->wsFlags &= ~WHERE_IDX_ONLY;
6744 }
drh08c88eb2008-04-10 13:33:18 +00006745 }
drheb04de32013-05-10 15:16:30 +00006746
drh9012bcb2004-12-19 00:11:35 +00006747 /* Open all tables in the pTabList and any indices selected for
6748 ** searching those tables.
6749 */
drh8b307fb2010-04-06 15:57:05 +00006750 notReady = ~(Bitmask)0;
drh9cd1c992012-09-25 20:43:35 +00006751 for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
danielk1977da184232006-01-05 11:34:32 +00006752 Table *pTab; /* Table to open */
danielk1977da184232006-01-05 11:34:32 +00006753 int iDb; /* Index of database containing table/index */
drh56f1b992012-09-25 14:29:39 +00006754 struct SrcList_item *pTabItem;
drh9012bcb2004-12-19 00:11:35 +00006755
drh29dda4a2005-07-21 18:23:20 +00006756 pTabItem = &pTabList->a[pLevel->iFrom];
drh9012bcb2004-12-19 00:11:35 +00006757 pTab = pTabItem->pTab;
danielk1977595a5232009-07-24 17:58:53 +00006758 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
drh7ba39a92013-05-30 17:43:19 +00006759 pLoop = pLevel->pWLoop;
drh424aab82010-04-06 18:28:20 +00006760 if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
drh75bb9f52010-04-06 18:51:42 +00006761 /* Do nothing */
6762 }else
drh9eff6162006-06-12 21:59:13 +00006763#ifndef SQLITE_OMIT_VIRTUALTABLE
drh7ba39a92013-05-30 17:43:19 +00006764 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
danielk1977595a5232009-07-24 17:58:53 +00006765 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
danielk197793626f42006-06-20 13:07:27 +00006766 int iCur = pTabItem->iCursor;
danielk1977595a5232009-07-24 17:58:53 +00006767 sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
drhfc5e5462012-12-03 17:04:40 +00006768 }else if( IsVirtual(pTab) ){
6769 /* noop */
drh9eff6162006-06-12 21:59:13 +00006770 }else
6771#endif
drh7ba39a92013-05-30 17:43:19 +00006772 if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
drh9ef61f42011-10-07 14:40:59 +00006773 && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){
drhfc8d4f92013-11-08 15:19:46 +00006774 int op = OP_OpenRead;
6775 if( pWInfo->okOnePass ){
6776 op = OP_OpenWrite;
6777 pWInfo->aiCurOnePass[0] = pTabItem->iCursor;
6778 };
drh08c88eb2008-04-10 13:33:18 +00006779 sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
drhfc8d4f92013-11-08 15:19:46 +00006780 assert( pTabItem->iCursor==pLevel->iTabCur );
drh7963b0e2013-06-17 21:37:40 +00006781 testcase( !pWInfo->okOnePass && pTab->nCol==BMS-1 );
6782 testcase( !pWInfo->okOnePass && pTab->nCol==BMS );
drhdd9930e2013-10-23 23:37:02 +00006783 if( !pWInfo->okOnePass && pTab->nCol<BMS && HasRowid(pTab) ){
danielk19779792eef2006-01-13 15:58:43 +00006784 Bitmask b = pTabItem->colUsed;
6785 int n = 0;
drh74161702006-02-24 02:53:49 +00006786 for(; b; b=b>>1, n++){}
drh8cff69d2009-11-12 19:59:44 +00006787 sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
6788 SQLITE_INT_TO_PTR(n), P4_INT32);
danielk19779792eef2006-01-13 15:58:43 +00006789 assert( n<=pTab->nCol );
6790 }
danielk1977c00da102006-01-07 13:21:04 +00006791 }else{
6792 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
drh9012bcb2004-12-19 00:11:35 +00006793 }
drh7e47cb82013-05-31 17:55:27 +00006794 if( pLoop->wsFlags & WHERE_INDEXED ){
drh7ba39a92013-05-30 17:43:19 +00006795 Index *pIx = pLoop->u.btree.pIndex;
drhfc8d4f92013-11-08 15:19:46 +00006796 int iIndexCur;
6797 int op = OP_OpenRead;
drh4308e342013-11-11 16:55:52 +00006798 /* iIdxCur is always set if to a positive value if ONEPASS is possible */
6799 assert( iIdxCur!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 );
drh48dd1d82014-05-27 18:18:58 +00006800 if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIx)
drha3bc66a2014-05-27 17:57:32 +00006801 && (wctrlFlags & WHERE_ONETABLE_ONLY)!=0
6802 ){
6803 /* This is one term of an OR-optimization using the PRIMARY KEY of a
6804 ** WITHOUT ROWID table. No need for a separate index */
6805 iIndexCur = pLevel->iTabCur;
6806 op = 0;
6807 }else if( pWInfo->okOnePass ){
drhfc8d4f92013-11-08 15:19:46 +00006808 Index *pJ = pTabItem->pTab->pIndex;
6809 iIndexCur = iIdxCur;
6810 assert( wctrlFlags & WHERE_ONEPASS_DESIRED );
6811 while( ALWAYS(pJ) && pJ!=pIx ){
6812 iIndexCur++;
6813 pJ = pJ->pNext;
6814 }
6815 op = OP_OpenWrite;
6816 pWInfo->aiCurOnePass[1] = iIndexCur;
6817 }else if( iIdxCur && (wctrlFlags & WHERE_ONETABLE_ONLY)!=0 ){
6818 iIndexCur = iIdxCur;
drh35263192014-07-22 20:02:19 +00006819 if( wctrlFlags & WHERE_REOPEN_IDX ) op = OP_ReopenIdx;
drhfc8d4f92013-11-08 15:19:46 +00006820 }else{
6821 iIndexCur = pParse->nTab++;
6822 }
6823 pLevel->iIdxCur = iIndexCur;
danielk1977da184232006-01-05 11:34:32 +00006824 assert( pIx->pSchema==pTab->pSchema );
drhb0367fb2012-08-25 02:11:13 +00006825 assert( iIndexCur>=0 );
drha3bc66a2014-05-27 17:57:32 +00006826 if( op ){
6827 sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb);
6828 sqlite3VdbeSetP4KeyInfo(pParse, pIx);
drhe0997b32015-03-20 14:57:50 +00006829 if( (pLoop->wsFlags & WHERE_CONSTRAINT)!=0
6830 && (pLoop->wsFlags & (WHERE_COLUMN_RANGE|WHERE_SKIPSCAN))==0
6831 && (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0
6832 ){
6833 sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ); /* Hint to COMDB2 */
6834 }
drha3bc66a2014-05-27 17:57:32 +00006835 VdbeComment((v, "%s", pIx->zName));
6836 }
drh9012bcb2004-12-19 00:11:35 +00006837 }
drhaceb31b2014-02-08 01:40:27 +00006838 if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb);
drh70d18342013-06-06 19:16:33 +00006839 notReady &= ~getMask(&pWInfo->sMaskSet, pTabItem->iCursor);
drh9012bcb2004-12-19 00:11:35 +00006840 }
6841 pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
drha21a64d2010-04-06 22:33:55 +00006842 if( db->mallocFailed ) goto whereBeginError;
drh9012bcb2004-12-19 00:11:35 +00006843
drh29dda4a2005-07-21 18:23:20 +00006844 /* Generate the code to do the search. Each iteration of the for
6845 ** loop below generates code for a single nested loop of the VM
6846 ** program.
drh75897232000-05-29 14:26:00 +00006847 */
drhfe05af82005-07-21 03:14:59 +00006848 notReady = ~(Bitmask)0;
drh9cd1c992012-09-25 20:43:35 +00006849 for(ii=0; ii<nTabList; ii++){
dan6f9702e2014-11-01 20:38:06 +00006850 int addrExplain;
6851 int wsFlags;
drh9cd1c992012-09-25 20:43:35 +00006852 pLevel = &pWInfo->a[ii];
dan6f9702e2014-11-01 20:38:06 +00006853 wsFlags = pLevel->pWLoop->wsFlags;
drhcc04afd2013-08-22 02:56:28 +00006854#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
6855 if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){
6856 constructAutomaticIndex(pParse, &pWInfo->sWC,
6857 &pTabList->a[pLevel->iFrom], notReady, pLevel);
6858 if( db->mallocFailed ) goto whereBeginError;
6859 }
6860#endif
dan6f9702e2014-11-01 20:38:06 +00006861 addrExplain = explainOneScan(
6862 pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags
6863 );
drhcc04afd2013-08-22 02:56:28 +00006864 pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
drh70d18342013-06-06 19:16:33 +00006865 notReady = codeOneLoopStart(pWInfo, ii, notReady);
dan4a07e3d2010-11-09 14:48:59 +00006866 pWInfo->iContinue = pLevel->addrCont;
dan6f9702e2014-11-01 20:38:06 +00006867 if( (wsFlags&WHERE_MULTI_OR)==0 && (wctrlFlags&WHERE_ONETABLE_ONLY)==0 ){
6868 addScanStatus(v, pTabList, pLevel, addrExplain);
6869 }
drh75897232000-05-29 14:26:00 +00006870 }
drh7ec764a2005-07-21 03:48:20 +00006871
drh6fa978d2013-05-30 19:29:19 +00006872 /* Done. */
drh6bc69a22013-11-19 12:33:23 +00006873 VdbeModuleComment((v, "Begin WHERE-core"));
drh75897232000-05-29 14:26:00 +00006874 return pWInfo;
drhe23399f2005-07-22 00:31:39 +00006875
6876 /* Jump here if malloc fails */
danielk197785574e32008-10-06 05:32:18 +00006877whereBeginError:
drh8b307fb2010-04-06 15:57:05 +00006878 if( pWInfo ){
6879 pParse->nQueryLoop = pWInfo->savedNQueryLoop;
6880 whereInfoFree(db, pWInfo);
6881 }
drhe23399f2005-07-22 00:31:39 +00006882 return 0;
drh75897232000-05-29 14:26:00 +00006883}
6884
6885/*
drhc27a1ce2002-06-14 20:58:45 +00006886** Generate the end of the WHERE loop. See comments on
danielk19774adee202004-05-08 08:23:19 +00006887** sqlite3WhereBegin() for additional information.
drh75897232000-05-29 14:26:00 +00006888*/
danielk19774adee202004-05-08 08:23:19 +00006889void sqlite3WhereEnd(WhereInfo *pWInfo){
drh633e6d52008-07-28 19:34:53 +00006890 Parse *pParse = pWInfo->pParse;
6891 Vdbe *v = pParse->pVdbe;
drh19a775c2000-06-05 18:54:46 +00006892 int i;
drh6b563442001-11-07 16:48:26 +00006893 WhereLevel *pLevel;
drh7ba39a92013-05-30 17:43:19 +00006894 WhereLoop *pLoop;
drhad3cab52002-05-24 02:04:32 +00006895 SrcList *pTabList = pWInfo->pTabList;
drh633e6d52008-07-28 19:34:53 +00006896 sqlite3 *db = pParse->db;
drh19a775c2000-06-05 18:54:46 +00006897
drh9012bcb2004-12-19 00:11:35 +00006898 /* Generate loop termination code.
6899 */
drh6bc69a22013-11-19 12:33:23 +00006900 VdbeModuleComment((v, "End WHERE-core"));
drhceea3322009-04-23 13:22:42 +00006901 sqlite3ExprCacheClear(pParse);
drhc01a3c12009-12-16 22:10:49 +00006902 for(i=pWInfo->nLevel-1; i>=0; i--){
drhcd8629e2013-11-13 12:27:25 +00006903 int addr;
drh6b563442001-11-07 16:48:26 +00006904 pLevel = &pWInfo->a[i];
drh7ba39a92013-05-30 17:43:19 +00006905 pLoop = pLevel->pWLoop;
drhb3190c12008-12-08 21:37:14 +00006906 sqlite3VdbeResolveLabel(v, pLevel->addrCont);
drh6b563442001-11-07 16:48:26 +00006907 if( pLevel->op!=OP_Noop ){
drhe39a7322014-02-03 14:04:11 +00006908 sqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3);
drhd1d38482008-10-07 23:46:38 +00006909 sqlite3VdbeChangeP5(v, pLevel->p5);
drh688852a2014-02-17 22:40:43 +00006910 VdbeCoverage(v);
drh7d176102014-02-18 03:07:12 +00006911 VdbeCoverageIf(v, pLevel->op==OP_Next);
6912 VdbeCoverageIf(v, pLevel->op==OP_Prev);
6913 VdbeCoverageIf(v, pLevel->op==OP_VNext);
drh19a775c2000-06-05 18:54:46 +00006914 }
drh7ba39a92013-05-30 17:43:19 +00006915 if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
drh72e8fa42007-03-28 14:30:06 +00006916 struct InLoop *pIn;
drhe23399f2005-07-22 00:31:39 +00006917 int j;
drhb3190c12008-12-08 21:37:14 +00006918 sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
drh111a6a72008-12-21 03:51:16 +00006919 for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
drhb3190c12008-12-08 21:37:14 +00006920 sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
drh2d96b932013-02-08 18:48:23 +00006921 sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
drh688852a2014-02-17 22:40:43 +00006922 VdbeCoverage(v);
drh7d176102014-02-18 03:07:12 +00006923 VdbeCoverageIf(v, pIn->eEndLoopOp==OP_PrevIfOpen);
6924 VdbeCoverageIf(v, pIn->eEndLoopOp==OP_NextIfOpen);
drhb3190c12008-12-08 21:37:14 +00006925 sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
drhe23399f2005-07-22 00:31:39 +00006926 }
drhd99f7062002-06-08 23:25:08 +00006927 }
drhb3190c12008-12-08 21:37:14 +00006928 sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
drhcd8629e2013-11-13 12:27:25 +00006929 if( pLevel->addrSkip ){
drhcd8629e2013-11-13 12:27:25 +00006930 sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrSkip);
drhe084f402013-11-13 17:24:38 +00006931 VdbeComment((v, "next skip-scan on %s", pLoop->u.btree.pIndex->zName));
drh2e5ef4e2013-11-13 16:58:54 +00006932 sqlite3VdbeJumpHere(v, pLevel->addrSkip);
6933 sqlite3VdbeJumpHere(v, pLevel->addrSkip-2);
drhcd8629e2013-11-13 12:27:25 +00006934 }
drhf07cf6e2015-03-06 16:45:16 +00006935 if( pLevel->addrLikeRep ){
drhb7c60ba2015-03-07 02:51:59 +00006936 int op;
6937 if( sqlite3VdbeGetOp(v, pLevel->addrLikeRep-1)->p1 ){
6938 op = OP_DecrJumpZero;
6939 }else{
6940 op = OP_JumpZeroIncr;
6941 }
6942 sqlite3VdbeAddOp2(v, op, pLevel->iLikeRepCntr, pLevel->addrLikeRep);
drhf07cf6e2015-03-06 16:45:16 +00006943 VdbeCoverage(v);
drhf07cf6e2015-03-06 16:45:16 +00006944 }
drhad2d8302002-05-24 20:31:36 +00006945 if( pLevel->iLeftJoin ){
drh688852a2014-02-17 22:40:43 +00006946 addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v);
drh7ba39a92013-05-30 17:43:19 +00006947 assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
6948 || (pLoop->wsFlags & WHERE_INDEXED)!=0 );
6949 if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 ){
drh35451c62009-11-12 04:26:39 +00006950 sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
6951 }
drh76f4cfb2013-05-31 18:20:52 +00006952 if( pLoop->wsFlags & WHERE_INDEXED ){
drh3c84ddf2008-01-09 02:15:38 +00006953 sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
drh7f09b3e2002-08-13 13:15:49 +00006954 }
drh336a5302009-04-24 15:46:21 +00006955 if( pLevel->op==OP_Return ){
6956 sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
6957 }else{
6958 sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
6959 }
drhd654be82005-09-20 17:42:23 +00006960 sqlite3VdbeJumpHere(v, addr);
drhad2d8302002-05-24 20:31:36 +00006961 }
drh6bc69a22013-11-19 12:33:23 +00006962 VdbeModuleComment((v, "End WHERE-loop%d: %s", i,
drhfc8d4f92013-11-08 15:19:46 +00006963 pWInfo->pTabList->a[pLevel->iFrom].pTab->zName));
drh19a775c2000-06-05 18:54:46 +00006964 }
drh9012bcb2004-12-19 00:11:35 +00006965
6966 /* The "break" point is here, just past the end of the outer loop.
6967 ** Set it.
6968 */
danielk19774adee202004-05-08 08:23:19 +00006969 sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
drh9012bcb2004-12-19 00:11:35 +00006970
drhfd636c72013-06-21 02:05:06 +00006971 assert( pWInfo->nLevel<=pTabList->nSrc );
drhc01a3c12009-12-16 22:10:49 +00006972 for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
drh5f612292014-02-08 23:20:32 +00006973 int k, last;
6974 VdbeOp *pOp;
danbfca6a42012-08-24 10:52:35 +00006975 Index *pIdx = 0;
drh29dda4a2005-07-21 18:23:20 +00006976 struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
drh9012bcb2004-12-19 00:11:35 +00006977 Table *pTab = pTabItem->pTab;
drh5cf590c2003-04-24 01:45:04 +00006978 assert( pTab!=0 );
drh7ba39a92013-05-30 17:43:19 +00006979 pLoop = pLevel->pWLoop;
drhfc8d4f92013-11-08 15:19:46 +00006980
drh5f612292014-02-08 23:20:32 +00006981 /* For a co-routine, change all OP_Column references to the table of
6982 ** the co-routine into OP_SCopy of result contained in a register.
6983 ** OP_Rowid becomes OP_Null.
6984 */
danfbf0f0e2014-03-03 14:20:30 +00006985 if( pTabItem->viaCoroutine && !db->mallocFailed ){
drh5f612292014-02-08 23:20:32 +00006986 last = sqlite3VdbeCurrentAddr(v);
6987 k = pLevel->addrBody;
6988 pOp = sqlite3VdbeGetOp(v, k);
6989 for(; k<last; k++, pOp++){
6990 if( pOp->p1!=pLevel->iTabCur ) continue;
6991 if( pOp->opcode==OP_Column ){
drhc438df12014-04-03 16:29:31 +00006992 pOp->opcode = OP_Copy;
drh5f612292014-02-08 23:20:32 +00006993 pOp->p1 = pOp->p2 + pTabItem->regResult;
6994 pOp->p2 = pOp->p3;
6995 pOp->p3 = 0;
6996 }else if( pOp->opcode==OP_Rowid ){
6997 pOp->opcode = OP_Null;
6998 pOp->p1 = 0;
6999 pOp->p3 = 0;
7000 }
7001 }
7002 continue;
7003 }
7004
drhfc8d4f92013-11-08 15:19:46 +00007005 /* Close all of the cursors that were opened by sqlite3WhereBegin.
7006 ** Except, do not close cursors that will be reused by the OR optimization
7007 ** (WHERE_OMIT_OPEN_CLOSE). And do not close the OP_OpenWrite cursors
7008 ** created for the ONEPASS optimization.
7009 */
drh4139c992010-04-07 14:59:45 +00007010 if( (pTab->tabFlags & TF_Ephemeral)==0
7011 && pTab->pSelect==0
drh9ef61f42011-10-07 14:40:59 +00007012 && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
drh4139c992010-04-07 14:59:45 +00007013 ){
drh7ba39a92013-05-30 17:43:19 +00007014 int ws = pLoop->wsFlags;
drh8b307fb2010-04-06 15:57:05 +00007015 if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
drh6df2acd2008-12-28 16:55:25 +00007016 sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
7017 }
drhfc8d4f92013-11-08 15:19:46 +00007018 if( (ws & WHERE_INDEXED)!=0
7019 && (ws & (WHERE_IPK|WHERE_AUTO_INDEX))==0
7020 && pLevel->iIdxCur!=pWInfo->aiCurOnePass[1]
7021 ){
drh6df2acd2008-12-28 16:55:25 +00007022 sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
7023 }
drh9012bcb2004-12-19 00:11:35 +00007024 }
7025
drhf0030762013-06-14 13:27:01 +00007026 /* If this scan uses an index, make VDBE code substitutions to read data
7027 ** from the index instead of from the table where possible. In some cases
7028 ** this optimization prevents the table from ever being read, which can
7029 ** yield a significant performance boost.
drh9012bcb2004-12-19 00:11:35 +00007030 **
7031 ** Calls to the code generator in between sqlite3WhereBegin and
7032 ** sqlite3WhereEnd will have created code that references the table
7033 ** directly. This loop scans all that code looking for opcodes
7034 ** that reference the table and converts them into opcodes that
7035 ** reference the index.
7036 */
drh7ba39a92013-05-30 17:43:19 +00007037 if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
7038 pIdx = pLoop->u.btree.pIndex;
7039 }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
drhd40e2082012-08-24 23:24:15 +00007040 pIdx = pLevel->u.pCovidx;
danbfca6a42012-08-24 10:52:35 +00007041 }
drh7ba39a92013-05-30 17:43:19 +00007042 if( pIdx && !db->mallocFailed ){
drh9012bcb2004-12-19 00:11:35 +00007043 last = sqlite3VdbeCurrentAddr(v);
drhcc04afd2013-08-22 02:56:28 +00007044 k = pLevel->addrBody;
7045 pOp = sqlite3VdbeGetOp(v, k);
7046 for(; k<last; k++, pOp++){
drh9012bcb2004-12-19 00:11:35 +00007047 if( pOp->p1!=pLevel->iTabCur ) continue;
7048 if( pOp->opcode==OP_Column ){
drhee0ec8e2013-10-31 17:38:01 +00007049 int x = pOp->p2;
drh511717c2013-11-08 17:13:23 +00007050 assert( pIdx->pTable==pTab );
drhee0ec8e2013-10-31 17:38:01 +00007051 if( !HasRowid(pTab) ){
7052 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
7053 x = pPk->aiColumn[x];
7054 }
7055 x = sqlite3ColumnOfIndex(pIdx, x);
drh44156282013-10-23 22:23:03 +00007056 if( x>=0 ){
7057 pOp->p2 = x;
7058 pOp->p1 = pLevel->iIdxCur;
drh9012bcb2004-12-19 00:11:35 +00007059 }
drh44156282013-10-23 22:23:03 +00007060 assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || x>=0 );
drhf0863fe2005-06-12 21:35:51 +00007061 }else if( pOp->opcode==OP_Rowid ){
drh9012bcb2004-12-19 00:11:35 +00007062 pOp->p1 = pLevel->iIdxCur;
drhf0863fe2005-06-12 21:35:51 +00007063 pOp->opcode = OP_IdxRowid;
drh9012bcb2004-12-19 00:11:35 +00007064 }
7065 }
drh6b563442001-11-07 16:48:26 +00007066 }
drh19a775c2000-06-05 18:54:46 +00007067 }
drh9012bcb2004-12-19 00:11:35 +00007068
7069 /* Final cleanup
7070 */
drhf12cde52010-04-08 17:28:00 +00007071 pParse->nQueryLoop = pWInfo->savedNQueryLoop;
7072 whereInfoFree(db, pWInfo);
drh75897232000-05-29 14:26:00 +00007073 return;
7074}