blob: 85eb00b46be41653f5de00fdaea2739a60e617a1 [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 );
drh50b39962006-10-28 00:28:09 +0000366 return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
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;
drhfe05af82005-07-21 03:14:59 +0000419 }else{
drhec1724e2008-12-09 01:32:03 +0000420 assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
421 c = (u16)(WO_EQ<<(op-TK_EQ));
drhfe05af82005-07-21 03:14:59 +0000422 }
drh50b39962006-10-28 00:28:09 +0000423 assert( op!=TK_ISNULL || c==WO_ISNULL );
drh51147ba2005-07-23 22:59:55 +0000424 assert( op!=TK_IN || c==WO_IN );
425 assert( op!=TK_EQ || c==WO_EQ );
426 assert( op!=TK_LT || c==WO_LT );
427 assert( op!=TK_LE || c==WO_LE );
428 assert( op!=TK_GT || c==WO_GT );
429 assert( op!=TK_GE || c==WO_GE );
430 return c;
drhfe05af82005-07-21 03:14:59 +0000431}
432
433/*
drh1c8148f2013-05-04 20:25:23 +0000434** Advance to the next WhereTerm that matches according to the criteria
435** established when the pScan object was initialized by whereScanInit().
436** Return NULL if there are no more matching WhereTerms.
437*/
danb2cfc142013-07-05 11:10:54 +0000438static WhereTerm *whereScanNext(WhereScan *pScan){
drh1c8148f2013-05-04 20:25:23 +0000439 int iCur; /* The cursor on the LHS of the term */
440 int iColumn; /* The column on the LHS of the term. -1 for IPK */
441 Expr *pX; /* An expression being tested */
442 WhereClause *pWC; /* Shorthand for pScan->pWC */
443 WhereTerm *pTerm; /* The term being tested */
drh43b85ef2013-06-10 12:34:45 +0000444 int k = pScan->k; /* Where to start scanning */
drh1c8148f2013-05-04 20:25:23 +0000445
446 while( pScan->iEquiv<=pScan->nEquiv ){
447 iCur = pScan->aEquiv[pScan->iEquiv-2];
448 iColumn = pScan->aEquiv[pScan->iEquiv-1];
449 while( (pWC = pScan->pWC)!=0 ){
drh43b85ef2013-06-10 12:34:45 +0000450 for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
drhe1a086e2013-10-28 20:15:56 +0000451 if( pTerm->leftCursor==iCur
452 && pTerm->u.leftColumn==iColumn
453 && (pScan->iEquiv<=2 || !ExprHasProperty(pTerm->pExpr, EP_FromJoin))
454 ){
drh1c8148f2013-05-04 20:25:23 +0000455 if( (pTerm->eOperator & WO_EQUIV)!=0
456 && pScan->nEquiv<ArraySize(pScan->aEquiv)
457 ){
458 int j;
459 pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight);
460 assert( pX->op==TK_COLUMN );
461 for(j=0; j<pScan->nEquiv; j+=2){
462 if( pScan->aEquiv[j]==pX->iTable
463 && pScan->aEquiv[j+1]==pX->iColumn ){
464 break;
465 }
466 }
467 if( j==pScan->nEquiv ){
468 pScan->aEquiv[j] = pX->iTable;
469 pScan->aEquiv[j+1] = pX->iColumn;
470 pScan->nEquiv += 2;
471 }
472 }
473 if( (pTerm->eOperator & pScan->opMask)!=0 ){
474 /* Verify the affinity and collating sequence match */
475 if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
476 CollSeq *pColl;
drh70d18342013-06-06 19:16:33 +0000477 Parse *pParse = pWC->pWInfo->pParse;
drh1c8148f2013-05-04 20:25:23 +0000478 pX = pTerm->pExpr;
479 if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
480 continue;
481 }
482 assert(pX->pLeft);
drh70d18342013-06-06 19:16:33 +0000483 pColl = sqlite3BinaryCompareCollSeq(pParse,
drh1c8148f2013-05-04 20:25:23 +0000484 pX->pLeft, pX->pRight);
drh70d18342013-06-06 19:16:33 +0000485 if( pColl==0 ) pColl = pParse->db->pDfltColl;
drh1c8148f2013-05-04 20:25:23 +0000486 if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
487 continue;
488 }
489 }
drha184fb82013-05-08 04:22:59 +0000490 if( (pTerm->eOperator & WO_EQ)!=0
491 && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN
492 && pX->iTable==pScan->aEquiv[0]
493 && pX->iColumn==pScan->aEquiv[1]
494 ){
495 continue;
496 }
drh43b85ef2013-06-10 12:34:45 +0000497 pScan->k = k+1;
drh1c8148f2013-05-04 20:25:23 +0000498 return pTerm;
499 }
500 }
501 }
drhad01d892013-06-19 13:59:49 +0000502 pScan->pWC = pScan->pWC->pOuter;
drh43b85ef2013-06-10 12:34:45 +0000503 k = 0;
drh1c8148f2013-05-04 20:25:23 +0000504 }
505 pScan->pWC = pScan->pOrigWC;
drh43b85ef2013-06-10 12:34:45 +0000506 k = 0;
drh1c8148f2013-05-04 20:25:23 +0000507 pScan->iEquiv += 2;
508 }
drh1c8148f2013-05-04 20:25:23 +0000509 return 0;
510}
511
512/*
513** Initialize a WHERE clause scanner object. Return a pointer to the
514** first match. Return NULL if there are no matches.
515**
516** The scanner will be searching the WHERE clause pWC. It will look
517** for terms of the form "X <op> <expr>" where X is column iColumn of table
518** iCur. The <op> must be one of the operators described by opMask.
519**
drh3b48e8c2013-06-12 20:18:16 +0000520** If the search is for X and the WHERE clause contains terms of the
521** form X=Y then this routine might also return terms of the form
522** "Y <op> <expr>". The number of levels of transitivity is limited,
523** but is enough to handle most commonly occurring SQL statements.
524**
drh1c8148f2013-05-04 20:25:23 +0000525** If X is not the INTEGER PRIMARY KEY then X must be compatible with
526** index pIdx.
527*/
danb2cfc142013-07-05 11:10:54 +0000528static WhereTerm *whereScanInit(
drh1c8148f2013-05-04 20:25:23 +0000529 WhereScan *pScan, /* The WhereScan object being initialized */
530 WhereClause *pWC, /* The WHERE clause to be scanned */
531 int iCur, /* Cursor to scan for */
532 int iColumn, /* Column to scan for */
533 u32 opMask, /* Operator(s) to scan for */
534 Index *pIdx /* Must be compatible with this index */
535){
536 int j;
537
drhe9d935a2013-06-05 16:19:59 +0000538 /* memset(pScan, 0, sizeof(*pScan)); */
drh1c8148f2013-05-04 20:25:23 +0000539 pScan->pOrigWC = pWC;
540 pScan->pWC = pWC;
541 if( pIdx && iColumn>=0 ){
542 pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
543 for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
dan39129ce2014-06-30 15:23:57 +0000544 if( NEVER(j>pIdx->nColumn) ) return 0;
drh1c8148f2013-05-04 20:25:23 +0000545 }
546 pScan->zCollName = pIdx->azColl[j];
drhe9d935a2013-06-05 16:19:59 +0000547 }else{
548 pScan->idxaff = 0;
549 pScan->zCollName = 0;
drh1c8148f2013-05-04 20:25:23 +0000550 }
551 pScan->opMask = opMask;
drhe9d935a2013-06-05 16:19:59 +0000552 pScan->k = 0;
drh1c8148f2013-05-04 20:25:23 +0000553 pScan->aEquiv[0] = iCur;
554 pScan->aEquiv[1] = iColumn;
555 pScan->nEquiv = 2;
556 pScan->iEquiv = 2;
557 return whereScanNext(pScan);
558}
559
560/*
drhfe05af82005-07-21 03:14:59 +0000561** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
562** where X is a reference to the iColumn of table iCur and <op> is one of
563** the WO_xx operator codes specified by the op parameter.
564** Return a pointer to the term. Return 0 if not found.
drh58eb1c02013-01-17 00:08:42 +0000565**
566** The term returned might by Y=<expr> if there is another constraint in
567** the WHERE clause that specifies that X=Y. Any such constraints will be
568** identified by the WO_EQUIV bit in the pTerm->eOperator field. The
569** aEquiv[] array holds X and all its equivalents, with each SQL variable
570** taking up two slots in aEquiv[]. The first slot is for the cursor number
571** and the second is for the column number. There are 22 slots in aEquiv[]
572** so that means we can look for X plus up to 10 other equivalent values.
573** Hence a search for X will return <expr> if X=A1 and A1=A2 and A2=A3
574** and ... and A9=A10 and A10=<expr>.
575**
576** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
577** then try for the one with no dependencies on <expr> - in other words where
578** <expr> is a constant expression of some kind. Only return entries of
579** the form "X <op> Y" where Y is a column in another table if no terms of
drh459f63e2013-03-06 01:55:27 +0000580** the form "X <op> <const-expr>" exist. If no terms with a constant RHS
581** exist, try to return a term that does not use WO_EQUIV.
drhfe05af82005-07-21 03:14:59 +0000582*/
583static WhereTerm *findTerm(
584 WhereClause *pWC, /* The WHERE clause to be searched */
585 int iCur, /* Cursor number of LHS */
586 int iColumn, /* Column number of LHS */
587 Bitmask notReady, /* RHS must not overlap with this mask */
drhec1724e2008-12-09 01:32:03 +0000588 u32 op, /* Mask of WO_xx values describing operator */
drhfe05af82005-07-21 03:14:59 +0000589 Index *pIdx /* Must be compatible with this index, if not NULL */
590){
drh1c8148f2013-05-04 20:25:23 +0000591 WhereTerm *pResult = 0;
592 WhereTerm *p;
593 WhereScan scan;
drh7a5bcc02013-01-16 17:08:58 +0000594
drh1c8148f2013-05-04 20:25:23 +0000595 p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
596 while( p ){
597 if( (p->prereqRight & notReady)==0 ){
598 if( p->prereqRight==0 && (p->eOperator&WO_EQ)!=0 ){
599 return p;
drhfe05af82005-07-21 03:14:59 +0000600 }
drh1c8148f2013-05-04 20:25:23 +0000601 if( pResult==0 ) pResult = p;
drhfe05af82005-07-21 03:14:59 +0000602 }
drh1c8148f2013-05-04 20:25:23 +0000603 p = whereScanNext(&scan);
drhfe05af82005-07-21 03:14:59 +0000604 }
drh7a5bcc02013-01-16 17:08:58 +0000605 return pResult;
drhfe05af82005-07-21 03:14:59 +0000606}
607
drh6c30be82005-07-29 15:10:17 +0000608/* Forward reference */
drh7b4fc6a2007-02-06 13:26:32 +0000609static void exprAnalyze(SrcList*, WhereClause*, int);
drh6c30be82005-07-29 15:10:17 +0000610
611/*
612** Call exprAnalyze on all terms in a WHERE clause.
drh6c30be82005-07-29 15:10:17 +0000613*/
614static void exprAnalyzeAll(
615 SrcList *pTabList, /* the FROM clause */
drh6c30be82005-07-29 15:10:17 +0000616 WhereClause *pWC /* the WHERE clause to be analyzed */
617){
drh6c30be82005-07-29 15:10:17 +0000618 int i;
drh9eb20282005-08-24 03:52:18 +0000619 for(i=pWC->nTerm-1; i>=0; i--){
drh7b4fc6a2007-02-06 13:26:32 +0000620 exprAnalyze(pTabList, pWC, i);
drh6c30be82005-07-29 15:10:17 +0000621 }
622}
623
drhd2687b72005-08-12 22:56:09 +0000624#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
625/*
626** Check to see if the given expression is a LIKE or GLOB operator that
627** can be optimized using inequality constraints. Return TRUE if it is
628** so and false if not.
629**
630** In order for the operator to be optimizible, the RHS must be a string
drhf07cf6e2015-03-06 16:45:16 +0000631** literal that does not begin with a wildcard. The LHS must be a column
632** that may only be NULL, a string, or a BLOB, never a number. (This means
633** that virtual tables cannot participate in the LIKE optimization.) If the
634** collating sequence for the column on the LHS must be appropriate for
635** the operator.
drhd2687b72005-08-12 22:56:09 +0000636*/
637static int isLikeOrGlob(
drh7d10d5a2008-08-20 16:35:10 +0000638 Parse *pParse, /* Parsing and code generating context */
drhd2687b72005-08-12 22:56:09 +0000639 Expr *pExpr, /* Test this expression */
dan937d0de2009-10-15 18:35:38 +0000640 Expr **ppPrefix, /* Pointer to TK_STRING expression with pattern prefix */
drh9f504ea2008-02-23 21:55:39 +0000641 int *pisComplete, /* True if the only wildcard is % in the last character */
642 int *pnoCase /* True if uppercase is equivalent to lowercase */
drhd2687b72005-08-12 22:56:09 +0000643){
dan937d0de2009-10-15 18:35:38 +0000644 const char *z = 0; /* String on RHS of LIKE operator */
drh5bd98ae2009-01-07 18:24:03 +0000645 Expr *pRight, *pLeft; /* Right and left size of LIKE operator */
646 ExprList *pList; /* List of operands to the LIKE operator */
647 int c; /* One character in z[] */
648 int cnt; /* Number of non-wildcard prefix characters */
649 char wc[3]; /* Wildcard characters */
drh5bd98ae2009-01-07 18:24:03 +0000650 sqlite3 *db = pParse->db; /* Database connection */
dan937d0de2009-10-15 18:35:38 +0000651 sqlite3_value *pVal = 0;
652 int op; /* Opcode of pRight */
drhd64fe2f2005-08-28 17:00:23 +0000653
drh9f504ea2008-02-23 21:55:39 +0000654 if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
drhd2687b72005-08-12 22:56:09 +0000655 return 0;
656 }
drh9f504ea2008-02-23 21:55:39 +0000657#ifdef SQLITE_EBCDIC
658 if( *pnoCase ) return 0;
659#endif
danielk19776ab3a2e2009-02-19 14:39:25 +0000660 pList = pExpr->x.pList;
drh55ef4d92005-08-14 01:20:37 +0000661 pLeft = pList->a[1].pExpr;
danc68939e2012-03-29 14:29:07 +0000662 if( pLeft->op!=TK_COLUMN
663 || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
drhf07cf6e2015-03-06 16:45:16 +0000664 || IsVirtual(pLeft->pTab) /* Value might be numeric */
danc68939e2012-03-29 14:29:07 +0000665 ){
drhd91ca492009-10-22 20:50:36 +0000666 /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
667 ** be the name of an indexed column with TEXT affinity. */
drhd2687b72005-08-12 22:56:09 +0000668 return 0;
669 }
drhd91ca492009-10-22 20:50:36 +0000670 assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
dan937d0de2009-10-15 18:35:38 +0000671
drh6ade4532014-01-16 15:31:41 +0000672 pRight = sqlite3ExprSkipCollate(pList->a[0].pExpr);
dan937d0de2009-10-15 18:35:38 +0000673 op = pRight->op;
dan937d0de2009-10-15 18:35:38 +0000674 if( op==TK_VARIABLE ){
675 Vdbe *pReprepare = pParse->pReprepare;
drha7044002010-09-14 18:22:59 +0000676 int iCol = pRight->iColumn;
drhcf0fd4a2013-08-01 12:21:58 +0000677 pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_NONE);
dan937d0de2009-10-15 18:35:38 +0000678 if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
679 z = (char *)sqlite3_value_text(pVal);
680 }
drhf9b22ca2011-10-21 16:47:31 +0000681 sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
dan937d0de2009-10-15 18:35:38 +0000682 assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
683 }else if( op==TK_STRING ){
684 z = pRight->u.zToken;
685 }
686 if( z ){
shane85095702009-06-15 16:27:08 +0000687 cnt = 0;
drhb7916a72009-05-27 10:31:29 +0000688 while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
drh24fb6272009-05-01 21:13:36 +0000689 cnt++;
690 }
drh93ee23c2010-07-22 12:33:57 +0000691 if( cnt!=0 && 255!=(u8)z[cnt-1] ){
dan937d0de2009-10-15 18:35:38 +0000692 Expr *pPrefix;
drh93ee23c2010-07-22 12:33:57 +0000693 *pisComplete = c==wc[0] && z[cnt+1]==0;
dan937d0de2009-10-15 18:35:38 +0000694 pPrefix = sqlite3Expr(db, TK_STRING, z);
695 if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
696 *ppPrefix = pPrefix;
697 if( op==TK_VARIABLE ){
698 Vdbe *v = pParse->pVdbe;
drhf9b22ca2011-10-21 16:47:31 +0000699 sqlite3VdbeSetVarmask(v, pRight->iColumn);
dan937d0de2009-10-15 18:35:38 +0000700 if( *pisComplete && pRight->u.zToken[1] ){
701 /* If the rhs of the LIKE expression is a variable, and the current
702 ** value of the variable means there is no need to invoke the LIKE
703 ** function, then no OP_Variable will be added to the program.
704 ** This causes problems for the sqlite3_bind_parameter_name()
peter.d.reid60ec9142014-09-06 16:39:46 +0000705 ** API. To work around them, add a dummy OP_Variable here.
drhbec451f2009-10-17 13:13:02 +0000706 */
707 int r1 = sqlite3GetTempReg(pParse);
708 sqlite3ExprCodeTarget(pParse, pRight, r1);
dan937d0de2009-10-15 18:35:38 +0000709 sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
drhbec451f2009-10-17 13:13:02 +0000710 sqlite3ReleaseTempReg(pParse, r1);
dan937d0de2009-10-15 18:35:38 +0000711 }
712 }
713 }else{
714 z = 0;
shane85095702009-06-15 16:27:08 +0000715 }
drhf998b732007-11-26 13:36:00 +0000716 }
dan937d0de2009-10-15 18:35:38 +0000717
718 sqlite3ValueFree(pVal);
719 return (z!=0);
drhd2687b72005-08-12 22:56:09 +0000720}
721#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
722
drhedb193b2006-06-27 13:20:21 +0000723
724#ifndef SQLITE_OMIT_VIRTUALTABLE
drhfe05af82005-07-21 03:14:59 +0000725/*
drh7f375902006-06-13 17:38:59 +0000726** Check to see if the given expression is of the form
727**
728** column MATCH expr
729**
730** If it is then return TRUE. If not, return FALSE.
731*/
732static int isMatchOfColumn(
733 Expr *pExpr /* Test this expression */
734){
735 ExprList *pList;
736
737 if( pExpr->op!=TK_FUNCTION ){
738 return 0;
739 }
drh33e619f2009-05-28 01:00:55 +0000740 if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
drh7f375902006-06-13 17:38:59 +0000741 return 0;
742 }
danielk19776ab3a2e2009-02-19 14:39:25 +0000743 pList = pExpr->x.pList;
drh7f375902006-06-13 17:38:59 +0000744 if( pList->nExpr!=2 ){
745 return 0;
746 }
747 if( pList->a[1].pExpr->op != TK_COLUMN ){
748 return 0;
749 }
750 return 1;
751}
drhedb193b2006-06-27 13:20:21 +0000752#endif /* SQLITE_OMIT_VIRTUALTABLE */
drh7f375902006-06-13 17:38:59 +0000753
754/*
drh54a167d2005-11-26 14:08:07 +0000755** If the pBase expression originated in the ON or USING clause of
756** a join, then transfer the appropriate markings over to derived.
757*/
758static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
drhd41d39f2013-08-28 16:27:01 +0000759 if( pDerived ){
760 pDerived->flags |= pBase->flags & EP_FromJoin;
761 pDerived->iRightJoinTable = pBase->iRightJoinTable;
762 }
drh54a167d2005-11-26 14:08:07 +0000763}
764
drh9769efc2014-10-24 14:32:21 +0000765/*
766** Mark term iChild as being a child of term iParent
767*/
768static void markTermAsChild(WhereClause *pWC, int iChild, int iParent){
769 pWC->a[iChild].iParent = iParent;
770 pWC->a[iChild].truthProb = pWC->a[iParent].truthProb;
771 pWC->a[iParent].nChild++;
772}
773
drh84266362015-03-16 12:13:31 +0000774/*
775** Return the N-th AND-connected subterm of pTerm. Or if pTerm is not
776** a conjunction, then return just pTerm when N==0. If N is exceeds
777** the number of available subterms, return NULL.
778*/
779static WhereTerm *whereNthSubterm(WhereTerm *pTerm, int N){
780 if( pTerm->eOperator!=WO_AND ){
781 return N==0 ? pTerm : 0;
782 }
783 if( N<pTerm->u.pAndInfo->wc.nTerm ){
784 return &pTerm->u.pAndInfo->wc.a[N];
785 }
786 return 0;
787}
788
789/*
790** Subterms pOne and pTwo are contained within WHERE clause pWC. The
791** two subterms are in disjunction - they are OR-ed together.
792**
793** If these two terms are both of the form: "A op B" with the same
794** A and B values but different operators and if the operators are
795** compatible (if one is = and the other is <, for example) then
drhc03acf22015-03-16 13:12:34 +0000796** add a new virtual AND term to pWC that is the combination of the
drh84266362015-03-16 12:13:31 +0000797** two.
798**
799** Some examples:
800**
801** x<y OR x=y --> x<=y
802** x=y OR x=y --> x=y
803** x<=y OR x<y --> x<=y
804**
805** The following is NOT generated:
806**
807** x<y OR x>y --> x!=y
808*/
809static void whereCombineDisjuncts(
810 SrcList *pSrc, /* the FROM clause */
811 WhereClause *pWC, /* The complete WHERE clause */
812 WhereTerm *pOne, /* First disjunct */
813 WhereTerm *pTwo /* Second disjunct */
814){
815 u16 eOp = pOne->eOperator | pTwo->eOperator;
816 sqlite3 *db; /* Database connection (for malloc) */
817 Expr *pNew; /* New virtual expression */
818 int op; /* Operator for the combined expression */
819 int idxNew; /* Index in pWC of the next virtual term */
820
821 if( (pOne->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
822 if( (pTwo->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
823 if( (eOp & (WO_EQ|WO_LT|WO_LE))!=eOp
824 && (eOp & (WO_EQ|WO_GT|WO_GE))!=eOp ) return;
825 assert( pOne->pExpr->pLeft!=0 && pOne->pExpr->pRight!=0 );
826 assert( pTwo->pExpr->pLeft!=0 && pTwo->pExpr->pRight!=0 );
827 if( sqlite3ExprCompare(pOne->pExpr->pLeft, pTwo->pExpr->pLeft, -1) ) return;
828 if( sqlite3ExprCompare(pOne->pExpr->pRight, pTwo->pExpr->pRight, -1) )return;
829 /* If we reach this point, it means the two subterms can be combined */
830 if( (eOp & (eOp-1))!=0 ){
831 if( eOp & (WO_LT|WO_LE) ){
832 eOp = WO_LE;
833 }else{
834 assert( eOp & (WO_GT|WO_GE) );
835 eOp = WO_GE;
836 }
837 }
838 db = pWC->pWInfo->pParse->db;
839 pNew = sqlite3ExprDup(db, pOne->pExpr, 0);
840 if( pNew==0 ) return;
841 for(op=TK_EQ; eOp!=(WO_EQ<<(op-TK_EQ)); op++){ assert( op<TK_GE ); }
842 pNew->op = op;
843 idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
844 exprAnalyze(pSrc, pWC, idxNew);
845}
846
drh3e355802007-02-23 23:13:33 +0000847#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
848/*
drh1a58fe02008-12-20 02:06:13 +0000849** Analyze a term that consists of two or more OR-connected
850** subterms. So in:
drh3e355802007-02-23 23:13:33 +0000851**
drh1a58fe02008-12-20 02:06:13 +0000852** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
853** ^^^^^^^^^^^^^^^^^^^^
drh3e355802007-02-23 23:13:33 +0000854**
drh1a58fe02008-12-20 02:06:13 +0000855** This routine analyzes terms such as the middle term in the above example.
856** A WhereOrTerm object is computed and attached to the term under
857** analysis, regardless of the outcome of the analysis. Hence:
drh3e355802007-02-23 23:13:33 +0000858**
drh1a58fe02008-12-20 02:06:13 +0000859** WhereTerm.wtFlags |= TERM_ORINFO
860** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object
drh3e355802007-02-23 23:13:33 +0000861**
drh1a58fe02008-12-20 02:06:13 +0000862** The term being analyzed must have two or more of OR-connected subterms.
danielk1977fdc40192008-12-29 18:33:32 +0000863** A single subterm might be a set of AND-connected sub-subterms.
drh1a58fe02008-12-20 02:06:13 +0000864** Examples of terms under analysis:
drh3e355802007-02-23 23:13:33 +0000865**
drh1a58fe02008-12-20 02:06:13 +0000866** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
867** (B) x=expr1 OR expr2=x OR x=expr3
868** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
869** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
870** (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 +0000871** (F) x>A OR (x=A AND y>=B)
drh3e355802007-02-23 23:13:33 +0000872**
drh1a58fe02008-12-20 02:06:13 +0000873** CASE 1:
874**
drhc3e552f2013-02-08 16:04:19 +0000875** If all subterms are of the form T.C=expr for some single column of C and
drh1a58fe02008-12-20 02:06:13 +0000876** a single table T (as shown in example B above) then create a new virtual
877** term that is an equivalent IN expression. In other words, if the term
878** being analyzed is:
879**
880** x = expr1 OR expr2 = x OR x = expr3
881**
882** then create a new virtual term like this:
883**
884** x IN (expr1,expr2,expr3)
885**
886** CASE 2:
887**
drhc03acf22015-03-16 13:12:34 +0000888** If there are exactly two disjuncts one side has x>A and the other side
889** has x=A (for the same x and A) then add a new virtual conjunct term to the
890** WHERE clause of the form "x>=A". Example:
891**
892** x>A OR (x=A AND y>B) adds: x>=A
893**
894** The added conjunct can sometimes be helpful in query planning.
drh84266362015-03-16 12:13:31 +0000895**
896** CASE 3:
897**
drh1a58fe02008-12-20 02:06:13 +0000898** If all subterms are indexable by a single table T, then set
899**
900** WhereTerm.eOperator = WO_OR
901** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T
902**
903** A subterm is "indexable" if it is of the form
904** "T.C <op> <expr>" where C is any column of table T and
905** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
906** A subterm is also indexable if it is an AND of two or more
907** subsubterms at least one of which is indexable. Indexable AND
908** subterms have their eOperator set to WO_AND and they have
909** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
910**
911** From another point of view, "indexable" means that the subterm could
912** potentially be used with an index if an appropriate index exists.
913** This analysis does not consider whether or not the index exists; that
drh4a6fc352013-08-07 01:18:38 +0000914** is decided elsewhere. This analysis only looks at whether subterms
915** appropriate for indexing exist.
drh1a58fe02008-12-20 02:06:13 +0000916**
drh4a6fc352013-08-07 01:18:38 +0000917** All examples A through E above satisfy case 2. But if a term
peter.d.reid60ec9142014-09-06 16:39:46 +0000918** also satisfies case 1 (such as B) we know that the optimizer will
drh1a58fe02008-12-20 02:06:13 +0000919** always prefer case 1, so in that case we pretend that case 2 is not
920** satisfied.
921**
922** It might be the case that multiple tables are indexable. For example,
923** (E) above is indexable on tables P, Q, and R.
924**
925** Terms that satisfy case 2 are candidates for lookup by using
926** separate indices to find rowids for each subterm and composing
927** the union of all rowids using a RowSet object. This is similar
928** to "bitmap indices" in other database engines.
929**
930** OTHERWISE:
931**
932** If neither case 1 nor case 2 apply, then leave the eOperator set to
933** zero. This term is not useful for search.
drh3e355802007-02-23 23:13:33 +0000934*/
drh1a58fe02008-12-20 02:06:13 +0000935static void exprAnalyzeOrTerm(
936 SrcList *pSrc, /* the FROM clause */
937 WhereClause *pWC, /* the complete WHERE clause */
938 int idxTerm /* Index of the OR-term to be analyzed */
939){
drh70d18342013-06-06 19:16:33 +0000940 WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
941 Parse *pParse = pWInfo->pParse; /* Parser context */
drh1a58fe02008-12-20 02:06:13 +0000942 sqlite3 *db = pParse->db; /* Database connection */
943 WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */
944 Expr *pExpr = pTerm->pExpr; /* The expression of the term */
drh1a58fe02008-12-20 02:06:13 +0000945 int i; /* Loop counters */
946 WhereClause *pOrWc; /* Breakup of pTerm into subterms */
947 WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */
948 WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */
949 Bitmask chngToIN; /* Tables that might satisfy case 1 */
950 Bitmask indexable; /* Tables that are indexable, satisfying case 2 */
drh3e355802007-02-23 23:13:33 +0000951
drh1a58fe02008-12-20 02:06:13 +0000952 /*
953 ** Break the OR clause into its separate subterms. The subterms are
954 ** stored in a WhereClause structure containing within the WhereOrInfo
955 ** object that is attached to the original OR clause term.
956 */
957 assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
958 assert( pExpr->op==TK_OR );
drh954701a2008-12-29 23:45:07 +0000959 pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
drh1a58fe02008-12-20 02:06:13 +0000960 if( pOrInfo==0 ) return;
961 pTerm->wtFlags |= TERM_ORINFO;
962 pOrWc = &pOrInfo->wc;
drh70d18342013-06-06 19:16:33 +0000963 whereClauseInit(pOrWc, pWInfo);
drh1a58fe02008-12-20 02:06:13 +0000964 whereSplit(pOrWc, pExpr, TK_OR);
965 exprAnalyzeAll(pSrc, pOrWc);
966 if( db->mallocFailed ) return;
967 assert( pOrWc->nTerm>=2 );
968
969 /*
970 ** Compute the set of tables that might satisfy cases 1 or 2.
971 */
danielk1977e672c8e2009-05-22 15:43:26 +0000972 indexable = ~(Bitmask)0;
drhc3e552f2013-02-08 16:04:19 +0000973 chngToIN = ~(Bitmask)0;
drh1a58fe02008-12-20 02:06:13 +0000974 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
975 if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
drh29435252008-12-28 18:35:08 +0000976 WhereAndInfo *pAndInfo;
drh29435252008-12-28 18:35:08 +0000977 assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
drh1a58fe02008-12-20 02:06:13 +0000978 chngToIN = 0;
drh29435252008-12-28 18:35:08 +0000979 pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
980 if( pAndInfo ){
981 WhereClause *pAndWC;
982 WhereTerm *pAndTerm;
983 int j;
984 Bitmask b = 0;
985 pOrTerm->u.pAndInfo = pAndInfo;
986 pOrTerm->wtFlags |= TERM_ANDINFO;
987 pOrTerm->eOperator = WO_AND;
988 pAndWC = &pAndInfo->wc;
drh70d18342013-06-06 19:16:33 +0000989 whereClauseInit(pAndWC, pWC->pWInfo);
drh29435252008-12-28 18:35:08 +0000990 whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
991 exprAnalyzeAll(pSrc, pAndWC);
drh8871ef52011-10-07 13:33:10 +0000992 pAndWC->pOuter = pWC;
drh7c2fbde2009-01-07 20:58:57 +0000993 testcase( db->mallocFailed );
drh96c7a7d2009-01-10 15:34:12 +0000994 if( !db->mallocFailed ){
995 for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
996 assert( pAndTerm->pExpr );
997 if( allowedOp(pAndTerm->pExpr->op) ){
drh70d18342013-06-06 19:16:33 +0000998 b |= getMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
drh96c7a7d2009-01-10 15:34:12 +0000999 }
drh29435252008-12-28 18:35:08 +00001000 }
1001 }
1002 indexable &= b;
1003 }
drh1a58fe02008-12-20 02:06:13 +00001004 }else if( pOrTerm->wtFlags & TERM_COPIED ){
1005 /* Skip this term for now. We revisit it when we process the
1006 ** corresponding TERM_VIRTUAL term */
1007 }else{
1008 Bitmask b;
drh70d18342013-06-06 19:16:33 +00001009 b = getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
drh1a58fe02008-12-20 02:06:13 +00001010 if( pOrTerm->wtFlags & TERM_VIRTUAL ){
1011 WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
drh70d18342013-06-06 19:16:33 +00001012 b |= getMask(&pWInfo->sMaskSet, pOther->leftCursor);
drh1a58fe02008-12-20 02:06:13 +00001013 }
1014 indexable &= b;
drh7a5bcc02013-01-16 17:08:58 +00001015 if( (pOrTerm->eOperator & WO_EQ)==0 ){
drh1a58fe02008-12-20 02:06:13 +00001016 chngToIN = 0;
1017 }else{
1018 chngToIN &= b;
1019 }
1020 }
drh3e355802007-02-23 23:13:33 +00001021 }
drh1a58fe02008-12-20 02:06:13 +00001022
1023 /*
drh84266362015-03-16 12:13:31 +00001024 ** Record the set of tables that satisfy case 3. The set might be
drh111a6a72008-12-21 03:51:16 +00001025 ** empty.
drh1a58fe02008-12-20 02:06:13 +00001026 */
1027 pOrInfo->indexable = indexable;
drh111a6a72008-12-21 03:51:16 +00001028 pTerm->eOperator = indexable==0 ? 0 : WO_OR;
drh1a58fe02008-12-20 02:06:13 +00001029
drh84266362015-03-16 12:13:31 +00001030 /* For a two-way OR, attempt to implementation case 2.
1031 */
1032 if( indexable && pOrWc->nTerm==2 ){
1033 int iOne = 0;
1034 WhereTerm *pOne;
1035 while( (pOne = whereNthSubterm(&pOrWc->a[0],iOne++))!=0 ){
1036 int iTwo = 0;
1037 WhereTerm *pTwo;
1038 while( (pTwo = whereNthSubterm(&pOrWc->a[1],iTwo++))!=0 ){
1039 whereCombineDisjuncts(pSrc, pWC, pOne, pTwo);
1040 }
1041 }
1042 }
1043
drh1a58fe02008-12-20 02:06:13 +00001044 /*
1045 ** chngToIN holds a set of tables that *might* satisfy case 1. But
1046 ** we have to do some additional checking to see if case 1 really
1047 ** is satisfied.
drh4e8be3b2009-06-08 17:11:08 +00001048 **
1049 ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means
1050 ** that there is no possibility of transforming the OR clause into an
1051 ** IN operator because one or more terms in the OR clause contain
1052 ** something other than == on a column in the single table. The 1-bit
1053 ** case means that every term of the OR clause is of the form
1054 ** "table.column=expr" for some single table. The one bit that is set
1055 ** will correspond to the common table. We still need to check to make
1056 ** sure the same column is used on all terms. The 2-bit case is when
1057 ** the all terms are of the form "table1.column=table2.column". It
1058 ** might be possible to form an IN operator with either table1.column
1059 ** or table2.column as the LHS if either is common to every term of
1060 ** the OR clause.
1061 **
1062 ** Note that terms of the form "table.column1=table.column2" (the
1063 ** same table on both sizes of the ==) cannot be optimized.
drh1a58fe02008-12-20 02:06:13 +00001064 */
1065 if( chngToIN ){
1066 int okToChngToIN = 0; /* True if the conversion to IN is valid */
1067 int iColumn = -1; /* Column index on lhs of IN operator */
shane63207ab2009-02-04 01:49:30 +00001068 int iCursor = -1; /* Table cursor common to all terms */
drh1a58fe02008-12-20 02:06:13 +00001069 int j = 0; /* Loop counter */
1070
1071 /* Search for a table and column that appears on one side or the
1072 ** other of the == operator in every subterm. That table and column
1073 ** will be recorded in iCursor and iColumn. There might not be any
1074 ** such table and column. Set okToChngToIN if an appropriate table
1075 ** and column is found but leave okToChngToIN false if not found.
1076 */
1077 for(j=0; j<2 && !okToChngToIN; j++){
1078 pOrTerm = pOrWc->a;
1079 for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
drh7a5bcc02013-01-16 17:08:58 +00001080 assert( pOrTerm->eOperator & WO_EQ );
drh1a58fe02008-12-20 02:06:13 +00001081 pOrTerm->wtFlags &= ~TERM_OR_OK;
drh4e8be3b2009-06-08 17:11:08 +00001082 if( pOrTerm->leftCursor==iCursor ){
1083 /* This is the 2-bit case and we are on the second iteration and
1084 ** current term is from the first iteration. So skip this term. */
1085 assert( j==1 );
1086 continue;
1087 }
drh70d18342013-06-06 19:16:33 +00001088 if( (chngToIN & getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor))==0 ){
drh4e8be3b2009-06-08 17:11:08 +00001089 /* This term must be of the form t1.a==t2.b where t2 is in the
peter.d.reid60ec9142014-09-06 16:39:46 +00001090 ** chngToIN set but t1 is not. This term will be either preceded
drh4e8be3b2009-06-08 17:11:08 +00001091 ** or follwed by an inverted copy (t2.b==t1.a). Skip this term
1092 ** and use its inversion. */
1093 testcase( pOrTerm->wtFlags & TERM_COPIED );
1094 testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
1095 assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
1096 continue;
1097 }
drh1a58fe02008-12-20 02:06:13 +00001098 iColumn = pOrTerm->u.leftColumn;
1099 iCursor = pOrTerm->leftCursor;
1100 break;
1101 }
1102 if( i<0 ){
drh4e8be3b2009-06-08 17:11:08 +00001103 /* No candidate table+column was found. This can only occur
1104 ** on the second iteration */
drh1a58fe02008-12-20 02:06:13 +00001105 assert( j==1 );
drh7a5bcc02013-01-16 17:08:58 +00001106 assert( IsPowerOfTwo(chngToIN) );
drh70d18342013-06-06 19:16:33 +00001107 assert( chngToIN==getMask(&pWInfo->sMaskSet, iCursor) );
drh1a58fe02008-12-20 02:06:13 +00001108 break;
1109 }
drh4e8be3b2009-06-08 17:11:08 +00001110 testcase( j==1 );
1111
1112 /* We have found a candidate table and column. Check to see if that
1113 ** table and column is common to every term in the OR clause */
drh1a58fe02008-12-20 02:06:13 +00001114 okToChngToIN = 1;
1115 for(; i>=0 && okToChngToIN; i--, pOrTerm++){
drh7a5bcc02013-01-16 17:08:58 +00001116 assert( pOrTerm->eOperator & WO_EQ );
drh1a58fe02008-12-20 02:06:13 +00001117 if( pOrTerm->leftCursor!=iCursor ){
1118 pOrTerm->wtFlags &= ~TERM_OR_OK;
1119 }else if( pOrTerm->u.leftColumn!=iColumn ){
1120 okToChngToIN = 0;
1121 }else{
1122 int affLeft, affRight;
1123 /* If the right-hand side is also a column, then the affinities
1124 ** of both right and left sides must be such that no type
1125 ** conversions are required on the right. (Ticket #2249)
1126 */
1127 affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
1128 affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
1129 if( affRight!=0 && affRight!=affLeft ){
1130 okToChngToIN = 0;
1131 }else{
1132 pOrTerm->wtFlags |= TERM_OR_OK;
1133 }
1134 }
1135 }
1136 }
1137
1138 /* At this point, okToChngToIN is true if original pTerm satisfies
1139 ** case 1. In that case, construct a new virtual term that is
1140 ** pTerm converted into an IN operator.
1141 */
1142 if( okToChngToIN ){
1143 Expr *pDup; /* A transient duplicate expression */
1144 ExprList *pList = 0; /* The RHS of the IN operator */
1145 Expr *pLeft = 0; /* The LHS of the IN operator */
1146 Expr *pNew; /* The complete IN operator */
1147
1148 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
1149 if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
drh7a5bcc02013-01-16 17:08:58 +00001150 assert( pOrTerm->eOperator & WO_EQ );
drh1a58fe02008-12-20 02:06:13 +00001151 assert( pOrTerm->leftCursor==iCursor );
1152 assert( pOrTerm->u.leftColumn==iColumn );
danielk19776ab3a2e2009-02-19 14:39:25 +00001153 pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
drh70d18342013-06-06 19:16:33 +00001154 pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
drh1a58fe02008-12-20 02:06:13 +00001155 pLeft = pOrTerm->pExpr->pLeft;
1156 }
1157 assert( pLeft!=0 );
danielk19776ab3a2e2009-02-19 14:39:25 +00001158 pDup = sqlite3ExprDup(db, pLeft, 0);
drhb7916a72009-05-27 10:31:29 +00001159 pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
drh1a58fe02008-12-20 02:06:13 +00001160 if( pNew ){
1161 int idxNew;
1162 transferJoinMarkings(pNew, pExpr);
danielk19776ab3a2e2009-02-19 14:39:25 +00001163 assert( !ExprHasProperty(pNew, EP_xIsSelect) );
1164 pNew->x.pList = pList;
drh1a58fe02008-12-20 02:06:13 +00001165 idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
1166 testcase( idxNew==0 );
1167 exprAnalyze(pSrc, pWC, idxNew);
1168 pTerm = &pWC->a[idxTerm];
drh9769efc2014-10-24 14:32:21 +00001169 markTermAsChild(pWC, idxNew, idxTerm);
drh1a58fe02008-12-20 02:06:13 +00001170 }else{
1171 sqlite3ExprListDelete(db, pList);
1172 }
drh84266362015-03-16 12:13:31 +00001173 pTerm->eOperator = WO_NOOP; /* case 1 trumps case 3 */
drh1a58fe02008-12-20 02:06:13 +00001174 }
drh3e355802007-02-23 23:13:33 +00001175 }
drh3e355802007-02-23 23:13:33 +00001176}
1177#endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
drh54a167d2005-11-26 14:08:07 +00001178
drh7a5bcc02013-01-16 17:08:58 +00001179/*
drh0aa74ed2005-07-16 13:33:20 +00001180** The input to this routine is an WhereTerm structure with only the
drh51147ba2005-07-23 22:59:55 +00001181** "pExpr" field filled in. The job of this routine is to analyze the
drh0aa74ed2005-07-16 13:33:20 +00001182** subexpression and populate all the other fields of the WhereTerm
drh75897232000-05-29 14:26:00 +00001183** structure.
drh51147ba2005-07-23 22:59:55 +00001184**
1185** If the expression is of the form "<expr> <op> X" it gets commuted
drh1a58fe02008-12-20 02:06:13 +00001186** to the standard form of "X <op> <expr>".
1187**
1188** If the expression is of the form "X <op> Y" where both X and Y are
1189** columns, then the original expression is unchanged and a new virtual
1190** term of the form "Y <op> X" is added to the WHERE clause and
1191** analyzed separately. The original term is marked with TERM_COPIED
1192** and the new term is marked with TERM_DYNAMIC (because it's pExpr
1193** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
1194** is a commuted copy of a prior term.) The original term has nChild=1
1195** and the copy has idxParent set to the index of the original term.
drh75897232000-05-29 14:26:00 +00001196*/
drh0fcef5e2005-07-19 17:38:22 +00001197static void exprAnalyze(
1198 SrcList *pSrc, /* the FROM clause */
drh9eb20282005-08-24 03:52:18 +00001199 WhereClause *pWC, /* the WHERE clause */
1200 int idxTerm /* Index of the term to be analyzed */
drh0fcef5e2005-07-19 17:38:22 +00001201){
drh70d18342013-06-06 19:16:33 +00001202 WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
drh1a58fe02008-12-20 02:06:13 +00001203 WhereTerm *pTerm; /* The term to be analyzed */
drh111a6a72008-12-21 03:51:16 +00001204 WhereMaskSet *pMaskSet; /* Set of table index masks */
drh1a58fe02008-12-20 02:06:13 +00001205 Expr *pExpr; /* The expression to be analyzed */
1206 Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */
1207 Bitmask prereqAll; /* Prerequesites of pExpr */
drh5e767c52010-02-25 04:15:47 +00001208 Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */
drh1d452e12009-11-01 19:26:59 +00001209 Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */
1210 int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */
drha9c18a92015-03-06 20:49:52 +00001211 int noCase = 0; /* uppercase equivalent to lowercase */
drh1a58fe02008-12-20 02:06:13 +00001212 int op; /* Top-level operator. pExpr->op */
drh70d18342013-06-06 19:16:33 +00001213 Parse *pParse = pWInfo->pParse; /* Parsing context */
drh1a58fe02008-12-20 02:06:13 +00001214 sqlite3 *db = pParse->db; /* Database connection */
drh0fcef5e2005-07-19 17:38:22 +00001215
drhf998b732007-11-26 13:36:00 +00001216 if( db->mallocFailed ){
1217 return;
1218 }
1219 pTerm = &pWC->a[idxTerm];
drh70d18342013-06-06 19:16:33 +00001220 pMaskSet = &pWInfo->sMaskSet;
drh7ee751d2012-12-19 15:53:51 +00001221 pExpr = pTerm->pExpr;
1222 assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
drh0fcef5e2005-07-19 17:38:22 +00001223 prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
drh50b39962006-10-28 00:28:09 +00001224 op = pExpr->op;
1225 if( op==TK_IN ){
drhf5b11382005-09-17 13:07:13 +00001226 assert( pExpr->pRight==0 );
danielk19776ab3a2e2009-02-19 14:39:25 +00001227 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
1228 pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
1229 }else{
1230 pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
1231 }
drh50b39962006-10-28 00:28:09 +00001232 }else if( op==TK_ISNULL ){
1233 pTerm->prereqRight = 0;
drhf5b11382005-09-17 13:07:13 +00001234 }else{
1235 pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
1236 }
drh22d6a532005-09-19 21:05:48 +00001237 prereqAll = exprTableUsage(pMaskSet, pExpr);
1238 if( ExprHasProperty(pExpr, EP_FromJoin) ){
drh42165be2008-03-26 14:56:34 +00001239 Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
1240 prereqAll |= x;
drhdafc0ce2008-04-17 19:14:02 +00001241 extraRight = x-1; /* ON clause terms may not be used with an index
1242 ** on left table of a LEFT JOIN. Ticket #3015 */
drh22d6a532005-09-19 21:05:48 +00001243 }
1244 pTerm->prereqAll = prereqAll;
drh0fcef5e2005-07-19 17:38:22 +00001245 pTerm->leftCursor = -1;
drh45b1ee42005-08-02 17:48:22 +00001246 pTerm->iParent = -1;
drhb52076c2006-01-23 13:22:09 +00001247 pTerm->eOperator = 0;
drh738fc792013-01-17 15:05:17 +00001248 if( allowedOp(op) ){
drh7a66da12012-12-07 20:31:11 +00001249 Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
1250 Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
drh738fc792013-01-17 15:05:17 +00001251 u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
drh0fcef5e2005-07-19 17:38:22 +00001252 if( pLeft->op==TK_COLUMN ){
1253 pTerm->leftCursor = pLeft->iTable;
drh700a2262008-12-17 19:22:15 +00001254 pTerm->u.leftColumn = pLeft->iColumn;
drh738fc792013-01-17 15:05:17 +00001255 pTerm->eOperator = operatorMask(op) & opMask;
drh75897232000-05-29 14:26:00 +00001256 }
drh0fcef5e2005-07-19 17:38:22 +00001257 if( pRight && pRight->op==TK_COLUMN ){
1258 WhereTerm *pNew;
1259 Expr *pDup;
drh7a5bcc02013-01-16 17:08:58 +00001260 u16 eExtraOp = 0; /* Extra bits for pNew->eOperator */
drh0fcef5e2005-07-19 17:38:22 +00001261 if( pTerm->leftCursor>=0 ){
drh9eb20282005-08-24 03:52:18 +00001262 int idxNew;
danielk19776ab3a2e2009-02-19 14:39:25 +00001263 pDup = sqlite3ExprDup(db, pExpr, 0);
drh17435752007-08-16 04:30:38 +00001264 if( db->mallocFailed ){
drh633e6d52008-07-28 19:34:53 +00001265 sqlite3ExprDelete(db, pDup);
drh28f45912006-10-18 23:26:38 +00001266 return;
1267 }
drh9eb20282005-08-24 03:52:18 +00001268 idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
1269 if( idxNew==0 ) return;
1270 pNew = &pWC->a[idxNew];
drh9769efc2014-10-24 14:32:21 +00001271 markTermAsChild(pWC, idxNew, idxTerm);
drh9eb20282005-08-24 03:52:18 +00001272 pTerm = &pWC->a[idxTerm];
drh165be382008-12-05 02:36:33 +00001273 pTerm->wtFlags |= TERM_COPIED;
drheb5bc922013-01-17 16:43:33 +00001274 if( pExpr->op==TK_EQ
1275 && !ExprHasProperty(pExpr, EP_FromJoin)
1276 && OptimizationEnabled(db, SQLITE_Transitive)
1277 ){
drh7a5bcc02013-01-16 17:08:58 +00001278 pTerm->eOperator |= WO_EQUIV;
1279 eExtraOp = WO_EQUIV;
1280 }
drh0fcef5e2005-07-19 17:38:22 +00001281 }else{
1282 pDup = pExpr;
1283 pNew = pTerm;
1284 }
drh7d10d5a2008-08-20 16:35:10 +00001285 exprCommute(pParse, pDup);
drhfb76f5a2012-12-08 14:16:47 +00001286 pLeft = sqlite3ExprSkipCollate(pDup->pLeft);
drh0fcef5e2005-07-19 17:38:22 +00001287 pNew->leftCursor = pLeft->iTable;
drh700a2262008-12-17 19:22:15 +00001288 pNew->u.leftColumn = pLeft->iColumn;
drh5e767c52010-02-25 04:15:47 +00001289 testcase( (prereqLeft | extraRight) != prereqLeft );
1290 pNew->prereqRight = prereqLeft | extraRight;
drh0fcef5e2005-07-19 17:38:22 +00001291 pNew->prereqAll = prereqAll;
drh738fc792013-01-17 15:05:17 +00001292 pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
drh75897232000-05-29 14:26:00 +00001293 }
1294 }
drhed378002005-07-28 23:12:08 +00001295
drhd2687b72005-08-12 22:56:09 +00001296#ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
drhed378002005-07-28 23:12:08 +00001297 /* If a term is the BETWEEN operator, create two new virtual terms
drh1a58fe02008-12-20 02:06:13 +00001298 ** that define the range that the BETWEEN implements. For example:
1299 **
1300 ** a BETWEEN b AND c
1301 **
1302 ** is converted into:
1303 **
1304 ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
1305 **
1306 ** The two new terms are added onto the end of the WhereClause object.
1307 ** The new terms are "dynamic" and are children of the original BETWEEN
1308 ** term. That means that if the BETWEEN term is coded, the children are
1309 ** skipped. Or, if the children are satisfied by an index, the original
1310 ** BETWEEN term is skipped.
drhed378002005-07-28 23:12:08 +00001311 */
drh29435252008-12-28 18:35:08 +00001312 else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
danielk19776ab3a2e2009-02-19 14:39:25 +00001313 ExprList *pList = pExpr->x.pList;
drhed378002005-07-28 23:12:08 +00001314 int i;
1315 static const u8 ops[] = {TK_GE, TK_LE};
1316 assert( pList!=0 );
1317 assert( pList->nExpr==2 );
1318 for(i=0; i<2; i++){
1319 Expr *pNewExpr;
drh9eb20282005-08-24 03:52:18 +00001320 int idxNew;
drhb7916a72009-05-27 10:31:29 +00001321 pNewExpr = sqlite3PExpr(pParse, ops[i],
1322 sqlite3ExprDup(db, pExpr->pLeft, 0),
danielk19776ab3a2e2009-02-19 14:39:25 +00001323 sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
drhd41d39f2013-08-28 16:27:01 +00001324 transferJoinMarkings(pNewExpr, pExpr);
drh9eb20282005-08-24 03:52:18 +00001325 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
drh6a1e0712008-12-05 15:24:15 +00001326 testcase( idxNew==0 );
drh7b4fc6a2007-02-06 13:26:32 +00001327 exprAnalyze(pSrc, pWC, idxNew);
drh9eb20282005-08-24 03:52:18 +00001328 pTerm = &pWC->a[idxTerm];
drh9769efc2014-10-24 14:32:21 +00001329 markTermAsChild(pWC, idxNew, idxTerm);
drhed378002005-07-28 23:12:08 +00001330 }
drhed378002005-07-28 23:12:08 +00001331 }
drhd2687b72005-08-12 22:56:09 +00001332#endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
drhed378002005-07-28 23:12:08 +00001333
danielk19771576cd92006-01-14 08:02:28 +00001334#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
drh1a58fe02008-12-20 02:06:13 +00001335 /* Analyze a term that is composed of two or more subterms connected by
1336 ** an OR operator.
drh6c30be82005-07-29 15:10:17 +00001337 */
1338 else if( pExpr->op==TK_OR ){
drh29435252008-12-28 18:35:08 +00001339 assert( pWC->op==TK_AND );
drh1a58fe02008-12-20 02:06:13 +00001340 exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
danielk1977f51d1bd2009-07-31 06:14:51 +00001341 pTerm = &pWC->a[idxTerm];
drh6c30be82005-07-29 15:10:17 +00001342 }
drhd2687b72005-08-12 22:56:09 +00001343#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
1344
1345#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
1346 /* Add constraints to reduce the search space on a LIKE or GLOB
1347 ** operator.
drh9f504ea2008-02-23 21:55:39 +00001348 **
drha9c18a92015-03-06 20:49:52 +00001349 ** A like pattern of the form "x LIKE 'aBc%'" is changed into constraints
drh9f504ea2008-02-23 21:55:39 +00001350 **
drha9c18a92015-03-06 20:49:52 +00001351 ** x>='ABC' AND x<'abd' AND x LIKE 'aBc%'
drh9f504ea2008-02-23 21:55:39 +00001352 **
1353 ** The last character of the prefix "abc" is incremented to form the
drha9c18a92015-03-06 20:49:52 +00001354 ** termination condition "abd". If case is not significant (the default
1355 ** for LIKE) then the lower-bound is made all uppercase and the upper-
1356 ** bound is made all lowercase so that the bounds also work when comparing
1357 ** BLOBs.
drhd2687b72005-08-12 22:56:09 +00001358 */
dan937d0de2009-10-15 18:35:38 +00001359 if( pWC->op==TK_AND
1360 && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
1361 ){
drh1d452e12009-11-01 19:26:59 +00001362 Expr *pLeft; /* LHS of LIKE/GLOB operator */
1363 Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */
1364 Expr *pNewExpr1;
1365 Expr *pNewExpr2;
1366 int idxNew1;
1367 int idxNew2;
dan80103fc2015-03-20 08:43:59 +00001368 const char *zCollSeqName; /* Name of collating sequence */
drh8f1a7ed2015-03-06 19:47:38 +00001369 const u16 wtFlags = TERM_LIKEOPT | TERM_VIRTUAL | TERM_DYNAMIC;
drh9eb20282005-08-24 03:52:18 +00001370
danielk19776ab3a2e2009-02-19 14:39:25 +00001371 pLeft = pExpr->x.pList->a[1].pExpr;
danielk19776ab3a2e2009-02-19 14:39:25 +00001372 pStr2 = sqlite3ExprDup(db, pStr1, 0);
drh8f1a7ed2015-03-06 19:47:38 +00001373
1374 /* Convert the lower bound to upper-case and the upper bound to
1375 ** lower-case (upper-case is less than lower-case in ASCII) so that
1376 ** the range constraints also work for BLOBs
1377 */
1378 if( noCase && !pParse->db->mallocFailed ){
1379 int i;
1380 char c;
drha9c18a92015-03-06 20:49:52 +00001381 pTerm->wtFlags |= TERM_LIKE;
drh8f1a7ed2015-03-06 19:47:38 +00001382 for(i=0; (c = pStr1->u.zToken[i])!=0; i++){
1383 pStr1->u.zToken[i] = sqlite3Toupper(c);
1384 pStr2->u.zToken[i] = sqlite3Tolower(c);
1385 }
1386 }
1387
drhf998b732007-11-26 13:36:00 +00001388 if( !db->mallocFailed ){
drh254993e2009-06-08 19:44:36 +00001389 u8 c, *pC; /* Last character before the first wildcard */
dan937d0de2009-10-15 18:35:38 +00001390 pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
drh9f504ea2008-02-23 21:55:39 +00001391 c = *pC;
drh02a50b72008-05-26 18:33:40 +00001392 if( noCase ){
drh254993e2009-06-08 19:44:36 +00001393 /* The point is to increment the last character before the first
1394 ** wildcard. But if we increment '@', that will push it into the
1395 ** alphabetic range where case conversions will mess up the
1396 ** inequality. To avoid this, make sure to also run the full
1397 ** LIKE on all candidate expressions by clearing the isComplete flag
1398 */
drh39759742013-08-02 23:40:45 +00001399 if( c=='A'-1 ) isComplete = 0;
drh02a50b72008-05-26 18:33:40 +00001400 c = sqlite3UpperToLower[c];
1401 }
drh9f504ea2008-02-23 21:55:39 +00001402 *pC = c + 1;
drhd2687b72005-08-12 22:56:09 +00001403 }
dan80103fc2015-03-20 08:43:59 +00001404 zCollSeqName = noCase ? "NOCASE" : "BINARY";
drhae80dde2012-12-06 21:16:43 +00001405 pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
drh8f1a7ed2015-03-06 19:47:38 +00001406 pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
dan80103fc2015-03-20 08:43:59 +00001407 sqlite3ExprAddCollateString(pParse,pNewExpr1,zCollSeqName),
drhae80dde2012-12-06 21:16:43 +00001408 pStr1, 0);
drhd41d39f2013-08-28 16:27:01 +00001409 transferJoinMarkings(pNewExpr1, pExpr);
drh8f1a7ed2015-03-06 19:47:38 +00001410 idxNew1 = whereClauseInsert(pWC, pNewExpr1, wtFlags);
drh6a1e0712008-12-05 15:24:15 +00001411 testcase( idxNew1==0 );
drh7b4fc6a2007-02-06 13:26:32 +00001412 exprAnalyze(pSrc, pWC, idxNew1);
drhae80dde2012-12-06 21:16:43 +00001413 pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
drh8342e492010-07-22 17:49:52 +00001414 pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
dan80103fc2015-03-20 08:43:59 +00001415 sqlite3ExprAddCollateString(pParse,pNewExpr2,zCollSeqName),
drhae80dde2012-12-06 21:16:43 +00001416 pStr2, 0);
drhd41d39f2013-08-28 16:27:01 +00001417 transferJoinMarkings(pNewExpr2, pExpr);
drh8f1a7ed2015-03-06 19:47:38 +00001418 idxNew2 = whereClauseInsert(pWC, pNewExpr2, wtFlags);
drh6a1e0712008-12-05 15:24:15 +00001419 testcase( idxNew2==0 );
drh7b4fc6a2007-02-06 13:26:32 +00001420 exprAnalyze(pSrc, pWC, idxNew2);
drh9eb20282005-08-24 03:52:18 +00001421 pTerm = &pWC->a[idxTerm];
drhd2687b72005-08-12 22:56:09 +00001422 if( isComplete ){
drh9769efc2014-10-24 14:32:21 +00001423 markTermAsChild(pWC, idxNew1, idxTerm);
1424 markTermAsChild(pWC, idxNew2, idxTerm);
drhd2687b72005-08-12 22:56:09 +00001425 }
1426 }
1427#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
drh7f375902006-06-13 17:38:59 +00001428
1429#ifndef SQLITE_OMIT_VIRTUALTABLE
1430 /* Add a WO_MATCH auxiliary term to the constraint set if the
1431 ** current expression is of the form: column MATCH expr.
1432 ** This information is used by the xBestIndex methods of
1433 ** virtual tables. The native query optimizer does not attempt
1434 ** to do anything with MATCH functions.
1435 */
1436 if( isMatchOfColumn(pExpr) ){
1437 int idxNew;
1438 Expr *pRight, *pLeft;
1439 WhereTerm *pNewTerm;
1440 Bitmask prereqColumn, prereqExpr;
1441
danielk19776ab3a2e2009-02-19 14:39:25 +00001442 pRight = pExpr->x.pList->a[0].pExpr;
1443 pLeft = pExpr->x.pList->a[1].pExpr;
drh7f375902006-06-13 17:38:59 +00001444 prereqExpr = exprTableUsage(pMaskSet, pRight);
1445 prereqColumn = exprTableUsage(pMaskSet, pLeft);
1446 if( (prereqExpr & prereqColumn)==0 ){
drh1a90e092006-06-14 22:07:10 +00001447 Expr *pNewExpr;
drhb7916a72009-05-27 10:31:29 +00001448 pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
1449 0, sqlite3ExprDup(db, pRight, 0), 0);
drh1a90e092006-06-14 22:07:10 +00001450 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
drh6a1e0712008-12-05 15:24:15 +00001451 testcase( idxNew==0 );
drh7f375902006-06-13 17:38:59 +00001452 pNewTerm = &pWC->a[idxNew];
1453 pNewTerm->prereqRight = prereqExpr;
1454 pNewTerm->leftCursor = pLeft->iTable;
drh700a2262008-12-17 19:22:15 +00001455 pNewTerm->u.leftColumn = pLeft->iColumn;
drh7f375902006-06-13 17:38:59 +00001456 pNewTerm->eOperator = WO_MATCH;
drh9769efc2014-10-24 14:32:21 +00001457 markTermAsChild(pWC, idxNew, idxTerm);
drhd2ca60d2006-06-27 02:36:58 +00001458 pTerm = &pWC->a[idxTerm];
drh165be382008-12-05 02:36:33 +00001459 pTerm->wtFlags |= TERM_COPIED;
drh7f375902006-06-13 17:38:59 +00001460 pNewTerm->prereqAll = pTerm->prereqAll;
1461 }
1462 }
1463#endif /* SQLITE_OMIT_VIRTUALTABLE */
drhdafc0ce2008-04-17 19:14:02 +00001464
drh1435a9a2013-08-27 23:15:44 +00001465#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drhd3ed7342011-09-21 00:09:41 +00001466 /* When sqlite_stat3 histogram data is available an operator of the
drh534230c2011-01-22 00:10:45 +00001467 ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
1468 ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a
1469 ** virtual term of that form.
1470 **
1471 ** Note that the virtual term must be tagged with TERM_VNULL. This
1472 ** TERM_VNULL tag will suppress the not-null check at the beginning
1473 ** of the loop. Without the TERM_VNULL flag, the not-null check at
1474 ** the start of the loop will prevent any results from being returned.
1475 */
drhea6dc442011-04-08 21:35:26 +00001476 if( pExpr->op==TK_NOTNULL
1477 && pExpr->pLeft->op==TK_COLUMN
1478 && pExpr->pLeft->iColumn>=0
drhd7d71472014-10-22 19:57:16 +00001479 && OptimizationEnabled(db, SQLITE_Stat34)
drhea6dc442011-04-08 21:35:26 +00001480 ){
drh534230c2011-01-22 00:10:45 +00001481 Expr *pNewExpr;
1482 Expr *pLeft = pExpr->pLeft;
1483 int idxNew;
1484 WhereTerm *pNewTerm;
1485
1486 pNewExpr = sqlite3PExpr(pParse, TK_GT,
1487 sqlite3ExprDup(db, pLeft, 0),
1488 sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
1489
1490 idxNew = whereClauseInsert(pWC, pNewExpr,
1491 TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
drhda91e712011-02-11 06:59:02 +00001492 if( idxNew ){
1493 pNewTerm = &pWC->a[idxNew];
1494 pNewTerm->prereqRight = 0;
1495 pNewTerm->leftCursor = pLeft->iTable;
1496 pNewTerm->u.leftColumn = pLeft->iColumn;
1497 pNewTerm->eOperator = WO_GT;
drh9769efc2014-10-24 14:32:21 +00001498 markTermAsChild(pWC, idxNew, idxTerm);
drhda91e712011-02-11 06:59:02 +00001499 pTerm = &pWC->a[idxTerm];
drhda91e712011-02-11 06:59:02 +00001500 pTerm->wtFlags |= TERM_COPIED;
1501 pNewTerm->prereqAll = pTerm->prereqAll;
1502 }
drh534230c2011-01-22 00:10:45 +00001503 }
drh1435a9a2013-08-27 23:15:44 +00001504#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
drh534230c2011-01-22 00:10:45 +00001505
drhdafc0ce2008-04-17 19:14:02 +00001506 /* Prevent ON clause terms of a LEFT JOIN from being used to drive
1507 ** an index for tables to the left of the join.
1508 */
1509 pTerm->prereqRight |= extraRight;
drh75897232000-05-29 14:26:00 +00001510}
1511
drh7b4fc6a2007-02-06 13:26:32 +00001512/*
peter.d.reid60ec9142014-09-06 16:39:46 +00001513** This function searches pList for an entry that matches the iCol-th column
drh3b48e8c2013-06-12 20:18:16 +00001514** of index pIdx.
dan6f343962011-07-01 18:26:40 +00001515**
1516** If such an expression is found, its index in pList->a[] is returned. If
1517** no expression is found, -1 is returned.
1518*/
1519static int findIndexCol(
1520 Parse *pParse, /* Parse context */
1521 ExprList *pList, /* Expression list to search */
1522 int iBase, /* Cursor for table associated with pIdx */
1523 Index *pIdx, /* Index to match column of */
1524 int iCol /* Column of index to match */
1525){
1526 int i;
1527 const char *zColl = pIdx->azColl[iCol];
1528
1529 for(i=0; i<pList->nExpr; i++){
drh580c8c12012-12-08 03:34:04 +00001530 Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
drhf1d3e322011-07-09 13:00:41 +00001531 if( p->op==TK_COLUMN
1532 && p->iColumn==pIdx->aiColumn[iCol]
1533 && p->iTable==iBase
1534 ){
drh580c8c12012-12-08 03:34:04 +00001535 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
drh65df68e2015-04-15 05:31:02 +00001536 if( pColl && 0==sqlite3StrICmp(pColl->zName, zColl) ){
dan6f343962011-07-01 18:26:40 +00001537 return i;
1538 }
1539 }
1540 }
1541
1542 return -1;
1543}
1544
1545/*
dan6f343962011-07-01 18:26:40 +00001546** Return true if the DISTINCT expression-list passed as the third argument
drh4f402f22013-06-11 18:59:38 +00001547** is redundant.
1548**
drh3b48e8c2013-06-12 20:18:16 +00001549** A DISTINCT list is redundant if the database contains some subset of
drh4f402f22013-06-11 18:59:38 +00001550** columns that are unique and non-null.
dan6f343962011-07-01 18:26:40 +00001551*/
1552static int isDistinctRedundant(
drh4f402f22013-06-11 18:59:38 +00001553 Parse *pParse, /* Parsing context */
1554 SrcList *pTabList, /* The FROM clause */
1555 WhereClause *pWC, /* The WHERE clause */
1556 ExprList *pDistinct /* The result set that needs to be DISTINCT */
dan6f343962011-07-01 18:26:40 +00001557){
1558 Table *pTab;
1559 Index *pIdx;
1560 int i;
1561 int iBase;
1562
1563 /* If there is more than one table or sub-select in the FROM clause of
1564 ** this query, then it will not be possible to show that the DISTINCT
1565 ** clause is redundant. */
1566 if( pTabList->nSrc!=1 ) return 0;
1567 iBase = pTabList->a[0].iCursor;
1568 pTab = pTabList->a[0].pTab;
1569
dan94e08d92011-07-02 06:44:05 +00001570 /* If any of the expressions is an IPK column on table iBase, then return
1571 ** true. Note: The (p->iTable==iBase) part of this test may be false if the
1572 ** current SELECT is a correlated sub-query.
1573 */
dan6f343962011-07-01 18:26:40 +00001574 for(i=0; i<pDistinct->nExpr; i++){
drh580c8c12012-12-08 03:34:04 +00001575 Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
dan94e08d92011-07-02 06:44:05 +00001576 if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
dan6f343962011-07-01 18:26:40 +00001577 }
1578
1579 /* Loop through all indices on the table, checking each to see if it makes
1580 ** the DISTINCT qualifier redundant. It does so if:
1581 **
1582 ** 1. The index is itself UNIQUE, and
1583 **
1584 ** 2. All of the columns in the index are either part of the pDistinct
1585 ** list, or else the WHERE clause contains a term of the form "col=X",
1586 ** where X is a constant value. The collation sequences of the
1587 ** comparison and select-list expressions must match those of the index.
dan6a36f432012-04-20 16:59:24 +00001588 **
1589 ** 3. All of those index columns for which the WHERE clause does not
1590 ** contain a "col=X" term are subject to a NOT NULL constraint.
dan6f343962011-07-01 18:26:40 +00001591 */
1592 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
drh5f1d1d92014-07-31 22:59:04 +00001593 if( !IsUniqueIndex(pIdx) ) continue;
drhbbbdc832013-10-22 18:01:40 +00001594 for(i=0; i<pIdx->nKeyCol; i++){
1595 i16 iCol = pIdx->aiColumn[i];
dan6a36f432012-04-20 16:59:24 +00001596 if( 0==findTerm(pWC, iBase, iCol, ~(Bitmask)0, WO_EQ, pIdx) ){
1597 int iIdxCol = findIndexCol(pParse, pDistinct, iBase, pIdx, i);
drhbbbdc832013-10-22 18:01:40 +00001598 if( iIdxCol<0 || pTab->aCol[iCol].notNull==0 ){
dan6a36f432012-04-20 16:59:24 +00001599 break;
1600 }
dan6f343962011-07-01 18:26:40 +00001601 }
1602 }
drhbbbdc832013-10-22 18:01:40 +00001603 if( i==pIdx->nKeyCol ){
dan6f343962011-07-01 18:26:40 +00001604 /* This index implies that the DISTINCT qualifier is redundant. */
1605 return 1;
1606 }
1607 }
1608
1609 return 0;
1610}
drh0fcef5e2005-07-19 17:38:22 +00001611
drh8636e9c2013-06-11 01:50:08 +00001612
drh75897232000-05-29 14:26:00 +00001613/*
drh3b48e8c2013-06-12 20:18:16 +00001614** Estimate the logarithm of the input value to base 2.
drh28c4cf42005-07-27 20:41:43 +00001615*/
drhbf539c42013-10-05 18:16:02 +00001616static LogEst estLog(LogEst N){
drh696964d2014-06-12 15:46:46 +00001617 return N<=10 ? 0 : sqlite3LogEst(N) - 33;
drh28c4cf42005-07-27 20:41:43 +00001618}
1619
drh6d209d82006-06-27 01:54:26 +00001620/*
1621** Two routines for printing the content of an sqlite3_index_info
1622** structure. Used for testing and debugging only. If neither
1623** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
1624** are no-ops.
1625*/
drhd15cb172013-05-21 19:23:10 +00001626#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
drh6d209d82006-06-27 01:54:26 +00001627static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
1628 int i;
mlcreech3a00f902008-03-04 17:45:01 +00001629 if( !sqlite3WhereTrace ) return;
drh6d209d82006-06-27 01:54:26 +00001630 for(i=0; i<p->nConstraint; i++){
1631 sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
1632 i,
1633 p->aConstraint[i].iColumn,
1634 p->aConstraint[i].iTermOffset,
1635 p->aConstraint[i].op,
1636 p->aConstraint[i].usable);
1637 }
1638 for(i=0; i<p->nOrderBy; i++){
1639 sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n",
1640 i,
1641 p->aOrderBy[i].iColumn,
1642 p->aOrderBy[i].desc);
1643 }
1644}
1645static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
1646 int i;
mlcreech3a00f902008-03-04 17:45:01 +00001647 if( !sqlite3WhereTrace ) return;
drh6d209d82006-06-27 01:54:26 +00001648 for(i=0; i<p->nConstraint; i++){
1649 sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n",
1650 i,
1651 p->aConstraintUsage[i].argvIndex,
1652 p->aConstraintUsage[i].omit);
1653 }
1654 sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum);
1655 sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr);
1656 sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed);
1657 sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost);
dana9f58152013-11-11 19:01:33 +00001658 sqlite3DebugPrintf(" estimatedRows=%lld\n", p->estimatedRows);
drh6d209d82006-06-27 01:54:26 +00001659}
1660#else
1661#define TRACE_IDX_INPUTS(A)
1662#define TRACE_IDX_OUTPUTS(A)
1663#endif
1664
drhc6339082010-04-07 16:54:58 +00001665#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
drh8b307fb2010-04-06 15:57:05 +00001666/*
drh4139c992010-04-07 14:59:45 +00001667** Return TRUE if the WHERE clause term pTerm is of a form where it
1668** could be used with an index to access pSrc, assuming an appropriate
1669** index existed.
1670*/
1671static int termCanDriveIndex(
1672 WhereTerm *pTerm, /* WHERE clause term to check */
1673 struct SrcList_item *pSrc, /* Table we are trying to access */
1674 Bitmask notReady /* Tables in outer loops of the join */
1675){
1676 char aff;
1677 if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
drh7a5bcc02013-01-16 17:08:58 +00001678 if( (pTerm->eOperator & WO_EQ)==0 ) return 0;
drh4139c992010-04-07 14:59:45 +00001679 if( (pTerm->prereqRight & notReady)!=0 ) return 0;
drh23f98da2013-05-21 15:52:07 +00001680 if( pTerm->u.leftColumn<0 ) return 0;
drh4139c992010-04-07 14:59:45 +00001681 aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
1682 if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
1683 return 1;
1684}
drhc6339082010-04-07 16:54:58 +00001685#endif
drh4139c992010-04-07 14:59:45 +00001686
drhc6339082010-04-07 16:54:58 +00001687
1688#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
drh8b307fb2010-04-06 15:57:05 +00001689/*
drhc6339082010-04-07 16:54:58 +00001690** Generate code to construct the Index object for an automatic index
1691** and to set up the WhereLevel object pLevel so that the code generator
1692** makes use of the automatic index.
drh8b307fb2010-04-06 15:57:05 +00001693*/
drhc6339082010-04-07 16:54:58 +00001694static void constructAutomaticIndex(
drh8b307fb2010-04-06 15:57:05 +00001695 Parse *pParse, /* The parsing context */
1696 WhereClause *pWC, /* The WHERE clause */
1697 struct SrcList_item *pSrc, /* The FROM clause term to get the next index */
1698 Bitmask notReady, /* Mask of cursors that are not available */
1699 WhereLevel *pLevel /* Write new index here */
1700){
drhbbbdc832013-10-22 18:01:40 +00001701 int nKeyCol; /* Number of columns in the constructed index */
drh8b307fb2010-04-06 15:57:05 +00001702 WhereTerm *pTerm; /* A single term of the WHERE clause */
1703 WhereTerm *pWCEnd; /* End of pWC->a[] */
drh8b307fb2010-04-06 15:57:05 +00001704 Index *pIdx; /* Object describing the transient index */
1705 Vdbe *v; /* Prepared statement under construction */
drh8b307fb2010-04-06 15:57:05 +00001706 int addrInit; /* Address of the initialization bypass jump */
1707 Table *pTable; /* The table being indexed */
drh8b307fb2010-04-06 15:57:05 +00001708 int addrTop; /* Top of the index fill loop */
1709 int regRecord; /* Register holding an index record */
1710 int n; /* Column counter */
drh4139c992010-04-07 14:59:45 +00001711 int i; /* Loop counter */
1712 int mxBitCol; /* Maximum column in pSrc->colUsed */
drh424aab82010-04-06 18:28:20 +00001713 CollSeq *pColl; /* Collating sequence to on a column */
drh7ba39a92013-05-30 17:43:19 +00001714 WhereLoop *pLoop; /* The Loop object */
drh77e57df2013-10-22 14:28:02 +00001715 char *zNotUsed; /* Extra space on the end of pIdx */
drh4139c992010-04-07 14:59:45 +00001716 Bitmask idxCols; /* Bitmap of columns used for indexing */
1717 Bitmask extraCols; /* Bitmap of additional columns */
drh8d56e202013-06-28 23:55:45 +00001718 u8 sentWarning = 0; /* True if a warnning has been issued */
drh059b2d52014-10-24 19:28:09 +00001719 Expr *pPartial = 0; /* Partial Index Expression */
1720 int iContinue = 0; /* Jump here to skip excluded rows */
drh8b307fb2010-04-06 15:57:05 +00001721
1722 /* Generate code to skip over the creation and initialization of the
1723 ** transient index on 2nd and subsequent iterations of the loop. */
1724 v = pParse->pVdbe;
1725 assert( v!=0 );
drh7d176102014-02-18 03:07:12 +00001726 addrInit = sqlite3CodeOnce(pParse); VdbeCoverage(v);
drh8b307fb2010-04-06 15:57:05 +00001727
drh4139c992010-04-07 14:59:45 +00001728 /* Count the number of columns that will be added to the index
1729 ** and used to match WHERE clause constraints */
drhbbbdc832013-10-22 18:01:40 +00001730 nKeyCol = 0;
drh424aab82010-04-06 18:28:20 +00001731 pTable = pSrc->pTab;
drh8b307fb2010-04-06 15:57:05 +00001732 pWCEnd = &pWC->a[pWC->nTerm];
drh7ba39a92013-05-30 17:43:19 +00001733 pLoop = pLevel->pWLoop;
drh4139c992010-04-07 14:59:45 +00001734 idxCols = 0;
drh81186b42013-06-18 01:52:41 +00001735 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
drh13cc90c2015-02-25 00:24:41 +00001736 Expr *pExpr = pTerm->pExpr;
1737 assert( !ExprHasProperty(pExpr, EP_FromJoin) /* prereq always non-zero */
1738 || pExpr->iRightJoinTable!=pSrc->iCursor /* for the right-hand */
1739 || pLoop->prereq!=0 ); /* table of a LEFT JOIN */
drh059b2d52014-10-24 19:28:09 +00001740 if( pLoop->prereq==0
drh051575c2014-10-25 12:28:25 +00001741 && (pTerm->wtFlags & TERM_VIRTUAL)==0
drh13cc90c2015-02-25 00:24:41 +00001742 && !ExprHasProperty(pExpr, EP_FromJoin)
1743 && sqlite3ExprIsTableConstant(pExpr, pSrc->iCursor) ){
drh059b2d52014-10-24 19:28:09 +00001744 pPartial = sqlite3ExprAnd(pParse->db, pPartial,
drh13cc90c2015-02-25 00:24:41 +00001745 sqlite3ExprDup(pParse->db, pExpr, 0));
drh059b2d52014-10-24 19:28:09 +00001746 }
drh4139c992010-04-07 14:59:45 +00001747 if( termCanDriveIndex(pTerm, pSrc, notReady) ){
1748 int iCol = pTerm->u.leftColumn;
drh7699d1c2013-06-04 12:42:29 +00001749 Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
drh52ff8ea2010-04-08 14:15:56 +00001750 testcase( iCol==BMS );
1751 testcase( iCol==BMS-1 );
drh8d56e202013-06-28 23:55:45 +00001752 if( !sentWarning ){
1753 sqlite3_log(SQLITE_WARNING_AUTOINDEX,
1754 "automatic index on %s(%s)", pTable->zName,
1755 pTable->aCol[iCol].zName);
1756 sentWarning = 1;
1757 }
drh0013e722010-04-08 00:40:15 +00001758 if( (idxCols & cMask)==0 ){
drh059b2d52014-10-24 19:28:09 +00001759 if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ){
1760 goto end_auto_index_create;
1761 }
drhbbbdc832013-10-22 18:01:40 +00001762 pLoop->aLTerm[nKeyCol++] = pTerm;
drh0013e722010-04-08 00:40:15 +00001763 idxCols |= cMask;
1764 }
drh8b307fb2010-04-06 15:57:05 +00001765 }
1766 }
drhbbbdc832013-10-22 18:01:40 +00001767 assert( nKeyCol>0 );
1768 pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol;
drh53b52f72013-05-31 11:57:39 +00001769 pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
drh986b3872013-06-28 21:12:20 +00001770 | WHERE_AUTO_INDEX;
drh4139c992010-04-07 14:59:45 +00001771
1772 /* Count the number of additional columns needed to create a
1773 ** covering index. A "covering index" is an index that contains all
1774 ** columns that are needed by the query. With a covering index, the
1775 ** original table never needs to be accessed. Automatic indices must
1776 ** be a covering index because the index will not be updated if the
1777 ** original table changes and the index and table cannot both be used
1778 ** if they go out of sync.
1779 */
drh7699d1c2013-06-04 12:42:29 +00001780 extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
drhc3ef4fa2014-10-28 15:58:50 +00001781 mxBitCol = MIN(BMS-1,pTable->nCol);
drh52ff8ea2010-04-08 14:15:56 +00001782 testcase( pTable->nCol==BMS-1 );
1783 testcase( pTable->nCol==BMS-2 );
drh4139c992010-04-07 14:59:45 +00001784 for(i=0; i<mxBitCol; i++){
drhbbbdc832013-10-22 18:01:40 +00001785 if( extraCols & MASKBIT(i) ) nKeyCol++;
drh4139c992010-04-07 14:59:45 +00001786 }
drh7699d1c2013-06-04 12:42:29 +00001787 if( pSrc->colUsed & MASKBIT(BMS-1) ){
drhbbbdc832013-10-22 18:01:40 +00001788 nKeyCol += pTable->nCol - BMS + 1;
drh4139c992010-04-07 14:59:45 +00001789 }
drh8b307fb2010-04-06 15:57:05 +00001790
1791 /* Construct the Index object to describe this index */
drhbbbdc832013-10-22 18:01:40 +00001792 pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed);
drh059b2d52014-10-24 19:28:09 +00001793 if( pIdx==0 ) goto end_auto_index_create;
drh7ba39a92013-05-30 17:43:19 +00001794 pLoop->u.btree.pIndex = pIdx;
drh8b307fb2010-04-06 15:57:05 +00001795 pIdx->zName = "auto-index";
drh424aab82010-04-06 18:28:20 +00001796 pIdx->pTable = pTable;
drh8b307fb2010-04-06 15:57:05 +00001797 n = 0;
drh0013e722010-04-08 00:40:15 +00001798 idxCols = 0;
drh8b307fb2010-04-06 15:57:05 +00001799 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
drh4139c992010-04-07 14:59:45 +00001800 if( termCanDriveIndex(pTerm, pSrc, notReady) ){
drh0013e722010-04-08 00:40:15 +00001801 int iCol = pTerm->u.leftColumn;
drh7699d1c2013-06-04 12:42:29 +00001802 Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
drh7963b0e2013-06-17 21:37:40 +00001803 testcase( iCol==BMS-1 );
1804 testcase( iCol==BMS );
drh0013e722010-04-08 00:40:15 +00001805 if( (idxCols & cMask)==0 ){
1806 Expr *pX = pTerm->pExpr;
1807 idxCols |= cMask;
1808 pIdx->aiColumn[n] = pTerm->u.leftColumn;
1809 pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
drh29031832015-04-15 07:34:25 +00001810 pIdx->azColl[n] = pColl ? pColl->zName : "BINARY";
drh0013e722010-04-08 00:40:15 +00001811 n++;
1812 }
drh8b307fb2010-04-06 15:57:05 +00001813 }
1814 }
drh7ba39a92013-05-30 17:43:19 +00001815 assert( (u32)n==pLoop->u.btree.nEq );
drh4139c992010-04-07 14:59:45 +00001816
drhc6339082010-04-07 16:54:58 +00001817 /* Add additional columns needed to make the automatic index into
1818 ** a covering index */
drh4139c992010-04-07 14:59:45 +00001819 for(i=0; i<mxBitCol; i++){
drh7699d1c2013-06-04 12:42:29 +00001820 if( extraCols & MASKBIT(i) ){
drh4139c992010-04-07 14:59:45 +00001821 pIdx->aiColumn[n] = i;
1822 pIdx->azColl[n] = "BINARY";
1823 n++;
1824 }
1825 }
drh7699d1c2013-06-04 12:42:29 +00001826 if( pSrc->colUsed & MASKBIT(BMS-1) ){
drh4139c992010-04-07 14:59:45 +00001827 for(i=BMS-1; i<pTable->nCol; i++){
1828 pIdx->aiColumn[n] = i;
1829 pIdx->azColl[n] = "BINARY";
1830 n++;
1831 }
1832 }
drhbbbdc832013-10-22 18:01:40 +00001833 assert( n==nKeyCol );
drh44156282013-10-23 22:23:03 +00001834 pIdx->aiColumn[n] = -1;
1835 pIdx->azColl[n] = "BINARY";
drh8b307fb2010-04-06 15:57:05 +00001836
drhc6339082010-04-07 16:54:58 +00001837 /* Create the automatic index */
drh8b307fb2010-04-06 15:57:05 +00001838 assert( pLevel->iIdxCur>=0 );
drha1f41242013-05-31 20:00:58 +00001839 pLevel->iIdxCur = pParse->nTab++;
drh2ec2fb22013-11-06 19:59:23 +00001840 sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1);
1841 sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
drha21a64d2010-04-06 22:33:55 +00001842 VdbeComment((v, "for %s", pTable->zName));
drh8b307fb2010-04-06 15:57:05 +00001843
drhc6339082010-04-07 16:54:58 +00001844 /* Fill the automatic index with content */
drh059b2d52014-10-24 19:28:09 +00001845 sqlite3ExprCachePush(pParse);
drh688852a2014-02-17 22:40:43 +00001846 addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v);
drh059b2d52014-10-24 19:28:09 +00001847 if( pPartial ){
1848 iContinue = sqlite3VdbeMakeLabel(v);
1849 sqlite3ExprIfFalse(pParse, pPartial, iContinue, SQLITE_JUMPIFNULL);
drh051575c2014-10-25 12:28:25 +00001850 pLoop->wsFlags |= WHERE_PARTIALIDX;
drh059b2d52014-10-24 19:28:09 +00001851 }
drh8b307fb2010-04-06 15:57:05 +00001852 regRecord = sqlite3GetTempReg(pParse);
drh1c2c0b72014-01-04 19:27:05 +00001853 sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0);
drh8b307fb2010-04-06 15:57:05 +00001854 sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
1855 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
drh059b2d52014-10-24 19:28:09 +00001856 if( pPartial ) sqlite3VdbeResolveLabel(v, iContinue);
drh688852a2014-02-17 22:40:43 +00001857 sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v);
drha21a64d2010-04-06 22:33:55 +00001858 sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
drh8b307fb2010-04-06 15:57:05 +00001859 sqlite3VdbeJumpHere(v, addrTop);
1860 sqlite3ReleaseTempReg(pParse, regRecord);
drh059b2d52014-10-24 19:28:09 +00001861 sqlite3ExprCachePop(pParse);
drh8b307fb2010-04-06 15:57:05 +00001862
1863 /* Jump here when skipping the initialization */
1864 sqlite3VdbeJumpHere(v, addrInit);
drh059b2d52014-10-24 19:28:09 +00001865
1866end_auto_index_create:
1867 sqlite3ExprDelete(pParse->db, pPartial);
drh8b307fb2010-04-06 15:57:05 +00001868}
drhc6339082010-04-07 16:54:58 +00001869#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
drh8b307fb2010-04-06 15:57:05 +00001870
drh9eff6162006-06-12 21:59:13 +00001871#ifndef SQLITE_OMIT_VIRTUALTABLE
1872/*
danielk19771d461462009-04-21 09:02:45 +00001873** Allocate and populate an sqlite3_index_info structure. It is the
1874** responsibility of the caller to eventually release the structure
1875** by passing the pointer returned by this function to sqlite3_free().
1876*/
drh5346e952013-05-08 14:14:26 +00001877static sqlite3_index_info *allocateIndexInfo(
1878 Parse *pParse,
1879 WhereClause *pWC,
1880 struct SrcList_item *pSrc,
1881 ExprList *pOrderBy
1882){
danielk19771d461462009-04-21 09:02:45 +00001883 int i, j;
1884 int nTerm;
1885 struct sqlite3_index_constraint *pIdxCons;
1886 struct sqlite3_index_orderby *pIdxOrderBy;
1887 struct sqlite3_index_constraint_usage *pUsage;
1888 WhereTerm *pTerm;
1889 int nOrderBy;
1890 sqlite3_index_info *pIdxInfo;
1891
danielk19771d461462009-04-21 09:02:45 +00001892 /* Count the number of possible WHERE clause constraints referring
1893 ** to this virtual table */
1894 for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
1895 if( pTerm->leftCursor != pSrc->iCursor ) continue;
drh7a5bcc02013-01-16 17:08:58 +00001896 assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
1897 testcase( pTerm->eOperator & WO_IN );
1898 testcase( pTerm->eOperator & WO_ISNULL );
dana4ff8252014-01-20 19:55:33 +00001899 testcase( pTerm->eOperator & WO_ALL );
1900 if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV))==0 ) continue;
drhb4256992011-08-02 01:57:39 +00001901 if( pTerm->wtFlags & TERM_VNULL ) continue;
danielk19771d461462009-04-21 09:02:45 +00001902 nTerm++;
1903 }
1904
1905 /* If the ORDER BY clause contains only columns in the current
1906 ** virtual table then allocate space for the aOrderBy part of
1907 ** the sqlite3_index_info structure.
1908 */
1909 nOrderBy = 0;
1910 if( pOrderBy ){
drh56f1b992012-09-25 14:29:39 +00001911 int n = pOrderBy->nExpr;
1912 for(i=0; i<n; i++){
danielk19771d461462009-04-21 09:02:45 +00001913 Expr *pExpr = pOrderBy->a[i].pExpr;
1914 if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
1915 }
drh56f1b992012-09-25 14:29:39 +00001916 if( i==n){
1917 nOrderBy = n;
danielk19771d461462009-04-21 09:02:45 +00001918 }
1919 }
1920
1921 /* Allocate the sqlite3_index_info structure
1922 */
1923 pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
1924 + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
1925 + sizeof(*pIdxOrderBy)*nOrderBy );
1926 if( pIdxInfo==0 ){
1927 sqlite3ErrorMsg(pParse, "out of memory");
danielk19771d461462009-04-21 09:02:45 +00001928 return 0;
1929 }
1930
1931 /* Initialize the structure. The sqlite3_index_info structure contains
1932 ** many fields that are declared "const" to prevent xBestIndex from
1933 ** changing them. We have to do some funky casting in order to
1934 ** initialize those fields.
1935 */
1936 pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
1937 pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
1938 pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
1939 *(int*)&pIdxInfo->nConstraint = nTerm;
1940 *(int*)&pIdxInfo->nOrderBy = nOrderBy;
1941 *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
1942 *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
1943 *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
1944 pUsage;
1945
1946 for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
drh281bbe22012-10-16 23:17:14 +00001947 u8 op;
danielk19771d461462009-04-21 09:02:45 +00001948 if( pTerm->leftCursor != pSrc->iCursor ) continue;
drh7a5bcc02013-01-16 17:08:58 +00001949 assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
1950 testcase( pTerm->eOperator & WO_IN );
1951 testcase( pTerm->eOperator & WO_ISNULL );
dana4ff8252014-01-20 19:55:33 +00001952 testcase( pTerm->eOperator & WO_ALL );
1953 if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV))==0 ) continue;
drhb4256992011-08-02 01:57:39 +00001954 if( pTerm->wtFlags & TERM_VNULL ) continue;
danielk19771d461462009-04-21 09:02:45 +00001955 pIdxCons[j].iColumn = pTerm->u.leftColumn;
1956 pIdxCons[j].iTermOffset = i;
drh7a5bcc02013-01-16 17:08:58 +00001957 op = (u8)pTerm->eOperator & WO_ALL;
drh281bbe22012-10-16 23:17:14 +00001958 if( op==WO_IN ) op = WO_EQ;
1959 pIdxCons[j].op = op;
danielk19771d461462009-04-21 09:02:45 +00001960 /* The direct assignment in the previous line is possible only because
1961 ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The
1962 ** following asserts verify this fact. */
1963 assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
1964 assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
1965 assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
1966 assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
1967 assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
1968 assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
drh281bbe22012-10-16 23:17:14 +00001969 assert( pTerm->eOperator & (WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
danielk19771d461462009-04-21 09:02:45 +00001970 j++;
1971 }
1972 for(i=0; i<nOrderBy; i++){
1973 Expr *pExpr = pOrderBy->a[i].pExpr;
1974 pIdxOrderBy[i].iColumn = pExpr->iColumn;
1975 pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
1976 }
1977
1978 return pIdxInfo;
1979}
1980
1981/*
1982** The table object reference passed as the second argument to this function
1983** must represent a virtual table. This function invokes the xBestIndex()
drh3b48e8c2013-06-12 20:18:16 +00001984** method of the virtual table with the sqlite3_index_info object that
1985** comes in as the 3rd argument to this function.
danielk19771d461462009-04-21 09:02:45 +00001986**
1987** If an error occurs, pParse is populated with an error message and a
1988** non-zero value is returned. Otherwise, 0 is returned and the output
1989** part of the sqlite3_index_info structure is left populated.
1990**
1991** Whether or not an error is returned, it is the responsibility of the
1992** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
1993** that this is required.
1994*/
1995static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
danielk1977595a5232009-07-24 17:58:53 +00001996 sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
danielk19771d461462009-04-21 09:02:45 +00001997 int i;
1998 int rc;
1999
danielk19771d461462009-04-21 09:02:45 +00002000 TRACE_IDX_INPUTS(p);
2001 rc = pVtab->pModule->xBestIndex(pVtab, p);
2002 TRACE_IDX_OUTPUTS(p);
danielk19771d461462009-04-21 09:02:45 +00002003
2004 if( rc!=SQLITE_OK ){
2005 if( rc==SQLITE_NOMEM ){
2006 pParse->db->mallocFailed = 1;
2007 }else if( !pVtab->zErrMsg ){
2008 sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
2009 }else{
2010 sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
2011 }
2012 }
drhb9755982010-07-24 16:34:37 +00002013 sqlite3_free(pVtab->zErrMsg);
danielk19771d461462009-04-21 09:02:45 +00002014 pVtab->zErrMsg = 0;
2015
2016 for(i=0; i<p->nConstraint; i++){
2017 if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
2018 sqlite3ErrorMsg(pParse,
2019 "table %s: xBestIndex returned an invalid plan", pTab->zName);
2020 }
2021 }
2022
2023 return pParse->nErr;
2024}
drh7ba39a92013-05-30 17:43:19 +00002025#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
danielk19771d461462009-04-21 09:02:45 +00002026
drh1435a9a2013-08-27 23:15:44 +00002027#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drh28c4cf42005-07-27 20:41:43 +00002028/*
drhfaacf172011-08-12 01:51:45 +00002029** Estimate the location of a particular key among all keys in an
2030** index. Store the results in aStat as follows:
drhe847d322011-01-20 02:56:37 +00002031**
dana3d0c132015-03-14 18:59:58 +00002032** aStat[0] Est. number of rows less than pRec
2033** aStat[1] Est. number of rows equal to pRec
dan02fa4692009-08-17 17:06:58 +00002034**
drh6d3f91d2014-11-05 19:26:12 +00002035** Return the index of the sample that is the smallest sample that
dana3d0c132015-03-14 18:59:58 +00002036** is greater than or equal to pRec. Note that this index is not an index
2037** into the aSample[] array - it is an index into a virtual set of samples
2038** based on the contents of aSample[] and the number of fields in record
2039** pRec.
dan02fa4692009-08-17 17:06:58 +00002040*/
drh6d3f91d2014-11-05 19:26:12 +00002041static int whereKeyStats(
dan02fa4692009-08-17 17:06:58 +00002042 Parse *pParse, /* Database connection */
2043 Index *pIdx, /* Index to consider domain of */
dan7a419232013-08-06 20:01:43 +00002044 UnpackedRecord *pRec, /* Vector of values to consider */
drhfaacf172011-08-12 01:51:45 +00002045 int roundUp, /* Round up if true. Round down if false */
2046 tRowcnt *aStat /* OUT: stats written here */
dan02fa4692009-08-17 17:06:58 +00002047){
danf52bb8d2013-08-03 20:24:58 +00002048 IndexSample *aSample = pIdx->aSample;
drhfbc38de2013-09-03 19:26:22 +00002049 int iCol; /* Index of required stats in anEq[] etc. */
dana3d0c132015-03-14 18:59:58 +00002050 int i; /* Index of first sample >= pRec */
2051 int iSample; /* Smallest sample larger than or equal to pRec */
dan84c309b2013-08-08 16:17:12 +00002052 int iMin = 0; /* Smallest sample not yet tested */
dan84c309b2013-08-08 16:17:12 +00002053 int iTest; /* Next sample to test */
2054 int res; /* Result of comparison operation */
dana3d0c132015-03-14 18:59:58 +00002055 int nField; /* Number of fields in pRec */
2056 tRowcnt iLower = 0; /* anLt[] + anEq[] of largest sample pRec is > */
dan02fa4692009-08-17 17:06:58 +00002057
drh4f991892013-10-11 15:05:05 +00002058#ifndef SQLITE_DEBUG
2059 UNUSED_PARAMETER( pParse );
2060#endif
drh7f594752013-12-03 19:49:55 +00002061 assert( pRec!=0 );
drh5c624862011-09-22 18:46:34 +00002062 assert( pIdx->nSample>0 );
dana3d0c132015-03-14 18:59:58 +00002063 assert( pRec->nField>0 && pRec->nField<=pIdx->nSampleCol );
2064
2065 /* Do a binary search to find the first sample greater than or equal
2066 ** to pRec. If pRec contains a single field, the set of samples to search
2067 ** is simply the aSample[] array. If the samples in aSample[] contain more
2068 ** than one fields, all fields following the first are ignored.
2069 **
2070 ** If pRec contains N fields, where N is more than one, then as well as the
2071 ** samples in aSample[] (truncated to N fields), the search also has to
2072 ** consider prefixes of those samples. For example, if the set of samples
2073 ** in aSample is:
2074 **
2075 ** aSample[0] = (a, 5)
2076 ** aSample[1] = (a, 10)
2077 ** aSample[2] = (b, 5)
2078 ** aSample[3] = (c, 100)
2079 ** aSample[4] = (c, 105)
2080 **
2081 ** Then the search space should ideally be the samples above and the
2082 ** unique prefixes [a], [b] and [c]. But since that is hard to organize,
2083 ** the code actually searches this set:
2084 **
2085 ** 0: (a)
2086 ** 1: (a, 5)
2087 ** 2: (a, 10)
2088 ** 3: (a, 10)
2089 ** 4: (b)
2090 ** 5: (b, 5)
2091 ** 6: (c)
2092 ** 7: (c, 100)
2093 ** 8: (c, 105)
2094 ** 9: (c, 105)
2095 **
2096 ** For each sample in the aSample[] array, N samples are present in the
2097 ** effective sample array. In the above, samples 0 and 1 are based on
2098 ** sample aSample[0]. Samples 2 and 3 on aSample[1] etc.
2099 **
2100 ** Often, sample i of each block of N effective samples has (i+1) fields.
2101 ** Except, each sample may be extended to ensure that it is greater than or
2102 ** equal to the previous sample in the array. For example, in the above,
2103 ** sample 2 is the first sample of a block of N samples, so at first it
2104 ** appears that it should be 1 field in size. However, that would make it
2105 ** smaller than sample 1, so the binary search would not work. As a result,
2106 ** it is extended to two fields. The duplicates that this creates do not
2107 ** cause any problems.
2108 */
2109 nField = pRec->nField;
2110 iCol = 0;
2111 iSample = pIdx->nSample * nField;
dan84c309b2013-08-08 16:17:12 +00002112 do{
dana3d0c132015-03-14 18:59:58 +00002113 int iSamp; /* Index in aSample[] of test sample */
2114 int n; /* Number of fields in test sample */
2115
2116 iTest = (iMin+iSample)/2;
2117 iSamp = iTest / nField;
2118 if( iSamp>0 ){
2119 /* The proposed effective sample is a prefix of sample aSample[iSamp].
2120 ** Specifically, the shortest prefix of at least (1 + iTest%nField)
2121 ** fields that is greater than the previous effective sample. */
2122 for(n=(iTest % nField) + 1; n<nField; n++){
2123 if( aSample[iSamp-1].anLt[n-1]!=aSample[iSamp].anLt[n-1] ) break;
2124 }
dan84c309b2013-08-08 16:17:12 +00002125 }else{
dana3d0c132015-03-14 18:59:58 +00002126 n = iTest + 1;
dan02fa4692009-08-17 17:06:58 +00002127 }
dana3d0c132015-03-14 18:59:58 +00002128
2129 pRec->nField = n;
2130 res = sqlite3VdbeRecordCompare(aSample[iSamp].n, aSample[iSamp].p, pRec);
2131 if( res<0 ){
2132 iLower = aSample[iSamp].anLt[n-1] + aSample[iSamp].anEq[n-1];
2133 iMin = iTest+1;
2134 }else if( res==0 && n<nField ){
2135 iLower = aSample[iSamp].anLt[n-1];
2136 iMin = iTest+1;
2137 res = -1;
2138 }else{
2139 iSample = iTest;
2140 iCol = n-1;
2141 }
2142 }while( res && iMin<iSample );
2143 i = iSample / nField;
drh51147ba2005-07-23 22:59:55 +00002144
dan84c309b2013-08-08 16:17:12 +00002145#ifdef SQLITE_DEBUG
2146 /* The following assert statements check that the binary search code
2147 ** above found the right answer. This block serves no purpose other
2148 ** than to invoke the asserts. */
dana3d0c132015-03-14 18:59:58 +00002149 if( pParse->db->mallocFailed==0 ){
2150 if( res==0 ){
2151 /* If (res==0) is true, then pRec must be equal to sample i. */
2152 assert( i<pIdx->nSample );
2153 assert( iCol==nField-1 );
2154 pRec->nField = nField;
2155 assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)
2156 || pParse->db->mallocFailed
2157 );
2158 }else{
2159 /* Unless i==pIdx->nSample, indicating that pRec is larger than
2160 ** all samples in the aSample[] array, pRec must be smaller than the
2161 ** (iCol+1) field prefix of sample i. */
2162 assert( i<=pIdx->nSample && i>=0 );
2163 pRec->nField = iCol+1;
2164 assert( i==pIdx->nSample
2165 || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0
2166 || pParse->db->mallocFailed );
2167
2168 /* if i==0 and iCol==0, then record pRec is smaller than all samples
2169 ** in the aSample[] array. Otherwise, if (iCol>0) then pRec must
2170 ** be greater than or equal to the (iCol) field prefix of sample i.
2171 ** If (i>0), then pRec must also be greater than sample (i-1). */
2172 if( iCol>0 ){
2173 pRec->nField = iCol;
2174 assert( sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)<=0
2175 || pParse->db->mallocFailed );
2176 }
2177 if( i>0 ){
2178 pRec->nField = nField;
2179 assert( sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0
2180 || pParse->db->mallocFailed );
2181 }
2182 }
drhfaacf172011-08-12 01:51:45 +00002183 }
dan84c309b2013-08-08 16:17:12 +00002184#endif /* ifdef SQLITE_DEBUG */
dan02fa4692009-08-17 17:06:58 +00002185
dan84c309b2013-08-08 16:17:12 +00002186 if( res==0 ){
dana3d0c132015-03-14 18:59:58 +00002187 /* Record pRec is equal to sample i */
2188 assert( iCol==nField-1 );
daneea568d2013-08-07 19:46:15 +00002189 aStat[0] = aSample[i].anLt[iCol];
2190 aStat[1] = aSample[i].anEq[iCol];
drhfaacf172011-08-12 01:51:45 +00002191 }else{
dana3d0c132015-03-14 18:59:58 +00002192 /* At this point, the (iCol+1) field prefix of aSample[i] is the first
2193 ** sample that is greater than pRec. Or, if i==pIdx->nSample then pRec
2194 ** is larger than all samples in the array. */
2195 tRowcnt iUpper, iGap;
2196 if( i>=pIdx->nSample ){
2197 iUpper = sqlite3LogEstToInt(pIdx->aiRowLogEst[0]);
drhfaacf172011-08-12 01:51:45 +00002198 }else{
dana3d0c132015-03-14 18:59:58 +00002199 iUpper = aSample[i].anLt[iCol];
drhfaacf172011-08-12 01:51:45 +00002200 }
dana3d0c132015-03-14 18:59:58 +00002201
drhfaacf172011-08-12 01:51:45 +00002202 if( iLower>=iUpper ){
2203 iGap = 0;
2204 }else{
2205 iGap = iUpper - iLower;
drhfaacf172011-08-12 01:51:45 +00002206 }
2207 if( roundUp ){
2208 iGap = (iGap*2)/3;
2209 }else{
2210 iGap = iGap/3;
2211 }
2212 aStat[0] = iLower + iGap;
dana3d0c132015-03-14 18:59:58 +00002213 aStat[1] = pIdx->aAvgEq[iCol];
dan02fa4692009-08-17 17:06:58 +00002214 }
dana3d0c132015-03-14 18:59:58 +00002215
2216 /* Restore the pRec->nField value before returning. */
2217 pRec->nField = nField;
drh6d3f91d2014-11-05 19:26:12 +00002218 return i;
dan02fa4692009-08-17 17:06:58 +00002219}
drh1435a9a2013-08-27 23:15:44 +00002220#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
dan937d0de2009-10-15 18:35:38 +00002221
2222/*
danaa9933c2014-04-24 20:04:49 +00002223** If it is not NULL, pTerm is a term that provides an upper or lower
2224** bound on a range scan. Without considering pTerm, it is estimated
2225** that the scan will visit nNew rows. This function returns the number
2226** estimated to be visited after taking pTerm into account.
2227**
2228** If the user explicitly specified a likelihood() value for this term,
2229** then the return value is the likelihood multiplied by the number of
2230** input rows. Otherwise, this function assumes that an "IS NOT NULL" term
2231** has a likelihood of 0.50, and any other term a likelihood of 0.25.
2232*/
2233static LogEst whereRangeAdjust(WhereTerm *pTerm, LogEst nNew){
2234 LogEst nRet = nNew;
2235 if( pTerm ){
2236 if( pTerm->truthProb<=0 ){
2237 nRet += pTerm->truthProb;
dan7de2a1f2014-04-28 20:11:20 +00002238 }else if( (pTerm->wtFlags & TERM_VNULL)==0 ){
danaa9933c2014-04-24 20:04:49 +00002239 nRet -= 20; assert( 20==sqlite3LogEst(4) );
2240 }
2241 }
2242 return nRet;
2243}
2244
mistachkin2d84ac42014-06-26 21:32:09 +00002245#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
danb0b82902014-06-26 20:21:46 +00002246/*
2247** This function is called to estimate the number of rows visited by a
2248** range-scan on a skip-scan index. For example:
2249**
2250** CREATE INDEX i1 ON t1(a, b, c);
2251** SELECT * FROM t1 WHERE a=? AND c BETWEEN ? AND ?;
2252**
2253** Value pLoop->nOut is currently set to the estimated number of rows
2254** visited for scanning (a=? AND b=?). This function reduces that estimate
2255** by some factor to account for the (c BETWEEN ? AND ?) expression based
2256** on the stat4 data for the index. this scan will be peformed multiple
2257** times (once for each (a,b) combination that matches a=?) is dealt with
2258** by the caller.
2259**
2260** It does this by scanning through all stat4 samples, comparing values
2261** extracted from pLower and pUpper with the corresponding column in each
2262** sample. If L and U are the number of samples found to be less than or
2263** equal to the values extracted from pLower and pUpper respectively, and
2264** N is the total number of samples, the pLoop->nOut value is adjusted
2265** as follows:
2266**
2267** nOut = nOut * ( min(U - L, 1) / N )
2268**
2269** If pLower is NULL, or a value cannot be extracted from the term, L is
2270** set to zero. If pUpper is NULL, or a value cannot be extracted from it,
2271** U is set to N.
2272**
2273** Normally, this function sets *pbDone to 1 before returning. However,
2274** if no value can be extracted from either pLower or pUpper (and so the
2275** estimate of the number of rows delivered remains unchanged), *pbDone
2276** is left as is.
2277**
2278** If an error occurs, an SQLite error code is returned. Otherwise,
2279** SQLITE_OK.
2280*/
2281static int whereRangeSkipScanEst(
2282 Parse *pParse, /* Parsing & code generating context */
2283 WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
2284 WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
2285 WhereLoop *pLoop, /* Update the .nOut value of this loop */
2286 int *pbDone /* Set to true if at least one expr. value extracted */
2287){
2288 Index *p = pLoop->u.btree.pIndex;
2289 int nEq = pLoop->u.btree.nEq;
2290 sqlite3 *db = pParse->db;
dan4e42ba42014-06-27 20:14:25 +00002291 int nLower = -1;
2292 int nUpper = p->nSample+1;
danb0b82902014-06-26 20:21:46 +00002293 int rc = SQLITE_OK;
drhd15f87e2014-07-24 22:41:20 +00002294 int iCol = p->aiColumn[nEq];
2295 u8 aff = iCol>=0 ? p->pTable->aCol[iCol].affinity : SQLITE_AFF_INTEGER;
danb0b82902014-06-26 20:21:46 +00002296 CollSeq *pColl;
2297
2298 sqlite3_value *p1 = 0; /* Value extracted from pLower */
2299 sqlite3_value *p2 = 0; /* Value extracted from pUpper */
2300 sqlite3_value *pVal = 0; /* Value extracted from record */
2301
2302 pColl = sqlite3LocateCollSeq(pParse, p->azColl[nEq]);
2303 if( pLower ){
2304 rc = sqlite3Stat4ValueFromExpr(pParse, pLower->pExpr->pRight, aff, &p1);
dan4e42ba42014-06-27 20:14:25 +00002305 nLower = 0;
danb0b82902014-06-26 20:21:46 +00002306 }
2307 if( pUpper && rc==SQLITE_OK ){
2308 rc = sqlite3Stat4ValueFromExpr(pParse, pUpper->pExpr->pRight, aff, &p2);
dan4e42ba42014-06-27 20:14:25 +00002309 nUpper = p2 ? 0 : p->nSample;
danb0b82902014-06-26 20:21:46 +00002310 }
2311
2312 if( p1 || p2 ){
2313 int i;
2314 int nDiff;
2315 for(i=0; rc==SQLITE_OK && i<p->nSample; i++){
2316 rc = sqlite3Stat4Column(db, p->aSample[i].p, p->aSample[i].n, nEq, &pVal);
2317 if( rc==SQLITE_OK && p1 ){
2318 int res = sqlite3MemCompare(p1, pVal, pColl);
dan4e42ba42014-06-27 20:14:25 +00002319 if( res>=0 ) nLower++;
danb0b82902014-06-26 20:21:46 +00002320 }
2321 if( rc==SQLITE_OK && p2 ){
2322 int res = sqlite3MemCompare(p2, pVal, pColl);
dan4e42ba42014-06-27 20:14:25 +00002323 if( res>=0 ) nUpper++;
danb0b82902014-06-26 20:21:46 +00002324 }
2325 }
danb0b82902014-06-26 20:21:46 +00002326 nDiff = (nUpper - nLower);
2327 if( nDiff<=0 ) nDiff = 1;
dan4e42ba42014-06-27 20:14:25 +00002328
2329 /* If there is both an upper and lower bound specified, and the
2330 ** comparisons indicate that they are close together, use the fallback
2331 ** method (assume that the scan visits 1/64 of the rows) for estimating
2332 ** the number of rows visited. Otherwise, estimate the number of rows
2333 ** using the method described in the header comment for this function. */
2334 if( nDiff!=1 || pUpper==0 || pLower==0 ){
2335 int nAdjust = (sqlite3LogEst(p->nSample) - sqlite3LogEst(nDiff));
2336 pLoop->nOut -= nAdjust;
2337 *pbDone = 1;
2338 WHERETRACE(0x10, ("range skip-scan regions: %u..%u adjust=%d est=%d\n",
danfa887452014-06-28 15:26:10 +00002339 nLower, nUpper, nAdjust*-1, pLoop->nOut));
dan4e42ba42014-06-27 20:14:25 +00002340 }
2341
danb0b82902014-06-26 20:21:46 +00002342 }else{
2343 assert( *pbDone==0 );
2344 }
2345
2346 sqlite3ValueFree(p1);
2347 sqlite3ValueFree(p2);
2348 sqlite3ValueFree(pVal);
2349
2350 return rc;
2351}
mistachkin2d84ac42014-06-26 21:32:09 +00002352#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
danb0b82902014-06-26 20:21:46 +00002353
danaa9933c2014-04-24 20:04:49 +00002354/*
dan02fa4692009-08-17 17:06:58 +00002355** This function is used to estimate the number of rows that will be visited
2356** by scanning an index for a range of values. The range may have an upper
2357** bound, a lower bound, or both. The WHERE clause terms that set the upper
2358** and lower bounds are represented by pLower and pUpper respectively. For
2359** example, assuming that index p is on t1(a):
2360**
2361** ... FROM t1 WHERE a > ? AND a < ? ...
2362** |_____| |_____|
2363** | |
2364** pLower pUpper
2365**
drh98cdf622009-08-20 18:14:42 +00002366** If either of the upper or lower bound is not present, then NULL is passed in
drhcdaca552009-08-20 13:45:07 +00002367** place of the corresponding WhereTerm.
dan02fa4692009-08-17 17:06:58 +00002368**
drh6d3f91d2014-11-05 19:26:12 +00002369** The value in (pBuilder->pNew->u.btree.nEq) is the number of the index
dan6cb8d762013-08-08 11:48:57 +00002370** column subject to the range constraint. Or, equivalently, the number of
2371** equality constraints optimized by the proposed index scan. For example,
2372** assuming index p is on t1(a, b), and the SQL query is:
dan02fa4692009-08-17 17:06:58 +00002373**
2374** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
2375**
dan6cb8d762013-08-08 11:48:57 +00002376** then nEq is set to 1 (as the range restricted column, b, is the second
2377** left-most column of the index). Or, if the query is:
dan02fa4692009-08-17 17:06:58 +00002378**
2379** ... FROM t1 WHERE a > ? AND a < ? ...
2380**
dan6cb8d762013-08-08 11:48:57 +00002381** then nEq is set to 0.
dan02fa4692009-08-17 17:06:58 +00002382**
drhbf539c42013-10-05 18:16:02 +00002383** When this function is called, *pnOut is set to the sqlite3LogEst() of the
dan6cb8d762013-08-08 11:48:57 +00002384** number of rows that the index scan is expected to visit without
drh6d3f91d2014-11-05 19:26:12 +00002385** considering the range constraints. If nEq is 0, then *pnOut is the number of
dan6cb8d762013-08-08 11:48:57 +00002386** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced)
peter.d.reid60ec9142014-09-06 16:39:46 +00002387** to account for the range constraints pLower and pUpper.
dan6cb8d762013-08-08 11:48:57 +00002388**
2389** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be
drh94aa7e02014-06-06 17:09:52 +00002390** used, a single range inequality reduces the search space by a factor of 4.
2391** and a pair of constraints (x>? AND x<?) reduces the expected number of
2392** rows visited by a factor of 64.
dan02fa4692009-08-17 17:06:58 +00002393*/
2394static int whereRangeScanEst(
drhcdaca552009-08-20 13:45:07 +00002395 Parse *pParse, /* Parsing & code generating context */
dan7a419232013-08-06 20:01:43 +00002396 WhereLoopBuilder *pBuilder,
drhcdaca552009-08-20 13:45:07 +00002397 WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
2398 WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
drh186ad8c2013-10-08 18:40:37 +00002399 WhereLoop *pLoop /* Modify the .nOut and maybe .rRun fields */
dan02fa4692009-08-17 17:06:58 +00002400){
dan69188d92009-08-19 08:18:32 +00002401 int rc = SQLITE_OK;
drh186ad8c2013-10-08 18:40:37 +00002402 int nOut = pLoop->nOut;
drhbf539c42013-10-05 18:16:02 +00002403 LogEst nNew;
dan69188d92009-08-19 08:18:32 +00002404
drh1435a9a2013-08-27 23:15:44 +00002405#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drh186ad8c2013-10-08 18:40:37 +00002406 Index *p = pLoop->u.btree.pIndex;
drh4f991892013-10-11 15:05:05 +00002407 int nEq = pLoop->u.btree.nEq;
dan02fa4692009-08-17 17:06:58 +00002408
drh6d3f91d2014-11-05 19:26:12 +00002409 if( p->nSample>0 && nEq<p->nSampleCol ){
danb0b82902014-06-26 20:21:46 +00002410 if( nEq==pBuilder->nRecValid ){
2411 UnpackedRecord *pRec = pBuilder->pRec;
2412 tRowcnt a[2];
2413 u8 aff;
drh98cdf622009-08-20 18:14:42 +00002414
danb0b82902014-06-26 20:21:46 +00002415 /* Variable iLower will be set to the estimate of the number of rows in
2416 ** the index that are less than the lower bound of the range query. The
2417 ** lower bound being the concatenation of $P and $L, where $P is the
2418 ** key-prefix formed by the nEq values matched against the nEq left-most
2419 ** columns of the index, and $L is the value in pLower.
2420 **
2421 ** Or, if pLower is NULL or $L cannot be extracted from it (because it
2422 ** is not a simple variable or literal value), the lower bound of the
2423 ** range is $P. Due to a quirk in the way whereKeyStats() works, even
2424 ** if $L is available, whereKeyStats() is called for both ($P) and
drh6d3f91d2014-11-05 19:26:12 +00002425 ** ($P:$L) and the larger of the two returned values is used.
danb0b82902014-06-26 20:21:46 +00002426 **
2427 ** Similarly, iUpper is to be set to the estimate of the number of rows
2428 ** less than the upper bound of the range query. Where the upper bound
2429 ** is either ($P) or ($P:$U). Again, even if $U is available, both values
2430 ** of iUpper are requested of whereKeyStats() and the smaller used.
drh6d3f91d2014-11-05 19:26:12 +00002431 **
2432 ** The number of rows between the two bounds is then just iUpper-iLower.
danb0b82902014-06-26 20:21:46 +00002433 */
drh6d3f91d2014-11-05 19:26:12 +00002434 tRowcnt iLower; /* Rows less than the lower bound */
2435 tRowcnt iUpper; /* Rows less than the upper bound */
2436 int iLwrIdx = -2; /* aSample[] for the lower bound */
2437 int iUprIdx = -1; /* aSample[] for the upper bound */
danb3c02e22013-08-08 19:38:40 +00002438
drhb34fc5b2014-08-28 17:20:37 +00002439 if( pRec ){
2440 testcase( pRec->nField!=pBuilder->nRecValid );
2441 pRec->nField = pBuilder->nRecValid;
2442 }
danb0b82902014-06-26 20:21:46 +00002443 if( nEq==p->nKeyCol ){
2444 aff = SQLITE_AFF_INTEGER;
dan7a419232013-08-06 20:01:43 +00002445 }else{
danb0b82902014-06-26 20:21:46 +00002446 aff = p->pTable->aCol[p->aiColumn[nEq]].affinity;
drhfaacf172011-08-12 01:51:45 +00002447 }
danb0b82902014-06-26 20:21:46 +00002448 /* Determine iLower and iUpper using ($P) only. */
2449 if( nEq==0 ){
2450 iLower = 0;
drh9f07cf72014-10-22 15:27:05 +00002451 iUpper = p->nRowEst0;
danb0b82902014-06-26 20:21:46 +00002452 }else{
2453 /* Note: this call could be optimized away - since the same values must
2454 ** have been requested when testing key $P in whereEqualScanEst(). */
2455 whereKeyStats(pParse, p, pRec, 0, a);
2456 iLower = a[0];
2457 iUpper = a[0] + a[1];
dan6cb8d762013-08-08 11:48:57 +00002458 }
danb0b82902014-06-26 20:21:46 +00002459
drh69afd992014-10-08 02:53:25 +00002460 assert( pLower==0 || (pLower->eOperator & (WO_GT|WO_GE))!=0 );
2461 assert( pUpper==0 || (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
drh681fca02014-10-10 15:01:46 +00002462 assert( p->aSortOrder!=0 );
2463 if( p->aSortOrder[nEq] ){
drh69afd992014-10-08 02:53:25 +00002464 /* The roles of pLower and pUpper are swapped for a DESC index */
2465 SWAP(WhereTerm*, pLower, pUpper);
2466 }
2467
danb0b82902014-06-26 20:21:46 +00002468 /* If possible, improve on the iLower estimate using ($P:$L). */
2469 if( pLower ){
2470 int bOk; /* True if value is extracted from pExpr */
2471 Expr *pExpr = pLower->pExpr->pRight;
danb0b82902014-06-26 20:21:46 +00002472 rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
2473 if( rc==SQLITE_OK && bOk ){
2474 tRowcnt iNew;
drh6d3f91d2014-11-05 19:26:12 +00002475 iLwrIdx = whereKeyStats(pParse, p, pRec, 0, a);
drh69afd992014-10-08 02:53:25 +00002476 iNew = a[0] + ((pLower->eOperator & (WO_GT|WO_LE)) ? a[1] : 0);
danb0b82902014-06-26 20:21:46 +00002477 if( iNew>iLower ) iLower = iNew;
2478 nOut--;
danf741e042014-08-25 18:29:38 +00002479 pLower = 0;
danb0b82902014-06-26 20:21:46 +00002480 }
2481 }
2482
2483 /* If possible, improve on the iUpper estimate using ($P:$U). */
2484 if( pUpper ){
2485 int bOk; /* True if value is extracted from pExpr */
2486 Expr *pExpr = pUpper->pExpr->pRight;
danb0b82902014-06-26 20:21:46 +00002487 rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
2488 if( rc==SQLITE_OK && bOk ){
2489 tRowcnt iNew;
drh6d3f91d2014-11-05 19:26:12 +00002490 iUprIdx = whereKeyStats(pParse, p, pRec, 1, a);
drh69afd992014-10-08 02:53:25 +00002491 iNew = a[0] + ((pUpper->eOperator & (WO_GT|WO_LE)) ? a[1] : 0);
danb0b82902014-06-26 20:21:46 +00002492 if( iNew<iUpper ) iUpper = iNew;
2493 nOut--;
danf741e042014-08-25 18:29:38 +00002494 pUpper = 0;
danb0b82902014-06-26 20:21:46 +00002495 }
2496 }
2497
2498 pBuilder->pRec = pRec;
2499 if( rc==SQLITE_OK ){
2500 if( iUpper>iLower ){
2501 nNew = sqlite3LogEst(iUpper - iLower);
drh6d3f91d2014-11-05 19:26:12 +00002502 /* TUNING: If both iUpper and iLower are derived from the same
2503 ** sample, then assume they are 4x more selective. This brings
2504 ** the estimated selectivity more in line with what it would be
2505 ** if estimated without the use of STAT3/4 tables. */
2506 if( iLwrIdx==iUprIdx ) nNew -= 20; assert( 20==sqlite3LogEst(4) );
danb0b82902014-06-26 20:21:46 +00002507 }else{
2508 nNew = 10; assert( 10==sqlite3LogEst(2) );
2509 }
2510 if( nNew<nOut ){
2511 nOut = nNew;
2512 }
drhae914d72014-08-28 19:38:22 +00002513 WHERETRACE(0x10, ("STAT4 range scan: %u..%u est=%d\n",
danb0b82902014-06-26 20:21:46 +00002514 (u32)iLower, (u32)iUpper, nOut));
danb0b82902014-06-26 20:21:46 +00002515 }
2516 }else{
2517 int bDone = 0;
2518 rc = whereRangeSkipScanEst(pParse, pLower, pUpper, pLoop, &bDone);
2519 if( bDone ) return rc;
drh98cdf622009-08-20 18:14:42 +00002520 }
dan02fa4692009-08-17 17:06:58 +00002521 }
drh3f022182009-09-09 16:10:50 +00002522#else
2523 UNUSED_PARAMETER(pParse);
dan7a419232013-08-06 20:01:43 +00002524 UNUSED_PARAMETER(pBuilder);
dan02fa4692009-08-17 17:06:58 +00002525 assert( pLower || pUpper );
danf741e042014-08-25 18:29:38 +00002526#endif
dan7de2a1f2014-04-28 20:11:20 +00002527 assert( pUpper==0 || (pUpper->wtFlags & TERM_VNULL)==0 );
danaa9933c2014-04-24 20:04:49 +00002528 nNew = whereRangeAdjust(pLower, nOut);
2529 nNew = whereRangeAdjust(pUpper, nNew);
dan7de2a1f2014-04-28 20:11:20 +00002530
drh4dd96a82014-10-24 15:26:29 +00002531 /* TUNING: If there is both an upper and lower limit and neither limit
2532 ** has an application-defined likelihood(), assume the range is
dan42685f22014-04-28 19:34:06 +00002533 ** reduced by an additional 75%. This means that, by default, an open-ended
2534 ** range query (e.g. col > ?) is assumed to match 1/4 of the rows in the
2535 ** index. While a closed range (e.g. col BETWEEN ? AND ?) is estimated to
2536 ** match 1/64 of the index. */
drh4dd96a82014-10-24 15:26:29 +00002537 if( pLower && pLower->truthProb>0 && pUpper && pUpper->truthProb>0 ){
2538 nNew -= 20;
2539 }
dan7de2a1f2014-04-28 20:11:20 +00002540
danaa9933c2014-04-24 20:04:49 +00002541 nOut -= (pLower!=0) + (pUpper!=0);
drhabfa6d52013-09-11 03:53:22 +00002542 if( nNew<10 ) nNew = 10;
2543 if( nNew<nOut ) nOut = nNew;
drhae914d72014-08-28 19:38:22 +00002544#if defined(WHERETRACE_ENABLED)
2545 if( pLoop->nOut>nOut ){
2546 WHERETRACE(0x10,("Range scan lowers nOut from %d to %d\n",
2547 pLoop->nOut, nOut));
2548 }
2549#endif
drh186ad8c2013-10-08 18:40:37 +00002550 pLoop->nOut = (LogEst)nOut;
dan02fa4692009-08-17 17:06:58 +00002551 return rc;
2552}
2553
drh1435a9a2013-08-27 23:15:44 +00002554#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drh82759752011-01-20 16:52:09 +00002555/*
2556** Estimate the number of rows that will be returned based on
2557** an equality constraint x=VALUE and where that VALUE occurs in
2558** the histogram data. This only works when x is the left-most
drhfaacf172011-08-12 01:51:45 +00002559** column of an index and sqlite_stat3 histogram data is available
drhac8eb112011-03-17 01:58:21 +00002560** for that index. When pExpr==NULL that means the constraint is
2561** "x IS NULL" instead of "x=VALUE".
drh82759752011-01-20 16:52:09 +00002562**
drh0c50fa02011-01-21 16:27:18 +00002563** Write the estimated row count into *pnRow and return SQLITE_OK.
2564** If unable to make an estimate, leave *pnRow unchanged and return
2565** non-zero.
drh9b3eb0a2011-01-21 14:37:04 +00002566**
2567** This routine can fail if it is unable to load a collating sequence
2568** required for string comparison, or if unable to allocate memory
2569** for a UTF conversion required for comparison. The error is stored
2570** in the pParse structure.
drh82759752011-01-20 16:52:09 +00002571*/
drh041e09f2011-04-07 19:56:21 +00002572static int whereEqualScanEst(
drh82759752011-01-20 16:52:09 +00002573 Parse *pParse, /* Parsing & code generating context */
dan7a419232013-08-06 20:01:43 +00002574 WhereLoopBuilder *pBuilder,
drh0c50fa02011-01-21 16:27:18 +00002575 Expr *pExpr, /* Expression for VALUE in the x=VALUE constraint */
drhb8a8e8a2013-06-10 19:12:39 +00002576 tRowcnt *pnRow /* Write the revised row estimate here */
drh82759752011-01-20 16:52:09 +00002577){
dan7a419232013-08-06 20:01:43 +00002578 Index *p = pBuilder->pNew->u.btree.pIndex;
2579 int nEq = pBuilder->pNew->u.btree.nEq;
2580 UnpackedRecord *pRec = pBuilder->pRec;
drh82759752011-01-20 16:52:09 +00002581 u8 aff; /* Column affinity */
2582 int rc; /* Subfunction return code */
drhfaacf172011-08-12 01:51:45 +00002583 tRowcnt a[2]; /* Statistics */
dan7a419232013-08-06 20:01:43 +00002584 int bOk;
drh82759752011-01-20 16:52:09 +00002585
dan7a419232013-08-06 20:01:43 +00002586 assert( nEq>=1 );
danfd984b82014-06-30 18:02:20 +00002587 assert( nEq<=p->nColumn );
drh82759752011-01-20 16:52:09 +00002588 assert( p->aSample!=0 );
drh5c624862011-09-22 18:46:34 +00002589 assert( p->nSample>0 );
dan7a419232013-08-06 20:01:43 +00002590 assert( pBuilder->nRecValid<nEq );
2591
2592 /* If values are not available for all fields of the index to the left
2593 ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */
2594 if( pBuilder->nRecValid<(nEq-1) ){
2595 return SQLITE_NOTFOUND;
drh1f9c7662011-03-17 01:34:26 +00002596 }
dan7a419232013-08-06 20:01:43 +00002597
dandd6e1f12013-08-10 19:08:30 +00002598 /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue()
2599 ** below would return the same value. */
danfd984b82014-06-30 18:02:20 +00002600 if( nEq>=p->nColumn ){
dan7a419232013-08-06 20:01:43 +00002601 *pnRow = 1;
2602 return SQLITE_OK;
drh82759752011-01-20 16:52:09 +00002603 }
dan7a419232013-08-06 20:01:43 +00002604
daneea568d2013-08-07 19:46:15 +00002605 aff = p->pTable->aCol[p->aiColumn[nEq-1]].affinity;
dan87cd9322013-08-07 15:52:41 +00002606 rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq-1, &bOk);
2607 pBuilder->pRec = pRec;
dan7a419232013-08-06 20:01:43 +00002608 if( rc!=SQLITE_OK ) return rc;
2609 if( bOk==0 ) return SQLITE_NOTFOUND;
dan7a419232013-08-06 20:01:43 +00002610 pBuilder->nRecValid = nEq;
dan7a419232013-08-06 20:01:43 +00002611
danb3c02e22013-08-08 19:38:40 +00002612 whereKeyStats(pParse, p, pRec, 0, a);
drh989578e2013-10-28 14:34:35 +00002613 WHERETRACE(0x10,("equality scan regions: %d\n", (int)a[1]));
danb3c02e22013-08-08 19:38:40 +00002614 *pnRow = a[1];
daneea568d2013-08-07 19:46:15 +00002615
drh0c50fa02011-01-21 16:27:18 +00002616 return rc;
2617}
drh1435a9a2013-08-27 23:15:44 +00002618#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
drh0c50fa02011-01-21 16:27:18 +00002619
drh1435a9a2013-08-27 23:15:44 +00002620#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drh0c50fa02011-01-21 16:27:18 +00002621/*
2622** Estimate the number of rows that will be returned based on
drh5ac06072011-01-21 18:18:13 +00002623** an IN constraint where the right-hand side of the IN operator
2624** is a list of values. Example:
2625**
2626** WHERE x IN (1,2,3,4)
drh0c50fa02011-01-21 16:27:18 +00002627**
2628** Write the estimated row count into *pnRow and return SQLITE_OK.
2629** If unable to make an estimate, leave *pnRow unchanged and return
2630** non-zero.
2631**
2632** This routine can fail if it is unable to load a collating sequence
2633** required for string comparison, or if unable to allocate memory
2634** for a UTF conversion required for comparison. The error is stored
2635** in the pParse structure.
2636*/
drh041e09f2011-04-07 19:56:21 +00002637static int whereInScanEst(
drh0c50fa02011-01-21 16:27:18 +00002638 Parse *pParse, /* Parsing & code generating context */
dan7a419232013-08-06 20:01:43 +00002639 WhereLoopBuilder *pBuilder,
drh0c50fa02011-01-21 16:27:18 +00002640 ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
drhb8a8e8a2013-06-10 19:12:39 +00002641 tRowcnt *pnRow /* Write the revised row estimate here */
drh0c50fa02011-01-21 16:27:18 +00002642){
dan7a419232013-08-06 20:01:43 +00002643 Index *p = pBuilder->pNew->u.btree.pIndex;
dancfc9df72014-04-25 15:01:01 +00002644 i64 nRow0 = sqlite3LogEstToInt(p->aiRowLogEst[0]);
dan7a419232013-08-06 20:01:43 +00002645 int nRecValid = pBuilder->nRecValid;
drhb8a8e8a2013-06-10 19:12:39 +00002646 int rc = SQLITE_OK; /* Subfunction return code */
2647 tRowcnt nEst; /* Number of rows for a single term */
2648 tRowcnt nRowEst = 0; /* New estimate of the number of rows */
2649 int i; /* Loop counter */
drh0c50fa02011-01-21 16:27:18 +00002650
2651 assert( p->aSample!=0 );
drhfaacf172011-08-12 01:51:45 +00002652 for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
dancfc9df72014-04-25 15:01:01 +00002653 nEst = nRow0;
dan7a419232013-08-06 20:01:43 +00002654 rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst);
drhfaacf172011-08-12 01:51:45 +00002655 nRowEst += nEst;
dan7a419232013-08-06 20:01:43 +00002656 pBuilder->nRecValid = nRecValid;
drh0c50fa02011-01-21 16:27:18 +00002657 }
dan7a419232013-08-06 20:01:43 +00002658
drh0c50fa02011-01-21 16:27:18 +00002659 if( rc==SQLITE_OK ){
dancfc9df72014-04-25 15:01:01 +00002660 if( nRowEst > nRow0 ) nRowEst = nRow0;
drh0c50fa02011-01-21 16:27:18 +00002661 *pnRow = nRowEst;
drh5418b122014-08-28 13:42:13 +00002662 WHERETRACE(0x10,("IN row estimate: est=%d\n", nRowEst));
drh0c50fa02011-01-21 16:27:18 +00002663 }
dan7a419232013-08-06 20:01:43 +00002664 assert( pBuilder->nRecValid==nRecValid );
drh0c50fa02011-01-21 16:27:18 +00002665 return rc;
drh82759752011-01-20 16:52:09 +00002666}
drh1435a9a2013-08-27 23:15:44 +00002667#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
drh82759752011-01-20 16:52:09 +00002668
drh46c35f92012-09-26 23:17:01 +00002669/*
drh2ffb1182004-07-19 19:14:01 +00002670** Disable a term in the WHERE clause. Except, do not disable the term
2671** if it controls a LEFT OUTER JOIN and it did not originate in the ON
2672** or USING clause of that join.
2673**
2674** Consider the term t2.z='ok' in the following queries:
2675**
2676** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
2677** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
2678** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
2679**
drh23bf66d2004-12-14 03:34:34 +00002680** The t2.z='ok' is disabled in the in (2) because it originates
drh2ffb1182004-07-19 19:14:01 +00002681** in the ON clause. The term is disabled in (3) because it is not part
2682** of a LEFT OUTER JOIN. In (1), the term is not disabled.
2683**
2684** Disabling a term causes that term to not be tested in the inner loop
drhb6fb62d2005-09-20 08:47:20 +00002685** of the join. Disabling is an optimization. When terms are satisfied
2686** by indices, we disable them to prevent redundant tests in the inner
2687** loop. We would get the correct results if nothing were ever disabled,
2688** but joins might run a little slower. The trick is to disable as much
2689** as we can without disabling too much. If we disabled in (1), we'd get
2690** the wrong answer. See ticket #813.
drh8f1a7ed2015-03-06 19:47:38 +00002691**
2692** If all the children of a term are disabled, then that term is also
2693** automatically disabled. In this way, terms get disabled if derived
2694** virtual terms are tested first. For example:
2695**
2696** x GLOB 'abc*' AND x>='abc' AND x<'acd'
2697** \___________/ \______/ \_____/
2698** parent child1 child2
2699**
2700** Only the parent term was in the original WHERE clause. The child1
2701** and child2 terms were added by the LIKE optimization. If both of
2702** the virtual child terms are valid, then testing of the parent can be
2703** skipped.
drha9c18a92015-03-06 20:49:52 +00002704**
2705** Usually the parent term is marked as TERM_CODED. But if the parent
2706** term was originally TERM_LIKE, then the parent gets TERM_LIKECOND instead.
2707** The TERM_LIKECOND marking indicates that the term should be coded inside
2708** a conditional such that is only evaluated on the second pass of a
2709** LIKE-optimization loop, when scanning BLOBs instead of strings.
drh2ffb1182004-07-19 19:14:01 +00002710*/
drh0fcef5e2005-07-19 17:38:22 +00002711static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
drh8f1a7ed2015-03-06 19:47:38 +00002712 int nLoop = 0;
2713 while( pTerm
drhbe837bd2010-04-30 21:03:24 +00002714 && (pTerm->wtFlags & TERM_CODED)==0
drh0fcef5e2005-07-19 17:38:22 +00002715 && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
drh0259bc32013-09-09 19:37:46 +00002716 && (pLevel->notReady & pTerm->prereqAll)==0
drh0fcef5e2005-07-19 17:38:22 +00002717 ){
drh8f1a7ed2015-03-06 19:47:38 +00002718 if( nLoop && (pTerm->wtFlags & TERM_LIKE)!=0 ){
2719 pTerm->wtFlags |= TERM_LIKECOND;
2720 }else{
2721 pTerm->wtFlags |= TERM_CODED;
drh0fcef5e2005-07-19 17:38:22 +00002722 }
drh8f1a7ed2015-03-06 19:47:38 +00002723 if( pTerm->iParent<0 ) break;
2724 pTerm = &pTerm->pWC->a[pTerm->iParent];
2725 pTerm->nChild--;
2726 if( pTerm->nChild!=0 ) break;
2727 nLoop++;
drh2ffb1182004-07-19 19:14:01 +00002728 }
2729}
2730
2731/*
dan69f8bb92009-08-13 19:21:16 +00002732** Code an OP_Affinity opcode to apply the column affinity string zAff
2733** to the n registers starting at base.
2734**
drh039fc322009-11-17 18:31:47 +00002735** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
2736** beginning and end of zAff are ignored. If all entries in zAff are
2737** SQLITE_AFF_NONE, then no code gets generated.
2738**
2739** This routine makes its own copy of zAff so that the caller is free
2740** to modify zAff after this routine returns.
drh94a11212004-09-25 13:12:14 +00002741*/
dan69f8bb92009-08-13 19:21:16 +00002742static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
2743 Vdbe *v = pParse->pVdbe;
drh039fc322009-11-17 18:31:47 +00002744 if( zAff==0 ){
2745 assert( pParse->db->mallocFailed );
2746 return;
2747 }
dan69f8bb92009-08-13 19:21:16 +00002748 assert( v!=0 );
drh039fc322009-11-17 18:31:47 +00002749
2750 /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
2751 ** and end of the affinity string.
2752 */
2753 while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
2754 n--;
2755 base++;
2756 zAff++;
2757 }
2758 while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
2759 n--;
2760 }
2761
2762 /* Code the OP_Affinity opcode if there is anything left to do. */
2763 if( n>0 ){
2764 sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
2765 sqlite3VdbeChangeP4(v, -1, zAff, n);
2766 sqlite3ExprCacheAffinityChange(pParse, base, n);
2767 }
drh94a11212004-09-25 13:12:14 +00002768}
2769
drhe8b97272005-07-19 22:22:12 +00002770
2771/*
drh51147ba2005-07-23 22:59:55 +00002772** Generate code for a single equality term of the WHERE clause. An equality
2773** term can be either X=expr or X IN (...). pTerm is the term to be
2774** coded.
2775**
drh1db639c2008-01-17 02:36:28 +00002776** The current value for the constraint is left in register iReg.
drh51147ba2005-07-23 22:59:55 +00002777**
2778** For a constraint of the form X=expr, the expression is evaluated and its
2779** result is left on the stack. For constraints of the form X IN (...)
2780** this routine sets up a loop that will iterate over all values of X.
drh94a11212004-09-25 13:12:14 +00002781*/
drh678ccce2008-03-31 18:19:54 +00002782static int codeEqualityTerm(
drh94a11212004-09-25 13:12:14 +00002783 Parse *pParse, /* The parsing context */
drhe23399f2005-07-22 00:31:39 +00002784 WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
drh0fe456b2013-03-12 18:34:50 +00002785 WhereLevel *pLevel, /* The level of the FROM clause we are working on */
2786 int iEq, /* Index of the equality term within this level */
drh7ba39a92013-05-30 17:43:19 +00002787 int bRev, /* True for reverse-order IN operations */
drh678ccce2008-03-31 18:19:54 +00002788 int iTarget /* Attempt to leave results in this register */
drh94a11212004-09-25 13:12:14 +00002789){
drh0fcef5e2005-07-19 17:38:22 +00002790 Expr *pX = pTerm->pExpr;
drh50b39962006-10-28 00:28:09 +00002791 Vdbe *v = pParse->pVdbe;
drh678ccce2008-03-31 18:19:54 +00002792 int iReg; /* Register holding results */
drh1db639c2008-01-17 02:36:28 +00002793
danielk19772d605492008-10-01 08:43:03 +00002794 assert( iTarget>0 );
drh50b39962006-10-28 00:28:09 +00002795 if( pX->op==TK_EQ ){
drh678ccce2008-03-31 18:19:54 +00002796 iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
drh50b39962006-10-28 00:28:09 +00002797 }else if( pX->op==TK_ISNULL ){
drh678ccce2008-03-31 18:19:54 +00002798 iReg = iTarget;
drh1db639c2008-01-17 02:36:28 +00002799 sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
danielk1977b3bce662005-01-29 08:32:43 +00002800#ifndef SQLITE_OMIT_SUBQUERY
drh94a11212004-09-25 13:12:14 +00002801 }else{
danielk19779a96b662007-11-29 17:05:18 +00002802 int eType;
danielk1977b3bce662005-01-29 08:32:43 +00002803 int iTab;
drh72e8fa42007-03-28 14:30:06 +00002804 struct InLoop *pIn;
drh7ba39a92013-05-30 17:43:19 +00002805 WhereLoop *pLoop = pLevel->pWLoop;
danielk1977b3bce662005-01-29 08:32:43 +00002806
drh7ba39a92013-05-30 17:43:19 +00002807 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
2808 && pLoop->u.btree.pIndex!=0
2809 && pLoop->u.btree.pIndex->aSortOrder[iEq]
drhd3832162013-03-12 18:49:25 +00002810 ){
drh725e1ae2013-03-12 23:58:42 +00002811 testcase( iEq==0 );
drh725e1ae2013-03-12 23:58:42 +00002812 testcase( bRev );
drh1ccce442013-03-12 20:38:51 +00002813 bRev = !bRev;
drh0fe456b2013-03-12 18:34:50 +00002814 }
drh50b39962006-10-28 00:28:09 +00002815 assert( pX->op==TK_IN );
drh678ccce2008-03-31 18:19:54 +00002816 iReg = iTarget;
drh3a856252014-08-01 14:46:57 +00002817 eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0);
drh725e1ae2013-03-12 23:58:42 +00002818 if( eType==IN_INDEX_INDEX_DESC ){
2819 testcase( bRev );
2820 bRev = !bRev;
2821 }
danielk1977b3bce662005-01-29 08:32:43 +00002822 iTab = pX->iTable;
drh7d176102014-02-18 03:07:12 +00002823 sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
2824 VdbeCoverageIf(v, bRev);
2825 VdbeCoverageIf(v, !bRev);
drh6fa978d2013-05-30 19:29:19 +00002826 assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
2827 pLoop->wsFlags |= WHERE_IN_ABLE;
drh111a6a72008-12-21 03:51:16 +00002828 if( pLevel->u.in.nIn==0 ){
drhb3190c12008-12-08 21:37:14 +00002829 pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
drh72e8fa42007-03-28 14:30:06 +00002830 }
drh111a6a72008-12-21 03:51:16 +00002831 pLevel->u.in.nIn++;
2832 pLevel->u.in.aInLoop =
2833 sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
2834 sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
2835 pIn = pLevel->u.in.aInLoop;
drh72e8fa42007-03-28 14:30:06 +00002836 if( pIn ){
drh111a6a72008-12-21 03:51:16 +00002837 pIn += pLevel->u.in.nIn - 1;
drh72e8fa42007-03-28 14:30:06 +00002838 pIn->iCur = iTab;
drh1db639c2008-01-17 02:36:28 +00002839 if( eType==IN_INDEX_ROWID ){
drhb3190c12008-12-08 21:37:14 +00002840 pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
drh1db639c2008-01-17 02:36:28 +00002841 }else{
drhb3190c12008-12-08 21:37:14 +00002842 pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
drh1db639c2008-01-17 02:36:28 +00002843 }
drhf93cd942013-11-21 03:12:25 +00002844 pIn->eEndLoopOp = bRev ? OP_PrevIfOpen : OP_NextIfOpen;
drh688852a2014-02-17 22:40:43 +00002845 sqlite3VdbeAddOp1(v, OP_IsNull, iReg); VdbeCoverage(v);
drha6110402005-07-28 20:51:19 +00002846 }else{
drh111a6a72008-12-21 03:51:16 +00002847 pLevel->u.in.nIn = 0;
drhe23399f2005-07-22 00:31:39 +00002848 }
danielk1977b3bce662005-01-29 08:32:43 +00002849#endif
drh94a11212004-09-25 13:12:14 +00002850 }
drh0fcef5e2005-07-19 17:38:22 +00002851 disableTerm(pLevel, pTerm);
drh678ccce2008-03-31 18:19:54 +00002852 return iReg;
drh94a11212004-09-25 13:12:14 +00002853}
2854
drh51147ba2005-07-23 22:59:55 +00002855/*
2856** Generate code that will evaluate all == and IN constraints for an
drhcd8629e2013-11-13 12:27:25 +00002857** index scan.
drh51147ba2005-07-23 22:59:55 +00002858**
2859** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
2860** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
2861** The index has as many as three equality constraints, but in this
2862** example, the third "c" value is an inequality. So only two
2863** constraints are coded. This routine will generate code to evaluate
drh6df2acd2008-12-28 16:55:25 +00002864** a==5 and b IN (1,2,3). The current values for a and b will be stored
2865** in consecutive registers and the index of the first register is returned.
drh51147ba2005-07-23 22:59:55 +00002866**
2867** In the example above nEq==2. But this subroutine works for any value
2868** of nEq including 0. If nEq==0, this routine is nearly a no-op.
drh039fc322009-11-17 18:31:47 +00002869** The only thing it does is allocate the pLevel->iMem memory cell and
2870** compute the affinity string.
drh51147ba2005-07-23 22:59:55 +00002871**
drhcd8629e2013-11-13 12:27:25 +00002872** The nExtraReg parameter is 0 or 1. It is 0 if all WHERE clause constraints
2873** are == or IN and are covered by the nEq. nExtraReg is 1 if there is
2874** an inequality constraint (such as the "c>=5 AND c<10" in the example) that
2875** occurs after the nEq quality constraints.
2876**
2877** This routine allocates a range of nEq+nExtraReg memory cells and returns
2878** the index of the first memory cell in that range. The code that
2879** calls this routine will use that memory range to store keys for
2880** start and termination conditions of the loop.
drh51147ba2005-07-23 22:59:55 +00002881** key value of the loop. If one or more IN operators appear, then
2882** this routine allocates an additional nEq memory cells for internal
2883** use.
dan69f8bb92009-08-13 19:21:16 +00002884**
2885** Before returning, *pzAff is set to point to a buffer containing a
2886** copy of the column affinity string of the index allocated using
2887** sqlite3DbMalloc(). Except, entries in the copy of the string associated
2888** with equality constraints that use NONE affinity are set to
2889** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
2890**
2891** CREATE TABLE t1(a TEXT PRIMARY KEY, b);
2892** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
2893**
2894** In the example above, the index on t1(a) has TEXT affinity. But since
2895** the right hand side of the equality constraint (t2.b) has NONE affinity,
2896** no conversion should be attempted before using a t2.b value as part of
2897** a key to search the index. Hence the first byte in the returned affinity
2898** string in this example would be set to SQLITE_AFF_NONE.
drh51147ba2005-07-23 22:59:55 +00002899*/
drh1db639c2008-01-17 02:36:28 +00002900static int codeAllEqualityTerms(
drh51147ba2005-07-23 22:59:55 +00002901 Parse *pParse, /* Parsing context */
2902 WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
drh7ba39a92013-05-30 17:43:19 +00002903 int bRev, /* Reverse the order of IN operators */
dan69f8bb92009-08-13 19:21:16 +00002904 int nExtraReg, /* Number of extra registers to allocate */
2905 char **pzAff /* OUT: Set to point to affinity string */
drh51147ba2005-07-23 22:59:55 +00002906){
drhcd8629e2013-11-13 12:27:25 +00002907 u16 nEq; /* The number of == or IN constraints to code */
2908 u16 nSkip; /* Number of left-most columns to skip */
drh111a6a72008-12-21 03:51:16 +00002909 Vdbe *v = pParse->pVdbe; /* The vm under construction */
2910 Index *pIdx; /* The index being used for this loop */
drh51147ba2005-07-23 22:59:55 +00002911 WhereTerm *pTerm; /* A single constraint term */
drh7ba39a92013-05-30 17:43:19 +00002912 WhereLoop *pLoop; /* The WhereLoop object */
drh51147ba2005-07-23 22:59:55 +00002913 int j; /* Loop counter */
drh1db639c2008-01-17 02:36:28 +00002914 int regBase; /* Base register */
drh6df2acd2008-12-28 16:55:25 +00002915 int nReg; /* Number of registers to allocate */
dan69f8bb92009-08-13 19:21:16 +00002916 char *zAff; /* Affinity string to return */
drh51147ba2005-07-23 22:59:55 +00002917
drh111a6a72008-12-21 03:51:16 +00002918 /* This module is only called on query plans that use an index. */
drh7ba39a92013-05-30 17:43:19 +00002919 pLoop = pLevel->pWLoop;
2920 assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
2921 nEq = pLoop->u.btree.nEq;
drhc8bbce12014-10-21 01:05:09 +00002922 nSkip = pLoop->nSkip;
drh7ba39a92013-05-30 17:43:19 +00002923 pIdx = pLoop->u.btree.pIndex;
2924 assert( pIdx!=0 );
drh111a6a72008-12-21 03:51:16 +00002925
drh51147ba2005-07-23 22:59:55 +00002926 /* Figure out how many memory cells we will need then allocate them.
drh51147ba2005-07-23 22:59:55 +00002927 */
drh700a2262008-12-17 19:22:15 +00002928 regBase = pParse->nMem + 1;
drh7ba39a92013-05-30 17:43:19 +00002929 nReg = pLoop->u.btree.nEq + nExtraReg;
drh6df2acd2008-12-28 16:55:25 +00002930 pParse->nMem += nReg;
drh51147ba2005-07-23 22:59:55 +00002931
dan69f8bb92009-08-13 19:21:16 +00002932 zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
2933 if( !zAff ){
2934 pParse->db->mallocFailed = 1;
2935 }
2936
drhcd8629e2013-11-13 12:27:25 +00002937 if( nSkip ){
2938 int iIdxCur = pLevel->iIdxCur;
drh7d176102014-02-18 03:07:12 +00002939 sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur);
2940 VdbeCoverageIf(v, bRev==0);
2941 VdbeCoverageIf(v, bRev!=0);
drhe084f402013-11-13 17:24:38 +00002942 VdbeComment((v, "begin skip-scan on %s", pIdx->zName));
drh2e5ef4e2013-11-13 16:58:54 +00002943 j = sqlite3VdbeAddOp0(v, OP_Goto);
drh4a1d3652014-02-14 15:13:36 +00002944 pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT),
drh7d176102014-02-18 03:07:12 +00002945 iIdxCur, 0, regBase, nSkip);
2946 VdbeCoverageIf(v, bRev==0);
2947 VdbeCoverageIf(v, bRev!=0);
drh2e5ef4e2013-11-13 16:58:54 +00002948 sqlite3VdbeJumpHere(v, j);
drhcd8629e2013-11-13 12:27:25 +00002949 for(j=0; j<nSkip; j++){
2950 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, j, regBase+j);
2951 assert( pIdx->aiColumn[j]>=0 );
2952 VdbeComment((v, "%s", pIdx->pTable->aCol[pIdx->aiColumn[j]].zName));
2953 }
2954 }
2955
drh51147ba2005-07-23 22:59:55 +00002956 /* Evaluate the equality constraints
2957 */
mistachkinf6418892013-08-28 01:54:12 +00002958 assert( zAff==0 || (int)strlen(zAff)>=nEq );
drhcd8629e2013-11-13 12:27:25 +00002959 for(j=nSkip; j<nEq; j++){
drh678ccce2008-03-31 18:19:54 +00002960 int r1;
drh4efc9292013-06-06 23:02:03 +00002961 pTerm = pLoop->aLTerm[j];
drh7ba39a92013-05-30 17:43:19 +00002962 assert( pTerm!=0 );
drhcd8629e2013-11-13 12:27:25 +00002963 /* The following testcase is true for indices with redundant columns.
drhbe837bd2010-04-30 21:03:24 +00002964 ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
2965 testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
drh39759742013-08-02 23:40:45 +00002966 testcase( pTerm->wtFlags & TERM_VIRTUAL );
drh7ba39a92013-05-30 17:43:19 +00002967 r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
drh678ccce2008-03-31 18:19:54 +00002968 if( r1!=regBase+j ){
drh6df2acd2008-12-28 16:55:25 +00002969 if( nReg==1 ){
2970 sqlite3ReleaseTempReg(pParse, regBase);
2971 regBase = r1;
2972 }else{
2973 sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
2974 }
drh678ccce2008-03-31 18:19:54 +00002975 }
drh981642f2008-04-19 14:40:43 +00002976 testcase( pTerm->eOperator & WO_ISNULL );
2977 testcase( pTerm->eOperator & WO_IN );
drh72e8fa42007-03-28 14:30:06 +00002978 if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
drh039fc322009-11-17 18:31:47 +00002979 Expr *pRight = pTerm->pExpr->pRight;
drh7d176102014-02-18 03:07:12 +00002980 if( sqlite3ExprCanBeNull(pRight) ){
2981 sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk);
2982 VdbeCoverage(v);
2983 }
drh039fc322009-11-17 18:31:47 +00002984 if( zAff ){
2985 if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
2986 zAff[j] = SQLITE_AFF_NONE;
2987 }
2988 if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
2989 zAff[j] = SQLITE_AFF_NONE;
2990 }
dan69f8bb92009-08-13 19:21:16 +00002991 }
drh51147ba2005-07-23 22:59:55 +00002992 }
2993 }
dan69f8bb92009-08-13 19:21:16 +00002994 *pzAff = zAff;
drh1db639c2008-01-17 02:36:28 +00002995 return regBase;
drh51147ba2005-07-23 22:59:55 +00002996}
2997
dan6f9702e2014-11-01 20:38:06 +00002998#ifndef SQLITE_OMIT_EXPLAIN
dan17c0bc02010-11-09 17:35:19 +00002999/*
drh69174c42010-11-12 15:35:59 +00003000** This routine is a helper for explainIndexRange() below
3001**
3002** pStr holds the text of an expression that we are building up one term
3003** at a time. This routine adds a new term to the end of the expression.
3004** Terms are separated by AND so add the "AND" text for second and subsequent
3005** terms only.
3006*/
3007static void explainAppendTerm(
3008 StrAccum *pStr, /* The text expression being built */
3009 int iTerm, /* Index of this term. First is zero */
3010 const char *zColumn, /* Name of the column */
3011 const char *zOp /* Name of the operator */
3012){
3013 if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
drha6353a32013-12-09 19:03:26 +00003014 sqlite3StrAccumAppendAll(pStr, zColumn);
drh69174c42010-11-12 15:35:59 +00003015 sqlite3StrAccumAppend(pStr, zOp, 1);
3016 sqlite3StrAccumAppend(pStr, "?", 1);
3017}
3018
3019/*
dan17c0bc02010-11-09 17:35:19 +00003020** Argument pLevel describes a strategy for scanning table pTab. This
drh6c977892014-10-10 15:47:46 +00003021** function appends text to pStr that describes the subset of table
3022** rows scanned by the strategy in the form of an SQL expression.
dan17c0bc02010-11-09 17:35:19 +00003023**
3024** For example, if the query:
3025**
3026** SELECT * FROM t1 WHERE a=1 AND b>2;
3027**
3028** is run and there is an index on (a, b), then this function returns a
3029** string similar to:
3030**
3031** "a=? AND b>?"
dan17c0bc02010-11-09 17:35:19 +00003032*/
drh1f8817c2014-10-10 19:15:35 +00003033static void explainIndexRange(StrAccum *pStr, WhereLoop *pLoop, Table *pTab){
drhef866372013-05-22 20:49:02 +00003034 Index *pIndex = pLoop->u.btree.pIndex;
drhcd8629e2013-11-13 12:27:25 +00003035 u16 nEq = pLoop->u.btree.nEq;
drhc8bbce12014-10-21 01:05:09 +00003036 u16 nSkip = pLoop->nSkip;
drh69174c42010-11-12 15:35:59 +00003037 int i, j;
3038 Column *aCol = pTab->aCol;
drhbbbdc832013-10-22 18:01:40 +00003039 i16 *aiColumn = pIndex->aiColumn;
dan2ce22452010-11-08 19:01:16 +00003040
drh6c977892014-10-10 15:47:46 +00003041 if( nEq==0 && (pLoop->wsFlags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ) return;
3042 sqlite3StrAccumAppend(pStr, " (", 2);
dan2ce22452010-11-08 19:01:16 +00003043 for(i=0; i<nEq; i++){
dan39129ce2014-06-30 15:23:57 +00003044 char *z = aiColumn[i] < 0 ? "rowid" : aCol[aiColumn[i]].zName;
drhcd8629e2013-11-13 12:27:25 +00003045 if( i>=nSkip ){
drh6c977892014-10-10 15:47:46 +00003046 explainAppendTerm(pStr, i, z, "=");
drhcd8629e2013-11-13 12:27:25 +00003047 }else{
drh6c977892014-10-10 15:47:46 +00003048 if( i ) sqlite3StrAccumAppend(pStr, " AND ", 5);
3049 sqlite3XPrintf(pStr, 0, "ANY(%s)", z);
drhcd8629e2013-11-13 12:27:25 +00003050 }
dan2ce22452010-11-08 19:01:16 +00003051 }
3052
drh69174c42010-11-12 15:35:59 +00003053 j = i;
drhef866372013-05-22 20:49:02 +00003054 if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
dan39129ce2014-06-30 15:23:57 +00003055 char *z = aiColumn[j] < 0 ? "rowid" : aCol[aiColumn[j]].zName;
drh6c977892014-10-10 15:47:46 +00003056 explainAppendTerm(pStr, i++, z, ">");
dan2ce22452010-11-08 19:01:16 +00003057 }
drhef866372013-05-22 20:49:02 +00003058 if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
dan39129ce2014-06-30 15:23:57 +00003059 char *z = aiColumn[j] < 0 ? "rowid" : aCol[aiColumn[j]].zName;
drh6c977892014-10-10 15:47:46 +00003060 explainAppendTerm(pStr, i, z, "<");
dan2ce22452010-11-08 19:01:16 +00003061 }
drh6c977892014-10-10 15:47:46 +00003062 sqlite3StrAccumAppend(pStr, ")", 1);
dan2ce22452010-11-08 19:01:16 +00003063}
3064
dan17c0bc02010-11-09 17:35:19 +00003065/*
3066** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
dan037b5322014-11-03 11:25:32 +00003067** command, or if either SQLITE_DEBUG or SQLITE_ENABLE_STMT_SCANSTATUS was
3068** defined at compile-time. If it is not a no-op, a single OP_Explain opcode
3069** is added to the output to describe the table scan strategy in pLevel.
3070**
3071** If an OP_Explain opcode is added to the VM, its address is returned.
3072** Otherwise, if no OP_Explain is coded, zero is returned.
dan17c0bc02010-11-09 17:35:19 +00003073*/
dan6f9702e2014-11-01 20:38:06 +00003074static int explainOneScan(
dan2ce22452010-11-08 19:01:16 +00003075 Parse *pParse, /* Parse context */
3076 SrcList *pTabList, /* Table list this loop refers to */
dan6f9702e2014-11-01 20:38:06 +00003077 WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
dan2ce22452010-11-08 19:01:16 +00003078 int iLevel, /* Value for "level" column of output */
dan6f9702e2014-11-01 20:38:06 +00003079 int iFrom, /* Value for "from" column of output */
dan4a07e3d2010-11-09 14:48:59 +00003080 u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
dan2ce22452010-11-08 19:01:16 +00003081){
dan6f9702e2014-11-01 20:38:06 +00003082 int ret = 0;
dan43764a82014-11-01 21:00:04 +00003083#if !defined(SQLITE_DEBUG) && !defined(SQLITE_ENABLE_STMT_SCANSTATUS)
drh84e55a82013-11-13 17:58:23 +00003084 if( pParse->explain==2 )
3085#endif
3086 {
dan2ce22452010-11-08 19:01:16 +00003087 struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
dan17c0bc02010-11-09 17:35:19 +00003088 Vdbe *v = pParse->pVdbe; /* VM being constructed */
3089 sqlite3 *db = pParse->db; /* Database handle */
dan6f9702e2014-11-01 20:38:06 +00003090 int iId = pParse->iSelectId; /* Select id (left-most output column) */
dan4bc39fa2010-11-13 16:42:27 +00003091 int isSearch; /* True for a SEARCH. False for SCAN. */
drhef866372013-05-22 20:49:02 +00003092 WhereLoop *pLoop; /* The controlling WhereLoop object */
3093 u32 flags; /* Flags that describe this loop */
dan6f9702e2014-11-01 20:38:06 +00003094 char *zMsg; /* Text to add to EQP output */
drh6c977892014-10-10 15:47:46 +00003095 StrAccum str; /* EQP output string */
3096 char zBuf[100]; /* Initial space for EQP output string */
dan2ce22452010-11-08 19:01:16 +00003097
drhef866372013-05-22 20:49:02 +00003098 pLoop = pLevel->pWLoop;
3099 flags = pLoop->wsFlags;
dan6f9702e2014-11-01 20:38:06 +00003100 if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return 0;
dan2ce22452010-11-08 19:01:16 +00003101
drhef866372013-05-22 20:49:02 +00003102 isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
3103 || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
3104 || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
dan6f9702e2014-11-01 20:38:06 +00003105
drhc0490572015-05-02 11:45:53 +00003106 sqlite3StrAccumInit(&str, db, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH);
drh6c977892014-10-10 15:47:46 +00003107 sqlite3StrAccumAppendAll(&str, isSearch ? "SEARCH" : "SCAN");
dan4a07e3d2010-11-09 14:48:59 +00003108 if( pItem->pSelect ){
drh6c977892014-10-10 15:47:46 +00003109 sqlite3XPrintf(&str, 0, " SUBQUERY %d", pItem->iSelectId);
dan4a07e3d2010-11-09 14:48:59 +00003110 }else{
drh6c977892014-10-10 15:47:46 +00003111 sqlite3XPrintf(&str, 0, " TABLE %s", pItem->zName);
dan4a07e3d2010-11-09 14:48:59 +00003112 }
3113
dan2ce22452010-11-08 19:01:16 +00003114 if( pItem->zAlias ){
drh6c977892014-10-10 15:47:46 +00003115 sqlite3XPrintf(&str, 0, " AS %s", pItem->zAlias);
dan2ce22452010-11-08 19:01:16 +00003116 }
drh6c977892014-10-10 15:47:46 +00003117 if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0 ){
3118 const char *zFmt = 0;
3119 Index *pIdx;
3120
3121 assert( pLoop->u.btree.pIndex!=0 );
3122 pIdx = pLoop->u.btree.pIndex;
dane96f2df2014-05-23 17:17:06 +00003123 assert( !(flags&WHERE_AUTO_INDEX) || (flags&WHERE_IDX_ONLY) );
drh48dd1d82014-05-27 18:18:58 +00003124 if( !HasRowid(pItem->pTab) && IsPrimaryKeyIndex(pIdx) ){
drhc631faa2014-10-11 01:22:16 +00003125 if( isSearch ){
drh6c977892014-10-10 15:47:46 +00003126 zFmt = "PRIMARY KEY";
3127 }
drh051575c2014-10-25 12:28:25 +00003128 }else if( flags & WHERE_PARTIALIDX ){
3129 zFmt = "AUTOMATIC PARTIAL COVERING INDEX";
dane96f2df2014-05-23 17:17:06 +00003130 }else if( flags & WHERE_AUTO_INDEX ){
drh6c977892014-10-10 15:47:46 +00003131 zFmt = "AUTOMATIC COVERING INDEX";
dane96f2df2014-05-23 17:17:06 +00003132 }else if( flags & WHERE_IDX_ONLY ){
drh6c977892014-10-10 15:47:46 +00003133 zFmt = "COVERING INDEX %s";
dane96f2df2014-05-23 17:17:06 +00003134 }else{
drh6c977892014-10-10 15:47:46 +00003135 zFmt = "INDEX %s";
dane96f2df2014-05-23 17:17:06 +00003136 }
drh6c977892014-10-10 15:47:46 +00003137 if( zFmt ){
3138 sqlite3StrAccumAppend(&str, " USING ", 7);
3139 sqlite3XPrintf(&str, 0, zFmt, pIdx->zName);
3140 explainIndexRange(&str, pLoop, pItem->pTab);
3141 }
drhef71c1f2013-06-04 12:58:02 +00003142 }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
drh6c977892014-10-10 15:47:46 +00003143 const char *zRange;
drh8e23daf2013-06-11 13:30:04 +00003144 if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
drh6c977892014-10-10 15:47:46 +00003145 zRange = "(rowid=?)";
drh04098e62010-11-15 21:50:19 +00003146 }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
drh6c977892014-10-10 15:47:46 +00003147 zRange = "(rowid>? AND rowid<?)";
dan2ce22452010-11-08 19:01:16 +00003148 }else if( flags&WHERE_BTM_LIMIT ){
drh6c977892014-10-10 15:47:46 +00003149 zRange = "(rowid>?)";
3150 }else{
3151 assert( flags&WHERE_TOP_LIMIT);
3152 zRange = "(rowid<?)";
dan2ce22452010-11-08 19:01:16 +00003153 }
drh6c977892014-10-10 15:47:46 +00003154 sqlite3StrAccumAppendAll(&str, " USING INTEGER PRIMARY KEY ");
3155 sqlite3StrAccumAppendAll(&str, zRange);
dan2ce22452010-11-08 19:01:16 +00003156 }
3157#ifndef SQLITE_OMIT_VIRTUALTABLE
3158 else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
drh6c977892014-10-10 15:47:46 +00003159 sqlite3XPrintf(&str, 0, " VIRTUAL TABLE INDEX %d:%s",
drhef866372013-05-22 20:49:02 +00003160 pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
dan2ce22452010-11-08 19:01:16 +00003161 }
3162#endif
drh98545bb2014-10-10 17:20:39 +00003163#ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS
dan6f9702e2014-11-01 20:38:06 +00003164 if( pLoop->nOut>=10 ){
3165 sqlite3XPrintf(&str, 0, " (~%llu rows)", sqlite3LogEstToInt(pLoop->nOut));
3166 }else{
3167 sqlite3StrAccumAppend(&str, " (~1 row)", 9);
dan04489b62014-10-31 20:11:32 +00003168 }
dan6f9702e2014-11-01 20:38:06 +00003169#endif
3170 zMsg = sqlite3StrAccumFinish(&str);
3171 ret = sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg,P4_DYNAMIC);
dan2ce22452010-11-08 19:01:16 +00003172 }
dan6f9702e2014-11-01 20:38:06 +00003173 return ret;
dan2ce22452010-11-08 19:01:16 +00003174}
3175#else
dan6f9702e2014-11-01 20:38:06 +00003176# define explainOneScan(u,v,w,x,y,z) 0
3177#endif /* SQLITE_OMIT_EXPLAIN */
3178
3179#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
dan037b5322014-11-03 11:25:32 +00003180/*
3181** Configure the VM passed as the first argument with an
3182** sqlite3_stmt_scanstatus() entry corresponding to the scan used to
3183** implement level pLvl. Argument pSrclist is a pointer to the FROM
3184** clause that the scan reads data from.
3185**
3186** If argument addrExplain is not 0, it must be the address of an
3187** OP_Explain instruction that describes the same loop.
3188*/
dan6f9702e2014-11-01 20:38:06 +00003189static void addScanStatus(
dan037b5322014-11-03 11:25:32 +00003190 Vdbe *v, /* Vdbe to add scanstatus entry to */
3191 SrcList *pSrclist, /* FROM clause pLvl reads data from */
3192 WhereLevel *pLvl, /* Level to add scanstatus() entry for */
3193 int addrExplain /* Address of OP_Explain (or 0) */
dan6f9702e2014-11-01 20:38:06 +00003194){
3195 const char *zObj = 0;
dan6f9702e2014-11-01 20:38:06 +00003196 WhereLoop *pLoop = pLvl->pWLoop;
drhcd934c32014-12-05 21:18:19 +00003197 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 && pLoop->u.btree.pIndex!=0 ){
dan6f9702e2014-11-01 20:38:06 +00003198 zObj = pLoop->u.btree.pIndex->zName;
3199 }else{
3200 zObj = pSrclist->a[pLvl->iFrom].zName;
3201 }
dan037b5322014-11-03 11:25:32 +00003202 sqlite3VdbeScanStatus(
drh518140e2014-11-06 03:55:10 +00003203 v, addrExplain, pLvl->addrBody, pLvl->addrVisit, pLoop->nOut, zObj
dan6f9702e2014-11-01 20:38:06 +00003204 );
3205}
3206#else
dane2f771b2014-11-03 15:33:17 +00003207# define addScanStatus(a, b, c, d) ((void)d)
dan6f9702e2014-11-01 20:38:06 +00003208#endif
3209
drhf07cf6e2015-03-06 16:45:16 +00003210/*
drha40da622015-03-09 12:11:56 +00003211** If the most recently coded instruction is a constant range contraint
3212** that originated from the LIKE optimization, then change the P3 to be
drhf07cf6e2015-03-06 16:45:16 +00003213** pLoop->iLikeRepCntr and set P5.
3214**
drh16897072015-03-07 00:57:37 +00003215** The LIKE optimization trys to evaluate "x LIKE 'abc%'" as a range
3216** expression: "x>='ABC' AND x<'abd'". But this requires that the range
3217** scan loop run twice, once for strings and a second time for BLOBs.
3218** The OP_String opcodes on the second pass convert the upper and lower
3219** bound string contants to blobs. This routine makes the necessary changes
3220** to the OP_String opcodes for that to happen.
drhf07cf6e2015-03-06 16:45:16 +00003221*/
drh52fc05b2015-03-07 20:32:49 +00003222static void whereLikeOptimizationStringFixup(
3223 Vdbe *v, /* prepared statement under construction */
3224 WhereLevel *pLevel, /* The loop that contains the LIKE operator */
3225 WhereTerm *pTerm /* The upper or lower bound just coded */
3226){
3227 if( pTerm->wtFlags & TERM_LIKEOPT ){
drha40da622015-03-09 12:11:56 +00003228 VdbeOp *pOp;
3229 assert( pLevel->iLikeRepCntr>0 );
3230 pOp = sqlite3VdbeGetOp(v, -1);
3231 assert( pOp!=0 );
3232 assert( pOp->opcode==OP_String8
3233 || pTerm->pWC->pWInfo->pParse->db->mallocFailed );
drhf07cf6e2015-03-06 16:45:16 +00003234 pOp->p3 = pLevel->iLikeRepCntr;
3235 pOp->p5 = 1;
3236 }
3237}
dan2ce22452010-11-08 19:01:16 +00003238
drh111a6a72008-12-21 03:51:16 +00003239/*
3240** Generate code for the start of the iLevel-th loop in the WHERE clause
3241** implementation described by pWInfo.
3242*/
3243static Bitmask codeOneLoopStart(
3244 WhereInfo *pWInfo, /* Complete information about the WHERE clause */
3245 int iLevel, /* Which level of pWInfo->a[] should be coded */
drh7a484802012-03-16 00:28:11 +00003246 Bitmask notReady /* Which tables are currently available */
drh111a6a72008-12-21 03:51:16 +00003247){
3248 int j, k; /* Loop counters */
3249 int iCur; /* The VDBE cursor for the table */
3250 int addrNxt; /* Where to jump to continue with the next IN case */
3251 int omitTable; /* True if we use the index only */
3252 int bRev; /* True if we need to scan in reverse order */
3253 WhereLevel *pLevel; /* The where level to be coded */
drh7ba39a92013-05-30 17:43:19 +00003254 WhereLoop *pLoop; /* The WhereLoop object being coded */
drh111a6a72008-12-21 03:51:16 +00003255 WhereClause *pWC; /* Decomposition of the entire WHERE clause */
3256 WhereTerm *pTerm; /* A WHERE clause term */
3257 Parse *pParse; /* Parsing context */
drh6b36e822013-07-30 15:10:32 +00003258 sqlite3 *db; /* Database connection */
drh111a6a72008-12-21 03:51:16 +00003259 Vdbe *v; /* The prepared stmt under constructions */
3260 struct SrcList_item *pTabItem; /* FROM clause term being coded */
drh23d04d52008-12-23 23:56:22 +00003261 int addrBrk; /* Jump here to break out of the loop */
3262 int addrCont; /* Jump here to continue with next cycle */
drh61495262009-04-22 15:32:59 +00003263 int iRowidReg = 0; /* Rowid is stored in this register, if not zero */
3264 int iReleaseReg = 0; /* Temp register to free before returning */
drh111a6a72008-12-21 03:51:16 +00003265
3266 pParse = pWInfo->pParse;
3267 v = pParse->pVdbe;
drh70d18342013-06-06 19:16:33 +00003268 pWC = &pWInfo->sWC;
drh6b36e822013-07-30 15:10:32 +00003269 db = pParse->db;
drh111a6a72008-12-21 03:51:16 +00003270 pLevel = &pWInfo->a[iLevel];
drh7ba39a92013-05-30 17:43:19 +00003271 pLoop = pLevel->pWLoop;
drh111a6a72008-12-21 03:51:16 +00003272 pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
3273 iCur = pTabItem->iCursor;
drh0259bc32013-09-09 19:37:46 +00003274 pLevel->notReady = notReady & ~getMask(&pWInfo->sMaskSet, iCur);
drh7ba39a92013-05-30 17:43:19 +00003275 bRev = (pWInfo->revMask>>iLevel)&1;
3276 omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
drh70d18342013-06-06 19:16:33 +00003277 && (pWInfo->wctrlFlags & WHERE_FORCE_TABLE)==0;
drh6bc69a22013-11-19 12:33:23 +00003278 VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName));
drh111a6a72008-12-21 03:51:16 +00003279
3280 /* Create labels for the "break" and "continue" instructions
3281 ** for the current loop. Jump to addrBrk to break out of a loop.
3282 ** Jump to cont to go immediately to the next iteration of the
3283 ** loop.
3284 **
3285 ** When there is an IN operator, we also have a "addrNxt" label that
3286 ** means to continue with the next IN value combination. When
3287 ** there are no IN operators in the constraints, the "addrNxt" label
3288 ** is the same as "addrBrk".
3289 */
3290 addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
3291 addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
3292
3293 /* If this is the right table of a LEFT OUTER JOIN, allocate and
3294 ** initialize a memory cell that records if this table matches any
3295 ** row of the left table of the join.
3296 */
3297 if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
3298 pLevel->iLeftJoin = ++pParse->nMem;
3299 sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
3300 VdbeComment((v, "init LEFT JOIN no-match flag"));
3301 }
3302
drh21172c42012-10-30 00:29:07 +00003303 /* Special case of a FROM clause subquery implemented as a co-routine */
3304 if( pTabItem->viaCoroutine ){
3305 int regYield = pTabItem->regReturn;
drhed71a832014-02-07 19:18:10 +00003306 sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
drh81cf13e2014-02-07 18:27:53 +00003307 pLevel->p2 = sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk);
drh688852a2014-02-17 22:40:43 +00003308 VdbeCoverage(v);
drh725de292014-02-08 13:12:19 +00003309 VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
drh21172c42012-10-30 00:29:07 +00003310 pLevel->op = OP_Goto;
3311 }else
3312
drh111a6a72008-12-21 03:51:16 +00003313#ifndef SQLITE_OMIT_VIRTUALTABLE
drh7ba39a92013-05-30 17:43:19 +00003314 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
3315 /* Case 1: The table is a virtual-table. Use the VFilter and VNext
drh111a6a72008-12-21 03:51:16 +00003316 ** to access the data.
3317 */
3318 int iReg; /* P3 Value for OP_VFilter */
drh281bbe22012-10-16 23:17:14 +00003319 int addrNotFound;
drh4efc9292013-06-06 23:02:03 +00003320 int nConstraint = pLoop->nLTerm;
drh111a6a72008-12-21 03:51:16 +00003321
drha62bb8d2009-11-23 21:23:45 +00003322 sqlite3ExprCachePush(pParse);
drh111a6a72008-12-21 03:51:16 +00003323 iReg = sqlite3GetTempRange(pParse, nConstraint+2);
drh281bbe22012-10-16 23:17:14 +00003324 addrNotFound = pLevel->addrBrk;
drh111a6a72008-12-21 03:51:16 +00003325 for(j=0; j<nConstraint; j++){
drhe2250172013-05-31 18:13:50 +00003326 int iTarget = iReg+j+2;
drh4efc9292013-06-06 23:02:03 +00003327 pTerm = pLoop->aLTerm[j];
drh95ed68d2013-06-12 17:55:50 +00003328 if( pTerm==0 ) continue;
drh7ba39a92013-05-30 17:43:19 +00003329 if( pTerm->eOperator & WO_IN ){
3330 codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
3331 addrNotFound = pLevel->addrNxt;
3332 }else{
3333 sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget);
3334 }
3335 }
3336 sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
drh7e47cb82013-05-31 17:55:27 +00003337 sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
drh7ba39a92013-05-30 17:43:19 +00003338 sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
3339 pLoop->u.vtab.idxStr,
3340 pLoop->u.vtab.needFree ? P4_MPRINTF : P4_STATIC);
drh688852a2014-02-17 22:40:43 +00003341 VdbeCoverage(v);
drh7ba39a92013-05-30 17:43:19 +00003342 pLoop->u.vtab.needFree = 0;
3343 for(j=0; j<nConstraint && j<16; j++){
3344 if( (pLoop->u.vtab.omitMask>>j)&1 ){
drh4efc9292013-06-06 23:02:03 +00003345 disableTerm(pLevel, pLoop->aLTerm[j]);
drh111a6a72008-12-21 03:51:16 +00003346 }
3347 }
3348 pLevel->op = OP_VNext;
3349 pLevel->p1 = iCur;
3350 pLevel->p2 = sqlite3VdbeCurrentAddr(v);
drh23d04d52008-12-23 23:56:22 +00003351 sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
drhd2490902014-04-13 19:28:15 +00003352 sqlite3ExprCachePop(pParse);
drh111a6a72008-12-21 03:51:16 +00003353 }else
3354#endif /* SQLITE_OMIT_VIRTUALTABLE */
3355
drh7ba39a92013-05-30 17:43:19 +00003356 if( (pLoop->wsFlags & WHERE_IPK)!=0
3357 && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
3358 ){
3359 /* Case 2: We can directly reference a single row using an
drh111a6a72008-12-21 03:51:16 +00003360 ** equality comparison against the ROWID field. Or
3361 ** we reference multiple rows using a "rowid IN (...)"
3362 ** construct.
3363 */
drh7ba39a92013-05-30 17:43:19 +00003364 assert( pLoop->u.btree.nEq==1 );
drh4efc9292013-06-06 23:02:03 +00003365 pTerm = pLoop->aLTerm[0];
drh111a6a72008-12-21 03:51:16 +00003366 assert( pTerm!=0 );
3367 assert( pTerm->pExpr!=0 );
drh111a6a72008-12-21 03:51:16 +00003368 assert( omitTable==0 );
drh39759742013-08-02 23:40:45 +00003369 testcase( pTerm->wtFlags & TERM_VIRTUAL );
drh0baa0352014-02-25 21:55:16 +00003370 iReleaseReg = ++pParse->nMem;
drh7ba39a92013-05-30 17:43:19 +00003371 iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
drh0baa0352014-02-25 21:55:16 +00003372 if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg);
drh111a6a72008-12-21 03:51:16 +00003373 addrNxt = pLevel->addrNxt;
drh688852a2014-02-17 22:40:43 +00003374 sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt); VdbeCoverage(v);
danielk19771d461462009-04-21 09:02:45 +00003375 sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
drh688852a2014-02-17 22:40:43 +00003376 VdbeCoverage(v);
drh459f63e2013-03-06 01:55:27 +00003377 sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
drhceea3322009-04-23 13:22:42 +00003378 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
drh111a6a72008-12-21 03:51:16 +00003379 VdbeComment((v, "pk"));
3380 pLevel->op = OP_Noop;
drh7ba39a92013-05-30 17:43:19 +00003381 }else if( (pLoop->wsFlags & WHERE_IPK)!=0
3382 && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
3383 ){
3384 /* Case 3: We have an inequality comparison against the ROWID field.
drh111a6a72008-12-21 03:51:16 +00003385 */
3386 int testOp = OP_Noop;
3387 int start;
3388 int memEndValue = 0;
3389 WhereTerm *pStart, *pEnd;
3390
3391 assert( omitTable==0 );
drh7ba39a92013-05-30 17:43:19 +00003392 j = 0;
3393 pStart = pEnd = 0;
drh4efc9292013-06-06 23:02:03 +00003394 if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
3395 if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
drh81186b42013-06-18 01:52:41 +00003396 assert( pStart!=0 || pEnd!=0 );
drh111a6a72008-12-21 03:51:16 +00003397 if( bRev ){
3398 pTerm = pStart;
3399 pStart = pEnd;
3400 pEnd = pTerm;
3401 }
3402 if( pStart ){
3403 Expr *pX; /* The expression that defines the start bound */
3404 int r1, rTemp; /* Registers for holding the start boundary */
3405
3406 /* The following constant maps TK_xx codes into corresponding
3407 ** seek opcodes. It depends on a particular ordering of TK_xx
3408 */
3409 const u8 aMoveOp[] = {
drh4a1d3652014-02-14 15:13:36 +00003410 /* TK_GT */ OP_SeekGT,
3411 /* TK_LE */ OP_SeekLE,
3412 /* TK_LT */ OP_SeekLT,
3413 /* TK_GE */ OP_SeekGE
drh111a6a72008-12-21 03:51:16 +00003414 };
3415 assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */
3416 assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */
3417 assert( TK_GE==TK_GT+3 ); /* ... is correcct. */
3418
drhb5246e52013-07-08 21:12:57 +00003419 assert( (pStart->wtFlags & TERM_VNULL)==0 );
drh39759742013-08-02 23:40:45 +00003420 testcase( pStart->wtFlags & TERM_VIRTUAL );
drh111a6a72008-12-21 03:51:16 +00003421 pX = pStart->pExpr;
3422 assert( pX!=0 );
drhb5246e52013-07-08 21:12:57 +00003423 testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
drh111a6a72008-12-21 03:51:16 +00003424 r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
3425 sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
drh7d176102014-02-18 03:07:12 +00003426 VdbeComment((v, "pk"));
3427 VdbeCoverageIf(v, pX->op==TK_GT);
3428 VdbeCoverageIf(v, pX->op==TK_LE);
3429 VdbeCoverageIf(v, pX->op==TK_LT);
3430 VdbeCoverageIf(v, pX->op==TK_GE);
drh111a6a72008-12-21 03:51:16 +00003431 sqlite3ExprCacheAffinityChange(pParse, r1, 1);
3432 sqlite3ReleaseTempReg(pParse, rTemp);
3433 disableTerm(pLevel, pStart);
3434 }else{
3435 sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
drh7d176102014-02-18 03:07:12 +00003436 VdbeCoverageIf(v, bRev==0);
3437 VdbeCoverageIf(v, bRev!=0);
drh111a6a72008-12-21 03:51:16 +00003438 }
3439 if( pEnd ){
3440 Expr *pX;
3441 pX = pEnd->pExpr;
3442 assert( pX!=0 );
drhb5246e52013-07-08 21:12:57 +00003443 assert( (pEnd->wtFlags & TERM_VNULL)==0 );
3444 testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
drh39759742013-08-02 23:40:45 +00003445 testcase( pEnd->wtFlags & TERM_VIRTUAL );
drh111a6a72008-12-21 03:51:16 +00003446 memEndValue = ++pParse->nMem;
3447 sqlite3ExprCode(pParse, pX->pRight, memEndValue);
3448 if( pX->op==TK_LT || pX->op==TK_GT ){
3449 testOp = bRev ? OP_Le : OP_Ge;
3450 }else{
3451 testOp = bRev ? OP_Lt : OP_Gt;
3452 }
3453 disableTerm(pLevel, pEnd);
3454 }
3455 start = sqlite3VdbeCurrentAddr(v);
3456 pLevel->op = bRev ? OP_Prev : OP_Next;
3457 pLevel->p1 = iCur;
3458 pLevel->p2 = start;
drh81186b42013-06-18 01:52:41 +00003459 assert( pLevel->p5==0 );
danielk19771d461462009-04-21 09:02:45 +00003460 if( testOp!=OP_Noop ){
drh0baa0352014-02-25 21:55:16 +00003461 iRowidReg = ++pParse->nMem;
danielk19771d461462009-04-21 09:02:45 +00003462 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
drhceea3322009-04-23 13:22:42 +00003463 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
danielk19771d461462009-04-21 09:02:45 +00003464 sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
drh7d176102014-02-18 03:07:12 +00003465 VdbeCoverageIf(v, testOp==OP_Le);
3466 VdbeCoverageIf(v, testOp==OP_Lt);
3467 VdbeCoverageIf(v, testOp==OP_Ge);
3468 VdbeCoverageIf(v, testOp==OP_Gt);
danielk19771d461462009-04-21 09:02:45 +00003469 sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
drh111a6a72008-12-21 03:51:16 +00003470 }
drh1b0f0262013-05-30 22:27:09 +00003471 }else if( pLoop->wsFlags & WHERE_INDEXED ){
drh7ba39a92013-05-30 17:43:19 +00003472 /* Case 4: A scan using an index.
drh111a6a72008-12-21 03:51:16 +00003473 **
3474 ** The WHERE clause may contain zero or more equality
3475 ** terms ("==" or "IN" operators) that refer to the N
3476 ** left-most columns of the index. It may also contain
3477 ** inequality constraints (>, <, >= or <=) on the indexed
3478 ** column that immediately follows the N equalities. Only
3479 ** the right-most column can be an inequality - the rest must
3480 ** use the "==" and "IN" operators. For example, if the
3481 ** index is on (x,y,z), then the following clauses are all
3482 ** optimized:
3483 **
3484 ** x=5
3485 ** x=5 AND y=10
3486 ** x=5 AND y<10
3487 ** x=5 AND y>5 AND y<10
3488 ** x=5 AND y=5 AND z<=10
3489 **
3490 ** The z<10 term of the following cannot be used, only
3491 ** the x=5 term:
3492 **
3493 ** x=5 AND z<10
3494 **
3495 ** N may be zero if there are inequality constraints.
3496 ** If there are no inequality constraints, then N is at
3497 ** least one.
3498 **
3499 ** This case is also used when there are no WHERE clause
3500 ** constraints but an index is selected anyway, in order
3501 ** to force the output order to conform to an ORDER BY.
3502 */
drh3bb9b932010-08-06 02:10:00 +00003503 static const u8 aStartOp[] = {
drh111a6a72008-12-21 03:51:16 +00003504 0,
3505 0,
3506 OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */
3507 OP_Last, /* 3: (!start_constraints && startEq && bRev) */
drh4a1d3652014-02-14 15:13:36 +00003508 OP_SeekGT, /* 4: (start_constraints && !startEq && !bRev) */
3509 OP_SeekLT, /* 5: (start_constraints && !startEq && bRev) */
3510 OP_SeekGE, /* 6: (start_constraints && startEq && !bRev) */
3511 OP_SeekLE /* 7: (start_constraints && startEq && bRev) */
drh111a6a72008-12-21 03:51:16 +00003512 };
drh3bb9b932010-08-06 02:10:00 +00003513 static const u8 aEndOp[] = {
drh4a1d3652014-02-14 15:13:36 +00003514 OP_IdxGE, /* 0: (end_constraints && !bRev && !endEq) */
3515 OP_IdxGT, /* 1: (end_constraints && !bRev && endEq) */
3516 OP_IdxLE, /* 2: (end_constraints && bRev && !endEq) */
3517 OP_IdxLT, /* 3: (end_constraints && bRev && endEq) */
drh111a6a72008-12-21 03:51:16 +00003518 };
drhcd8629e2013-11-13 12:27:25 +00003519 u16 nEq = pLoop->u.btree.nEq; /* Number of == or IN terms */
drh111a6a72008-12-21 03:51:16 +00003520 int regBase; /* Base register holding constraint values */
drh111a6a72008-12-21 03:51:16 +00003521 WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */
3522 WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */
3523 int startEq; /* True if range start uses ==, >= or <= */
3524 int endEq; /* True if range end uses ==, >= or <= */
3525 int start_constraints; /* Start of range is constrained */
3526 int nConstraint; /* Number of constraint terms */
drh3bb9b932010-08-06 02:10:00 +00003527 Index *pIdx; /* The index we will be using */
3528 int iIdxCur; /* The VDBE cursor for the index */
3529 int nExtraReg = 0; /* Number of extra registers needed */
3530 int op; /* Instruction opcode */
dan6ac43392010-06-09 15:47:11 +00003531 char *zStartAff; /* Affinity for start of range constraint */
drh33cad2f2013-11-15 12:41:01 +00003532 char cEndAff = 0; /* Affinity for end of range constraint */
drhcfc6ca42014-02-14 23:49:13 +00003533 u8 bSeekPastNull = 0; /* True to seek past initial nulls */
3534 u8 bStopAtNull = 0; /* Add condition to terminate at NULLs */
drh111a6a72008-12-21 03:51:16 +00003535
drh7ba39a92013-05-30 17:43:19 +00003536 pIdx = pLoop->u.btree.pIndex;
drh111a6a72008-12-21 03:51:16 +00003537 iIdxCur = pLevel->iIdxCur;
drhc8bbce12014-10-21 01:05:09 +00003538 assert( nEq>=pLoop->nSkip );
drh111a6a72008-12-21 03:51:16 +00003539
drh111a6a72008-12-21 03:51:16 +00003540 /* If this loop satisfies a sort order (pOrderBy) request that
3541 ** was passed to this function to implement a "SELECT min(x) ..."
3542 ** query, then the caller will only allow the loop to run for
3543 ** a single iteration. This means that the first row returned
3544 ** should not have a NULL value stored in 'x'. If column 'x' is
3545 ** the first one after the nEq equality constraints in the index,
3546 ** this requires some special handling.
3547 */
drhddba0c22014-03-18 20:33:42 +00003548 assert( pWInfo->pOrderBy==0
3549 || pWInfo->pOrderBy->nExpr==1
3550 || (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0 );
drh70d18342013-06-06 19:16:33 +00003551 if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
drhddba0c22014-03-18 20:33:42 +00003552 && pWInfo->nOBSat>0
drhbbbdc832013-10-22 18:01:40 +00003553 && (pIdx->nKeyCol>nEq)
drh111a6a72008-12-21 03:51:16 +00003554 ){
drhc8bbce12014-10-21 01:05:09 +00003555 assert( pLoop->nSkip==0 );
drhcfc6ca42014-02-14 23:49:13 +00003556 bSeekPastNull = 1;
drh6df2acd2008-12-28 16:55:25 +00003557 nExtraReg = 1;
drh111a6a72008-12-21 03:51:16 +00003558 }
3559
3560 /* Find any inequality constraint terms for the start and end
3561 ** of the range.
3562 */
drh7ba39a92013-05-30 17:43:19 +00003563 j = nEq;
3564 if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
drh4efc9292013-06-06 23:02:03 +00003565 pRangeStart = pLoop->aLTerm[j++];
drh6df2acd2008-12-28 16:55:25 +00003566 nExtraReg = 1;
drh80314622015-03-09 13:01:02 +00003567 /* Like optimization range constraints always occur in pairs */
3568 assert( (pRangeStart->wtFlags & TERM_LIKEOPT)==0 ||
3569 (pLoop->wsFlags & WHERE_TOP_LIMIT)!=0 );
drh111a6a72008-12-21 03:51:16 +00003570 }
drh7ba39a92013-05-30 17:43:19 +00003571 if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
drh4efc9292013-06-06 23:02:03 +00003572 pRangeEnd = pLoop->aLTerm[j++];
drh6df2acd2008-12-28 16:55:25 +00003573 nExtraReg = 1;
drha40da622015-03-09 12:11:56 +00003574 if( (pRangeEnd->wtFlags & TERM_LIKEOPT)!=0 ){
drh80314622015-03-09 13:01:02 +00003575 assert( pRangeStart!=0 ); /* LIKE opt constraints */
3576 assert( pRangeStart->wtFlags & TERM_LIKEOPT ); /* occur in pairs */
drhf07cf6e2015-03-06 16:45:16 +00003577 pLevel->iLikeRepCntr = ++pParse->nMem;
drhb7c60ba2015-03-07 02:51:59 +00003578 testcase( bRev );
3579 testcase( pIdx->aSortOrder[nEq]==SQLITE_SO_DESC );
3580 sqlite3VdbeAddOp2(v, OP_Integer,
3581 bRev ^ (pIdx->aSortOrder[nEq]==SQLITE_SO_DESC),
3582 pLevel->iLikeRepCntr);
drh16897072015-03-07 00:57:37 +00003583 VdbeComment((v, "LIKE loop counter"));
drhf07cf6e2015-03-06 16:45:16 +00003584 pLevel->addrLikeRep = sqlite3VdbeCurrentAddr(v);
3585 }
drhcfc6ca42014-02-14 23:49:13 +00003586 if( pRangeStart==0
drhcfc6ca42014-02-14 23:49:13 +00003587 && (j = pIdx->aiColumn[nEq])>=0
3588 && pIdx->pTable->aCol[j].notNull==0
3589 ){
3590 bSeekPastNull = 1;
3591 }
drh111a6a72008-12-21 03:51:16 +00003592 }
dan0df163a2014-03-06 12:36:26 +00003593 assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 );
drh111a6a72008-12-21 03:51:16 +00003594
drh6df2acd2008-12-28 16:55:25 +00003595 /* Generate code to evaluate all constraint terms using == or IN
3596 ** and store the values of those terms in an array of registers
3597 ** starting at regBase.
3598 */
drh613ba1e2013-06-15 15:11:45 +00003599 regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
drh33cad2f2013-11-15 12:41:01 +00003600 assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq );
3601 if( zStartAff ) cEndAff = zStartAff[nEq];
drh6df2acd2008-12-28 16:55:25 +00003602 addrNxt = pLevel->addrNxt;
3603
drh111a6a72008-12-21 03:51:16 +00003604 /* If we are doing a reverse order scan on an ascending index, or
3605 ** a forward order scan on a descending index, interchange the
3606 ** start and end terms (pRangeStart and pRangeEnd).
3607 */
drhbbbdc832013-10-22 18:01:40 +00003608 if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
3609 || (bRev && pIdx->nKeyCol==nEq)
dan0c733f62011-11-16 15:27:09 +00003610 ){
drh111a6a72008-12-21 03:51:16 +00003611 SWAP(WhereTerm *, pRangeEnd, pRangeStart);
drhcfc6ca42014-02-14 23:49:13 +00003612 SWAP(u8, bSeekPastNull, bStopAtNull);
drh111a6a72008-12-21 03:51:16 +00003613 }
3614
drh7963b0e2013-06-17 21:37:40 +00003615 testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
3616 testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
3617 testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
3618 testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
drh111a6a72008-12-21 03:51:16 +00003619 startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
3620 endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
3621 start_constraints = pRangeStart || nEq>0;
3622
3623 /* Seek the index cursor to the start of the range. */
3624 nConstraint = nEq;
3625 if( pRangeStart ){
dan69f8bb92009-08-13 19:21:16 +00003626 Expr *pRight = pRangeStart->pExpr->pRight;
3627 sqlite3ExprCode(pParse, pRight, regBase+nEq);
drh52fc05b2015-03-07 20:32:49 +00003628 whereLikeOptimizationStringFixup(v, pLevel, pRangeStart);
drh7d176102014-02-18 03:07:12 +00003629 if( (pRangeStart->wtFlags & TERM_VNULL)==0
3630 && sqlite3ExprCanBeNull(pRight)
3631 ){
3632 sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
3633 VdbeCoverage(v);
drh534230c2011-01-22 00:10:45 +00003634 }
dan6ac43392010-06-09 15:47:11 +00003635 if( zStartAff ){
3636 if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
drh039fc322009-11-17 18:31:47 +00003637 /* Since the comparison is to be performed with no conversions
3638 ** applied to the operands, set the affinity to apply to pRight to
3639 ** SQLITE_AFF_NONE. */
dan6ac43392010-06-09 15:47:11 +00003640 zStartAff[nEq] = SQLITE_AFF_NONE;
drh039fc322009-11-17 18:31:47 +00003641 }
dan6ac43392010-06-09 15:47:11 +00003642 if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
3643 zStartAff[nEq] = SQLITE_AFF_NONE;
drh039fc322009-11-17 18:31:47 +00003644 }
3645 }
drh111a6a72008-12-21 03:51:16 +00003646 nConstraint++;
drh39759742013-08-02 23:40:45 +00003647 testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
drhcfc6ca42014-02-14 23:49:13 +00003648 }else if( bSeekPastNull ){
drh111a6a72008-12-21 03:51:16 +00003649 sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
3650 nConstraint++;
3651 startEq = 0;
3652 start_constraints = 1;
3653 }
drhcfc6ca42014-02-14 23:49:13 +00003654 codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff);
drh111a6a72008-12-21 03:51:16 +00003655 op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
3656 assert( op!=0 );
drh8cff69d2009-11-12 19:59:44 +00003657 sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
drh688852a2014-02-17 22:40:43 +00003658 VdbeCoverage(v);
drh7d176102014-02-18 03:07:12 +00003659 VdbeCoverageIf(v, op==OP_Rewind); testcase( op==OP_Rewind );
3660 VdbeCoverageIf(v, op==OP_Last); testcase( op==OP_Last );
3661 VdbeCoverageIf(v, op==OP_SeekGT); testcase( op==OP_SeekGT );
3662 VdbeCoverageIf(v, op==OP_SeekGE); testcase( op==OP_SeekGE );
3663 VdbeCoverageIf(v, op==OP_SeekLE); testcase( op==OP_SeekLE );
3664 VdbeCoverageIf(v, op==OP_SeekLT); testcase( op==OP_SeekLT );
drh111a6a72008-12-21 03:51:16 +00003665
3666 /* Load the value for the inequality constraint at the end of the
3667 ** range (if any).
3668 */
3669 nConstraint = nEq;
3670 if( pRangeEnd ){
dan69f8bb92009-08-13 19:21:16 +00003671 Expr *pRight = pRangeEnd->pExpr->pRight;
drhf49f3522009-12-30 14:12:38 +00003672 sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
dan69f8bb92009-08-13 19:21:16 +00003673 sqlite3ExprCode(pParse, pRight, regBase+nEq);
drh52fc05b2015-03-07 20:32:49 +00003674 whereLikeOptimizationStringFixup(v, pLevel, pRangeEnd);
drh7d176102014-02-18 03:07:12 +00003675 if( (pRangeEnd->wtFlags & TERM_VNULL)==0
3676 && sqlite3ExprCanBeNull(pRight)
3677 ){
3678 sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
3679 VdbeCoverage(v);
drh534230c2011-01-22 00:10:45 +00003680 }
drh33cad2f2013-11-15 12:41:01 +00003681 if( sqlite3CompareAffinity(pRight, cEndAff)!=SQLITE_AFF_NONE
3682 && !sqlite3ExprNeedsNoAffinityChange(pRight, cEndAff)
3683 ){
3684 codeApplyAffinity(pParse, regBase+nEq, 1, &cEndAff);
3685 }
drh111a6a72008-12-21 03:51:16 +00003686 nConstraint++;
drh39759742013-08-02 23:40:45 +00003687 testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
drhcfc6ca42014-02-14 23:49:13 +00003688 }else if( bStopAtNull ){
3689 sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
3690 endEq = 0;
3691 nConstraint++;
drh111a6a72008-12-21 03:51:16 +00003692 }
drh6b36e822013-07-30 15:10:32 +00003693 sqlite3DbFree(db, zStartAff);
drh111a6a72008-12-21 03:51:16 +00003694
3695 /* Top of the loop body */
3696 pLevel->p2 = sqlite3VdbeCurrentAddr(v);
3697
3698 /* Check if the index cursor is past the end of the range. */
drhcfc6ca42014-02-14 23:49:13 +00003699 if( nConstraint ){
drh4a1d3652014-02-14 15:13:36 +00003700 op = aEndOp[bRev*2 + endEq];
drh8cff69d2009-11-12 19:59:44 +00003701 sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
drh7d176102014-02-18 03:07:12 +00003702 testcase( op==OP_IdxGT ); VdbeCoverageIf(v, op==OP_IdxGT );
3703 testcase( op==OP_IdxGE ); VdbeCoverageIf(v, op==OP_IdxGE );
3704 testcase( op==OP_IdxLT ); VdbeCoverageIf(v, op==OP_IdxLT );
3705 testcase( op==OP_IdxLE ); VdbeCoverageIf(v, op==OP_IdxLE );
drh6df2acd2008-12-28 16:55:25 +00003706 }
drh111a6a72008-12-21 03:51:16 +00003707
drh111a6a72008-12-21 03:51:16 +00003708 /* Seek the table cursor, if required */
drh23d04d52008-12-23 23:56:22 +00003709 disableTerm(pLevel, pRangeStart);
3710 disableTerm(pLevel, pRangeEnd);
drh85c1c552013-10-24 00:18:18 +00003711 if( omitTable ){
3712 /* pIdx is a covering index. No need to access the main table. */
3713 }else if( HasRowid(pIdx->pTable) ){
drh0baa0352014-02-25 21:55:16 +00003714 iRowidReg = ++pParse->nMem;
danielk19771d461462009-04-21 09:02:45 +00003715 sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
drhceea3322009-04-23 13:22:42 +00003716 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
danielk19771d461462009-04-21 09:02:45 +00003717 sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg); /* Deferred seek */
drha3bc66a2014-05-27 17:57:32 +00003718 }else if( iCur!=iIdxCur ){
drh85c1c552013-10-24 00:18:18 +00003719 Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
3720 iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol);
3721 for(j=0; j<pPk->nKeyCol; j++){
3722 k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
3723 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j);
3724 }
drh261c02d2013-10-25 14:46:15 +00003725 sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont,
drh688852a2014-02-17 22:40:43 +00003726 iRowidReg, pPk->nKeyCol); VdbeCoverage(v);
drh111a6a72008-12-21 03:51:16 +00003727 }
drh111a6a72008-12-21 03:51:16 +00003728
3729 /* Record the instruction used to terminate the loop. Disable
3730 ** WHERE clause terms made redundant by the index range scan.
3731 */
drh7699d1c2013-06-04 12:42:29 +00003732 if( pLoop->wsFlags & WHERE_ONEROW ){
drh95e037b2011-03-09 21:02:31 +00003733 pLevel->op = OP_Noop;
3734 }else if( bRev ){
3735 pLevel->op = OP_Prev;
3736 }else{
3737 pLevel->op = OP_Next;
3738 }
drh111a6a72008-12-21 03:51:16 +00003739 pLevel->p1 = iIdxCur;
drh0c8a9342014-03-20 12:17:35 +00003740 pLevel->p3 = (pLoop->wsFlags&WHERE_UNQ_WANTED)!=0 ? 1:0;
drh53cfbe92013-06-13 17:28:22 +00003741 if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
drh3f4d1d12012-09-15 18:45:54 +00003742 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
3743 }else{
3744 assert( pLevel->p5==0 );
3745 }
drhdd5f5a62008-12-23 13:35:23 +00003746 }else
3747
drh23d04d52008-12-23 23:56:22 +00003748#ifndef SQLITE_OMIT_OR_OPTIMIZATION
drh7ba39a92013-05-30 17:43:19 +00003749 if( pLoop->wsFlags & WHERE_MULTI_OR ){
3750 /* Case 5: Two or more separately indexed terms connected by OR
drh111a6a72008-12-21 03:51:16 +00003751 **
3752 ** Example:
3753 **
3754 ** CREATE TABLE t1(a,b,c,d);
3755 ** CREATE INDEX i1 ON t1(a);
3756 ** CREATE INDEX i2 ON t1(b);
3757 ** CREATE INDEX i3 ON t1(c);
3758 **
3759 ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
3760 **
3761 ** In the example, there are three indexed terms connected by OR.
danielk19771d461462009-04-21 09:02:45 +00003762 ** The top of the loop looks like this:
drh111a6a72008-12-21 03:51:16 +00003763 **
drh1b26c7c2009-04-22 02:15:47 +00003764 ** Null 1 # Zero the rowset in reg 1
drh111a6a72008-12-21 03:51:16 +00003765 **
danielk19771d461462009-04-21 09:02:45 +00003766 ** Then, for each indexed term, the following. The arguments to
drh1b26c7c2009-04-22 02:15:47 +00003767 ** RowSetTest are such that the rowid of the current row is inserted
3768 ** into the RowSet. If it is already present, control skips the
danielk19771d461462009-04-21 09:02:45 +00003769 ** Gosub opcode and jumps straight to the code generated by WhereEnd().
drh111a6a72008-12-21 03:51:16 +00003770 **
danielk19771d461462009-04-21 09:02:45 +00003771 ** sqlite3WhereBegin(<term>)
drh1b26c7c2009-04-22 02:15:47 +00003772 ** RowSetTest # Insert rowid into rowset
danielk19771d461462009-04-21 09:02:45 +00003773 ** Gosub 2 A
3774 ** sqlite3WhereEnd()
3775 **
3776 ** Following the above, code to terminate the loop. Label A, the target
3777 ** of the Gosub above, jumps to the instruction right after the Goto.
3778 **
drh1b26c7c2009-04-22 02:15:47 +00003779 ** Null 1 # Zero the rowset in reg 1
danielk19771d461462009-04-21 09:02:45 +00003780 ** Goto B # The loop is finished.
3781 **
3782 ** A: <loop body> # Return data, whatever.
3783 **
3784 ** Return 2 # Jump back to the Gosub
3785 **
3786 ** B: <after the loop>
3787 **
drh5609baf2014-05-26 22:01:00 +00003788 ** Added 2014-05-26: If the table is a WITHOUT ROWID table, then
peter.d.reid60ec9142014-09-06 16:39:46 +00003789 ** use an ephemeral index instead of a RowSet to record the primary
drh5609baf2014-05-26 22:01:00 +00003790 ** keys of the rows we have already seen.
3791 **
drh111a6a72008-12-21 03:51:16 +00003792 */
drh111a6a72008-12-21 03:51:16 +00003793 WhereClause *pOrWc; /* The OR-clause broken out into subterms */
drhc01a3c12009-12-16 22:10:49 +00003794 SrcList *pOrTab; /* Shortened table list or OR-clause generation */
dan0efb72c2012-08-24 18:44:56 +00003795 Index *pCov = 0; /* Potential covering index (or NULL) */
3796 int iCovCur = pParse->nTab++; /* Cursor used for index scans (if any) */
danielk19771d461462009-04-21 09:02:45 +00003797
3798 int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */
shane85095702009-06-15 16:27:08 +00003799 int regRowset = 0; /* Register for RowSet object */
3800 int regRowid = 0; /* Register holding rowid */
danielk19771d461462009-04-21 09:02:45 +00003801 int iLoopBody = sqlite3VdbeMakeLabel(v); /* Start of loop body */
3802 int iRetInit; /* Address of regReturn init */
drhc01a3c12009-12-16 22:10:49 +00003803 int untestedTerms = 0; /* Some terms not completely tested */
drh8871ef52011-10-07 13:33:10 +00003804 int ii; /* Loop counter */
drh35263192014-07-22 20:02:19 +00003805 u16 wctrlFlags; /* Flags for sub-WHERE clause */
drh8871ef52011-10-07 13:33:10 +00003806 Expr *pAndExpr = 0; /* An ".. AND (...)" expression */
danf97dad82014-05-26 20:06:45 +00003807 Table *pTab = pTabItem->pTab;
drh111a6a72008-12-21 03:51:16 +00003808
drh4efc9292013-06-06 23:02:03 +00003809 pTerm = pLoop->aLTerm[0];
drh111a6a72008-12-21 03:51:16 +00003810 assert( pTerm!=0 );
drh7a5bcc02013-01-16 17:08:58 +00003811 assert( pTerm->eOperator & WO_OR );
drh111a6a72008-12-21 03:51:16 +00003812 assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
3813 pOrWc = &pTerm->u.pOrInfo->wc;
drhc01a3c12009-12-16 22:10:49 +00003814 pLevel->op = OP_Return;
3815 pLevel->p1 = regReturn;
drh23d04d52008-12-23 23:56:22 +00003816
danbfca6a42012-08-24 10:52:35 +00003817 /* Set up a new SrcList in pOrTab containing the table being scanned
drhc01a3c12009-12-16 22:10:49 +00003818 ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
3819 ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
3820 */
3821 if( pWInfo->nLevel>1 ){
3822 int nNotReady; /* The number of notReady tables */
3823 struct SrcList_item *origSrc; /* Original list of tables */
3824 nNotReady = pWInfo->nLevel - iLevel - 1;
drh6b36e822013-07-30 15:10:32 +00003825 pOrTab = sqlite3StackAllocRaw(db,
drhc01a3c12009-12-16 22:10:49 +00003826 sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
3827 if( pOrTab==0 ) return notReady;
drhad01d892013-06-19 13:59:49 +00003828 pOrTab->nAlloc = (u8)(nNotReady + 1);
shaneh46aae3c2009-12-31 19:06:23 +00003829 pOrTab->nSrc = pOrTab->nAlloc;
drhc01a3c12009-12-16 22:10:49 +00003830 memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
3831 origSrc = pWInfo->pTabList->a;
3832 for(k=1; k<=nNotReady; k++){
3833 memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
3834 }
3835 }else{
3836 pOrTab = pWInfo->pTabList;
3837 }
danielk19771d461462009-04-21 09:02:45 +00003838
drh1b26c7c2009-04-22 02:15:47 +00003839 /* Initialize the rowset register to contain NULL. An SQL NULL is
peter.d.reid60ec9142014-09-06 16:39:46 +00003840 ** equivalent to an empty rowset. Or, create an ephemeral index
drh5609baf2014-05-26 22:01:00 +00003841 ** capable of holding primary keys in the case of a WITHOUT ROWID.
danielk19771d461462009-04-21 09:02:45 +00003842 **
3843 ** Also initialize regReturn to contain the address of the instruction
3844 ** immediately following the OP_Return at the bottom of the loop. This
3845 ** is required in a few obscure LEFT JOIN cases where control jumps
3846 ** over the top of the loop into the body of it. In this case the
3847 ** correct response for the end-of-loop code (the OP_Return) is to
3848 ** fall through to the next instruction, just as an OP_Next does if
3849 ** called on an uninitialized cursor.
3850 */
drh70d18342013-06-06 19:16:33 +00003851 if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
danf97dad82014-05-26 20:06:45 +00003852 if( HasRowid(pTab) ){
3853 regRowset = ++pParse->nMem;
3854 sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
3855 }else{
3856 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
3857 regRowset = pParse->nTab++;
3858 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, regRowset, pPk->nKeyCol);
3859 sqlite3VdbeSetP4KeyInfo(pParse, pPk);
3860 }
drh336a5302009-04-24 15:46:21 +00003861 regRowid = ++pParse->nMem;
drh336a5302009-04-24 15:46:21 +00003862 }
danielk19771d461462009-04-21 09:02:45 +00003863 iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
3864
drh8871ef52011-10-07 13:33:10 +00003865 /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y
3866 ** Then for every term xN, evaluate as the subexpression: xN AND z
3867 ** That way, terms in y that are factored into the disjunction will
3868 ** be picked up by the recursive calls to sqlite3WhereBegin() below.
drh331b67c2012-03-09 22:02:08 +00003869 **
3870 ** Actually, each subexpression is converted to "xN AND w" where w is
3871 ** the "interesting" terms of z - terms that did not originate in the
3872 ** ON or USING clause of a LEFT JOIN, and terms that are usable as
3873 ** indices.
drhb3129fa2013-05-09 14:20:11 +00003874 **
3875 ** This optimization also only applies if the (x1 OR x2 OR ...) term
3876 ** is not contained in the ON clause of a LEFT JOIN.
3877 ** See ticket http://www.sqlite.org/src/info/f2369304e4
drh8871ef52011-10-07 13:33:10 +00003878 */
3879 if( pWC->nTerm>1 ){
drh7a484802012-03-16 00:28:11 +00003880 int iTerm;
3881 for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
3882 Expr *pExpr = pWC->a[iTerm].pExpr;
drhaa32e3c2013-07-16 21:31:23 +00003883 if( &pWC->a[iTerm] == pTerm ) continue;
drh331b67c2012-03-09 22:02:08 +00003884 if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
drh1d324882014-12-04 20:24:50 +00003885 if( (pWC->a[iTerm].wtFlags & TERM_VIRTUAL)!=0 ) continue;
drh7a484802012-03-16 00:28:11 +00003886 if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
drh1d324882014-12-04 20:24:50 +00003887 testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO );
drh6b36e822013-07-30 15:10:32 +00003888 pExpr = sqlite3ExprDup(db, pExpr, 0);
3889 pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr);
drh331b67c2012-03-09 22:02:08 +00003890 }
3891 if( pAndExpr ){
3892 pAndExpr = sqlite3PExpr(pParse, TK_AND, 0, pAndExpr, 0);
3893 }
drh8871ef52011-10-07 13:33:10 +00003894 }
3895
drh3fb67302014-05-27 16:41:39 +00003896 /* Run a separate WHERE clause for each term of the OR clause. After
3897 ** eliminating duplicates from other WHERE clauses, the action for each
3898 ** sub-WHERE clause is to to invoke the main loop body as a subroutine.
3899 */
drh36be4c42014-09-30 17:31:23 +00003900 wctrlFlags = WHERE_OMIT_OPEN_CLOSE
3901 | WHERE_FORCE_TABLE
drh8e8e7ef2015-03-02 17:25:00 +00003902 | WHERE_ONETABLE_ONLY
3903 | WHERE_NO_AUTOINDEX;
danielk19771d461462009-04-21 09:02:45 +00003904 for(ii=0; ii<pOrWc->nTerm; ii++){
3905 WhereTerm *pOrTerm = &pOrWc->a[ii];
drh7a5bcc02013-01-16 17:08:58 +00003906 if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
drh3fb67302014-05-27 16:41:39 +00003907 WhereInfo *pSubWInfo; /* Info for single OR-term scan */
3908 Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */
3909 int j1 = 0; /* Address of jump operation */
drhb3129fa2013-05-09 14:20:11 +00003910 if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){
drh8871ef52011-10-07 13:33:10 +00003911 pAndExpr->pLeft = pOrExpr;
3912 pOrExpr = pAndExpr;
3913 }
danielk19771d461462009-04-21 09:02:45 +00003914 /* Loop through table entries that match term pOrTerm. */
drh0a99ba32014-09-30 17:03:35 +00003915 WHERETRACE(0xffff, ("Subplan for OR-clause:\n"));
drh8871ef52011-10-07 13:33:10 +00003916 pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
drh35263192014-07-22 20:02:19 +00003917 wctrlFlags, iCovCur);
drh6b36e822013-07-30 15:10:32 +00003918 assert( pSubWInfo || pParse->nErr || db->mallocFailed );
danielk19771d461462009-04-21 09:02:45 +00003919 if( pSubWInfo ){
drh7ba39a92013-05-30 17:43:19 +00003920 WhereLoop *pSubLoop;
dan6f9702e2014-11-01 20:38:06 +00003921 int addrExplain = explainOneScan(
3922 pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
3923 );
3924 addScanStatus(v, pOrTab, &pSubWInfo->a[0], addrExplain);
dan89e71642014-11-01 18:08:04 +00003925
drh3fb67302014-05-27 16:41:39 +00003926 /* This is the sub-WHERE clause body. First skip over
3927 ** duplicate rows from prior sub-WHERE clauses, and record the
3928 ** rowid (or PRIMARY KEY) for the current row so that the same
3929 ** row will be skipped in subsequent sub-WHERE clauses.
3930 */
drh70d18342013-06-06 19:16:33 +00003931 if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
drh336a5302009-04-24 15:46:21 +00003932 int r;
danf97dad82014-05-26 20:06:45 +00003933 int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
3934 if( HasRowid(pTab) ){
3935 r = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, regRowid, 0);
drh5609baf2014-05-26 22:01:00 +00003936 j1 = sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, 0, r,iSet);
danf97dad82014-05-26 20:06:45 +00003937 VdbeCoverage(v);
3938 }else{
3939 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
3940 int nPk = pPk->nKeyCol;
3941 int iPk;
3942
3943 /* Read the PK into an array of temp registers. */
3944 r = sqlite3GetTempRange(pParse, nPk);
3945 for(iPk=0; iPk<nPk; iPk++){
3946 int iCol = pPk->aiColumn[iPk];
3947 sqlite3ExprCodeGetColumn(pParse, pTab, iCol, iCur, r+iPk, 0);
3948 }
3949
3950 /* Check if the temp table already contains this key. If so,
3951 ** the row has already been included in the result set and
3952 ** can be ignored (by jumping past the Gosub below). Otherwise,
3953 ** insert the key into the temp table and proceed with processing
3954 ** the row.
3955 **
3956 ** Use some of the same optimizations as OP_RowSetTest: If iSet
3957 ** is zero, assume that the key cannot already be present in
3958 ** the temp table. And if iSet is -1, assume that there is no
3959 ** need to insert the key into the temp table, as it will never
3960 ** be tested for. */
3961 if( iSet ){
drh5609baf2014-05-26 22:01:00 +00003962 j1 = sqlite3VdbeAddOp4Int(v, OP_Found, regRowset, 0, r, nPk);
drh68c12152014-05-26 20:25:34 +00003963 VdbeCoverage(v);
danf97dad82014-05-26 20:06:45 +00003964 }
3965 if( iSet>=0 ){
3966 sqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, regRowid);
3967 sqlite3VdbeAddOp3(v, OP_IdxInsert, regRowset, regRowid, 0);
3968 if( iSet ) sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
3969 }
3970
3971 /* Release the array of temp registers */
3972 sqlite3ReleaseTempRange(pParse, r, nPk);
3973 }
drh336a5302009-04-24 15:46:21 +00003974 }
drh3fb67302014-05-27 16:41:39 +00003975
3976 /* Invoke the main loop body as a subroutine */
danielk19771d461462009-04-21 09:02:45 +00003977 sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
drh3fb67302014-05-27 16:41:39 +00003978
3979 /* Jump here (skipping the main loop body subroutine) if the
3980 ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */
drh5609baf2014-05-26 22:01:00 +00003981 if( j1 ) sqlite3VdbeJumpHere(v, j1);
danielk19771d461462009-04-21 09:02:45 +00003982
drhc01a3c12009-12-16 22:10:49 +00003983 /* The pSubWInfo->untestedTerms flag means that this OR term
3984 ** contained one or more AND term from a notReady table. The
3985 ** terms from the notReady table could not be tested and will
3986 ** need to be tested later.
3987 */
3988 if( pSubWInfo->untestedTerms ) untestedTerms = 1;
3989
danbfca6a42012-08-24 10:52:35 +00003990 /* If all of the OR-connected terms are optimized using the same
3991 ** index, and the index is opened using the same cursor number
3992 ** by each call to sqlite3WhereBegin() made by this loop, it may
3993 ** be possible to use that index as a covering index.
3994 **
3995 ** If the call to sqlite3WhereBegin() above resulted in a scan that
3996 ** uses an index, and this is either the first OR-connected term
3997 ** processed or the index is the same as that used by all previous
dan0efb72c2012-08-24 18:44:56 +00003998 ** terms, set pCov to the candidate covering index. Otherwise, set
3999 ** pCov to NULL to indicate that no candidate covering index will
4000 ** be available.
danbfca6a42012-08-24 10:52:35 +00004001 */
drh7ba39a92013-05-30 17:43:19 +00004002 pSubLoop = pSubWInfo->a[0].pWLoop;
drh986b3872013-06-28 21:12:20 +00004003 assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
drh7ba39a92013-05-30 17:43:19 +00004004 if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
drh7ba39a92013-05-30 17:43:19 +00004005 && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
drh48dd1d82014-05-27 18:18:58 +00004006 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pSubLoop->u.btree.pIndex))
danbfca6a42012-08-24 10:52:35 +00004007 ){
drh7ba39a92013-05-30 17:43:19 +00004008 assert( pSubWInfo->a[0].iIdxCur==iCovCur );
drh907717f2013-06-04 18:03:22 +00004009 pCov = pSubLoop->u.btree.pIndex;
drh35263192014-07-22 20:02:19 +00004010 wctrlFlags |= WHERE_REOPEN_IDX;
danbfca6a42012-08-24 10:52:35 +00004011 }else{
4012 pCov = 0;
4013 }
4014
danielk19771d461462009-04-21 09:02:45 +00004015 /* Finish the loop through table entries that match term pOrTerm. */
4016 sqlite3WhereEnd(pSubWInfo);
4017 }
drhdd5f5a62008-12-23 13:35:23 +00004018 }
4019 }
drhd40e2082012-08-24 23:24:15 +00004020 pLevel->u.pCovidx = pCov;
drh90abfd02012-10-09 21:07:23 +00004021 if( pCov ) pLevel->iIdxCur = iCovCur;
drh331b67c2012-03-09 22:02:08 +00004022 if( pAndExpr ){
4023 pAndExpr->pLeft = 0;
drh6b36e822013-07-30 15:10:32 +00004024 sqlite3ExprDelete(db, pAndExpr);
drh331b67c2012-03-09 22:02:08 +00004025 }
danielk19771d461462009-04-21 09:02:45 +00004026 sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
danielk19771d461462009-04-21 09:02:45 +00004027 sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
4028 sqlite3VdbeResolveLabel(v, iLoopBody);
4029
drh6b36e822013-07-30 15:10:32 +00004030 if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab);
drhc01a3c12009-12-16 22:10:49 +00004031 if( !untestedTerms ) disableTerm(pLevel, pTerm);
drhdd5f5a62008-12-23 13:35:23 +00004032 }else
drh23d04d52008-12-23 23:56:22 +00004033#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
drhdd5f5a62008-12-23 13:35:23 +00004034
4035 {
drh7ba39a92013-05-30 17:43:19 +00004036 /* Case 6: There is no usable index. We must do a complete
drh111a6a72008-12-21 03:51:16 +00004037 ** scan of the entire table.
4038 */
drh699b3d42009-02-23 16:52:07 +00004039 static const u8 aStep[] = { OP_Next, OP_Prev };
4040 static const u8 aStart[] = { OP_Rewind, OP_Last };
4041 assert( bRev==0 || bRev==1 );
drhe73f0592014-01-21 22:25:45 +00004042 if( pTabItem->isRecursive ){
drh340309f2014-01-22 00:23:49 +00004043 /* Tables marked isRecursive have only a single row that is stored in
dan41028152014-01-22 10:22:25 +00004044 ** a pseudo-cursor. No need to Rewind or Next such cursors. */
drhe73f0592014-01-21 22:25:45 +00004045 pLevel->op = OP_Noop;
4046 }else{
4047 pLevel->op = aStep[bRev];
4048 pLevel->p1 = iCur;
4049 pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
drh7d176102014-02-18 03:07:12 +00004050 VdbeCoverageIf(v, bRev==0);
4051 VdbeCoverageIf(v, bRev!=0);
drhe73f0592014-01-21 22:25:45 +00004052 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
4053 }
drh111a6a72008-12-21 03:51:16 +00004054 }
drh111a6a72008-12-21 03:51:16 +00004055
dan6f9702e2014-11-01 20:38:06 +00004056#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
4057 pLevel->addrVisit = sqlite3VdbeCurrentAddr(v);
4058#endif
4059
drh111a6a72008-12-21 03:51:16 +00004060 /* Insert code to test every subexpression that can be completely
4061 ** computed using the current set of tables.
4062 */
drh111a6a72008-12-21 03:51:16 +00004063 for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
4064 Expr *pE;
drh8f1a7ed2015-03-06 19:47:38 +00004065 int skipLikeAddr = 0;
drh39759742013-08-02 23:40:45 +00004066 testcase( pTerm->wtFlags & TERM_VIRTUAL );
drh111a6a72008-12-21 03:51:16 +00004067 testcase( pTerm->wtFlags & TERM_CODED );
4068 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
drh0259bc32013-09-09 19:37:46 +00004069 if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
drhc01a3c12009-12-16 22:10:49 +00004070 testcase( pWInfo->untestedTerms==0
4071 && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
4072 pWInfo->untestedTerms = 1;
4073 continue;
4074 }
drh111a6a72008-12-21 03:51:16 +00004075 pE = pTerm->pExpr;
4076 assert( pE!=0 );
4077 if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
4078 continue;
4079 }
drh8f1a7ed2015-03-06 19:47:38 +00004080 if( pTerm->wtFlags & TERM_LIKECOND ){
4081 assert( pLevel->iLikeRepCntr>0 );
drh16897072015-03-07 00:57:37 +00004082 skipLikeAddr = sqlite3VdbeAddOp1(v, OP_IfNot, pLevel->iLikeRepCntr);
drh8f1a7ed2015-03-06 19:47:38 +00004083 VdbeCoverage(v);
4084 }
drh111a6a72008-12-21 03:51:16 +00004085 sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
drh8f1a7ed2015-03-06 19:47:38 +00004086 if( skipLikeAddr ) sqlite3VdbeJumpHere(v, skipLikeAddr);
drh111a6a72008-12-21 03:51:16 +00004087 pTerm->wtFlags |= TERM_CODED;
4088 }
4089
drh0c41d222013-04-22 02:39:10 +00004090 /* Insert code to test for implied constraints based on transitivity
4091 ** of the "==" operator.
4092 **
4093 ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
4094 ** and we are coding the t1 loop and the t2 loop has not yet coded,
4095 ** then we cannot use the "t1.a=t2.b" constraint, but we can code
4096 ** the implied "t1.a=123" constraint.
4097 */
4098 for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
drh6b36e822013-07-30 15:10:32 +00004099 Expr *pE, *pEAlt;
drh0c41d222013-04-22 02:39:10 +00004100 WhereTerm *pAlt;
drh0c41d222013-04-22 02:39:10 +00004101 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
4102 if( pTerm->eOperator!=(WO_EQUIV|WO_EQ) ) continue;
4103 if( pTerm->leftCursor!=iCur ) continue;
drhcdc2e432013-07-01 17:27:19 +00004104 if( pLevel->iLeftJoin ) continue;
drh0c41d222013-04-22 02:39:10 +00004105 pE = pTerm->pExpr;
4106 assert( !ExprHasProperty(pE, EP_FromJoin) );
drh0259bc32013-09-09 19:37:46 +00004107 assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
drh0c41d222013-04-22 02:39:10 +00004108 pAlt = findTerm(pWC, iCur, pTerm->u.leftColumn, notReady, WO_EQ|WO_IN, 0);
4109 if( pAlt==0 ) continue;
drh5c10f3b2013-05-01 17:22:38 +00004110 if( pAlt->wtFlags & (TERM_CODED) ) continue;
drh7963b0e2013-06-17 21:37:40 +00004111 testcase( pAlt->eOperator & WO_EQ );
4112 testcase( pAlt->eOperator & WO_IN );
drh6bc69a22013-11-19 12:33:23 +00004113 VdbeModuleComment((v, "begin transitive constraint"));
drh6b36e822013-07-30 15:10:32 +00004114 pEAlt = sqlite3StackAllocRaw(db, sizeof(*pEAlt));
4115 if( pEAlt ){
4116 *pEAlt = *pAlt->pExpr;
4117 pEAlt->pLeft = pE->pLeft;
4118 sqlite3ExprIfFalse(pParse, pEAlt, addrCont, SQLITE_JUMPIFNULL);
4119 sqlite3StackFree(db, pEAlt);
4120 }
drh0c41d222013-04-22 02:39:10 +00004121 }
4122
drh111a6a72008-12-21 03:51:16 +00004123 /* For a LEFT OUTER JOIN, generate code that will record the fact that
4124 ** at least one row of the right table has matched the left table.
4125 */
4126 if( pLevel->iLeftJoin ){
4127 pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
4128 sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
4129 VdbeComment((v, "record LEFT JOIN hit"));
drhceea3322009-04-23 13:22:42 +00004130 sqlite3ExprCacheClear(pParse);
drh111a6a72008-12-21 03:51:16 +00004131 for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
drh39759742013-08-02 23:40:45 +00004132 testcase( pTerm->wtFlags & TERM_VIRTUAL );
drh111a6a72008-12-21 03:51:16 +00004133 testcase( pTerm->wtFlags & TERM_CODED );
4134 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
drh0259bc32013-09-09 19:37:46 +00004135 if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
drhb057e562009-12-16 23:43:55 +00004136 assert( pWInfo->untestedTerms );
drhc01a3c12009-12-16 22:10:49 +00004137 continue;
4138 }
drh111a6a72008-12-21 03:51:16 +00004139 assert( pTerm->pExpr );
4140 sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
4141 pTerm->wtFlags |= TERM_CODED;
4142 }
4143 }
drh23d04d52008-12-23 23:56:22 +00004144
drh0259bc32013-09-09 19:37:46 +00004145 return pLevel->notReady;
drh111a6a72008-12-21 03:51:16 +00004146}
4147
drhd15cb172013-05-21 19:23:10 +00004148#ifdef WHERETRACE_ENABLED
drha18f3d22013-05-08 03:05:41 +00004149/*
drhc90713d2014-09-30 13:46:49 +00004150** Print the content of a WhereTerm object
4151*/
4152static void whereTermPrint(WhereTerm *pTerm, int iTerm){
drh0a99ba32014-09-30 17:03:35 +00004153 if( pTerm==0 ){
4154 sqlite3DebugPrintf("TERM-%-3d NULL\n", iTerm);
4155 }else{
4156 char zType[4];
4157 memcpy(zType, "...", 4);
4158 if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V';
4159 if( pTerm->eOperator & WO_EQUIV ) zType[1] = 'E';
4160 if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) zType[2] = 'L';
4161 sqlite3DebugPrintf("TERM-%-3d %p %s cursor=%-3d prob=%-3d op=0x%03x\n",
4162 iTerm, pTerm, zType, pTerm->leftCursor, pTerm->truthProb,
4163 pTerm->eOperator);
4164 sqlite3TreeViewExpr(0, pTerm->pExpr, 0);
4165 }
drhc90713d2014-09-30 13:46:49 +00004166}
4167#endif
4168
4169#ifdef WHERETRACE_ENABLED
4170/*
drha18f3d22013-05-08 03:05:41 +00004171** Print a WhereLoop object for debugging purposes
4172*/
drhc1ba2e72013-10-28 19:03:21 +00004173static void whereLoopPrint(WhereLoop *p, WhereClause *pWC){
4174 WhereInfo *pWInfo = pWC->pWInfo;
drh989578e2013-10-28 14:34:35 +00004175 int nb = 1+(pWInfo->pTabList->nSrc+7)/8;
4176 struct SrcList_item *pItem = pWInfo->pTabList->a + p->iTab;
drha18f3d22013-05-08 03:05:41 +00004177 Table *pTab = pItem->pTab;
drh6457a352013-06-21 00:35:37 +00004178 sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
drha184fb82013-05-08 04:22:59 +00004179 p->iTab, nb, p->maskSelf, nb, p->prereq);
drh6457a352013-06-21 00:35:37 +00004180 sqlite3DebugPrintf(" %12s",
drha18f3d22013-05-08 03:05:41 +00004181 pItem->zAlias ? pItem->zAlias : pTab->zName);
drh5346e952013-05-08 14:14:26 +00004182 if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
drhf3f69ac2014-08-20 23:38:07 +00004183 const char *zName;
4184 if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){
drh319f6772013-05-14 15:31:07 +00004185 if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
4186 int i = sqlite3Strlen30(zName) - 1;
4187 while( zName[i]!='_' ) i--;
4188 zName += i;
4189 }
drh6457a352013-06-21 00:35:37 +00004190 sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq);
drh5346e952013-05-08 14:14:26 +00004191 }else{
drh6457a352013-06-21 00:35:37 +00004192 sqlite3DebugPrintf("%20s","");
drh5346e952013-05-08 14:14:26 +00004193 }
drha18f3d22013-05-08 03:05:41 +00004194 }else{
drh5346e952013-05-08 14:14:26 +00004195 char *z;
4196 if( p->u.vtab.idxStr ){
drh3bd26f02013-05-24 14:52:03 +00004197 z = sqlite3_mprintf("(%d,\"%s\",%x)",
4198 p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
drh5346e952013-05-08 14:14:26 +00004199 }else{
drh3bd26f02013-05-24 14:52:03 +00004200 z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
drh5346e952013-05-08 14:14:26 +00004201 }
drh6457a352013-06-21 00:35:37 +00004202 sqlite3DebugPrintf(" %-19s", z);
drh5346e952013-05-08 14:14:26 +00004203 sqlite3_free(z);
drha18f3d22013-05-08 03:05:41 +00004204 }
drhf3f69ac2014-08-20 23:38:07 +00004205 if( p->wsFlags & WHERE_SKIPSCAN ){
drhc8bbce12014-10-21 01:05:09 +00004206 sqlite3DebugPrintf(" f %05x %d-%d", p->wsFlags, p->nLTerm,p->nSkip);
drhf3f69ac2014-08-20 23:38:07 +00004207 }else{
4208 sqlite3DebugPrintf(" f %05x N %d", p->wsFlags, p->nLTerm);
4209 }
drhb8a8e8a2013-06-10 19:12:39 +00004210 sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
drhc90713d2014-09-30 13:46:49 +00004211 if( p->nLTerm && (sqlite3WhereTrace & 0x100)!=0 ){
4212 int i;
4213 for(i=0; i<p->nLTerm; i++){
drh0a99ba32014-09-30 17:03:35 +00004214 whereTermPrint(p->aLTerm[i], i);
drhc90713d2014-09-30 13:46:49 +00004215 }
4216 }
drha18f3d22013-05-08 03:05:41 +00004217}
4218#endif
4219
drhf1b5f5b2013-05-02 00:15:01 +00004220/*
drh4efc9292013-06-06 23:02:03 +00004221** Convert bulk memory into a valid WhereLoop that can be passed
4222** to whereLoopClear harmlessly.
drh5346e952013-05-08 14:14:26 +00004223*/
drh4efc9292013-06-06 23:02:03 +00004224static void whereLoopInit(WhereLoop *p){
4225 p->aLTerm = p->aLTermSpace;
4226 p->nLTerm = 0;
4227 p->nLSlot = ArraySize(p->aLTermSpace);
4228 p->wsFlags = 0;
4229}
4230
4231/*
4232** Clear the WhereLoop.u union. Leave WhereLoop.pLTerm intact.
4233*/
4234static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
drh986b3872013-06-28 21:12:20 +00004235 if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){
drh13e11b42013-06-06 23:44:25 +00004236 if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
4237 sqlite3_free(p->u.vtab.idxStr);
4238 p->u.vtab.needFree = 0;
4239 p->u.vtab.idxStr = 0;
drh986b3872013-06-28 21:12:20 +00004240 }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){
drh13e11b42013-06-06 23:44:25 +00004241 sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
4242 sqlite3DbFree(db, p->u.btree.pIndex);
4243 p->u.btree.pIndex = 0;
4244 }
drh5346e952013-05-08 14:14:26 +00004245 }
4246}
4247
drh4efc9292013-06-06 23:02:03 +00004248/*
4249** Deallocate internal memory used by a WhereLoop object
4250*/
4251static void whereLoopClear(sqlite3 *db, WhereLoop *p){
4252 if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
4253 whereLoopClearUnion(db, p);
4254 whereLoopInit(p);
4255}
4256
4257/*
4258** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
4259*/
4260static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
4261 WhereTerm **paNew;
4262 if( p->nLSlot>=n ) return SQLITE_OK;
4263 n = (n+7)&~7;
4264 paNew = sqlite3DbMallocRaw(db, sizeof(p->aLTerm[0])*n);
4265 if( paNew==0 ) return SQLITE_NOMEM;
4266 memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
4267 if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
4268 p->aLTerm = paNew;
4269 p->nLSlot = n;
4270 return SQLITE_OK;
4271}
4272
4273/*
4274** Transfer content from the second pLoop into the first.
4275*/
4276static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
drh4efc9292013-06-06 23:02:03 +00004277 whereLoopClearUnion(db, pTo);
drh0d31dc32013-09-06 00:40:59 +00004278 if( whereLoopResize(db, pTo, pFrom->nLTerm) ){
4279 memset(&pTo->u, 0, sizeof(pTo->u));
4280 return SQLITE_NOMEM;
4281 }
drha2014152013-06-07 00:29:23 +00004282 memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
4283 memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
drh4efc9292013-06-06 23:02:03 +00004284 if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
4285 pFrom->u.vtab.needFree = 0;
drh986b3872013-06-28 21:12:20 +00004286 }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){
drh4efc9292013-06-06 23:02:03 +00004287 pFrom->u.btree.pIndex = 0;
4288 }
4289 return SQLITE_OK;
4290}
4291
drh5346e952013-05-08 14:14:26 +00004292/*
drhf1b5f5b2013-05-02 00:15:01 +00004293** Delete a WhereLoop object
4294*/
4295static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
drh5346e952013-05-08 14:14:26 +00004296 whereLoopClear(db, p);
drhf1b5f5b2013-05-02 00:15:01 +00004297 sqlite3DbFree(db, p);
4298}
drh84bfda42005-07-15 13:05:21 +00004299
drh9eff6162006-06-12 21:59:13 +00004300/*
4301** Free a WhereInfo structure
4302*/
drh10fe8402008-10-11 16:47:35 +00004303static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
drh52ff8ea2010-04-08 14:15:56 +00004304 if( ALWAYS(pWInfo) ){
danf89aa472015-04-25 12:20:24 +00004305 int i;
4306 for(i=0; i<pWInfo->nLevel; i++){
4307 WhereLevel *pLevel = &pWInfo->a[i];
4308 if( pLevel->pWLoop && (pLevel->pWLoop->wsFlags & WHERE_IN_ABLE) ){
4309 sqlite3DbFree(db, pLevel->u.in.aInLoop);
4310 }
4311 }
drh70d18342013-06-06 19:16:33 +00004312 whereClauseClear(&pWInfo->sWC);
drhf1b5f5b2013-05-02 00:15:01 +00004313 while( pWInfo->pLoops ){
4314 WhereLoop *p = pWInfo->pLoops;
4315 pWInfo->pLoops = p->pNextLoop;
4316 whereLoopDelete(db, p);
4317 }
drh633e6d52008-07-28 19:34:53 +00004318 sqlite3DbFree(db, pWInfo);
drh9eff6162006-06-12 21:59:13 +00004319 }
4320}
4321
drhf1b5f5b2013-05-02 00:15:01 +00004322/*
drhe0de8762014-11-05 13:13:13 +00004323** Return TRUE if all of the following are true:
drhb355c2c2014-04-18 22:20:31 +00004324**
4325** (1) X has the same or lower cost that Y
4326** (2) X is a proper subset of Y
drhe0de8762014-11-05 13:13:13 +00004327** (3) X skips at least as many columns as Y
drhb355c2c2014-04-18 22:20:31 +00004328**
4329** By "proper subset" we mean that X uses fewer WHERE clause terms
4330** than Y and that every WHERE clause term used by X is also used
4331** by Y.
4332**
4333** If X is a proper subset of Y then Y is a better choice and ought
4334** to have a lower cost. This routine returns TRUE when that cost
drhe0de8762014-11-05 13:13:13 +00004335** relationship is inverted and needs to be adjusted. The third rule
4336** was added because if X uses skip-scan less than Y it still might
4337** deserve a lower cost even if it is a proper subset of Y.
drh3fb183d2014-03-31 19:49:00 +00004338*/
drhb355c2c2014-04-18 22:20:31 +00004339static int whereLoopCheaperProperSubset(
4340 const WhereLoop *pX, /* First WhereLoop to compare */
4341 const WhereLoop *pY /* Compare against this WhereLoop */
4342){
drh3fb183d2014-03-31 19:49:00 +00004343 int i, j;
drhc8bbce12014-10-21 01:05:09 +00004344 if( pX->nLTerm-pX->nSkip >= pY->nLTerm-pY->nSkip ){
4345 return 0; /* X is not a subset of Y */
4346 }
drhe0de8762014-11-05 13:13:13 +00004347 if( pY->nSkip > pX->nSkip ) return 0;
drhb355c2c2014-04-18 22:20:31 +00004348 if( pX->rRun >= pY->rRun ){
4349 if( pX->rRun > pY->rRun ) return 0; /* X costs more than Y */
4350 if( pX->nOut > pY->nOut ) return 0; /* X costs more than Y */
drh3fb183d2014-03-31 19:49:00 +00004351 }
drh9ee88102014-05-07 20:33:17 +00004352 for(i=pX->nLTerm-1; i>=0; i--){
drhc8bbce12014-10-21 01:05:09 +00004353 if( pX->aLTerm[i]==0 ) continue;
drhb355c2c2014-04-18 22:20:31 +00004354 for(j=pY->nLTerm-1; j>=0; j--){
4355 if( pY->aLTerm[j]==pX->aLTerm[i] ) break;
4356 }
4357 if( j<0 ) return 0; /* X not a subset of Y since term X[i] not used by Y */
4358 }
4359 return 1; /* All conditions meet */
drh3fb183d2014-03-31 19:49:00 +00004360}
4361
4362/*
4363** Try to adjust the cost of WhereLoop pTemplate upwards or downwards so
4364** that:
drh53cd10a2014-03-31 18:24:18 +00004365**
drh3fb183d2014-03-31 19:49:00 +00004366** (1) pTemplate costs less than any other WhereLoops that are a proper
4367** subset of pTemplate
drh53cd10a2014-03-31 18:24:18 +00004368**
drh3fb183d2014-03-31 19:49:00 +00004369** (2) pTemplate costs more than any other WhereLoops for which pTemplate
4370** is a proper subset.
drh53cd10a2014-03-31 18:24:18 +00004371**
drh3fb183d2014-03-31 19:49:00 +00004372** To say "WhereLoop X is a proper subset of Y" means that X uses fewer
4373** WHERE clause terms than Y and that every WHERE clause term used by X is
4374** also used by Y.
drh53cd10a2014-03-31 18:24:18 +00004375*/
4376static void whereLoopAdjustCost(const WhereLoop *p, WhereLoop *pTemplate){
4377 if( (pTemplate->wsFlags & WHERE_INDEXED)==0 ) return;
drh53cd10a2014-03-31 18:24:18 +00004378 for(; p; p=p->pNextLoop){
drh3fb183d2014-03-31 19:49:00 +00004379 if( p->iTab!=pTemplate->iTab ) continue;
4380 if( (p->wsFlags & WHERE_INDEXED)==0 ) continue;
drhb355c2c2014-04-18 22:20:31 +00004381 if( whereLoopCheaperProperSubset(p, pTemplate) ){
4382 /* Adjust pTemplate cost downward so that it is cheaper than its
drhe0de8762014-11-05 13:13:13 +00004383 ** subset p. */
drh1b131b72014-10-21 16:01:40 +00004384 WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
4385 pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut-1));
drh3fb183d2014-03-31 19:49:00 +00004386 pTemplate->rRun = p->rRun;
4387 pTemplate->nOut = p->nOut - 1;
drhb355c2c2014-04-18 22:20:31 +00004388 }else if( whereLoopCheaperProperSubset(pTemplate, p) ){
4389 /* Adjust pTemplate cost upward so that it is costlier than p since
4390 ** pTemplate is a proper subset of p */
drh1b131b72014-10-21 16:01:40 +00004391 WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
4392 pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut+1));
drh3fb183d2014-03-31 19:49:00 +00004393 pTemplate->rRun = p->rRun;
4394 pTemplate->nOut = p->nOut + 1;
drh53cd10a2014-03-31 18:24:18 +00004395 }
4396 }
4397}
4398
4399/*
drh7a4b1642014-03-29 21:16:07 +00004400** Search the list of WhereLoops in *ppPrev looking for one that can be
4401** supplanted by pTemplate.
drhf1b5f5b2013-05-02 00:15:01 +00004402**
drh7a4b1642014-03-29 21:16:07 +00004403** Return NULL if the WhereLoop list contains an entry that can supplant
4404** pTemplate, in other words if pTemplate does not belong on the list.
drh23f98da2013-05-21 15:52:07 +00004405**
drh7a4b1642014-03-29 21:16:07 +00004406** If pX is a WhereLoop that pTemplate can supplant, then return the
4407** link that points to pX.
drh23f98da2013-05-21 15:52:07 +00004408**
drh7a4b1642014-03-29 21:16:07 +00004409** If pTemplate cannot supplant any existing element of the list but needs
4410** to be added to the list, then return a pointer to the tail of the list.
drhf1b5f5b2013-05-02 00:15:01 +00004411*/
drh7a4b1642014-03-29 21:16:07 +00004412static WhereLoop **whereLoopFindLesser(
4413 WhereLoop **ppPrev,
4414 const WhereLoop *pTemplate
4415){
4416 WhereLoop *p;
4417 for(p=(*ppPrev); p; ppPrev=&p->pNextLoop, p=*ppPrev){
drhdbb80232013-06-19 12:34:13 +00004418 if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
4419 /* If either the iTab or iSortIdx values for two WhereLoop are different
4420 ** then those WhereLoops need to be considered separately. Neither is
4421 ** a candidate to replace the other. */
4422 continue;
4423 }
4424 /* In the current implementation, the rSetup value is either zero
4425 ** or the cost of building an automatic index (NlogN) and the NlogN
4426 ** is the same for compatible WhereLoops. */
4427 assert( p->rSetup==0 || pTemplate->rSetup==0
4428 || p->rSetup==pTemplate->rSetup );
4429
4430 /* whereLoopAddBtree() always generates and inserts the automatic index
4431 ** case first. Hence compatible candidate WhereLoops never have a larger
4432 ** rSetup. Call this SETUP-INVARIANT */
4433 assert( p->rSetup>=pTemplate->rSetup );
4434
drhdabe36d2014-06-17 20:16:43 +00004435 /* Any loop using an appliation-defined index (or PRIMARY KEY or
4436 ** UNIQUE constraint) with one or more == constraints is better
dan70273d02014-11-14 19:34:20 +00004437 ** than an automatic index. Unless it is a skip-scan. */
drhdabe36d2014-06-17 20:16:43 +00004438 if( (p->wsFlags & WHERE_AUTO_INDEX)!=0
dan70273d02014-11-14 19:34:20 +00004439 && (pTemplate->nSkip)==0
drhdabe36d2014-06-17 20:16:43 +00004440 && (pTemplate->wsFlags & WHERE_INDEXED)!=0
4441 && (pTemplate->wsFlags & WHERE_COLUMN_EQ)!=0
4442 && (p->prereq & pTemplate->prereq)==pTemplate->prereq
4443 ){
4444 break;
4445 }
4446
drh53cd10a2014-03-31 18:24:18 +00004447 /* If existing WhereLoop p is better than pTemplate, pTemplate can be
4448 ** discarded. WhereLoop p is better if:
4449 ** (1) p has no more dependencies than pTemplate, and
4450 ** (2) p has an equal or lower cost than pTemplate
4451 */
4452 if( (p->prereq & pTemplate->prereq)==p->prereq /* (1) */
4453 && p->rSetup<=pTemplate->rSetup /* (2a) */
4454 && p->rRun<=pTemplate->rRun /* (2b) */
4455 && p->nOut<=pTemplate->nOut /* (2c) */
drhf1b5f5b2013-05-02 00:15:01 +00004456 ){
drh53cd10a2014-03-31 18:24:18 +00004457 return 0; /* Discard pTemplate */
drhf1b5f5b2013-05-02 00:15:01 +00004458 }
drh53cd10a2014-03-31 18:24:18 +00004459
4460 /* If pTemplate is always better than p, then cause p to be overwritten
4461 ** with pTemplate. pTemplate is better than p if:
4462 ** (1) pTemplate has no more dependences than p, and
4463 ** (2) pTemplate has an equal or lower cost than p.
4464 */
4465 if( (p->prereq & pTemplate->prereq)==pTemplate->prereq /* (1) */
4466 && p->rRun>=pTemplate->rRun /* (2a) */
4467 && p->nOut>=pTemplate->nOut /* (2b) */
drhf1b5f5b2013-05-02 00:15:01 +00004468 ){
drhadd5ce32013-09-07 00:29:06 +00004469 assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */
drh53cd10a2014-03-31 18:24:18 +00004470 break; /* Cause p to be overwritten by pTemplate */
drhf1b5f5b2013-05-02 00:15:01 +00004471 }
4472 }
drh7a4b1642014-03-29 21:16:07 +00004473 return ppPrev;
4474}
4475
4476/*
drh94a11212004-09-25 13:12:14 +00004477** Insert or replace a WhereLoop entry using the template supplied.
4478**
4479** An existing WhereLoop entry might be overwritten if the new template
4480** is better and has fewer dependencies. Or the template will be ignored
4481** and no insert will occur if an existing WhereLoop is faster and has
4482** fewer dependencies than the template. Otherwise a new WhereLoop is
4483** added based on the template.
drh51669862004-12-18 18:40:26 +00004484**
drh7a4b1642014-03-29 21:16:07 +00004485** If pBuilder->pOrSet is not NULL then we care about only the
drh94a11212004-09-25 13:12:14 +00004486** prerequisites and rRun and nOut costs of the N best loops. That
4487** information is gathered in the pBuilder->pOrSet object. This special
drh51669862004-12-18 18:40:26 +00004488** processing mode is used only for OR clause processing.
4489**
4490** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
4491** still might overwrite similar loops with the new template if the
drh53cd10a2014-03-31 18:24:18 +00004492** new template is better. Loops may be overwritten if the following
drh94a11212004-09-25 13:12:14 +00004493** conditions are met:
4494**
4495** (1) They have the same iTab.
4496** (2) They have the same iSortIdx.
4497** (3) The template has same or fewer dependencies than the current loop
4498** (4) The template has the same or lower cost than the current loop
drh94a11212004-09-25 13:12:14 +00004499*/
4500static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
drh7a4b1642014-03-29 21:16:07 +00004501 WhereLoop **ppPrev, *p;
drh94a11212004-09-25 13:12:14 +00004502 WhereInfo *pWInfo = pBuilder->pWInfo;
4503 sqlite3 *db = pWInfo->pParse->db;
4504
4505 /* If pBuilder->pOrSet is defined, then only keep track of the costs
4506 ** and prereqs.
4507 */
4508 if( pBuilder->pOrSet!=0 ){
4509#if WHERETRACE_ENABLED
drh51669862004-12-18 18:40:26 +00004510 u16 n = pBuilder->pOrSet->n;
4511 int x =
4512#endif
4513 whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
4514 pTemplate->nOut);
drh94a11212004-09-25 13:12:14 +00004515#if WHERETRACE_ENABLED /* 0x8 */
4516 if( sqlite3WhereTrace & 0x8 ){
drhe3184742002-06-19 14:27:05 +00004517 sqlite3DebugPrintf(x?" or-%d: ":" or-X: ", n);
drhacf3b982005-01-03 01:27:18 +00004518 whereLoopPrint(pTemplate, pBuilder->pWC);
drh75897232000-05-29 14:26:00 +00004519 }
danielk19774adee202004-05-08 08:23:19 +00004520#endif
drh75897232000-05-29 14:26:00 +00004521 return SQLITE_OK;
4522 }
4523
drh7a4b1642014-03-29 21:16:07 +00004524 /* Look for an existing WhereLoop to replace with pTemplate
drh75897232000-05-29 14:26:00 +00004525 */
drh53cd10a2014-03-31 18:24:18 +00004526 whereLoopAdjustCost(pWInfo->pLoops, pTemplate);
drh7a4b1642014-03-29 21:16:07 +00004527 ppPrev = whereLoopFindLesser(&pWInfo->pLoops, pTemplate);
drhf1b5f5b2013-05-02 00:15:01 +00004528
drh7a4b1642014-03-29 21:16:07 +00004529 if( ppPrev==0 ){
4530 /* There already exists a WhereLoop on the list that is better
4531 ** than pTemplate, so just ignore pTemplate */
4532#if WHERETRACE_ENABLED /* 0x8 */
4533 if( sqlite3WhereTrace & 0x8 ){
drh9a7b41d2014-10-08 00:08:08 +00004534 sqlite3DebugPrintf(" skip: ");
drh7a4b1642014-03-29 21:16:07 +00004535 whereLoopPrint(pTemplate, pBuilder->pWC);
drhf1b5f5b2013-05-02 00:15:01 +00004536 }
drh7a4b1642014-03-29 21:16:07 +00004537#endif
4538 return SQLITE_OK;
4539 }else{
4540 p = *ppPrev;
drhf1b5f5b2013-05-02 00:15:01 +00004541 }
4542
4543 /* If we reach this point it means that either p[] should be overwritten
4544 ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
4545 ** WhereLoop and insert it.
4546 */
drh989578e2013-10-28 14:34:35 +00004547#if WHERETRACE_ENABLED /* 0x8 */
drhae70cf12013-05-31 15:18:46 +00004548 if( sqlite3WhereTrace & 0x8 ){
4549 if( p!=0 ){
drh9a7b41d2014-10-08 00:08:08 +00004550 sqlite3DebugPrintf("replace: ");
drhc1ba2e72013-10-28 19:03:21 +00004551 whereLoopPrint(p, pBuilder->pWC);
drhae70cf12013-05-31 15:18:46 +00004552 }
drh9a7b41d2014-10-08 00:08:08 +00004553 sqlite3DebugPrintf(" add: ");
drhc1ba2e72013-10-28 19:03:21 +00004554 whereLoopPrint(pTemplate, pBuilder->pWC);
drhae70cf12013-05-31 15:18:46 +00004555 }
4556#endif
drhf1b5f5b2013-05-02 00:15:01 +00004557 if( p==0 ){
drh7a4b1642014-03-29 21:16:07 +00004558 /* Allocate a new WhereLoop to add to the end of the list */
4559 *ppPrev = p = sqlite3DbMallocRaw(db, sizeof(WhereLoop));
drhf1b5f5b2013-05-02 00:15:01 +00004560 if( p==0 ) return SQLITE_NOMEM;
drh4efc9292013-06-06 23:02:03 +00004561 whereLoopInit(p);
drh7a4b1642014-03-29 21:16:07 +00004562 p->pNextLoop = 0;
4563 }else{
4564 /* We will be overwriting WhereLoop p[]. But before we do, first
4565 ** go through the rest of the list and delete any other entries besides
4566 ** p[] that are also supplated by pTemplate */
4567 WhereLoop **ppTail = &p->pNextLoop;
4568 WhereLoop *pToDel;
4569 while( *ppTail ){
4570 ppTail = whereLoopFindLesser(ppTail, pTemplate);
drhdabe36d2014-06-17 20:16:43 +00004571 if( ppTail==0 ) break;
drh7a4b1642014-03-29 21:16:07 +00004572 pToDel = *ppTail;
4573 if( pToDel==0 ) break;
4574 *ppTail = pToDel->pNextLoop;
4575#if WHERETRACE_ENABLED /* 0x8 */
4576 if( sqlite3WhereTrace & 0x8 ){
drh9a7b41d2014-10-08 00:08:08 +00004577 sqlite3DebugPrintf(" delete: ");
drh7a4b1642014-03-29 21:16:07 +00004578 whereLoopPrint(pToDel, pBuilder->pWC);
4579 }
4580#endif
4581 whereLoopDelete(db, pToDel);
4582 }
drhf1b5f5b2013-05-02 00:15:01 +00004583 }
drh4efc9292013-06-06 23:02:03 +00004584 whereLoopXfer(db, p, pTemplate);
drh5346e952013-05-08 14:14:26 +00004585 if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
drhef866372013-05-22 20:49:02 +00004586 Index *pIndex = p->u.btree.pIndex;
4587 if( pIndex && pIndex->tnum==0 ){
drhcf8fa7a2013-05-10 20:26:22 +00004588 p->u.btree.pIndex = 0;
4589 }
drh5346e952013-05-08 14:14:26 +00004590 }
drhf1b5f5b2013-05-02 00:15:01 +00004591 return SQLITE_OK;
4592}
4593
4594/*
drhcca9f3d2013-09-06 15:23:29 +00004595** Adjust the WhereLoop.nOut value downward to account for terms of the
4596** WHERE clause that reference the loop but which are not used by an
4597** index.
drh7a1bca72014-11-22 18:50:44 +00004598*
4599** For every WHERE clause term that is not used by the index
4600** and which has a truth probability assigned by one of the likelihood(),
4601** likely(), or unlikely() SQL functions, reduce the estimated number
4602** of output rows by the probability specified.
drhcca9f3d2013-09-06 15:23:29 +00004603**
drh7a1bca72014-11-22 18:50:44 +00004604** TUNING: For every WHERE clause term that is not used by the index
4605** and which does not have an assigned truth probability, heuristics
4606** described below are used to try to estimate the truth probability.
4607** TODO --> Perhaps this is something that could be improved by better
4608** table statistics.
4609**
drhab4624d2014-11-22 19:52:10 +00004610** Heuristic 1: Estimate the truth probability as 93.75%. The 93.75%
4611** value corresponds to -1 in LogEst notation, so this means decrement
drh7a1bca72014-11-22 18:50:44 +00004612** the WhereLoop.nOut field for every such WHERE clause term.
4613**
4614** Heuristic 2: If there exists one or more WHERE clause terms of the
4615** form "x==EXPR" and EXPR is not a constant 0 or 1, then make sure the
4616** final output row estimate is no greater than 1/4 of the total number
4617** of rows in the table. In other words, assume that x==EXPR will filter
4618** out at least 3 out of 4 rows. If EXPR is -1 or 0 or 1, then maybe the
4619** "x" column is boolean or else -1 or 0 or 1 is a common default value
4620** on the "x" column and so in that case only cap the output row estimate
4621** at 1/2 instead of 1/4.
drhcca9f3d2013-09-06 15:23:29 +00004622*/
drhd8b77e22014-09-06 01:35:57 +00004623static void whereLoopOutputAdjust(
4624 WhereClause *pWC, /* The WHERE clause */
4625 WhereLoop *pLoop, /* The loop to adjust downward */
4626 LogEst nRow /* Number of rows in the entire table */
4627){
drh7d9e7d82013-09-11 17:39:09 +00004628 WhereTerm *pTerm, *pX;
drhcca9f3d2013-09-06 15:23:29 +00004629 Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf);
drh7a1bca72014-11-22 18:50:44 +00004630 int i, j, k;
4631 LogEst iReduce = 0; /* pLoop->nOut should not exceed nRow-iReduce */
drhadd5ce32013-09-07 00:29:06 +00004632
drha3898252014-11-22 12:22:13 +00004633 assert( (pLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
drhcca9f3d2013-09-06 15:23:29 +00004634 for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){
drh7d9e7d82013-09-11 17:39:09 +00004635 if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break;
drhcca9f3d2013-09-06 15:23:29 +00004636 if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;
4637 if( (pTerm->prereqAll & notAllowed)!=0 ) continue;
drh7d9e7d82013-09-11 17:39:09 +00004638 for(j=pLoop->nLTerm-1; j>=0; j--){
4639 pX = pLoop->aLTerm[j];
drhd2447442013-11-13 19:01:41 +00004640 if( pX==0 ) continue;
drh7d9e7d82013-09-11 17:39:09 +00004641 if( pX==pTerm ) break;
4642 if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break;
4643 }
danaa9933c2014-04-24 20:04:49 +00004644 if( j<0 ){
drhd8b77e22014-09-06 01:35:57 +00004645 if( pTerm->truthProb<=0 ){
drh7a1bca72014-11-22 18:50:44 +00004646 /* If a truth probability is specified using the likelihood() hints,
4647 ** then use the probability provided by the application. */
drhd8b77e22014-09-06 01:35:57 +00004648 pLoop->nOut += pTerm->truthProb;
4649 }else{
drh7a1bca72014-11-22 18:50:44 +00004650 /* In the absence of explicit truth probabilities, use heuristics to
4651 ** guess a reasonable truth probability. */
drhd8b77e22014-09-06 01:35:57 +00004652 pLoop->nOut--;
drh7a1bca72014-11-22 18:50:44 +00004653 if( pTerm->eOperator&WO_EQ ){
4654 Expr *pRight = pTerm->pExpr->pRight;
4655 if( sqlite3ExprIsInteger(pRight, &k) && k>=(-1) && k<=1 ){
4656 k = 10;
4657 }else{
4658 k = 20;
4659 }
4660 if( iReduce<k ) iReduce = k;
4661 }
drhd8b77e22014-09-06 01:35:57 +00004662 }
danaa9933c2014-04-24 20:04:49 +00004663 }
drhcca9f3d2013-09-06 15:23:29 +00004664 }
drh7a1bca72014-11-22 18:50:44 +00004665 if( pLoop->nOut > nRow-iReduce ) pLoop->nOut = nRow - iReduce;
drhcca9f3d2013-09-06 15:23:29 +00004666}
4667
4668/*
drhdbd94862014-07-23 23:57:42 +00004669** Adjust the cost C by the costMult facter T. This only occurs if
4670** compiled with -DSQLITE_ENABLE_COSTMULT
4671*/
4672#ifdef SQLITE_ENABLE_COSTMULT
4673# define ApplyCostMultiplier(C,T) C += T
4674#else
4675# define ApplyCostMultiplier(C,T)
4676#endif
4677
4678/*
dan4a6b8a02014-04-30 14:47:01 +00004679** We have so far matched pBuilder->pNew->u.btree.nEq terms of the
4680** index pIndex. Try to match one more.
4681**
4682** When this function is called, pBuilder->pNew->nOut contains the
4683** number of rows expected to be visited by filtering using the nEq
4684** terms only. If it is modified, this value is restored before this
4685** function returns.
drh1c8148f2013-05-04 20:25:23 +00004686**
4687** If pProbe->tnum==0, that means pIndex is a fake index used for the
4688** INTEGER PRIMARY KEY.
4689*/
drh5346e952013-05-08 14:14:26 +00004690static int whereLoopAddBtreeIndex(
drh1c8148f2013-05-04 20:25:23 +00004691 WhereLoopBuilder *pBuilder, /* The WhereLoop factory */
4692 struct SrcList_item *pSrc, /* FROM clause term being analyzed */
4693 Index *pProbe, /* An index on pSrc */
drhbf539c42013-10-05 18:16:02 +00004694 LogEst nInMul /* log(Number of iterations due to IN) */
drh1c8148f2013-05-04 20:25:23 +00004695){
drh70d18342013-06-06 19:16:33 +00004696 WhereInfo *pWInfo = pBuilder->pWInfo; /* WHERE analyse context */
4697 Parse *pParse = pWInfo->pParse; /* Parsing context */
4698 sqlite3 *db = pParse->db; /* Database connection malloc context */
drh1c8148f2013-05-04 20:25:23 +00004699 WhereLoop *pNew; /* Template WhereLoop under construction */
4700 WhereTerm *pTerm; /* A WhereTerm under consideration */
drh43fe25f2013-05-07 23:06:23 +00004701 int opMask; /* Valid operators for constraints */
drh1c8148f2013-05-04 20:25:23 +00004702 WhereScan scan; /* Iterator for WHERE terms */
drh4efc9292013-06-06 23:02:03 +00004703 Bitmask saved_prereq; /* Original value of pNew->prereq */
4704 u16 saved_nLTerm; /* Original value of pNew->nLTerm */
drhcd8629e2013-11-13 12:27:25 +00004705 u16 saved_nEq; /* Original value of pNew->u.btree.nEq */
drhc8bbce12014-10-21 01:05:09 +00004706 u16 saved_nSkip; /* Original value of pNew->nSkip */
drh4efc9292013-06-06 23:02:03 +00004707 u32 saved_wsFlags; /* Original value of pNew->wsFlags */
drhbf539c42013-10-05 18:16:02 +00004708 LogEst saved_nOut; /* Original value of pNew->nOut */
drha18f3d22013-05-08 03:05:41 +00004709 int iCol; /* Index of the column in the table */
drh5346e952013-05-08 14:14:26 +00004710 int rc = SQLITE_OK; /* Return code */
drhd8b77e22014-09-06 01:35:57 +00004711 LogEst rSize; /* Number of rows in the table */
drhbf539c42013-10-05 18:16:02 +00004712 LogEst rLogSize; /* Logarithm of table size */
drhc7f0d222013-06-19 03:27:12 +00004713 WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
drh1c8148f2013-05-04 20:25:23 +00004714
drh1c8148f2013-05-04 20:25:23 +00004715 pNew = pBuilder->pNew;
drh5346e952013-05-08 14:14:26 +00004716 if( db->mallocFailed ) return SQLITE_NOMEM;
drh1c8148f2013-05-04 20:25:23 +00004717
drh5346e952013-05-08 14:14:26 +00004718 assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
drh43fe25f2013-05-07 23:06:23 +00004719 assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
4720 if( pNew->wsFlags & WHERE_BTM_LIMIT ){
4721 opMask = WO_LT|WO_LE;
4722 }else if( pProbe->tnum<=0 || (pSrc->jointype & JT_LEFT)!=0 ){
4723 opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE;
drh1c8148f2013-05-04 20:25:23 +00004724 }else{
drh43fe25f2013-05-07 23:06:23 +00004725 opMask = WO_EQ|WO_IN|WO_ISNULL|WO_GT|WO_GE|WO_LT|WO_LE;
drh1c8148f2013-05-04 20:25:23 +00004726 }
drhef866372013-05-22 20:49:02 +00004727 if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
drh1c8148f2013-05-04 20:25:23 +00004728
dan39129ce2014-06-30 15:23:57 +00004729 assert( pNew->u.btree.nEq<pProbe->nColumn );
4730 iCol = pProbe->aiColumn[pNew->u.btree.nEq];
4731
drha18f3d22013-05-08 03:05:41 +00004732 pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, iCol,
drh0f133a42013-05-22 17:01:17 +00004733 opMask, pProbe);
drh4efc9292013-06-06 23:02:03 +00004734 saved_nEq = pNew->u.btree.nEq;
drhc8bbce12014-10-21 01:05:09 +00004735 saved_nSkip = pNew->nSkip;
drh4efc9292013-06-06 23:02:03 +00004736 saved_nLTerm = pNew->nLTerm;
4737 saved_wsFlags = pNew->wsFlags;
4738 saved_prereq = pNew->prereq;
4739 saved_nOut = pNew->nOut;
drhb8a8e8a2013-06-10 19:12:39 +00004740 pNew->rSetup = 0;
drhd8b77e22014-09-06 01:35:57 +00004741 rSize = pProbe->aiRowLogEst[0];
4742 rLogSize = estLog(rSize);
drh5346e952013-05-08 14:14:26 +00004743 for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
dan8ad1d8b2014-04-25 20:22:45 +00004744 u16 eOp = pTerm->eOperator; /* Shorthand for pTerm->eOperator */
danaa9933c2014-04-24 20:04:49 +00004745 LogEst rCostIdx;
dan8ad1d8b2014-04-25 20:22:45 +00004746 LogEst nOutUnadjusted; /* nOut before IN() and WHERE adjustments */
drhb8a8e8a2013-06-10 19:12:39 +00004747 int nIn = 0;
drh1435a9a2013-08-27 23:15:44 +00004748#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
dan7a419232013-08-06 20:01:43 +00004749 int nRecValid = pBuilder->nRecValid;
drhb5246e52013-07-08 21:12:57 +00004750#endif
dan8ad1d8b2014-04-25 20:22:45 +00004751 if( (eOp==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)
dan8bff07a2013-08-29 14:56:14 +00004752 && (iCol<0 || pSrc->pTab->aCol[iCol].notNull)
4753 ){
4754 continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */
4755 }
dan7a419232013-08-06 20:01:43 +00004756 if( pTerm->prereqRight & pNew->maskSelf ) continue;
4757
drha40da622015-03-09 12:11:56 +00004758 /* Do not allow the upper bound of a LIKE optimization range constraint
4759 ** to mix with a lower range bound from some other source */
4760 if( pTerm->wtFlags & TERM_LIKEOPT && pTerm->eOperator==WO_LT ) continue;
4761
drh4efc9292013-06-06 23:02:03 +00004762 pNew->wsFlags = saved_wsFlags;
4763 pNew->u.btree.nEq = saved_nEq;
4764 pNew->nLTerm = saved_nLTerm;
4765 if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
4766 pNew->aLTerm[pNew->nLTerm++] = pTerm;
4767 pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
dan8ad1d8b2014-04-25 20:22:45 +00004768
4769 assert( nInMul==0
4770 || (pNew->wsFlags & WHERE_COLUMN_NULL)!=0
4771 || (pNew->wsFlags & WHERE_COLUMN_IN)!=0
4772 || (pNew->wsFlags & WHERE_SKIPSCAN)!=0
4773 );
4774
4775 if( eOp & WO_IN ){
drha18f3d22013-05-08 03:05:41 +00004776 Expr *pExpr = pTerm->pExpr;
4777 pNew->wsFlags |= WHERE_COLUMN_IN;
4778 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
drhe1e2e9a2013-06-13 15:16:53 +00004779 /* "x IN (SELECT ...)": TUNING: the SELECT returns 25 rows */
drhbf539c42013-10-05 18:16:02 +00004780 nIn = 46; assert( 46==sqlite3LogEst(25) );
drha18f3d22013-05-08 03:05:41 +00004781 }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
4782 /* "x IN (value, value, ...)" */
drhbf539c42013-10-05 18:16:02 +00004783 nIn = sqlite3LogEst(pExpr->x.pList->nExpr);
drhf1645f02013-05-07 19:44:38 +00004784 }
drh2b59b3a2014-03-20 13:26:47 +00004785 assert( nIn>0 ); /* RHS always has 2 or more terms... The parser
4786 ** changes "x IN (?)" into "x=?". */
dan8ad1d8b2014-04-25 20:22:45 +00004787
4788 }else if( eOp & (WO_EQ) ){
drha18f3d22013-05-08 03:05:41 +00004789 pNew->wsFlags |= WHERE_COLUMN_EQ;
dan8ad1d8b2014-04-25 20:22:45 +00004790 if( iCol<0 || (nInMul==0 && pNew->u.btree.nEq==pProbe->nKeyCol-1) ){
dan2813bde2015-04-11 11:44:27 +00004791 if( iCol>=0 && pProbe->uniqNotNull==0 ){
drhe39a7322014-02-03 14:04:11 +00004792 pNew->wsFlags |= WHERE_UNQ_WANTED;
4793 }else{
4794 pNew->wsFlags |= WHERE_ONEROW;
4795 }
drh21f7ff72013-06-03 15:07:23 +00004796 }
dan2dd3cdc2014-04-26 20:21:14 +00004797 }else if( eOp & WO_ISNULL ){
4798 pNew->wsFlags |= WHERE_COLUMN_NULL;
dan8ad1d8b2014-04-25 20:22:45 +00004799 }else if( eOp & (WO_GT|WO_GE) ){
4800 testcase( eOp & WO_GT );
4801 testcase( eOp & WO_GE );
drha18f3d22013-05-08 03:05:41 +00004802 pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
drh6f2bfad2013-06-03 17:35:22 +00004803 pBtm = pTerm;
4804 pTop = 0;
drha40da622015-03-09 12:11:56 +00004805 if( pTerm->wtFlags & TERM_LIKEOPT ){
drh80314622015-03-09 13:01:02 +00004806 /* Range contraints that come from the LIKE optimization are
4807 ** always used in pairs. */
drha40da622015-03-09 12:11:56 +00004808 pTop = &pTerm[1];
4809 assert( (pTop-(pTerm->pWC->a))<pTerm->pWC->nTerm );
4810 assert( pTop->wtFlags & TERM_LIKEOPT );
4811 assert( pTop->eOperator==WO_LT );
4812 if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
4813 pNew->aLTerm[pNew->nLTerm++] = pTop;
4814 pNew->wsFlags |= WHERE_TOP_LIMIT;
4815 }
dan2dd3cdc2014-04-26 20:21:14 +00004816 }else{
dan8ad1d8b2014-04-25 20:22:45 +00004817 assert( eOp & (WO_LT|WO_LE) );
4818 testcase( eOp & WO_LT );
4819 testcase( eOp & WO_LE );
drha18f3d22013-05-08 03:05:41 +00004820 pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
drh6f2bfad2013-06-03 17:35:22 +00004821 pTop = pTerm;
4822 pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
drh4efc9292013-06-06 23:02:03 +00004823 pNew->aLTerm[pNew->nLTerm-2] : 0;
drh1c8148f2013-05-04 20:25:23 +00004824 }
dan8ad1d8b2014-04-25 20:22:45 +00004825
4826 /* At this point pNew->nOut is set to the number of rows expected to
4827 ** be visited by the index scan before considering term pTerm, or the
4828 ** values of nIn and nInMul. In other words, assuming that all
4829 ** "x IN(...)" terms are replaced with "x = ?". This block updates
4830 ** the value of pNew->nOut to account for pTerm (but not nIn/nInMul). */
4831 assert( pNew->nOut==saved_nOut );
drh6f2bfad2013-06-03 17:35:22 +00004832 if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
danaa9933c2014-04-24 20:04:49 +00004833 /* Adjust nOut using stat3/stat4 data. Or, if there is no stat3/stat4
4834 ** data, using some other estimate. */
drh186ad8c2013-10-08 18:40:37 +00004835 whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew);
dan8ad1d8b2014-04-25 20:22:45 +00004836 }else{
4837 int nEq = ++pNew->u.btree.nEq;
4838 assert( eOp & (WO_ISNULL|WO_EQ|WO_IN) );
4839
4840 assert( pNew->nOut==saved_nOut );
dan09e1df62014-04-29 16:10:22 +00004841 if( pTerm->truthProb<=0 && iCol>=0 ){
dan8ad1d8b2014-04-25 20:22:45 +00004842 assert( (eOp & WO_IN) || nIn==0 );
drhc5f246e2014-05-01 20:24:21 +00004843 testcase( eOp & WO_IN );
dan8ad1d8b2014-04-25 20:22:45 +00004844 pNew->nOut += pTerm->truthProb;
4845 pNew->nOut -= nIn;
dan8ad1d8b2014-04-25 20:22:45 +00004846 }else{
drh1435a9a2013-08-27 23:15:44 +00004847#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
dan8ad1d8b2014-04-25 20:22:45 +00004848 tRowcnt nOut = 0;
4849 if( nInMul==0
4850 && pProbe->nSample
4851 && pNew->u.btree.nEq<=pProbe->nSampleCol
dan8ad1d8b2014-04-25 20:22:45 +00004852 && ((eOp & WO_IN)==0 || !ExprHasProperty(pTerm->pExpr, EP_xIsSelect))
dan8ad1d8b2014-04-25 20:22:45 +00004853 ){
4854 Expr *pExpr = pTerm->pExpr;
4855 if( (eOp & (WO_EQ|WO_ISNULL))!=0 ){
4856 testcase( eOp & WO_EQ );
4857 testcase( eOp & WO_ISNULL );
4858 rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut);
4859 }else{
4860 rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut);
4861 }
dan8ad1d8b2014-04-25 20:22:45 +00004862 if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
4863 if( rc!=SQLITE_OK ) break; /* Jump out of the pTerm loop */
4864 if( nOut ){
4865 pNew->nOut = sqlite3LogEst(nOut);
4866 if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut;
4867 pNew->nOut -= nIn;
4868 }
4869 }
4870 if( nOut==0 )
4871#endif
4872 {
4873 pNew->nOut += (pProbe->aiRowLogEst[nEq] - pProbe->aiRowLogEst[nEq-1]);
4874 if( eOp & WO_ISNULL ){
4875 /* TUNING: If there is no likelihood() value, assume that a
4876 ** "col IS NULL" expression matches twice as many rows
4877 ** as (col=?). */
4878 pNew->nOut += 10;
4879 }
4880 }
dan6cb8d762013-08-08 11:48:57 +00004881 }
drh6f2bfad2013-06-03 17:35:22 +00004882 }
dan8ad1d8b2014-04-25 20:22:45 +00004883
danaa9933c2014-04-24 20:04:49 +00004884 /* Set rCostIdx to the cost of visiting selected rows in index. Add
4885 ** it to pNew->rRun, which is currently set to the cost of the index
4886 ** seek only. Then, if this is a non-covering index, add the cost of
4887 ** visiting the rows in the main table. */
4888 rCostIdx = pNew->nOut + 1 + (15*pProbe->szIdxRow)/pSrc->pTab->szTabRow;
dan8ad1d8b2014-04-25 20:22:45 +00004889 pNew->rRun = sqlite3LogEstAdd(rLogSize, rCostIdx);
drhe217efc2013-06-12 03:48:41 +00004890 if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
danaa9933c2014-04-24 20:04:49 +00004891 pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut + 16);
drheb04de32013-05-10 15:16:30 +00004892 }
drhdbd94862014-07-23 23:57:42 +00004893 ApplyCostMultiplier(pNew->rRun, pProbe->pTable->costMult);
danaa9933c2014-04-24 20:04:49 +00004894
dan8ad1d8b2014-04-25 20:22:45 +00004895 nOutUnadjusted = pNew->nOut;
4896 pNew->rRun += nInMul + nIn;
4897 pNew->nOut += nInMul + nIn;
drhd8b77e22014-09-06 01:35:57 +00004898 whereLoopOutputAdjust(pBuilder->pWC, pNew, rSize);
drhcf8fa7a2013-05-10 20:26:22 +00004899 rc = whereLoopInsert(pBuilder, pNew);
dan440e6ff2014-04-28 08:49:54 +00004900
4901 if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
4902 pNew->nOut = saved_nOut;
4903 }else{
4904 pNew->nOut = nOutUnadjusted;
4905 }
dan8ad1d8b2014-04-25 20:22:45 +00004906
drh5346e952013-05-08 14:14:26 +00004907 if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
dan39129ce2014-06-30 15:23:57 +00004908 && pNew->u.btree.nEq<pProbe->nColumn
drh5346e952013-05-08 14:14:26 +00004909 ){
drhb8a8e8a2013-06-10 19:12:39 +00004910 whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
drha18f3d22013-05-08 03:05:41 +00004911 }
danad45ed72013-08-08 12:21:32 +00004912 pNew->nOut = saved_nOut;
drh1435a9a2013-08-27 23:15:44 +00004913#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
dan7a419232013-08-06 20:01:43 +00004914 pBuilder->nRecValid = nRecValid;
dan7a419232013-08-06 20:01:43 +00004915#endif
drh1c8148f2013-05-04 20:25:23 +00004916 }
drh4efc9292013-06-06 23:02:03 +00004917 pNew->prereq = saved_prereq;
4918 pNew->u.btree.nEq = saved_nEq;
drhc8bbce12014-10-21 01:05:09 +00004919 pNew->nSkip = saved_nSkip;
drh4efc9292013-06-06 23:02:03 +00004920 pNew->wsFlags = saved_wsFlags;
4921 pNew->nOut = saved_nOut;
4922 pNew->nLTerm = saved_nLTerm;
drhc8bbce12014-10-21 01:05:09 +00004923
4924 /* Consider using a skip-scan if there are no WHERE clause constraints
4925 ** available for the left-most terms of the index, and if the average
4926 ** number of repeats in the left-most terms is at least 18.
4927 **
4928 ** The magic number 18 is selected on the basis that scanning 17 rows
4929 ** is almost always quicker than an index seek (even though if the index
4930 ** contains fewer than 2^17 rows we assume otherwise in other parts of
4931 ** the code). And, even if it is not, it should not be too much slower.
4932 ** On the other hand, the extra seeks could end up being significantly
4933 ** more expensive. */
4934 assert( 42==sqlite3LogEst(18) );
4935 if( saved_nEq==saved_nSkip
4936 && saved_nEq+1<pProbe->nKeyCol
drhf9df2fb2014-11-15 19:08:13 +00004937 && pProbe->noSkipScan==0
drhc8bbce12014-10-21 01:05:09 +00004938 && pProbe->aiRowLogEst[saved_nEq+1]>=42 /* TUNING: Minimum for skip-scan */
4939 && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK
4940 ){
4941 LogEst nIter;
4942 pNew->u.btree.nEq++;
4943 pNew->nSkip++;
4944 pNew->aLTerm[pNew->nLTerm++] = 0;
4945 pNew->wsFlags |= WHERE_SKIPSCAN;
4946 nIter = pProbe->aiRowLogEst[saved_nEq] - pProbe->aiRowLogEst[saved_nEq+1];
drhc8bbce12014-10-21 01:05:09 +00004947 pNew->nOut -= nIter;
4948 /* TUNING: Because uncertainties in the estimates for skip-scan queries,
4949 ** add a 1.375 fudge factor to make skip-scan slightly less likely. */
4950 nIter += 5;
4951 whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nIter + nInMul);
4952 pNew->nOut = saved_nOut;
4953 pNew->u.btree.nEq = saved_nEq;
4954 pNew->nSkip = saved_nSkip;
4955 pNew->wsFlags = saved_wsFlags;
4956 }
4957
drh5346e952013-05-08 14:14:26 +00004958 return rc;
drh1c8148f2013-05-04 20:25:23 +00004959}
4960
4961/*
drh23f98da2013-05-21 15:52:07 +00004962** Return True if it is possible that pIndex might be useful in
4963** implementing the ORDER BY clause in pBuilder.
4964**
4965** Return False if pBuilder does not contain an ORDER BY clause or
4966** if there is no way for pIndex to be useful in implementing that
4967** ORDER BY clause.
4968*/
4969static int indexMightHelpWithOrderBy(
4970 WhereLoopBuilder *pBuilder,
4971 Index *pIndex,
4972 int iCursor
4973){
4974 ExprList *pOB;
drh6d381472013-06-13 17:58:08 +00004975 int ii, jj;
drh23f98da2013-05-21 15:52:07 +00004976
drh53cfbe92013-06-13 17:28:22 +00004977 if( pIndex->bUnordered ) return 0;
drh70d18342013-06-06 19:16:33 +00004978 if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
drh23f98da2013-05-21 15:52:07 +00004979 for(ii=0; ii<pOB->nExpr; ii++){
drh45c154a2013-06-03 20:46:35 +00004980 Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr);
drh23f98da2013-05-21 15:52:07 +00004981 if( pExpr->op!=TK_COLUMN ) return 0;
4982 if( pExpr->iTable==iCursor ){
drh137fd4f2014-09-19 02:01:37 +00004983 if( pExpr->iColumn<0 ) return 1;
drhbbbdc832013-10-22 18:01:40 +00004984 for(jj=0; jj<pIndex->nKeyCol; jj++){
drh6d381472013-06-13 17:58:08 +00004985 if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
4986 }
drh23f98da2013-05-21 15:52:07 +00004987 }
4988 }
4989 return 0;
4990}
4991
4992/*
drh92a121f2013-06-10 12:15:47 +00004993** Return a bitmask where 1s indicate that the corresponding column of
4994** the table is used by an index. Only the first 63 columns are considered.
4995*/
drhfd5874d2013-06-12 14:52:39 +00004996static Bitmask columnsInIndex(Index *pIdx){
drh92a121f2013-06-10 12:15:47 +00004997 Bitmask m = 0;
4998 int j;
drhec95c442013-10-23 01:57:32 +00004999 for(j=pIdx->nColumn-1; j>=0; j--){
drh92a121f2013-06-10 12:15:47 +00005000 int x = pIdx->aiColumn[j];
drhec95c442013-10-23 01:57:32 +00005001 if( x>=0 ){
5002 testcase( x==BMS-1 );
5003 testcase( x==BMS-2 );
5004 if( x<BMS-1 ) m |= MASKBIT(x);
5005 }
drh92a121f2013-06-10 12:15:47 +00005006 }
5007 return m;
5008}
5009
drh4bd5f732013-07-31 23:22:39 +00005010/* Check to see if a partial index with pPartIndexWhere can be used
5011** in the current query. Return true if it can be and false if not.
5012*/
5013static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere){
5014 int i;
5015 WhereTerm *pTerm;
5016 for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
dan2a45cb52015-02-24 20:10:49 +00005017 Expr *pExpr = pTerm->pExpr;
5018 if( sqlite3ExprImpliesExpr(pExpr, pWhere, iTab)
5019 && (!ExprHasProperty(pExpr, EP_FromJoin) || pExpr->iRightJoinTable==iTab)
drh077f06e2015-02-24 16:48:59 +00005020 ){
5021 return 1;
5022 }
drh4bd5f732013-07-31 23:22:39 +00005023 }
5024 return 0;
5025}
drh92a121f2013-06-10 12:15:47 +00005026
5027/*
dan51576f42013-07-02 10:06:15 +00005028** Add all WhereLoop objects for a single table of the join where the table
drh0823c892013-05-11 00:06:23 +00005029** is idenfied by pBuilder->pNew->iTab. That table is guaranteed to be
5030** a b-tree table, not a virtual table.
dan81647222014-04-30 15:00:16 +00005031**
5032** The costs (WhereLoop.rRun) of the b-tree loops added by this function
5033** are calculated as follows:
5034**
5035** For a full scan, assuming the table (or index) contains nRow rows:
5036**
5037** cost = nRow * 3.0 // full-table scan
5038** cost = nRow * K // scan of covering index
5039** cost = nRow * (K+3.0) // scan of non-covering index
5040**
5041** where K is a value between 1.1 and 3.0 set based on the relative
5042** estimated average size of the index and table records.
5043**
5044** For an index scan, where nVisit is the number of index rows visited
5045** by the scan, and nSeek is the number of seek operations required on
5046** the index b-tree:
5047**
5048** cost = nSeek * (log(nRow) + K * nVisit) // covering index
5049** cost = nSeek * (log(nRow) + (K+3.0) * nVisit) // non-covering index
5050**
5051** Normally, nSeek is 1. nSeek values greater than 1 come about if the
5052** WHERE clause includes "x IN (....)" terms used in place of "x=?". Or when
5053** implicit "x IN (SELECT x FROM tbl)" terms are added for skip-scans.
drh83a305f2014-07-22 12:05:32 +00005054**
5055** The estimated values (nRow, nVisit, nSeek) often contain a large amount
5056** of uncertainty. For this reason, scoring is designed to pick plans that
5057** "do the least harm" if the estimates are inaccurate. For example, a
5058** log(nRow) factor is omitted from a non-covering index scan in order to
5059** bias the scoring in favor of using an index, since the worst-case
5060** performance of using an index is far better than the worst-case performance
5061** of a full table scan.
drhf1b5f5b2013-05-02 00:15:01 +00005062*/
drh5346e952013-05-08 14:14:26 +00005063static int whereLoopAddBtree(
drh1c8148f2013-05-04 20:25:23 +00005064 WhereLoopBuilder *pBuilder, /* WHERE clause information */
drh1c8148f2013-05-04 20:25:23 +00005065 Bitmask mExtra /* Extra prerequesites for using this table */
drhf1b5f5b2013-05-02 00:15:01 +00005066){
drh70d18342013-06-06 19:16:33 +00005067 WhereInfo *pWInfo; /* WHERE analysis context */
drh1c8148f2013-05-04 20:25:23 +00005068 Index *pProbe; /* An index we are evaluating */
drh1c8148f2013-05-04 20:25:23 +00005069 Index sPk; /* A fake index object for the primary key */
dancfc9df72014-04-25 15:01:01 +00005070 LogEst aiRowEstPk[2]; /* The aiRowLogEst[] value for the sPk index */
drhbbbdc832013-10-22 18:01:40 +00005071 i16 aiColumnPk = -1; /* The aColumn[] value for the sPk index */
drh70d18342013-06-06 19:16:33 +00005072 SrcList *pTabList; /* The FROM clause */
drh1c8148f2013-05-04 20:25:23 +00005073 struct SrcList_item *pSrc; /* The FROM clause btree term to add */
drh1c8148f2013-05-04 20:25:23 +00005074 WhereLoop *pNew; /* Template WhereLoop object */
drh5346e952013-05-08 14:14:26 +00005075 int rc = SQLITE_OK; /* Return code */
drhd044d202013-05-31 12:43:55 +00005076 int iSortIdx = 1; /* Index number */
drh23f98da2013-05-21 15:52:07 +00005077 int b; /* A boolean value */
drhbf539c42013-10-05 18:16:02 +00005078 LogEst rSize; /* number of rows in the table */
5079 LogEst rLogSize; /* Logarithm of the number of rows in the table */
drh4bd5f732013-07-31 23:22:39 +00005080 WhereClause *pWC; /* The parsed WHERE clause */
drh3495d202013-10-07 17:32:15 +00005081 Table *pTab; /* Table being queried */
drh23f98da2013-05-21 15:52:07 +00005082
drh1c8148f2013-05-04 20:25:23 +00005083 pNew = pBuilder->pNew;
drh70d18342013-06-06 19:16:33 +00005084 pWInfo = pBuilder->pWInfo;
5085 pTabList = pWInfo->pTabList;
5086 pSrc = pTabList->a + pNew->iTab;
drh3495d202013-10-07 17:32:15 +00005087 pTab = pSrc->pTab;
drh4bd5f732013-07-31 23:22:39 +00005088 pWC = pBuilder->pWC;
drh0823c892013-05-11 00:06:23 +00005089 assert( !IsVirtual(pSrc->pTab) );
drh1c8148f2013-05-04 20:25:23 +00005090
5091 if( pSrc->pIndex ){
5092 /* An INDEXED BY clause specifies a particular index to use */
5093 pProbe = pSrc->pIndex;
drhec95c442013-10-23 01:57:32 +00005094 }else if( !HasRowid(pTab) ){
5095 pProbe = pTab->pIndex;
drh1c8148f2013-05-04 20:25:23 +00005096 }else{
5097 /* There is no INDEXED BY clause. Create a fake Index object in local
5098 ** variable sPk to represent the rowid primary key index. Make this
5099 ** fake index the first in a chain of Index objects with all of the real
5100 ** indices to follow */
5101 Index *pFirst; /* First of real indices on the table */
5102 memset(&sPk, 0, sizeof(Index));
drhbbbdc832013-10-22 18:01:40 +00005103 sPk.nKeyCol = 1;
dan39129ce2014-06-30 15:23:57 +00005104 sPk.nColumn = 1;
drh1c8148f2013-05-04 20:25:23 +00005105 sPk.aiColumn = &aiColumnPk;
dancfc9df72014-04-25 15:01:01 +00005106 sPk.aiRowLogEst = aiRowEstPk;
drh1c8148f2013-05-04 20:25:23 +00005107 sPk.onError = OE_Replace;
drh3495d202013-10-07 17:32:15 +00005108 sPk.pTable = pTab;
danaa9933c2014-04-24 20:04:49 +00005109 sPk.szIdxRow = pTab->szTabRow;
dancfc9df72014-04-25 15:01:01 +00005110 aiRowEstPk[0] = pTab->nRowLogEst;
5111 aiRowEstPk[1] = 0;
drh1c8148f2013-05-04 20:25:23 +00005112 pFirst = pSrc->pTab->pIndex;
5113 if( pSrc->notIndexed==0 ){
5114 /* The real indices of the table are only considered if the
5115 ** NOT INDEXED qualifier is omitted from the FROM clause */
5116 sPk.pNext = pFirst;
5117 }
5118 pProbe = &sPk;
5119 }
dancfc9df72014-04-25 15:01:01 +00005120 rSize = pTab->nRowLogEst;
drheb04de32013-05-10 15:16:30 +00005121 rLogSize = estLog(rSize);
5122
drhfeb56e02013-08-23 17:33:46 +00005123#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
drheb04de32013-05-10 15:16:30 +00005124 /* Automatic indexes */
drhaa32e3c2013-07-16 21:31:23 +00005125 if( !pBuilder->pOrSet
drh8e8e7ef2015-03-02 17:25:00 +00005126 && (pWInfo->wctrlFlags & WHERE_NO_AUTOINDEX)==0
drh4fe425a2013-06-12 17:08:06 +00005127 && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
5128 && pSrc->pIndex==0
drheb04de32013-05-10 15:16:30 +00005129 && !pSrc->viaCoroutine
5130 && !pSrc->notIndexed
drhec95c442013-10-23 01:57:32 +00005131 && HasRowid(pTab)
drheb04de32013-05-10 15:16:30 +00005132 && !pSrc->isCorrelated
dan62ba4e42014-01-15 18:21:41 +00005133 && !pSrc->isRecursive
drheb04de32013-05-10 15:16:30 +00005134 ){
5135 /* Generate auto-index WhereLoops */
drheb04de32013-05-10 15:16:30 +00005136 WhereTerm *pTerm;
5137 WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
5138 for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
drh79a13bf2013-05-31 20:28:28 +00005139 if( pTerm->prereqRight & pNew->maskSelf ) continue;
drheb04de32013-05-10 15:16:30 +00005140 if( termCanDriveIndex(pTerm, pSrc, 0) ){
5141 pNew->u.btree.nEq = 1;
drhc8bbce12014-10-21 01:05:09 +00005142 pNew->nSkip = 0;
drhef866372013-05-22 20:49:02 +00005143 pNew->u.btree.pIndex = 0;
drh4efc9292013-06-06 23:02:03 +00005144 pNew->nLTerm = 1;
5145 pNew->aLTerm[0] = pTerm;
drhe1e2e9a2013-06-13 15:16:53 +00005146 /* TUNING: One-time cost for computing the automatic index is
drh7e074332014-09-22 14:30:51 +00005147 ** estimated to be X*N*log2(N) where N is the number of rows in
5148 ** the table being indexed and where X is 7 (LogEst=28) for normal
5149 ** tables or 1.375 (LogEst=4) for views and subqueries. The value
5150 ** of X is smaller for views and subqueries so that the query planner
5151 ** will be more aggressive about generating automatic indexes for
5152 ** those objects, since there is no opportunity to add schema
5153 ** indexes on subqueries and views. */
5154 pNew->rSetup = rLogSize + rSize + 4;
5155 if( pTab->pSelect==0 && (pTab->tabFlags & TF_Ephemeral)==0 ){
5156 pNew->rSetup += 24;
5157 }
drhdbd94862014-07-23 23:57:42 +00005158 ApplyCostMultiplier(pNew->rSetup, pTab->costMult);
drh986b3872013-06-28 21:12:20 +00005159 /* TUNING: Each index lookup yields 20 rows in the table. This
5160 ** is more than the usual guess of 10 rows, since we have no way
peter.d.reid60ec9142014-09-06 16:39:46 +00005161 ** of knowing how selective the index will ultimately be. It would
drh986b3872013-06-28 21:12:20 +00005162 ** not be unreasonable to make this value much larger. */
drhbf539c42013-10-05 18:16:02 +00005163 pNew->nOut = 43; assert( 43==sqlite3LogEst(20) );
drhb50596d2013-10-08 20:42:41 +00005164 pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut);
drh986b3872013-06-28 21:12:20 +00005165 pNew->wsFlags = WHERE_AUTO_INDEX;
drheb04de32013-05-10 15:16:30 +00005166 pNew->prereq = mExtra | pTerm->prereqRight;
drhcf8fa7a2013-05-10 20:26:22 +00005167 rc = whereLoopInsert(pBuilder, pNew);
drheb04de32013-05-10 15:16:30 +00005168 }
5169 }
5170 }
drhfeb56e02013-08-23 17:33:46 +00005171#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
drh1c8148f2013-05-04 20:25:23 +00005172
5173 /* Loop over all indices
5174 */
drh23f98da2013-05-21 15:52:07 +00005175 for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){
drh4bd5f732013-07-31 23:22:39 +00005176 if( pProbe->pPartIdxWhere!=0
dan08291692014-08-27 17:37:20 +00005177 && !whereUsablePartialIndex(pSrc->iCursor, pWC, pProbe->pPartIdxWhere) ){
5178 testcase( pNew->iTab!=pSrc->iCursor ); /* See ticket [98d973b8f5] */
drh4bd5f732013-07-31 23:22:39 +00005179 continue; /* Partial index inappropriate for this query */
5180 }
dan7de2a1f2014-04-28 20:11:20 +00005181 rSize = pProbe->aiRowLogEst[0];
drh5346e952013-05-08 14:14:26 +00005182 pNew->u.btree.nEq = 0;
drhc8bbce12014-10-21 01:05:09 +00005183 pNew->nSkip = 0;
drh4efc9292013-06-06 23:02:03 +00005184 pNew->nLTerm = 0;
drh23f98da2013-05-21 15:52:07 +00005185 pNew->iSortIdx = 0;
drhb8a8e8a2013-06-10 19:12:39 +00005186 pNew->rSetup = 0;
drh23f98da2013-05-21 15:52:07 +00005187 pNew->prereq = mExtra;
drh74f91d42013-06-19 18:01:44 +00005188 pNew->nOut = rSize;
drh23f98da2013-05-21 15:52:07 +00005189 pNew->u.btree.pIndex = pProbe;
5190 b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
drh53cfbe92013-06-13 17:28:22 +00005191 /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
5192 assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
drh43fe25f2013-05-07 23:06:23 +00005193 if( pProbe->tnum<=0 ){
5194 /* Integer primary key index */
5195 pNew->wsFlags = WHERE_IPK;
drh23f98da2013-05-21 15:52:07 +00005196
5197 /* Full table scan */
drhd044d202013-05-31 12:43:55 +00005198 pNew->iSortIdx = b ? iSortIdx : 0;
danaa9933c2014-04-24 20:04:49 +00005199 /* TUNING: Cost of full table scan is (N*3.0). */
5200 pNew->rRun = rSize + 16;
drhdbd94862014-07-23 23:57:42 +00005201 ApplyCostMultiplier(pNew->rRun, pTab->costMult);
drhd8b77e22014-09-06 01:35:57 +00005202 whereLoopOutputAdjust(pWC, pNew, rSize);
drh23f98da2013-05-21 15:52:07 +00005203 rc = whereLoopInsert(pBuilder, pNew);
drhcca9f3d2013-09-06 15:23:29 +00005204 pNew->nOut = rSize;
drh23f98da2013-05-21 15:52:07 +00005205 if( rc ) break;
drh43fe25f2013-05-07 23:06:23 +00005206 }else{
drhec95c442013-10-23 01:57:32 +00005207 Bitmask m;
5208 if( pProbe->isCovering ){
5209 pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
5210 m = 0;
5211 }else{
5212 m = pSrc->colUsed & ~columnsInIndex(pProbe);
5213 pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
5214 }
drh1c8148f2013-05-04 20:25:23 +00005215
drh23f98da2013-05-21 15:52:07 +00005216 /* Full scan via index */
drh53cfbe92013-06-13 17:28:22 +00005217 if( b
drh702ba9f2013-11-07 21:25:13 +00005218 || !HasRowid(pTab)
drh53cfbe92013-06-13 17:28:22 +00005219 || ( m==0
5220 && pProbe->bUnordered==0
drh702ba9f2013-11-07 21:25:13 +00005221 && (pProbe->szIdxRow<pTab->szTabRow)
drh53cfbe92013-06-13 17:28:22 +00005222 && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
5223 && sqlite3GlobalConfig.bUseCis
5224 && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
5225 )
drhe3b7c922013-06-03 19:17:40 +00005226 ){
drh23f98da2013-05-21 15:52:07 +00005227 pNew->iSortIdx = b ? iSortIdx : 0;
danaa9933c2014-04-24 20:04:49 +00005228
5229 /* The cost of visiting the index rows is N*K, where K is
5230 ** between 1.1 and 3.0, depending on the relative sizes of the
5231 ** index and table rows. If this is a non-covering index scan,
5232 ** also add the cost of visiting table rows (N*3.0). */
5233 pNew->rRun = rSize + 1 + (15*pProbe->szIdxRow)/pTab->szTabRow;
5234 if( m!=0 ){
5235 pNew->rRun = sqlite3LogEstAdd(pNew->rRun, rSize+16);
drhe1e2e9a2013-06-13 15:16:53 +00005236 }
drhdbd94862014-07-23 23:57:42 +00005237 ApplyCostMultiplier(pNew->rRun, pTab->costMult);
drhd8b77e22014-09-06 01:35:57 +00005238 whereLoopOutputAdjust(pWC, pNew, rSize);
drh23f98da2013-05-21 15:52:07 +00005239 rc = whereLoopInsert(pBuilder, pNew);
drhcca9f3d2013-09-06 15:23:29 +00005240 pNew->nOut = rSize;
drh23f98da2013-05-21 15:52:07 +00005241 if( rc ) break;
5242 }
5243 }
dan7a419232013-08-06 20:01:43 +00005244
drhb8a8e8a2013-06-10 19:12:39 +00005245 rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
drh1435a9a2013-08-27 23:15:44 +00005246#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
dan87cd9322013-08-07 15:52:41 +00005247 sqlite3Stat4ProbeFree(pBuilder->pRec);
5248 pBuilder->nRecValid = 0;
5249 pBuilder->pRec = 0;
danddc2d6e2013-08-06 20:15:06 +00005250#endif
drh1c8148f2013-05-04 20:25:23 +00005251
5252 /* If there was an INDEXED BY clause, then only that one index is
5253 ** considered. */
5254 if( pSrc->pIndex ) break;
5255 }
drh5346e952013-05-08 14:14:26 +00005256 return rc;
drhf1b5f5b2013-05-02 00:15:01 +00005257}
5258
drh8636e9c2013-06-11 01:50:08 +00005259#ifndef SQLITE_OMIT_VIRTUALTABLE
drhf1b5f5b2013-05-02 00:15:01 +00005260/*
drh0823c892013-05-11 00:06:23 +00005261** Add all WhereLoop objects for a table of the join identified by
5262** pBuilder->pNew->iTab. That table is guaranteed to be a virtual table.
drhf1b5f5b2013-05-02 00:15:01 +00005263*/
drh5346e952013-05-08 14:14:26 +00005264static int whereLoopAddVirtual(
danff4b23b2013-11-12 12:17:16 +00005265 WhereLoopBuilder *pBuilder, /* WHERE clause information */
5266 Bitmask mExtra
drhf1b5f5b2013-05-02 00:15:01 +00005267){
drh70d18342013-06-06 19:16:33 +00005268 WhereInfo *pWInfo; /* WHERE analysis context */
drh5346e952013-05-08 14:14:26 +00005269 Parse *pParse; /* The parsing context */
5270 WhereClause *pWC; /* The WHERE clause */
5271 struct SrcList_item *pSrc; /* The FROM clause term to search */
5272 Table *pTab;
5273 sqlite3 *db;
5274 sqlite3_index_info *pIdxInfo;
5275 struct sqlite3_index_constraint *pIdxCons;
5276 struct sqlite3_index_constraint_usage *pUsage;
5277 WhereTerm *pTerm;
5278 int i, j;
5279 int iTerm, mxTerm;
drh4efc9292013-06-06 23:02:03 +00005280 int nConstraint;
drh5346e952013-05-08 14:14:26 +00005281 int seenIn = 0; /* True if an IN operator is seen */
5282 int seenVar = 0; /* True if a non-constant constraint is seen */
5283 int iPhase; /* 0: const w/o IN, 1: const, 2: no IN, 2: IN */
5284 WhereLoop *pNew;
drh5346e952013-05-08 14:14:26 +00005285 int rc = SQLITE_OK;
5286
drh70d18342013-06-06 19:16:33 +00005287 pWInfo = pBuilder->pWInfo;
5288 pParse = pWInfo->pParse;
drh5346e952013-05-08 14:14:26 +00005289 db = pParse->db;
5290 pWC = pBuilder->pWC;
drh5346e952013-05-08 14:14:26 +00005291 pNew = pBuilder->pNew;
drh70d18342013-06-06 19:16:33 +00005292 pSrc = &pWInfo->pTabList->a[pNew->iTab];
drhb2a90f02013-05-10 03:30:49 +00005293 pTab = pSrc->pTab;
drh0823c892013-05-11 00:06:23 +00005294 assert( IsVirtual(pTab) );
drhb2a90f02013-05-10 03:30:49 +00005295 pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pBuilder->pOrderBy);
drh5346e952013-05-08 14:14:26 +00005296 if( pIdxInfo==0 ) return SQLITE_NOMEM;
drh5346e952013-05-08 14:14:26 +00005297 pNew->prereq = 0;
drh5346e952013-05-08 14:14:26 +00005298 pNew->rSetup = 0;
5299 pNew->wsFlags = WHERE_VIRTUALTABLE;
drh4efc9292013-06-06 23:02:03 +00005300 pNew->nLTerm = 0;
drh5346e952013-05-08 14:14:26 +00005301 pNew->u.vtab.needFree = 0;
5302 pUsage = pIdxInfo->aConstraintUsage;
drh4efc9292013-06-06 23:02:03 +00005303 nConstraint = pIdxInfo->nConstraint;
drh7963b0e2013-06-17 21:37:40 +00005304 if( whereLoopResize(db, pNew, nConstraint) ){
5305 sqlite3DbFree(db, pIdxInfo);
5306 return SQLITE_NOMEM;
5307 }
drh5346e952013-05-08 14:14:26 +00005308
drh0823c892013-05-11 00:06:23 +00005309 for(iPhase=0; iPhase<=3; iPhase++){
drh5346e952013-05-08 14:14:26 +00005310 if( !seenIn && (iPhase&1)!=0 ){
5311 iPhase++;
5312 if( iPhase>3 ) break;
5313 }
5314 if( !seenVar && iPhase>1 ) break;
5315 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
5316 for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
5317 j = pIdxCons->iTermOffset;
5318 pTerm = &pWC->a[j];
5319 switch( iPhase ){
5320 case 0: /* Constants without IN operator */
5321 pIdxCons->usable = 0;
5322 if( (pTerm->eOperator & WO_IN)!=0 ){
5323 seenIn = 1;
drh7963b0e2013-06-17 21:37:40 +00005324 }
5325 if( pTerm->prereqRight!=0 ){
drh5346e952013-05-08 14:14:26 +00005326 seenVar = 1;
drh7963b0e2013-06-17 21:37:40 +00005327 }else if( (pTerm->eOperator & WO_IN)==0 ){
drh5346e952013-05-08 14:14:26 +00005328 pIdxCons->usable = 1;
5329 }
5330 break;
5331 case 1: /* Constants with IN operators */
5332 assert( seenIn );
5333 pIdxCons->usable = (pTerm->prereqRight==0);
5334 break;
5335 case 2: /* Variables without IN */
5336 assert( seenVar );
5337 pIdxCons->usable = (pTerm->eOperator & WO_IN)==0;
5338 break;
5339 default: /* Variables with IN */
5340 assert( seenVar && seenIn );
5341 pIdxCons->usable = 1;
5342 break;
5343 }
5344 }
5345 memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
5346 if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
5347 pIdxInfo->idxStr = 0;
5348 pIdxInfo->idxNum = 0;
5349 pIdxInfo->needToFreeIdxStr = 0;
5350 pIdxInfo->orderByConsumed = 0;
drh8636e9c2013-06-11 01:50:08 +00005351 pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
dana9f58152013-11-11 19:01:33 +00005352 pIdxInfo->estimatedRows = 25;
drh5346e952013-05-08 14:14:26 +00005353 rc = vtabBestIndex(pParse, pTab, pIdxInfo);
5354 if( rc ) goto whereLoopAddVtab_exit;
5355 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
danff4b23b2013-11-12 12:17:16 +00005356 pNew->prereq = mExtra;
drhc718f1c2013-05-08 20:05:58 +00005357 mxTerm = -1;
drh4efc9292013-06-06 23:02:03 +00005358 assert( pNew->nLSlot>=nConstraint );
5359 for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
drh3bd26f02013-05-24 14:52:03 +00005360 pNew->u.vtab.omitMask = 0;
drh4efc9292013-06-06 23:02:03 +00005361 for(i=0; i<nConstraint; i++, pIdxCons++){
drh5346e952013-05-08 14:14:26 +00005362 if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
5363 j = pIdxCons->iTermOffset;
drh4efc9292013-06-06 23:02:03 +00005364 if( iTerm>=nConstraint
drh5346e952013-05-08 14:14:26 +00005365 || j<0
5366 || j>=pWC->nTerm
drh4efc9292013-06-06 23:02:03 +00005367 || pNew->aLTerm[iTerm]!=0
drh5346e952013-05-08 14:14:26 +00005368 ){
5369 rc = SQLITE_ERROR;
5370 sqlite3ErrorMsg(pParse, "%s.xBestIndex() malfunction", pTab->zName);
5371 goto whereLoopAddVtab_exit;
5372 }
drh7963b0e2013-06-17 21:37:40 +00005373 testcase( iTerm==nConstraint-1 );
5374 testcase( j==0 );
5375 testcase( j==pWC->nTerm-1 );
drh5346e952013-05-08 14:14:26 +00005376 pTerm = &pWC->a[j];
5377 pNew->prereq |= pTerm->prereqRight;
drh4efc9292013-06-06 23:02:03 +00005378 assert( iTerm<pNew->nLSlot );
5379 pNew->aLTerm[iTerm] = pTerm;
drh5346e952013-05-08 14:14:26 +00005380 if( iTerm>mxTerm ) mxTerm = iTerm;
drh7963b0e2013-06-17 21:37:40 +00005381 testcase( iTerm==15 );
5382 testcase( iTerm==16 );
drh52986302013-06-03 16:03:16 +00005383 if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm;
drh5346e952013-05-08 14:14:26 +00005384 if( (pTerm->eOperator & WO_IN)!=0 ){
5385 if( pUsage[i].omit==0 ){
5386 /* Do not attempt to use an IN constraint if the virtual table
5387 ** says that the equivalent EQ constraint cannot be safely omitted.
5388 ** If we do attempt to use such a constraint, some rows might be
5389 ** repeated in the output. */
5390 break;
5391 }
5392 /* A virtual table that is constrained by an IN clause may not
5393 ** consume the ORDER BY clause because (1) the order of IN terms
5394 ** is not necessarily related to the order of output terms and
5395 ** (2) Multiple outputs from a single IN value will not merge
5396 ** together. */
5397 pIdxInfo->orderByConsumed = 0;
5398 }
5399 }
5400 }
drh4efc9292013-06-06 23:02:03 +00005401 if( i>=nConstraint ){
5402 pNew->nLTerm = mxTerm+1;
5403 assert( pNew->nLTerm<=pNew->nLSlot );
drh5346e952013-05-08 14:14:26 +00005404 pNew->u.vtab.idxNum = pIdxInfo->idxNum;
5405 pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
5406 pIdxInfo->needToFreeIdxStr = 0;
5407 pNew->u.vtab.idxStr = pIdxInfo->idxStr;
drh0401ace2014-03-18 15:30:27 +00005408 pNew->u.vtab.isOrdered = (i8)(pIdxInfo->orderByConsumed ?
5409 pIdxInfo->nOrderBy : 0);
drhb8a8e8a2013-06-10 19:12:39 +00005410 pNew->rSetup = 0;
drhb50596d2013-10-08 20:42:41 +00005411 pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost);
dana9f58152013-11-11 19:01:33 +00005412 pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows);
drhcf8fa7a2013-05-10 20:26:22 +00005413 whereLoopInsert(pBuilder, pNew);
drh5346e952013-05-08 14:14:26 +00005414 if( pNew->u.vtab.needFree ){
5415 sqlite3_free(pNew->u.vtab.idxStr);
5416 pNew->u.vtab.needFree = 0;
5417 }
5418 }
5419 }
5420
5421whereLoopAddVtab_exit:
5422 if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
5423 sqlite3DbFree(db, pIdxInfo);
5424 return rc;
drhf1b5f5b2013-05-02 00:15:01 +00005425}
drh8636e9c2013-06-11 01:50:08 +00005426#endif /* SQLITE_OMIT_VIRTUALTABLE */
drhf1b5f5b2013-05-02 00:15:01 +00005427
5428/*
drhcf8fa7a2013-05-10 20:26:22 +00005429** Add WhereLoop entries to handle OR terms. This works for either
5430** btrees or virtual tables.
5431*/
5432static int whereLoopAddOr(WhereLoopBuilder *pBuilder, Bitmask mExtra){
drh70d18342013-06-06 19:16:33 +00005433 WhereInfo *pWInfo = pBuilder->pWInfo;
drhcf8fa7a2013-05-10 20:26:22 +00005434 WhereClause *pWC;
5435 WhereLoop *pNew;
5436 WhereTerm *pTerm, *pWCEnd;
5437 int rc = SQLITE_OK;
5438 int iCur;
5439 WhereClause tempWC;
5440 WhereLoopBuilder sSubBuild;
dan5da73e12014-04-30 18:11:55 +00005441 WhereOrSet sSum, sCur;
drhcf8fa7a2013-05-10 20:26:22 +00005442 struct SrcList_item *pItem;
5443
drhcf8fa7a2013-05-10 20:26:22 +00005444 pWC = pBuilder->pWC;
drhcf8fa7a2013-05-10 20:26:22 +00005445 pWCEnd = pWC->a + pWC->nTerm;
5446 pNew = pBuilder->pNew;
drh77dfd5b2013-08-19 11:15:48 +00005447 memset(&sSum, 0, sizeof(sSum));
drh186ad8c2013-10-08 18:40:37 +00005448 pItem = pWInfo->pTabList->a + pNew->iTab;
5449 iCur = pItem->iCursor;
drhcf8fa7a2013-05-10 20:26:22 +00005450
5451 for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
5452 if( (pTerm->eOperator & WO_OR)!=0
5453 && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
5454 ){
5455 WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
5456 WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
5457 WhereTerm *pOrTerm;
drhaa32e3c2013-07-16 21:31:23 +00005458 int once = 1;
5459 int i, j;
drh783dece2013-06-05 17:53:43 +00005460
drh783dece2013-06-05 17:53:43 +00005461 sSubBuild = *pBuilder;
5462 sSubBuild.pOrderBy = 0;
drhaa32e3c2013-07-16 21:31:23 +00005463 sSubBuild.pOrSet = &sCur;
drhcf8fa7a2013-05-10 20:26:22 +00005464
drh0a99ba32014-09-30 17:03:35 +00005465 WHERETRACE(0x200, ("Begin processing OR-clause %p\n", pTerm));
drhc7f0d222013-06-19 03:27:12 +00005466 for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
drh783dece2013-06-05 17:53:43 +00005467 if( (pOrTerm->eOperator & WO_AND)!=0 ){
drhcf8fa7a2013-05-10 20:26:22 +00005468 sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
5469 }else if( pOrTerm->leftCursor==iCur ){
drh70d18342013-06-06 19:16:33 +00005470 tempWC.pWInfo = pWC->pWInfo;
drh783dece2013-06-05 17:53:43 +00005471 tempWC.pOuter = pWC;
5472 tempWC.op = TK_AND;
drh783dece2013-06-05 17:53:43 +00005473 tempWC.nTerm = 1;
drhcf8fa7a2013-05-10 20:26:22 +00005474 tempWC.a = pOrTerm;
5475 sSubBuild.pWC = &tempWC;
5476 }else{
5477 continue;
5478 }
drhaa32e3c2013-07-16 21:31:23 +00005479 sCur.n = 0;
drh52651492014-09-30 14:14:19 +00005480#ifdef WHERETRACE_ENABLED
drh0a99ba32014-09-30 17:03:35 +00005481 WHERETRACE(0x200, ("OR-term %d of %p has %d subterms:\n",
5482 (int)(pOrTerm-pOrWC->a), pTerm, sSubBuild.pWC->nTerm));
5483 if( sqlite3WhereTrace & 0x400 ){
5484 for(i=0; i<sSubBuild.pWC->nTerm; i++){
5485 whereTermPrint(&sSubBuild.pWC->a[i], i);
5486 }
drh52651492014-09-30 14:14:19 +00005487 }
5488#endif
drh8636e9c2013-06-11 01:50:08 +00005489#ifndef SQLITE_OMIT_VIRTUALTABLE
drhcf8fa7a2013-05-10 20:26:22 +00005490 if( IsVirtual(pItem->pTab) ){
danff4b23b2013-11-12 12:17:16 +00005491 rc = whereLoopAddVirtual(&sSubBuild, mExtra);
drh8636e9c2013-06-11 01:50:08 +00005492 }else
5493#endif
5494 {
drhcf8fa7a2013-05-10 20:26:22 +00005495 rc = whereLoopAddBtree(&sSubBuild, mExtra);
5496 }
drh36be4c42014-09-30 17:31:23 +00005497 if( rc==SQLITE_OK ){
5498 rc = whereLoopAddOr(&sSubBuild, mExtra);
5499 }
drhaa32e3c2013-07-16 21:31:23 +00005500 assert( rc==SQLITE_OK || sCur.n==0 );
5501 if( sCur.n==0 ){
5502 sSum.n = 0;
5503 break;
5504 }else if( once ){
5505 whereOrMove(&sSum, &sCur);
5506 once = 0;
5507 }else{
dan5da73e12014-04-30 18:11:55 +00005508 WhereOrSet sPrev;
drhaa32e3c2013-07-16 21:31:23 +00005509 whereOrMove(&sPrev, &sSum);
5510 sSum.n = 0;
5511 for(i=0; i<sPrev.n; i++){
5512 for(j=0; j<sCur.n; j++){
5513 whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,
drhbf539c42013-10-05 18:16:02 +00005514 sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
5515 sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
drhaa32e3c2013-07-16 21:31:23 +00005516 }
5517 }
5518 }
drhcf8fa7a2013-05-10 20:26:22 +00005519 }
drhaa32e3c2013-07-16 21:31:23 +00005520 pNew->nLTerm = 1;
5521 pNew->aLTerm[0] = pTerm;
5522 pNew->wsFlags = WHERE_MULTI_OR;
5523 pNew->rSetup = 0;
5524 pNew->iSortIdx = 0;
5525 memset(&pNew->u, 0, sizeof(pNew->u));
5526 for(i=0; rc==SQLITE_OK && i<sSum.n; i++){
dan5da73e12014-04-30 18:11:55 +00005527 /* TUNING: Currently sSum.a[i].rRun is set to the sum of the costs
5528 ** of all sub-scans required by the OR-scan. However, due to rounding
5529 ** errors, it may be that the cost of the OR-scan is equal to its
5530 ** most expensive sub-scan. Add the smallest possible penalty
5531 ** (equivalent to multiplying the cost by 1.07) to ensure that
5532 ** this does not happen. Otherwise, for WHERE clauses such as the
5533 ** following where there is an index on "y":
5534 **
5535 ** WHERE likelihood(x=?, 0.99) OR y=?
5536 **
5537 ** the planner may elect to "OR" together a full-table scan and an
5538 ** index lookup. And other similarly odd results. */
5539 pNew->rRun = sSum.a[i].rRun + 1;
drhaa32e3c2013-07-16 21:31:23 +00005540 pNew->nOut = sSum.a[i].nOut;
5541 pNew->prereq = sSum.a[i].prereq;
drhfd5874d2013-06-12 14:52:39 +00005542 rc = whereLoopInsert(pBuilder, pNew);
5543 }
drh0a99ba32014-09-30 17:03:35 +00005544 WHERETRACE(0x200, ("End processing OR-clause %p\n", pTerm));
drhcf8fa7a2013-05-10 20:26:22 +00005545 }
5546 }
5547 return rc;
5548}
5549
5550/*
drhf1b5f5b2013-05-02 00:15:01 +00005551** Add all WhereLoop objects for all tables
5552*/
drh5346e952013-05-08 14:14:26 +00005553static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
drh70d18342013-06-06 19:16:33 +00005554 WhereInfo *pWInfo = pBuilder->pWInfo;
drhf1b5f5b2013-05-02 00:15:01 +00005555 Bitmask mExtra = 0;
5556 Bitmask mPrior = 0;
5557 int iTab;
drh70d18342013-06-06 19:16:33 +00005558 SrcList *pTabList = pWInfo->pTabList;
drhf1b5f5b2013-05-02 00:15:01 +00005559 struct SrcList_item *pItem;
drh70d18342013-06-06 19:16:33 +00005560 sqlite3 *db = pWInfo->pParse->db;
5561 int nTabList = pWInfo->nLevel;
drh5346e952013-05-08 14:14:26 +00005562 int rc = SQLITE_OK;
drhc63367e2013-06-10 20:46:50 +00005563 u8 priorJoinType = 0;
drhb8a8e8a2013-06-10 19:12:39 +00005564 WhereLoop *pNew;
drhf1b5f5b2013-05-02 00:15:01 +00005565
5566 /* Loop over the tables in the join, from left to right */
drhb8a8e8a2013-06-10 19:12:39 +00005567 pNew = pBuilder->pNew;
drha2014152013-06-07 00:29:23 +00005568 whereLoopInit(pNew);
drha18f3d22013-05-08 03:05:41 +00005569 for(iTab=0, pItem=pTabList->a; iTab<nTabList; iTab++, pItem++){
drhb2a90f02013-05-10 03:30:49 +00005570 pNew->iTab = iTab;
drh70d18342013-06-06 19:16:33 +00005571 pNew->maskSelf = getMask(&pWInfo->sMaskSet, pItem->iCursor);
drhc63367e2013-06-10 20:46:50 +00005572 if( ((pItem->jointype|priorJoinType) & (JT_LEFT|JT_CROSS))!=0 ){
drhf1b5f5b2013-05-02 00:15:01 +00005573 mExtra = mPrior;
5574 }
drhc63367e2013-06-10 20:46:50 +00005575 priorJoinType = pItem->jointype;
drhb2a90f02013-05-10 03:30:49 +00005576 if( IsVirtual(pItem->pTab) ){
danff4b23b2013-11-12 12:17:16 +00005577 rc = whereLoopAddVirtual(pBuilder, mExtra);
drhb2a90f02013-05-10 03:30:49 +00005578 }else{
5579 rc = whereLoopAddBtree(pBuilder, mExtra);
5580 }
drhb2a90f02013-05-10 03:30:49 +00005581 if( rc==SQLITE_OK ){
5582 rc = whereLoopAddOr(pBuilder, mExtra);
5583 }
drhb2a90f02013-05-10 03:30:49 +00005584 mPrior |= pNew->maskSelf;
drh5346e952013-05-08 14:14:26 +00005585 if( rc || db->mallocFailed ) break;
drhf1b5f5b2013-05-02 00:15:01 +00005586 }
drha2014152013-06-07 00:29:23 +00005587 whereLoopClear(db, pNew);
drh5346e952013-05-08 14:14:26 +00005588 return rc;
drhf1b5f5b2013-05-02 00:15:01 +00005589}
5590
drha18f3d22013-05-08 03:05:41 +00005591/*
drh7699d1c2013-06-04 12:42:29 +00005592** Examine a WherePath (with the addition of the extra WhereLoop of the 5th
drh319f6772013-05-14 15:31:07 +00005593** parameters) to see if it outputs rows in the requested ORDER BY
drh0401ace2014-03-18 15:30:27 +00005594** (or GROUP BY) without requiring a separate sort operation. Return N:
drh319f6772013-05-14 15:31:07 +00005595**
drh0401ace2014-03-18 15:30:27 +00005596** N>0: N terms of the ORDER BY clause are satisfied
5597** N==0: No terms of the ORDER BY clause are satisfied
5598** N<0: Unknown yet how many terms of ORDER BY might be satisfied.
drh319f6772013-05-14 15:31:07 +00005599**
drh94433422013-07-01 11:05:50 +00005600** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
5601** strict. With GROUP BY and DISTINCT the only requirement is that
5602** equivalent rows appear immediately adjacent to one another. GROUP BY
dan374cd782014-04-21 13:21:56 +00005603** and DISTINCT do not require rows to appear in any particular order as long
peter.d.reid60ec9142014-09-06 16:39:46 +00005604** as equivalent rows are grouped together. Thus for GROUP BY and DISTINCT
drh94433422013-07-01 11:05:50 +00005605** the pOrderBy terms can be matched in any order. With ORDER BY, the
5606** pOrderBy terms must be matched in strict left-to-right order.
drh6b7157b2013-05-10 02:00:35 +00005607*/
drh0401ace2014-03-18 15:30:27 +00005608static i8 wherePathSatisfiesOrderBy(
drh6b7157b2013-05-10 02:00:35 +00005609 WhereInfo *pWInfo, /* The WHERE clause */
drh4f402f22013-06-11 18:59:38 +00005610 ExprList *pOrderBy, /* ORDER BY or GROUP BY or DISTINCT clause to check */
drh6b7157b2013-05-10 02:00:35 +00005611 WherePath *pPath, /* The WherePath to check */
drh4f402f22013-06-11 18:59:38 +00005612 u16 wctrlFlags, /* Might contain WHERE_GROUPBY or WHERE_DISTINCTBY */
5613 u16 nLoop, /* Number of entries in pPath->aLoop[] */
drh319f6772013-05-14 15:31:07 +00005614 WhereLoop *pLast, /* Add this WhereLoop to the end of pPath->aLoop[] */
drh4f402f22013-06-11 18:59:38 +00005615 Bitmask *pRevMask /* OUT: Mask of WhereLoops to run in reverse order */
drh6b7157b2013-05-10 02:00:35 +00005616){
drh88da6442013-05-27 17:59:37 +00005617 u8 revSet; /* True if rev is known */
5618 u8 rev; /* Composite sort order */
5619 u8 revIdx; /* Index sort order */
drhe353ee32013-06-04 23:40:53 +00005620 u8 isOrderDistinct; /* All prior WhereLoops are order-distinct */
5621 u8 distinctColumns; /* True if the loop has UNIQUE NOT NULL columns */
5622 u8 isMatch; /* iColumn matches a term of the ORDER BY clause */
drh416846a2013-11-06 12:56:04 +00005623 u16 nKeyCol; /* Number of key columns in pIndex */
5624 u16 nColumn; /* Total number of ordered columns in the index */
drh7699d1c2013-06-04 12:42:29 +00005625 u16 nOrderBy; /* Number terms in the ORDER BY clause */
5626 int iLoop; /* Index of WhereLoop in pPath being processed */
5627 int i, j; /* Loop counters */
5628 int iCur; /* Cursor number for current WhereLoop */
5629 int iColumn; /* A column number within table iCur */
drhe8ae5832013-06-19 13:32:46 +00005630 WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
drh7699d1c2013-06-04 12:42:29 +00005631 WhereTerm *pTerm; /* A single term of the WHERE clause */
5632 Expr *pOBExpr; /* An expression from the ORDER BY clause */
5633 CollSeq *pColl; /* COLLATE function from an ORDER BY clause term */
5634 Index *pIndex; /* The index associated with pLoop */
5635 sqlite3 *db = pWInfo->pParse->db; /* Database connection */
5636 Bitmask obSat = 0; /* Mask of ORDER BY terms satisfied so far */
5637 Bitmask obDone; /* Mask of all ORDER BY terms */
drhe353ee32013-06-04 23:40:53 +00005638 Bitmask orderDistinctMask; /* Mask of all well-ordered loops */
drhb8916be2013-06-14 02:51:48 +00005639 Bitmask ready; /* Mask of inner loops */
drh319f6772013-05-14 15:31:07 +00005640
5641 /*
drh7699d1c2013-06-04 12:42:29 +00005642 ** We say the WhereLoop is "one-row" if it generates no more than one
5643 ** row of output. A WhereLoop is one-row if all of the following are true:
drh319f6772013-05-14 15:31:07 +00005644 ** (a) All index columns match with WHERE_COLUMN_EQ.
5645 ** (b) The index is unique
drh7699d1c2013-06-04 12:42:29 +00005646 ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
5647 ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
drh319f6772013-05-14 15:31:07 +00005648 **
drhe353ee32013-06-04 23:40:53 +00005649 ** We say the WhereLoop is "order-distinct" if the set of columns from
5650 ** that WhereLoop that are in the ORDER BY clause are different for every
5651 ** row of the WhereLoop. Every one-row WhereLoop is automatically
5652 ** order-distinct. A WhereLoop that has no columns in the ORDER BY clause
5653 ** is not order-distinct. To be order-distinct is not quite the same as being
5654 ** UNIQUE since a UNIQUE column or index can have multiple rows that
5655 ** are NULL and NULL values are equivalent for the purpose of order-distinct.
5656 ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
5657 **
5658 ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
5659 ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
5660 ** automatically order-distinct.
drh319f6772013-05-14 15:31:07 +00005661 */
5662
5663 assert( pOrderBy!=0 );
drh7699d1c2013-06-04 12:42:29 +00005664 if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
drh319f6772013-05-14 15:31:07 +00005665
drh319f6772013-05-14 15:31:07 +00005666 nOrderBy = pOrderBy->nExpr;
drh7963b0e2013-06-17 21:37:40 +00005667 testcase( nOrderBy==BMS-1 );
drhe353ee32013-06-04 23:40:53 +00005668 if( nOrderBy>BMS-1 ) return 0; /* Cannot optimize overly large ORDER BYs */
5669 isOrderDistinct = 1;
drh7699d1c2013-06-04 12:42:29 +00005670 obDone = MASKBIT(nOrderBy)-1;
drhe353ee32013-06-04 23:40:53 +00005671 orderDistinctMask = 0;
drhb8916be2013-06-14 02:51:48 +00005672 ready = 0;
drhe353ee32013-06-04 23:40:53 +00005673 for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
drhb8916be2013-06-14 02:51:48 +00005674 if( iLoop>0 ) ready |= pLoop->maskSelf;
drh7699d1c2013-06-04 12:42:29 +00005675 pLoop = iLoop<nLoop ? pPath->aLoop[iLoop] : pLast;
drh9dfaf622014-04-25 14:42:17 +00005676 if( pLoop->wsFlags & WHERE_VIRTUALTABLE ){
5677 if( pLoop->u.vtab.isOrdered ) obSat = obDone;
5678 break;
5679 }
drh319f6772013-05-14 15:31:07 +00005680 iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
drhb8916be2013-06-14 02:51:48 +00005681
5682 /* Mark off any ORDER BY term X that is a column in the table of
5683 ** the current loop for which there is term in the WHERE
5684 ** clause of the form X IS NULL or X=? that reference only outer
5685 ** loops.
5686 */
5687 for(i=0; i<nOrderBy; i++){
5688 if( MASKBIT(i) & obSat ) continue;
5689 pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
5690 if( pOBExpr->op!=TK_COLUMN ) continue;
5691 if( pOBExpr->iTable!=iCur ) continue;
5692 pTerm = findTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
5693 ~ready, WO_EQ|WO_ISNULL, 0);
5694 if( pTerm==0 ) continue;
drh7963b0e2013-06-17 21:37:40 +00005695 if( (pTerm->eOperator&WO_EQ)!=0 && pOBExpr->iColumn>=0 ){
drhb8916be2013-06-14 02:51:48 +00005696 const char *z1, *z2;
5697 pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
5698 if( !pColl ) pColl = db->pDfltColl;
5699 z1 = pColl->zName;
5700 pColl = sqlite3ExprCollSeq(pWInfo->pParse, pTerm->pExpr);
5701 if( !pColl ) pColl = db->pDfltColl;
5702 z2 = pColl->zName;
5703 if( sqlite3StrICmp(z1, z2)!=0 ) continue;
5704 }
5705 obSat |= MASKBIT(i);
5706 }
5707
drh7699d1c2013-06-04 12:42:29 +00005708 if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
5709 if( pLoop->wsFlags & WHERE_IPK ){
5710 pIndex = 0;
drhbbbdc832013-10-22 18:01:40 +00005711 nKeyCol = 0;
drh416846a2013-11-06 12:56:04 +00005712 nColumn = 1;
drh7699d1c2013-06-04 12:42:29 +00005713 }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
drh1b0f0262013-05-30 22:27:09 +00005714 return 0;
drh7699d1c2013-06-04 12:42:29 +00005715 }else{
drhbbbdc832013-10-22 18:01:40 +00005716 nKeyCol = pIndex->nKeyCol;
drh416846a2013-11-06 12:56:04 +00005717 nColumn = pIndex->nColumn;
5718 assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) );
5719 assert( pIndex->aiColumn[nColumn-1]==(-1) || !HasRowid(pIndex->pTable));
drh5f1d1d92014-07-31 22:59:04 +00005720 isOrderDistinct = IsUniqueIndex(pIndex);
drh1b0f0262013-05-30 22:27:09 +00005721 }
drh7699d1c2013-06-04 12:42:29 +00005722
drh7699d1c2013-06-04 12:42:29 +00005723 /* Loop through all columns of the index and deal with the ones
5724 ** that are not constrained by == or IN.
5725 */
5726 rev = revSet = 0;
drhe353ee32013-06-04 23:40:53 +00005727 distinctColumns = 0;
drh416846a2013-11-06 12:56:04 +00005728 for(j=0; j<nColumn; j++){
drh7699d1c2013-06-04 12:42:29 +00005729 u8 bOnce; /* True to run the ORDER BY search loop */
5730
drhe353ee32013-06-04 23:40:53 +00005731 /* Skip over == and IS NULL terms */
drh7699d1c2013-06-04 12:42:29 +00005732 if( j<pLoop->u.btree.nEq
drhc8bbce12014-10-21 01:05:09 +00005733 && pLoop->nSkip==0
drh4efc9292013-06-06 23:02:03 +00005734 && ((i = pLoop->aLTerm[j]->eOperator) & (WO_EQ|WO_ISNULL))!=0
drh7699d1c2013-06-04 12:42:29 +00005735 ){
drh7963b0e2013-06-17 21:37:40 +00005736 if( i & WO_ISNULL ){
5737 testcase( isOrderDistinct );
5738 isOrderDistinct = 0;
5739 }
drhe353ee32013-06-04 23:40:53 +00005740 continue;
drh7699d1c2013-06-04 12:42:29 +00005741 }
5742
drhe353ee32013-06-04 23:40:53 +00005743 /* Get the column number in the table (iColumn) and sort order
5744 ** (revIdx) for the j-th column of the index.
drh7699d1c2013-06-04 12:42:29 +00005745 */
drh416846a2013-11-06 12:56:04 +00005746 if( pIndex ){
drh7699d1c2013-06-04 12:42:29 +00005747 iColumn = pIndex->aiColumn[j];
5748 revIdx = pIndex->aSortOrder[j];
5749 if( iColumn==pIndex->pTable->iPKey ) iColumn = -1;
drhdc3cd4b2013-05-30 23:21:20 +00005750 }else{
drh7699d1c2013-06-04 12:42:29 +00005751 iColumn = -1;
5752 revIdx = 0;
drhdc3cd4b2013-05-30 23:21:20 +00005753 }
drh7699d1c2013-06-04 12:42:29 +00005754
5755 /* An unconstrained column that might be NULL means that this
drh416846a2013-11-06 12:56:04 +00005756 ** WhereLoop is not well-ordered
drh7699d1c2013-06-04 12:42:29 +00005757 */
drhe353ee32013-06-04 23:40:53 +00005758 if( isOrderDistinct
5759 && iColumn>=0
drh7699d1c2013-06-04 12:42:29 +00005760 && j>=pLoop->u.btree.nEq
5761 && pIndex->pTable->aCol[iColumn].notNull==0
5762 ){
drhe353ee32013-06-04 23:40:53 +00005763 isOrderDistinct = 0;
drh7699d1c2013-06-04 12:42:29 +00005764 }
5765
5766 /* Find the ORDER BY term that corresponds to the j-th column
dan374cd782014-04-21 13:21:56 +00005767 ** of the index and mark that ORDER BY term off
drh7699d1c2013-06-04 12:42:29 +00005768 */
5769 bOnce = 1;
drhe353ee32013-06-04 23:40:53 +00005770 isMatch = 0;
drh7699d1c2013-06-04 12:42:29 +00005771 for(i=0; bOnce && i<nOrderBy; i++){
5772 if( MASKBIT(i) & obSat ) continue;
5773 pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
drh93ec45d2013-06-17 18:20:48 +00005774 testcase( wctrlFlags & WHERE_GROUPBY );
5775 testcase( wctrlFlags & WHERE_DISTINCTBY );
drh4f402f22013-06-11 18:59:38 +00005776 if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
drhe353ee32013-06-04 23:40:53 +00005777 if( pOBExpr->op!=TK_COLUMN ) continue;
drh7699d1c2013-06-04 12:42:29 +00005778 if( pOBExpr->iTable!=iCur ) continue;
5779 if( pOBExpr->iColumn!=iColumn ) continue;
5780 if( iColumn>=0 ){
5781 pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
5782 if( !pColl ) pColl = db->pDfltColl;
5783 if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
5784 }
drhe353ee32013-06-04 23:40:53 +00005785 isMatch = 1;
drh7699d1c2013-06-04 12:42:29 +00005786 break;
5787 }
drh49290472014-10-11 02:12:58 +00005788 if( isMatch && (wctrlFlags & WHERE_GROUPBY)==0 ){
drh59b8f2e2014-03-22 00:27:14 +00005789 /* Make sure the sort order is compatible in an ORDER BY clause.
5790 ** Sort order is irrelevant for a GROUP BY clause. */
5791 if( revSet ){
5792 if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) isMatch = 0;
5793 }else{
5794 rev = revIdx ^ pOrderBy->a[i].sortOrder;
5795 if( rev ) *pRevMask |= MASKBIT(iLoop);
5796 revSet = 1;
5797 }
5798 }
drhe353ee32013-06-04 23:40:53 +00005799 if( isMatch ){
drh7963b0e2013-06-17 21:37:40 +00005800 if( iColumn<0 ){
5801 testcase( distinctColumns==0 );
5802 distinctColumns = 1;
5803 }
drh7699d1c2013-06-04 12:42:29 +00005804 obSat |= MASKBIT(i);
drh7699d1c2013-06-04 12:42:29 +00005805 }else{
5806 /* No match found */
drhbbbdc832013-10-22 18:01:40 +00005807 if( j==0 || j<nKeyCol ){
drh7963b0e2013-06-17 21:37:40 +00005808 testcase( isOrderDistinct!=0 );
5809 isOrderDistinct = 0;
5810 }
drh7699d1c2013-06-04 12:42:29 +00005811 break;
5812 }
5813 } /* end Loop over all index columns */
drh81186b42013-06-18 01:52:41 +00005814 if( distinctColumns ){
5815 testcase( isOrderDistinct==0 );
5816 isOrderDistinct = 1;
5817 }
drh7699d1c2013-06-04 12:42:29 +00005818 } /* end-if not one-row */
5819
5820 /* Mark off any other ORDER BY terms that reference pLoop */
drhe353ee32013-06-04 23:40:53 +00005821 if( isOrderDistinct ){
5822 orderDistinctMask |= pLoop->maskSelf;
drh7699d1c2013-06-04 12:42:29 +00005823 for(i=0; i<nOrderBy; i++){
5824 Expr *p;
drh434a9312014-02-26 02:26:09 +00005825 Bitmask mTerm;
drh7699d1c2013-06-04 12:42:29 +00005826 if( MASKBIT(i) & obSat ) continue;
5827 p = pOrderBy->a[i].pExpr;
drh434a9312014-02-26 02:26:09 +00005828 mTerm = exprTableUsage(&pWInfo->sMaskSet,p);
5829 if( mTerm==0 && !sqlite3ExprIsConstant(p) ) continue;
5830 if( (mTerm&~orderDistinctMask)==0 ){
drh7699d1c2013-06-04 12:42:29 +00005831 obSat |= MASKBIT(i);
5832 }
drh0afb4232013-05-31 13:36:32 +00005833 }
drh319f6772013-05-14 15:31:07 +00005834 }
drhb8916be2013-06-14 02:51:48 +00005835 } /* End the loop over all WhereLoops from outer-most down to inner-most */
drh36ed0342014-03-28 12:56:57 +00005836 if( obSat==obDone ) return (i8)nOrderBy;
drhd2de8612014-03-18 18:59:07 +00005837 if( !isOrderDistinct ){
5838 for(i=nOrderBy-1; i>0; i--){
5839 Bitmask m = MASKBIT(i) - 1;
5840 if( (obSat&m)==m ) return i;
5841 }
5842 return 0;
5843 }
drh319f6772013-05-14 15:31:07 +00005844 return -1;
drh6b7157b2013-05-10 02:00:35 +00005845}
5846
dan374cd782014-04-21 13:21:56 +00005847
5848/*
5849** If the WHERE_GROUPBY flag is set in the mask passed to sqlite3WhereBegin(),
5850** the planner assumes that the specified pOrderBy list is actually a GROUP
5851** BY clause - and so any order that groups rows as required satisfies the
5852** request.
5853**
5854** Normally, in this case it is not possible for the caller to determine
5855** whether or not the rows are really being delivered in sorted order, or
5856** just in some other order that provides the required grouping. However,
5857** if the WHERE_SORTBYGROUP flag is also passed to sqlite3WhereBegin(), then
5858** this function may be called on the returned WhereInfo object. It returns
5859** true if the rows really will be sorted in the specified order, or false
5860** otherwise.
5861**
5862** For example, assuming:
5863**
5864** CREATE INDEX i1 ON t1(x, Y);
5865**
5866** then
5867**
5868** SELECT * FROM t1 GROUP BY x,y ORDER BY x,y; -- IsSorted()==1
5869** SELECT * FROM t1 GROUP BY y,x ORDER BY y,x; -- IsSorted()==0
5870*/
5871int sqlite3WhereIsSorted(WhereInfo *pWInfo){
5872 assert( pWInfo->wctrlFlags & WHERE_GROUPBY );
5873 assert( pWInfo->wctrlFlags & WHERE_SORTBYGROUP );
5874 return pWInfo->sorted;
5875}
5876
drhd15cb172013-05-21 19:23:10 +00005877#ifdef WHERETRACE_ENABLED
5878/* For debugging use only: */
5879static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
5880 static char zName[65];
5881 int i;
5882 for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
5883 if( pLast ) zName[i++] = pLast->cId;
5884 zName[i] = 0;
5885 return zName;
5886}
5887#endif
5888
drh6b7157b2013-05-10 02:00:35 +00005889/*
dan50ae31e2014-08-08 16:52:28 +00005890** Return the cost of sorting nRow rows, assuming that the keys have
5891** nOrderby columns and that the first nSorted columns are already in
5892** order.
5893*/
5894static LogEst whereSortingCost(
5895 WhereInfo *pWInfo,
5896 LogEst nRow,
5897 int nOrderBy,
5898 int nSorted
5899){
5900 /* TUNING: Estimated cost of a full external sort, where N is
5901 ** the number of rows to sort is:
5902 **
5903 ** cost = (3.0 * N * log(N)).
5904 **
5905 ** Or, if the order-by clause has X terms but only the last Y
5906 ** terms are out of order, then block-sorting will reduce the
5907 ** sorting cost to:
5908 **
5909 ** cost = (3.0 * N * log(N)) * (Y/X)
5910 **
5911 ** The (Y/X) term is implemented using stack variable rScale
5912 ** below. */
5913 LogEst rScale, rSortCost;
5914 assert( nOrderBy>0 && 66==sqlite3LogEst(100) );
5915 rScale = sqlite3LogEst((nOrderBy-nSorted)*100/nOrderBy) - 66;
5916 rSortCost = nRow + estLog(nRow) + rScale + 16;
5917
5918 /* TUNING: The cost of implementing DISTINCT using a B-TREE is
5919 ** similar but with a larger constant of proportionality.
5920 ** Multiply by an additional factor of 3.0. */
5921 if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
5922 rSortCost += 16;
5923 }
5924
5925 return rSortCost;
5926}
5927
5928/*
dan51576f42013-07-02 10:06:15 +00005929** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
drha18f3d22013-05-08 03:05:41 +00005930** attempts to find the lowest cost path that visits each WhereLoop
5931** once. This path is then loaded into the pWInfo->a[].pWLoop fields.
5932**
drhc7f0d222013-06-19 03:27:12 +00005933** Assume that the total number of output rows that will need to be sorted
5934** will be nRowEst (in the 10*log2 representation). Or, ignore sorting
5935** costs if nRowEst==0.
5936**
drha18f3d22013-05-08 03:05:41 +00005937** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
5938** error occurs.
5939*/
drhbf539c42013-10-05 18:16:02 +00005940static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
drh783dece2013-06-05 17:53:43 +00005941 int mxChoice; /* Maximum number of simultaneous paths tracked */
drha18f3d22013-05-08 03:05:41 +00005942 int nLoop; /* Number of terms in the join */
drhe1e2e9a2013-06-13 15:16:53 +00005943 Parse *pParse; /* Parsing context */
drha18f3d22013-05-08 03:05:41 +00005944 sqlite3 *db; /* The database connection */
5945 int iLoop; /* Loop counter over the terms of the join */
5946 int ii, jj; /* Loop counters */
drhfde1e6b2013-09-06 17:45:42 +00005947 int mxI = 0; /* Index of next entry to replace */
drhd2de8612014-03-18 18:59:07 +00005948 int nOrderBy; /* Number of ORDER BY clause terms */
drhbf539c42013-10-05 18:16:02 +00005949 LogEst mxCost = 0; /* Maximum cost of a set of paths */
dan50ae31e2014-08-08 16:52:28 +00005950 LogEst mxUnsorted = 0; /* Maximum unsorted cost of a set of path */
drha18f3d22013-05-08 03:05:41 +00005951 int nTo, nFrom; /* Number of valid entries in aTo[] and aFrom[] */
5952 WherePath *aFrom; /* All nFrom paths at the previous level */
5953 WherePath *aTo; /* The nTo best paths at the current level */
5954 WherePath *pFrom; /* An element of aFrom[] that we are working on */
5955 WherePath *pTo; /* An element of aTo[] that we are working on */
5956 WhereLoop *pWLoop; /* One of the WhereLoop objects */
5957 WhereLoop **pX; /* Used to divy up the pSpace memory */
dan50ae31e2014-08-08 16:52:28 +00005958 LogEst *aSortCost = 0; /* Sorting and partial sorting costs */
drha18f3d22013-05-08 03:05:41 +00005959 char *pSpace; /* Temporary memory used by this routine */
dane2c27852014-08-08 17:25:33 +00005960 int nSpace; /* Bytes of space allocated at pSpace */
drha18f3d22013-05-08 03:05:41 +00005961
drhe1e2e9a2013-06-13 15:16:53 +00005962 pParse = pWInfo->pParse;
5963 db = pParse->db;
drha18f3d22013-05-08 03:05:41 +00005964 nLoop = pWInfo->nLevel;
drhe1e2e9a2013-06-13 15:16:53 +00005965 /* TUNING: For simple queries, only the best path is tracked.
5966 ** For 2-way joins, the 5 best paths are followed.
5967 ** For joins of 3 or more tables, track the 10 best paths */
drh2504c6c2014-06-02 11:26:33 +00005968 mxChoice = (nLoop<=1) ? 1 : (nLoop==2 ? 5 : 10);
drha18f3d22013-05-08 03:05:41 +00005969 assert( nLoop<=pWInfo->pTabList->nSrc );
drhddef5dc2014-08-07 16:50:00 +00005970 WHERETRACE(0x002, ("---- begin solver. (nRowEst=%d)\n", nRowEst));
drha18f3d22013-05-08 03:05:41 +00005971
dan50ae31e2014-08-08 16:52:28 +00005972 /* If nRowEst is zero and there is an ORDER BY clause, ignore it. In this
5973 ** case the purpose of this call is to estimate the number of rows returned
5974 ** by the overall query. Once this estimate has been obtained, the caller
5975 ** will invoke this function a second time, passing the estimate as the
5976 ** nRowEst parameter. */
5977 if( pWInfo->pOrderBy==0 || nRowEst==0 ){
5978 nOrderBy = 0;
5979 }else{
5980 nOrderBy = pWInfo->pOrderBy->nExpr;
5981 }
5982
5983 /* Allocate and initialize space for aTo, aFrom and aSortCost[] */
dane2c27852014-08-08 17:25:33 +00005984 nSpace = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
5985 nSpace += sizeof(LogEst) * nOrderBy;
5986 pSpace = sqlite3DbMallocRaw(db, nSpace);
drha18f3d22013-05-08 03:05:41 +00005987 if( pSpace==0 ) return SQLITE_NOMEM;
5988 aTo = (WherePath*)pSpace;
5989 aFrom = aTo+mxChoice;
5990 memset(aFrom, 0, sizeof(aFrom[0]));
5991 pX = (WhereLoop**)(aFrom+mxChoice);
drhe9d935a2013-06-05 16:19:59 +00005992 for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
drha18f3d22013-05-08 03:05:41 +00005993 pFrom->aLoop = pX;
5994 }
dan50ae31e2014-08-08 16:52:28 +00005995 if( nOrderBy ){
5996 /* If there is an ORDER BY clause and it is not being ignored, set up
5997 ** space for the aSortCost[] array. Each element of the aSortCost array
5998 ** is either zero - meaning it has not yet been initialized - or the
5999 ** cost of sorting nRowEst rows of data where the first X terms of
6000 ** the ORDER BY clause are already in order, where X is the array
6001 ** index. */
6002 aSortCost = (LogEst*)pX;
dane2c27852014-08-08 17:25:33 +00006003 memset(aSortCost, 0, sizeof(LogEst) * nOrderBy);
dan50ae31e2014-08-08 16:52:28 +00006004 }
dane2c27852014-08-08 17:25:33 +00006005 assert( aSortCost==0 || &pSpace[nSpace]==(char*)&aSortCost[nOrderBy] );
6006 assert( aSortCost!=0 || &pSpace[nSpace]==(char*)pX );
drha18f3d22013-05-08 03:05:41 +00006007
drhe1e2e9a2013-06-13 15:16:53 +00006008 /* Seed the search with a single WherePath containing zero WhereLoops.
6009 **
danf104abb2015-03-16 20:40:00 +00006010 ** TUNING: Do not let the number of iterations go above 28. If the cost
6011 ** of computing an automatic index is not paid back within the first 28
drhe1e2e9a2013-06-13 15:16:53 +00006012 ** rows, then do not use the automatic index. */
danf104abb2015-03-16 20:40:00 +00006013 aFrom[0].nRow = MIN(pParse->nQueryLoop, 48); assert( 48==sqlite3LogEst(28) );
drha18f3d22013-05-08 03:05:41 +00006014 nFrom = 1;
dan50ae31e2014-08-08 16:52:28 +00006015 assert( aFrom[0].isOrdered==0 );
6016 if( nOrderBy ){
6017 /* If nLoop is zero, then there are no FROM terms in the query. Since
6018 ** in this case the query may return a maximum of one row, the results
6019 ** are already in the requested order. Set isOrdered to nOrderBy to
6020 ** indicate this. Or, if nLoop is greater than zero, set isOrdered to
6021 ** -1, indicating that the result set may or may not be ordered,
6022 ** depending on the loops added to the current plan. */
6023 aFrom[0].isOrdered = nLoop>0 ? -1 : nOrderBy;
drh6b7157b2013-05-10 02:00:35 +00006024 }
6025
6026 /* Compute successively longer WherePaths using the previous generation
6027 ** of WherePaths as the basis for the next. Keep track of the mxChoice
6028 ** best paths at each generation */
drha18f3d22013-05-08 03:05:41 +00006029 for(iLoop=0; iLoop<nLoop; iLoop++){
6030 nTo = 0;
6031 for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
6032 for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
dan50ae31e2014-08-08 16:52:28 +00006033 LogEst nOut; /* Rows visited by (pFrom+pWLoop) */
6034 LogEst rCost; /* Cost of path (pFrom+pWLoop) */
6035 LogEst rUnsorted; /* Unsorted cost of (pFrom+pWLoop) */
6036 i8 isOrdered = pFrom->isOrdered; /* isOrdered for (pFrom+pWLoop) */
6037 Bitmask maskNew; /* Mask of src visited by (..) */
6038 Bitmask revMask = 0; /* Mask of rev-order loops for (..) */
6039
drha18f3d22013-05-08 03:05:41 +00006040 if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
6041 if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
drh6b7157b2013-05-10 02:00:35 +00006042 /* At this point, pWLoop is a candidate to be the next loop.
6043 ** Compute its cost */
dan50ae31e2014-08-08 16:52:28 +00006044 rUnsorted = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
6045 rUnsorted = sqlite3LogEstAdd(rUnsorted, pFrom->rUnsorted);
drhfde1e6b2013-09-06 17:45:42 +00006046 nOut = pFrom->nRow + pWLoop->nOut;
drha18f3d22013-05-08 03:05:41 +00006047 maskNew = pFrom->maskLoop | pWLoop->maskSelf;
drh0401ace2014-03-18 15:30:27 +00006048 if( isOrdered<0 ){
6049 isOrdered = wherePathSatisfiesOrderBy(pWInfo,
drh4f402f22013-06-11 18:59:38 +00006050 pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
drh0401ace2014-03-18 15:30:27 +00006051 iLoop, pWLoop, &revMask);
drh3a5ba8b2013-06-03 15:34:48 +00006052 }else{
6053 revMask = pFrom->revLoop;
drh6b7157b2013-05-10 02:00:35 +00006054 }
dan50ae31e2014-08-08 16:52:28 +00006055 if( isOrdered>=0 && isOrdered<nOrderBy ){
6056 if( aSortCost[isOrdered]==0 ){
6057 aSortCost[isOrdered] = whereSortingCost(
6058 pWInfo, nRowEst, nOrderBy, isOrdered
6059 );
6060 }
6061 rCost = sqlite3LogEstAdd(rUnsorted, aSortCost[isOrdered]);
6062
6063 WHERETRACE(0x002,
6064 ("---- sort cost=%-3d (%d/%d) increases cost %3d to %-3d\n",
6065 aSortCost[isOrdered], (nOrderBy-isOrdered), nOrderBy,
6066 rUnsorted, rCost));
6067 }else{
6068 rCost = rUnsorted;
6069 }
6070
drhddef5dc2014-08-07 16:50:00 +00006071 /* Check to see if pWLoop should be added to the set of
6072 ** mxChoice best-so-far paths.
6073 **
6074 ** First look for an existing path among best-so-far paths
6075 ** that covers the same set of loops and has the same isOrdered
6076 ** setting as the current path candidate.
drhf2a90302014-08-07 20:37:01 +00006077 **
6078 ** The term "((pTo->isOrdered^isOrdered)&0x80)==0" is equivalent
6079 ** to (pTo->isOrdered==(-1))==(isOrdered==(-1))" for the range
6080 ** of legal values for isOrdered, -1..64.
drhddef5dc2014-08-07 16:50:00 +00006081 */
drh6b7157b2013-05-10 02:00:35 +00006082 for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
drhfde1e6b2013-09-06 17:45:42 +00006083 if( pTo->maskLoop==maskNew
drhf2a90302014-08-07 20:37:01 +00006084 && ((pTo->isOrdered^isOrdered)&0x80)==0
drhfde1e6b2013-09-06 17:45:42 +00006085 ){
drh7963b0e2013-06-17 21:37:40 +00006086 testcase( jj==nTo-1 );
drh6b7157b2013-05-10 02:00:35 +00006087 break;
6088 }
6089 }
drha18f3d22013-05-08 03:05:41 +00006090 if( jj>=nTo ){
drhddef5dc2014-08-07 16:50:00 +00006091 /* None of the existing best-so-far paths match the candidate. */
drhddef5dc2014-08-07 16:50:00 +00006092 if( nTo>=mxChoice
dan50ae31e2014-08-08 16:52:28 +00006093 && (rCost>mxCost || (rCost==mxCost && rUnsorted>=mxUnsorted))
drhddef5dc2014-08-07 16:50:00 +00006094 ){
6095 /* The current candidate is no better than any of the mxChoice
6096 ** paths currently in the best-so-far buffer. So discard
6097 ** this candidate as not viable. */
drh989578e2013-10-28 14:34:35 +00006098#ifdef WHERETRACE_ENABLED /* 0x4 */
drhae70cf12013-05-31 15:18:46 +00006099 if( sqlite3WhereTrace&0x4 ){
drhfde1e6b2013-09-06 17:45:42 +00006100 sqlite3DebugPrintf("Skip %s cost=%-3d,%3d order=%c\n",
6101 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
drh0401ace2014-03-18 15:30:27 +00006102 isOrdered>=0 ? isOrdered+'0' : '?');
drhd15cb172013-05-21 19:23:10 +00006103 }
6104#endif
6105 continue;
6106 }
drhddef5dc2014-08-07 16:50:00 +00006107 /* If we reach this points it means that the new candidate path
6108 ** needs to be added to the set of best-so-far paths. */
drha18f3d22013-05-08 03:05:41 +00006109 if( nTo<mxChoice ){
drhd15cb172013-05-21 19:23:10 +00006110 /* Increase the size of the aTo set by one */
drha18f3d22013-05-08 03:05:41 +00006111 jj = nTo++;
6112 }else{
drhd15cb172013-05-21 19:23:10 +00006113 /* New path replaces the prior worst to keep count below mxChoice */
drhfde1e6b2013-09-06 17:45:42 +00006114 jj = mxI;
drha18f3d22013-05-08 03:05:41 +00006115 }
6116 pTo = &aTo[jj];
drh989578e2013-10-28 14:34:35 +00006117#ifdef WHERETRACE_ENABLED /* 0x4 */
drhae70cf12013-05-31 15:18:46 +00006118 if( sqlite3WhereTrace&0x4 ){
drhfde1e6b2013-09-06 17:45:42 +00006119 sqlite3DebugPrintf("New %s cost=%-3d,%3d order=%c\n",
6120 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
drh0401ace2014-03-18 15:30:27 +00006121 isOrdered>=0 ? isOrdered+'0' : '?');
drhd15cb172013-05-21 19:23:10 +00006122 }
6123#endif
drhf204dac2013-05-08 03:22:07 +00006124 }else{
drhddef5dc2014-08-07 16:50:00 +00006125 /* Control reaches here if best-so-far path pTo=aTo[jj] covers the
6126 ** same set of loops and has the sam isOrdered setting as the
6127 ** candidate path. Check to see if the candidate should replace
6128 ** pTo or if the candidate should be skipped */
6129 if( pTo->rCost<rCost || (pTo->rCost==rCost && pTo->nRow<=nOut) ){
drh989578e2013-10-28 14:34:35 +00006130#ifdef WHERETRACE_ENABLED /* 0x4 */
drhae70cf12013-05-31 15:18:46 +00006131 if( sqlite3WhereTrace&0x4 ){
drhd15cb172013-05-21 19:23:10 +00006132 sqlite3DebugPrintf(
drhfde1e6b2013-09-06 17:45:42 +00006133 "Skip %s cost=%-3d,%3d order=%c",
6134 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
drh0401ace2014-03-18 15:30:27 +00006135 isOrdered>=0 ? isOrdered+'0' : '?');
drhfde1e6b2013-09-06 17:45:42 +00006136 sqlite3DebugPrintf(" vs %s cost=%-3d,%d order=%c\n",
6137 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
drh0401ace2014-03-18 15:30:27 +00006138 pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
drhd15cb172013-05-21 19:23:10 +00006139 }
6140#endif
drhddef5dc2014-08-07 16:50:00 +00006141 /* Discard the candidate path from further consideration */
drh7963b0e2013-06-17 21:37:40 +00006142 testcase( pTo->rCost==rCost );
drhd15cb172013-05-21 19:23:10 +00006143 continue;
6144 }
drh7963b0e2013-06-17 21:37:40 +00006145 testcase( pTo->rCost==rCost+1 );
drhddef5dc2014-08-07 16:50:00 +00006146 /* Control reaches here if the candidate path is better than the
6147 ** pTo path. Replace pTo with the candidate. */
drh989578e2013-10-28 14:34:35 +00006148#ifdef WHERETRACE_ENABLED /* 0x4 */
drhae70cf12013-05-31 15:18:46 +00006149 if( sqlite3WhereTrace&0x4 ){
drhd15cb172013-05-21 19:23:10 +00006150 sqlite3DebugPrintf(
drhfde1e6b2013-09-06 17:45:42 +00006151 "Update %s cost=%-3d,%3d order=%c",
6152 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
drh0401ace2014-03-18 15:30:27 +00006153 isOrdered>=0 ? isOrdered+'0' : '?');
drhfde1e6b2013-09-06 17:45:42 +00006154 sqlite3DebugPrintf(" was %s cost=%-3d,%3d order=%c\n",
6155 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
drh0401ace2014-03-18 15:30:27 +00006156 pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
drhd15cb172013-05-21 19:23:10 +00006157 }
6158#endif
drha18f3d22013-05-08 03:05:41 +00006159 }
drh6b7157b2013-05-10 02:00:35 +00006160 /* pWLoop is a winner. Add it to the set of best so far */
drha18f3d22013-05-08 03:05:41 +00006161 pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
drh319f6772013-05-14 15:31:07 +00006162 pTo->revLoop = revMask;
drhfde1e6b2013-09-06 17:45:42 +00006163 pTo->nRow = nOut;
drha18f3d22013-05-08 03:05:41 +00006164 pTo->rCost = rCost;
dan50ae31e2014-08-08 16:52:28 +00006165 pTo->rUnsorted = rUnsorted;
drh6b7157b2013-05-10 02:00:35 +00006166 pTo->isOrdered = isOrdered;
drha18f3d22013-05-08 03:05:41 +00006167 memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
6168 pTo->aLoop[iLoop] = pWLoop;
6169 if( nTo>=mxChoice ){
drhfde1e6b2013-09-06 17:45:42 +00006170 mxI = 0;
drha18f3d22013-05-08 03:05:41 +00006171 mxCost = aTo[0].rCost;
dan50ae31e2014-08-08 16:52:28 +00006172 mxUnsorted = aTo[0].nRow;
drha18f3d22013-05-08 03:05:41 +00006173 for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
dan50ae31e2014-08-08 16:52:28 +00006174 if( pTo->rCost>mxCost
6175 || (pTo->rCost==mxCost && pTo->rUnsorted>mxUnsorted)
6176 ){
drhfde1e6b2013-09-06 17:45:42 +00006177 mxCost = pTo->rCost;
dan50ae31e2014-08-08 16:52:28 +00006178 mxUnsorted = pTo->rUnsorted;
drhfde1e6b2013-09-06 17:45:42 +00006179 mxI = jj;
6180 }
drha18f3d22013-05-08 03:05:41 +00006181 }
6182 }
6183 }
6184 }
6185
drh989578e2013-10-28 14:34:35 +00006186#ifdef WHERETRACE_ENABLED /* >=2 */
drh1b131b72014-10-21 16:01:40 +00006187 if( sqlite3WhereTrace & 0x02 ){
drha50ef112013-05-22 02:06:59 +00006188 sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
drhd15cb172013-05-21 19:23:10 +00006189 for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
drhb8a8e8a2013-06-10 19:12:39 +00006190 sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
drha50ef112013-05-22 02:06:59 +00006191 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
drh0401ace2014-03-18 15:30:27 +00006192 pTo->isOrdered>=0 ? (pTo->isOrdered+'0') : '?');
6193 if( pTo->isOrdered>0 ){
drh88da6442013-05-27 17:59:37 +00006194 sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
6195 }else{
6196 sqlite3DebugPrintf("\n");
6197 }
drhf204dac2013-05-08 03:22:07 +00006198 }
6199 }
6200#endif
6201
drh6b7157b2013-05-10 02:00:35 +00006202 /* Swap the roles of aFrom and aTo for the next generation */
drha18f3d22013-05-08 03:05:41 +00006203 pFrom = aTo;
6204 aTo = aFrom;
6205 aFrom = pFrom;
6206 nFrom = nTo;
6207 }
6208
drh75b93402013-05-31 20:43:57 +00006209 if( nFrom==0 ){
drhe1e2e9a2013-06-13 15:16:53 +00006210 sqlite3ErrorMsg(pParse, "no query solution");
drh75b93402013-05-31 20:43:57 +00006211 sqlite3DbFree(db, pSpace);
6212 return SQLITE_ERROR;
6213 }
drha18f3d22013-05-08 03:05:41 +00006214
drh6b7157b2013-05-10 02:00:35 +00006215 /* Find the lowest cost path. pFrom will be left pointing to that path */
drha18f3d22013-05-08 03:05:41 +00006216 pFrom = aFrom;
6217 for(ii=1; ii<nFrom; ii++){
6218 if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
6219 }
6220 assert( pWInfo->nLevel==nLoop );
drh6b7157b2013-05-10 02:00:35 +00006221 /* Load the lowest cost path into pWInfo */
drha18f3d22013-05-08 03:05:41 +00006222 for(iLoop=0; iLoop<nLoop; iLoop++){
drh7ba39a92013-05-30 17:43:19 +00006223 WhereLevel *pLevel = pWInfo->a + iLoop;
6224 pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
drhe217efc2013-06-12 03:48:41 +00006225 pLevel->iFrom = pWLoop->iTab;
drh7ba39a92013-05-30 17:43:19 +00006226 pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
drha18f3d22013-05-08 03:05:41 +00006227 }
drhfd636c72013-06-21 02:05:06 +00006228 if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0
6229 && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
6230 && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
drh4f402f22013-06-11 18:59:38 +00006231 && nRowEst
6232 ){
6233 Bitmask notUsed;
drh6457a352013-06-21 00:35:37 +00006234 int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom,
drh93ec45d2013-06-17 18:20:48 +00006235 WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
drh0401ace2014-03-18 15:30:27 +00006236 if( rc==pWInfo->pResultSet->nExpr ){
6237 pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
6238 }
drh4f402f22013-06-11 18:59:38 +00006239 }
drh079a3072014-03-19 14:10:55 +00006240 if( pWInfo->pOrderBy ){
drh4f402f22013-06-11 18:59:38 +00006241 if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
drh079a3072014-03-19 14:10:55 +00006242 if( pFrom->isOrdered==pWInfo->pOrderBy->nExpr ){
6243 pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
6244 }
drh4f402f22013-06-11 18:59:38 +00006245 }else{
drhddba0c22014-03-18 20:33:42 +00006246 pWInfo->nOBSat = pFrom->isOrdered;
drhea6c36e2014-03-19 14:30:55 +00006247 if( pWInfo->nOBSat<0 ) pWInfo->nOBSat = 0;
drh4f402f22013-06-11 18:59:38 +00006248 pWInfo->revMask = pFrom->revLoop;
6249 }
dan374cd782014-04-21 13:21:56 +00006250 if( (pWInfo->wctrlFlags & WHERE_SORTBYGROUP)
drh11b04812015-04-12 01:22:04 +00006251 && pWInfo->nOBSat==pWInfo->pOrderBy->nExpr && nLoop>0
dan374cd782014-04-21 13:21:56 +00006252 ){
danb6453202014-10-10 20:52:53 +00006253 Bitmask revMask = 0;
dan374cd782014-04-21 13:21:56 +00006254 int nOrder = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy,
danb6453202014-10-10 20:52:53 +00006255 pFrom, 0, nLoop-1, pFrom->aLoop[nLoop-1], &revMask
dan374cd782014-04-21 13:21:56 +00006256 );
6257 assert( pWInfo->sorted==0 );
danb6453202014-10-10 20:52:53 +00006258 if( nOrder==pWInfo->pOrderBy->nExpr ){
6259 pWInfo->sorted = 1;
6260 pWInfo->revMask = revMask;
6261 }
dan374cd782014-04-21 13:21:56 +00006262 }
drh6b7157b2013-05-10 02:00:35 +00006263 }
dan374cd782014-04-21 13:21:56 +00006264
6265
drha50ef112013-05-22 02:06:59 +00006266 pWInfo->nRowOut = pFrom->nRow;
drha18f3d22013-05-08 03:05:41 +00006267
6268 /* Free temporary memory and return success */
6269 sqlite3DbFree(db, pSpace);
6270 return SQLITE_OK;
6271}
drh75897232000-05-29 14:26:00 +00006272
6273/*
drh60c96cd2013-06-09 17:21:25 +00006274** Most queries use only a single table (they are not joins) and have
6275** simple == constraints against indexed fields. This routine attempts
6276** to plan those simple cases using much less ceremony than the
6277** general-purpose query planner, and thereby yield faster sqlite3_prepare()
6278** times for the common case.
6279**
6280** Return non-zero on success, if this query can be handled by this
6281** no-frills query planner. Return zero if this query needs the
6282** general-purpose query planner.
6283*/
drhb8a8e8a2013-06-10 19:12:39 +00006284static int whereShortCut(WhereLoopBuilder *pBuilder){
drh60c96cd2013-06-09 17:21:25 +00006285 WhereInfo *pWInfo;
6286 struct SrcList_item *pItem;
6287 WhereClause *pWC;
6288 WhereTerm *pTerm;
6289 WhereLoop *pLoop;
6290 int iCur;
drh92a121f2013-06-10 12:15:47 +00006291 int j;
drh60c96cd2013-06-09 17:21:25 +00006292 Table *pTab;
6293 Index *pIdx;
6294
6295 pWInfo = pBuilder->pWInfo;
drh5822d6f2013-06-10 23:30:09 +00006296 if( pWInfo->wctrlFlags & WHERE_FORCE_TABLE ) return 0;
drh60c96cd2013-06-09 17:21:25 +00006297 assert( pWInfo->pTabList->nSrc>=1 );
6298 pItem = pWInfo->pTabList->a;
6299 pTab = pItem->pTab;
6300 if( IsVirtual(pTab) ) return 0;
6301 if( pItem->zIndex ) return 0;
6302 iCur = pItem->iCursor;
6303 pWC = &pWInfo->sWC;
6304 pLoop = pBuilder->pNew;
drh60c96cd2013-06-09 17:21:25 +00006305 pLoop->wsFlags = 0;
drhc8bbce12014-10-21 01:05:09 +00006306 pLoop->nSkip = 0;
drh3b75ffa2013-06-10 14:56:25 +00006307 pTerm = findTerm(pWC, iCur, -1, 0, WO_EQ, 0);
drh60c96cd2013-06-09 17:21:25 +00006308 if( pTerm ){
6309 pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
6310 pLoop->aLTerm[0] = pTerm;
6311 pLoop->nLTerm = 1;
6312 pLoop->u.btree.nEq = 1;
drhe1e2e9a2013-06-13 15:16:53 +00006313 /* TUNING: Cost of a rowid lookup is 10 */
drhbf539c42013-10-05 18:16:02 +00006314 pLoop->rRun = 33; /* 33==sqlite3LogEst(10) */
drh60c96cd2013-06-09 17:21:25 +00006315 }else{
6316 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
dancd40abb2013-08-29 10:46:05 +00006317 assert( pLoop->aLTermSpace==pLoop->aLTerm );
drh5f1d1d92014-07-31 22:59:04 +00006318 if( !IsUniqueIndex(pIdx)
dancd40abb2013-08-29 10:46:05 +00006319 || pIdx->pPartIdxWhere!=0
drhbbbdc832013-10-22 18:01:40 +00006320 || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace)
dancd40abb2013-08-29 10:46:05 +00006321 ) continue;
drhbbbdc832013-10-22 18:01:40 +00006322 for(j=0; j<pIdx->nKeyCol; j++){
drh3b75ffa2013-06-10 14:56:25 +00006323 pTerm = findTerm(pWC, iCur, pIdx->aiColumn[j], 0, WO_EQ, pIdx);
drh60c96cd2013-06-09 17:21:25 +00006324 if( pTerm==0 ) break;
drh60c96cd2013-06-09 17:21:25 +00006325 pLoop->aLTerm[j] = pTerm;
6326 }
drhbbbdc832013-10-22 18:01:40 +00006327 if( j!=pIdx->nKeyCol ) continue;
drh92a121f2013-06-10 12:15:47 +00006328 pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
drhec95c442013-10-23 01:57:32 +00006329 if( pIdx->isCovering || (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){
drh92a121f2013-06-10 12:15:47 +00006330 pLoop->wsFlags |= WHERE_IDX_ONLY;
6331 }
drh60c96cd2013-06-09 17:21:25 +00006332 pLoop->nLTerm = j;
6333 pLoop->u.btree.nEq = j;
6334 pLoop->u.btree.pIndex = pIdx;
drhe1e2e9a2013-06-13 15:16:53 +00006335 /* TUNING: Cost of a unique index lookup is 15 */
drhbf539c42013-10-05 18:16:02 +00006336 pLoop->rRun = 39; /* 39==sqlite3LogEst(15) */
drh60c96cd2013-06-09 17:21:25 +00006337 break;
6338 }
6339 }
drh3b75ffa2013-06-10 14:56:25 +00006340 if( pLoop->wsFlags ){
drhbf539c42013-10-05 18:16:02 +00006341 pLoop->nOut = (LogEst)1;
drh3b75ffa2013-06-10 14:56:25 +00006342 pWInfo->a[0].pWLoop = pLoop;
6343 pLoop->maskSelf = getMask(&pWInfo->sMaskSet, iCur);
6344 pWInfo->a[0].iTabCur = iCur;
6345 pWInfo->nRowOut = 1;
drhddba0c22014-03-18 20:33:42 +00006346 if( pWInfo->pOrderBy ) pWInfo->nOBSat = pWInfo->pOrderBy->nExpr;
drh6457a352013-06-21 00:35:37 +00006347 if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
6348 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
6349 }
drh3b75ffa2013-06-10 14:56:25 +00006350#ifdef SQLITE_DEBUG
6351 pLoop->cId = '0';
6352#endif
6353 return 1;
6354 }
6355 return 0;
drh60c96cd2013-06-09 17:21:25 +00006356}
6357
6358/*
drh75897232000-05-29 14:26:00 +00006359** Generate the beginning of the loop used for WHERE clause processing.
6360** The return value is a pointer to an opaque structure that contains
6361** information needed to terminate the loop. Later, the calling routine
6362** should invoke sqlite3WhereEnd() with the return value of this function
6363** in order to complete the WHERE clause processing.
6364**
6365** If an error occurs, this routine returns NULL.
drhc27a1ce2002-06-14 20:58:45 +00006366**
6367** The basic idea is to do a nested loop, one loop for each table in
6368** the FROM clause of a select. (INSERT and UPDATE statements are the
6369** same as a SELECT with only a single table in the FROM clause.) For
6370** example, if the SQL is this:
6371**
6372** SELECT * FROM t1, t2, t3 WHERE ...;
6373**
6374** Then the code generated is conceptually like the following:
6375**
6376** foreach row1 in t1 do \ Code generated
danielk19774adee202004-05-08 08:23:19 +00006377** foreach row2 in t2 do |-- by sqlite3WhereBegin()
drhc27a1ce2002-06-14 20:58:45 +00006378** foreach row3 in t3 do /
6379** ...
6380** end \ Code generated
danielk19774adee202004-05-08 08:23:19 +00006381** end |-- by sqlite3WhereEnd()
drhc27a1ce2002-06-14 20:58:45 +00006382** end /
6383**
drh29dda4a2005-07-21 18:23:20 +00006384** Note that the loops might not be nested in the order in which they
6385** appear in the FROM clause if a different order is better able to make
drh51147ba2005-07-23 22:59:55 +00006386** use of indices. Note also that when the IN operator appears in
6387** the WHERE clause, it might result in additional nested loops for
6388** scanning through all values on the right-hand side of the IN.
drh29dda4a2005-07-21 18:23:20 +00006389**
drhc27a1ce2002-06-14 20:58:45 +00006390** There are Btree cursors associated with each table. t1 uses cursor
drh6a3ea0e2003-05-02 14:32:12 +00006391** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
6392** And so forth. This routine generates code to open those VDBE cursors
danielk19774adee202004-05-08 08:23:19 +00006393** and sqlite3WhereEnd() generates the code to close them.
drhc27a1ce2002-06-14 20:58:45 +00006394**
drhe6f85e72004-12-25 01:03:13 +00006395** The code that sqlite3WhereBegin() generates leaves the cursors named
6396** in pTabList pointing at their appropriate entries. The [...] code
drhf0863fe2005-06-12 21:35:51 +00006397** can use OP_Column and OP_Rowid opcodes on these cursors to extract
drhe6f85e72004-12-25 01:03:13 +00006398** data from the various tables of the loop.
6399**
drhc27a1ce2002-06-14 20:58:45 +00006400** If the WHERE clause is empty, the foreach loops must each scan their
6401** entire tables. Thus a three-way join is an O(N^3) operation. But if
6402** the tables have indices and there are terms in the WHERE clause that
6403** refer to those indices, a complete table scan can be avoided and the
6404** code will run much faster. Most of the work of this routine is checking
6405** to see if there are indices that can be used to speed up the loop.
6406**
6407** Terms of the WHERE clause are also used to limit which rows actually
6408** make it to the "..." in the middle of the loop. After each "foreach",
6409** terms of the WHERE clause that use only terms in that loop and outer
6410** loops are evaluated and if false a jump is made around all subsequent
6411** inner loops (or around the "..." if the test occurs within the inner-
6412** most loop)
6413**
6414** OUTER JOINS
6415**
6416** An outer join of tables t1 and t2 is conceptally coded as follows:
6417**
6418** foreach row1 in t1 do
6419** flag = 0
6420** foreach row2 in t2 do
6421** start:
6422** ...
6423** flag = 1
6424** end
drhe3184742002-06-19 14:27:05 +00006425** if flag==0 then
6426** move the row2 cursor to a null row
6427** goto start
6428** fi
drhc27a1ce2002-06-14 20:58:45 +00006429** end
6430**
drhe3184742002-06-19 14:27:05 +00006431** ORDER BY CLAUSE PROCESSING
6432**
drh94433422013-07-01 11:05:50 +00006433** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause
6434** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement
drhe3184742002-06-19 14:27:05 +00006435** if there is one. If there is no ORDER BY clause or if this routine
drh46ec5b62012-09-24 15:30:54 +00006436** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
drhfc8d4f92013-11-08 15:19:46 +00006437**
6438** The iIdxCur parameter is the cursor number of an index. If
6439** WHERE_ONETABLE_ONLY is set, iIdxCur is the cursor number of an index
6440** to use for OR clause processing. The WHERE clause should use this
6441** specific cursor. If WHERE_ONEPASS_DESIRED is set, then iIdxCur is
6442** the first cursor in an array of cursors for all indices. iIdxCur should
6443** be used to compute the appropriate cursor depending on which index is
6444** used.
drh75897232000-05-29 14:26:00 +00006445*/
danielk19774adee202004-05-08 08:23:19 +00006446WhereInfo *sqlite3WhereBegin(
danielk1977ed326d72004-11-16 15:50:19 +00006447 Parse *pParse, /* The parser context */
drh6457a352013-06-21 00:35:37 +00006448 SrcList *pTabList, /* FROM clause: A list of all tables to be scanned */
danielk1977ed326d72004-11-16 15:50:19 +00006449 Expr *pWhere, /* The WHERE clause */
drh0401ace2014-03-18 15:30:27 +00006450 ExprList *pOrderBy, /* An ORDER BY (or GROUP BY) clause, or NULL */
drh6457a352013-06-21 00:35:37 +00006451 ExprList *pResultSet, /* Result set of the query */
dan0efb72c2012-08-24 18:44:56 +00006452 u16 wctrlFlags, /* One of the WHERE_* flags defined in sqliteInt.h */
6453 int iIdxCur /* If WHERE_ONETABLE_ONLY is set, index cursor number */
drh75897232000-05-29 14:26:00 +00006454){
danielk1977be229652009-03-20 14:18:51 +00006455 int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
drhc01a3c12009-12-16 22:10:49 +00006456 int nTabList; /* Number of elements in pTabList */
drh75897232000-05-29 14:26:00 +00006457 WhereInfo *pWInfo; /* Will become the return value of this function */
6458 Vdbe *v = pParse->pVdbe; /* The virtual database engine */
drhfe05af82005-07-21 03:14:59 +00006459 Bitmask notReady; /* Cursors that are not yet positioned */
drh1c8148f2013-05-04 20:25:23 +00006460 WhereLoopBuilder sWLB; /* The WhereLoop builder */
drh111a6a72008-12-21 03:51:16 +00006461 WhereMaskSet *pMaskSet; /* The expression mask set */
drh56f1b992012-09-25 14:29:39 +00006462 WhereLevel *pLevel; /* A single level in pWInfo->a[] */
drhfd636c72013-06-21 02:05:06 +00006463 WhereLoop *pLoop; /* Pointer to a single WhereLoop object */
drh9cd1c992012-09-25 20:43:35 +00006464 int ii; /* Loop counter */
drh17435752007-08-16 04:30:38 +00006465 sqlite3 *db; /* Database connection */
drh5346e952013-05-08 14:14:26 +00006466 int rc; /* Return code */
drh75897232000-05-29 14:26:00 +00006467
drh56f1b992012-09-25 14:29:39 +00006468
6469 /* Variable initialization */
drhfd636c72013-06-21 02:05:06 +00006470 db = pParse->db;
drh1c8148f2013-05-04 20:25:23 +00006471 memset(&sWLB, 0, sizeof(sWLB));
drh0401ace2014-03-18 15:30:27 +00006472
6473 /* An ORDER/GROUP BY clause of more than 63 terms cannot be optimized */
6474 testcase( pOrderBy && pOrderBy->nExpr==BMS-1 );
6475 if( pOrderBy && pOrderBy->nExpr>=BMS ) pOrderBy = 0;
drh1c8148f2013-05-04 20:25:23 +00006476 sWLB.pOrderBy = pOrderBy;
drh56f1b992012-09-25 14:29:39 +00006477
drhfd636c72013-06-21 02:05:06 +00006478 /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
6479 ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
6480 if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
6481 wctrlFlags &= ~WHERE_WANT_DISTINCT;
6482 }
6483
drh29dda4a2005-07-21 18:23:20 +00006484 /* The number of tables in the FROM clause is limited by the number of
drh1398ad32005-01-19 23:24:50 +00006485 ** bits in a Bitmask
6486 */
drh67ae0cb2010-04-08 14:38:51 +00006487 testcase( pTabList->nSrc==BMS );
drh29dda4a2005-07-21 18:23:20 +00006488 if( pTabList->nSrc>BMS ){
6489 sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
drh1398ad32005-01-19 23:24:50 +00006490 return 0;
6491 }
6492
drhc01a3c12009-12-16 22:10:49 +00006493 /* This function normally generates a nested loop for all tables in
6494 ** pTabList. But if the WHERE_ONETABLE_ONLY flag is set, then we should
6495 ** only generate code for the first table in pTabList and assume that
6496 ** any cursors associated with subsequent tables are uninitialized.
6497 */
6498 nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
6499
drh75897232000-05-29 14:26:00 +00006500 /* Allocate and initialize the WhereInfo structure that will become the
danielk1977be229652009-03-20 14:18:51 +00006501 ** return value. A single allocation is used to store the WhereInfo
6502 ** struct, the contents of WhereInfo.a[], the WhereClause structure
6503 ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
6504 ** field (type Bitmask) it must be aligned on an 8-byte boundary on
6505 ** some architectures. Hence the ROUND8() below.
drh75897232000-05-29 14:26:00 +00006506 */
drhc01a3c12009-12-16 22:10:49 +00006507 nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
drh60c96cd2013-06-09 17:21:25 +00006508 pWInfo = sqlite3DbMallocZero(db, nByteWInfo + sizeof(WhereLoop));
drh17435752007-08-16 04:30:38 +00006509 if( db->mallocFailed ){
drh8b307fb2010-04-06 15:57:05 +00006510 sqlite3DbFree(db, pWInfo);
6511 pWInfo = 0;
danielk197785574e32008-10-06 05:32:18 +00006512 goto whereBeginError;
drh75897232000-05-29 14:26:00 +00006513 }
drhfc8d4f92013-11-08 15:19:46 +00006514 pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1;
drhc01a3c12009-12-16 22:10:49 +00006515 pWInfo->nLevel = nTabList;
drh75897232000-05-29 14:26:00 +00006516 pWInfo->pParse = pParse;
6517 pWInfo->pTabList = pTabList;
drh6b7157b2013-05-10 02:00:35 +00006518 pWInfo->pOrderBy = pOrderBy;
drh6457a352013-06-21 00:35:37 +00006519 pWInfo->pResultSet = pResultSet;
drha22a75e2014-03-21 18:16:23 +00006520 pWInfo->iBreak = pWInfo->iContinue = sqlite3VdbeMakeLabel(v);
drh6df2acd2008-12-28 16:55:25 +00006521 pWInfo->wctrlFlags = wctrlFlags;
drh8b307fb2010-04-06 15:57:05 +00006522 pWInfo->savedNQueryLoop = pParse->nQueryLoop;
drh70d18342013-06-06 19:16:33 +00006523 pMaskSet = &pWInfo->sMaskSet;
drh1c8148f2013-05-04 20:25:23 +00006524 sWLB.pWInfo = pWInfo;
drh70d18342013-06-06 19:16:33 +00006525 sWLB.pWC = &pWInfo->sWC;
drh1ac87e12013-07-18 14:50:56 +00006526 sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);
6527 assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) );
drh60c96cd2013-06-09 17:21:25 +00006528 whereLoopInit(sWLB.pNew);
drhb8a8e8a2013-06-10 19:12:39 +00006529#ifdef SQLITE_DEBUG
6530 sWLB.pNew->cId = '*';
6531#endif
drh08192d52002-04-30 19:20:28 +00006532
drh111a6a72008-12-21 03:51:16 +00006533 /* Split the WHERE clause into separate subexpressions where each
6534 ** subexpression is separated by an AND operator.
6535 */
6536 initMaskSet(pMaskSet);
drh70d18342013-06-06 19:16:33 +00006537 whereClauseInit(&pWInfo->sWC, pWInfo);
drh39759742013-08-02 23:40:45 +00006538 whereSplit(&pWInfo->sWC, pWhere, TK_AND);
drh111a6a72008-12-21 03:51:16 +00006539
drh08192d52002-04-30 19:20:28 +00006540 /* Special case: a WHERE clause that is constant. Evaluate the
6541 ** expression and either jump over all of the code or fall thru.
6542 */
drh759e8582014-01-02 21:05:10 +00006543 for(ii=0; ii<sWLB.pWC->nTerm; ii++){
6544 if( nTabList==0 || sqlite3ExprIsConstantNotJoin(sWLB.pWC->a[ii].pExpr) ){
6545 sqlite3ExprIfFalse(pParse, sWLB.pWC->a[ii].pExpr, pWInfo->iBreak,
6546 SQLITE_JUMPIFNULL);
6547 sWLB.pWC->a[ii].wtFlags |= TERM_CODED;
6548 }
drh08192d52002-04-30 19:20:28 +00006549 }
drh75897232000-05-29 14:26:00 +00006550
drh4fe425a2013-06-12 17:08:06 +00006551 /* Special case: No FROM clause
6552 */
6553 if( nTabList==0 ){
drhddba0c22014-03-18 20:33:42 +00006554 if( pOrderBy ) pWInfo->nOBSat = pOrderBy->nExpr;
drh6457a352013-06-21 00:35:37 +00006555 if( wctrlFlags & WHERE_WANT_DISTINCT ){
6556 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
6557 }
drh4fe425a2013-06-12 17:08:06 +00006558 }
6559
drh42165be2008-03-26 14:56:34 +00006560 /* Assign a bit from the bitmask to every term in the FROM clause.
6561 **
6562 ** When assigning bitmask values to FROM clause cursors, it must be
6563 ** the case that if X is the bitmask for the N-th FROM clause term then
6564 ** the bitmask for all FROM clause terms to the left of the N-th term
6565 ** is (X-1). An expression from the ON clause of a LEFT JOIN can use
6566 ** its Expr.iRightJoinTable value to find the bitmask of the right table
6567 ** of the join. Subtracting one from the right table bitmask gives a
6568 ** bitmask for all tables to the left of the join. Knowing the bitmask
6569 ** for all tables to the left of a left join is important. Ticket #3015.
danielk1977e672c8e2009-05-22 15:43:26 +00006570 **
drhc01a3c12009-12-16 22:10:49 +00006571 ** Note that bitmasks are created for all pTabList->nSrc tables in
6572 ** pTabList, not just the first nTabList tables. nTabList is normally
6573 ** equal to pTabList->nSrc but might be shortened to 1 if the
6574 ** WHERE_ONETABLE_ONLY flag is set.
drh42165be2008-03-26 14:56:34 +00006575 */
drh9cd1c992012-09-25 20:43:35 +00006576 for(ii=0; ii<pTabList->nSrc; ii++){
6577 createMask(pMaskSet, pTabList->a[ii].iCursor);
drh42165be2008-03-26 14:56:34 +00006578 }
6579#ifndef NDEBUG
6580 {
6581 Bitmask toTheLeft = 0;
drh9cd1c992012-09-25 20:43:35 +00006582 for(ii=0; ii<pTabList->nSrc; ii++){
6583 Bitmask m = getMask(pMaskSet, pTabList->a[ii].iCursor);
drh42165be2008-03-26 14:56:34 +00006584 assert( (m-1)==toTheLeft );
6585 toTheLeft |= m;
6586 }
6587 }
6588#endif
6589
drh29dda4a2005-07-21 18:23:20 +00006590 /* Analyze all of the subexpressions. Note that exprAnalyze() might
6591 ** add new virtual terms onto the end of the WHERE clause. We do not
6592 ** want to analyze these virtual terms, so start analyzing at the end
drhb6fb62d2005-09-20 08:47:20 +00006593 ** and work forward so that the added virtual terms are never processed.
drh75897232000-05-29 14:26:00 +00006594 */
drh70d18342013-06-06 19:16:33 +00006595 exprAnalyzeAll(pTabList, &pWInfo->sWC);
drh17435752007-08-16 04:30:38 +00006596 if( db->mallocFailed ){
danielk197785574e32008-10-06 05:32:18 +00006597 goto whereBeginError;
drh0bbaa1b2005-08-19 19:14:12 +00006598 }
drh75897232000-05-29 14:26:00 +00006599
drh6457a352013-06-21 00:35:37 +00006600 if( wctrlFlags & WHERE_WANT_DISTINCT ){
6601 if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){
6602 /* The DISTINCT marking is pointless. Ignore it. */
drh4f402f22013-06-11 18:59:38 +00006603 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
6604 }else if( pOrderBy==0 ){
drh6457a352013-06-21 00:35:37 +00006605 /* Try to ORDER BY the result set to make distinct processing easier */
drh4f402f22013-06-11 18:59:38 +00006606 pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
drh6457a352013-06-21 00:35:37 +00006607 pWInfo->pOrderBy = pResultSet;
drh4f402f22013-06-11 18:59:38 +00006608 }
dan38cc40c2011-06-30 20:17:15 +00006609 }
6610
drhf1b5f5b2013-05-02 00:15:01 +00006611 /* Construct the WhereLoop objects */
drh3b48e8c2013-06-12 20:18:16 +00006612 WHERETRACE(0xffff,("*** Optimizer Start ***\n"));
drhc90713d2014-09-30 13:46:49 +00006613#if defined(WHERETRACE_ENABLED)
6614 /* Display all terms of the WHERE clause */
6615 if( sqlite3WhereTrace & 0x100 ){
6616 int i;
6617 for(i=0; i<sWLB.pWC->nTerm; i++){
6618 whereTermPrint(&sWLB.pWC->a[i], i);
6619 }
6620 }
6621#endif
6622
drhb8a8e8a2013-06-10 19:12:39 +00006623 if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
drh60c96cd2013-06-09 17:21:25 +00006624 rc = whereLoopAddAll(&sWLB);
6625 if( rc ) goto whereBeginError;
6626
6627 /* Display all of the WhereLoop objects if wheretrace is enabled */
drh989578e2013-10-28 14:34:35 +00006628#ifdef WHERETRACE_ENABLED /* !=0 */
drh60c96cd2013-06-09 17:21:25 +00006629 if( sqlite3WhereTrace ){
6630 WhereLoop *p;
drhfd636c72013-06-21 02:05:06 +00006631 int i;
drh60c96cd2013-06-09 17:21:25 +00006632 static char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
6633 "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
drhfd636c72013-06-21 02:05:06 +00006634 for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
6635 p->cId = zLabel[i%sizeof(zLabel)];
drhc1ba2e72013-10-28 19:03:21 +00006636 whereLoopPrint(p, sWLB.pWC);
drh60c96cd2013-06-09 17:21:25 +00006637 }
6638 }
6639#endif
6640
drh4f402f22013-06-11 18:59:38 +00006641 wherePathSolver(pWInfo, 0);
drh60c96cd2013-06-09 17:21:25 +00006642 if( db->mallocFailed ) goto whereBeginError;
6643 if( pWInfo->pOrderBy ){
drhc7f0d222013-06-19 03:27:12 +00006644 wherePathSolver(pWInfo, pWInfo->nRowOut+1);
drh60c96cd2013-06-09 17:21:25 +00006645 if( db->mallocFailed ) goto whereBeginError;
drha18f3d22013-05-08 03:05:41 +00006646 }
6647 }
drh60c96cd2013-06-09 17:21:25 +00006648 if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
drhd84ce352013-06-04 18:27:41 +00006649 pWInfo->revMask = (Bitmask)(-1);
drha50ef112013-05-22 02:06:59 +00006650 }
drh81186b42013-06-18 01:52:41 +00006651 if( pParse->nErr || NEVER(db->mallocFailed) ){
drh75b93402013-05-31 20:43:57 +00006652 goto whereBeginError;
6653 }
drh989578e2013-10-28 14:34:35 +00006654#ifdef WHERETRACE_ENABLED /* !=0 */
drha18f3d22013-05-08 03:05:41 +00006655 if( sqlite3WhereTrace ){
drh4f402f22013-06-11 18:59:38 +00006656 sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
drhddba0c22014-03-18 20:33:42 +00006657 if( pWInfo->nOBSat>0 ){
6658 sqlite3DebugPrintf(" ORDERBY=%d,0x%llx", pWInfo->nOBSat, pWInfo->revMask);
drh319f6772013-05-14 15:31:07 +00006659 }
drh4f402f22013-06-11 18:59:38 +00006660 switch( pWInfo->eDistinct ){
6661 case WHERE_DISTINCT_UNIQUE: {
6662 sqlite3DebugPrintf(" DISTINCT=unique");
6663 break;
6664 }
6665 case WHERE_DISTINCT_ORDERED: {
6666 sqlite3DebugPrintf(" DISTINCT=ordered");
6667 break;
6668 }
6669 case WHERE_DISTINCT_UNORDERED: {
6670 sqlite3DebugPrintf(" DISTINCT=unordered");
6671 break;
6672 }
6673 }
6674 sqlite3DebugPrintf("\n");
drhfd636c72013-06-21 02:05:06 +00006675 for(ii=0; ii<pWInfo->nLevel; ii++){
drhc1ba2e72013-10-28 19:03:21 +00006676 whereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC);
drhf1b5f5b2013-05-02 00:15:01 +00006677 }
6678 }
6679#endif
drhfd636c72013-06-21 02:05:06 +00006680 /* Attempt to omit tables from the join that do not effect the result */
drh1031bd92013-06-22 15:44:26 +00006681 if( pWInfo->nLevel>=2
6682 && pResultSet!=0
6683 && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
6684 ){
drhfd636c72013-06-21 02:05:06 +00006685 Bitmask tabUsed = exprListTableUsage(pMaskSet, pResultSet);
drh67a5ec72013-09-03 14:03:47 +00006686 if( sWLB.pOrderBy ) tabUsed |= exprListTableUsage(pMaskSet, sWLB.pOrderBy);
drhfd636c72013-06-21 02:05:06 +00006687 while( pWInfo->nLevel>=2 ){
drh9d5a5792013-06-28 13:43:33 +00006688 WhereTerm *pTerm, *pEnd;
drhfd636c72013-06-21 02:05:06 +00006689 pLoop = pWInfo->a[pWInfo->nLevel-1].pWLoop;
drhbc71b1d2013-06-21 02:15:48 +00006690 if( (pWInfo->pTabList->a[pLoop->iTab].jointype & JT_LEFT)==0 ) break;
6691 if( (wctrlFlags & WHERE_WANT_DISTINCT)==0
6692 && (pLoop->wsFlags & WHERE_ONEROW)==0
drhfd636c72013-06-21 02:05:06 +00006693 ){
drhfd636c72013-06-21 02:05:06 +00006694 break;
6695 }
drhbc71b1d2013-06-21 02:15:48 +00006696 if( (tabUsed & pLoop->maskSelf)!=0 ) break;
drh9d5a5792013-06-28 13:43:33 +00006697 pEnd = sWLB.pWC->a + sWLB.pWC->nTerm;
6698 for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
6699 if( (pTerm->prereqAll & pLoop->maskSelf)!=0
6700 && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
6701 ){
6702 break;
6703 }
6704 }
6705 if( pTerm<pEnd ) break;
drhbc71b1d2013-06-21 02:15:48 +00006706 WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId));
6707 pWInfo->nLevel--;
6708 nTabList--;
drhfd636c72013-06-21 02:05:06 +00006709 }
6710 }
drh3b48e8c2013-06-12 20:18:16 +00006711 WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
drh8e23daf2013-06-11 13:30:04 +00006712 pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
drhf1b5f5b2013-05-02 00:15:01 +00006713
drh08c88eb2008-04-10 13:33:18 +00006714 /* If the caller is an UPDATE or DELETE statement that is requesting
6715 ** to use a one-pass algorithm, determine if this is appropriate.
drh24b7fe92013-09-30 19:33:06 +00006716 ** The one-pass algorithm only works if the WHERE clause constrains
drh08c88eb2008-04-10 13:33:18 +00006717 ** the statement to update a single row.
6718 */
drh165be382008-12-05 02:36:33 +00006719 assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
drh3b48e8c2013-06-12 20:18:16 +00006720 if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
6721 && (pWInfo->a[0].pWLoop->wsFlags & WHERE_ONEROW)!=0 ){
drh08c88eb2008-04-10 13:33:18 +00006722 pWInfo->okOnePass = 1;
drh702ba9f2013-11-07 21:25:13 +00006723 if( HasRowid(pTabList->a[0].pTab) ){
6724 pWInfo->a[0].pWLoop->wsFlags &= ~WHERE_IDX_ONLY;
6725 }
drh08c88eb2008-04-10 13:33:18 +00006726 }
drheb04de32013-05-10 15:16:30 +00006727
drh9012bcb2004-12-19 00:11:35 +00006728 /* Open all tables in the pTabList and any indices selected for
6729 ** searching those tables.
6730 */
drh8b307fb2010-04-06 15:57:05 +00006731 notReady = ~(Bitmask)0;
drh9cd1c992012-09-25 20:43:35 +00006732 for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
danielk1977da184232006-01-05 11:34:32 +00006733 Table *pTab; /* Table to open */
danielk1977da184232006-01-05 11:34:32 +00006734 int iDb; /* Index of database containing table/index */
drh56f1b992012-09-25 14:29:39 +00006735 struct SrcList_item *pTabItem;
drh9012bcb2004-12-19 00:11:35 +00006736
drh29dda4a2005-07-21 18:23:20 +00006737 pTabItem = &pTabList->a[pLevel->iFrom];
drh9012bcb2004-12-19 00:11:35 +00006738 pTab = pTabItem->pTab;
danielk1977595a5232009-07-24 17:58:53 +00006739 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
drh7ba39a92013-05-30 17:43:19 +00006740 pLoop = pLevel->pWLoop;
drh424aab82010-04-06 18:28:20 +00006741 if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
drh75bb9f52010-04-06 18:51:42 +00006742 /* Do nothing */
6743 }else
drh9eff6162006-06-12 21:59:13 +00006744#ifndef SQLITE_OMIT_VIRTUALTABLE
drh7ba39a92013-05-30 17:43:19 +00006745 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
danielk1977595a5232009-07-24 17:58:53 +00006746 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
danielk197793626f42006-06-20 13:07:27 +00006747 int iCur = pTabItem->iCursor;
danielk1977595a5232009-07-24 17:58:53 +00006748 sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
drhfc5e5462012-12-03 17:04:40 +00006749 }else if( IsVirtual(pTab) ){
6750 /* noop */
drh9eff6162006-06-12 21:59:13 +00006751 }else
6752#endif
drh7ba39a92013-05-30 17:43:19 +00006753 if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
drh9ef61f42011-10-07 14:40:59 +00006754 && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){
drhfc8d4f92013-11-08 15:19:46 +00006755 int op = OP_OpenRead;
6756 if( pWInfo->okOnePass ){
6757 op = OP_OpenWrite;
6758 pWInfo->aiCurOnePass[0] = pTabItem->iCursor;
6759 };
drh08c88eb2008-04-10 13:33:18 +00006760 sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
drhfc8d4f92013-11-08 15:19:46 +00006761 assert( pTabItem->iCursor==pLevel->iTabCur );
drh7963b0e2013-06-17 21:37:40 +00006762 testcase( !pWInfo->okOnePass && pTab->nCol==BMS-1 );
6763 testcase( !pWInfo->okOnePass && pTab->nCol==BMS );
drhdd9930e2013-10-23 23:37:02 +00006764 if( !pWInfo->okOnePass && pTab->nCol<BMS && HasRowid(pTab) ){
danielk19779792eef2006-01-13 15:58:43 +00006765 Bitmask b = pTabItem->colUsed;
6766 int n = 0;
drh74161702006-02-24 02:53:49 +00006767 for(; b; b=b>>1, n++){}
drh8cff69d2009-11-12 19:59:44 +00006768 sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
6769 SQLITE_INT_TO_PTR(n), P4_INT32);
danielk19779792eef2006-01-13 15:58:43 +00006770 assert( n<=pTab->nCol );
6771 }
danielk1977c00da102006-01-07 13:21:04 +00006772 }else{
6773 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
drh9012bcb2004-12-19 00:11:35 +00006774 }
drh7e47cb82013-05-31 17:55:27 +00006775 if( pLoop->wsFlags & WHERE_INDEXED ){
drh7ba39a92013-05-30 17:43:19 +00006776 Index *pIx = pLoop->u.btree.pIndex;
drhfc8d4f92013-11-08 15:19:46 +00006777 int iIndexCur;
6778 int op = OP_OpenRead;
drh4308e342013-11-11 16:55:52 +00006779 /* iIdxCur is always set if to a positive value if ONEPASS is possible */
6780 assert( iIdxCur!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 );
drh48dd1d82014-05-27 18:18:58 +00006781 if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIx)
drha3bc66a2014-05-27 17:57:32 +00006782 && (wctrlFlags & WHERE_ONETABLE_ONLY)!=0
6783 ){
6784 /* This is one term of an OR-optimization using the PRIMARY KEY of a
6785 ** WITHOUT ROWID table. No need for a separate index */
6786 iIndexCur = pLevel->iTabCur;
6787 op = 0;
6788 }else if( pWInfo->okOnePass ){
drhfc8d4f92013-11-08 15:19:46 +00006789 Index *pJ = pTabItem->pTab->pIndex;
6790 iIndexCur = iIdxCur;
6791 assert( wctrlFlags & WHERE_ONEPASS_DESIRED );
6792 while( ALWAYS(pJ) && pJ!=pIx ){
6793 iIndexCur++;
6794 pJ = pJ->pNext;
6795 }
6796 op = OP_OpenWrite;
6797 pWInfo->aiCurOnePass[1] = iIndexCur;
6798 }else if( iIdxCur && (wctrlFlags & WHERE_ONETABLE_ONLY)!=0 ){
6799 iIndexCur = iIdxCur;
drh35263192014-07-22 20:02:19 +00006800 if( wctrlFlags & WHERE_REOPEN_IDX ) op = OP_ReopenIdx;
drhfc8d4f92013-11-08 15:19:46 +00006801 }else{
6802 iIndexCur = pParse->nTab++;
6803 }
6804 pLevel->iIdxCur = iIndexCur;
danielk1977da184232006-01-05 11:34:32 +00006805 assert( pIx->pSchema==pTab->pSchema );
drhb0367fb2012-08-25 02:11:13 +00006806 assert( iIndexCur>=0 );
drha3bc66a2014-05-27 17:57:32 +00006807 if( op ){
6808 sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb);
6809 sqlite3VdbeSetP4KeyInfo(pParse, pIx);
drhe0997b32015-03-20 14:57:50 +00006810 if( (pLoop->wsFlags & WHERE_CONSTRAINT)!=0
6811 && (pLoop->wsFlags & (WHERE_COLUMN_RANGE|WHERE_SKIPSCAN))==0
6812 && (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0
6813 ){
6814 sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ); /* Hint to COMDB2 */
6815 }
drha3bc66a2014-05-27 17:57:32 +00006816 VdbeComment((v, "%s", pIx->zName));
6817 }
drh9012bcb2004-12-19 00:11:35 +00006818 }
drhaceb31b2014-02-08 01:40:27 +00006819 if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb);
drh70d18342013-06-06 19:16:33 +00006820 notReady &= ~getMask(&pWInfo->sMaskSet, pTabItem->iCursor);
drh9012bcb2004-12-19 00:11:35 +00006821 }
6822 pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
drha21a64d2010-04-06 22:33:55 +00006823 if( db->mallocFailed ) goto whereBeginError;
drh9012bcb2004-12-19 00:11:35 +00006824
drh29dda4a2005-07-21 18:23:20 +00006825 /* Generate the code to do the search. Each iteration of the for
6826 ** loop below generates code for a single nested loop of the VM
6827 ** program.
drh75897232000-05-29 14:26:00 +00006828 */
drhfe05af82005-07-21 03:14:59 +00006829 notReady = ~(Bitmask)0;
drh9cd1c992012-09-25 20:43:35 +00006830 for(ii=0; ii<nTabList; ii++){
dan6f9702e2014-11-01 20:38:06 +00006831 int addrExplain;
6832 int wsFlags;
drh9cd1c992012-09-25 20:43:35 +00006833 pLevel = &pWInfo->a[ii];
dan6f9702e2014-11-01 20:38:06 +00006834 wsFlags = pLevel->pWLoop->wsFlags;
drhcc04afd2013-08-22 02:56:28 +00006835#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
6836 if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){
6837 constructAutomaticIndex(pParse, &pWInfo->sWC,
6838 &pTabList->a[pLevel->iFrom], notReady, pLevel);
6839 if( db->mallocFailed ) goto whereBeginError;
6840 }
6841#endif
dan6f9702e2014-11-01 20:38:06 +00006842 addrExplain = explainOneScan(
6843 pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags
6844 );
drhcc04afd2013-08-22 02:56:28 +00006845 pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
drh70d18342013-06-06 19:16:33 +00006846 notReady = codeOneLoopStart(pWInfo, ii, notReady);
dan4a07e3d2010-11-09 14:48:59 +00006847 pWInfo->iContinue = pLevel->addrCont;
dan6f9702e2014-11-01 20:38:06 +00006848 if( (wsFlags&WHERE_MULTI_OR)==0 && (wctrlFlags&WHERE_ONETABLE_ONLY)==0 ){
6849 addScanStatus(v, pTabList, pLevel, addrExplain);
6850 }
drh75897232000-05-29 14:26:00 +00006851 }
drh7ec764a2005-07-21 03:48:20 +00006852
drh6fa978d2013-05-30 19:29:19 +00006853 /* Done. */
drh6bc69a22013-11-19 12:33:23 +00006854 VdbeModuleComment((v, "Begin WHERE-core"));
drh75897232000-05-29 14:26:00 +00006855 return pWInfo;
drhe23399f2005-07-22 00:31:39 +00006856
6857 /* Jump here if malloc fails */
danielk197785574e32008-10-06 05:32:18 +00006858whereBeginError:
drh8b307fb2010-04-06 15:57:05 +00006859 if( pWInfo ){
6860 pParse->nQueryLoop = pWInfo->savedNQueryLoop;
6861 whereInfoFree(db, pWInfo);
6862 }
drhe23399f2005-07-22 00:31:39 +00006863 return 0;
drh75897232000-05-29 14:26:00 +00006864}
6865
6866/*
drhc27a1ce2002-06-14 20:58:45 +00006867** Generate the end of the WHERE loop. See comments on
danielk19774adee202004-05-08 08:23:19 +00006868** sqlite3WhereBegin() for additional information.
drh75897232000-05-29 14:26:00 +00006869*/
danielk19774adee202004-05-08 08:23:19 +00006870void sqlite3WhereEnd(WhereInfo *pWInfo){
drh633e6d52008-07-28 19:34:53 +00006871 Parse *pParse = pWInfo->pParse;
6872 Vdbe *v = pParse->pVdbe;
drh19a775c2000-06-05 18:54:46 +00006873 int i;
drh6b563442001-11-07 16:48:26 +00006874 WhereLevel *pLevel;
drh7ba39a92013-05-30 17:43:19 +00006875 WhereLoop *pLoop;
drhad3cab52002-05-24 02:04:32 +00006876 SrcList *pTabList = pWInfo->pTabList;
drh633e6d52008-07-28 19:34:53 +00006877 sqlite3 *db = pParse->db;
drh19a775c2000-06-05 18:54:46 +00006878
drh9012bcb2004-12-19 00:11:35 +00006879 /* Generate loop termination code.
6880 */
drh6bc69a22013-11-19 12:33:23 +00006881 VdbeModuleComment((v, "End WHERE-core"));
drhceea3322009-04-23 13:22:42 +00006882 sqlite3ExprCacheClear(pParse);
drhc01a3c12009-12-16 22:10:49 +00006883 for(i=pWInfo->nLevel-1; i>=0; i--){
drhcd8629e2013-11-13 12:27:25 +00006884 int addr;
drh6b563442001-11-07 16:48:26 +00006885 pLevel = &pWInfo->a[i];
drh7ba39a92013-05-30 17:43:19 +00006886 pLoop = pLevel->pWLoop;
drhb3190c12008-12-08 21:37:14 +00006887 sqlite3VdbeResolveLabel(v, pLevel->addrCont);
drh6b563442001-11-07 16:48:26 +00006888 if( pLevel->op!=OP_Noop ){
drhe39a7322014-02-03 14:04:11 +00006889 sqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3);
drhd1d38482008-10-07 23:46:38 +00006890 sqlite3VdbeChangeP5(v, pLevel->p5);
drh688852a2014-02-17 22:40:43 +00006891 VdbeCoverage(v);
drh7d176102014-02-18 03:07:12 +00006892 VdbeCoverageIf(v, pLevel->op==OP_Next);
6893 VdbeCoverageIf(v, pLevel->op==OP_Prev);
6894 VdbeCoverageIf(v, pLevel->op==OP_VNext);
drh19a775c2000-06-05 18:54:46 +00006895 }
drh7ba39a92013-05-30 17:43:19 +00006896 if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
drh72e8fa42007-03-28 14:30:06 +00006897 struct InLoop *pIn;
drhe23399f2005-07-22 00:31:39 +00006898 int j;
drhb3190c12008-12-08 21:37:14 +00006899 sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
drh111a6a72008-12-21 03:51:16 +00006900 for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
drhb3190c12008-12-08 21:37:14 +00006901 sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
drh2d96b932013-02-08 18:48:23 +00006902 sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
drh688852a2014-02-17 22:40:43 +00006903 VdbeCoverage(v);
drh7d176102014-02-18 03:07:12 +00006904 VdbeCoverageIf(v, pIn->eEndLoopOp==OP_PrevIfOpen);
6905 VdbeCoverageIf(v, pIn->eEndLoopOp==OP_NextIfOpen);
drhb3190c12008-12-08 21:37:14 +00006906 sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
drhe23399f2005-07-22 00:31:39 +00006907 }
drhd99f7062002-06-08 23:25:08 +00006908 }
drhb3190c12008-12-08 21:37:14 +00006909 sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
drhcd8629e2013-11-13 12:27:25 +00006910 if( pLevel->addrSkip ){
drhcd8629e2013-11-13 12:27:25 +00006911 sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrSkip);
drhe084f402013-11-13 17:24:38 +00006912 VdbeComment((v, "next skip-scan on %s", pLoop->u.btree.pIndex->zName));
drh2e5ef4e2013-11-13 16:58:54 +00006913 sqlite3VdbeJumpHere(v, pLevel->addrSkip);
6914 sqlite3VdbeJumpHere(v, pLevel->addrSkip-2);
drhcd8629e2013-11-13 12:27:25 +00006915 }
drhf07cf6e2015-03-06 16:45:16 +00006916 if( pLevel->addrLikeRep ){
drhb7c60ba2015-03-07 02:51:59 +00006917 int op;
6918 if( sqlite3VdbeGetOp(v, pLevel->addrLikeRep-1)->p1 ){
6919 op = OP_DecrJumpZero;
6920 }else{
6921 op = OP_JumpZeroIncr;
6922 }
6923 sqlite3VdbeAddOp2(v, op, pLevel->iLikeRepCntr, pLevel->addrLikeRep);
drhf07cf6e2015-03-06 16:45:16 +00006924 VdbeCoverage(v);
drhf07cf6e2015-03-06 16:45:16 +00006925 }
drhad2d8302002-05-24 20:31:36 +00006926 if( pLevel->iLeftJoin ){
drh688852a2014-02-17 22:40:43 +00006927 addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v);
drh7ba39a92013-05-30 17:43:19 +00006928 assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
6929 || (pLoop->wsFlags & WHERE_INDEXED)!=0 );
6930 if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 ){
drh35451c62009-11-12 04:26:39 +00006931 sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
6932 }
drh76f4cfb2013-05-31 18:20:52 +00006933 if( pLoop->wsFlags & WHERE_INDEXED ){
drh3c84ddf2008-01-09 02:15:38 +00006934 sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
drh7f09b3e2002-08-13 13:15:49 +00006935 }
drh336a5302009-04-24 15:46:21 +00006936 if( pLevel->op==OP_Return ){
6937 sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
6938 }else{
6939 sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
6940 }
drhd654be82005-09-20 17:42:23 +00006941 sqlite3VdbeJumpHere(v, addr);
drhad2d8302002-05-24 20:31:36 +00006942 }
drh6bc69a22013-11-19 12:33:23 +00006943 VdbeModuleComment((v, "End WHERE-loop%d: %s", i,
drhfc8d4f92013-11-08 15:19:46 +00006944 pWInfo->pTabList->a[pLevel->iFrom].pTab->zName));
drh19a775c2000-06-05 18:54:46 +00006945 }
drh9012bcb2004-12-19 00:11:35 +00006946
6947 /* The "break" point is here, just past the end of the outer loop.
6948 ** Set it.
6949 */
danielk19774adee202004-05-08 08:23:19 +00006950 sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
drh9012bcb2004-12-19 00:11:35 +00006951
drhfd636c72013-06-21 02:05:06 +00006952 assert( pWInfo->nLevel<=pTabList->nSrc );
drhc01a3c12009-12-16 22:10:49 +00006953 for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
drh5f612292014-02-08 23:20:32 +00006954 int k, last;
6955 VdbeOp *pOp;
danbfca6a42012-08-24 10:52:35 +00006956 Index *pIdx = 0;
drh29dda4a2005-07-21 18:23:20 +00006957 struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
drh9012bcb2004-12-19 00:11:35 +00006958 Table *pTab = pTabItem->pTab;
drh5cf590c2003-04-24 01:45:04 +00006959 assert( pTab!=0 );
drh7ba39a92013-05-30 17:43:19 +00006960 pLoop = pLevel->pWLoop;
drhfc8d4f92013-11-08 15:19:46 +00006961
drh5f612292014-02-08 23:20:32 +00006962 /* For a co-routine, change all OP_Column references to the table of
6963 ** the co-routine into OP_SCopy of result contained in a register.
6964 ** OP_Rowid becomes OP_Null.
6965 */
danfbf0f0e2014-03-03 14:20:30 +00006966 if( pTabItem->viaCoroutine && !db->mallocFailed ){
drh5f612292014-02-08 23:20:32 +00006967 last = sqlite3VdbeCurrentAddr(v);
6968 k = pLevel->addrBody;
6969 pOp = sqlite3VdbeGetOp(v, k);
6970 for(; k<last; k++, pOp++){
6971 if( pOp->p1!=pLevel->iTabCur ) continue;
6972 if( pOp->opcode==OP_Column ){
drhc438df12014-04-03 16:29:31 +00006973 pOp->opcode = OP_Copy;
drh5f612292014-02-08 23:20:32 +00006974 pOp->p1 = pOp->p2 + pTabItem->regResult;
6975 pOp->p2 = pOp->p3;
6976 pOp->p3 = 0;
6977 }else if( pOp->opcode==OP_Rowid ){
6978 pOp->opcode = OP_Null;
6979 pOp->p1 = 0;
6980 pOp->p3 = 0;
6981 }
6982 }
6983 continue;
6984 }
6985
drhfc8d4f92013-11-08 15:19:46 +00006986 /* Close all of the cursors that were opened by sqlite3WhereBegin.
6987 ** Except, do not close cursors that will be reused by the OR optimization
6988 ** (WHERE_OMIT_OPEN_CLOSE). And do not close the OP_OpenWrite cursors
6989 ** created for the ONEPASS optimization.
6990 */
drh4139c992010-04-07 14:59:45 +00006991 if( (pTab->tabFlags & TF_Ephemeral)==0
6992 && pTab->pSelect==0
drh9ef61f42011-10-07 14:40:59 +00006993 && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
drh4139c992010-04-07 14:59:45 +00006994 ){
drh7ba39a92013-05-30 17:43:19 +00006995 int ws = pLoop->wsFlags;
drh8b307fb2010-04-06 15:57:05 +00006996 if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
drh6df2acd2008-12-28 16:55:25 +00006997 sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
6998 }
drhfc8d4f92013-11-08 15:19:46 +00006999 if( (ws & WHERE_INDEXED)!=0
7000 && (ws & (WHERE_IPK|WHERE_AUTO_INDEX))==0
7001 && pLevel->iIdxCur!=pWInfo->aiCurOnePass[1]
7002 ){
drh6df2acd2008-12-28 16:55:25 +00007003 sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
7004 }
drh9012bcb2004-12-19 00:11:35 +00007005 }
7006
drhf0030762013-06-14 13:27:01 +00007007 /* If this scan uses an index, make VDBE code substitutions to read data
7008 ** from the index instead of from the table where possible. In some cases
7009 ** this optimization prevents the table from ever being read, which can
7010 ** yield a significant performance boost.
drh9012bcb2004-12-19 00:11:35 +00007011 **
7012 ** Calls to the code generator in between sqlite3WhereBegin and
7013 ** sqlite3WhereEnd will have created code that references the table
7014 ** directly. This loop scans all that code looking for opcodes
7015 ** that reference the table and converts them into opcodes that
7016 ** reference the index.
7017 */
drh7ba39a92013-05-30 17:43:19 +00007018 if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
7019 pIdx = pLoop->u.btree.pIndex;
7020 }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
drhd40e2082012-08-24 23:24:15 +00007021 pIdx = pLevel->u.pCovidx;
danbfca6a42012-08-24 10:52:35 +00007022 }
drh7ba39a92013-05-30 17:43:19 +00007023 if( pIdx && !db->mallocFailed ){
drh9012bcb2004-12-19 00:11:35 +00007024 last = sqlite3VdbeCurrentAddr(v);
drhcc04afd2013-08-22 02:56:28 +00007025 k = pLevel->addrBody;
7026 pOp = sqlite3VdbeGetOp(v, k);
7027 for(; k<last; k++, pOp++){
drh9012bcb2004-12-19 00:11:35 +00007028 if( pOp->p1!=pLevel->iTabCur ) continue;
7029 if( pOp->opcode==OP_Column ){
drhee0ec8e2013-10-31 17:38:01 +00007030 int x = pOp->p2;
drh511717c2013-11-08 17:13:23 +00007031 assert( pIdx->pTable==pTab );
drhee0ec8e2013-10-31 17:38:01 +00007032 if( !HasRowid(pTab) ){
7033 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
7034 x = pPk->aiColumn[x];
7035 }
7036 x = sqlite3ColumnOfIndex(pIdx, x);
drh44156282013-10-23 22:23:03 +00007037 if( x>=0 ){
7038 pOp->p2 = x;
7039 pOp->p1 = pLevel->iIdxCur;
drh9012bcb2004-12-19 00:11:35 +00007040 }
drh44156282013-10-23 22:23:03 +00007041 assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || x>=0 );
drhf0863fe2005-06-12 21:35:51 +00007042 }else if( pOp->opcode==OP_Rowid ){
drh9012bcb2004-12-19 00:11:35 +00007043 pOp->p1 = pLevel->iIdxCur;
drhf0863fe2005-06-12 21:35:51 +00007044 pOp->opcode = OP_IdxRowid;
drh9012bcb2004-12-19 00:11:35 +00007045 }
7046 }
drh6b563442001-11-07 16:48:26 +00007047 }
drh19a775c2000-06-05 18:54:46 +00007048 }
drh9012bcb2004-12-19 00:11:35 +00007049
7050 /* Final cleanup
7051 */
drhf12cde52010-04-08 17:28:00 +00007052 pParse->nQueryLoop = pWInfo->savedNQueryLoop;
7053 whereInfoFree(db, pWInfo);
drh75897232000-05-29 14:26:00 +00007054 return;
7055}