blob: d6bce65d2e5724a18d4b938ca29b38eae8a5834f [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){
258 pWC->op = op;
drh0aa74ed2005-07-16 13:33:20 +0000259 if( pExpr==0 ) return;
drh6c30be82005-07-29 15:10:17 +0000260 if( pExpr->op!=op ){
drh0aa74ed2005-07-16 13:33:20 +0000261 whereClauseInsert(pWC, pExpr, 0);
drh75897232000-05-29 14:26:00 +0000262 }else{
drh6c30be82005-07-29 15:10:17 +0000263 whereSplit(pWC, pExpr->pLeft, op);
264 whereSplit(pWC, pExpr->pRight, op);
drh75897232000-05-29 14:26:00 +0000265 }
drh75897232000-05-29 14:26:00 +0000266}
267
268/*
drh3b48e8c2013-06-12 20:18:16 +0000269** Initialize a WhereMaskSet object
drh6a3ea0e2003-05-02 14:32:12 +0000270*/
drhfd5874d2013-06-12 14:52:39 +0000271#define initMaskSet(P) (P)->n=0
drh6a3ea0e2003-05-02 14:32:12 +0000272
273/*
drh1398ad32005-01-19 23:24:50 +0000274** Return the bitmask for the given cursor number. Return 0 if
275** iCursor is not in the set.
drh6a3ea0e2003-05-02 14:32:12 +0000276*/
drh111a6a72008-12-21 03:51:16 +0000277static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
drh6a3ea0e2003-05-02 14:32:12 +0000278 int i;
drhfcd71b62011-04-05 22:08:24 +0000279 assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
drh6a3ea0e2003-05-02 14:32:12 +0000280 for(i=0; i<pMaskSet->n; i++){
drh51669862004-12-18 18:40:26 +0000281 if( pMaskSet->ix[i]==iCursor ){
drh7699d1c2013-06-04 12:42:29 +0000282 return MASKBIT(i);
drh51669862004-12-18 18:40:26 +0000283 }
drh6a3ea0e2003-05-02 14:32:12 +0000284 }
drh6a3ea0e2003-05-02 14:32:12 +0000285 return 0;
286}
287
288/*
drh1398ad32005-01-19 23:24:50 +0000289** Create a new mask for cursor iCursor.
drh0fcef5e2005-07-19 17:38:22 +0000290**
291** There is one cursor per table in the FROM clause. The number of
292** tables in the FROM clause is limited by a test early in the
drhb6fb62d2005-09-20 08:47:20 +0000293** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[]
drh0fcef5e2005-07-19 17:38:22 +0000294** array will never overflow.
drh1398ad32005-01-19 23:24:50 +0000295*/
drh111a6a72008-12-21 03:51:16 +0000296static void createMask(WhereMaskSet *pMaskSet, int iCursor){
drhcad651e2007-04-20 12:22:01 +0000297 assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
drh0fcef5e2005-07-19 17:38:22 +0000298 pMaskSet->ix[pMaskSet->n++] = iCursor;
drh1398ad32005-01-19 23:24:50 +0000299}
300
301/*
drh4a6fc352013-08-07 01:18:38 +0000302** These routines walk (recursively) an expression tree and generate
drh75897232000-05-29 14:26:00 +0000303** a bitmask indicating which tables are used in that expression
drh6a3ea0e2003-05-02 14:32:12 +0000304** tree.
drh75897232000-05-29 14:26:00 +0000305*/
drh111a6a72008-12-21 03:51:16 +0000306static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
307static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
308static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
drh51669862004-12-18 18:40:26 +0000309 Bitmask mask = 0;
drh75897232000-05-29 14:26:00 +0000310 if( p==0 ) return 0;
drh967e8b72000-06-21 13:59:10 +0000311 if( p->op==TK_COLUMN ){
drh8feb4b12004-07-19 02:12:14 +0000312 mask = getMask(pMaskSet, p->iTable);
drh8feb4b12004-07-19 02:12:14 +0000313 return mask;
drh75897232000-05-29 14:26:00 +0000314 }
danielk1977b3bce662005-01-29 08:32:43 +0000315 mask = exprTableUsage(pMaskSet, p->pRight);
316 mask |= exprTableUsage(pMaskSet, p->pLeft);
danielk19776ab3a2e2009-02-19 14:39:25 +0000317 if( ExprHasProperty(p, EP_xIsSelect) ){
318 mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
319 }else{
320 mask |= exprListTableUsage(pMaskSet, p->x.pList);
321 }
danielk1977b3bce662005-01-29 08:32:43 +0000322 return mask;
323}
drh111a6a72008-12-21 03:51:16 +0000324static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
danielk1977b3bce662005-01-29 08:32:43 +0000325 int i;
326 Bitmask mask = 0;
327 if( pList ){
328 for(i=0; i<pList->nExpr; i++){
329 mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
drhdd579122002-04-02 01:58:57 +0000330 }
331 }
drh75897232000-05-29 14:26:00 +0000332 return mask;
333}
drh111a6a72008-12-21 03:51:16 +0000334static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
drha430ae82007-09-12 15:41:01 +0000335 Bitmask mask = 0;
336 while( pS ){
drha464c232011-09-16 19:04:03 +0000337 SrcList *pSrc = pS->pSrc;
drha430ae82007-09-12 15:41:01 +0000338 mask |= exprListTableUsage(pMaskSet, pS->pEList);
drhf5b11382005-09-17 13:07:13 +0000339 mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
340 mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
341 mask |= exprTableUsage(pMaskSet, pS->pWhere);
342 mask |= exprTableUsage(pMaskSet, pS->pHaving);
drha464c232011-09-16 19:04:03 +0000343 if( ALWAYS(pSrc!=0) ){
drh88501772011-09-16 17:43:06 +0000344 int i;
345 for(i=0; i<pSrc->nSrc; i++){
346 mask |= exprSelectTableUsage(pMaskSet, pSrc->a[i].pSelect);
347 mask |= exprTableUsage(pMaskSet, pSrc->a[i].pOn);
348 }
349 }
drha430ae82007-09-12 15:41:01 +0000350 pS = pS->pPrior;
drhf5b11382005-09-17 13:07:13 +0000351 }
352 return mask;
353}
drh75897232000-05-29 14:26:00 +0000354
355/*
drh487ab3c2001-11-08 00:45:21 +0000356** Return TRUE if the given operator is one of the operators that is
drh51669862004-12-18 18:40:26 +0000357** allowed for an indexable WHERE clause term. The allowed operators are
drh3b48e8c2013-06-12 20:18:16 +0000358** "=", "<", ">", "<=", ">=", "IN", and "IS NULL"
drh487ab3c2001-11-08 00:45:21 +0000359*/
360static int allowedOp(int op){
drhfe05af82005-07-21 03:14:59 +0000361 assert( TK_GT>TK_EQ && TK_GT<TK_GE );
362 assert( TK_LT>TK_EQ && TK_LT<TK_GE );
363 assert( TK_LE>TK_EQ && TK_LE<TK_GE );
364 assert( TK_GE==TK_EQ+4 );
drh50b39962006-10-28 00:28:09 +0000365 return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
drh487ab3c2001-11-08 00:45:21 +0000366}
367
368/*
drh909626d2008-05-30 14:58:37 +0000369** Commute a comparison operator. Expressions of the form "X op Y"
drh0fcef5e2005-07-19 17:38:22 +0000370** are converted into "Y op X".
danielk1977eb5453d2007-07-30 14:40:48 +0000371**
mistachkin48864df2013-03-21 21:20:32 +0000372** If left/right precedence rules come into play when determining the
drh3b48e8c2013-06-12 20:18:16 +0000373** collating sequence, then COLLATE operators are adjusted to ensure
374** that the collating sequence does not change. For example:
375** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on
danielk1977eb5453d2007-07-30 14:40:48 +0000376** the left hand side of a comparison overrides any collation sequence
drhae80dde2012-12-06 21:16:43 +0000377** attached to the right. For the same reason the EP_Collate flag
danielk1977eb5453d2007-07-30 14:40:48 +0000378** is not commuted.
drh193bd772004-07-20 18:23:14 +0000379*/
drh7d10d5a2008-08-20 16:35:10 +0000380static void exprCommute(Parse *pParse, Expr *pExpr){
drhae80dde2012-12-06 21:16:43 +0000381 u16 expRight = (pExpr->pRight->flags & EP_Collate);
382 u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
drhfe05af82005-07-21 03:14:59 +0000383 assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
drhae80dde2012-12-06 21:16:43 +0000384 if( expRight==expLeft ){
385 /* Either X and Y both have COLLATE operator or neither do */
386 if( expRight ){
387 /* Both X and Y have COLLATE operators. Make sure X is always
388 ** used by clearing the EP_Collate flag from Y. */
389 pExpr->pRight->flags &= ~EP_Collate;
390 }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
391 /* Neither X nor Y have COLLATE operators, but X has a non-default
392 ** collating sequence. So add the EP_Collate marker on X to cause
393 ** it to be searched first. */
394 pExpr->pLeft->flags |= EP_Collate;
395 }
396 }
drh0fcef5e2005-07-19 17:38:22 +0000397 SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
398 if( pExpr->op>=TK_GT ){
399 assert( TK_LT==TK_GT+2 );
400 assert( TK_GE==TK_LE+2 );
401 assert( TK_GT>TK_EQ );
402 assert( TK_GT<TK_LE );
403 assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
404 pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
drh193bd772004-07-20 18:23:14 +0000405 }
drh193bd772004-07-20 18:23:14 +0000406}
407
408/*
drhfe05af82005-07-21 03:14:59 +0000409** Translate from TK_xx operator to WO_xx bitmask.
410*/
drhec1724e2008-12-09 01:32:03 +0000411static u16 operatorMask(int op){
412 u16 c;
drhfe05af82005-07-21 03:14:59 +0000413 assert( allowedOp(op) );
414 if( op==TK_IN ){
drh51147ba2005-07-23 22:59:55 +0000415 c = WO_IN;
drh50b39962006-10-28 00:28:09 +0000416 }else if( op==TK_ISNULL ){
417 c = WO_ISNULL;
drhfe05af82005-07-21 03:14:59 +0000418 }else{
drhec1724e2008-12-09 01:32:03 +0000419 assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
420 c = (u16)(WO_EQ<<(op-TK_EQ));
drhfe05af82005-07-21 03:14:59 +0000421 }
drh50b39962006-10-28 00:28:09 +0000422 assert( op!=TK_ISNULL || c==WO_ISNULL );
drh51147ba2005-07-23 22:59:55 +0000423 assert( op!=TK_IN || c==WO_IN );
424 assert( op!=TK_EQ || c==WO_EQ );
425 assert( op!=TK_LT || c==WO_LT );
426 assert( op!=TK_LE || c==WO_LE );
427 assert( op!=TK_GT || c==WO_GT );
428 assert( op!=TK_GE || c==WO_GE );
429 return c;
drhfe05af82005-07-21 03:14:59 +0000430}
431
432/*
drh1c8148f2013-05-04 20:25:23 +0000433** Advance to the next WhereTerm that matches according to the criteria
434** established when the pScan object was initialized by whereScanInit().
435** Return NULL if there are no more matching WhereTerms.
436*/
danb2cfc142013-07-05 11:10:54 +0000437static WhereTerm *whereScanNext(WhereScan *pScan){
drh1c8148f2013-05-04 20:25:23 +0000438 int iCur; /* The cursor on the LHS of the term */
439 int iColumn; /* The column on the LHS of the term. -1 for IPK */
440 Expr *pX; /* An expression being tested */
441 WhereClause *pWC; /* Shorthand for pScan->pWC */
442 WhereTerm *pTerm; /* The term being tested */
drh43b85ef2013-06-10 12:34:45 +0000443 int k = pScan->k; /* Where to start scanning */
drh1c8148f2013-05-04 20:25:23 +0000444
445 while( pScan->iEquiv<=pScan->nEquiv ){
446 iCur = pScan->aEquiv[pScan->iEquiv-2];
447 iColumn = pScan->aEquiv[pScan->iEquiv-1];
448 while( (pWC = pScan->pWC)!=0 ){
drh43b85ef2013-06-10 12:34:45 +0000449 for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
drhe1a086e2013-10-28 20:15:56 +0000450 if( pTerm->leftCursor==iCur
451 && pTerm->u.leftColumn==iColumn
452 && (pScan->iEquiv<=2 || !ExprHasProperty(pTerm->pExpr, EP_FromJoin))
453 ){
drh1c8148f2013-05-04 20:25:23 +0000454 if( (pTerm->eOperator & WO_EQUIV)!=0
455 && pScan->nEquiv<ArraySize(pScan->aEquiv)
456 ){
457 int j;
458 pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight);
459 assert( pX->op==TK_COLUMN );
460 for(j=0; j<pScan->nEquiv; j+=2){
461 if( pScan->aEquiv[j]==pX->iTable
462 && pScan->aEquiv[j+1]==pX->iColumn ){
463 break;
464 }
465 }
466 if( j==pScan->nEquiv ){
467 pScan->aEquiv[j] = pX->iTable;
468 pScan->aEquiv[j+1] = pX->iColumn;
469 pScan->nEquiv += 2;
470 }
471 }
472 if( (pTerm->eOperator & pScan->opMask)!=0 ){
473 /* Verify the affinity and collating sequence match */
474 if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
475 CollSeq *pColl;
drh70d18342013-06-06 19:16:33 +0000476 Parse *pParse = pWC->pWInfo->pParse;
drh1c8148f2013-05-04 20:25:23 +0000477 pX = pTerm->pExpr;
478 if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
479 continue;
480 }
481 assert(pX->pLeft);
drh70d18342013-06-06 19:16:33 +0000482 pColl = sqlite3BinaryCompareCollSeq(pParse,
drh1c8148f2013-05-04 20:25:23 +0000483 pX->pLeft, pX->pRight);
drh70d18342013-06-06 19:16:33 +0000484 if( pColl==0 ) pColl = pParse->db->pDfltColl;
drh1c8148f2013-05-04 20:25:23 +0000485 if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
486 continue;
487 }
488 }
drha184fb82013-05-08 04:22:59 +0000489 if( (pTerm->eOperator & WO_EQ)!=0
490 && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN
491 && pX->iTable==pScan->aEquiv[0]
492 && pX->iColumn==pScan->aEquiv[1]
493 ){
494 continue;
495 }
drh43b85ef2013-06-10 12:34:45 +0000496 pScan->k = k+1;
drh1c8148f2013-05-04 20:25:23 +0000497 return pTerm;
498 }
499 }
500 }
drhad01d892013-06-19 13:59:49 +0000501 pScan->pWC = pScan->pWC->pOuter;
drh43b85ef2013-06-10 12:34:45 +0000502 k = 0;
drh1c8148f2013-05-04 20:25:23 +0000503 }
504 pScan->pWC = pScan->pOrigWC;
drh43b85ef2013-06-10 12:34:45 +0000505 k = 0;
drh1c8148f2013-05-04 20:25:23 +0000506 pScan->iEquiv += 2;
507 }
drh1c8148f2013-05-04 20:25:23 +0000508 return 0;
509}
510
511/*
512** Initialize a WHERE clause scanner object. Return a pointer to the
513** first match. Return NULL if there are no matches.
514**
515** The scanner will be searching the WHERE clause pWC. It will look
516** for terms of the form "X <op> <expr>" where X is column iColumn of table
517** iCur. The <op> must be one of the operators described by opMask.
518**
drh3b48e8c2013-06-12 20:18:16 +0000519** If the search is for X and the WHERE clause contains terms of the
520** form X=Y then this routine might also return terms of the form
521** "Y <op> <expr>". The number of levels of transitivity is limited,
522** but is enough to handle most commonly occurring SQL statements.
523**
drh1c8148f2013-05-04 20:25:23 +0000524** If X is not the INTEGER PRIMARY KEY then X must be compatible with
525** index pIdx.
526*/
danb2cfc142013-07-05 11:10:54 +0000527static WhereTerm *whereScanInit(
drh1c8148f2013-05-04 20:25:23 +0000528 WhereScan *pScan, /* The WhereScan object being initialized */
529 WhereClause *pWC, /* The WHERE clause to be scanned */
530 int iCur, /* Cursor to scan for */
531 int iColumn, /* Column to scan for */
532 u32 opMask, /* Operator(s) to scan for */
533 Index *pIdx /* Must be compatible with this index */
534){
535 int j;
536
drhe9d935a2013-06-05 16:19:59 +0000537 /* memset(pScan, 0, sizeof(*pScan)); */
drh1c8148f2013-05-04 20:25:23 +0000538 pScan->pOrigWC = pWC;
539 pScan->pWC = pWC;
540 if( pIdx && iColumn>=0 ){
541 pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
542 for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
dan39129ce2014-06-30 15:23:57 +0000543 if( NEVER(j>pIdx->nColumn) ) return 0;
drh1c8148f2013-05-04 20:25:23 +0000544 }
545 pScan->zCollName = pIdx->azColl[j];
drhe9d935a2013-06-05 16:19:59 +0000546 }else{
547 pScan->idxaff = 0;
548 pScan->zCollName = 0;
drh1c8148f2013-05-04 20:25:23 +0000549 }
550 pScan->opMask = opMask;
drhe9d935a2013-06-05 16:19:59 +0000551 pScan->k = 0;
drh1c8148f2013-05-04 20:25:23 +0000552 pScan->aEquiv[0] = iCur;
553 pScan->aEquiv[1] = iColumn;
554 pScan->nEquiv = 2;
555 pScan->iEquiv = 2;
556 return whereScanNext(pScan);
557}
558
559/*
drhfe05af82005-07-21 03:14:59 +0000560** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
561** where X is a reference to the iColumn of table iCur and <op> is one of
562** the WO_xx operator codes specified by the op parameter.
563** Return a pointer to the term. Return 0 if not found.
drh58eb1c02013-01-17 00:08:42 +0000564**
565** The term returned might by Y=<expr> if there is another constraint in
566** the WHERE clause that specifies that X=Y. Any such constraints will be
567** identified by the WO_EQUIV bit in the pTerm->eOperator field. The
568** aEquiv[] array holds X and all its equivalents, with each SQL variable
569** taking up two slots in aEquiv[]. The first slot is for the cursor number
570** and the second is for the column number. There are 22 slots in aEquiv[]
571** so that means we can look for X plus up to 10 other equivalent values.
572** Hence a search for X will return <expr> if X=A1 and A1=A2 and A2=A3
573** and ... and A9=A10 and A10=<expr>.
574**
575** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
576** then try for the one with no dependencies on <expr> - in other words where
577** <expr> is a constant expression of some kind. Only return entries of
578** the form "X <op> Y" where Y is a column in another table if no terms of
drh459f63e2013-03-06 01:55:27 +0000579** the form "X <op> <const-expr>" exist. If no terms with a constant RHS
580** exist, try to return a term that does not use WO_EQUIV.
drhfe05af82005-07-21 03:14:59 +0000581*/
582static WhereTerm *findTerm(
583 WhereClause *pWC, /* The WHERE clause to be searched */
584 int iCur, /* Cursor number of LHS */
585 int iColumn, /* Column number of LHS */
586 Bitmask notReady, /* RHS must not overlap with this mask */
drhec1724e2008-12-09 01:32:03 +0000587 u32 op, /* Mask of WO_xx values describing operator */
drhfe05af82005-07-21 03:14:59 +0000588 Index *pIdx /* Must be compatible with this index, if not NULL */
589){
drh1c8148f2013-05-04 20:25:23 +0000590 WhereTerm *pResult = 0;
591 WhereTerm *p;
592 WhereScan scan;
drh7a5bcc02013-01-16 17:08:58 +0000593
drh1c8148f2013-05-04 20:25:23 +0000594 p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
595 while( p ){
596 if( (p->prereqRight & notReady)==0 ){
597 if( p->prereqRight==0 && (p->eOperator&WO_EQ)!=0 ){
598 return p;
drhfe05af82005-07-21 03:14:59 +0000599 }
drh1c8148f2013-05-04 20:25:23 +0000600 if( pResult==0 ) pResult = p;
drhfe05af82005-07-21 03:14:59 +0000601 }
drh1c8148f2013-05-04 20:25:23 +0000602 p = whereScanNext(&scan);
drhfe05af82005-07-21 03:14:59 +0000603 }
drh7a5bcc02013-01-16 17:08:58 +0000604 return pResult;
drhfe05af82005-07-21 03:14:59 +0000605}
606
drh6c30be82005-07-29 15:10:17 +0000607/* Forward reference */
drh7b4fc6a2007-02-06 13:26:32 +0000608static void exprAnalyze(SrcList*, WhereClause*, int);
drh6c30be82005-07-29 15:10:17 +0000609
610/*
611** Call exprAnalyze on all terms in a WHERE clause.
drh6c30be82005-07-29 15:10:17 +0000612*/
613static void exprAnalyzeAll(
614 SrcList *pTabList, /* the FROM clause */
drh6c30be82005-07-29 15:10:17 +0000615 WhereClause *pWC /* the WHERE clause to be analyzed */
616){
drh6c30be82005-07-29 15:10:17 +0000617 int i;
drh9eb20282005-08-24 03:52:18 +0000618 for(i=pWC->nTerm-1; i>=0; i--){
drh7b4fc6a2007-02-06 13:26:32 +0000619 exprAnalyze(pTabList, pWC, i);
drh6c30be82005-07-29 15:10:17 +0000620 }
621}
622
drhd2687b72005-08-12 22:56:09 +0000623#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
624/*
625** Check to see if the given expression is a LIKE or GLOB operator that
626** can be optimized using inequality constraints. Return TRUE if it is
627** so and false if not.
628**
629** In order for the operator to be optimizible, the RHS must be a string
drhf07cf6e2015-03-06 16:45:16 +0000630** literal that does not begin with a wildcard. The LHS must be a column
631** that may only be NULL, a string, or a BLOB, never a number. (This means
632** that virtual tables cannot participate in the LIKE optimization.) If the
633** collating sequence for the column on the LHS must be appropriate for
634** the operator.
drhd2687b72005-08-12 22:56:09 +0000635*/
636static int isLikeOrGlob(
drh7d10d5a2008-08-20 16:35:10 +0000637 Parse *pParse, /* Parsing and code generating context */
drhd2687b72005-08-12 22:56:09 +0000638 Expr *pExpr, /* Test this expression */
dan937d0de2009-10-15 18:35:38 +0000639 Expr **ppPrefix, /* Pointer to TK_STRING expression with pattern prefix */
drh9f504ea2008-02-23 21:55:39 +0000640 int *pisComplete, /* True if the only wildcard is % in the last character */
641 int *pnoCase /* True if uppercase is equivalent to lowercase */
drhd2687b72005-08-12 22:56:09 +0000642){
dan937d0de2009-10-15 18:35:38 +0000643 const char *z = 0; /* String on RHS of LIKE operator */
drh5bd98ae2009-01-07 18:24:03 +0000644 Expr *pRight, *pLeft; /* Right and left size of LIKE operator */
645 ExprList *pList; /* List of operands to the LIKE operator */
646 int c; /* One character in z[] */
647 int cnt; /* Number of non-wildcard prefix characters */
648 char wc[3]; /* Wildcard characters */
drh5bd98ae2009-01-07 18:24:03 +0000649 sqlite3 *db = pParse->db; /* Database connection */
dan937d0de2009-10-15 18:35:38 +0000650 sqlite3_value *pVal = 0;
651 int op; /* Opcode of pRight */
drhd64fe2f2005-08-28 17:00:23 +0000652
drh9f504ea2008-02-23 21:55:39 +0000653 if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
drhd2687b72005-08-12 22:56:09 +0000654 return 0;
655 }
drh9f504ea2008-02-23 21:55:39 +0000656#ifdef SQLITE_EBCDIC
657 if( *pnoCase ) return 0;
658#endif
danielk19776ab3a2e2009-02-19 14:39:25 +0000659 pList = pExpr->x.pList;
drh55ef4d92005-08-14 01:20:37 +0000660 pLeft = pList->a[1].pExpr;
danc68939e2012-03-29 14:29:07 +0000661 if( pLeft->op!=TK_COLUMN
662 || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
drhf07cf6e2015-03-06 16:45:16 +0000663 || IsVirtual(pLeft->pTab) /* Value might be numeric */
danc68939e2012-03-29 14:29:07 +0000664 ){
drhd91ca492009-10-22 20:50:36 +0000665 /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
666 ** be the name of an indexed column with TEXT affinity. */
drhd2687b72005-08-12 22:56:09 +0000667 return 0;
668 }
drhd91ca492009-10-22 20:50:36 +0000669 assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
dan937d0de2009-10-15 18:35:38 +0000670
drh6ade4532014-01-16 15:31:41 +0000671 pRight = sqlite3ExprSkipCollate(pList->a[0].pExpr);
dan937d0de2009-10-15 18:35:38 +0000672 op = pRight->op;
dan937d0de2009-10-15 18:35:38 +0000673 if( op==TK_VARIABLE ){
674 Vdbe *pReprepare = pParse->pReprepare;
drha7044002010-09-14 18:22:59 +0000675 int iCol = pRight->iColumn;
drhcf0fd4a2013-08-01 12:21:58 +0000676 pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_NONE);
dan937d0de2009-10-15 18:35:38 +0000677 if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
678 z = (char *)sqlite3_value_text(pVal);
679 }
drhf9b22ca2011-10-21 16:47:31 +0000680 sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
dan937d0de2009-10-15 18:35:38 +0000681 assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
682 }else if( op==TK_STRING ){
683 z = pRight->u.zToken;
684 }
685 if( z ){
shane85095702009-06-15 16:27:08 +0000686 cnt = 0;
drhb7916a72009-05-27 10:31:29 +0000687 while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
drh24fb6272009-05-01 21:13:36 +0000688 cnt++;
689 }
drh93ee23c2010-07-22 12:33:57 +0000690 if( cnt!=0 && 255!=(u8)z[cnt-1] ){
dan937d0de2009-10-15 18:35:38 +0000691 Expr *pPrefix;
drh93ee23c2010-07-22 12:33:57 +0000692 *pisComplete = c==wc[0] && z[cnt+1]==0;
dan937d0de2009-10-15 18:35:38 +0000693 pPrefix = sqlite3Expr(db, TK_STRING, z);
694 if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
695 *ppPrefix = pPrefix;
696 if( op==TK_VARIABLE ){
697 Vdbe *v = pParse->pVdbe;
drhf9b22ca2011-10-21 16:47:31 +0000698 sqlite3VdbeSetVarmask(v, pRight->iColumn);
dan937d0de2009-10-15 18:35:38 +0000699 if( *pisComplete && pRight->u.zToken[1] ){
700 /* If the rhs of the LIKE expression is a variable, and the current
701 ** value of the variable means there is no need to invoke the LIKE
702 ** function, then no OP_Variable will be added to the program.
703 ** This causes problems for the sqlite3_bind_parameter_name()
peter.d.reid60ec9142014-09-06 16:39:46 +0000704 ** API. To work around them, add a dummy OP_Variable here.
drhbec451f2009-10-17 13:13:02 +0000705 */
706 int r1 = sqlite3GetTempReg(pParse);
707 sqlite3ExprCodeTarget(pParse, pRight, r1);
dan937d0de2009-10-15 18:35:38 +0000708 sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
drhbec451f2009-10-17 13:13:02 +0000709 sqlite3ReleaseTempReg(pParse, r1);
dan937d0de2009-10-15 18:35:38 +0000710 }
711 }
712 }else{
713 z = 0;
shane85095702009-06-15 16:27:08 +0000714 }
drhf998b732007-11-26 13:36:00 +0000715 }
dan937d0de2009-10-15 18:35:38 +0000716
717 sqlite3ValueFree(pVal);
718 return (z!=0);
drhd2687b72005-08-12 22:56:09 +0000719}
720#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
721
drhedb193b2006-06-27 13:20:21 +0000722
723#ifndef SQLITE_OMIT_VIRTUALTABLE
drhfe05af82005-07-21 03:14:59 +0000724/*
drh7f375902006-06-13 17:38:59 +0000725** Check to see if the given expression is of the form
726**
727** column MATCH expr
728**
729** If it is then return TRUE. If not, return FALSE.
730*/
731static int isMatchOfColumn(
732 Expr *pExpr /* Test this expression */
733){
734 ExprList *pList;
735
736 if( pExpr->op!=TK_FUNCTION ){
737 return 0;
738 }
drh33e619f2009-05-28 01:00:55 +0000739 if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
drh7f375902006-06-13 17:38:59 +0000740 return 0;
741 }
danielk19776ab3a2e2009-02-19 14:39:25 +0000742 pList = pExpr->x.pList;
drh7f375902006-06-13 17:38:59 +0000743 if( pList->nExpr!=2 ){
744 return 0;
745 }
746 if( pList->a[1].pExpr->op != TK_COLUMN ){
747 return 0;
748 }
749 return 1;
750}
drhedb193b2006-06-27 13:20:21 +0000751#endif /* SQLITE_OMIT_VIRTUALTABLE */
drh7f375902006-06-13 17:38:59 +0000752
753/*
drh54a167d2005-11-26 14:08:07 +0000754** If the pBase expression originated in the ON or USING clause of
755** a join, then transfer the appropriate markings over to derived.
756*/
757static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
drhd41d39f2013-08-28 16:27:01 +0000758 if( pDerived ){
759 pDerived->flags |= pBase->flags & EP_FromJoin;
760 pDerived->iRightJoinTable = pBase->iRightJoinTable;
761 }
drh54a167d2005-11-26 14:08:07 +0000762}
763
drh9769efc2014-10-24 14:32:21 +0000764/*
765** Mark term iChild as being a child of term iParent
766*/
767static void markTermAsChild(WhereClause *pWC, int iChild, int iParent){
768 pWC->a[iChild].iParent = iParent;
769 pWC->a[iChild].truthProb = pWC->a[iParent].truthProb;
770 pWC->a[iParent].nChild++;
771}
772
drh3e355802007-02-23 23:13:33 +0000773#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
774/*
drh1a58fe02008-12-20 02:06:13 +0000775** Analyze a term that consists of two or more OR-connected
776** subterms. So in:
drh3e355802007-02-23 23:13:33 +0000777**
drh1a58fe02008-12-20 02:06:13 +0000778** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
779** ^^^^^^^^^^^^^^^^^^^^
drh3e355802007-02-23 23:13:33 +0000780**
drh1a58fe02008-12-20 02:06:13 +0000781** This routine analyzes terms such as the middle term in the above example.
782** A WhereOrTerm object is computed and attached to the term under
783** analysis, regardless of the outcome of the analysis. Hence:
drh3e355802007-02-23 23:13:33 +0000784**
drh1a58fe02008-12-20 02:06:13 +0000785** WhereTerm.wtFlags |= TERM_ORINFO
786** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object
drh3e355802007-02-23 23:13:33 +0000787**
drh1a58fe02008-12-20 02:06:13 +0000788** The term being analyzed must have two or more of OR-connected subterms.
danielk1977fdc40192008-12-29 18:33:32 +0000789** A single subterm might be a set of AND-connected sub-subterms.
drh1a58fe02008-12-20 02:06:13 +0000790** Examples of terms under analysis:
drh3e355802007-02-23 23:13:33 +0000791**
drh1a58fe02008-12-20 02:06:13 +0000792** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
793** (B) x=expr1 OR expr2=x OR x=expr3
794** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
795** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
796** (E) (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
drh3e355802007-02-23 23:13:33 +0000797**
drh1a58fe02008-12-20 02:06:13 +0000798** CASE 1:
799**
drhc3e552f2013-02-08 16:04:19 +0000800** If all subterms are of the form T.C=expr for some single column of C and
drh1a58fe02008-12-20 02:06:13 +0000801** a single table T (as shown in example B above) then create a new virtual
802** term that is an equivalent IN expression. In other words, if the term
803** being analyzed is:
804**
805** x = expr1 OR expr2 = x OR x = expr3
806**
807** then create a new virtual term like this:
808**
809** x IN (expr1,expr2,expr3)
810**
811** CASE 2:
812**
813** If all subterms are indexable by a single table T, then set
814**
815** WhereTerm.eOperator = WO_OR
816** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T
817**
818** A subterm is "indexable" if it is of the form
819** "T.C <op> <expr>" where C is any column of table T and
820** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
821** A subterm is also indexable if it is an AND of two or more
822** subsubterms at least one of which is indexable. Indexable AND
823** subterms have their eOperator set to WO_AND and they have
824** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
825**
826** From another point of view, "indexable" means that the subterm could
827** potentially be used with an index if an appropriate index exists.
828** This analysis does not consider whether or not the index exists; that
drh4a6fc352013-08-07 01:18:38 +0000829** is decided elsewhere. This analysis only looks at whether subterms
830** appropriate for indexing exist.
drh1a58fe02008-12-20 02:06:13 +0000831**
drh4a6fc352013-08-07 01:18:38 +0000832** All examples A through E above satisfy case 2. But if a term
peter.d.reid60ec9142014-09-06 16:39:46 +0000833** also satisfies case 1 (such as B) we know that the optimizer will
drh1a58fe02008-12-20 02:06:13 +0000834** always prefer case 1, so in that case we pretend that case 2 is not
835** satisfied.
836**
837** It might be the case that multiple tables are indexable. For example,
838** (E) above is indexable on tables P, Q, and R.
839**
840** Terms that satisfy case 2 are candidates for lookup by using
841** separate indices to find rowids for each subterm and composing
842** the union of all rowids using a RowSet object. This is similar
843** to "bitmap indices" in other database engines.
844**
845** OTHERWISE:
846**
847** If neither case 1 nor case 2 apply, then leave the eOperator set to
848** zero. This term is not useful for search.
drh3e355802007-02-23 23:13:33 +0000849*/
drh1a58fe02008-12-20 02:06:13 +0000850static void exprAnalyzeOrTerm(
851 SrcList *pSrc, /* the FROM clause */
852 WhereClause *pWC, /* the complete WHERE clause */
853 int idxTerm /* Index of the OR-term to be analyzed */
854){
drh70d18342013-06-06 19:16:33 +0000855 WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
856 Parse *pParse = pWInfo->pParse; /* Parser context */
drh1a58fe02008-12-20 02:06:13 +0000857 sqlite3 *db = pParse->db; /* Database connection */
858 WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */
859 Expr *pExpr = pTerm->pExpr; /* The expression of the term */
drh1a58fe02008-12-20 02:06:13 +0000860 int i; /* Loop counters */
861 WhereClause *pOrWc; /* Breakup of pTerm into subterms */
862 WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */
863 WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */
864 Bitmask chngToIN; /* Tables that might satisfy case 1 */
865 Bitmask indexable; /* Tables that are indexable, satisfying case 2 */
drh3e355802007-02-23 23:13:33 +0000866
drh1a58fe02008-12-20 02:06:13 +0000867 /*
868 ** Break the OR clause into its separate subterms. The subterms are
869 ** stored in a WhereClause structure containing within the WhereOrInfo
870 ** object that is attached to the original OR clause term.
871 */
872 assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
873 assert( pExpr->op==TK_OR );
drh954701a2008-12-29 23:45:07 +0000874 pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
drh1a58fe02008-12-20 02:06:13 +0000875 if( pOrInfo==0 ) return;
876 pTerm->wtFlags |= TERM_ORINFO;
877 pOrWc = &pOrInfo->wc;
drh70d18342013-06-06 19:16:33 +0000878 whereClauseInit(pOrWc, pWInfo);
drh1a58fe02008-12-20 02:06:13 +0000879 whereSplit(pOrWc, pExpr, TK_OR);
880 exprAnalyzeAll(pSrc, pOrWc);
881 if( db->mallocFailed ) return;
882 assert( pOrWc->nTerm>=2 );
883
884 /*
885 ** Compute the set of tables that might satisfy cases 1 or 2.
886 */
danielk1977e672c8e2009-05-22 15:43:26 +0000887 indexable = ~(Bitmask)0;
drhc3e552f2013-02-08 16:04:19 +0000888 chngToIN = ~(Bitmask)0;
drh1a58fe02008-12-20 02:06:13 +0000889 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
890 if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
drh29435252008-12-28 18:35:08 +0000891 WhereAndInfo *pAndInfo;
drh29435252008-12-28 18:35:08 +0000892 assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
drh1a58fe02008-12-20 02:06:13 +0000893 chngToIN = 0;
drh29435252008-12-28 18:35:08 +0000894 pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
895 if( pAndInfo ){
896 WhereClause *pAndWC;
897 WhereTerm *pAndTerm;
898 int j;
899 Bitmask b = 0;
900 pOrTerm->u.pAndInfo = pAndInfo;
901 pOrTerm->wtFlags |= TERM_ANDINFO;
902 pOrTerm->eOperator = WO_AND;
903 pAndWC = &pAndInfo->wc;
drh70d18342013-06-06 19:16:33 +0000904 whereClauseInit(pAndWC, pWC->pWInfo);
drh29435252008-12-28 18:35:08 +0000905 whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
906 exprAnalyzeAll(pSrc, pAndWC);
drh8871ef52011-10-07 13:33:10 +0000907 pAndWC->pOuter = pWC;
drh7c2fbde2009-01-07 20:58:57 +0000908 testcase( db->mallocFailed );
drh96c7a7d2009-01-10 15:34:12 +0000909 if( !db->mallocFailed ){
910 for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
911 assert( pAndTerm->pExpr );
912 if( allowedOp(pAndTerm->pExpr->op) ){
drh70d18342013-06-06 19:16:33 +0000913 b |= getMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
drh96c7a7d2009-01-10 15:34:12 +0000914 }
drh29435252008-12-28 18:35:08 +0000915 }
916 }
917 indexable &= b;
918 }
drh1a58fe02008-12-20 02:06:13 +0000919 }else if( pOrTerm->wtFlags & TERM_COPIED ){
920 /* Skip this term for now. We revisit it when we process the
921 ** corresponding TERM_VIRTUAL term */
922 }else{
923 Bitmask b;
drh70d18342013-06-06 19:16:33 +0000924 b = getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
drh1a58fe02008-12-20 02:06:13 +0000925 if( pOrTerm->wtFlags & TERM_VIRTUAL ){
926 WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
drh70d18342013-06-06 19:16:33 +0000927 b |= getMask(&pWInfo->sMaskSet, pOther->leftCursor);
drh1a58fe02008-12-20 02:06:13 +0000928 }
929 indexable &= b;
drh7a5bcc02013-01-16 17:08:58 +0000930 if( (pOrTerm->eOperator & WO_EQ)==0 ){
drh1a58fe02008-12-20 02:06:13 +0000931 chngToIN = 0;
932 }else{
933 chngToIN &= b;
934 }
935 }
drh3e355802007-02-23 23:13:33 +0000936 }
drh1a58fe02008-12-20 02:06:13 +0000937
938 /*
939 ** Record the set of tables that satisfy case 2. The set might be
drh111a6a72008-12-21 03:51:16 +0000940 ** empty.
drh1a58fe02008-12-20 02:06:13 +0000941 */
942 pOrInfo->indexable = indexable;
drh111a6a72008-12-21 03:51:16 +0000943 pTerm->eOperator = indexable==0 ? 0 : WO_OR;
drh1a58fe02008-12-20 02:06:13 +0000944
945 /*
946 ** chngToIN holds a set of tables that *might* satisfy case 1. But
947 ** we have to do some additional checking to see if case 1 really
948 ** is satisfied.
drh4e8be3b2009-06-08 17:11:08 +0000949 **
950 ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means
951 ** that there is no possibility of transforming the OR clause into an
952 ** IN operator because one or more terms in the OR clause contain
953 ** something other than == on a column in the single table. The 1-bit
954 ** case means that every term of the OR clause is of the form
955 ** "table.column=expr" for some single table. The one bit that is set
956 ** will correspond to the common table. We still need to check to make
957 ** sure the same column is used on all terms. The 2-bit case is when
958 ** the all terms are of the form "table1.column=table2.column". It
959 ** might be possible to form an IN operator with either table1.column
960 ** or table2.column as the LHS if either is common to every term of
961 ** the OR clause.
962 **
963 ** Note that terms of the form "table.column1=table.column2" (the
964 ** same table on both sizes of the ==) cannot be optimized.
drh1a58fe02008-12-20 02:06:13 +0000965 */
966 if( chngToIN ){
967 int okToChngToIN = 0; /* True if the conversion to IN is valid */
968 int iColumn = -1; /* Column index on lhs of IN operator */
shane63207ab2009-02-04 01:49:30 +0000969 int iCursor = -1; /* Table cursor common to all terms */
drh1a58fe02008-12-20 02:06:13 +0000970 int j = 0; /* Loop counter */
971
972 /* Search for a table and column that appears on one side or the
973 ** other of the == operator in every subterm. That table and column
974 ** will be recorded in iCursor and iColumn. There might not be any
975 ** such table and column. Set okToChngToIN if an appropriate table
976 ** and column is found but leave okToChngToIN false if not found.
977 */
978 for(j=0; j<2 && !okToChngToIN; j++){
979 pOrTerm = pOrWc->a;
980 for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
drh7a5bcc02013-01-16 17:08:58 +0000981 assert( pOrTerm->eOperator & WO_EQ );
drh1a58fe02008-12-20 02:06:13 +0000982 pOrTerm->wtFlags &= ~TERM_OR_OK;
drh4e8be3b2009-06-08 17:11:08 +0000983 if( pOrTerm->leftCursor==iCursor ){
984 /* This is the 2-bit case and we are on the second iteration and
985 ** current term is from the first iteration. So skip this term. */
986 assert( j==1 );
987 continue;
988 }
drh70d18342013-06-06 19:16:33 +0000989 if( (chngToIN & getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor))==0 ){
drh4e8be3b2009-06-08 17:11:08 +0000990 /* This term must be of the form t1.a==t2.b where t2 is in the
peter.d.reid60ec9142014-09-06 16:39:46 +0000991 ** chngToIN set but t1 is not. This term will be either preceded
drh4e8be3b2009-06-08 17:11:08 +0000992 ** or follwed by an inverted copy (t2.b==t1.a). Skip this term
993 ** and use its inversion. */
994 testcase( pOrTerm->wtFlags & TERM_COPIED );
995 testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
996 assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
997 continue;
998 }
drh1a58fe02008-12-20 02:06:13 +0000999 iColumn = pOrTerm->u.leftColumn;
1000 iCursor = pOrTerm->leftCursor;
1001 break;
1002 }
1003 if( i<0 ){
drh4e8be3b2009-06-08 17:11:08 +00001004 /* No candidate table+column was found. This can only occur
1005 ** on the second iteration */
drh1a58fe02008-12-20 02:06:13 +00001006 assert( j==1 );
drh7a5bcc02013-01-16 17:08:58 +00001007 assert( IsPowerOfTwo(chngToIN) );
drh70d18342013-06-06 19:16:33 +00001008 assert( chngToIN==getMask(&pWInfo->sMaskSet, iCursor) );
drh1a58fe02008-12-20 02:06:13 +00001009 break;
1010 }
drh4e8be3b2009-06-08 17:11:08 +00001011 testcase( j==1 );
1012
1013 /* We have found a candidate table and column. Check to see if that
1014 ** table and column is common to every term in the OR clause */
drh1a58fe02008-12-20 02:06:13 +00001015 okToChngToIN = 1;
1016 for(; i>=0 && okToChngToIN; i--, pOrTerm++){
drh7a5bcc02013-01-16 17:08:58 +00001017 assert( pOrTerm->eOperator & WO_EQ );
drh1a58fe02008-12-20 02:06:13 +00001018 if( pOrTerm->leftCursor!=iCursor ){
1019 pOrTerm->wtFlags &= ~TERM_OR_OK;
1020 }else if( pOrTerm->u.leftColumn!=iColumn ){
1021 okToChngToIN = 0;
1022 }else{
1023 int affLeft, affRight;
1024 /* If the right-hand side is also a column, then the affinities
1025 ** of both right and left sides must be such that no type
1026 ** conversions are required on the right. (Ticket #2249)
1027 */
1028 affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
1029 affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
1030 if( affRight!=0 && affRight!=affLeft ){
1031 okToChngToIN = 0;
1032 }else{
1033 pOrTerm->wtFlags |= TERM_OR_OK;
1034 }
1035 }
1036 }
1037 }
1038
1039 /* At this point, okToChngToIN is true if original pTerm satisfies
1040 ** case 1. In that case, construct a new virtual term that is
1041 ** pTerm converted into an IN operator.
1042 */
1043 if( okToChngToIN ){
1044 Expr *pDup; /* A transient duplicate expression */
1045 ExprList *pList = 0; /* The RHS of the IN operator */
1046 Expr *pLeft = 0; /* The LHS of the IN operator */
1047 Expr *pNew; /* The complete IN operator */
1048
1049 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
1050 if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
drh7a5bcc02013-01-16 17:08:58 +00001051 assert( pOrTerm->eOperator & WO_EQ );
drh1a58fe02008-12-20 02:06:13 +00001052 assert( pOrTerm->leftCursor==iCursor );
1053 assert( pOrTerm->u.leftColumn==iColumn );
danielk19776ab3a2e2009-02-19 14:39:25 +00001054 pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
drh70d18342013-06-06 19:16:33 +00001055 pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
drh1a58fe02008-12-20 02:06:13 +00001056 pLeft = pOrTerm->pExpr->pLeft;
1057 }
1058 assert( pLeft!=0 );
danielk19776ab3a2e2009-02-19 14:39:25 +00001059 pDup = sqlite3ExprDup(db, pLeft, 0);
drhb7916a72009-05-27 10:31:29 +00001060 pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
drh1a58fe02008-12-20 02:06:13 +00001061 if( pNew ){
1062 int idxNew;
1063 transferJoinMarkings(pNew, pExpr);
danielk19776ab3a2e2009-02-19 14:39:25 +00001064 assert( !ExprHasProperty(pNew, EP_xIsSelect) );
1065 pNew->x.pList = pList;
drh1a58fe02008-12-20 02:06:13 +00001066 idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
1067 testcase( idxNew==0 );
1068 exprAnalyze(pSrc, pWC, idxNew);
1069 pTerm = &pWC->a[idxTerm];
drh9769efc2014-10-24 14:32:21 +00001070 markTermAsChild(pWC, idxNew, idxTerm);
drh1a58fe02008-12-20 02:06:13 +00001071 }else{
1072 sqlite3ExprListDelete(db, pList);
1073 }
drh534230c2011-01-22 00:10:45 +00001074 pTerm->eOperator = WO_NOOP; /* case 1 trumps case 2 */
drh1a58fe02008-12-20 02:06:13 +00001075 }
drh3e355802007-02-23 23:13:33 +00001076 }
drh3e355802007-02-23 23:13:33 +00001077}
1078#endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
drh54a167d2005-11-26 14:08:07 +00001079
drh7a5bcc02013-01-16 17:08:58 +00001080/*
drh0aa74ed2005-07-16 13:33:20 +00001081** The input to this routine is an WhereTerm structure with only the
drh51147ba2005-07-23 22:59:55 +00001082** "pExpr" field filled in. The job of this routine is to analyze the
drh0aa74ed2005-07-16 13:33:20 +00001083** subexpression and populate all the other fields of the WhereTerm
drh75897232000-05-29 14:26:00 +00001084** structure.
drh51147ba2005-07-23 22:59:55 +00001085**
1086** If the expression is of the form "<expr> <op> X" it gets commuted
drh1a58fe02008-12-20 02:06:13 +00001087** to the standard form of "X <op> <expr>".
1088**
1089** If the expression is of the form "X <op> Y" where both X and Y are
1090** columns, then the original expression is unchanged and a new virtual
1091** term of the form "Y <op> X" is added to the WHERE clause and
1092** analyzed separately. The original term is marked with TERM_COPIED
1093** and the new term is marked with TERM_DYNAMIC (because it's pExpr
1094** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
1095** is a commuted copy of a prior term.) The original term has nChild=1
1096** and the copy has idxParent set to the index of the original term.
drh75897232000-05-29 14:26:00 +00001097*/
drh0fcef5e2005-07-19 17:38:22 +00001098static void exprAnalyze(
1099 SrcList *pSrc, /* the FROM clause */
drh9eb20282005-08-24 03:52:18 +00001100 WhereClause *pWC, /* the WHERE clause */
1101 int idxTerm /* Index of the term to be analyzed */
drh0fcef5e2005-07-19 17:38:22 +00001102){
drh70d18342013-06-06 19:16:33 +00001103 WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
drh1a58fe02008-12-20 02:06:13 +00001104 WhereTerm *pTerm; /* The term to be analyzed */
drh111a6a72008-12-21 03:51:16 +00001105 WhereMaskSet *pMaskSet; /* Set of table index masks */
drh1a58fe02008-12-20 02:06:13 +00001106 Expr *pExpr; /* The expression to be analyzed */
1107 Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */
1108 Bitmask prereqAll; /* Prerequesites of pExpr */
drh5e767c52010-02-25 04:15:47 +00001109 Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */
drh1d452e12009-11-01 19:26:59 +00001110 Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */
1111 int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */
drha9c18a92015-03-06 20:49:52 +00001112 int noCase = 0; /* uppercase equivalent to lowercase */
drh1a58fe02008-12-20 02:06:13 +00001113 int op; /* Top-level operator. pExpr->op */
drh70d18342013-06-06 19:16:33 +00001114 Parse *pParse = pWInfo->pParse; /* Parsing context */
drh1a58fe02008-12-20 02:06:13 +00001115 sqlite3 *db = pParse->db; /* Database connection */
drh0fcef5e2005-07-19 17:38:22 +00001116
drhf998b732007-11-26 13:36:00 +00001117 if( db->mallocFailed ){
1118 return;
1119 }
1120 pTerm = &pWC->a[idxTerm];
drh70d18342013-06-06 19:16:33 +00001121 pMaskSet = &pWInfo->sMaskSet;
drh7ee751d2012-12-19 15:53:51 +00001122 pExpr = pTerm->pExpr;
1123 assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
drh0fcef5e2005-07-19 17:38:22 +00001124 prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
drh50b39962006-10-28 00:28:09 +00001125 op = pExpr->op;
1126 if( op==TK_IN ){
drhf5b11382005-09-17 13:07:13 +00001127 assert( pExpr->pRight==0 );
danielk19776ab3a2e2009-02-19 14:39:25 +00001128 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
1129 pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
1130 }else{
1131 pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
1132 }
drh50b39962006-10-28 00:28:09 +00001133 }else if( op==TK_ISNULL ){
1134 pTerm->prereqRight = 0;
drhf5b11382005-09-17 13:07:13 +00001135 }else{
1136 pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
1137 }
drh22d6a532005-09-19 21:05:48 +00001138 prereqAll = exprTableUsage(pMaskSet, pExpr);
1139 if( ExprHasProperty(pExpr, EP_FromJoin) ){
drh42165be2008-03-26 14:56:34 +00001140 Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
1141 prereqAll |= x;
drhdafc0ce2008-04-17 19:14:02 +00001142 extraRight = x-1; /* ON clause terms may not be used with an index
1143 ** on left table of a LEFT JOIN. Ticket #3015 */
drh22d6a532005-09-19 21:05:48 +00001144 }
1145 pTerm->prereqAll = prereqAll;
drh0fcef5e2005-07-19 17:38:22 +00001146 pTerm->leftCursor = -1;
drh45b1ee42005-08-02 17:48:22 +00001147 pTerm->iParent = -1;
drhb52076c2006-01-23 13:22:09 +00001148 pTerm->eOperator = 0;
drh738fc792013-01-17 15:05:17 +00001149 if( allowedOp(op) ){
drh7a66da12012-12-07 20:31:11 +00001150 Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
1151 Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
drh738fc792013-01-17 15:05:17 +00001152 u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
drh0fcef5e2005-07-19 17:38:22 +00001153 if( pLeft->op==TK_COLUMN ){
1154 pTerm->leftCursor = pLeft->iTable;
drh700a2262008-12-17 19:22:15 +00001155 pTerm->u.leftColumn = pLeft->iColumn;
drh738fc792013-01-17 15:05:17 +00001156 pTerm->eOperator = operatorMask(op) & opMask;
drh75897232000-05-29 14:26:00 +00001157 }
drh0fcef5e2005-07-19 17:38:22 +00001158 if( pRight && pRight->op==TK_COLUMN ){
1159 WhereTerm *pNew;
1160 Expr *pDup;
drh7a5bcc02013-01-16 17:08:58 +00001161 u16 eExtraOp = 0; /* Extra bits for pNew->eOperator */
drh0fcef5e2005-07-19 17:38:22 +00001162 if( pTerm->leftCursor>=0 ){
drh9eb20282005-08-24 03:52:18 +00001163 int idxNew;
danielk19776ab3a2e2009-02-19 14:39:25 +00001164 pDup = sqlite3ExprDup(db, pExpr, 0);
drh17435752007-08-16 04:30:38 +00001165 if( db->mallocFailed ){
drh633e6d52008-07-28 19:34:53 +00001166 sqlite3ExprDelete(db, pDup);
drh28f45912006-10-18 23:26:38 +00001167 return;
1168 }
drh9eb20282005-08-24 03:52:18 +00001169 idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
1170 if( idxNew==0 ) return;
1171 pNew = &pWC->a[idxNew];
drh9769efc2014-10-24 14:32:21 +00001172 markTermAsChild(pWC, idxNew, idxTerm);
drh9eb20282005-08-24 03:52:18 +00001173 pTerm = &pWC->a[idxTerm];
drh165be382008-12-05 02:36:33 +00001174 pTerm->wtFlags |= TERM_COPIED;
drheb5bc922013-01-17 16:43:33 +00001175 if( pExpr->op==TK_EQ
1176 && !ExprHasProperty(pExpr, EP_FromJoin)
1177 && OptimizationEnabled(db, SQLITE_Transitive)
1178 ){
drh7a5bcc02013-01-16 17:08:58 +00001179 pTerm->eOperator |= WO_EQUIV;
1180 eExtraOp = WO_EQUIV;
1181 }
drh0fcef5e2005-07-19 17:38:22 +00001182 }else{
1183 pDup = pExpr;
1184 pNew = pTerm;
1185 }
drh7d10d5a2008-08-20 16:35:10 +00001186 exprCommute(pParse, pDup);
drhfb76f5a2012-12-08 14:16:47 +00001187 pLeft = sqlite3ExprSkipCollate(pDup->pLeft);
drh0fcef5e2005-07-19 17:38:22 +00001188 pNew->leftCursor = pLeft->iTable;
drh700a2262008-12-17 19:22:15 +00001189 pNew->u.leftColumn = pLeft->iColumn;
drh5e767c52010-02-25 04:15:47 +00001190 testcase( (prereqLeft | extraRight) != prereqLeft );
1191 pNew->prereqRight = prereqLeft | extraRight;
drh0fcef5e2005-07-19 17:38:22 +00001192 pNew->prereqAll = prereqAll;
drh738fc792013-01-17 15:05:17 +00001193 pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
drh75897232000-05-29 14:26:00 +00001194 }
1195 }
drhed378002005-07-28 23:12:08 +00001196
drhd2687b72005-08-12 22:56:09 +00001197#ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
drhed378002005-07-28 23:12:08 +00001198 /* If a term is the BETWEEN operator, create two new virtual terms
drh1a58fe02008-12-20 02:06:13 +00001199 ** that define the range that the BETWEEN implements. For example:
1200 **
1201 ** a BETWEEN b AND c
1202 **
1203 ** is converted into:
1204 **
1205 ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
1206 **
1207 ** The two new terms are added onto the end of the WhereClause object.
1208 ** The new terms are "dynamic" and are children of the original BETWEEN
1209 ** term. That means that if the BETWEEN term is coded, the children are
1210 ** skipped. Or, if the children are satisfied by an index, the original
1211 ** BETWEEN term is skipped.
drhed378002005-07-28 23:12:08 +00001212 */
drh29435252008-12-28 18:35:08 +00001213 else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
danielk19776ab3a2e2009-02-19 14:39:25 +00001214 ExprList *pList = pExpr->x.pList;
drhed378002005-07-28 23:12:08 +00001215 int i;
1216 static const u8 ops[] = {TK_GE, TK_LE};
1217 assert( pList!=0 );
1218 assert( pList->nExpr==2 );
1219 for(i=0; i<2; i++){
1220 Expr *pNewExpr;
drh9eb20282005-08-24 03:52:18 +00001221 int idxNew;
drhb7916a72009-05-27 10:31:29 +00001222 pNewExpr = sqlite3PExpr(pParse, ops[i],
1223 sqlite3ExprDup(db, pExpr->pLeft, 0),
danielk19776ab3a2e2009-02-19 14:39:25 +00001224 sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
drhd41d39f2013-08-28 16:27:01 +00001225 transferJoinMarkings(pNewExpr, pExpr);
drh9eb20282005-08-24 03:52:18 +00001226 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
drh6a1e0712008-12-05 15:24:15 +00001227 testcase( idxNew==0 );
drh7b4fc6a2007-02-06 13:26:32 +00001228 exprAnalyze(pSrc, pWC, idxNew);
drh9eb20282005-08-24 03:52:18 +00001229 pTerm = &pWC->a[idxTerm];
drh9769efc2014-10-24 14:32:21 +00001230 markTermAsChild(pWC, idxNew, idxTerm);
drhed378002005-07-28 23:12:08 +00001231 }
drhed378002005-07-28 23:12:08 +00001232 }
drhd2687b72005-08-12 22:56:09 +00001233#endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
drhed378002005-07-28 23:12:08 +00001234
danielk19771576cd92006-01-14 08:02:28 +00001235#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
drh1a58fe02008-12-20 02:06:13 +00001236 /* Analyze a term that is composed of two or more subterms connected by
1237 ** an OR operator.
drh6c30be82005-07-29 15:10:17 +00001238 */
1239 else if( pExpr->op==TK_OR ){
drh29435252008-12-28 18:35:08 +00001240 assert( pWC->op==TK_AND );
drh1a58fe02008-12-20 02:06:13 +00001241 exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
danielk1977f51d1bd2009-07-31 06:14:51 +00001242 pTerm = &pWC->a[idxTerm];
drh6c30be82005-07-29 15:10:17 +00001243 }
drhd2687b72005-08-12 22:56:09 +00001244#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
1245
1246#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
1247 /* Add constraints to reduce the search space on a LIKE or GLOB
1248 ** operator.
drh9f504ea2008-02-23 21:55:39 +00001249 **
drha9c18a92015-03-06 20:49:52 +00001250 ** A like pattern of the form "x LIKE 'aBc%'" is changed into constraints
drh9f504ea2008-02-23 21:55:39 +00001251 **
drha9c18a92015-03-06 20:49:52 +00001252 ** x>='ABC' AND x<'abd' AND x LIKE 'aBc%'
drh9f504ea2008-02-23 21:55:39 +00001253 **
1254 ** The last character of the prefix "abc" is incremented to form the
drha9c18a92015-03-06 20:49:52 +00001255 ** termination condition "abd". If case is not significant (the default
1256 ** for LIKE) then the lower-bound is made all uppercase and the upper-
1257 ** bound is made all lowercase so that the bounds also work when comparing
1258 ** BLOBs.
drhd2687b72005-08-12 22:56:09 +00001259 */
dan937d0de2009-10-15 18:35:38 +00001260 if( pWC->op==TK_AND
1261 && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
1262 ){
drh1d452e12009-11-01 19:26:59 +00001263 Expr *pLeft; /* LHS of LIKE/GLOB operator */
1264 Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */
1265 Expr *pNewExpr1;
1266 Expr *pNewExpr2;
1267 int idxNew1;
1268 int idxNew2;
drhae80dde2012-12-06 21:16:43 +00001269 Token sCollSeqName; /* Name of collating sequence */
drh8f1a7ed2015-03-06 19:47:38 +00001270 const u16 wtFlags = TERM_LIKEOPT | TERM_VIRTUAL | TERM_DYNAMIC;
drh9eb20282005-08-24 03:52:18 +00001271
danielk19776ab3a2e2009-02-19 14:39:25 +00001272 pLeft = pExpr->x.pList->a[1].pExpr;
danielk19776ab3a2e2009-02-19 14:39:25 +00001273 pStr2 = sqlite3ExprDup(db, pStr1, 0);
drh8f1a7ed2015-03-06 19:47:38 +00001274
1275 /* Convert the lower bound to upper-case and the upper bound to
1276 ** lower-case (upper-case is less than lower-case in ASCII) so that
1277 ** the range constraints also work for BLOBs
1278 */
1279 if( noCase && !pParse->db->mallocFailed ){
1280 int i;
1281 char c;
drha9c18a92015-03-06 20:49:52 +00001282 pTerm->wtFlags |= TERM_LIKE;
drh8f1a7ed2015-03-06 19:47:38 +00001283 for(i=0; (c = pStr1->u.zToken[i])!=0; i++){
1284 pStr1->u.zToken[i] = sqlite3Toupper(c);
1285 pStr2->u.zToken[i] = sqlite3Tolower(c);
1286 }
1287 }
1288
drhf998b732007-11-26 13:36:00 +00001289 if( !db->mallocFailed ){
drh254993e2009-06-08 19:44:36 +00001290 u8 c, *pC; /* Last character before the first wildcard */
dan937d0de2009-10-15 18:35:38 +00001291 pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
drh9f504ea2008-02-23 21:55:39 +00001292 c = *pC;
drh02a50b72008-05-26 18:33:40 +00001293 if( noCase ){
drh254993e2009-06-08 19:44:36 +00001294 /* The point is to increment the last character before the first
1295 ** wildcard. But if we increment '@', that will push it into the
1296 ** alphabetic range where case conversions will mess up the
1297 ** inequality. To avoid this, make sure to also run the full
1298 ** LIKE on all candidate expressions by clearing the isComplete flag
1299 */
drh39759742013-08-02 23:40:45 +00001300 if( c=='A'-1 ) isComplete = 0;
drh02a50b72008-05-26 18:33:40 +00001301 c = sqlite3UpperToLower[c];
1302 }
drh9f504ea2008-02-23 21:55:39 +00001303 *pC = c + 1;
drhd2687b72005-08-12 22:56:09 +00001304 }
drhae80dde2012-12-06 21:16:43 +00001305 sCollSeqName.z = noCase ? "NOCASE" : "BINARY";
1306 sCollSeqName.n = 6;
1307 pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
drh8f1a7ed2015-03-06 19:47:38 +00001308 pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
drh0a8a4062012-12-07 18:38:16 +00001309 sqlite3ExprAddCollateToken(pParse,pNewExpr1,&sCollSeqName),
drhae80dde2012-12-06 21:16:43 +00001310 pStr1, 0);
drhd41d39f2013-08-28 16:27:01 +00001311 transferJoinMarkings(pNewExpr1, pExpr);
drh8f1a7ed2015-03-06 19:47:38 +00001312 idxNew1 = whereClauseInsert(pWC, pNewExpr1, wtFlags);
drh6a1e0712008-12-05 15:24:15 +00001313 testcase( idxNew1==0 );
drh7b4fc6a2007-02-06 13:26:32 +00001314 exprAnalyze(pSrc, pWC, idxNew1);
drhae80dde2012-12-06 21:16:43 +00001315 pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
drh8342e492010-07-22 17:49:52 +00001316 pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
drh0a8a4062012-12-07 18:38:16 +00001317 sqlite3ExprAddCollateToken(pParse,pNewExpr2,&sCollSeqName),
drhae80dde2012-12-06 21:16:43 +00001318 pStr2, 0);
drhd41d39f2013-08-28 16:27:01 +00001319 transferJoinMarkings(pNewExpr2, pExpr);
drh8f1a7ed2015-03-06 19:47:38 +00001320 idxNew2 = whereClauseInsert(pWC, pNewExpr2, wtFlags);
drh6a1e0712008-12-05 15:24:15 +00001321 testcase( idxNew2==0 );
drh7b4fc6a2007-02-06 13:26:32 +00001322 exprAnalyze(pSrc, pWC, idxNew2);
drh9eb20282005-08-24 03:52:18 +00001323 pTerm = &pWC->a[idxTerm];
drhd2687b72005-08-12 22:56:09 +00001324 if( isComplete ){
drh9769efc2014-10-24 14:32:21 +00001325 markTermAsChild(pWC, idxNew1, idxTerm);
1326 markTermAsChild(pWC, idxNew2, idxTerm);
drhd2687b72005-08-12 22:56:09 +00001327 }
1328 }
1329#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
drh7f375902006-06-13 17:38:59 +00001330
1331#ifndef SQLITE_OMIT_VIRTUALTABLE
1332 /* Add a WO_MATCH auxiliary term to the constraint set if the
1333 ** current expression is of the form: column MATCH expr.
1334 ** This information is used by the xBestIndex methods of
1335 ** virtual tables. The native query optimizer does not attempt
1336 ** to do anything with MATCH functions.
1337 */
1338 if( isMatchOfColumn(pExpr) ){
1339 int idxNew;
1340 Expr *pRight, *pLeft;
1341 WhereTerm *pNewTerm;
1342 Bitmask prereqColumn, prereqExpr;
1343
danielk19776ab3a2e2009-02-19 14:39:25 +00001344 pRight = pExpr->x.pList->a[0].pExpr;
1345 pLeft = pExpr->x.pList->a[1].pExpr;
drh7f375902006-06-13 17:38:59 +00001346 prereqExpr = exprTableUsage(pMaskSet, pRight);
1347 prereqColumn = exprTableUsage(pMaskSet, pLeft);
1348 if( (prereqExpr & prereqColumn)==0 ){
drh1a90e092006-06-14 22:07:10 +00001349 Expr *pNewExpr;
drhb7916a72009-05-27 10:31:29 +00001350 pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
1351 0, sqlite3ExprDup(db, pRight, 0), 0);
drh1a90e092006-06-14 22:07:10 +00001352 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
drh6a1e0712008-12-05 15:24:15 +00001353 testcase( idxNew==0 );
drh7f375902006-06-13 17:38:59 +00001354 pNewTerm = &pWC->a[idxNew];
1355 pNewTerm->prereqRight = prereqExpr;
1356 pNewTerm->leftCursor = pLeft->iTable;
drh700a2262008-12-17 19:22:15 +00001357 pNewTerm->u.leftColumn = pLeft->iColumn;
drh7f375902006-06-13 17:38:59 +00001358 pNewTerm->eOperator = WO_MATCH;
drh9769efc2014-10-24 14:32:21 +00001359 markTermAsChild(pWC, idxNew, idxTerm);
drhd2ca60d2006-06-27 02:36:58 +00001360 pTerm = &pWC->a[idxTerm];
drh165be382008-12-05 02:36:33 +00001361 pTerm->wtFlags |= TERM_COPIED;
drh7f375902006-06-13 17:38:59 +00001362 pNewTerm->prereqAll = pTerm->prereqAll;
1363 }
1364 }
1365#endif /* SQLITE_OMIT_VIRTUALTABLE */
drhdafc0ce2008-04-17 19:14:02 +00001366
drh1435a9a2013-08-27 23:15:44 +00001367#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drhd3ed7342011-09-21 00:09:41 +00001368 /* When sqlite_stat3 histogram data is available an operator of the
drh534230c2011-01-22 00:10:45 +00001369 ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
1370 ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a
1371 ** virtual term of that form.
1372 **
1373 ** Note that the virtual term must be tagged with TERM_VNULL. This
1374 ** TERM_VNULL tag will suppress the not-null check at the beginning
1375 ** of the loop. Without the TERM_VNULL flag, the not-null check at
1376 ** the start of the loop will prevent any results from being returned.
1377 */
drhea6dc442011-04-08 21:35:26 +00001378 if( pExpr->op==TK_NOTNULL
1379 && pExpr->pLeft->op==TK_COLUMN
1380 && pExpr->pLeft->iColumn>=0
drhd7d71472014-10-22 19:57:16 +00001381 && OptimizationEnabled(db, SQLITE_Stat34)
drhea6dc442011-04-08 21:35:26 +00001382 ){
drh534230c2011-01-22 00:10:45 +00001383 Expr *pNewExpr;
1384 Expr *pLeft = pExpr->pLeft;
1385 int idxNew;
1386 WhereTerm *pNewTerm;
1387
1388 pNewExpr = sqlite3PExpr(pParse, TK_GT,
1389 sqlite3ExprDup(db, pLeft, 0),
1390 sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
1391
1392 idxNew = whereClauseInsert(pWC, pNewExpr,
1393 TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
drhda91e712011-02-11 06:59:02 +00001394 if( idxNew ){
1395 pNewTerm = &pWC->a[idxNew];
1396 pNewTerm->prereqRight = 0;
1397 pNewTerm->leftCursor = pLeft->iTable;
1398 pNewTerm->u.leftColumn = pLeft->iColumn;
1399 pNewTerm->eOperator = WO_GT;
drh9769efc2014-10-24 14:32:21 +00001400 markTermAsChild(pWC, idxNew, idxTerm);
drhda91e712011-02-11 06:59:02 +00001401 pTerm = &pWC->a[idxTerm];
drhda91e712011-02-11 06:59:02 +00001402 pTerm->wtFlags |= TERM_COPIED;
1403 pNewTerm->prereqAll = pTerm->prereqAll;
1404 }
drh534230c2011-01-22 00:10:45 +00001405 }
drh1435a9a2013-08-27 23:15:44 +00001406#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
drh534230c2011-01-22 00:10:45 +00001407
drhdafc0ce2008-04-17 19:14:02 +00001408 /* Prevent ON clause terms of a LEFT JOIN from being used to drive
1409 ** an index for tables to the left of the join.
1410 */
1411 pTerm->prereqRight |= extraRight;
drh75897232000-05-29 14:26:00 +00001412}
1413
drh7b4fc6a2007-02-06 13:26:32 +00001414/*
peter.d.reid60ec9142014-09-06 16:39:46 +00001415** This function searches pList for an entry that matches the iCol-th column
drh3b48e8c2013-06-12 20:18:16 +00001416** of index pIdx.
dan6f343962011-07-01 18:26:40 +00001417**
1418** If such an expression is found, its index in pList->a[] is returned. If
1419** no expression is found, -1 is returned.
1420*/
1421static int findIndexCol(
1422 Parse *pParse, /* Parse context */
1423 ExprList *pList, /* Expression list to search */
1424 int iBase, /* Cursor for table associated with pIdx */
1425 Index *pIdx, /* Index to match column of */
1426 int iCol /* Column of index to match */
1427){
1428 int i;
1429 const char *zColl = pIdx->azColl[iCol];
1430
1431 for(i=0; i<pList->nExpr; i++){
drh580c8c12012-12-08 03:34:04 +00001432 Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
drhf1d3e322011-07-09 13:00:41 +00001433 if( p->op==TK_COLUMN
1434 && p->iColumn==pIdx->aiColumn[iCol]
1435 && p->iTable==iBase
1436 ){
drh580c8c12012-12-08 03:34:04 +00001437 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
drhf1d3e322011-07-09 13:00:41 +00001438 if( ALWAYS(pColl) && 0==sqlite3StrICmp(pColl->zName, zColl) ){
dan6f343962011-07-01 18:26:40 +00001439 return i;
1440 }
1441 }
1442 }
1443
1444 return -1;
1445}
1446
1447/*
dan6f343962011-07-01 18:26:40 +00001448** Return true if the DISTINCT expression-list passed as the third argument
drh4f402f22013-06-11 18:59:38 +00001449** is redundant.
1450**
drh3b48e8c2013-06-12 20:18:16 +00001451** A DISTINCT list is redundant if the database contains some subset of
drh4f402f22013-06-11 18:59:38 +00001452** columns that are unique and non-null.
dan6f343962011-07-01 18:26:40 +00001453*/
1454static int isDistinctRedundant(
drh4f402f22013-06-11 18:59:38 +00001455 Parse *pParse, /* Parsing context */
1456 SrcList *pTabList, /* The FROM clause */
1457 WhereClause *pWC, /* The WHERE clause */
1458 ExprList *pDistinct /* The result set that needs to be DISTINCT */
dan6f343962011-07-01 18:26:40 +00001459){
1460 Table *pTab;
1461 Index *pIdx;
1462 int i;
1463 int iBase;
1464
1465 /* If there is more than one table or sub-select in the FROM clause of
1466 ** this query, then it will not be possible to show that the DISTINCT
1467 ** clause is redundant. */
1468 if( pTabList->nSrc!=1 ) return 0;
1469 iBase = pTabList->a[0].iCursor;
1470 pTab = pTabList->a[0].pTab;
1471
dan94e08d92011-07-02 06:44:05 +00001472 /* If any of the expressions is an IPK column on table iBase, then return
1473 ** true. Note: The (p->iTable==iBase) part of this test may be false if the
1474 ** current SELECT is a correlated sub-query.
1475 */
dan6f343962011-07-01 18:26:40 +00001476 for(i=0; i<pDistinct->nExpr; i++){
drh580c8c12012-12-08 03:34:04 +00001477 Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
dan94e08d92011-07-02 06:44:05 +00001478 if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
dan6f343962011-07-01 18:26:40 +00001479 }
1480
1481 /* Loop through all indices on the table, checking each to see if it makes
1482 ** the DISTINCT qualifier redundant. It does so if:
1483 **
1484 ** 1. The index is itself UNIQUE, and
1485 **
1486 ** 2. All of the columns in the index are either part of the pDistinct
1487 ** list, or else the WHERE clause contains a term of the form "col=X",
1488 ** where X is a constant value. The collation sequences of the
1489 ** comparison and select-list expressions must match those of the index.
dan6a36f432012-04-20 16:59:24 +00001490 **
1491 ** 3. All of those index columns for which the WHERE clause does not
1492 ** contain a "col=X" term are subject to a NOT NULL constraint.
dan6f343962011-07-01 18:26:40 +00001493 */
1494 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
drh5f1d1d92014-07-31 22:59:04 +00001495 if( !IsUniqueIndex(pIdx) ) continue;
drhbbbdc832013-10-22 18:01:40 +00001496 for(i=0; i<pIdx->nKeyCol; i++){
1497 i16 iCol = pIdx->aiColumn[i];
dan6a36f432012-04-20 16:59:24 +00001498 if( 0==findTerm(pWC, iBase, iCol, ~(Bitmask)0, WO_EQ, pIdx) ){
1499 int iIdxCol = findIndexCol(pParse, pDistinct, iBase, pIdx, i);
drhbbbdc832013-10-22 18:01:40 +00001500 if( iIdxCol<0 || pTab->aCol[iCol].notNull==0 ){
dan6a36f432012-04-20 16:59:24 +00001501 break;
1502 }
dan6f343962011-07-01 18:26:40 +00001503 }
1504 }
drhbbbdc832013-10-22 18:01:40 +00001505 if( i==pIdx->nKeyCol ){
dan6f343962011-07-01 18:26:40 +00001506 /* This index implies that the DISTINCT qualifier is redundant. */
1507 return 1;
1508 }
1509 }
1510
1511 return 0;
1512}
drh0fcef5e2005-07-19 17:38:22 +00001513
drh8636e9c2013-06-11 01:50:08 +00001514
drh75897232000-05-29 14:26:00 +00001515/*
drh3b48e8c2013-06-12 20:18:16 +00001516** Estimate the logarithm of the input value to base 2.
drh28c4cf42005-07-27 20:41:43 +00001517*/
drhbf539c42013-10-05 18:16:02 +00001518static LogEst estLog(LogEst N){
drh696964d2014-06-12 15:46:46 +00001519 return N<=10 ? 0 : sqlite3LogEst(N) - 33;
drh28c4cf42005-07-27 20:41:43 +00001520}
1521
drh6d209d82006-06-27 01:54:26 +00001522/*
1523** Two routines for printing the content of an sqlite3_index_info
1524** structure. Used for testing and debugging only. If neither
1525** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
1526** are no-ops.
1527*/
drhd15cb172013-05-21 19:23:10 +00001528#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
drh6d209d82006-06-27 01:54:26 +00001529static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
1530 int i;
mlcreech3a00f902008-03-04 17:45:01 +00001531 if( !sqlite3WhereTrace ) return;
drh6d209d82006-06-27 01:54:26 +00001532 for(i=0; i<p->nConstraint; i++){
1533 sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
1534 i,
1535 p->aConstraint[i].iColumn,
1536 p->aConstraint[i].iTermOffset,
1537 p->aConstraint[i].op,
1538 p->aConstraint[i].usable);
1539 }
1540 for(i=0; i<p->nOrderBy; i++){
1541 sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n",
1542 i,
1543 p->aOrderBy[i].iColumn,
1544 p->aOrderBy[i].desc);
1545 }
1546}
1547static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
1548 int i;
mlcreech3a00f902008-03-04 17:45:01 +00001549 if( !sqlite3WhereTrace ) return;
drh6d209d82006-06-27 01:54:26 +00001550 for(i=0; i<p->nConstraint; i++){
1551 sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n",
1552 i,
1553 p->aConstraintUsage[i].argvIndex,
1554 p->aConstraintUsage[i].omit);
1555 }
1556 sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum);
1557 sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr);
1558 sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed);
1559 sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost);
dana9f58152013-11-11 19:01:33 +00001560 sqlite3DebugPrintf(" estimatedRows=%lld\n", p->estimatedRows);
drh6d209d82006-06-27 01:54:26 +00001561}
1562#else
1563#define TRACE_IDX_INPUTS(A)
1564#define TRACE_IDX_OUTPUTS(A)
1565#endif
1566
drhc6339082010-04-07 16:54:58 +00001567#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
drh8b307fb2010-04-06 15:57:05 +00001568/*
drh4139c992010-04-07 14:59:45 +00001569** Return TRUE if the WHERE clause term pTerm is of a form where it
1570** could be used with an index to access pSrc, assuming an appropriate
1571** index existed.
1572*/
1573static int termCanDriveIndex(
1574 WhereTerm *pTerm, /* WHERE clause term to check */
1575 struct SrcList_item *pSrc, /* Table we are trying to access */
1576 Bitmask notReady /* Tables in outer loops of the join */
1577){
1578 char aff;
1579 if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
drh7a5bcc02013-01-16 17:08:58 +00001580 if( (pTerm->eOperator & WO_EQ)==0 ) return 0;
drh4139c992010-04-07 14:59:45 +00001581 if( (pTerm->prereqRight & notReady)!=0 ) return 0;
drh23f98da2013-05-21 15:52:07 +00001582 if( pTerm->u.leftColumn<0 ) return 0;
drh4139c992010-04-07 14:59:45 +00001583 aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
1584 if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
1585 return 1;
1586}
drhc6339082010-04-07 16:54:58 +00001587#endif
drh4139c992010-04-07 14:59:45 +00001588
drhc6339082010-04-07 16:54:58 +00001589
1590#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
drh8b307fb2010-04-06 15:57:05 +00001591/*
drhc6339082010-04-07 16:54:58 +00001592** Generate code to construct the Index object for an automatic index
1593** and to set up the WhereLevel object pLevel so that the code generator
1594** makes use of the automatic index.
drh8b307fb2010-04-06 15:57:05 +00001595*/
drhc6339082010-04-07 16:54:58 +00001596static void constructAutomaticIndex(
drh8b307fb2010-04-06 15:57:05 +00001597 Parse *pParse, /* The parsing context */
1598 WhereClause *pWC, /* The WHERE clause */
1599 struct SrcList_item *pSrc, /* The FROM clause term to get the next index */
1600 Bitmask notReady, /* Mask of cursors that are not available */
1601 WhereLevel *pLevel /* Write new index here */
1602){
drhbbbdc832013-10-22 18:01:40 +00001603 int nKeyCol; /* Number of columns in the constructed index */
drh8b307fb2010-04-06 15:57:05 +00001604 WhereTerm *pTerm; /* A single term of the WHERE clause */
1605 WhereTerm *pWCEnd; /* End of pWC->a[] */
drh8b307fb2010-04-06 15:57:05 +00001606 Index *pIdx; /* Object describing the transient index */
1607 Vdbe *v; /* Prepared statement under construction */
drh8b307fb2010-04-06 15:57:05 +00001608 int addrInit; /* Address of the initialization bypass jump */
1609 Table *pTable; /* The table being indexed */
drh8b307fb2010-04-06 15:57:05 +00001610 int addrTop; /* Top of the index fill loop */
1611 int regRecord; /* Register holding an index record */
1612 int n; /* Column counter */
drh4139c992010-04-07 14:59:45 +00001613 int i; /* Loop counter */
1614 int mxBitCol; /* Maximum column in pSrc->colUsed */
drh424aab82010-04-06 18:28:20 +00001615 CollSeq *pColl; /* Collating sequence to on a column */
drh7ba39a92013-05-30 17:43:19 +00001616 WhereLoop *pLoop; /* The Loop object */
drh77e57df2013-10-22 14:28:02 +00001617 char *zNotUsed; /* Extra space on the end of pIdx */
drh4139c992010-04-07 14:59:45 +00001618 Bitmask idxCols; /* Bitmap of columns used for indexing */
1619 Bitmask extraCols; /* Bitmap of additional columns */
drh8d56e202013-06-28 23:55:45 +00001620 u8 sentWarning = 0; /* True if a warnning has been issued */
drh059b2d52014-10-24 19:28:09 +00001621 Expr *pPartial = 0; /* Partial Index Expression */
1622 int iContinue = 0; /* Jump here to skip excluded rows */
drh8b307fb2010-04-06 15:57:05 +00001623
1624 /* Generate code to skip over the creation and initialization of the
1625 ** transient index on 2nd and subsequent iterations of the loop. */
1626 v = pParse->pVdbe;
1627 assert( v!=0 );
drh7d176102014-02-18 03:07:12 +00001628 addrInit = sqlite3CodeOnce(pParse); VdbeCoverage(v);
drh8b307fb2010-04-06 15:57:05 +00001629
drh4139c992010-04-07 14:59:45 +00001630 /* Count the number of columns that will be added to the index
1631 ** and used to match WHERE clause constraints */
drhbbbdc832013-10-22 18:01:40 +00001632 nKeyCol = 0;
drh424aab82010-04-06 18:28:20 +00001633 pTable = pSrc->pTab;
drh8b307fb2010-04-06 15:57:05 +00001634 pWCEnd = &pWC->a[pWC->nTerm];
drh7ba39a92013-05-30 17:43:19 +00001635 pLoop = pLevel->pWLoop;
drh4139c992010-04-07 14:59:45 +00001636 idxCols = 0;
drh81186b42013-06-18 01:52:41 +00001637 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
drh13cc90c2015-02-25 00:24:41 +00001638 Expr *pExpr = pTerm->pExpr;
1639 assert( !ExprHasProperty(pExpr, EP_FromJoin) /* prereq always non-zero */
1640 || pExpr->iRightJoinTable!=pSrc->iCursor /* for the right-hand */
1641 || pLoop->prereq!=0 ); /* table of a LEFT JOIN */
drh059b2d52014-10-24 19:28:09 +00001642 if( pLoop->prereq==0
drh051575c2014-10-25 12:28:25 +00001643 && (pTerm->wtFlags & TERM_VIRTUAL)==0
drh13cc90c2015-02-25 00:24:41 +00001644 && !ExprHasProperty(pExpr, EP_FromJoin)
1645 && sqlite3ExprIsTableConstant(pExpr, pSrc->iCursor) ){
drh059b2d52014-10-24 19:28:09 +00001646 pPartial = sqlite3ExprAnd(pParse->db, pPartial,
drh13cc90c2015-02-25 00:24:41 +00001647 sqlite3ExprDup(pParse->db, pExpr, 0));
drh059b2d52014-10-24 19:28:09 +00001648 }
drh4139c992010-04-07 14:59:45 +00001649 if( termCanDriveIndex(pTerm, pSrc, notReady) ){
1650 int iCol = pTerm->u.leftColumn;
drh7699d1c2013-06-04 12:42:29 +00001651 Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
drh52ff8ea2010-04-08 14:15:56 +00001652 testcase( iCol==BMS );
1653 testcase( iCol==BMS-1 );
drh8d56e202013-06-28 23:55:45 +00001654 if( !sentWarning ){
1655 sqlite3_log(SQLITE_WARNING_AUTOINDEX,
1656 "automatic index on %s(%s)", pTable->zName,
1657 pTable->aCol[iCol].zName);
1658 sentWarning = 1;
1659 }
drh0013e722010-04-08 00:40:15 +00001660 if( (idxCols & cMask)==0 ){
drh059b2d52014-10-24 19:28:09 +00001661 if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ){
1662 goto end_auto_index_create;
1663 }
drhbbbdc832013-10-22 18:01:40 +00001664 pLoop->aLTerm[nKeyCol++] = pTerm;
drh0013e722010-04-08 00:40:15 +00001665 idxCols |= cMask;
1666 }
drh8b307fb2010-04-06 15:57:05 +00001667 }
1668 }
drhbbbdc832013-10-22 18:01:40 +00001669 assert( nKeyCol>0 );
1670 pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol;
drh53b52f72013-05-31 11:57:39 +00001671 pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
drh986b3872013-06-28 21:12:20 +00001672 | WHERE_AUTO_INDEX;
drh4139c992010-04-07 14:59:45 +00001673
1674 /* Count the number of additional columns needed to create a
1675 ** covering index. A "covering index" is an index that contains all
1676 ** columns that are needed by the query. With a covering index, the
1677 ** original table never needs to be accessed. Automatic indices must
1678 ** be a covering index because the index will not be updated if the
1679 ** original table changes and the index and table cannot both be used
1680 ** if they go out of sync.
1681 */
drh7699d1c2013-06-04 12:42:29 +00001682 extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
drhc3ef4fa2014-10-28 15:58:50 +00001683 mxBitCol = MIN(BMS-1,pTable->nCol);
drh52ff8ea2010-04-08 14:15:56 +00001684 testcase( pTable->nCol==BMS-1 );
1685 testcase( pTable->nCol==BMS-2 );
drh4139c992010-04-07 14:59:45 +00001686 for(i=0; i<mxBitCol; i++){
drhbbbdc832013-10-22 18:01:40 +00001687 if( extraCols & MASKBIT(i) ) nKeyCol++;
drh4139c992010-04-07 14:59:45 +00001688 }
drh7699d1c2013-06-04 12:42:29 +00001689 if( pSrc->colUsed & MASKBIT(BMS-1) ){
drhbbbdc832013-10-22 18:01:40 +00001690 nKeyCol += pTable->nCol - BMS + 1;
drh4139c992010-04-07 14:59:45 +00001691 }
drh8b307fb2010-04-06 15:57:05 +00001692
1693 /* Construct the Index object to describe this index */
drhbbbdc832013-10-22 18:01:40 +00001694 pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed);
drh059b2d52014-10-24 19:28:09 +00001695 if( pIdx==0 ) goto end_auto_index_create;
drh7ba39a92013-05-30 17:43:19 +00001696 pLoop->u.btree.pIndex = pIdx;
drh8b307fb2010-04-06 15:57:05 +00001697 pIdx->zName = "auto-index";
drh424aab82010-04-06 18:28:20 +00001698 pIdx->pTable = pTable;
drh8b307fb2010-04-06 15:57:05 +00001699 n = 0;
drh0013e722010-04-08 00:40:15 +00001700 idxCols = 0;
drh8b307fb2010-04-06 15:57:05 +00001701 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
drh4139c992010-04-07 14:59:45 +00001702 if( termCanDriveIndex(pTerm, pSrc, notReady) ){
drh0013e722010-04-08 00:40:15 +00001703 int iCol = pTerm->u.leftColumn;
drh7699d1c2013-06-04 12:42:29 +00001704 Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
drh7963b0e2013-06-17 21:37:40 +00001705 testcase( iCol==BMS-1 );
1706 testcase( iCol==BMS );
drh0013e722010-04-08 00:40:15 +00001707 if( (idxCols & cMask)==0 ){
1708 Expr *pX = pTerm->pExpr;
1709 idxCols |= cMask;
1710 pIdx->aiColumn[n] = pTerm->u.leftColumn;
1711 pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
drh6f2e6c02011-02-17 13:33:15 +00001712 pIdx->azColl[n] = ALWAYS(pColl) ? pColl->zName : "BINARY";
drh0013e722010-04-08 00:40:15 +00001713 n++;
1714 }
drh8b307fb2010-04-06 15:57:05 +00001715 }
1716 }
drh7ba39a92013-05-30 17:43:19 +00001717 assert( (u32)n==pLoop->u.btree.nEq );
drh4139c992010-04-07 14:59:45 +00001718
drhc6339082010-04-07 16:54:58 +00001719 /* Add additional columns needed to make the automatic index into
1720 ** a covering index */
drh4139c992010-04-07 14:59:45 +00001721 for(i=0; i<mxBitCol; i++){
drh7699d1c2013-06-04 12:42:29 +00001722 if( extraCols & MASKBIT(i) ){
drh4139c992010-04-07 14:59:45 +00001723 pIdx->aiColumn[n] = i;
1724 pIdx->azColl[n] = "BINARY";
1725 n++;
1726 }
1727 }
drh7699d1c2013-06-04 12:42:29 +00001728 if( pSrc->colUsed & MASKBIT(BMS-1) ){
drh4139c992010-04-07 14:59:45 +00001729 for(i=BMS-1; i<pTable->nCol; i++){
1730 pIdx->aiColumn[n] = i;
1731 pIdx->azColl[n] = "BINARY";
1732 n++;
1733 }
1734 }
drhbbbdc832013-10-22 18:01:40 +00001735 assert( n==nKeyCol );
drh44156282013-10-23 22:23:03 +00001736 pIdx->aiColumn[n] = -1;
1737 pIdx->azColl[n] = "BINARY";
drh8b307fb2010-04-06 15:57:05 +00001738
drhc6339082010-04-07 16:54:58 +00001739 /* Create the automatic index */
drh8b307fb2010-04-06 15:57:05 +00001740 assert( pLevel->iIdxCur>=0 );
drha1f41242013-05-31 20:00:58 +00001741 pLevel->iIdxCur = pParse->nTab++;
drh2ec2fb22013-11-06 19:59:23 +00001742 sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1);
1743 sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
drha21a64d2010-04-06 22:33:55 +00001744 VdbeComment((v, "for %s", pTable->zName));
drh8b307fb2010-04-06 15:57:05 +00001745
drhc6339082010-04-07 16:54:58 +00001746 /* Fill the automatic index with content */
drh059b2d52014-10-24 19:28:09 +00001747 sqlite3ExprCachePush(pParse);
drh688852a2014-02-17 22:40:43 +00001748 addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v);
drh059b2d52014-10-24 19:28:09 +00001749 if( pPartial ){
1750 iContinue = sqlite3VdbeMakeLabel(v);
1751 sqlite3ExprIfFalse(pParse, pPartial, iContinue, SQLITE_JUMPIFNULL);
drh051575c2014-10-25 12:28:25 +00001752 pLoop->wsFlags |= WHERE_PARTIALIDX;
drh059b2d52014-10-24 19:28:09 +00001753 }
drh8b307fb2010-04-06 15:57:05 +00001754 regRecord = sqlite3GetTempReg(pParse);
drh1c2c0b72014-01-04 19:27:05 +00001755 sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0);
drh8b307fb2010-04-06 15:57:05 +00001756 sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
1757 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
drh059b2d52014-10-24 19:28:09 +00001758 if( pPartial ) sqlite3VdbeResolveLabel(v, iContinue);
drh688852a2014-02-17 22:40:43 +00001759 sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v);
drha21a64d2010-04-06 22:33:55 +00001760 sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
drh8b307fb2010-04-06 15:57:05 +00001761 sqlite3VdbeJumpHere(v, addrTop);
1762 sqlite3ReleaseTempReg(pParse, regRecord);
drh059b2d52014-10-24 19:28:09 +00001763 sqlite3ExprCachePop(pParse);
drh8b307fb2010-04-06 15:57:05 +00001764
1765 /* Jump here when skipping the initialization */
1766 sqlite3VdbeJumpHere(v, addrInit);
drh059b2d52014-10-24 19:28:09 +00001767
1768end_auto_index_create:
1769 sqlite3ExprDelete(pParse->db, pPartial);
drh8b307fb2010-04-06 15:57:05 +00001770}
drhc6339082010-04-07 16:54:58 +00001771#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
drh8b307fb2010-04-06 15:57:05 +00001772
drh9eff6162006-06-12 21:59:13 +00001773#ifndef SQLITE_OMIT_VIRTUALTABLE
1774/*
danielk19771d461462009-04-21 09:02:45 +00001775** Allocate and populate an sqlite3_index_info structure. It is the
1776** responsibility of the caller to eventually release the structure
1777** by passing the pointer returned by this function to sqlite3_free().
1778*/
drh5346e952013-05-08 14:14:26 +00001779static sqlite3_index_info *allocateIndexInfo(
1780 Parse *pParse,
1781 WhereClause *pWC,
1782 struct SrcList_item *pSrc,
1783 ExprList *pOrderBy
1784){
danielk19771d461462009-04-21 09:02:45 +00001785 int i, j;
1786 int nTerm;
1787 struct sqlite3_index_constraint *pIdxCons;
1788 struct sqlite3_index_orderby *pIdxOrderBy;
1789 struct sqlite3_index_constraint_usage *pUsage;
1790 WhereTerm *pTerm;
1791 int nOrderBy;
1792 sqlite3_index_info *pIdxInfo;
1793
danielk19771d461462009-04-21 09:02:45 +00001794 /* Count the number of possible WHERE clause constraints referring
1795 ** to this virtual table */
1796 for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
1797 if( pTerm->leftCursor != pSrc->iCursor ) continue;
drh7a5bcc02013-01-16 17:08:58 +00001798 assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
1799 testcase( pTerm->eOperator & WO_IN );
1800 testcase( pTerm->eOperator & WO_ISNULL );
dana4ff8252014-01-20 19:55:33 +00001801 testcase( pTerm->eOperator & WO_ALL );
1802 if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV))==0 ) continue;
drhb4256992011-08-02 01:57:39 +00001803 if( pTerm->wtFlags & TERM_VNULL ) continue;
danielk19771d461462009-04-21 09:02:45 +00001804 nTerm++;
1805 }
1806
1807 /* If the ORDER BY clause contains only columns in the current
1808 ** virtual table then allocate space for the aOrderBy part of
1809 ** the sqlite3_index_info structure.
1810 */
1811 nOrderBy = 0;
1812 if( pOrderBy ){
drh56f1b992012-09-25 14:29:39 +00001813 int n = pOrderBy->nExpr;
1814 for(i=0; i<n; i++){
danielk19771d461462009-04-21 09:02:45 +00001815 Expr *pExpr = pOrderBy->a[i].pExpr;
1816 if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
1817 }
drh56f1b992012-09-25 14:29:39 +00001818 if( i==n){
1819 nOrderBy = n;
danielk19771d461462009-04-21 09:02:45 +00001820 }
1821 }
1822
1823 /* Allocate the sqlite3_index_info structure
1824 */
1825 pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
1826 + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
1827 + sizeof(*pIdxOrderBy)*nOrderBy );
1828 if( pIdxInfo==0 ){
1829 sqlite3ErrorMsg(pParse, "out of memory");
danielk19771d461462009-04-21 09:02:45 +00001830 return 0;
1831 }
1832
1833 /* Initialize the structure. The sqlite3_index_info structure contains
1834 ** many fields that are declared "const" to prevent xBestIndex from
1835 ** changing them. We have to do some funky casting in order to
1836 ** initialize those fields.
1837 */
1838 pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
1839 pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
1840 pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
1841 *(int*)&pIdxInfo->nConstraint = nTerm;
1842 *(int*)&pIdxInfo->nOrderBy = nOrderBy;
1843 *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
1844 *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
1845 *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
1846 pUsage;
1847
1848 for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
drh281bbe22012-10-16 23:17:14 +00001849 u8 op;
danielk19771d461462009-04-21 09:02:45 +00001850 if( pTerm->leftCursor != pSrc->iCursor ) continue;
drh7a5bcc02013-01-16 17:08:58 +00001851 assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
1852 testcase( pTerm->eOperator & WO_IN );
1853 testcase( pTerm->eOperator & WO_ISNULL );
dana4ff8252014-01-20 19:55:33 +00001854 testcase( pTerm->eOperator & WO_ALL );
1855 if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV))==0 ) continue;
drhb4256992011-08-02 01:57:39 +00001856 if( pTerm->wtFlags & TERM_VNULL ) continue;
danielk19771d461462009-04-21 09:02:45 +00001857 pIdxCons[j].iColumn = pTerm->u.leftColumn;
1858 pIdxCons[j].iTermOffset = i;
drh7a5bcc02013-01-16 17:08:58 +00001859 op = (u8)pTerm->eOperator & WO_ALL;
drh281bbe22012-10-16 23:17:14 +00001860 if( op==WO_IN ) op = WO_EQ;
1861 pIdxCons[j].op = op;
danielk19771d461462009-04-21 09:02:45 +00001862 /* The direct assignment in the previous line is possible only because
1863 ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The
1864 ** following asserts verify this fact. */
1865 assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
1866 assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
1867 assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
1868 assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
1869 assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
1870 assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
drh281bbe22012-10-16 23:17:14 +00001871 assert( pTerm->eOperator & (WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
danielk19771d461462009-04-21 09:02:45 +00001872 j++;
1873 }
1874 for(i=0; i<nOrderBy; i++){
1875 Expr *pExpr = pOrderBy->a[i].pExpr;
1876 pIdxOrderBy[i].iColumn = pExpr->iColumn;
1877 pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
1878 }
1879
1880 return pIdxInfo;
1881}
1882
1883/*
1884** The table object reference passed as the second argument to this function
1885** must represent a virtual table. This function invokes the xBestIndex()
drh3b48e8c2013-06-12 20:18:16 +00001886** method of the virtual table with the sqlite3_index_info object that
1887** comes in as the 3rd argument to this function.
danielk19771d461462009-04-21 09:02:45 +00001888**
1889** If an error occurs, pParse is populated with an error message and a
1890** non-zero value is returned. Otherwise, 0 is returned and the output
1891** part of the sqlite3_index_info structure is left populated.
1892**
1893** Whether or not an error is returned, it is the responsibility of the
1894** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
1895** that this is required.
1896*/
1897static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
danielk1977595a5232009-07-24 17:58:53 +00001898 sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
danielk19771d461462009-04-21 09:02:45 +00001899 int i;
1900 int rc;
1901
danielk19771d461462009-04-21 09:02:45 +00001902 TRACE_IDX_INPUTS(p);
1903 rc = pVtab->pModule->xBestIndex(pVtab, p);
1904 TRACE_IDX_OUTPUTS(p);
danielk19771d461462009-04-21 09:02:45 +00001905
1906 if( rc!=SQLITE_OK ){
1907 if( rc==SQLITE_NOMEM ){
1908 pParse->db->mallocFailed = 1;
1909 }else if( !pVtab->zErrMsg ){
1910 sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
1911 }else{
1912 sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
1913 }
1914 }
drhb9755982010-07-24 16:34:37 +00001915 sqlite3_free(pVtab->zErrMsg);
danielk19771d461462009-04-21 09:02:45 +00001916 pVtab->zErrMsg = 0;
1917
1918 for(i=0; i<p->nConstraint; i++){
1919 if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
1920 sqlite3ErrorMsg(pParse,
1921 "table %s: xBestIndex returned an invalid plan", pTab->zName);
1922 }
1923 }
1924
1925 return pParse->nErr;
1926}
drh7ba39a92013-05-30 17:43:19 +00001927#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
danielk19771d461462009-04-21 09:02:45 +00001928
drh1435a9a2013-08-27 23:15:44 +00001929#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drh28c4cf42005-07-27 20:41:43 +00001930/*
drhfaacf172011-08-12 01:51:45 +00001931** Estimate the location of a particular key among all keys in an
1932** index. Store the results in aStat as follows:
drhe847d322011-01-20 02:56:37 +00001933**
drhfaacf172011-08-12 01:51:45 +00001934** aStat[0] Est. number of rows less than pVal
1935** aStat[1] Est. number of rows equal to pVal
dan02fa4692009-08-17 17:06:58 +00001936**
drh6d3f91d2014-11-05 19:26:12 +00001937** Return the index of the sample that is the smallest sample that
1938** is greater than or equal to pRec.
dan02fa4692009-08-17 17:06:58 +00001939*/
drh6d3f91d2014-11-05 19:26:12 +00001940static int whereKeyStats(
dan02fa4692009-08-17 17:06:58 +00001941 Parse *pParse, /* Database connection */
1942 Index *pIdx, /* Index to consider domain of */
dan7a419232013-08-06 20:01:43 +00001943 UnpackedRecord *pRec, /* Vector of values to consider */
drhfaacf172011-08-12 01:51:45 +00001944 int roundUp, /* Round up if true. Round down if false */
1945 tRowcnt *aStat /* OUT: stats written here */
dan02fa4692009-08-17 17:06:58 +00001946){
danf52bb8d2013-08-03 20:24:58 +00001947 IndexSample *aSample = pIdx->aSample;
drhfbc38de2013-09-03 19:26:22 +00001948 int iCol; /* Index of required stats in anEq[] etc. */
dan84c309b2013-08-08 16:17:12 +00001949 int iMin = 0; /* Smallest sample not yet tested */
1950 int i = pIdx->nSample; /* Smallest sample larger than or equal to pRec */
1951 int iTest; /* Next sample to test */
1952 int res; /* Result of comparison operation */
dan02fa4692009-08-17 17:06:58 +00001953
drh4f991892013-10-11 15:05:05 +00001954#ifndef SQLITE_DEBUG
1955 UNUSED_PARAMETER( pParse );
1956#endif
drh7f594752013-12-03 19:49:55 +00001957 assert( pRec!=0 );
drhfbc38de2013-09-03 19:26:22 +00001958 iCol = pRec->nField - 1;
drh5c624862011-09-22 18:46:34 +00001959 assert( pIdx->nSample>0 );
dan8ad169a2013-08-12 20:14:04 +00001960 assert( pRec->nField>0 && iCol<pIdx->nSampleCol );
dan84c309b2013-08-08 16:17:12 +00001961 do{
1962 iTest = (iMin+i)/2;
drh75179de2014-09-16 14:37:35 +00001963 res = sqlite3VdbeRecordCompare(aSample[iTest].n, aSample[iTest].p, pRec);
dan84c309b2013-08-08 16:17:12 +00001964 if( res<0 ){
1965 iMin = iTest+1;
1966 }else{
1967 i = iTest;
dan02fa4692009-08-17 17:06:58 +00001968 }
dan84c309b2013-08-08 16:17:12 +00001969 }while( res && iMin<i );
drh51147ba2005-07-23 22:59:55 +00001970
dan84c309b2013-08-08 16:17:12 +00001971#ifdef SQLITE_DEBUG
1972 /* The following assert statements check that the binary search code
1973 ** above found the right answer. This block serves no purpose other
1974 ** than to invoke the asserts. */
1975 if( res==0 ){
1976 /* If (res==0) is true, then sample $i must be equal to pRec */
1977 assert( i<pIdx->nSample );
drh75179de2014-09-16 14:37:35 +00001978 assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)
drh0e1f0022013-08-16 14:49:00 +00001979 || pParse->db->mallocFailed );
dan02fa4692009-08-17 17:06:58 +00001980 }else{
dan84c309b2013-08-08 16:17:12 +00001981 /* Otherwise, pRec must be smaller than sample $i and larger than
1982 ** sample ($i-1). */
1983 assert( i==pIdx->nSample
drh75179de2014-09-16 14:37:35 +00001984 || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0
drh0e1f0022013-08-16 14:49:00 +00001985 || pParse->db->mallocFailed );
dan84c309b2013-08-08 16:17:12 +00001986 assert( i==0
drh75179de2014-09-16 14:37:35 +00001987 || sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0
drh0e1f0022013-08-16 14:49:00 +00001988 || pParse->db->mallocFailed );
drhfaacf172011-08-12 01:51:45 +00001989 }
dan84c309b2013-08-08 16:17:12 +00001990#endif /* ifdef SQLITE_DEBUG */
dan02fa4692009-08-17 17:06:58 +00001991
drhfaacf172011-08-12 01:51:45 +00001992 /* At this point, aSample[i] is the first sample that is greater than
1993 ** or equal to pVal. Or if i==pIdx->nSample, then all samples are less
dan84c309b2013-08-08 16:17:12 +00001994 ** than pVal. If aSample[i]==pVal, then res==0.
drhfaacf172011-08-12 01:51:45 +00001995 */
dan84c309b2013-08-08 16:17:12 +00001996 if( res==0 ){
daneea568d2013-08-07 19:46:15 +00001997 aStat[0] = aSample[i].anLt[iCol];
1998 aStat[1] = aSample[i].anEq[iCol];
drhfaacf172011-08-12 01:51:45 +00001999 }else{
2000 tRowcnt iLower, iUpper, iGap;
2001 if( i==0 ){
2002 iLower = 0;
daneea568d2013-08-07 19:46:15 +00002003 iUpper = aSample[0].anLt[iCol];
drhfaacf172011-08-12 01:51:45 +00002004 }else{
dancfc9df72014-04-25 15:01:01 +00002005 i64 nRow0 = sqlite3LogEstToInt(pIdx->aiRowLogEst[0]);
2006 iUpper = i>=pIdx->nSample ? nRow0 : aSample[i].anLt[iCol];
daneea568d2013-08-07 19:46:15 +00002007 iLower = aSample[i-1].anEq[iCol] + aSample[i-1].anLt[iCol];
drhfaacf172011-08-12 01:51:45 +00002008 }
dan39caccf2014-07-01 11:54:02 +00002009 aStat[1] = pIdx->aAvgEq[iCol];
drhfaacf172011-08-12 01:51:45 +00002010 if( iLower>=iUpper ){
2011 iGap = 0;
2012 }else{
2013 iGap = iUpper - iLower;
drhfaacf172011-08-12 01:51:45 +00002014 }
2015 if( roundUp ){
2016 iGap = (iGap*2)/3;
2017 }else{
2018 iGap = iGap/3;
2019 }
2020 aStat[0] = iLower + iGap;
dan02fa4692009-08-17 17:06:58 +00002021 }
drh6d3f91d2014-11-05 19:26:12 +00002022 return i;
dan02fa4692009-08-17 17:06:58 +00002023}
drh1435a9a2013-08-27 23:15:44 +00002024#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
dan937d0de2009-10-15 18:35:38 +00002025
2026/*
danaa9933c2014-04-24 20:04:49 +00002027** If it is not NULL, pTerm is a term that provides an upper or lower
2028** bound on a range scan. Without considering pTerm, it is estimated
2029** that the scan will visit nNew rows. This function returns the number
2030** estimated to be visited after taking pTerm into account.
2031**
2032** If the user explicitly specified a likelihood() value for this term,
2033** then the return value is the likelihood multiplied by the number of
2034** input rows. Otherwise, this function assumes that an "IS NOT NULL" term
2035** has a likelihood of 0.50, and any other term a likelihood of 0.25.
2036*/
2037static LogEst whereRangeAdjust(WhereTerm *pTerm, LogEst nNew){
2038 LogEst nRet = nNew;
2039 if( pTerm ){
2040 if( pTerm->truthProb<=0 ){
2041 nRet += pTerm->truthProb;
dan7de2a1f2014-04-28 20:11:20 +00002042 }else if( (pTerm->wtFlags & TERM_VNULL)==0 ){
danaa9933c2014-04-24 20:04:49 +00002043 nRet -= 20; assert( 20==sqlite3LogEst(4) );
2044 }
2045 }
2046 return nRet;
2047}
2048
mistachkin2d84ac42014-06-26 21:32:09 +00002049#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
danb0b82902014-06-26 20:21:46 +00002050/*
2051** This function is called to estimate the number of rows visited by a
2052** range-scan on a skip-scan index. For example:
2053**
2054** CREATE INDEX i1 ON t1(a, b, c);
2055** SELECT * FROM t1 WHERE a=? AND c BETWEEN ? AND ?;
2056**
2057** Value pLoop->nOut is currently set to the estimated number of rows
2058** visited for scanning (a=? AND b=?). This function reduces that estimate
2059** by some factor to account for the (c BETWEEN ? AND ?) expression based
2060** on the stat4 data for the index. this scan will be peformed multiple
2061** times (once for each (a,b) combination that matches a=?) is dealt with
2062** by the caller.
2063**
2064** It does this by scanning through all stat4 samples, comparing values
2065** extracted from pLower and pUpper with the corresponding column in each
2066** sample. If L and U are the number of samples found to be less than or
2067** equal to the values extracted from pLower and pUpper respectively, and
2068** N is the total number of samples, the pLoop->nOut value is adjusted
2069** as follows:
2070**
2071** nOut = nOut * ( min(U - L, 1) / N )
2072**
2073** If pLower is NULL, or a value cannot be extracted from the term, L is
2074** set to zero. If pUpper is NULL, or a value cannot be extracted from it,
2075** U is set to N.
2076**
2077** Normally, this function sets *pbDone to 1 before returning. However,
2078** if no value can be extracted from either pLower or pUpper (and so the
2079** estimate of the number of rows delivered remains unchanged), *pbDone
2080** is left as is.
2081**
2082** If an error occurs, an SQLite error code is returned. Otherwise,
2083** SQLITE_OK.
2084*/
2085static int whereRangeSkipScanEst(
2086 Parse *pParse, /* Parsing & code generating context */
2087 WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
2088 WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
2089 WhereLoop *pLoop, /* Update the .nOut value of this loop */
2090 int *pbDone /* Set to true if at least one expr. value extracted */
2091){
2092 Index *p = pLoop->u.btree.pIndex;
2093 int nEq = pLoop->u.btree.nEq;
2094 sqlite3 *db = pParse->db;
dan4e42ba42014-06-27 20:14:25 +00002095 int nLower = -1;
2096 int nUpper = p->nSample+1;
danb0b82902014-06-26 20:21:46 +00002097 int rc = SQLITE_OK;
drhd15f87e2014-07-24 22:41:20 +00002098 int iCol = p->aiColumn[nEq];
2099 u8 aff = iCol>=0 ? p->pTable->aCol[iCol].affinity : SQLITE_AFF_INTEGER;
danb0b82902014-06-26 20:21:46 +00002100 CollSeq *pColl;
2101
2102 sqlite3_value *p1 = 0; /* Value extracted from pLower */
2103 sqlite3_value *p2 = 0; /* Value extracted from pUpper */
2104 sqlite3_value *pVal = 0; /* Value extracted from record */
2105
2106 pColl = sqlite3LocateCollSeq(pParse, p->azColl[nEq]);
2107 if( pLower ){
2108 rc = sqlite3Stat4ValueFromExpr(pParse, pLower->pExpr->pRight, aff, &p1);
dan4e42ba42014-06-27 20:14:25 +00002109 nLower = 0;
danb0b82902014-06-26 20:21:46 +00002110 }
2111 if( pUpper && rc==SQLITE_OK ){
2112 rc = sqlite3Stat4ValueFromExpr(pParse, pUpper->pExpr->pRight, aff, &p2);
dan4e42ba42014-06-27 20:14:25 +00002113 nUpper = p2 ? 0 : p->nSample;
danb0b82902014-06-26 20:21:46 +00002114 }
2115
2116 if( p1 || p2 ){
2117 int i;
2118 int nDiff;
2119 for(i=0; rc==SQLITE_OK && i<p->nSample; i++){
2120 rc = sqlite3Stat4Column(db, p->aSample[i].p, p->aSample[i].n, nEq, &pVal);
2121 if( rc==SQLITE_OK && p1 ){
2122 int res = sqlite3MemCompare(p1, pVal, pColl);
dan4e42ba42014-06-27 20:14:25 +00002123 if( res>=0 ) nLower++;
danb0b82902014-06-26 20:21:46 +00002124 }
2125 if( rc==SQLITE_OK && p2 ){
2126 int res = sqlite3MemCompare(p2, pVal, pColl);
dan4e42ba42014-06-27 20:14:25 +00002127 if( res>=0 ) nUpper++;
danb0b82902014-06-26 20:21:46 +00002128 }
2129 }
danb0b82902014-06-26 20:21:46 +00002130 nDiff = (nUpper - nLower);
2131 if( nDiff<=0 ) nDiff = 1;
dan4e42ba42014-06-27 20:14:25 +00002132
2133 /* If there is both an upper and lower bound specified, and the
2134 ** comparisons indicate that they are close together, use the fallback
2135 ** method (assume that the scan visits 1/64 of the rows) for estimating
2136 ** the number of rows visited. Otherwise, estimate the number of rows
2137 ** using the method described in the header comment for this function. */
2138 if( nDiff!=1 || pUpper==0 || pLower==0 ){
2139 int nAdjust = (sqlite3LogEst(p->nSample) - sqlite3LogEst(nDiff));
2140 pLoop->nOut -= nAdjust;
2141 *pbDone = 1;
2142 WHERETRACE(0x10, ("range skip-scan regions: %u..%u adjust=%d est=%d\n",
danfa887452014-06-28 15:26:10 +00002143 nLower, nUpper, nAdjust*-1, pLoop->nOut));
dan4e42ba42014-06-27 20:14:25 +00002144 }
2145
danb0b82902014-06-26 20:21:46 +00002146 }else{
2147 assert( *pbDone==0 );
2148 }
2149
2150 sqlite3ValueFree(p1);
2151 sqlite3ValueFree(p2);
2152 sqlite3ValueFree(pVal);
2153
2154 return rc;
2155}
mistachkin2d84ac42014-06-26 21:32:09 +00002156#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
danb0b82902014-06-26 20:21:46 +00002157
danaa9933c2014-04-24 20:04:49 +00002158/*
dan02fa4692009-08-17 17:06:58 +00002159** This function is used to estimate the number of rows that will be visited
2160** by scanning an index for a range of values. The range may have an upper
2161** bound, a lower bound, or both. The WHERE clause terms that set the upper
2162** and lower bounds are represented by pLower and pUpper respectively. For
2163** example, assuming that index p is on t1(a):
2164**
2165** ... FROM t1 WHERE a > ? AND a < ? ...
2166** |_____| |_____|
2167** | |
2168** pLower pUpper
2169**
drh98cdf622009-08-20 18:14:42 +00002170** If either of the upper or lower bound is not present, then NULL is passed in
drhcdaca552009-08-20 13:45:07 +00002171** place of the corresponding WhereTerm.
dan02fa4692009-08-17 17:06:58 +00002172**
drh6d3f91d2014-11-05 19:26:12 +00002173** The value in (pBuilder->pNew->u.btree.nEq) is the number of the index
dan6cb8d762013-08-08 11:48:57 +00002174** column subject to the range constraint. Or, equivalently, the number of
2175** equality constraints optimized by the proposed index scan. For example,
2176** assuming index p is on t1(a, b), and the SQL query is:
dan02fa4692009-08-17 17:06:58 +00002177**
2178** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
2179**
dan6cb8d762013-08-08 11:48:57 +00002180** then nEq is set to 1 (as the range restricted column, b, is the second
2181** left-most column of the index). Or, if the query is:
dan02fa4692009-08-17 17:06:58 +00002182**
2183** ... FROM t1 WHERE a > ? AND a < ? ...
2184**
dan6cb8d762013-08-08 11:48:57 +00002185** then nEq is set to 0.
dan02fa4692009-08-17 17:06:58 +00002186**
drhbf539c42013-10-05 18:16:02 +00002187** When this function is called, *pnOut is set to the sqlite3LogEst() of the
dan6cb8d762013-08-08 11:48:57 +00002188** number of rows that the index scan is expected to visit without
drh6d3f91d2014-11-05 19:26:12 +00002189** considering the range constraints. If nEq is 0, then *pnOut is the number of
dan6cb8d762013-08-08 11:48:57 +00002190** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced)
peter.d.reid60ec9142014-09-06 16:39:46 +00002191** to account for the range constraints pLower and pUpper.
dan6cb8d762013-08-08 11:48:57 +00002192**
2193** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be
drh94aa7e02014-06-06 17:09:52 +00002194** used, a single range inequality reduces the search space by a factor of 4.
2195** and a pair of constraints (x>? AND x<?) reduces the expected number of
2196** rows visited by a factor of 64.
dan02fa4692009-08-17 17:06:58 +00002197*/
2198static int whereRangeScanEst(
drhcdaca552009-08-20 13:45:07 +00002199 Parse *pParse, /* Parsing & code generating context */
dan7a419232013-08-06 20:01:43 +00002200 WhereLoopBuilder *pBuilder,
drhcdaca552009-08-20 13:45:07 +00002201 WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
2202 WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
drh186ad8c2013-10-08 18:40:37 +00002203 WhereLoop *pLoop /* Modify the .nOut and maybe .rRun fields */
dan02fa4692009-08-17 17:06:58 +00002204){
dan69188d92009-08-19 08:18:32 +00002205 int rc = SQLITE_OK;
drh186ad8c2013-10-08 18:40:37 +00002206 int nOut = pLoop->nOut;
drhbf539c42013-10-05 18:16:02 +00002207 LogEst nNew;
dan69188d92009-08-19 08:18:32 +00002208
drh1435a9a2013-08-27 23:15:44 +00002209#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drh186ad8c2013-10-08 18:40:37 +00002210 Index *p = pLoop->u.btree.pIndex;
drh4f991892013-10-11 15:05:05 +00002211 int nEq = pLoop->u.btree.nEq;
dan02fa4692009-08-17 17:06:58 +00002212
drh6d3f91d2014-11-05 19:26:12 +00002213 if( p->nSample>0 && nEq<p->nSampleCol ){
danb0b82902014-06-26 20:21:46 +00002214 if( nEq==pBuilder->nRecValid ){
2215 UnpackedRecord *pRec = pBuilder->pRec;
2216 tRowcnt a[2];
2217 u8 aff;
drh98cdf622009-08-20 18:14:42 +00002218
danb0b82902014-06-26 20:21:46 +00002219 /* Variable iLower will be set to the estimate of the number of rows in
2220 ** the index that are less than the lower bound of the range query. The
2221 ** lower bound being the concatenation of $P and $L, where $P is the
2222 ** key-prefix formed by the nEq values matched against the nEq left-most
2223 ** columns of the index, and $L is the value in pLower.
2224 **
2225 ** Or, if pLower is NULL or $L cannot be extracted from it (because it
2226 ** is not a simple variable or literal value), the lower bound of the
2227 ** range is $P. Due to a quirk in the way whereKeyStats() works, even
2228 ** if $L is available, whereKeyStats() is called for both ($P) and
drh6d3f91d2014-11-05 19:26:12 +00002229 ** ($P:$L) and the larger of the two returned values is used.
danb0b82902014-06-26 20:21:46 +00002230 **
2231 ** Similarly, iUpper is to be set to the estimate of the number of rows
2232 ** less than the upper bound of the range query. Where the upper bound
2233 ** is either ($P) or ($P:$U). Again, even if $U is available, both values
2234 ** of iUpper are requested of whereKeyStats() and the smaller used.
drh6d3f91d2014-11-05 19:26:12 +00002235 **
2236 ** The number of rows between the two bounds is then just iUpper-iLower.
danb0b82902014-06-26 20:21:46 +00002237 */
drh6d3f91d2014-11-05 19:26:12 +00002238 tRowcnt iLower; /* Rows less than the lower bound */
2239 tRowcnt iUpper; /* Rows less than the upper bound */
2240 int iLwrIdx = -2; /* aSample[] for the lower bound */
2241 int iUprIdx = -1; /* aSample[] for the upper bound */
danb3c02e22013-08-08 19:38:40 +00002242
drhb34fc5b2014-08-28 17:20:37 +00002243 if( pRec ){
2244 testcase( pRec->nField!=pBuilder->nRecValid );
2245 pRec->nField = pBuilder->nRecValid;
2246 }
danb0b82902014-06-26 20:21:46 +00002247 if( nEq==p->nKeyCol ){
2248 aff = SQLITE_AFF_INTEGER;
dan7a419232013-08-06 20:01:43 +00002249 }else{
danb0b82902014-06-26 20:21:46 +00002250 aff = p->pTable->aCol[p->aiColumn[nEq]].affinity;
drhfaacf172011-08-12 01:51:45 +00002251 }
danb0b82902014-06-26 20:21:46 +00002252 /* Determine iLower and iUpper using ($P) only. */
2253 if( nEq==0 ){
2254 iLower = 0;
drh9f07cf72014-10-22 15:27:05 +00002255 iUpper = p->nRowEst0;
danb0b82902014-06-26 20:21:46 +00002256 }else{
2257 /* Note: this call could be optimized away - since the same values must
2258 ** have been requested when testing key $P in whereEqualScanEst(). */
2259 whereKeyStats(pParse, p, pRec, 0, a);
2260 iLower = a[0];
2261 iUpper = a[0] + a[1];
dan6cb8d762013-08-08 11:48:57 +00002262 }
danb0b82902014-06-26 20:21:46 +00002263
drh69afd992014-10-08 02:53:25 +00002264 assert( pLower==0 || (pLower->eOperator & (WO_GT|WO_GE))!=0 );
2265 assert( pUpper==0 || (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
drh681fca02014-10-10 15:01:46 +00002266 assert( p->aSortOrder!=0 );
2267 if( p->aSortOrder[nEq] ){
drh69afd992014-10-08 02:53:25 +00002268 /* The roles of pLower and pUpper are swapped for a DESC index */
2269 SWAP(WhereTerm*, pLower, pUpper);
2270 }
2271
danb0b82902014-06-26 20:21:46 +00002272 /* If possible, improve on the iLower estimate using ($P:$L). */
2273 if( pLower ){
2274 int bOk; /* True if value is extracted from pExpr */
2275 Expr *pExpr = pLower->pExpr->pRight;
danb0b82902014-06-26 20:21:46 +00002276 rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
2277 if( rc==SQLITE_OK && bOk ){
2278 tRowcnt iNew;
drh6d3f91d2014-11-05 19:26:12 +00002279 iLwrIdx = whereKeyStats(pParse, p, pRec, 0, a);
drh69afd992014-10-08 02:53:25 +00002280 iNew = a[0] + ((pLower->eOperator & (WO_GT|WO_LE)) ? a[1] : 0);
danb0b82902014-06-26 20:21:46 +00002281 if( iNew>iLower ) iLower = iNew;
2282 nOut--;
danf741e042014-08-25 18:29:38 +00002283 pLower = 0;
danb0b82902014-06-26 20:21:46 +00002284 }
2285 }
2286
2287 /* If possible, improve on the iUpper estimate using ($P:$U). */
2288 if( pUpper ){
2289 int bOk; /* True if value is extracted from pExpr */
2290 Expr *pExpr = pUpper->pExpr->pRight;
danb0b82902014-06-26 20:21:46 +00002291 rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
2292 if( rc==SQLITE_OK && bOk ){
2293 tRowcnt iNew;
drh6d3f91d2014-11-05 19:26:12 +00002294 iUprIdx = whereKeyStats(pParse, p, pRec, 1, a);
drh69afd992014-10-08 02:53:25 +00002295 iNew = a[0] + ((pUpper->eOperator & (WO_GT|WO_LE)) ? a[1] : 0);
danb0b82902014-06-26 20:21:46 +00002296 if( iNew<iUpper ) iUpper = iNew;
2297 nOut--;
danf741e042014-08-25 18:29:38 +00002298 pUpper = 0;
danb0b82902014-06-26 20:21:46 +00002299 }
2300 }
2301
2302 pBuilder->pRec = pRec;
2303 if( rc==SQLITE_OK ){
2304 if( iUpper>iLower ){
2305 nNew = sqlite3LogEst(iUpper - iLower);
drh6d3f91d2014-11-05 19:26:12 +00002306 /* TUNING: If both iUpper and iLower are derived from the same
2307 ** sample, then assume they are 4x more selective. This brings
2308 ** the estimated selectivity more in line with what it would be
2309 ** if estimated without the use of STAT3/4 tables. */
2310 if( iLwrIdx==iUprIdx ) nNew -= 20; assert( 20==sqlite3LogEst(4) );
danb0b82902014-06-26 20:21:46 +00002311 }else{
2312 nNew = 10; assert( 10==sqlite3LogEst(2) );
2313 }
2314 if( nNew<nOut ){
2315 nOut = nNew;
2316 }
drhae914d72014-08-28 19:38:22 +00002317 WHERETRACE(0x10, ("STAT4 range scan: %u..%u est=%d\n",
danb0b82902014-06-26 20:21:46 +00002318 (u32)iLower, (u32)iUpper, nOut));
danb0b82902014-06-26 20:21:46 +00002319 }
2320 }else{
2321 int bDone = 0;
2322 rc = whereRangeSkipScanEst(pParse, pLower, pUpper, pLoop, &bDone);
2323 if( bDone ) return rc;
drh98cdf622009-08-20 18:14:42 +00002324 }
dan02fa4692009-08-17 17:06:58 +00002325 }
drh3f022182009-09-09 16:10:50 +00002326#else
2327 UNUSED_PARAMETER(pParse);
dan7a419232013-08-06 20:01:43 +00002328 UNUSED_PARAMETER(pBuilder);
dan02fa4692009-08-17 17:06:58 +00002329 assert( pLower || pUpper );
danf741e042014-08-25 18:29:38 +00002330#endif
dan7de2a1f2014-04-28 20:11:20 +00002331 assert( pUpper==0 || (pUpper->wtFlags & TERM_VNULL)==0 );
danaa9933c2014-04-24 20:04:49 +00002332 nNew = whereRangeAdjust(pLower, nOut);
2333 nNew = whereRangeAdjust(pUpper, nNew);
dan7de2a1f2014-04-28 20:11:20 +00002334
drh4dd96a82014-10-24 15:26:29 +00002335 /* TUNING: If there is both an upper and lower limit and neither limit
2336 ** has an application-defined likelihood(), assume the range is
dan42685f22014-04-28 19:34:06 +00002337 ** reduced by an additional 75%. This means that, by default, an open-ended
2338 ** range query (e.g. col > ?) is assumed to match 1/4 of the rows in the
2339 ** index. While a closed range (e.g. col BETWEEN ? AND ?) is estimated to
2340 ** match 1/64 of the index. */
drh4dd96a82014-10-24 15:26:29 +00002341 if( pLower && pLower->truthProb>0 && pUpper && pUpper->truthProb>0 ){
2342 nNew -= 20;
2343 }
dan7de2a1f2014-04-28 20:11:20 +00002344
danaa9933c2014-04-24 20:04:49 +00002345 nOut -= (pLower!=0) + (pUpper!=0);
drhabfa6d52013-09-11 03:53:22 +00002346 if( nNew<10 ) nNew = 10;
2347 if( nNew<nOut ) nOut = nNew;
drhae914d72014-08-28 19:38:22 +00002348#if defined(WHERETRACE_ENABLED)
2349 if( pLoop->nOut>nOut ){
2350 WHERETRACE(0x10,("Range scan lowers nOut from %d to %d\n",
2351 pLoop->nOut, nOut));
2352 }
2353#endif
drh186ad8c2013-10-08 18:40:37 +00002354 pLoop->nOut = (LogEst)nOut;
dan02fa4692009-08-17 17:06:58 +00002355 return rc;
2356}
2357
drh1435a9a2013-08-27 23:15:44 +00002358#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drh82759752011-01-20 16:52:09 +00002359/*
2360** Estimate the number of rows that will be returned based on
2361** an equality constraint x=VALUE and where that VALUE occurs in
2362** the histogram data. This only works when x is the left-most
drhfaacf172011-08-12 01:51:45 +00002363** column of an index and sqlite_stat3 histogram data is available
drhac8eb112011-03-17 01:58:21 +00002364** for that index. When pExpr==NULL that means the constraint is
2365** "x IS NULL" instead of "x=VALUE".
drh82759752011-01-20 16:52:09 +00002366**
drh0c50fa02011-01-21 16:27:18 +00002367** Write the estimated row count into *pnRow and return SQLITE_OK.
2368** If unable to make an estimate, leave *pnRow unchanged and return
2369** non-zero.
drh9b3eb0a2011-01-21 14:37:04 +00002370**
2371** This routine can fail if it is unable to load a collating sequence
2372** required for string comparison, or if unable to allocate memory
2373** for a UTF conversion required for comparison. The error is stored
2374** in the pParse structure.
drh82759752011-01-20 16:52:09 +00002375*/
drh041e09f2011-04-07 19:56:21 +00002376static int whereEqualScanEst(
drh82759752011-01-20 16:52:09 +00002377 Parse *pParse, /* Parsing & code generating context */
dan7a419232013-08-06 20:01:43 +00002378 WhereLoopBuilder *pBuilder,
drh0c50fa02011-01-21 16:27:18 +00002379 Expr *pExpr, /* Expression for VALUE in the x=VALUE constraint */
drhb8a8e8a2013-06-10 19:12:39 +00002380 tRowcnt *pnRow /* Write the revised row estimate here */
drh82759752011-01-20 16:52:09 +00002381){
dan7a419232013-08-06 20:01:43 +00002382 Index *p = pBuilder->pNew->u.btree.pIndex;
2383 int nEq = pBuilder->pNew->u.btree.nEq;
2384 UnpackedRecord *pRec = pBuilder->pRec;
drh82759752011-01-20 16:52:09 +00002385 u8 aff; /* Column affinity */
2386 int rc; /* Subfunction return code */
drhfaacf172011-08-12 01:51:45 +00002387 tRowcnt a[2]; /* Statistics */
dan7a419232013-08-06 20:01:43 +00002388 int bOk;
drh82759752011-01-20 16:52:09 +00002389
dan7a419232013-08-06 20:01:43 +00002390 assert( nEq>=1 );
danfd984b82014-06-30 18:02:20 +00002391 assert( nEq<=p->nColumn );
drh82759752011-01-20 16:52:09 +00002392 assert( p->aSample!=0 );
drh5c624862011-09-22 18:46:34 +00002393 assert( p->nSample>0 );
dan7a419232013-08-06 20:01:43 +00002394 assert( pBuilder->nRecValid<nEq );
2395
2396 /* If values are not available for all fields of the index to the left
2397 ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */
2398 if( pBuilder->nRecValid<(nEq-1) ){
2399 return SQLITE_NOTFOUND;
drh1f9c7662011-03-17 01:34:26 +00002400 }
dan7a419232013-08-06 20:01:43 +00002401
dandd6e1f12013-08-10 19:08:30 +00002402 /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue()
2403 ** below would return the same value. */
danfd984b82014-06-30 18:02:20 +00002404 if( nEq>=p->nColumn ){
dan7a419232013-08-06 20:01:43 +00002405 *pnRow = 1;
2406 return SQLITE_OK;
drh82759752011-01-20 16:52:09 +00002407 }
dan7a419232013-08-06 20:01:43 +00002408
daneea568d2013-08-07 19:46:15 +00002409 aff = p->pTable->aCol[p->aiColumn[nEq-1]].affinity;
dan87cd9322013-08-07 15:52:41 +00002410 rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq-1, &bOk);
2411 pBuilder->pRec = pRec;
dan7a419232013-08-06 20:01:43 +00002412 if( rc!=SQLITE_OK ) return rc;
2413 if( bOk==0 ) return SQLITE_NOTFOUND;
dan7a419232013-08-06 20:01:43 +00002414 pBuilder->nRecValid = nEq;
dan7a419232013-08-06 20:01:43 +00002415
danb3c02e22013-08-08 19:38:40 +00002416 whereKeyStats(pParse, p, pRec, 0, a);
drh989578e2013-10-28 14:34:35 +00002417 WHERETRACE(0x10,("equality scan regions: %d\n", (int)a[1]));
danb3c02e22013-08-08 19:38:40 +00002418 *pnRow = a[1];
daneea568d2013-08-07 19:46:15 +00002419
drh0c50fa02011-01-21 16:27:18 +00002420 return rc;
2421}
drh1435a9a2013-08-27 23:15:44 +00002422#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
drh0c50fa02011-01-21 16:27:18 +00002423
drh1435a9a2013-08-27 23:15:44 +00002424#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drh0c50fa02011-01-21 16:27:18 +00002425/*
2426** Estimate the number of rows that will be returned based on
drh5ac06072011-01-21 18:18:13 +00002427** an IN constraint where the right-hand side of the IN operator
2428** is a list of values. Example:
2429**
2430** WHERE x IN (1,2,3,4)
drh0c50fa02011-01-21 16:27:18 +00002431**
2432** Write the estimated row count into *pnRow and return SQLITE_OK.
2433** If unable to make an estimate, leave *pnRow unchanged and return
2434** non-zero.
2435**
2436** This routine can fail if it is unable to load a collating sequence
2437** required for string comparison, or if unable to allocate memory
2438** for a UTF conversion required for comparison. The error is stored
2439** in the pParse structure.
2440*/
drh041e09f2011-04-07 19:56:21 +00002441static int whereInScanEst(
drh0c50fa02011-01-21 16:27:18 +00002442 Parse *pParse, /* Parsing & code generating context */
dan7a419232013-08-06 20:01:43 +00002443 WhereLoopBuilder *pBuilder,
drh0c50fa02011-01-21 16:27:18 +00002444 ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
drhb8a8e8a2013-06-10 19:12:39 +00002445 tRowcnt *pnRow /* Write the revised row estimate here */
drh0c50fa02011-01-21 16:27:18 +00002446){
dan7a419232013-08-06 20:01:43 +00002447 Index *p = pBuilder->pNew->u.btree.pIndex;
dancfc9df72014-04-25 15:01:01 +00002448 i64 nRow0 = sqlite3LogEstToInt(p->aiRowLogEst[0]);
dan7a419232013-08-06 20:01:43 +00002449 int nRecValid = pBuilder->nRecValid;
drhb8a8e8a2013-06-10 19:12:39 +00002450 int rc = SQLITE_OK; /* Subfunction return code */
2451 tRowcnt nEst; /* Number of rows for a single term */
2452 tRowcnt nRowEst = 0; /* New estimate of the number of rows */
2453 int i; /* Loop counter */
drh0c50fa02011-01-21 16:27:18 +00002454
2455 assert( p->aSample!=0 );
drhfaacf172011-08-12 01:51:45 +00002456 for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
dancfc9df72014-04-25 15:01:01 +00002457 nEst = nRow0;
dan7a419232013-08-06 20:01:43 +00002458 rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst);
drhfaacf172011-08-12 01:51:45 +00002459 nRowEst += nEst;
dan7a419232013-08-06 20:01:43 +00002460 pBuilder->nRecValid = nRecValid;
drh0c50fa02011-01-21 16:27:18 +00002461 }
dan7a419232013-08-06 20:01:43 +00002462
drh0c50fa02011-01-21 16:27:18 +00002463 if( rc==SQLITE_OK ){
dancfc9df72014-04-25 15:01:01 +00002464 if( nRowEst > nRow0 ) nRowEst = nRow0;
drh0c50fa02011-01-21 16:27:18 +00002465 *pnRow = nRowEst;
drh5418b122014-08-28 13:42:13 +00002466 WHERETRACE(0x10,("IN row estimate: est=%d\n", nRowEst));
drh0c50fa02011-01-21 16:27:18 +00002467 }
dan7a419232013-08-06 20:01:43 +00002468 assert( pBuilder->nRecValid==nRecValid );
drh0c50fa02011-01-21 16:27:18 +00002469 return rc;
drh82759752011-01-20 16:52:09 +00002470}
drh1435a9a2013-08-27 23:15:44 +00002471#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
drh82759752011-01-20 16:52:09 +00002472
drh46c35f92012-09-26 23:17:01 +00002473/*
drh2ffb1182004-07-19 19:14:01 +00002474** Disable a term in the WHERE clause. Except, do not disable the term
2475** if it controls a LEFT OUTER JOIN and it did not originate in the ON
2476** or USING clause of that join.
2477**
2478** Consider the term t2.z='ok' in the following queries:
2479**
2480** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
2481** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
2482** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
2483**
drh23bf66d2004-12-14 03:34:34 +00002484** The t2.z='ok' is disabled in the in (2) because it originates
drh2ffb1182004-07-19 19:14:01 +00002485** in the ON clause. The term is disabled in (3) because it is not part
2486** of a LEFT OUTER JOIN. In (1), the term is not disabled.
2487**
2488** Disabling a term causes that term to not be tested in the inner loop
drhb6fb62d2005-09-20 08:47:20 +00002489** of the join. Disabling is an optimization. When terms are satisfied
2490** by indices, we disable them to prevent redundant tests in the inner
2491** loop. We would get the correct results if nothing were ever disabled,
2492** but joins might run a little slower. The trick is to disable as much
2493** as we can without disabling too much. If we disabled in (1), we'd get
2494** the wrong answer. See ticket #813.
drh8f1a7ed2015-03-06 19:47:38 +00002495**
2496** If all the children of a term are disabled, then that term is also
2497** automatically disabled. In this way, terms get disabled if derived
2498** virtual terms are tested first. For example:
2499**
2500** x GLOB 'abc*' AND x>='abc' AND x<'acd'
2501** \___________/ \______/ \_____/
2502** parent child1 child2
2503**
2504** Only the parent term was in the original WHERE clause. The child1
2505** and child2 terms were added by the LIKE optimization. If both of
2506** the virtual child terms are valid, then testing of the parent can be
2507** skipped.
drha9c18a92015-03-06 20:49:52 +00002508**
2509** Usually the parent term is marked as TERM_CODED. But if the parent
2510** term was originally TERM_LIKE, then the parent gets TERM_LIKECOND instead.
2511** The TERM_LIKECOND marking indicates that the term should be coded inside
2512** a conditional such that is only evaluated on the second pass of a
2513** LIKE-optimization loop, when scanning BLOBs instead of strings.
drh2ffb1182004-07-19 19:14:01 +00002514*/
drh0fcef5e2005-07-19 17:38:22 +00002515static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
drh8f1a7ed2015-03-06 19:47:38 +00002516 int nLoop = 0;
2517 while( pTerm
drhbe837bd2010-04-30 21:03:24 +00002518 && (pTerm->wtFlags & TERM_CODED)==0
drh0fcef5e2005-07-19 17:38:22 +00002519 && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
drh0259bc32013-09-09 19:37:46 +00002520 && (pLevel->notReady & pTerm->prereqAll)==0
drh0fcef5e2005-07-19 17:38:22 +00002521 ){
drh8f1a7ed2015-03-06 19:47:38 +00002522 if( nLoop && (pTerm->wtFlags & TERM_LIKE)!=0 ){
2523 pTerm->wtFlags |= TERM_LIKECOND;
2524 }else{
2525 pTerm->wtFlags |= TERM_CODED;
drh0fcef5e2005-07-19 17:38:22 +00002526 }
drh8f1a7ed2015-03-06 19:47:38 +00002527 if( pTerm->iParent<0 ) break;
2528 pTerm = &pTerm->pWC->a[pTerm->iParent];
2529 pTerm->nChild--;
2530 if( pTerm->nChild!=0 ) break;
2531 nLoop++;
drh2ffb1182004-07-19 19:14:01 +00002532 }
2533}
2534
2535/*
dan69f8bb92009-08-13 19:21:16 +00002536** Code an OP_Affinity opcode to apply the column affinity string zAff
2537** to the n registers starting at base.
2538**
drh039fc322009-11-17 18:31:47 +00002539** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
2540** beginning and end of zAff are ignored. If all entries in zAff are
2541** SQLITE_AFF_NONE, then no code gets generated.
2542**
2543** This routine makes its own copy of zAff so that the caller is free
2544** to modify zAff after this routine returns.
drh94a11212004-09-25 13:12:14 +00002545*/
dan69f8bb92009-08-13 19:21:16 +00002546static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
2547 Vdbe *v = pParse->pVdbe;
drh039fc322009-11-17 18:31:47 +00002548 if( zAff==0 ){
2549 assert( pParse->db->mallocFailed );
2550 return;
2551 }
dan69f8bb92009-08-13 19:21:16 +00002552 assert( v!=0 );
drh039fc322009-11-17 18:31:47 +00002553
2554 /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
2555 ** and end of the affinity string.
2556 */
2557 while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
2558 n--;
2559 base++;
2560 zAff++;
2561 }
2562 while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
2563 n--;
2564 }
2565
2566 /* Code the OP_Affinity opcode if there is anything left to do. */
2567 if( n>0 ){
2568 sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
2569 sqlite3VdbeChangeP4(v, -1, zAff, n);
2570 sqlite3ExprCacheAffinityChange(pParse, base, n);
2571 }
drh94a11212004-09-25 13:12:14 +00002572}
2573
drhe8b97272005-07-19 22:22:12 +00002574
2575/*
drh51147ba2005-07-23 22:59:55 +00002576** Generate code for a single equality term of the WHERE clause. An equality
2577** term can be either X=expr or X IN (...). pTerm is the term to be
2578** coded.
2579**
drh1db639c2008-01-17 02:36:28 +00002580** The current value for the constraint is left in register iReg.
drh51147ba2005-07-23 22:59:55 +00002581**
2582** For a constraint of the form X=expr, the expression is evaluated and its
2583** result is left on the stack. For constraints of the form X IN (...)
2584** this routine sets up a loop that will iterate over all values of X.
drh94a11212004-09-25 13:12:14 +00002585*/
drh678ccce2008-03-31 18:19:54 +00002586static int codeEqualityTerm(
drh94a11212004-09-25 13:12:14 +00002587 Parse *pParse, /* The parsing context */
drhe23399f2005-07-22 00:31:39 +00002588 WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
drh0fe456b2013-03-12 18:34:50 +00002589 WhereLevel *pLevel, /* The level of the FROM clause we are working on */
2590 int iEq, /* Index of the equality term within this level */
drh7ba39a92013-05-30 17:43:19 +00002591 int bRev, /* True for reverse-order IN operations */
drh678ccce2008-03-31 18:19:54 +00002592 int iTarget /* Attempt to leave results in this register */
drh94a11212004-09-25 13:12:14 +00002593){
drh0fcef5e2005-07-19 17:38:22 +00002594 Expr *pX = pTerm->pExpr;
drh50b39962006-10-28 00:28:09 +00002595 Vdbe *v = pParse->pVdbe;
drh678ccce2008-03-31 18:19:54 +00002596 int iReg; /* Register holding results */
drh1db639c2008-01-17 02:36:28 +00002597
danielk19772d605492008-10-01 08:43:03 +00002598 assert( iTarget>0 );
drh50b39962006-10-28 00:28:09 +00002599 if( pX->op==TK_EQ ){
drh678ccce2008-03-31 18:19:54 +00002600 iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
drh50b39962006-10-28 00:28:09 +00002601 }else if( pX->op==TK_ISNULL ){
drh678ccce2008-03-31 18:19:54 +00002602 iReg = iTarget;
drh1db639c2008-01-17 02:36:28 +00002603 sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
danielk1977b3bce662005-01-29 08:32:43 +00002604#ifndef SQLITE_OMIT_SUBQUERY
drh94a11212004-09-25 13:12:14 +00002605 }else{
danielk19779a96b662007-11-29 17:05:18 +00002606 int eType;
danielk1977b3bce662005-01-29 08:32:43 +00002607 int iTab;
drh72e8fa42007-03-28 14:30:06 +00002608 struct InLoop *pIn;
drh7ba39a92013-05-30 17:43:19 +00002609 WhereLoop *pLoop = pLevel->pWLoop;
danielk1977b3bce662005-01-29 08:32:43 +00002610
drh7ba39a92013-05-30 17:43:19 +00002611 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
2612 && pLoop->u.btree.pIndex!=0
2613 && pLoop->u.btree.pIndex->aSortOrder[iEq]
drhd3832162013-03-12 18:49:25 +00002614 ){
drh725e1ae2013-03-12 23:58:42 +00002615 testcase( iEq==0 );
drh725e1ae2013-03-12 23:58:42 +00002616 testcase( bRev );
drh1ccce442013-03-12 20:38:51 +00002617 bRev = !bRev;
drh0fe456b2013-03-12 18:34:50 +00002618 }
drh50b39962006-10-28 00:28:09 +00002619 assert( pX->op==TK_IN );
drh678ccce2008-03-31 18:19:54 +00002620 iReg = iTarget;
drh3a856252014-08-01 14:46:57 +00002621 eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0);
drh725e1ae2013-03-12 23:58:42 +00002622 if( eType==IN_INDEX_INDEX_DESC ){
2623 testcase( bRev );
2624 bRev = !bRev;
2625 }
danielk1977b3bce662005-01-29 08:32:43 +00002626 iTab = pX->iTable;
drh7d176102014-02-18 03:07:12 +00002627 sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
2628 VdbeCoverageIf(v, bRev);
2629 VdbeCoverageIf(v, !bRev);
drh6fa978d2013-05-30 19:29:19 +00002630 assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
2631 pLoop->wsFlags |= WHERE_IN_ABLE;
drh111a6a72008-12-21 03:51:16 +00002632 if( pLevel->u.in.nIn==0 ){
drhb3190c12008-12-08 21:37:14 +00002633 pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
drh72e8fa42007-03-28 14:30:06 +00002634 }
drh111a6a72008-12-21 03:51:16 +00002635 pLevel->u.in.nIn++;
2636 pLevel->u.in.aInLoop =
2637 sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
2638 sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
2639 pIn = pLevel->u.in.aInLoop;
drh72e8fa42007-03-28 14:30:06 +00002640 if( pIn ){
drh111a6a72008-12-21 03:51:16 +00002641 pIn += pLevel->u.in.nIn - 1;
drh72e8fa42007-03-28 14:30:06 +00002642 pIn->iCur = iTab;
drh1db639c2008-01-17 02:36:28 +00002643 if( eType==IN_INDEX_ROWID ){
drhb3190c12008-12-08 21:37:14 +00002644 pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
drh1db639c2008-01-17 02:36:28 +00002645 }else{
drhb3190c12008-12-08 21:37:14 +00002646 pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
drh1db639c2008-01-17 02:36:28 +00002647 }
drhf93cd942013-11-21 03:12:25 +00002648 pIn->eEndLoopOp = bRev ? OP_PrevIfOpen : OP_NextIfOpen;
drh688852a2014-02-17 22:40:43 +00002649 sqlite3VdbeAddOp1(v, OP_IsNull, iReg); VdbeCoverage(v);
drha6110402005-07-28 20:51:19 +00002650 }else{
drh111a6a72008-12-21 03:51:16 +00002651 pLevel->u.in.nIn = 0;
drhe23399f2005-07-22 00:31:39 +00002652 }
danielk1977b3bce662005-01-29 08:32:43 +00002653#endif
drh94a11212004-09-25 13:12:14 +00002654 }
drh0fcef5e2005-07-19 17:38:22 +00002655 disableTerm(pLevel, pTerm);
drh678ccce2008-03-31 18:19:54 +00002656 return iReg;
drh94a11212004-09-25 13:12:14 +00002657}
2658
drh51147ba2005-07-23 22:59:55 +00002659/*
2660** Generate code that will evaluate all == and IN constraints for an
drhcd8629e2013-11-13 12:27:25 +00002661** index scan.
drh51147ba2005-07-23 22:59:55 +00002662**
2663** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
2664** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
2665** The index has as many as three equality constraints, but in this
2666** example, the third "c" value is an inequality. So only two
2667** constraints are coded. This routine will generate code to evaluate
drh6df2acd2008-12-28 16:55:25 +00002668** a==5 and b IN (1,2,3). The current values for a and b will be stored
2669** in consecutive registers and the index of the first register is returned.
drh51147ba2005-07-23 22:59:55 +00002670**
2671** In the example above nEq==2. But this subroutine works for any value
2672** of nEq including 0. If nEq==0, this routine is nearly a no-op.
drh039fc322009-11-17 18:31:47 +00002673** The only thing it does is allocate the pLevel->iMem memory cell and
2674** compute the affinity string.
drh51147ba2005-07-23 22:59:55 +00002675**
drhcd8629e2013-11-13 12:27:25 +00002676** The nExtraReg parameter is 0 or 1. It is 0 if all WHERE clause constraints
2677** are == or IN and are covered by the nEq. nExtraReg is 1 if there is
2678** an inequality constraint (such as the "c>=5 AND c<10" in the example) that
2679** occurs after the nEq quality constraints.
2680**
2681** This routine allocates a range of nEq+nExtraReg memory cells and returns
2682** the index of the first memory cell in that range. The code that
2683** calls this routine will use that memory range to store keys for
2684** start and termination conditions of the loop.
drh51147ba2005-07-23 22:59:55 +00002685** key value of the loop. If one or more IN operators appear, then
2686** this routine allocates an additional nEq memory cells for internal
2687** use.
dan69f8bb92009-08-13 19:21:16 +00002688**
2689** Before returning, *pzAff is set to point to a buffer containing a
2690** copy of the column affinity string of the index allocated using
2691** sqlite3DbMalloc(). Except, entries in the copy of the string associated
2692** with equality constraints that use NONE affinity are set to
2693** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
2694**
2695** CREATE TABLE t1(a TEXT PRIMARY KEY, b);
2696** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
2697**
2698** In the example above, the index on t1(a) has TEXT affinity. But since
2699** the right hand side of the equality constraint (t2.b) has NONE affinity,
2700** no conversion should be attempted before using a t2.b value as part of
2701** a key to search the index. Hence the first byte in the returned affinity
2702** string in this example would be set to SQLITE_AFF_NONE.
drh51147ba2005-07-23 22:59:55 +00002703*/
drh1db639c2008-01-17 02:36:28 +00002704static int codeAllEqualityTerms(
drh51147ba2005-07-23 22:59:55 +00002705 Parse *pParse, /* Parsing context */
2706 WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
drh7ba39a92013-05-30 17:43:19 +00002707 int bRev, /* Reverse the order of IN operators */
dan69f8bb92009-08-13 19:21:16 +00002708 int nExtraReg, /* Number of extra registers to allocate */
2709 char **pzAff /* OUT: Set to point to affinity string */
drh51147ba2005-07-23 22:59:55 +00002710){
drhcd8629e2013-11-13 12:27:25 +00002711 u16 nEq; /* The number of == or IN constraints to code */
2712 u16 nSkip; /* Number of left-most columns to skip */
drh111a6a72008-12-21 03:51:16 +00002713 Vdbe *v = pParse->pVdbe; /* The vm under construction */
2714 Index *pIdx; /* The index being used for this loop */
drh51147ba2005-07-23 22:59:55 +00002715 WhereTerm *pTerm; /* A single constraint term */
drh7ba39a92013-05-30 17:43:19 +00002716 WhereLoop *pLoop; /* The WhereLoop object */
drh51147ba2005-07-23 22:59:55 +00002717 int j; /* Loop counter */
drh1db639c2008-01-17 02:36:28 +00002718 int regBase; /* Base register */
drh6df2acd2008-12-28 16:55:25 +00002719 int nReg; /* Number of registers to allocate */
dan69f8bb92009-08-13 19:21:16 +00002720 char *zAff; /* Affinity string to return */
drh51147ba2005-07-23 22:59:55 +00002721
drh111a6a72008-12-21 03:51:16 +00002722 /* This module is only called on query plans that use an index. */
drh7ba39a92013-05-30 17:43:19 +00002723 pLoop = pLevel->pWLoop;
2724 assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
2725 nEq = pLoop->u.btree.nEq;
drhc8bbce12014-10-21 01:05:09 +00002726 nSkip = pLoop->nSkip;
drh7ba39a92013-05-30 17:43:19 +00002727 pIdx = pLoop->u.btree.pIndex;
2728 assert( pIdx!=0 );
drh111a6a72008-12-21 03:51:16 +00002729
drh51147ba2005-07-23 22:59:55 +00002730 /* Figure out how many memory cells we will need then allocate them.
drh51147ba2005-07-23 22:59:55 +00002731 */
drh700a2262008-12-17 19:22:15 +00002732 regBase = pParse->nMem + 1;
drh7ba39a92013-05-30 17:43:19 +00002733 nReg = pLoop->u.btree.nEq + nExtraReg;
drh6df2acd2008-12-28 16:55:25 +00002734 pParse->nMem += nReg;
drh51147ba2005-07-23 22:59:55 +00002735
dan69f8bb92009-08-13 19:21:16 +00002736 zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
2737 if( !zAff ){
2738 pParse->db->mallocFailed = 1;
2739 }
2740
drhcd8629e2013-11-13 12:27:25 +00002741 if( nSkip ){
2742 int iIdxCur = pLevel->iIdxCur;
drh7d176102014-02-18 03:07:12 +00002743 sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur);
2744 VdbeCoverageIf(v, bRev==0);
2745 VdbeCoverageIf(v, bRev!=0);
drhe084f402013-11-13 17:24:38 +00002746 VdbeComment((v, "begin skip-scan on %s", pIdx->zName));
drh2e5ef4e2013-11-13 16:58:54 +00002747 j = sqlite3VdbeAddOp0(v, OP_Goto);
drh4a1d3652014-02-14 15:13:36 +00002748 pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT),
drh7d176102014-02-18 03:07:12 +00002749 iIdxCur, 0, regBase, nSkip);
2750 VdbeCoverageIf(v, bRev==0);
2751 VdbeCoverageIf(v, bRev!=0);
drh2e5ef4e2013-11-13 16:58:54 +00002752 sqlite3VdbeJumpHere(v, j);
drhcd8629e2013-11-13 12:27:25 +00002753 for(j=0; j<nSkip; j++){
2754 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, j, regBase+j);
2755 assert( pIdx->aiColumn[j]>=0 );
2756 VdbeComment((v, "%s", pIdx->pTable->aCol[pIdx->aiColumn[j]].zName));
2757 }
2758 }
2759
drh51147ba2005-07-23 22:59:55 +00002760 /* Evaluate the equality constraints
2761 */
mistachkinf6418892013-08-28 01:54:12 +00002762 assert( zAff==0 || (int)strlen(zAff)>=nEq );
drhcd8629e2013-11-13 12:27:25 +00002763 for(j=nSkip; j<nEq; j++){
drh678ccce2008-03-31 18:19:54 +00002764 int r1;
drh4efc9292013-06-06 23:02:03 +00002765 pTerm = pLoop->aLTerm[j];
drh7ba39a92013-05-30 17:43:19 +00002766 assert( pTerm!=0 );
drhcd8629e2013-11-13 12:27:25 +00002767 /* The following testcase is true for indices with redundant columns.
drhbe837bd2010-04-30 21:03:24 +00002768 ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
2769 testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
drh39759742013-08-02 23:40:45 +00002770 testcase( pTerm->wtFlags & TERM_VIRTUAL );
drh7ba39a92013-05-30 17:43:19 +00002771 r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
drh678ccce2008-03-31 18:19:54 +00002772 if( r1!=regBase+j ){
drh6df2acd2008-12-28 16:55:25 +00002773 if( nReg==1 ){
2774 sqlite3ReleaseTempReg(pParse, regBase);
2775 regBase = r1;
2776 }else{
2777 sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
2778 }
drh678ccce2008-03-31 18:19:54 +00002779 }
drh981642f2008-04-19 14:40:43 +00002780 testcase( pTerm->eOperator & WO_ISNULL );
2781 testcase( pTerm->eOperator & WO_IN );
drh72e8fa42007-03-28 14:30:06 +00002782 if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
drh039fc322009-11-17 18:31:47 +00002783 Expr *pRight = pTerm->pExpr->pRight;
drh7d176102014-02-18 03:07:12 +00002784 if( sqlite3ExprCanBeNull(pRight) ){
2785 sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk);
2786 VdbeCoverage(v);
2787 }
drh039fc322009-11-17 18:31:47 +00002788 if( zAff ){
2789 if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
2790 zAff[j] = SQLITE_AFF_NONE;
2791 }
2792 if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
2793 zAff[j] = SQLITE_AFF_NONE;
2794 }
dan69f8bb92009-08-13 19:21:16 +00002795 }
drh51147ba2005-07-23 22:59:55 +00002796 }
2797 }
dan69f8bb92009-08-13 19:21:16 +00002798 *pzAff = zAff;
drh1db639c2008-01-17 02:36:28 +00002799 return regBase;
drh51147ba2005-07-23 22:59:55 +00002800}
2801
dan6f9702e2014-11-01 20:38:06 +00002802#ifndef SQLITE_OMIT_EXPLAIN
dan17c0bc02010-11-09 17:35:19 +00002803/*
drh69174c42010-11-12 15:35:59 +00002804** This routine is a helper for explainIndexRange() below
2805**
2806** pStr holds the text of an expression that we are building up one term
2807** at a time. This routine adds a new term to the end of the expression.
2808** Terms are separated by AND so add the "AND" text for second and subsequent
2809** terms only.
2810*/
2811static void explainAppendTerm(
2812 StrAccum *pStr, /* The text expression being built */
2813 int iTerm, /* Index of this term. First is zero */
2814 const char *zColumn, /* Name of the column */
2815 const char *zOp /* Name of the operator */
2816){
2817 if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
drha6353a32013-12-09 19:03:26 +00002818 sqlite3StrAccumAppendAll(pStr, zColumn);
drh69174c42010-11-12 15:35:59 +00002819 sqlite3StrAccumAppend(pStr, zOp, 1);
2820 sqlite3StrAccumAppend(pStr, "?", 1);
2821}
2822
2823/*
dan17c0bc02010-11-09 17:35:19 +00002824** Argument pLevel describes a strategy for scanning table pTab. This
drh6c977892014-10-10 15:47:46 +00002825** function appends text to pStr that describes the subset of table
2826** rows scanned by the strategy in the form of an SQL expression.
dan17c0bc02010-11-09 17:35:19 +00002827**
2828** For example, if the query:
2829**
2830** SELECT * FROM t1 WHERE a=1 AND b>2;
2831**
2832** is run and there is an index on (a, b), then this function returns a
2833** string similar to:
2834**
2835** "a=? AND b>?"
dan17c0bc02010-11-09 17:35:19 +00002836*/
drh1f8817c2014-10-10 19:15:35 +00002837static void explainIndexRange(StrAccum *pStr, WhereLoop *pLoop, Table *pTab){
drhef866372013-05-22 20:49:02 +00002838 Index *pIndex = pLoop->u.btree.pIndex;
drhcd8629e2013-11-13 12:27:25 +00002839 u16 nEq = pLoop->u.btree.nEq;
drhc8bbce12014-10-21 01:05:09 +00002840 u16 nSkip = pLoop->nSkip;
drh69174c42010-11-12 15:35:59 +00002841 int i, j;
2842 Column *aCol = pTab->aCol;
drhbbbdc832013-10-22 18:01:40 +00002843 i16 *aiColumn = pIndex->aiColumn;
dan2ce22452010-11-08 19:01:16 +00002844
drh6c977892014-10-10 15:47:46 +00002845 if( nEq==0 && (pLoop->wsFlags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ) return;
2846 sqlite3StrAccumAppend(pStr, " (", 2);
dan2ce22452010-11-08 19:01:16 +00002847 for(i=0; i<nEq; i++){
dan39129ce2014-06-30 15:23:57 +00002848 char *z = aiColumn[i] < 0 ? "rowid" : aCol[aiColumn[i]].zName;
drhcd8629e2013-11-13 12:27:25 +00002849 if( i>=nSkip ){
drh6c977892014-10-10 15:47:46 +00002850 explainAppendTerm(pStr, i, z, "=");
drhcd8629e2013-11-13 12:27:25 +00002851 }else{
drh6c977892014-10-10 15:47:46 +00002852 if( i ) sqlite3StrAccumAppend(pStr, " AND ", 5);
2853 sqlite3XPrintf(pStr, 0, "ANY(%s)", z);
drhcd8629e2013-11-13 12:27:25 +00002854 }
dan2ce22452010-11-08 19:01:16 +00002855 }
2856
drh69174c42010-11-12 15:35:59 +00002857 j = i;
drhef866372013-05-22 20:49:02 +00002858 if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
dan39129ce2014-06-30 15:23:57 +00002859 char *z = aiColumn[j] < 0 ? "rowid" : aCol[aiColumn[j]].zName;
drh6c977892014-10-10 15:47:46 +00002860 explainAppendTerm(pStr, i++, z, ">");
dan2ce22452010-11-08 19:01:16 +00002861 }
drhef866372013-05-22 20:49:02 +00002862 if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
dan39129ce2014-06-30 15:23:57 +00002863 char *z = aiColumn[j] < 0 ? "rowid" : aCol[aiColumn[j]].zName;
drh6c977892014-10-10 15:47:46 +00002864 explainAppendTerm(pStr, i, z, "<");
dan2ce22452010-11-08 19:01:16 +00002865 }
drh6c977892014-10-10 15:47:46 +00002866 sqlite3StrAccumAppend(pStr, ")", 1);
dan2ce22452010-11-08 19:01:16 +00002867}
2868
dan17c0bc02010-11-09 17:35:19 +00002869/*
2870** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
dan037b5322014-11-03 11:25:32 +00002871** command, or if either SQLITE_DEBUG or SQLITE_ENABLE_STMT_SCANSTATUS was
2872** defined at compile-time. If it is not a no-op, a single OP_Explain opcode
2873** is added to the output to describe the table scan strategy in pLevel.
2874**
2875** If an OP_Explain opcode is added to the VM, its address is returned.
2876** Otherwise, if no OP_Explain is coded, zero is returned.
dan17c0bc02010-11-09 17:35:19 +00002877*/
dan6f9702e2014-11-01 20:38:06 +00002878static int explainOneScan(
dan2ce22452010-11-08 19:01:16 +00002879 Parse *pParse, /* Parse context */
2880 SrcList *pTabList, /* Table list this loop refers to */
dan6f9702e2014-11-01 20:38:06 +00002881 WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
dan2ce22452010-11-08 19:01:16 +00002882 int iLevel, /* Value for "level" column of output */
dan6f9702e2014-11-01 20:38:06 +00002883 int iFrom, /* Value for "from" column of output */
dan4a07e3d2010-11-09 14:48:59 +00002884 u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
dan2ce22452010-11-08 19:01:16 +00002885){
dan6f9702e2014-11-01 20:38:06 +00002886 int ret = 0;
dan43764a82014-11-01 21:00:04 +00002887#if !defined(SQLITE_DEBUG) && !defined(SQLITE_ENABLE_STMT_SCANSTATUS)
drh84e55a82013-11-13 17:58:23 +00002888 if( pParse->explain==2 )
2889#endif
2890 {
dan2ce22452010-11-08 19:01:16 +00002891 struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
dan17c0bc02010-11-09 17:35:19 +00002892 Vdbe *v = pParse->pVdbe; /* VM being constructed */
2893 sqlite3 *db = pParse->db; /* Database handle */
dan6f9702e2014-11-01 20:38:06 +00002894 int iId = pParse->iSelectId; /* Select id (left-most output column) */
dan4bc39fa2010-11-13 16:42:27 +00002895 int isSearch; /* True for a SEARCH. False for SCAN. */
drhef866372013-05-22 20:49:02 +00002896 WhereLoop *pLoop; /* The controlling WhereLoop object */
2897 u32 flags; /* Flags that describe this loop */
dan6f9702e2014-11-01 20:38:06 +00002898 char *zMsg; /* Text to add to EQP output */
drh6c977892014-10-10 15:47:46 +00002899 StrAccum str; /* EQP output string */
2900 char zBuf[100]; /* Initial space for EQP output string */
dan2ce22452010-11-08 19:01:16 +00002901
drhef866372013-05-22 20:49:02 +00002902 pLoop = pLevel->pWLoop;
2903 flags = pLoop->wsFlags;
dan6f9702e2014-11-01 20:38:06 +00002904 if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return 0;
dan2ce22452010-11-08 19:01:16 +00002905
drhef866372013-05-22 20:49:02 +00002906 isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
2907 || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
2908 || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
dan6f9702e2014-11-01 20:38:06 +00002909
2910 sqlite3StrAccumInit(&str, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH);
2911 str.db = db;
drh6c977892014-10-10 15:47:46 +00002912 sqlite3StrAccumAppendAll(&str, isSearch ? "SEARCH" : "SCAN");
dan4a07e3d2010-11-09 14:48:59 +00002913 if( pItem->pSelect ){
drh6c977892014-10-10 15:47:46 +00002914 sqlite3XPrintf(&str, 0, " SUBQUERY %d", pItem->iSelectId);
dan4a07e3d2010-11-09 14:48:59 +00002915 }else{
drh6c977892014-10-10 15:47:46 +00002916 sqlite3XPrintf(&str, 0, " TABLE %s", pItem->zName);
dan4a07e3d2010-11-09 14:48:59 +00002917 }
2918
dan2ce22452010-11-08 19:01:16 +00002919 if( pItem->zAlias ){
drh6c977892014-10-10 15:47:46 +00002920 sqlite3XPrintf(&str, 0, " AS %s", pItem->zAlias);
dan2ce22452010-11-08 19:01:16 +00002921 }
drh6c977892014-10-10 15:47:46 +00002922 if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0 ){
2923 const char *zFmt = 0;
2924 Index *pIdx;
2925
2926 assert( pLoop->u.btree.pIndex!=0 );
2927 pIdx = pLoop->u.btree.pIndex;
dane96f2df2014-05-23 17:17:06 +00002928 assert( !(flags&WHERE_AUTO_INDEX) || (flags&WHERE_IDX_ONLY) );
drh48dd1d82014-05-27 18:18:58 +00002929 if( !HasRowid(pItem->pTab) && IsPrimaryKeyIndex(pIdx) ){
drhc631faa2014-10-11 01:22:16 +00002930 if( isSearch ){
drh6c977892014-10-10 15:47:46 +00002931 zFmt = "PRIMARY KEY";
2932 }
drh051575c2014-10-25 12:28:25 +00002933 }else if( flags & WHERE_PARTIALIDX ){
2934 zFmt = "AUTOMATIC PARTIAL COVERING INDEX";
dane96f2df2014-05-23 17:17:06 +00002935 }else if( flags & WHERE_AUTO_INDEX ){
drh6c977892014-10-10 15:47:46 +00002936 zFmt = "AUTOMATIC COVERING INDEX";
dane96f2df2014-05-23 17:17:06 +00002937 }else if( flags & WHERE_IDX_ONLY ){
drh6c977892014-10-10 15:47:46 +00002938 zFmt = "COVERING INDEX %s";
dane96f2df2014-05-23 17:17:06 +00002939 }else{
drh6c977892014-10-10 15:47:46 +00002940 zFmt = "INDEX %s";
dane96f2df2014-05-23 17:17:06 +00002941 }
drh6c977892014-10-10 15:47:46 +00002942 if( zFmt ){
2943 sqlite3StrAccumAppend(&str, " USING ", 7);
2944 sqlite3XPrintf(&str, 0, zFmt, pIdx->zName);
2945 explainIndexRange(&str, pLoop, pItem->pTab);
2946 }
drhef71c1f2013-06-04 12:58:02 +00002947 }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
drh6c977892014-10-10 15:47:46 +00002948 const char *zRange;
drh8e23daf2013-06-11 13:30:04 +00002949 if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
drh6c977892014-10-10 15:47:46 +00002950 zRange = "(rowid=?)";
drh04098e62010-11-15 21:50:19 +00002951 }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
drh6c977892014-10-10 15:47:46 +00002952 zRange = "(rowid>? AND rowid<?)";
dan2ce22452010-11-08 19:01:16 +00002953 }else if( flags&WHERE_BTM_LIMIT ){
drh6c977892014-10-10 15:47:46 +00002954 zRange = "(rowid>?)";
2955 }else{
2956 assert( flags&WHERE_TOP_LIMIT);
2957 zRange = "(rowid<?)";
dan2ce22452010-11-08 19:01:16 +00002958 }
drh6c977892014-10-10 15:47:46 +00002959 sqlite3StrAccumAppendAll(&str, " USING INTEGER PRIMARY KEY ");
2960 sqlite3StrAccumAppendAll(&str, zRange);
dan2ce22452010-11-08 19:01:16 +00002961 }
2962#ifndef SQLITE_OMIT_VIRTUALTABLE
2963 else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
drh6c977892014-10-10 15:47:46 +00002964 sqlite3XPrintf(&str, 0, " VIRTUAL TABLE INDEX %d:%s",
drhef866372013-05-22 20:49:02 +00002965 pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
dan2ce22452010-11-08 19:01:16 +00002966 }
2967#endif
drh98545bb2014-10-10 17:20:39 +00002968#ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS
dan6f9702e2014-11-01 20:38:06 +00002969 if( pLoop->nOut>=10 ){
2970 sqlite3XPrintf(&str, 0, " (~%llu rows)", sqlite3LogEstToInt(pLoop->nOut));
2971 }else{
2972 sqlite3StrAccumAppend(&str, " (~1 row)", 9);
dan04489b62014-10-31 20:11:32 +00002973 }
dan6f9702e2014-11-01 20:38:06 +00002974#endif
2975 zMsg = sqlite3StrAccumFinish(&str);
2976 ret = sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg,P4_DYNAMIC);
dan2ce22452010-11-08 19:01:16 +00002977 }
dan6f9702e2014-11-01 20:38:06 +00002978 return ret;
dan2ce22452010-11-08 19:01:16 +00002979}
2980#else
dan6f9702e2014-11-01 20:38:06 +00002981# define explainOneScan(u,v,w,x,y,z) 0
2982#endif /* SQLITE_OMIT_EXPLAIN */
2983
2984#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
dan037b5322014-11-03 11:25:32 +00002985/*
2986** Configure the VM passed as the first argument with an
2987** sqlite3_stmt_scanstatus() entry corresponding to the scan used to
2988** implement level pLvl. Argument pSrclist is a pointer to the FROM
2989** clause that the scan reads data from.
2990**
2991** If argument addrExplain is not 0, it must be the address of an
2992** OP_Explain instruction that describes the same loop.
2993*/
dan6f9702e2014-11-01 20:38:06 +00002994static void addScanStatus(
dan037b5322014-11-03 11:25:32 +00002995 Vdbe *v, /* Vdbe to add scanstatus entry to */
2996 SrcList *pSrclist, /* FROM clause pLvl reads data from */
2997 WhereLevel *pLvl, /* Level to add scanstatus() entry for */
2998 int addrExplain /* Address of OP_Explain (or 0) */
dan6f9702e2014-11-01 20:38:06 +00002999){
3000 const char *zObj = 0;
dan6f9702e2014-11-01 20:38:06 +00003001 WhereLoop *pLoop = pLvl->pWLoop;
drhcd934c32014-12-05 21:18:19 +00003002 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 && pLoop->u.btree.pIndex!=0 ){
dan6f9702e2014-11-01 20:38:06 +00003003 zObj = pLoop->u.btree.pIndex->zName;
3004 }else{
3005 zObj = pSrclist->a[pLvl->iFrom].zName;
3006 }
dan037b5322014-11-03 11:25:32 +00003007 sqlite3VdbeScanStatus(
drh518140e2014-11-06 03:55:10 +00003008 v, addrExplain, pLvl->addrBody, pLvl->addrVisit, pLoop->nOut, zObj
dan6f9702e2014-11-01 20:38:06 +00003009 );
3010}
3011#else
dane2f771b2014-11-03 15:33:17 +00003012# define addScanStatus(a, b, c, d) ((void)d)
dan6f9702e2014-11-01 20:38:06 +00003013#endif
3014
drhf07cf6e2015-03-06 16:45:16 +00003015/*
drha40da622015-03-09 12:11:56 +00003016** If the most recently coded instruction is a constant range contraint
3017** that originated from the LIKE optimization, then change the P3 to be
drhf07cf6e2015-03-06 16:45:16 +00003018** pLoop->iLikeRepCntr and set P5.
3019**
drh16897072015-03-07 00:57:37 +00003020** The LIKE optimization trys to evaluate "x LIKE 'abc%'" as a range
3021** expression: "x>='ABC' AND x<'abd'". But this requires that the range
3022** scan loop run twice, once for strings and a second time for BLOBs.
3023** The OP_String opcodes on the second pass convert the upper and lower
3024** bound string contants to blobs. This routine makes the necessary changes
3025** to the OP_String opcodes for that to happen.
drhf07cf6e2015-03-06 16:45:16 +00003026*/
drh52fc05b2015-03-07 20:32:49 +00003027static void whereLikeOptimizationStringFixup(
3028 Vdbe *v, /* prepared statement under construction */
3029 WhereLevel *pLevel, /* The loop that contains the LIKE operator */
3030 WhereTerm *pTerm /* The upper or lower bound just coded */
3031){
3032 if( pTerm->wtFlags & TERM_LIKEOPT ){
drha40da622015-03-09 12:11:56 +00003033 VdbeOp *pOp;
3034 assert( pLevel->iLikeRepCntr>0 );
3035 pOp = sqlite3VdbeGetOp(v, -1);
3036 assert( pOp!=0 );
3037 assert( pOp->opcode==OP_String8
3038 || pTerm->pWC->pWInfo->pParse->db->mallocFailed );
3039 pOp->p3 = pLevel->iLikeRepCntr;
3040 pOp->p5 = 1;
drhf07cf6e2015-03-06 16:45:16 +00003041 }
3042}
dan2ce22452010-11-08 19:01:16 +00003043
drh111a6a72008-12-21 03:51:16 +00003044/*
3045** Generate code for the start of the iLevel-th loop in the WHERE clause
3046** implementation described by pWInfo.
3047*/
3048static Bitmask codeOneLoopStart(
3049 WhereInfo *pWInfo, /* Complete information about the WHERE clause */
3050 int iLevel, /* Which level of pWInfo->a[] should be coded */
drh7a484802012-03-16 00:28:11 +00003051 Bitmask notReady /* Which tables are currently available */
drh111a6a72008-12-21 03:51:16 +00003052){
3053 int j, k; /* Loop counters */
3054 int iCur; /* The VDBE cursor for the table */
3055 int addrNxt; /* Where to jump to continue with the next IN case */
3056 int omitTable; /* True if we use the index only */
3057 int bRev; /* True if we need to scan in reverse order */
3058 WhereLevel *pLevel; /* The where level to be coded */
drh7ba39a92013-05-30 17:43:19 +00003059 WhereLoop *pLoop; /* The WhereLoop object being coded */
drh111a6a72008-12-21 03:51:16 +00003060 WhereClause *pWC; /* Decomposition of the entire WHERE clause */
3061 WhereTerm *pTerm; /* A WHERE clause term */
3062 Parse *pParse; /* Parsing context */
drh6b36e822013-07-30 15:10:32 +00003063 sqlite3 *db; /* Database connection */
drh111a6a72008-12-21 03:51:16 +00003064 Vdbe *v; /* The prepared stmt under constructions */
3065 struct SrcList_item *pTabItem; /* FROM clause term being coded */
drh23d04d52008-12-23 23:56:22 +00003066 int addrBrk; /* Jump here to break out of the loop */
3067 int addrCont; /* Jump here to continue with next cycle */
drh61495262009-04-22 15:32:59 +00003068 int iRowidReg = 0; /* Rowid is stored in this register, if not zero */
3069 int iReleaseReg = 0; /* Temp register to free before returning */
drh111a6a72008-12-21 03:51:16 +00003070
3071 pParse = pWInfo->pParse;
3072 v = pParse->pVdbe;
drh70d18342013-06-06 19:16:33 +00003073 pWC = &pWInfo->sWC;
drh6b36e822013-07-30 15:10:32 +00003074 db = pParse->db;
drh111a6a72008-12-21 03:51:16 +00003075 pLevel = &pWInfo->a[iLevel];
drh7ba39a92013-05-30 17:43:19 +00003076 pLoop = pLevel->pWLoop;
drh111a6a72008-12-21 03:51:16 +00003077 pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
3078 iCur = pTabItem->iCursor;
drh0259bc32013-09-09 19:37:46 +00003079 pLevel->notReady = notReady & ~getMask(&pWInfo->sMaskSet, iCur);
drh7ba39a92013-05-30 17:43:19 +00003080 bRev = (pWInfo->revMask>>iLevel)&1;
3081 omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
drh70d18342013-06-06 19:16:33 +00003082 && (pWInfo->wctrlFlags & WHERE_FORCE_TABLE)==0;
drh6bc69a22013-11-19 12:33:23 +00003083 VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName));
drh111a6a72008-12-21 03:51:16 +00003084
3085 /* Create labels for the "break" and "continue" instructions
3086 ** for the current loop. Jump to addrBrk to break out of a loop.
3087 ** Jump to cont to go immediately to the next iteration of the
3088 ** loop.
3089 **
3090 ** When there is an IN operator, we also have a "addrNxt" label that
3091 ** means to continue with the next IN value combination. When
3092 ** there are no IN operators in the constraints, the "addrNxt" label
3093 ** is the same as "addrBrk".
3094 */
3095 addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
3096 addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
3097
3098 /* If this is the right table of a LEFT OUTER JOIN, allocate and
3099 ** initialize a memory cell that records if this table matches any
3100 ** row of the left table of the join.
3101 */
3102 if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
3103 pLevel->iLeftJoin = ++pParse->nMem;
3104 sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
3105 VdbeComment((v, "init LEFT JOIN no-match flag"));
3106 }
3107
drh21172c42012-10-30 00:29:07 +00003108 /* Special case of a FROM clause subquery implemented as a co-routine */
3109 if( pTabItem->viaCoroutine ){
3110 int regYield = pTabItem->regReturn;
drhed71a832014-02-07 19:18:10 +00003111 sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
drh81cf13e2014-02-07 18:27:53 +00003112 pLevel->p2 = sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk);
drh688852a2014-02-17 22:40:43 +00003113 VdbeCoverage(v);
drh725de292014-02-08 13:12:19 +00003114 VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
drh21172c42012-10-30 00:29:07 +00003115 pLevel->op = OP_Goto;
3116 }else
3117
drh111a6a72008-12-21 03:51:16 +00003118#ifndef SQLITE_OMIT_VIRTUALTABLE
drh7ba39a92013-05-30 17:43:19 +00003119 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
3120 /* Case 1: The table is a virtual-table. Use the VFilter and VNext
drh111a6a72008-12-21 03:51:16 +00003121 ** to access the data.
3122 */
3123 int iReg; /* P3 Value for OP_VFilter */
drh281bbe22012-10-16 23:17:14 +00003124 int addrNotFound;
drh4efc9292013-06-06 23:02:03 +00003125 int nConstraint = pLoop->nLTerm;
drh111a6a72008-12-21 03:51:16 +00003126
drha62bb8d2009-11-23 21:23:45 +00003127 sqlite3ExprCachePush(pParse);
drh111a6a72008-12-21 03:51:16 +00003128 iReg = sqlite3GetTempRange(pParse, nConstraint+2);
drh281bbe22012-10-16 23:17:14 +00003129 addrNotFound = pLevel->addrBrk;
drh111a6a72008-12-21 03:51:16 +00003130 for(j=0; j<nConstraint; j++){
drhe2250172013-05-31 18:13:50 +00003131 int iTarget = iReg+j+2;
drh4efc9292013-06-06 23:02:03 +00003132 pTerm = pLoop->aLTerm[j];
drh95ed68d2013-06-12 17:55:50 +00003133 if( pTerm==0 ) continue;
drh7ba39a92013-05-30 17:43:19 +00003134 if( pTerm->eOperator & WO_IN ){
3135 codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
3136 addrNotFound = pLevel->addrNxt;
3137 }else{
3138 sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget);
3139 }
3140 }
3141 sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
drh7e47cb82013-05-31 17:55:27 +00003142 sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
drh7ba39a92013-05-30 17:43:19 +00003143 sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
3144 pLoop->u.vtab.idxStr,
3145 pLoop->u.vtab.needFree ? P4_MPRINTF : P4_STATIC);
drh688852a2014-02-17 22:40:43 +00003146 VdbeCoverage(v);
drh7ba39a92013-05-30 17:43:19 +00003147 pLoop->u.vtab.needFree = 0;
3148 for(j=0; j<nConstraint && j<16; j++){
3149 if( (pLoop->u.vtab.omitMask>>j)&1 ){
drh4efc9292013-06-06 23:02:03 +00003150 disableTerm(pLevel, pLoop->aLTerm[j]);
drh111a6a72008-12-21 03:51:16 +00003151 }
3152 }
3153 pLevel->op = OP_VNext;
3154 pLevel->p1 = iCur;
3155 pLevel->p2 = sqlite3VdbeCurrentAddr(v);
drh23d04d52008-12-23 23:56:22 +00003156 sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
drhd2490902014-04-13 19:28:15 +00003157 sqlite3ExprCachePop(pParse);
drh111a6a72008-12-21 03:51:16 +00003158 }else
3159#endif /* SQLITE_OMIT_VIRTUALTABLE */
3160
drh7ba39a92013-05-30 17:43:19 +00003161 if( (pLoop->wsFlags & WHERE_IPK)!=0
3162 && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
3163 ){
3164 /* Case 2: We can directly reference a single row using an
drh111a6a72008-12-21 03:51:16 +00003165 ** equality comparison against the ROWID field. Or
3166 ** we reference multiple rows using a "rowid IN (...)"
3167 ** construct.
3168 */
drh7ba39a92013-05-30 17:43:19 +00003169 assert( pLoop->u.btree.nEq==1 );
drh4efc9292013-06-06 23:02:03 +00003170 pTerm = pLoop->aLTerm[0];
drh111a6a72008-12-21 03:51:16 +00003171 assert( pTerm!=0 );
3172 assert( pTerm->pExpr!=0 );
drh111a6a72008-12-21 03:51:16 +00003173 assert( omitTable==0 );
drh39759742013-08-02 23:40:45 +00003174 testcase( pTerm->wtFlags & TERM_VIRTUAL );
drh0baa0352014-02-25 21:55:16 +00003175 iReleaseReg = ++pParse->nMem;
drh7ba39a92013-05-30 17:43:19 +00003176 iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
drh0baa0352014-02-25 21:55:16 +00003177 if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg);
drh111a6a72008-12-21 03:51:16 +00003178 addrNxt = pLevel->addrNxt;
drh688852a2014-02-17 22:40:43 +00003179 sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt); VdbeCoverage(v);
danielk19771d461462009-04-21 09:02:45 +00003180 sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
drh688852a2014-02-17 22:40:43 +00003181 VdbeCoverage(v);
drh459f63e2013-03-06 01:55:27 +00003182 sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
drhceea3322009-04-23 13:22:42 +00003183 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
drh111a6a72008-12-21 03:51:16 +00003184 VdbeComment((v, "pk"));
3185 pLevel->op = OP_Noop;
drh7ba39a92013-05-30 17:43:19 +00003186 }else if( (pLoop->wsFlags & WHERE_IPK)!=0
3187 && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
3188 ){
3189 /* Case 3: We have an inequality comparison against the ROWID field.
drh111a6a72008-12-21 03:51:16 +00003190 */
3191 int testOp = OP_Noop;
3192 int start;
3193 int memEndValue = 0;
3194 WhereTerm *pStart, *pEnd;
3195
3196 assert( omitTable==0 );
drh7ba39a92013-05-30 17:43:19 +00003197 j = 0;
3198 pStart = pEnd = 0;
drh4efc9292013-06-06 23:02:03 +00003199 if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
3200 if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
drh81186b42013-06-18 01:52:41 +00003201 assert( pStart!=0 || pEnd!=0 );
drh111a6a72008-12-21 03:51:16 +00003202 if( bRev ){
3203 pTerm = pStart;
3204 pStart = pEnd;
3205 pEnd = pTerm;
3206 }
3207 if( pStart ){
3208 Expr *pX; /* The expression that defines the start bound */
3209 int r1, rTemp; /* Registers for holding the start boundary */
3210
3211 /* The following constant maps TK_xx codes into corresponding
3212 ** seek opcodes. It depends on a particular ordering of TK_xx
3213 */
3214 const u8 aMoveOp[] = {
drh4a1d3652014-02-14 15:13:36 +00003215 /* TK_GT */ OP_SeekGT,
3216 /* TK_LE */ OP_SeekLE,
3217 /* TK_LT */ OP_SeekLT,
3218 /* TK_GE */ OP_SeekGE
drh111a6a72008-12-21 03:51:16 +00003219 };
3220 assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */
3221 assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */
3222 assert( TK_GE==TK_GT+3 ); /* ... is correcct. */
3223
drhb5246e52013-07-08 21:12:57 +00003224 assert( (pStart->wtFlags & TERM_VNULL)==0 );
drh39759742013-08-02 23:40:45 +00003225 testcase( pStart->wtFlags & TERM_VIRTUAL );
drh111a6a72008-12-21 03:51:16 +00003226 pX = pStart->pExpr;
3227 assert( pX!=0 );
drhb5246e52013-07-08 21:12:57 +00003228 testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
drh111a6a72008-12-21 03:51:16 +00003229 r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
3230 sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
drh7d176102014-02-18 03:07:12 +00003231 VdbeComment((v, "pk"));
3232 VdbeCoverageIf(v, pX->op==TK_GT);
3233 VdbeCoverageIf(v, pX->op==TK_LE);
3234 VdbeCoverageIf(v, pX->op==TK_LT);
3235 VdbeCoverageIf(v, pX->op==TK_GE);
drh111a6a72008-12-21 03:51:16 +00003236 sqlite3ExprCacheAffinityChange(pParse, r1, 1);
3237 sqlite3ReleaseTempReg(pParse, rTemp);
3238 disableTerm(pLevel, pStart);
3239 }else{
3240 sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
drh7d176102014-02-18 03:07:12 +00003241 VdbeCoverageIf(v, bRev==0);
3242 VdbeCoverageIf(v, bRev!=0);
drh111a6a72008-12-21 03:51:16 +00003243 }
3244 if( pEnd ){
3245 Expr *pX;
3246 pX = pEnd->pExpr;
3247 assert( pX!=0 );
drhb5246e52013-07-08 21:12:57 +00003248 assert( (pEnd->wtFlags & TERM_VNULL)==0 );
3249 testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
drh39759742013-08-02 23:40:45 +00003250 testcase( pEnd->wtFlags & TERM_VIRTUAL );
drh111a6a72008-12-21 03:51:16 +00003251 memEndValue = ++pParse->nMem;
3252 sqlite3ExprCode(pParse, pX->pRight, memEndValue);
3253 if( pX->op==TK_LT || pX->op==TK_GT ){
3254 testOp = bRev ? OP_Le : OP_Ge;
3255 }else{
3256 testOp = bRev ? OP_Lt : OP_Gt;
3257 }
3258 disableTerm(pLevel, pEnd);
3259 }
3260 start = sqlite3VdbeCurrentAddr(v);
3261 pLevel->op = bRev ? OP_Prev : OP_Next;
3262 pLevel->p1 = iCur;
3263 pLevel->p2 = start;
drh81186b42013-06-18 01:52:41 +00003264 assert( pLevel->p5==0 );
danielk19771d461462009-04-21 09:02:45 +00003265 if( testOp!=OP_Noop ){
drh0baa0352014-02-25 21:55:16 +00003266 iRowidReg = ++pParse->nMem;
danielk19771d461462009-04-21 09:02:45 +00003267 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
drhceea3322009-04-23 13:22:42 +00003268 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
danielk19771d461462009-04-21 09:02:45 +00003269 sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
drh7d176102014-02-18 03:07:12 +00003270 VdbeCoverageIf(v, testOp==OP_Le);
3271 VdbeCoverageIf(v, testOp==OP_Lt);
3272 VdbeCoverageIf(v, testOp==OP_Ge);
3273 VdbeCoverageIf(v, testOp==OP_Gt);
danielk19771d461462009-04-21 09:02:45 +00003274 sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
drh111a6a72008-12-21 03:51:16 +00003275 }
drh1b0f0262013-05-30 22:27:09 +00003276 }else if( pLoop->wsFlags & WHERE_INDEXED ){
drh7ba39a92013-05-30 17:43:19 +00003277 /* Case 4: A scan using an index.
drh111a6a72008-12-21 03:51:16 +00003278 **
3279 ** The WHERE clause may contain zero or more equality
3280 ** terms ("==" or "IN" operators) that refer to the N
3281 ** left-most columns of the index. It may also contain
3282 ** inequality constraints (>, <, >= or <=) on the indexed
3283 ** column that immediately follows the N equalities. Only
3284 ** the right-most column can be an inequality - the rest must
3285 ** use the "==" and "IN" operators. For example, if the
3286 ** index is on (x,y,z), then the following clauses are all
3287 ** optimized:
3288 **
3289 ** x=5
3290 ** x=5 AND y=10
3291 ** x=5 AND y<10
3292 ** x=5 AND y>5 AND y<10
3293 ** x=5 AND y=5 AND z<=10
3294 **
3295 ** The z<10 term of the following cannot be used, only
3296 ** the x=5 term:
3297 **
3298 ** x=5 AND z<10
3299 **
3300 ** N may be zero if there are inequality constraints.
3301 ** If there are no inequality constraints, then N is at
3302 ** least one.
3303 **
3304 ** This case is also used when there are no WHERE clause
3305 ** constraints but an index is selected anyway, in order
3306 ** to force the output order to conform to an ORDER BY.
3307 */
drh3bb9b932010-08-06 02:10:00 +00003308 static const u8 aStartOp[] = {
drh111a6a72008-12-21 03:51:16 +00003309 0,
3310 0,
3311 OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */
3312 OP_Last, /* 3: (!start_constraints && startEq && bRev) */
drh4a1d3652014-02-14 15:13:36 +00003313 OP_SeekGT, /* 4: (start_constraints && !startEq && !bRev) */
3314 OP_SeekLT, /* 5: (start_constraints && !startEq && bRev) */
3315 OP_SeekGE, /* 6: (start_constraints && startEq && !bRev) */
3316 OP_SeekLE /* 7: (start_constraints && startEq && bRev) */
drh111a6a72008-12-21 03:51:16 +00003317 };
drh3bb9b932010-08-06 02:10:00 +00003318 static const u8 aEndOp[] = {
drh4a1d3652014-02-14 15:13:36 +00003319 OP_IdxGE, /* 0: (end_constraints && !bRev && !endEq) */
3320 OP_IdxGT, /* 1: (end_constraints && !bRev && endEq) */
3321 OP_IdxLE, /* 2: (end_constraints && bRev && !endEq) */
3322 OP_IdxLT, /* 3: (end_constraints && bRev && endEq) */
drh111a6a72008-12-21 03:51:16 +00003323 };
drhcd8629e2013-11-13 12:27:25 +00003324 u16 nEq = pLoop->u.btree.nEq; /* Number of == or IN terms */
drh111a6a72008-12-21 03:51:16 +00003325 int regBase; /* Base register holding constraint values */
drh111a6a72008-12-21 03:51:16 +00003326 WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */
3327 WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */
3328 int startEq; /* True if range start uses ==, >= or <= */
3329 int endEq; /* True if range end uses ==, >= or <= */
3330 int start_constraints; /* Start of range is constrained */
3331 int nConstraint; /* Number of constraint terms */
drh3bb9b932010-08-06 02:10:00 +00003332 Index *pIdx; /* The index we will be using */
3333 int iIdxCur; /* The VDBE cursor for the index */
3334 int nExtraReg = 0; /* Number of extra registers needed */
3335 int op; /* Instruction opcode */
dan6ac43392010-06-09 15:47:11 +00003336 char *zStartAff; /* Affinity for start of range constraint */
drh33cad2f2013-11-15 12:41:01 +00003337 char cEndAff = 0; /* Affinity for end of range constraint */
drhcfc6ca42014-02-14 23:49:13 +00003338 u8 bSeekPastNull = 0; /* True to seek past initial nulls */
3339 u8 bStopAtNull = 0; /* Add condition to terminate at NULLs */
drh111a6a72008-12-21 03:51:16 +00003340
drh7ba39a92013-05-30 17:43:19 +00003341 pIdx = pLoop->u.btree.pIndex;
drh111a6a72008-12-21 03:51:16 +00003342 iIdxCur = pLevel->iIdxCur;
drhc8bbce12014-10-21 01:05:09 +00003343 assert( nEq>=pLoop->nSkip );
drh111a6a72008-12-21 03:51:16 +00003344
drh111a6a72008-12-21 03:51:16 +00003345 /* If this loop satisfies a sort order (pOrderBy) request that
3346 ** was passed to this function to implement a "SELECT min(x) ..."
3347 ** query, then the caller will only allow the loop to run for
3348 ** a single iteration. This means that the first row returned
3349 ** should not have a NULL value stored in 'x'. If column 'x' is
3350 ** the first one after the nEq equality constraints in the index,
3351 ** this requires some special handling.
3352 */
drhddba0c22014-03-18 20:33:42 +00003353 assert( pWInfo->pOrderBy==0
3354 || pWInfo->pOrderBy->nExpr==1
3355 || (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0 );
drh70d18342013-06-06 19:16:33 +00003356 if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
drhddba0c22014-03-18 20:33:42 +00003357 && pWInfo->nOBSat>0
drhbbbdc832013-10-22 18:01:40 +00003358 && (pIdx->nKeyCol>nEq)
drh111a6a72008-12-21 03:51:16 +00003359 ){
drhc8bbce12014-10-21 01:05:09 +00003360 assert( pLoop->nSkip==0 );
drhcfc6ca42014-02-14 23:49:13 +00003361 bSeekPastNull = 1;
drh6df2acd2008-12-28 16:55:25 +00003362 nExtraReg = 1;
drh111a6a72008-12-21 03:51:16 +00003363 }
3364
3365 /* Find any inequality constraint terms for the start and end
3366 ** of the range.
3367 */
drh7ba39a92013-05-30 17:43:19 +00003368 j = nEq;
3369 if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
drh4efc9292013-06-06 23:02:03 +00003370 pRangeStart = pLoop->aLTerm[j++];
drh6df2acd2008-12-28 16:55:25 +00003371 nExtraReg = 1;
drh111a6a72008-12-21 03:51:16 +00003372 }
drh7ba39a92013-05-30 17:43:19 +00003373 if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
drh4efc9292013-06-06 23:02:03 +00003374 pRangeEnd = pLoop->aLTerm[j++];
drh6df2acd2008-12-28 16:55:25 +00003375 nExtraReg = 1;
drha40da622015-03-09 12:11:56 +00003376 if( (pRangeEnd->wtFlags & TERM_LIKEOPT)!=0 ){
3377 assert( pRangeStart!=0 );
3378 assert( pRangeStart->wtFlags & TERM_LIKEOPT );
drhf07cf6e2015-03-06 16:45:16 +00003379 pLevel->iLikeRepCntr = ++pParse->nMem;
drhb7c60ba2015-03-07 02:51:59 +00003380 testcase( bRev );
3381 testcase( pIdx->aSortOrder[nEq]==SQLITE_SO_DESC );
3382 sqlite3VdbeAddOp2(v, OP_Integer,
3383 bRev ^ (pIdx->aSortOrder[nEq]==SQLITE_SO_DESC),
3384 pLevel->iLikeRepCntr);
drh16897072015-03-07 00:57:37 +00003385 VdbeComment((v, "LIKE loop counter"));
drhf07cf6e2015-03-06 16:45:16 +00003386 pLevel->addrLikeRep = sqlite3VdbeCurrentAddr(v);
3387 }
drhcfc6ca42014-02-14 23:49:13 +00003388 if( pRangeStart==0
drhcfc6ca42014-02-14 23:49:13 +00003389 && (j = pIdx->aiColumn[nEq])>=0
3390 && pIdx->pTable->aCol[j].notNull==0
3391 ){
3392 bSeekPastNull = 1;
3393 }
drh111a6a72008-12-21 03:51:16 +00003394 }
dan0df163a2014-03-06 12:36:26 +00003395 assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 );
drh111a6a72008-12-21 03:51:16 +00003396
drh6df2acd2008-12-28 16:55:25 +00003397 /* Generate code to evaluate all constraint terms using == or IN
3398 ** and store the values of those terms in an array of registers
3399 ** starting at regBase.
3400 */
drh613ba1e2013-06-15 15:11:45 +00003401 regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
drh33cad2f2013-11-15 12:41:01 +00003402 assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq );
3403 if( zStartAff ) cEndAff = zStartAff[nEq];
drh6df2acd2008-12-28 16:55:25 +00003404 addrNxt = pLevel->addrNxt;
3405
drh111a6a72008-12-21 03:51:16 +00003406 /* If we are doing a reverse order scan on an ascending index, or
3407 ** a forward order scan on a descending index, interchange the
3408 ** start and end terms (pRangeStart and pRangeEnd).
3409 */
drhbbbdc832013-10-22 18:01:40 +00003410 if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
3411 || (bRev && pIdx->nKeyCol==nEq)
dan0c733f62011-11-16 15:27:09 +00003412 ){
drh111a6a72008-12-21 03:51:16 +00003413 SWAP(WhereTerm *, pRangeEnd, pRangeStart);
drhcfc6ca42014-02-14 23:49:13 +00003414 SWAP(u8, bSeekPastNull, bStopAtNull);
drh111a6a72008-12-21 03:51:16 +00003415 }
3416
drh7963b0e2013-06-17 21:37:40 +00003417 testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
3418 testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
3419 testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
3420 testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
drh111a6a72008-12-21 03:51:16 +00003421 startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
3422 endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
3423 start_constraints = pRangeStart || nEq>0;
3424
3425 /* Seek the index cursor to the start of the range. */
3426 nConstraint = nEq;
3427 if( pRangeStart ){
dan69f8bb92009-08-13 19:21:16 +00003428 Expr *pRight = pRangeStart->pExpr->pRight;
3429 sqlite3ExprCode(pParse, pRight, regBase+nEq);
drh52fc05b2015-03-07 20:32:49 +00003430 whereLikeOptimizationStringFixup(v, pLevel, pRangeStart);
drh7d176102014-02-18 03:07:12 +00003431 if( (pRangeStart->wtFlags & TERM_VNULL)==0
3432 && sqlite3ExprCanBeNull(pRight)
3433 ){
3434 sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
3435 VdbeCoverage(v);
drh534230c2011-01-22 00:10:45 +00003436 }
dan6ac43392010-06-09 15:47:11 +00003437 if( zStartAff ){
3438 if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
drh039fc322009-11-17 18:31:47 +00003439 /* Since the comparison is to be performed with no conversions
3440 ** applied to the operands, set the affinity to apply to pRight to
3441 ** SQLITE_AFF_NONE. */
dan6ac43392010-06-09 15:47:11 +00003442 zStartAff[nEq] = SQLITE_AFF_NONE;
drh039fc322009-11-17 18:31:47 +00003443 }
dan6ac43392010-06-09 15:47:11 +00003444 if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
3445 zStartAff[nEq] = SQLITE_AFF_NONE;
drh039fc322009-11-17 18:31:47 +00003446 }
3447 }
drh111a6a72008-12-21 03:51:16 +00003448 nConstraint++;
drh39759742013-08-02 23:40:45 +00003449 testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
drhcfc6ca42014-02-14 23:49:13 +00003450 }else if( bSeekPastNull ){
drh111a6a72008-12-21 03:51:16 +00003451 sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
3452 nConstraint++;
3453 startEq = 0;
3454 start_constraints = 1;
3455 }
drhcfc6ca42014-02-14 23:49:13 +00003456 codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff);
drh111a6a72008-12-21 03:51:16 +00003457 op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
3458 assert( op!=0 );
drh8cff69d2009-11-12 19:59:44 +00003459 sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
drh688852a2014-02-17 22:40:43 +00003460 VdbeCoverage(v);
drh7d176102014-02-18 03:07:12 +00003461 VdbeCoverageIf(v, op==OP_Rewind); testcase( op==OP_Rewind );
3462 VdbeCoverageIf(v, op==OP_Last); testcase( op==OP_Last );
3463 VdbeCoverageIf(v, op==OP_SeekGT); testcase( op==OP_SeekGT );
3464 VdbeCoverageIf(v, op==OP_SeekGE); testcase( op==OP_SeekGE );
3465 VdbeCoverageIf(v, op==OP_SeekLE); testcase( op==OP_SeekLE );
3466 VdbeCoverageIf(v, op==OP_SeekLT); testcase( op==OP_SeekLT );
drh111a6a72008-12-21 03:51:16 +00003467
3468 /* Load the value for the inequality constraint at the end of the
3469 ** range (if any).
3470 */
3471 nConstraint = nEq;
3472 if( pRangeEnd ){
dan69f8bb92009-08-13 19:21:16 +00003473 Expr *pRight = pRangeEnd->pExpr->pRight;
drhf49f3522009-12-30 14:12:38 +00003474 sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
dan69f8bb92009-08-13 19:21:16 +00003475 sqlite3ExprCode(pParse, pRight, regBase+nEq);
drh52fc05b2015-03-07 20:32:49 +00003476 whereLikeOptimizationStringFixup(v, pLevel, pRangeEnd);
drh7d176102014-02-18 03:07:12 +00003477 if( (pRangeEnd->wtFlags & TERM_VNULL)==0
3478 && sqlite3ExprCanBeNull(pRight)
3479 ){
3480 sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
3481 VdbeCoverage(v);
drh534230c2011-01-22 00:10:45 +00003482 }
drh33cad2f2013-11-15 12:41:01 +00003483 if( sqlite3CompareAffinity(pRight, cEndAff)!=SQLITE_AFF_NONE
3484 && !sqlite3ExprNeedsNoAffinityChange(pRight, cEndAff)
3485 ){
3486 codeApplyAffinity(pParse, regBase+nEq, 1, &cEndAff);
3487 }
drh111a6a72008-12-21 03:51:16 +00003488 nConstraint++;
drh39759742013-08-02 23:40:45 +00003489 testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
drhcfc6ca42014-02-14 23:49:13 +00003490 }else if( bStopAtNull ){
3491 sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
3492 endEq = 0;
3493 nConstraint++;
drh111a6a72008-12-21 03:51:16 +00003494 }
drh6b36e822013-07-30 15:10:32 +00003495 sqlite3DbFree(db, zStartAff);
drh111a6a72008-12-21 03:51:16 +00003496
3497 /* Top of the loop body */
3498 pLevel->p2 = sqlite3VdbeCurrentAddr(v);
3499
3500 /* Check if the index cursor is past the end of the range. */
drhcfc6ca42014-02-14 23:49:13 +00003501 if( nConstraint ){
drh4a1d3652014-02-14 15:13:36 +00003502 op = aEndOp[bRev*2 + endEq];
drh8cff69d2009-11-12 19:59:44 +00003503 sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
drh7d176102014-02-18 03:07:12 +00003504 testcase( op==OP_IdxGT ); VdbeCoverageIf(v, op==OP_IdxGT );
3505 testcase( op==OP_IdxGE ); VdbeCoverageIf(v, op==OP_IdxGE );
3506 testcase( op==OP_IdxLT ); VdbeCoverageIf(v, op==OP_IdxLT );
3507 testcase( op==OP_IdxLE ); VdbeCoverageIf(v, op==OP_IdxLE );
drh6df2acd2008-12-28 16:55:25 +00003508 }
drh111a6a72008-12-21 03:51:16 +00003509
drh111a6a72008-12-21 03:51:16 +00003510 /* Seek the table cursor, if required */
drh23d04d52008-12-23 23:56:22 +00003511 disableTerm(pLevel, pRangeStart);
3512 disableTerm(pLevel, pRangeEnd);
drh85c1c552013-10-24 00:18:18 +00003513 if( omitTable ){
3514 /* pIdx is a covering index. No need to access the main table. */
3515 }else if( HasRowid(pIdx->pTable) ){
drh0baa0352014-02-25 21:55:16 +00003516 iRowidReg = ++pParse->nMem;
danielk19771d461462009-04-21 09:02:45 +00003517 sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
drhceea3322009-04-23 13:22:42 +00003518 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
danielk19771d461462009-04-21 09:02:45 +00003519 sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg); /* Deferred seek */
drha3bc66a2014-05-27 17:57:32 +00003520 }else if( iCur!=iIdxCur ){
drh85c1c552013-10-24 00:18:18 +00003521 Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
3522 iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol);
3523 for(j=0; j<pPk->nKeyCol; j++){
3524 k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
3525 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j);
3526 }
drh261c02d2013-10-25 14:46:15 +00003527 sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont,
drh688852a2014-02-17 22:40:43 +00003528 iRowidReg, pPk->nKeyCol); VdbeCoverage(v);
drh111a6a72008-12-21 03:51:16 +00003529 }
drh111a6a72008-12-21 03:51:16 +00003530
3531 /* Record the instruction used to terminate the loop. Disable
3532 ** WHERE clause terms made redundant by the index range scan.
3533 */
drh7699d1c2013-06-04 12:42:29 +00003534 if( pLoop->wsFlags & WHERE_ONEROW ){
drh95e037b2011-03-09 21:02:31 +00003535 pLevel->op = OP_Noop;
3536 }else if( bRev ){
3537 pLevel->op = OP_Prev;
3538 }else{
3539 pLevel->op = OP_Next;
3540 }
drh111a6a72008-12-21 03:51:16 +00003541 pLevel->p1 = iIdxCur;
drh0c8a9342014-03-20 12:17:35 +00003542 pLevel->p3 = (pLoop->wsFlags&WHERE_UNQ_WANTED)!=0 ? 1:0;
drh53cfbe92013-06-13 17:28:22 +00003543 if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
drh3f4d1d12012-09-15 18:45:54 +00003544 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
3545 }else{
3546 assert( pLevel->p5==0 );
3547 }
drhdd5f5a62008-12-23 13:35:23 +00003548 }else
3549
drh23d04d52008-12-23 23:56:22 +00003550#ifndef SQLITE_OMIT_OR_OPTIMIZATION
drh7ba39a92013-05-30 17:43:19 +00003551 if( pLoop->wsFlags & WHERE_MULTI_OR ){
3552 /* Case 5: Two or more separately indexed terms connected by OR
drh111a6a72008-12-21 03:51:16 +00003553 **
3554 ** Example:
3555 **
3556 ** CREATE TABLE t1(a,b,c,d);
3557 ** CREATE INDEX i1 ON t1(a);
3558 ** CREATE INDEX i2 ON t1(b);
3559 ** CREATE INDEX i3 ON t1(c);
3560 **
3561 ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
3562 **
3563 ** In the example, there are three indexed terms connected by OR.
danielk19771d461462009-04-21 09:02:45 +00003564 ** The top of the loop looks like this:
drh111a6a72008-12-21 03:51:16 +00003565 **
drh1b26c7c2009-04-22 02:15:47 +00003566 ** Null 1 # Zero the rowset in reg 1
drh111a6a72008-12-21 03:51:16 +00003567 **
danielk19771d461462009-04-21 09:02:45 +00003568 ** Then, for each indexed term, the following. The arguments to
drh1b26c7c2009-04-22 02:15:47 +00003569 ** RowSetTest are such that the rowid of the current row is inserted
3570 ** into the RowSet. If it is already present, control skips the
danielk19771d461462009-04-21 09:02:45 +00003571 ** Gosub opcode and jumps straight to the code generated by WhereEnd().
drh111a6a72008-12-21 03:51:16 +00003572 **
danielk19771d461462009-04-21 09:02:45 +00003573 ** sqlite3WhereBegin(<term>)
drh1b26c7c2009-04-22 02:15:47 +00003574 ** RowSetTest # Insert rowid into rowset
danielk19771d461462009-04-21 09:02:45 +00003575 ** Gosub 2 A
3576 ** sqlite3WhereEnd()
3577 **
3578 ** Following the above, code to terminate the loop. Label A, the target
3579 ** of the Gosub above, jumps to the instruction right after the Goto.
3580 **
drh1b26c7c2009-04-22 02:15:47 +00003581 ** Null 1 # Zero the rowset in reg 1
danielk19771d461462009-04-21 09:02:45 +00003582 ** Goto B # The loop is finished.
3583 **
3584 ** A: <loop body> # Return data, whatever.
3585 **
3586 ** Return 2 # Jump back to the Gosub
3587 **
3588 ** B: <after the loop>
3589 **
drh5609baf2014-05-26 22:01:00 +00003590 ** Added 2014-05-26: If the table is a WITHOUT ROWID table, then
peter.d.reid60ec9142014-09-06 16:39:46 +00003591 ** use an ephemeral index instead of a RowSet to record the primary
drh5609baf2014-05-26 22:01:00 +00003592 ** keys of the rows we have already seen.
3593 **
drh111a6a72008-12-21 03:51:16 +00003594 */
drh111a6a72008-12-21 03:51:16 +00003595 WhereClause *pOrWc; /* The OR-clause broken out into subterms */
drhc01a3c12009-12-16 22:10:49 +00003596 SrcList *pOrTab; /* Shortened table list or OR-clause generation */
dan0efb72c2012-08-24 18:44:56 +00003597 Index *pCov = 0; /* Potential covering index (or NULL) */
3598 int iCovCur = pParse->nTab++; /* Cursor used for index scans (if any) */
danielk19771d461462009-04-21 09:02:45 +00003599
3600 int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */
shane85095702009-06-15 16:27:08 +00003601 int regRowset = 0; /* Register for RowSet object */
3602 int regRowid = 0; /* Register holding rowid */
danielk19771d461462009-04-21 09:02:45 +00003603 int iLoopBody = sqlite3VdbeMakeLabel(v); /* Start of loop body */
3604 int iRetInit; /* Address of regReturn init */
drhc01a3c12009-12-16 22:10:49 +00003605 int untestedTerms = 0; /* Some terms not completely tested */
drh8871ef52011-10-07 13:33:10 +00003606 int ii; /* Loop counter */
drh35263192014-07-22 20:02:19 +00003607 u16 wctrlFlags; /* Flags for sub-WHERE clause */
drh8871ef52011-10-07 13:33:10 +00003608 Expr *pAndExpr = 0; /* An ".. AND (...)" expression */
danf97dad82014-05-26 20:06:45 +00003609 Table *pTab = pTabItem->pTab;
drh111a6a72008-12-21 03:51:16 +00003610
drh4efc9292013-06-06 23:02:03 +00003611 pTerm = pLoop->aLTerm[0];
drh111a6a72008-12-21 03:51:16 +00003612 assert( pTerm!=0 );
drh7a5bcc02013-01-16 17:08:58 +00003613 assert( pTerm->eOperator & WO_OR );
drh111a6a72008-12-21 03:51:16 +00003614 assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
3615 pOrWc = &pTerm->u.pOrInfo->wc;
drhc01a3c12009-12-16 22:10:49 +00003616 pLevel->op = OP_Return;
3617 pLevel->p1 = regReturn;
drh23d04d52008-12-23 23:56:22 +00003618
danbfca6a42012-08-24 10:52:35 +00003619 /* Set up a new SrcList in pOrTab containing the table being scanned
drhc01a3c12009-12-16 22:10:49 +00003620 ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
3621 ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
3622 */
3623 if( pWInfo->nLevel>1 ){
3624 int nNotReady; /* The number of notReady tables */
3625 struct SrcList_item *origSrc; /* Original list of tables */
3626 nNotReady = pWInfo->nLevel - iLevel - 1;
drh6b36e822013-07-30 15:10:32 +00003627 pOrTab = sqlite3StackAllocRaw(db,
drhc01a3c12009-12-16 22:10:49 +00003628 sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
3629 if( pOrTab==0 ) return notReady;
drhad01d892013-06-19 13:59:49 +00003630 pOrTab->nAlloc = (u8)(nNotReady + 1);
shaneh46aae3c2009-12-31 19:06:23 +00003631 pOrTab->nSrc = pOrTab->nAlloc;
drhc01a3c12009-12-16 22:10:49 +00003632 memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
3633 origSrc = pWInfo->pTabList->a;
3634 for(k=1; k<=nNotReady; k++){
3635 memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
3636 }
3637 }else{
3638 pOrTab = pWInfo->pTabList;
3639 }
danielk19771d461462009-04-21 09:02:45 +00003640
drh1b26c7c2009-04-22 02:15:47 +00003641 /* Initialize the rowset register to contain NULL. An SQL NULL is
peter.d.reid60ec9142014-09-06 16:39:46 +00003642 ** equivalent to an empty rowset. Or, create an ephemeral index
drh5609baf2014-05-26 22:01:00 +00003643 ** capable of holding primary keys in the case of a WITHOUT ROWID.
danielk19771d461462009-04-21 09:02:45 +00003644 **
3645 ** Also initialize regReturn to contain the address of the instruction
3646 ** immediately following the OP_Return at the bottom of the loop. This
3647 ** is required in a few obscure LEFT JOIN cases where control jumps
3648 ** over the top of the loop into the body of it. In this case the
3649 ** correct response for the end-of-loop code (the OP_Return) is to
3650 ** fall through to the next instruction, just as an OP_Next does if
3651 ** called on an uninitialized cursor.
3652 */
drh70d18342013-06-06 19:16:33 +00003653 if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
danf97dad82014-05-26 20:06:45 +00003654 if( HasRowid(pTab) ){
3655 regRowset = ++pParse->nMem;
3656 sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
3657 }else{
3658 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
3659 regRowset = pParse->nTab++;
3660 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, regRowset, pPk->nKeyCol);
3661 sqlite3VdbeSetP4KeyInfo(pParse, pPk);
3662 }
drh336a5302009-04-24 15:46:21 +00003663 regRowid = ++pParse->nMem;
drh336a5302009-04-24 15:46:21 +00003664 }
danielk19771d461462009-04-21 09:02:45 +00003665 iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
3666
drh8871ef52011-10-07 13:33:10 +00003667 /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y
3668 ** Then for every term xN, evaluate as the subexpression: xN AND z
3669 ** That way, terms in y that are factored into the disjunction will
3670 ** be picked up by the recursive calls to sqlite3WhereBegin() below.
drh331b67c2012-03-09 22:02:08 +00003671 **
3672 ** Actually, each subexpression is converted to "xN AND w" where w is
3673 ** the "interesting" terms of z - terms that did not originate in the
3674 ** ON or USING clause of a LEFT JOIN, and terms that are usable as
3675 ** indices.
drhb3129fa2013-05-09 14:20:11 +00003676 **
3677 ** This optimization also only applies if the (x1 OR x2 OR ...) term
3678 ** is not contained in the ON clause of a LEFT JOIN.
3679 ** See ticket http://www.sqlite.org/src/info/f2369304e4
drh8871ef52011-10-07 13:33:10 +00003680 */
3681 if( pWC->nTerm>1 ){
drh7a484802012-03-16 00:28:11 +00003682 int iTerm;
3683 for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
3684 Expr *pExpr = pWC->a[iTerm].pExpr;
drhaa32e3c2013-07-16 21:31:23 +00003685 if( &pWC->a[iTerm] == pTerm ) continue;
drh331b67c2012-03-09 22:02:08 +00003686 if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
drh1d324882014-12-04 20:24:50 +00003687 if( (pWC->a[iTerm].wtFlags & TERM_VIRTUAL)!=0 ) continue;
drh7a484802012-03-16 00:28:11 +00003688 if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
drh1d324882014-12-04 20:24:50 +00003689 testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO );
drh6b36e822013-07-30 15:10:32 +00003690 pExpr = sqlite3ExprDup(db, pExpr, 0);
3691 pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr);
drh331b67c2012-03-09 22:02:08 +00003692 }
3693 if( pAndExpr ){
3694 pAndExpr = sqlite3PExpr(pParse, TK_AND, 0, pAndExpr, 0);
3695 }
drh8871ef52011-10-07 13:33:10 +00003696 }
3697
drh3fb67302014-05-27 16:41:39 +00003698 /* Run a separate WHERE clause for each term of the OR clause. After
3699 ** eliminating duplicates from other WHERE clauses, the action for each
3700 ** sub-WHERE clause is to to invoke the main loop body as a subroutine.
3701 */
drh36be4c42014-09-30 17:31:23 +00003702 wctrlFlags = WHERE_OMIT_OPEN_CLOSE
3703 | WHERE_FORCE_TABLE
drh8e8e7ef2015-03-02 17:25:00 +00003704 | WHERE_ONETABLE_ONLY
3705 | WHERE_NO_AUTOINDEX;
danielk19771d461462009-04-21 09:02:45 +00003706 for(ii=0; ii<pOrWc->nTerm; ii++){
3707 WhereTerm *pOrTerm = &pOrWc->a[ii];
drh7a5bcc02013-01-16 17:08:58 +00003708 if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
drh3fb67302014-05-27 16:41:39 +00003709 WhereInfo *pSubWInfo; /* Info for single OR-term scan */
3710 Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */
3711 int j1 = 0; /* Address of jump operation */
drhb3129fa2013-05-09 14:20:11 +00003712 if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){
drh8871ef52011-10-07 13:33:10 +00003713 pAndExpr->pLeft = pOrExpr;
3714 pOrExpr = pAndExpr;
3715 }
danielk19771d461462009-04-21 09:02:45 +00003716 /* Loop through table entries that match term pOrTerm. */
drh0a99ba32014-09-30 17:03:35 +00003717 WHERETRACE(0xffff, ("Subplan for OR-clause:\n"));
drh8871ef52011-10-07 13:33:10 +00003718 pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
drh35263192014-07-22 20:02:19 +00003719 wctrlFlags, iCovCur);
drh6b36e822013-07-30 15:10:32 +00003720 assert( pSubWInfo || pParse->nErr || db->mallocFailed );
danielk19771d461462009-04-21 09:02:45 +00003721 if( pSubWInfo ){
drh7ba39a92013-05-30 17:43:19 +00003722 WhereLoop *pSubLoop;
dan6f9702e2014-11-01 20:38:06 +00003723 int addrExplain = explainOneScan(
3724 pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
3725 );
3726 addScanStatus(v, pOrTab, &pSubWInfo->a[0], addrExplain);
dan89e71642014-11-01 18:08:04 +00003727
drh3fb67302014-05-27 16:41:39 +00003728 /* This is the sub-WHERE clause body. First skip over
3729 ** duplicate rows from prior sub-WHERE clauses, and record the
3730 ** rowid (or PRIMARY KEY) for the current row so that the same
3731 ** row will be skipped in subsequent sub-WHERE clauses.
3732 */
drh70d18342013-06-06 19:16:33 +00003733 if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
drh336a5302009-04-24 15:46:21 +00003734 int r;
danf97dad82014-05-26 20:06:45 +00003735 int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
3736 if( HasRowid(pTab) ){
3737 r = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, regRowid, 0);
drh5609baf2014-05-26 22:01:00 +00003738 j1 = sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, 0, r,iSet);
danf97dad82014-05-26 20:06:45 +00003739 VdbeCoverage(v);
3740 }else{
3741 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
3742 int nPk = pPk->nKeyCol;
3743 int iPk;
3744
3745 /* Read the PK into an array of temp registers. */
3746 r = sqlite3GetTempRange(pParse, nPk);
3747 for(iPk=0; iPk<nPk; iPk++){
3748 int iCol = pPk->aiColumn[iPk];
3749 sqlite3ExprCodeGetColumn(pParse, pTab, iCol, iCur, r+iPk, 0);
3750 }
3751
3752 /* Check if the temp table already contains this key. If so,
3753 ** the row has already been included in the result set and
3754 ** can be ignored (by jumping past the Gosub below). Otherwise,
3755 ** insert the key into the temp table and proceed with processing
3756 ** the row.
3757 **
3758 ** Use some of the same optimizations as OP_RowSetTest: If iSet
3759 ** is zero, assume that the key cannot already be present in
3760 ** the temp table. And if iSet is -1, assume that there is no
3761 ** need to insert the key into the temp table, as it will never
3762 ** be tested for. */
3763 if( iSet ){
drh5609baf2014-05-26 22:01:00 +00003764 j1 = sqlite3VdbeAddOp4Int(v, OP_Found, regRowset, 0, r, nPk);
drh68c12152014-05-26 20:25:34 +00003765 VdbeCoverage(v);
danf97dad82014-05-26 20:06:45 +00003766 }
3767 if( iSet>=0 ){
3768 sqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, regRowid);
3769 sqlite3VdbeAddOp3(v, OP_IdxInsert, regRowset, regRowid, 0);
3770 if( iSet ) sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
3771 }
3772
3773 /* Release the array of temp registers */
3774 sqlite3ReleaseTempRange(pParse, r, nPk);
3775 }
drh336a5302009-04-24 15:46:21 +00003776 }
drh3fb67302014-05-27 16:41:39 +00003777
3778 /* Invoke the main loop body as a subroutine */
danielk19771d461462009-04-21 09:02:45 +00003779 sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
drh3fb67302014-05-27 16:41:39 +00003780
3781 /* Jump here (skipping the main loop body subroutine) if the
3782 ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */
drh5609baf2014-05-26 22:01:00 +00003783 if( j1 ) sqlite3VdbeJumpHere(v, j1);
danielk19771d461462009-04-21 09:02:45 +00003784
drhc01a3c12009-12-16 22:10:49 +00003785 /* The pSubWInfo->untestedTerms flag means that this OR term
3786 ** contained one or more AND term from a notReady table. The
3787 ** terms from the notReady table could not be tested and will
3788 ** need to be tested later.
3789 */
3790 if( pSubWInfo->untestedTerms ) untestedTerms = 1;
3791
danbfca6a42012-08-24 10:52:35 +00003792 /* If all of the OR-connected terms are optimized using the same
3793 ** index, and the index is opened using the same cursor number
3794 ** by each call to sqlite3WhereBegin() made by this loop, it may
3795 ** be possible to use that index as a covering index.
3796 **
3797 ** If the call to sqlite3WhereBegin() above resulted in a scan that
3798 ** uses an index, and this is either the first OR-connected term
3799 ** processed or the index is the same as that used by all previous
dan0efb72c2012-08-24 18:44:56 +00003800 ** terms, set pCov to the candidate covering index. Otherwise, set
3801 ** pCov to NULL to indicate that no candidate covering index will
3802 ** be available.
danbfca6a42012-08-24 10:52:35 +00003803 */
drh7ba39a92013-05-30 17:43:19 +00003804 pSubLoop = pSubWInfo->a[0].pWLoop;
drh986b3872013-06-28 21:12:20 +00003805 assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
drh7ba39a92013-05-30 17:43:19 +00003806 if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
drh7ba39a92013-05-30 17:43:19 +00003807 && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
drh48dd1d82014-05-27 18:18:58 +00003808 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pSubLoop->u.btree.pIndex))
danbfca6a42012-08-24 10:52:35 +00003809 ){
drh7ba39a92013-05-30 17:43:19 +00003810 assert( pSubWInfo->a[0].iIdxCur==iCovCur );
drh907717f2013-06-04 18:03:22 +00003811 pCov = pSubLoop->u.btree.pIndex;
drh35263192014-07-22 20:02:19 +00003812 wctrlFlags |= WHERE_REOPEN_IDX;
danbfca6a42012-08-24 10:52:35 +00003813 }else{
3814 pCov = 0;
3815 }
3816
danielk19771d461462009-04-21 09:02:45 +00003817 /* Finish the loop through table entries that match term pOrTerm. */
3818 sqlite3WhereEnd(pSubWInfo);
3819 }
drhdd5f5a62008-12-23 13:35:23 +00003820 }
3821 }
drhd40e2082012-08-24 23:24:15 +00003822 pLevel->u.pCovidx = pCov;
drh90abfd02012-10-09 21:07:23 +00003823 if( pCov ) pLevel->iIdxCur = iCovCur;
drh331b67c2012-03-09 22:02:08 +00003824 if( pAndExpr ){
3825 pAndExpr->pLeft = 0;
drh6b36e822013-07-30 15:10:32 +00003826 sqlite3ExprDelete(db, pAndExpr);
drh331b67c2012-03-09 22:02:08 +00003827 }
danielk19771d461462009-04-21 09:02:45 +00003828 sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
danielk19771d461462009-04-21 09:02:45 +00003829 sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
3830 sqlite3VdbeResolveLabel(v, iLoopBody);
3831
drh6b36e822013-07-30 15:10:32 +00003832 if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab);
drhc01a3c12009-12-16 22:10:49 +00003833 if( !untestedTerms ) disableTerm(pLevel, pTerm);
drhdd5f5a62008-12-23 13:35:23 +00003834 }else
drh23d04d52008-12-23 23:56:22 +00003835#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
drhdd5f5a62008-12-23 13:35:23 +00003836
3837 {
drh7ba39a92013-05-30 17:43:19 +00003838 /* Case 6: There is no usable index. We must do a complete
drh111a6a72008-12-21 03:51:16 +00003839 ** scan of the entire table.
3840 */
drh699b3d42009-02-23 16:52:07 +00003841 static const u8 aStep[] = { OP_Next, OP_Prev };
3842 static const u8 aStart[] = { OP_Rewind, OP_Last };
3843 assert( bRev==0 || bRev==1 );
drhe73f0592014-01-21 22:25:45 +00003844 if( pTabItem->isRecursive ){
drh340309f2014-01-22 00:23:49 +00003845 /* Tables marked isRecursive have only a single row that is stored in
dan41028152014-01-22 10:22:25 +00003846 ** a pseudo-cursor. No need to Rewind or Next such cursors. */
drhe73f0592014-01-21 22:25:45 +00003847 pLevel->op = OP_Noop;
3848 }else{
3849 pLevel->op = aStep[bRev];
3850 pLevel->p1 = iCur;
3851 pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
drh7d176102014-02-18 03:07:12 +00003852 VdbeCoverageIf(v, bRev==0);
3853 VdbeCoverageIf(v, bRev!=0);
drhe73f0592014-01-21 22:25:45 +00003854 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
3855 }
drh111a6a72008-12-21 03:51:16 +00003856 }
drh111a6a72008-12-21 03:51:16 +00003857
dan6f9702e2014-11-01 20:38:06 +00003858#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
3859 pLevel->addrVisit = sqlite3VdbeCurrentAddr(v);
3860#endif
3861
drh111a6a72008-12-21 03:51:16 +00003862 /* Insert code to test every subexpression that can be completely
3863 ** computed using the current set of tables.
3864 */
drh111a6a72008-12-21 03:51:16 +00003865 for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
3866 Expr *pE;
drh8f1a7ed2015-03-06 19:47:38 +00003867 int skipLikeAddr = 0;
drh39759742013-08-02 23:40:45 +00003868 testcase( pTerm->wtFlags & TERM_VIRTUAL );
drh111a6a72008-12-21 03:51:16 +00003869 testcase( pTerm->wtFlags & TERM_CODED );
3870 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
drh0259bc32013-09-09 19:37:46 +00003871 if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
drhc01a3c12009-12-16 22:10:49 +00003872 testcase( pWInfo->untestedTerms==0
3873 && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
3874 pWInfo->untestedTerms = 1;
3875 continue;
3876 }
drh111a6a72008-12-21 03:51:16 +00003877 pE = pTerm->pExpr;
3878 assert( pE!=0 );
3879 if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
3880 continue;
3881 }
drh8f1a7ed2015-03-06 19:47:38 +00003882 if( pTerm->wtFlags & TERM_LIKECOND ){
3883 assert( pLevel->iLikeRepCntr>0 );
drh16897072015-03-07 00:57:37 +00003884 skipLikeAddr = sqlite3VdbeAddOp1(v, OP_IfNot, pLevel->iLikeRepCntr);
drh8f1a7ed2015-03-06 19:47:38 +00003885 VdbeCoverage(v);
3886 }
drh111a6a72008-12-21 03:51:16 +00003887 sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
drh8f1a7ed2015-03-06 19:47:38 +00003888 if( skipLikeAddr ) sqlite3VdbeJumpHere(v, skipLikeAddr);
drh111a6a72008-12-21 03:51:16 +00003889 pTerm->wtFlags |= TERM_CODED;
3890 }
3891
drh0c41d222013-04-22 02:39:10 +00003892 /* Insert code to test for implied constraints based on transitivity
3893 ** of the "==" operator.
3894 **
3895 ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
3896 ** and we are coding the t1 loop and the t2 loop has not yet coded,
3897 ** then we cannot use the "t1.a=t2.b" constraint, but we can code
3898 ** the implied "t1.a=123" constraint.
3899 */
3900 for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
drh6b36e822013-07-30 15:10:32 +00003901 Expr *pE, *pEAlt;
drh0c41d222013-04-22 02:39:10 +00003902 WhereTerm *pAlt;
drh0c41d222013-04-22 02:39:10 +00003903 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
3904 if( pTerm->eOperator!=(WO_EQUIV|WO_EQ) ) continue;
3905 if( pTerm->leftCursor!=iCur ) continue;
drhcdc2e432013-07-01 17:27:19 +00003906 if( pLevel->iLeftJoin ) continue;
drh0c41d222013-04-22 02:39:10 +00003907 pE = pTerm->pExpr;
3908 assert( !ExprHasProperty(pE, EP_FromJoin) );
drh0259bc32013-09-09 19:37:46 +00003909 assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
drh0c41d222013-04-22 02:39:10 +00003910 pAlt = findTerm(pWC, iCur, pTerm->u.leftColumn, notReady, WO_EQ|WO_IN, 0);
3911 if( pAlt==0 ) continue;
drh5c10f3b2013-05-01 17:22:38 +00003912 if( pAlt->wtFlags & (TERM_CODED) ) continue;
drh7963b0e2013-06-17 21:37:40 +00003913 testcase( pAlt->eOperator & WO_EQ );
3914 testcase( pAlt->eOperator & WO_IN );
drh6bc69a22013-11-19 12:33:23 +00003915 VdbeModuleComment((v, "begin transitive constraint"));
drh6b36e822013-07-30 15:10:32 +00003916 pEAlt = sqlite3StackAllocRaw(db, sizeof(*pEAlt));
3917 if( pEAlt ){
3918 *pEAlt = *pAlt->pExpr;
3919 pEAlt->pLeft = pE->pLeft;
3920 sqlite3ExprIfFalse(pParse, pEAlt, addrCont, SQLITE_JUMPIFNULL);
3921 sqlite3StackFree(db, pEAlt);
3922 }
drh0c41d222013-04-22 02:39:10 +00003923 }
3924
drh111a6a72008-12-21 03:51:16 +00003925 /* For a LEFT OUTER JOIN, generate code that will record the fact that
3926 ** at least one row of the right table has matched the left table.
3927 */
3928 if( pLevel->iLeftJoin ){
3929 pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
3930 sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
3931 VdbeComment((v, "record LEFT JOIN hit"));
drhceea3322009-04-23 13:22:42 +00003932 sqlite3ExprCacheClear(pParse);
drh111a6a72008-12-21 03:51:16 +00003933 for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
drh39759742013-08-02 23:40:45 +00003934 testcase( pTerm->wtFlags & TERM_VIRTUAL );
drh111a6a72008-12-21 03:51:16 +00003935 testcase( pTerm->wtFlags & TERM_CODED );
3936 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
drh0259bc32013-09-09 19:37:46 +00003937 if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
drhb057e562009-12-16 23:43:55 +00003938 assert( pWInfo->untestedTerms );
drhc01a3c12009-12-16 22:10:49 +00003939 continue;
3940 }
drh111a6a72008-12-21 03:51:16 +00003941 assert( pTerm->pExpr );
3942 sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
3943 pTerm->wtFlags |= TERM_CODED;
3944 }
3945 }
drh23d04d52008-12-23 23:56:22 +00003946
drh0259bc32013-09-09 19:37:46 +00003947 return pLevel->notReady;
drh111a6a72008-12-21 03:51:16 +00003948}
3949
drhd15cb172013-05-21 19:23:10 +00003950#ifdef WHERETRACE_ENABLED
drha18f3d22013-05-08 03:05:41 +00003951/*
drhc90713d2014-09-30 13:46:49 +00003952** Print the content of a WhereTerm object
3953*/
3954static void whereTermPrint(WhereTerm *pTerm, int iTerm){
drh0a99ba32014-09-30 17:03:35 +00003955 if( pTerm==0 ){
3956 sqlite3DebugPrintf("TERM-%-3d NULL\n", iTerm);
3957 }else{
3958 char zType[4];
3959 memcpy(zType, "...", 4);
3960 if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V';
3961 if( pTerm->eOperator & WO_EQUIV ) zType[1] = 'E';
3962 if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) zType[2] = 'L';
3963 sqlite3DebugPrintf("TERM-%-3d %p %s cursor=%-3d prob=%-3d op=0x%03x\n",
3964 iTerm, pTerm, zType, pTerm->leftCursor, pTerm->truthProb,
3965 pTerm->eOperator);
3966 sqlite3TreeViewExpr(0, pTerm->pExpr, 0);
3967 }
drhc90713d2014-09-30 13:46:49 +00003968}
3969#endif
3970
3971#ifdef WHERETRACE_ENABLED
3972/*
drha18f3d22013-05-08 03:05:41 +00003973** Print a WhereLoop object for debugging purposes
3974*/
drhc1ba2e72013-10-28 19:03:21 +00003975static void whereLoopPrint(WhereLoop *p, WhereClause *pWC){
3976 WhereInfo *pWInfo = pWC->pWInfo;
drh989578e2013-10-28 14:34:35 +00003977 int nb = 1+(pWInfo->pTabList->nSrc+7)/8;
3978 struct SrcList_item *pItem = pWInfo->pTabList->a + p->iTab;
drha18f3d22013-05-08 03:05:41 +00003979 Table *pTab = pItem->pTab;
drh6457a352013-06-21 00:35:37 +00003980 sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
drha184fb82013-05-08 04:22:59 +00003981 p->iTab, nb, p->maskSelf, nb, p->prereq);
drh6457a352013-06-21 00:35:37 +00003982 sqlite3DebugPrintf(" %12s",
drha18f3d22013-05-08 03:05:41 +00003983 pItem->zAlias ? pItem->zAlias : pTab->zName);
drh5346e952013-05-08 14:14:26 +00003984 if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
drhf3f69ac2014-08-20 23:38:07 +00003985 const char *zName;
3986 if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){
drh319f6772013-05-14 15:31:07 +00003987 if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
3988 int i = sqlite3Strlen30(zName) - 1;
3989 while( zName[i]!='_' ) i--;
3990 zName += i;
3991 }
drh6457a352013-06-21 00:35:37 +00003992 sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq);
drh5346e952013-05-08 14:14:26 +00003993 }else{
drh6457a352013-06-21 00:35:37 +00003994 sqlite3DebugPrintf("%20s","");
drh5346e952013-05-08 14:14:26 +00003995 }
drha18f3d22013-05-08 03:05:41 +00003996 }else{
drh5346e952013-05-08 14:14:26 +00003997 char *z;
3998 if( p->u.vtab.idxStr ){
drh3bd26f02013-05-24 14:52:03 +00003999 z = sqlite3_mprintf("(%d,\"%s\",%x)",
4000 p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
drh5346e952013-05-08 14:14:26 +00004001 }else{
drh3bd26f02013-05-24 14:52:03 +00004002 z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
drh5346e952013-05-08 14:14:26 +00004003 }
drh6457a352013-06-21 00:35:37 +00004004 sqlite3DebugPrintf(" %-19s", z);
drh5346e952013-05-08 14:14:26 +00004005 sqlite3_free(z);
drha18f3d22013-05-08 03:05:41 +00004006 }
drhf3f69ac2014-08-20 23:38:07 +00004007 if( p->wsFlags & WHERE_SKIPSCAN ){
drhc8bbce12014-10-21 01:05:09 +00004008 sqlite3DebugPrintf(" f %05x %d-%d", p->wsFlags, p->nLTerm,p->nSkip);
drhf3f69ac2014-08-20 23:38:07 +00004009 }else{
4010 sqlite3DebugPrintf(" f %05x N %d", p->wsFlags, p->nLTerm);
4011 }
drhb8a8e8a2013-06-10 19:12:39 +00004012 sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
drhc90713d2014-09-30 13:46:49 +00004013 if( p->nLTerm && (sqlite3WhereTrace & 0x100)!=0 ){
4014 int i;
4015 for(i=0; i<p->nLTerm; i++){
drh0a99ba32014-09-30 17:03:35 +00004016 whereTermPrint(p->aLTerm[i], i);
drhc90713d2014-09-30 13:46:49 +00004017 }
4018 }
drha18f3d22013-05-08 03:05:41 +00004019}
4020#endif
4021
drhf1b5f5b2013-05-02 00:15:01 +00004022/*
drh4efc9292013-06-06 23:02:03 +00004023** Convert bulk memory into a valid WhereLoop that can be passed
4024** to whereLoopClear harmlessly.
drh5346e952013-05-08 14:14:26 +00004025*/
drh4efc9292013-06-06 23:02:03 +00004026static void whereLoopInit(WhereLoop *p){
4027 p->aLTerm = p->aLTermSpace;
4028 p->nLTerm = 0;
4029 p->nLSlot = ArraySize(p->aLTermSpace);
4030 p->wsFlags = 0;
4031}
4032
4033/*
4034** Clear the WhereLoop.u union. Leave WhereLoop.pLTerm intact.
4035*/
4036static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
drh986b3872013-06-28 21:12:20 +00004037 if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){
drh13e11b42013-06-06 23:44:25 +00004038 if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
4039 sqlite3_free(p->u.vtab.idxStr);
4040 p->u.vtab.needFree = 0;
4041 p->u.vtab.idxStr = 0;
drh986b3872013-06-28 21:12:20 +00004042 }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){
drh13e11b42013-06-06 23:44:25 +00004043 sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
4044 sqlite3DbFree(db, p->u.btree.pIndex);
4045 p->u.btree.pIndex = 0;
4046 }
drh5346e952013-05-08 14:14:26 +00004047 }
4048}
4049
drh4efc9292013-06-06 23:02:03 +00004050/*
4051** Deallocate internal memory used by a WhereLoop object
4052*/
4053static void whereLoopClear(sqlite3 *db, WhereLoop *p){
4054 if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
4055 whereLoopClearUnion(db, p);
4056 whereLoopInit(p);
4057}
4058
4059/*
4060** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
4061*/
4062static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
4063 WhereTerm **paNew;
4064 if( p->nLSlot>=n ) return SQLITE_OK;
4065 n = (n+7)&~7;
4066 paNew = sqlite3DbMallocRaw(db, sizeof(p->aLTerm[0])*n);
4067 if( paNew==0 ) return SQLITE_NOMEM;
4068 memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
4069 if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
4070 p->aLTerm = paNew;
4071 p->nLSlot = n;
4072 return SQLITE_OK;
4073}
4074
4075/*
4076** Transfer content from the second pLoop into the first.
4077*/
4078static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
drh4efc9292013-06-06 23:02:03 +00004079 whereLoopClearUnion(db, pTo);
drh0d31dc32013-09-06 00:40:59 +00004080 if( whereLoopResize(db, pTo, pFrom->nLTerm) ){
4081 memset(&pTo->u, 0, sizeof(pTo->u));
4082 return SQLITE_NOMEM;
4083 }
drha2014152013-06-07 00:29:23 +00004084 memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
4085 memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
drh4efc9292013-06-06 23:02:03 +00004086 if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
4087 pFrom->u.vtab.needFree = 0;
drh986b3872013-06-28 21:12:20 +00004088 }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){
drh4efc9292013-06-06 23:02:03 +00004089 pFrom->u.btree.pIndex = 0;
4090 }
4091 return SQLITE_OK;
4092}
4093
drh5346e952013-05-08 14:14:26 +00004094/*
drhf1b5f5b2013-05-02 00:15:01 +00004095** Delete a WhereLoop object
4096*/
4097static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
drh5346e952013-05-08 14:14:26 +00004098 whereLoopClear(db, p);
drhf1b5f5b2013-05-02 00:15:01 +00004099 sqlite3DbFree(db, p);
4100}
drh84bfda42005-07-15 13:05:21 +00004101
drh9eff6162006-06-12 21:59:13 +00004102/*
4103** Free a WhereInfo structure
4104*/
drh10fe8402008-10-11 16:47:35 +00004105static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
drh52ff8ea2010-04-08 14:15:56 +00004106 if( ALWAYS(pWInfo) ){
drh70d18342013-06-06 19:16:33 +00004107 whereClauseClear(&pWInfo->sWC);
drhf1b5f5b2013-05-02 00:15:01 +00004108 while( pWInfo->pLoops ){
4109 WhereLoop *p = pWInfo->pLoops;
4110 pWInfo->pLoops = p->pNextLoop;
4111 whereLoopDelete(db, p);
4112 }
drh633e6d52008-07-28 19:34:53 +00004113 sqlite3DbFree(db, pWInfo);
drh9eff6162006-06-12 21:59:13 +00004114 }
4115}
4116
drhf1b5f5b2013-05-02 00:15:01 +00004117/*
drhe0de8762014-11-05 13:13:13 +00004118** Return TRUE if all of the following are true:
drhb355c2c2014-04-18 22:20:31 +00004119**
4120** (1) X has the same or lower cost that Y
4121** (2) X is a proper subset of Y
drhe0de8762014-11-05 13:13:13 +00004122** (3) X skips at least as many columns as Y
drhb355c2c2014-04-18 22:20:31 +00004123**
4124** By "proper subset" we mean that X uses fewer WHERE clause terms
4125** than Y and that every WHERE clause term used by X is also used
4126** by Y.
4127**
4128** If X is a proper subset of Y then Y is a better choice and ought
4129** to have a lower cost. This routine returns TRUE when that cost
drhe0de8762014-11-05 13:13:13 +00004130** relationship is inverted and needs to be adjusted. The third rule
4131** was added because if X uses skip-scan less than Y it still might
4132** deserve a lower cost even if it is a proper subset of Y.
drh3fb183d2014-03-31 19:49:00 +00004133*/
drhb355c2c2014-04-18 22:20:31 +00004134static int whereLoopCheaperProperSubset(
4135 const WhereLoop *pX, /* First WhereLoop to compare */
4136 const WhereLoop *pY /* Compare against this WhereLoop */
4137){
drh3fb183d2014-03-31 19:49:00 +00004138 int i, j;
drhc8bbce12014-10-21 01:05:09 +00004139 if( pX->nLTerm-pX->nSkip >= pY->nLTerm-pY->nSkip ){
4140 return 0; /* X is not a subset of Y */
4141 }
drhe0de8762014-11-05 13:13:13 +00004142 if( pY->nSkip > pX->nSkip ) return 0;
drhb355c2c2014-04-18 22:20:31 +00004143 if( pX->rRun >= pY->rRun ){
4144 if( pX->rRun > pY->rRun ) return 0; /* X costs more than Y */
4145 if( pX->nOut > pY->nOut ) return 0; /* X costs more than Y */
drh3fb183d2014-03-31 19:49:00 +00004146 }
drh9ee88102014-05-07 20:33:17 +00004147 for(i=pX->nLTerm-1; i>=0; i--){
drhc8bbce12014-10-21 01:05:09 +00004148 if( pX->aLTerm[i]==0 ) continue;
drhb355c2c2014-04-18 22:20:31 +00004149 for(j=pY->nLTerm-1; j>=0; j--){
4150 if( pY->aLTerm[j]==pX->aLTerm[i] ) break;
4151 }
4152 if( j<0 ) return 0; /* X not a subset of Y since term X[i] not used by Y */
4153 }
4154 return 1; /* All conditions meet */
drh3fb183d2014-03-31 19:49:00 +00004155}
4156
4157/*
4158** Try to adjust the cost of WhereLoop pTemplate upwards or downwards so
4159** that:
drh53cd10a2014-03-31 18:24:18 +00004160**
drh3fb183d2014-03-31 19:49:00 +00004161** (1) pTemplate costs less than any other WhereLoops that are a proper
4162** subset of pTemplate
drh53cd10a2014-03-31 18:24:18 +00004163**
drh3fb183d2014-03-31 19:49:00 +00004164** (2) pTemplate costs more than any other WhereLoops for which pTemplate
4165** is a proper subset.
drh53cd10a2014-03-31 18:24:18 +00004166**
drh3fb183d2014-03-31 19:49:00 +00004167** To say "WhereLoop X is a proper subset of Y" means that X uses fewer
4168** WHERE clause terms than Y and that every WHERE clause term used by X is
4169** also used by Y.
drh53cd10a2014-03-31 18:24:18 +00004170*/
4171static void whereLoopAdjustCost(const WhereLoop *p, WhereLoop *pTemplate){
4172 if( (pTemplate->wsFlags & WHERE_INDEXED)==0 ) return;
drh53cd10a2014-03-31 18:24:18 +00004173 for(; p; p=p->pNextLoop){
drh3fb183d2014-03-31 19:49:00 +00004174 if( p->iTab!=pTemplate->iTab ) continue;
4175 if( (p->wsFlags & WHERE_INDEXED)==0 ) continue;
drhb355c2c2014-04-18 22:20:31 +00004176 if( whereLoopCheaperProperSubset(p, pTemplate) ){
4177 /* Adjust pTemplate cost downward so that it is cheaper than its
drhe0de8762014-11-05 13:13:13 +00004178 ** subset p. */
drh1b131b72014-10-21 16:01:40 +00004179 WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
4180 pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut-1));
drh3fb183d2014-03-31 19:49:00 +00004181 pTemplate->rRun = p->rRun;
4182 pTemplate->nOut = p->nOut - 1;
drhb355c2c2014-04-18 22:20:31 +00004183 }else if( whereLoopCheaperProperSubset(pTemplate, p) ){
4184 /* Adjust pTemplate cost upward so that it is costlier than p since
4185 ** pTemplate is a proper subset of p */
drh1b131b72014-10-21 16:01:40 +00004186 WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
4187 pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut+1));
drh3fb183d2014-03-31 19:49:00 +00004188 pTemplate->rRun = p->rRun;
4189 pTemplate->nOut = p->nOut + 1;
drh53cd10a2014-03-31 18:24:18 +00004190 }
4191 }
4192}
4193
4194/*
drh7a4b1642014-03-29 21:16:07 +00004195** Search the list of WhereLoops in *ppPrev looking for one that can be
4196** supplanted by pTemplate.
drhf1b5f5b2013-05-02 00:15:01 +00004197**
drh7a4b1642014-03-29 21:16:07 +00004198** Return NULL if the WhereLoop list contains an entry that can supplant
4199** pTemplate, in other words if pTemplate does not belong on the list.
drh23f98da2013-05-21 15:52:07 +00004200**
drh7a4b1642014-03-29 21:16:07 +00004201** If pX is a WhereLoop that pTemplate can supplant, then return the
4202** link that points to pX.
drh23f98da2013-05-21 15:52:07 +00004203**
drh7a4b1642014-03-29 21:16:07 +00004204** If pTemplate cannot supplant any existing element of the list but needs
4205** to be added to the list, then return a pointer to the tail of the list.
drhf1b5f5b2013-05-02 00:15:01 +00004206*/
drh7a4b1642014-03-29 21:16:07 +00004207static WhereLoop **whereLoopFindLesser(
4208 WhereLoop **ppPrev,
4209 const WhereLoop *pTemplate
4210){
4211 WhereLoop *p;
4212 for(p=(*ppPrev); p; ppPrev=&p->pNextLoop, p=*ppPrev){
drhdbb80232013-06-19 12:34:13 +00004213 if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
4214 /* If either the iTab or iSortIdx values for two WhereLoop are different
4215 ** then those WhereLoops need to be considered separately. Neither is
4216 ** a candidate to replace the other. */
4217 continue;
4218 }
4219 /* In the current implementation, the rSetup value is either zero
4220 ** or the cost of building an automatic index (NlogN) and the NlogN
4221 ** is the same for compatible WhereLoops. */
4222 assert( p->rSetup==0 || pTemplate->rSetup==0
4223 || p->rSetup==pTemplate->rSetup );
4224
4225 /* whereLoopAddBtree() always generates and inserts the automatic index
4226 ** case first. Hence compatible candidate WhereLoops never have a larger
4227 ** rSetup. Call this SETUP-INVARIANT */
4228 assert( p->rSetup>=pTemplate->rSetup );
4229
drhdabe36d2014-06-17 20:16:43 +00004230 /* Any loop using an appliation-defined index (or PRIMARY KEY or
4231 ** UNIQUE constraint) with one or more == constraints is better
dan70273d02014-11-14 19:34:20 +00004232 ** than an automatic index. Unless it is a skip-scan. */
drhdabe36d2014-06-17 20:16:43 +00004233 if( (p->wsFlags & WHERE_AUTO_INDEX)!=0
dan70273d02014-11-14 19:34:20 +00004234 && (pTemplate->nSkip)==0
drhdabe36d2014-06-17 20:16:43 +00004235 && (pTemplate->wsFlags & WHERE_INDEXED)!=0
4236 && (pTemplate->wsFlags & WHERE_COLUMN_EQ)!=0
4237 && (p->prereq & pTemplate->prereq)==pTemplate->prereq
4238 ){
4239 break;
4240 }
4241
drh53cd10a2014-03-31 18:24:18 +00004242 /* If existing WhereLoop p is better than pTemplate, pTemplate can be
4243 ** discarded. WhereLoop p is better if:
4244 ** (1) p has no more dependencies than pTemplate, and
4245 ** (2) p has an equal or lower cost than pTemplate
4246 */
4247 if( (p->prereq & pTemplate->prereq)==p->prereq /* (1) */
4248 && p->rSetup<=pTemplate->rSetup /* (2a) */
4249 && p->rRun<=pTemplate->rRun /* (2b) */
4250 && p->nOut<=pTemplate->nOut /* (2c) */
drhf1b5f5b2013-05-02 00:15:01 +00004251 ){
drh53cd10a2014-03-31 18:24:18 +00004252 return 0; /* Discard pTemplate */
drhf1b5f5b2013-05-02 00:15:01 +00004253 }
drh53cd10a2014-03-31 18:24:18 +00004254
4255 /* If pTemplate is always better than p, then cause p to be overwritten
4256 ** with pTemplate. pTemplate is better than p if:
4257 ** (1) pTemplate has no more dependences than p, and
4258 ** (2) pTemplate has an equal or lower cost than p.
4259 */
4260 if( (p->prereq & pTemplate->prereq)==pTemplate->prereq /* (1) */
4261 && p->rRun>=pTemplate->rRun /* (2a) */
4262 && p->nOut>=pTemplate->nOut /* (2b) */
drhf1b5f5b2013-05-02 00:15:01 +00004263 ){
drhadd5ce32013-09-07 00:29:06 +00004264 assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */
drh53cd10a2014-03-31 18:24:18 +00004265 break; /* Cause p to be overwritten by pTemplate */
drhf1b5f5b2013-05-02 00:15:01 +00004266 }
4267 }
drh7a4b1642014-03-29 21:16:07 +00004268 return ppPrev;
4269}
4270
4271/*
drh94a11212004-09-25 13:12:14 +00004272** Insert or replace a WhereLoop entry using the template supplied.
4273**
4274** An existing WhereLoop entry might be overwritten if the new template
4275** is better and has fewer dependencies. Or the template will be ignored
4276** and no insert will occur if an existing WhereLoop is faster and has
4277** fewer dependencies than the template. Otherwise a new WhereLoop is
4278** added based on the template.
drh51669862004-12-18 18:40:26 +00004279**
drh7a4b1642014-03-29 21:16:07 +00004280** If pBuilder->pOrSet is not NULL then we care about only the
drh94a11212004-09-25 13:12:14 +00004281** prerequisites and rRun and nOut costs of the N best loops. That
4282** information is gathered in the pBuilder->pOrSet object. This special
drh51669862004-12-18 18:40:26 +00004283** processing mode is used only for OR clause processing.
4284**
4285** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
4286** still might overwrite similar loops with the new template if the
drh53cd10a2014-03-31 18:24:18 +00004287** new template is better. Loops may be overwritten if the following
drh94a11212004-09-25 13:12:14 +00004288** conditions are met:
4289**
4290** (1) They have the same iTab.
4291** (2) They have the same iSortIdx.
4292** (3) The template has same or fewer dependencies than the current loop
4293** (4) The template has the same or lower cost than the current loop
drh94a11212004-09-25 13:12:14 +00004294*/
4295static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
drh7a4b1642014-03-29 21:16:07 +00004296 WhereLoop **ppPrev, *p;
drh94a11212004-09-25 13:12:14 +00004297 WhereInfo *pWInfo = pBuilder->pWInfo;
4298 sqlite3 *db = pWInfo->pParse->db;
4299
4300 /* If pBuilder->pOrSet is defined, then only keep track of the costs
4301 ** and prereqs.
4302 */
4303 if( pBuilder->pOrSet!=0 ){
4304#if WHERETRACE_ENABLED
drh51669862004-12-18 18:40:26 +00004305 u16 n = pBuilder->pOrSet->n;
4306 int x =
4307#endif
4308 whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
4309 pTemplate->nOut);
drh94a11212004-09-25 13:12:14 +00004310#if WHERETRACE_ENABLED /* 0x8 */
4311 if( sqlite3WhereTrace & 0x8 ){
drhe3184742002-06-19 14:27:05 +00004312 sqlite3DebugPrintf(x?" or-%d: ":" or-X: ", n);
drhacf3b982005-01-03 01:27:18 +00004313 whereLoopPrint(pTemplate, pBuilder->pWC);
drh75897232000-05-29 14:26:00 +00004314 }
danielk19774adee202004-05-08 08:23:19 +00004315#endif
drh75897232000-05-29 14:26:00 +00004316 return SQLITE_OK;
4317 }
4318
drh7a4b1642014-03-29 21:16:07 +00004319 /* Look for an existing WhereLoop to replace with pTemplate
drh75897232000-05-29 14:26:00 +00004320 */
drh53cd10a2014-03-31 18:24:18 +00004321 whereLoopAdjustCost(pWInfo->pLoops, pTemplate);
drh7a4b1642014-03-29 21:16:07 +00004322 ppPrev = whereLoopFindLesser(&pWInfo->pLoops, pTemplate);
drhf1b5f5b2013-05-02 00:15:01 +00004323
drh7a4b1642014-03-29 21:16:07 +00004324 if( ppPrev==0 ){
4325 /* There already exists a WhereLoop on the list that is better
4326 ** than pTemplate, so just ignore pTemplate */
4327#if WHERETRACE_ENABLED /* 0x8 */
4328 if( sqlite3WhereTrace & 0x8 ){
drh9a7b41d2014-10-08 00:08:08 +00004329 sqlite3DebugPrintf(" skip: ");
drh7a4b1642014-03-29 21:16:07 +00004330 whereLoopPrint(pTemplate, pBuilder->pWC);
drhf1b5f5b2013-05-02 00:15:01 +00004331 }
drh7a4b1642014-03-29 21:16:07 +00004332#endif
4333 return SQLITE_OK;
4334 }else{
4335 p = *ppPrev;
drhf1b5f5b2013-05-02 00:15:01 +00004336 }
4337
4338 /* If we reach this point it means that either p[] should be overwritten
4339 ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
4340 ** WhereLoop and insert it.
4341 */
drh989578e2013-10-28 14:34:35 +00004342#if WHERETRACE_ENABLED /* 0x8 */
drhae70cf12013-05-31 15:18:46 +00004343 if( sqlite3WhereTrace & 0x8 ){
4344 if( p!=0 ){
drh9a7b41d2014-10-08 00:08:08 +00004345 sqlite3DebugPrintf("replace: ");
drhc1ba2e72013-10-28 19:03:21 +00004346 whereLoopPrint(p, pBuilder->pWC);
drhae70cf12013-05-31 15:18:46 +00004347 }
drh9a7b41d2014-10-08 00:08:08 +00004348 sqlite3DebugPrintf(" add: ");
drhc1ba2e72013-10-28 19:03:21 +00004349 whereLoopPrint(pTemplate, pBuilder->pWC);
drhae70cf12013-05-31 15:18:46 +00004350 }
4351#endif
drhf1b5f5b2013-05-02 00:15:01 +00004352 if( p==0 ){
drh7a4b1642014-03-29 21:16:07 +00004353 /* Allocate a new WhereLoop to add to the end of the list */
4354 *ppPrev = p = sqlite3DbMallocRaw(db, sizeof(WhereLoop));
drhf1b5f5b2013-05-02 00:15:01 +00004355 if( p==0 ) return SQLITE_NOMEM;
drh4efc9292013-06-06 23:02:03 +00004356 whereLoopInit(p);
drh7a4b1642014-03-29 21:16:07 +00004357 p->pNextLoop = 0;
4358 }else{
4359 /* We will be overwriting WhereLoop p[]. But before we do, first
4360 ** go through the rest of the list and delete any other entries besides
4361 ** p[] that are also supplated by pTemplate */
4362 WhereLoop **ppTail = &p->pNextLoop;
4363 WhereLoop *pToDel;
4364 while( *ppTail ){
4365 ppTail = whereLoopFindLesser(ppTail, pTemplate);
drhdabe36d2014-06-17 20:16:43 +00004366 if( ppTail==0 ) break;
drh7a4b1642014-03-29 21:16:07 +00004367 pToDel = *ppTail;
4368 if( pToDel==0 ) break;
4369 *ppTail = pToDel->pNextLoop;
4370#if WHERETRACE_ENABLED /* 0x8 */
4371 if( sqlite3WhereTrace & 0x8 ){
drh9a7b41d2014-10-08 00:08:08 +00004372 sqlite3DebugPrintf(" delete: ");
drh7a4b1642014-03-29 21:16:07 +00004373 whereLoopPrint(pToDel, pBuilder->pWC);
4374 }
4375#endif
4376 whereLoopDelete(db, pToDel);
4377 }
drhf1b5f5b2013-05-02 00:15:01 +00004378 }
drh4efc9292013-06-06 23:02:03 +00004379 whereLoopXfer(db, p, pTemplate);
drh5346e952013-05-08 14:14:26 +00004380 if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
drhef866372013-05-22 20:49:02 +00004381 Index *pIndex = p->u.btree.pIndex;
4382 if( pIndex && pIndex->tnum==0 ){
drhcf8fa7a2013-05-10 20:26:22 +00004383 p->u.btree.pIndex = 0;
4384 }
drh5346e952013-05-08 14:14:26 +00004385 }
drhf1b5f5b2013-05-02 00:15:01 +00004386 return SQLITE_OK;
4387}
4388
4389/*
drhcca9f3d2013-09-06 15:23:29 +00004390** Adjust the WhereLoop.nOut value downward to account for terms of the
4391** WHERE clause that reference the loop but which are not used by an
4392** index.
drh7a1bca72014-11-22 18:50:44 +00004393*
4394** For every WHERE clause term that is not used by the index
4395** and which has a truth probability assigned by one of the likelihood(),
4396** likely(), or unlikely() SQL functions, reduce the estimated number
4397** of output rows by the probability specified.
drhcca9f3d2013-09-06 15:23:29 +00004398**
drh7a1bca72014-11-22 18:50:44 +00004399** TUNING: For every WHERE clause term that is not used by the index
4400** and which does not have an assigned truth probability, heuristics
4401** described below are used to try to estimate the truth probability.
4402** TODO --> Perhaps this is something that could be improved by better
4403** table statistics.
4404**
drhab4624d2014-11-22 19:52:10 +00004405** Heuristic 1: Estimate the truth probability as 93.75%. The 93.75%
4406** value corresponds to -1 in LogEst notation, so this means decrement
drh7a1bca72014-11-22 18:50:44 +00004407** the WhereLoop.nOut field for every such WHERE clause term.
4408**
4409** Heuristic 2: If there exists one or more WHERE clause terms of the
4410** form "x==EXPR" and EXPR is not a constant 0 or 1, then make sure the
4411** final output row estimate is no greater than 1/4 of the total number
4412** of rows in the table. In other words, assume that x==EXPR will filter
4413** out at least 3 out of 4 rows. If EXPR is -1 or 0 or 1, then maybe the
4414** "x" column is boolean or else -1 or 0 or 1 is a common default value
4415** on the "x" column and so in that case only cap the output row estimate
4416** at 1/2 instead of 1/4.
drhcca9f3d2013-09-06 15:23:29 +00004417*/
drhd8b77e22014-09-06 01:35:57 +00004418static void whereLoopOutputAdjust(
4419 WhereClause *pWC, /* The WHERE clause */
4420 WhereLoop *pLoop, /* The loop to adjust downward */
4421 LogEst nRow /* Number of rows in the entire table */
4422){
drh7d9e7d82013-09-11 17:39:09 +00004423 WhereTerm *pTerm, *pX;
drhcca9f3d2013-09-06 15:23:29 +00004424 Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf);
drh7a1bca72014-11-22 18:50:44 +00004425 int i, j, k;
4426 LogEst iReduce = 0; /* pLoop->nOut should not exceed nRow-iReduce */
drhadd5ce32013-09-07 00:29:06 +00004427
drha3898252014-11-22 12:22:13 +00004428 assert( (pLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
drhcca9f3d2013-09-06 15:23:29 +00004429 for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){
drh7d9e7d82013-09-11 17:39:09 +00004430 if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break;
drhcca9f3d2013-09-06 15:23:29 +00004431 if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;
4432 if( (pTerm->prereqAll & notAllowed)!=0 ) continue;
drh7d9e7d82013-09-11 17:39:09 +00004433 for(j=pLoop->nLTerm-1; j>=0; j--){
4434 pX = pLoop->aLTerm[j];
drhd2447442013-11-13 19:01:41 +00004435 if( pX==0 ) continue;
drh7d9e7d82013-09-11 17:39:09 +00004436 if( pX==pTerm ) break;
4437 if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break;
4438 }
danaa9933c2014-04-24 20:04:49 +00004439 if( j<0 ){
drhd8b77e22014-09-06 01:35:57 +00004440 if( pTerm->truthProb<=0 ){
drh7a1bca72014-11-22 18:50:44 +00004441 /* If a truth probability is specified using the likelihood() hints,
4442 ** then use the probability provided by the application. */
drhd8b77e22014-09-06 01:35:57 +00004443 pLoop->nOut += pTerm->truthProb;
4444 }else{
drh7a1bca72014-11-22 18:50:44 +00004445 /* In the absence of explicit truth probabilities, use heuristics to
4446 ** guess a reasonable truth probability. */
drhd8b77e22014-09-06 01:35:57 +00004447 pLoop->nOut--;
drh7a1bca72014-11-22 18:50:44 +00004448 if( pTerm->eOperator&WO_EQ ){
4449 Expr *pRight = pTerm->pExpr->pRight;
4450 if( sqlite3ExprIsInteger(pRight, &k) && k>=(-1) && k<=1 ){
4451 k = 10;
4452 }else{
4453 k = 20;
4454 }
4455 if( iReduce<k ) iReduce = k;
4456 }
drhd8b77e22014-09-06 01:35:57 +00004457 }
danaa9933c2014-04-24 20:04:49 +00004458 }
drhcca9f3d2013-09-06 15:23:29 +00004459 }
drh7a1bca72014-11-22 18:50:44 +00004460 if( pLoop->nOut > nRow-iReduce ) pLoop->nOut = nRow - iReduce;
drhcca9f3d2013-09-06 15:23:29 +00004461}
4462
4463/*
drhdbd94862014-07-23 23:57:42 +00004464** Adjust the cost C by the costMult facter T. This only occurs if
4465** compiled with -DSQLITE_ENABLE_COSTMULT
4466*/
4467#ifdef SQLITE_ENABLE_COSTMULT
4468# define ApplyCostMultiplier(C,T) C += T
4469#else
4470# define ApplyCostMultiplier(C,T)
4471#endif
4472
4473/*
dan4a6b8a02014-04-30 14:47:01 +00004474** We have so far matched pBuilder->pNew->u.btree.nEq terms of the
4475** index pIndex. Try to match one more.
4476**
4477** When this function is called, pBuilder->pNew->nOut contains the
4478** number of rows expected to be visited by filtering using the nEq
4479** terms only. If it is modified, this value is restored before this
4480** function returns.
drh1c8148f2013-05-04 20:25:23 +00004481**
4482** If pProbe->tnum==0, that means pIndex is a fake index used for the
4483** INTEGER PRIMARY KEY.
4484*/
drh5346e952013-05-08 14:14:26 +00004485static int whereLoopAddBtreeIndex(
drh1c8148f2013-05-04 20:25:23 +00004486 WhereLoopBuilder *pBuilder, /* The WhereLoop factory */
4487 struct SrcList_item *pSrc, /* FROM clause term being analyzed */
4488 Index *pProbe, /* An index on pSrc */
drhbf539c42013-10-05 18:16:02 +00004489 LogEst nInMul /* log(Number of iterations due to IN) */
drh1c8148f2013-05-04 20:25:23 +00004490){
drh70d18342013-06-06 19:16:33 +00004491 WhereInfo *pWInfo = pBuilder->pWInfo; /* WHERE analyse context */
4492 Parse *pParse = pWInfo->pParse; /* Parsing context */
4493 sqlite3 *db = pParse->db; /* Database connection malloc context */
drh1c8148f2013-05-04 20:25:23 +00004494 WhereLoop *pNew; /* Template WhereLoop under construction */
4495 WhereTerm *pTerm; /* A WhereTerm under consideration */
drh43fe25f2013-05-07 23:06:23 +00004496 int opMask; /* Valid operators for constraints */
drh1c8148f2013-05-04 20:25:23 +00004497 WhereScan scan; /* Iterator for WHERE terms */
drh4efc9292013-06-06 23:02:03 +00004498 Bitmask saved_prereq; /* Original value of pNew->prereq */
4499 u16 saved_nLTerm; /* Original value of pNew->nLTerm */
drhcd8629e2013-11-13 12:27:25 +00004500 u16 saved_nEq; /* Original value of pNew->u.btree.nEq */
drhc8bbce12014-10-21 01:05:09 +00004501 u16 saved_nSkip; /* Original value of pNew->nSkip */
drh4efc9292013-06-06 23:02:03 +00004502 u32 saved_wsFlags; /* Original value of pNew->wsFlags */
drhbf539c42013-10-05 18:16:02 +00004503 LogEst saved_nOut; /* Original value of pNew->nOut */
drha18f3d22013-05-08 03:05:41 +00004504 int iCol; /* Index of the column in the table */
drh5346e952013-05-08 14:14:26 +00004505 int rc = SQLITE_OK; /* Return code */
drhd8b77e22014-09-06 01:35:57 +00004506 LogEst rSize; /* Number of rows in the table */
drhbf539c42013-10-05 18:16:02 +00004507 LogEst rLogSize; /* Logarithm of table size */
drhc7f0d222013-06-19 03:27:12 +00004508 WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
drh1c8148f2013-05-04 20:25:23 +00004509
drh1c8148f2013-05-04 20:25:23 +00004510 pNew = pBuilder->pNew;
drh5346e952013-05-08 14:14:26 +00004511 if( db->mallocFailed ) return SQLITE_NOMEM;
drh1c8148f2013-05-04 20:25:23 +00004512
drh5346e952013-05-08 14:14:26 +00004513 assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
drh43fe25f2013-05-07 23:06:23 +00004514 assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
4515 if( pNew->wsFlags & WHERE_BTM_LIMIT ){
4516 opMask = WO_LT|WO_LE;
4517 }else if( pProbe->tnum<=0 || (pSrc->jointype & JT_LEFT)!=0 ){
4518 opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE;
drh1c8148f2013-05-04 20:25:23 +00004519 }else{
drh43fe25f2013-05-07 23:06:23 +00004520 opMask = WO_EQ|WO_IN|WO_ISNULL|WO_GT|WO_GE|WO_LT|WO_LE;
drh1c8148f2013-05-04 20:25:23 +00004521 }
drhef866372013-05-22 20:49:02 +00004522 if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
drh1c8148f2013-05-04 20:25:23 +00004523
dan39129ce2014-06-30 15:23:57 +00004524 assert( pNew->u.btree.nEq<pProbe->nColumn );
4525 iCol = pProbe->aiColumn[pNew->u.btree.nEq];
4526
drha18f3d22013-05-08 03:05:41 +00004527 pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, iCol,
drh0f133a42013-05-22 17:01:17 +00004528 opMask, pProbe);
drh4efc9292013-06-06 23:02:03 +00004529 saved_nEq = pNew->u.btree.nEq;
drhc8bbce12014-10-21 01:05:09 +00004530 saved_nSkip = pNew->nSkip;
drh4efc9292013-06-06 23:02:03 +00004531 saved_nLTerm = pNew->nLTerm;
4532 saved_wsFlags = pNew->wsFlags;
4533 saved_prereq = pNew->prereq;
4534 saved_nOut = pNew->nOut;
drhb8a8e8a2013-06-10 19:12:39 +00004535 pNew->rSetup = 0;
drhd8b77e22014-09-06 01:35:57 +00004536 rSize = pProbe->aiRowLogEst[0];
4537 rLogSize = estLog(rSize);
drh5346e952013-05-08 14:14:26 +00004538 for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
dan8ad1d8b2014-04-25 20:22:45 +00004539 u16 eOp = pTerm->eOperator; /* Shorthand for pTerm->eOperator */
danaa9933c2014-04-24 20:04:49 +00004540 LogEst rCostIdx;
dan8ad1d8b2014-04-25 20:22:45 +00004541 LogEst nOutUnadjusted; /* nOut before IN() and WHERE adjustments */
drhb8a8e8a2013-06-10 19:12:39 +00004542 int nIn = 0;
drh1435a9a2013-08-27 23:15:44 +00004543#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
dan7a419232013-08-06 20:01:43 +00004544 int nRecValid = pBuilder->nRecValid;
drhb5246e52013-07-08 21:12:57 +00004545#endif
dan8ad1d8b2014-04-25 20:22:45 +00004546 if( (eOp==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)
dan8bff07a2013-08-29 14:56:14 +00004547 && (iCol<0 || pSrc->pTab->aCol[iCol].notNull)
4548 ){
4549 continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */
4550 }
dan7a419232013-08-06 20:01:43 +00004551 if( pTerm->prereqRight & pNew->maskSelf ) continue;
4552
drha40da622015-03-09 12:11:56 +00004553 /* Do not allow the upper bound of a LIKE optimization range constraint
4554 ** to mix with a lower range bound from some other source */
4555 if( pTerm->wtFlags & TERM_LIKEOPT && pTerm->eOperator==WO_LT ) continue;
4556
drh4efc9292013-06-06 23:02:03 +00004557 pNew->wsFlags = saved_wsFlags;
4558 pNew->u.btree.nEq = saved_nEq;
4559 pNew->nLTerm = saved_nLTerm;
4560 if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
4561 pNew->aLTerm[pNew->nLTerm++] = pTerm;
4562 pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
dan8ad1d8b2014-04-25 20:22:45 +00004563
4564 assert( nInMul==0
4565 || (pNew->wsFlags & WHERE_COLUMN_NULL)!=0
4566 || (pNew->wsFlags & WHERE_COLUMN_IN)!=0
4567 || (pNew->wsFlags & WHERE_SKIPSCAN)!=0
4568 );
4569
4570 if( eOp & WO_IN ){
drha18f3d22013-05-08 03:05:41 +00004571 Expr *pExpr = pTerm->pExpr;
4572 pNew->wsFlags |= WHERE_COLUMN_IN;
4573 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
drhe1e2e9a2013-06-13 15:16:53 +00004574 /* "x IN (SELECT ...)": TUNING: the SELECT returns 25 rows */
drhbf539c42013-10-05 18:16:02 +00004575 nIn = 46; assert( 46==sqlite3LogEst(25) );
drha18f3d22013-05-08 03:05:41 +00004576 }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
4577 /* "x IN (value, value, ...)" */
drhbf539c42013-10-05 18:16:02 +00004578 nIn = sqlite3LogEst(pExpr->x.pList->nExpr);
drhf1645f02013-05-07 19:44:38 +00004579 }
drh2b59b3a2014-03-20 13:26:47 +00004580 assert( nIn>0 ); /* RHS always has 2 or more terms... The parser
4581 ** changes "x IN (?)" into "x=?". */
dan8ad1d8b2014-04-25 20:22:45 +00004582
4583 }else if( eOp & (WO_EQ) ){
drha18f3d22013-05-08 03:05:41 +00004584 pNew->wsFlags |= WHERE_COLUMN_EQ;
dan8ad1d8b2014-04-25 20:22:45 +00004585 if( iCol<0 || (nInMul==0 && pNew->u.btree.nEq==pProbe->nKeyCol-1) ){
drh5f1d1d92014-07-31 22:59:04 +00004586 if( iCol>=0 && !IsUniqueIndex(pProbe) ){
drhe39a7322014-02-03 14:04:11 +00004587 pNew->wsFlags |= WHERE_UNQ_WANTED;
4588 }else{
4589 pNew->wsFlags |= WHERE_ONEROW;
4590 }
drh21f7ff72013-06-03 15:07:23 +00004591 }
dan2dd3cdc2014-04-26 20:21:14 +00004592 }else if( eOp & WO_ISNULL ){
4593 pNew->wsFlags |= WHERE_COLUMN_NULL;
dan8ad1d8b2014-04-25 20:22:45 +00004594 }else if( eOp & (WO_GT|WO_GE) ){
4595 testcase( eOp & WO_GT );
4596 testcase( eOp & WO_GE );
drha18f3d22013-05-08 03:05:41 +00004597 pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
drh6f2bfad2013-06-03 17:35:22 +00004598 pBtm = pTerm;
4599 pTop = 0;
drha40da622015-03-09 12:11:56 +00004600 if( pTerm->wtFlags & TERM_LIKEOPT ){
4601 /* Make sure that range contraints that come from the LIKE
4602 ** optimization are always used in pairs. */
4603 pTop = &pTerm[1];
4604 assert( (pTop-(pTerm->pWC->a))<pTerm->pWC->nTerm );
4605 assert( pTop->wtFlags & TERM_LIKEOPT );
4606 assert( pTop->eOperator==WO_LT );
4607 if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
4608 pNew->aLTerm[pNew->nLTerm++] = pTop;
4609 pNew->wsFlags |= WHERE_TOP_LIMIT;
4610 }
dan2dd3cdc2014-04-26 20:21:14 +00004611 }else{
dan8ad1d8b2014-04-25 20:22:45 +00004612 assert( eOp & (WO_LT|WO_LE) );
4613 testcase( eOp & WO_LT );
4614 testcase( eOp & WO_LE );
drha18f3d22013-05-08 03:05:41 +00004615 pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
drh6f2bfad2013-06-03 17:35:22 +00004616 pTop = pTerm;
4617 pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
drh4efc9292013-06-06 23:02:03 +00004618 pNew->aLTerm[pNew->nLTerm-2] : 0;
drh1c8148f2013-05-04 20:25:23 +00004619 }
dan8ad1d8b2014-04-25 20:22:45 +00004620
4621 /* At this point pNew->nOut is set to the number of rows expected to
4622 ** be visited by the index scan before considering term pTerm, or the
4623 ** values of nIn and nInMul. In other words, assuming that all
4624 ** "x IN(...)" terms are replaced with "x = ?". This block updates
4625 ** the value of pNew->nOut to account for pTerm (but not nIn/nInMul). */
4626 assert( pNew->nOut==saved_nOut );
drh6f2bfad2013-06-03 17:35:22 +00004627 if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
danaa9933c2014-04-24 20:04:49 +00004628 /* Adjust nOut using stat3/stat4 data. Or, if there is no stat3/stat4
4629 ** data, using some other estimate. */
drh186ad8c2013-10-08 18:40:37 +00004630 whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew);
dan8ad1d8b2014-04-25 20:22:45 +00004631 }else{
4632 int nEq = ++pNew->u.btree.nEq;
4633 assert( eOp & (WO_ISNULL|WO_EQ|WO_IN) );
4634
4635 assert( pNew->nOut==saved_nOut );
dan09e1df62014-04-29 16:10:22 +00004636 if( pTerm->truthProb<=0 && iCol>=0 ){
dan8ad1d8b2014-04-25 20:22:45 +00004637 assert( (eOp & WO_IN) || nIn==0 );
drhc5f246e2014-05-01 20:24:21 +00004638 testcase( eOp & WO_IN );
dan8ad1d8b2014-04-25 20:22:45 +00004639 pNew->nOut += pTerm->truthProb;
4640 pNew->nOut -= nIn;
dan8ad1d8b2014-04-25 20:22:45 +00004641 }else{
drh1435a9a2013-08-27 23:15:44 +00004642#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
dan8ad1d8b2014-04-25 20:22:45 +00004643 tRowcnt nOut = 0;
4644 if( nInMul==0
4645 && pProbe->nSample
4646 && pNew->u.btree.nEq<=pProbe->nSampleCol
dan8ad1d8b2014-04-25 20:22:45 +00004647 && ((eOp & WO_IN)==0 || !ExprHasProperty(pTerm->pExpr, EP_xIsSelect))
dan8ad1d8b2014-04-25 20:22:45 +00004648 ){
4649 Expr *pExpr = pTerm->pExpr;
4650 if( (eOp & (WO_EQ|WO_ISNULL))!=0 ){
4651 testcase( eOp & WO_EQ );
4652 testcase( eOp & WO_ISNULL );
4653 rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut);
4654 }else{
4655 rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut);
4656 }
dan8ad1d8b2014-04-25 20:22:45 +00004657 if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
4658 if( rc!=SQLITE_OK ) break; /* Jump out of the pTerm loop */
4659 if( nOut ){
4660 pNew->nOut = sqlite3LogEst(nOut);
4661 if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut;
4662 pNew->nOut -= nIn;
4663 }
4664 }
4665 if( nOut==0 )
4666#endif
4667 {
4668 pNew->nOut += (pProbe->aiRowLogEst[nEq] - pProbe->aiRowLogEst[nEq-1]);
4669 if( eOp & WO_ISNULL ){
4670 /* TUNING: If there is no likelihood() value, assume that a
4671 ** "col IS NULL" expression matches twice as many rows
4672 ** as (col=?). */
4673 pNew->nOut += 10;
4674 }
4675 }
dan6cb8d762013-08-08 11:48:57 +00004676 }
drh6f2bfad2013-06-03 17:35:22 +00004677 }
dan8ad1d8b2014-04-25 20:22:45 +00004678
danaa9933c2014-04-24 20:04:49 +00004679 /* Set rCostIdx to the cost of visiting selected rows in index. Add
4680 ** it to pNew->rRun, which is currently set to the cost of the index
4681 ** seek only. Then, if this is a non-covering index, add the cost of
4682 ** visiting the rows in the main table. */
4683 rCostIdx = pNew->nOut + 1 + (15*pProbe->szIdxRow)/pSrc->pTab->szTabRow;
dan8ad1d8b2014-04-25 20:22:45 +00004684 pNew->rRun = sqlite3LogEstAdd(rLogSize, rCostIdx);
drhe217efc2013-06-12 03:48:41 +00004685 if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
danaa9933c2014-04-24 20:04:49 +00004686 pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut + 16);
drheb04de32013-05-10 15:16:30 +00004687 }
drhdbd94862014-07-23 23:57:42 +00004688 ApplyCostMultiplier(pNew->rRun, pProbe->pTable->costMult);
danaa9933c2014-04-24 20:04:49 +00004689
dan8ad1d8b2014-04-25 20:22:45 +00004690 nOutUnadjusted = pNew->nOut;
4691 pNew->rRun += nInMul + nIn;
4692 pNew->nOut += nInMul + nIn;
drhd8b77e22014-09-06 01:35:57 +00004693 whereLoopOutputAdjust(pBuilder->pWC, pNew, rSize);
drhcf8fa7a2013-05-10 20:26:22 +00004694 rc = whereLoopInsert(pBuilder, pNew);
dan440e6ff2014-04-28 08:49:54 +00004695
4696 if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
4697 pNew->nOut = saved_nOut;
4698 }else{
4699 pNew->nOut = nOutUnadjusted;
4700 }
dan8ad1d8b2014-04-25 20:22:45 +00004701
drh5346e952013-05-08 14:14:26 +00004702 if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
dan39129ce2014-06-30 15:23:57 +00004703 && pNew->u.btree.nEq<pProbe->nColumn
drh5346e952013-05-08 14:14:26 +00004704 ){
drhb8a8e8a2013-06-10 19:12:39 +00004705 whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
drha18f3d22013-05-08 03:05:41 +00004706 }
danad45ed72013-08-08 12:21:32 +00004707 pNew->nOut = saved_nOut;
drh1435a9a2013-08-27 23:15:44 +00004708#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
dan7a419232013-08-06 20:01:43 +00004709 pBuilder->nRecValid = nRecValid;
dan7a419232013-08-06 20:01:43 +00004710#endif
drh1c8148f2013-05-04 20:25:23 +00004711 }
drh4efc9292013-06-06 23:02:03 +00004712 pNew->prereq = saved_prereq;
4713 pNew->u.btree.nEq = saved_nEq;
drhc8bbce12014-10-21 01:05:09 +00004714 pNew->nSkip = saved_nSkip;
drh4efc9292013-06-06 23:02:03 +00004715 pNew->wsFlags = saved_wsFlags;
4716 pNew->nOut = saved_nOut;
4717 pNew->nLTerm = saved_nLTerm;
drhc8bbce12014-10-21 01:05:09 +00004718
4719 /* Consider using a skip-scan if there are no WHERE clause constraints
4720 ** available for the left-most terms of the index, and if the average
4721 ** number of repeats in the left-most terms is at least 18.
4722 **
4723 ** The magic number 18 is selected on the basis that scanning 17 rows
4724 ** is almost always quicker than an index seek (even though if the index
4725 ** contains fewer than 2^17 rows we assume otherwise in other parts of
4726 ** the code). And, even if it is not, it should not be too much slower.
4727 ** On the other hand, the extra seeks could end up being significantly
4728 ** more expensive. */
4729 assert( 42==sqlite3LogEst(18) );
4730 if( saved_nEq==saved_nSkip
4731 && saved_nEq+1<pProbe->nKeyCol
drhf9df2fb2014-11-15 19:08:13 +00004732 && pProbe->noSkipScan==0
drhc8bbce12014-10-21 01:05:09 +00004733 && pProbe->aiRowLogEst[saved_nEq+1]>=42 /* TUNING: Minimum for skip-scan */
4734 && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK
4735 ){
4736 LogEst nIter;
4737 pNew->u.btree.nEq++;
4738 pNew->nSkip++;
4739 pNew->aLTerm[pNew->nLTerm++] = 0;
4740 pNew->wsFlags |= WHERE_SKIPSCAN;
4741 nIter = pProbe->aiRowLogEst[saved_nEq] - pProbe->aiRowLogEst[saved_nEq+1];
drhc8bbce12014-10-21 01:05:09 +00004742 pNew->nOut -= nIter;
4743 /* TUNING: Because uncertainties in the estimates for skip-scan queries,
4744 ** add a 1.375 fudge factor to make skip-scan slightly less likely. */
4745 nIter += 5;
4746 whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nIter + nInMul);
4747 pNew->nOut = saved_nOut;
4748 pNew->u.btree.nEq = saved_nEq;
4749 pNew->nSkip = saved_nSkip;
4750 pNew->wsFlags = saved_wsFlags;
4751 }
4752
drh5346e952013-05-08 14:14:26 +00004753 return rc;
drh1c8148f2013-05-04 20:25:23 +00004754}
4755
4756/*
drh23f98da2013-05-21 15:52:07 +00004757** Return True if it is possible that pIndex might be useful in
4758** implementing the ORDER BY clause in pBuilder.
4759**
4760** Return False if pBuilder does not contain an ORDER BY clause or
4761** if there is no way for pIndex to be useful in implementing that
4762** ORDER BY clause.
4763*/
4764static int indexMightHelpWithOrderBy(
4765 WhereLoopBuilder *pBuilder,
4766 Index *pIndex,
4767 int iCursor
4768){
4769 ExprList *pOB;
drh6d381472013-06-13 17:58:08 +00004770 int ii, jj;
drh23f98da2013-05-21 15:52:07 +00004771
drh53cfbe92013-06-13 17:28:22 +00004772 if( pIndex->bUnordered ) return 0;
drh70d18342013-06-06 19:16:33 +00004773 if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
drh23f98da2013-05-21 15:52:07 +00004774 for(ii=0; ii<pOB->nExpr; ii++){
drh45c154a2013-06-03 20:46:35 +00004775 Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr);
drh23f98da2013-05-21 15:52:07 +00004776 if( pExpr->op!=TK_COLUMN ) return 0;
4777 if( pExpr->iTable==iCursor ){
drh137fd4f2014-09-19 02:01:37 +00004778 if( pExpr->iColumn<0 ) return 1;
drhbbbdc832013-10-22 18:01:40 +00004779 for(jj=0; jj<pIndex->nKeyCol; jj++){
drh6d381472013-06-13 17:58:08 +00004780 if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
4781 }
drh23f98da2013-05-21 15:52:07 +00004782 }
4783 }
4784 return 0;
4785}
4786
4787/*
drh92a121f2013-06-10 12:15:47 +00004788** Return a bitmask where 1s indicate that the corresponding column of
4789** the table is used by an index. Only the first 63 columns are considered.
4790*/
drhfd5874d2013-06-12 14:52:39 +00004791static Bitmask columnsInIndex(Index *pIdx){
drh92a121f2013-06-10 12:15:47 +00004792 Bitmask m = 0;
4793 int j;
drhec95c442013-10-23 01:57:32 +00004794 for(j=pIdx->nColumn-1; j>=0; j--){
drh92a121f2013-06-10 12:15:47 +00004795 int x = pIdx->aiColumn[j];
drhec95c442013-10-23 01:57:32 +00004796 if( x>=0 ){
4797 testcase( x==BMS-1 );
4798 testcase( x==BMS-2 );
4799 if( x<BMS-1 ) m |= MASKBIT(x);
4800 }
drh92a121f2013-06-10 12:15:47 +00004801 }
4802 return m;
4803}
4804
drh4bd5f732013-07-31 23:22:39 +00004805/* Check to see if a partial index with pPartIndexWhere can be used
4806** in the current query. Return true if it can be and false if not.
4807*/
4808static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere){
4809 int i;
4810 WhereTerm *pTerm;
4811 for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
dan2a45cb52015-02-24 20:10:49 +00004812 Expr *pExpr = pTerm->pExpr;
4813 if( sqlite3ExprImpliesExpr(pExpr, pWhere, iTab)
4814 && (!ExprHasProperty(pExpr, EP_FromJoin) || pExpr->iRightJoinTable==iTab)
drh077f06e2015-02-24 16:48:59 +00004815 ){
4816 return 1;
4817 }
drh4bd5f732013-07-31 23:22:39 +00004818 }
4819 return 0;
4820}
drh92a121f2013-06-10 12:15:47 +00004821
4822/*
dan51576f42013-07-02 10:06:15 +00004823** Add all WhereLoop objects for a single table of the join where the table
drh0823c892013-05-11 00:06:23 +00004824** is idenfied by pBuilder->pNew->iTab. That table is guaranteed to be
4825** a b-tree table, not a virtual table.
dan81647222014-04-30 15:00:16 +00004826**
4827** The costs (WhereLoop.rRun) of the b-tree loops added by this function
4828** are calculated as follows:
4829**
4830** For a full scan, assuming the table (or index) contains nRow rows:
4831**
4832** cost = nRow * 3.0 // full-table scan
4833** cost = nRow * K // scan of covering index
4834** cost = nRow * (K+3.0) // scan of non-covering index
4835**
4836** where K is a value between 1.1 and 3.0 set based on the relative
4837** estimated average size of the index and table records.
4838**
4839** For an index scan, where nVisit is the number of index rows visited
4840** by the scan, and nSeek is the number of seek operations required on
4841** the index b-tree:
4842**
4843** cost = nSeek * (log(nRow) + K * nVisit) // covering index
4844** cost = nSeek * (log(nRow) + (K+3.0) * nVisit) // non-covering index
4845**
4846** Normally, nSeek is 1. nSeek values greater than 1 come about if the
4847** WHERE clause includes "x IN (....)" terms used in place of "x=?". Or when
4848** implicit "x IN (SELECT x FROM tbl)" terms are added for skip-scans.
drh83a305f2014-07-22 12:05:32 +00004849**
4850** The estimated values (nRow, nVisit, nSeek) often contain a large amount
4851** of uncertainty. For this reason, scoring is designed to pick plans that
4852** "do the least harm" if the estimates are inaccurate. For example, a
4853** log(nRow) factor is omitted from a non-covering index scan in order to
4854** bias the scoring in favor of using an index, since the worst-case
4855** performance of using an index is far better than the worst-case performance
4856** of a full table scan.
drhf1b5f5b2013-05-02 00:15:01 +00004857*/
drh5346e952013-05-08 14:14:26 +00004858static int whereLoopAddBtree(
drh1c8148f2013-05-04 20:25:23 +00004859 WhereLoopBuilder *pBuilder, /* WHERE clause information */
drh1c8148f2013-05-04 20:25:23 +00004860 Bitmask mExtra /* Extra prerequesites for using this table */
drhf1b5f5b2013-05-02 00:15:01 +00004861){
drh70d18342013-06-06 19:16:33 +00004862 WhereInfo *pWInfo; /* WHERE analysis context */
drh1c8148f2013-05-04 20:25:23 +00004863 Index *pProbe; /* An index we are evaluating */
drh1c8148f2013-05-04 20:25:23 +00004864 Index sPk; /* A fake index object for the primary key */
dancfc9df72014-04-25 15:01:01 +00004865 LogEst aiRowEstPk[2]; /* The aiRowLogEst[] value for the sPk index */
drhbbbdc832013-10-22 18:01:40 +00004866 i16 aiColumnPk = -1; /* The aColumn[] value for the sPk index */
drh70d18342013-06-06 19:16:33 +00004867 SrcList *pTabList; /* The FROM clause */
drh1c8148f2013-05-04 20:25:23 +00004868 struct SrcList_item *pSrc; /* The FROM clause btree term to add */
drh1c8148f2013-05-04 20:25:23 +00004869 WhereLoop *pNew; /* Template WhereLoop object */
drh5346e952013-05-08 14:14:26 +00004870 int rc = SQLITE_OK; /* Return code */
drhd044d202013-05-31 12:43:55 +00004871 int iSortIdx = 1; /* Index number */
drh23f98da2013-05-21 15:52:07 +00004872 int b; /* A boolean value */
drhbf539c42013-10-05 18:16:02 +00004873 LogEst rSize; /* number of rows in the table */
4874 LogEst rLogSize; /* Logarithm of the number of rows in the table */
drh4bd5f732013-07-31 23:22:39 +00004875 WhereClause *pWC; /* The parsed WHERE clause */
drh3495d202013-10-07 17:32:15 +00004876 Table *pTab; /* Table being queried */
drh23f98da2013-05-21 15:52:07 +00004877
drh1c8148f2013-05-04 20:25:23 +00004878 pNew = pBuilder->pNew;
drh70d18342013-06-06 19:16:33 +00004879 pWInfo = pBuilder->pWInfo;
4880 pTabList = pWInfo->pTabList;
4881 pSrc = pTabList->a + pNew->iTab;
drh3495d202013-10-07 17:32:15 +00004882 pTab = pSrc->pTab;
drh4bd5f732013-07-31 23:22:39 +00004883 pWC = pBuilder->pWC;
drh0823c892013-05-11 00:06:23 +00004884 assert( !IsVirtual(pSrc->pTab) );
drh1c8148f2013-05-04 20:25:23 +00004885
4886 if( pSrc->pIndex ){
4887 /* An INDEXED BY clause specifies a particular index to use */
4888 pProbe = pSrc->pIndex;
drhec95c442013-10-23 01:57:32 +00004889 }else if( !HasRowid(pTab) ){
4890 pProbe = pTab->pIndex;
drh1c8148f2013-05-04 20:25:23 +00004891 }else{
4892 /* There is no INDEXED BY clause. Create a fake Index object in local
4893 ** variable sPk to represent the rowid primary key index. Make this
4894 ** fake index the first in a chain of Index objects with all of the real
4895 ** indices to follow */
4896 Index *pFirst; /* First of real indices on the table */
4897 memset(&sPk, 0, sizeof(Index));
drhbbbdc832013-10-22 18:01:40 +00004898 sPk.nKeyCol = 1;
dan39129ce2014-06-30 15:23:57 +00004899 sPk.nColumn = 1;
drh1c8148f2013-05-04 20:25:23 +00004900 sPk.aiColumn = &aiColumnPk;
dancfc9df72014-04-25 15:01:01 +00004901 sPk.aiRowLogEst = aiRowEstPk;
drh1c8148f2013-05-04 20:25:23 +00004902 sPk.onError = OE_Replace;
drh3495d202013-10-07 17:32:15 +00004903 sPk.pTable = pTab;
danaa9933c2014-04-24 20:04:49 +00004904 sPk.szIdxRow = pTab->szTabRow;
dancfc9df72014-04-25 15:01:01 +00004905 aiRowEstPk[0] = pTab->nRowLogEst;
4906 aiRowEstPk[1] = 0;
drh1c8148f2013-05-04 20:25:23 +00004907 pFirst = pSrc->pTab->pIndex;
4908 if( pSrc->notIndexed==0 ){
4909 /* The real indices of the table are only considered if the
4910 ** NOT INDEXED qualifier is omitted from the FROM clause */
4911 sPk.pNext = pFirst;
4912 }
4913 pProbe = &sPk;
4914 }
dancfc9df72014-04-25 15:01:01 +00004915 rSize = pTab->nRowLogEst;
drheb04de32013-05-10 15:16:30 +00004916 rLogSize = estLog(rSize);
4917
drhfeb56e02013-08-23 17:33:46 +00004918#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
drheb04de32013-05-10 15:16:30 +00004919 /* Automatic indexes */
drhaa32e3c2013-07-16 21:31:23 +00004920 if( !pBuilder->pOrSet
drh8e8e7ef2015-03-02 17:25:00 +00004921 && (pWInfo->wctrlFlags & WHERE_NO_AUTOINDEX)==0
drh4fe425a2013-06-12 17:08:06 +00004922 && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
4923 && pSrc->pIndex==0
drheb04de32013-05-10 15:16:30 +00004924 && !pSrc->viaCoroutine
4925 && !pSrc->notIndexed
drhec95c442013-10-23 01:57:32 +00004926 && HasRowid(pTab)
drheb04de32013-05-10 15:16:30 +00004927 && !pSrc->isCorrelated
dan62ba4e42014-01-15 18:21:41 +00004928 && !pSrc->isRecursive
drheb04de32013-05-10 15:16:30 +00004929 ){
4930 /* Generate auto-index WhereLoops */
drheb04de32013-05-10 15:16:30 +00004931 WhereTerm *pTerm;
4932 WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
4933 for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
drh79a13bf2013-05-31 20:28:28 +00004934 if( pTerm->prereqRight & pNew->maskSelf ) continue;
drheb04de32013-05-10 15:16:30 +00004935 if( termCanDriveIndex(pTerm, pSrc, 0) ){
4936 pNew->u.btree.nEq = 1;
drhc8bbce12014-10-21 01:05:09 +00004937 pNew->nSkip = 0;
drhef866372013-05-22 20:49:02 +00004938 pNew->u.btree.pIndex = 0;
drh4efc9292013-06-06 23:02:03 +00004939 pNew->nLTerm = 1;
4940 pNew->aLTerm[0] = pTerm;
drhe1e2e9a2013-06-13 15:16:53 +00004941 /* TUNING: One-time cost for computing the automatic index is
drh7e074332014-09-22 14:30:51 +00004942 ** estimated to be X*N*log2(N) where N is the number of rows in
4943 ** the table being indexed and where X is 7 (LogEst=28) for normal
4944 ** tables or 1.375 (LogEst=4) for views and subqueries. The value
4945 ** of X is smaller for views and subqueries so that the query planner
4946 ** will be more aggressive about generating automatic indexes for
4947 ** those objects, since there is no opportunity to add schema
4948 ** indexes on subqueries and views. */
4949 pNew->rSetup = rLogSize + rSize + 4;
4950 if( pTab->pSelect==0 && (pTab->tabFlags & TF_Ephemeral)==0 ){
4951 pNew->rSetup += 24;
4952 }
drhdbd94862014-07-23 23:57:42 +00004953 ApplyCostMultiplier(pNew->rSetup, pTab->costMult);
drh986b3872013-06-28 21:12:20 +00004954 /* TUNING: Each index lookup yields 20 rows in the table. This
4955 ** is more than the usual guess of 10 rows, since we have no way
peter.d.reid60ec9142014-09-06 16:39:46 +00004956 ** of knowing how selective the index will ultimately be. It would
drh986b3872013-06-28 21:12:20 +00004957 ** not be unreasonable to make this value much larger. */
drhbf539c42013-10-05 18:16:02 +00004958 pNew->nOut = 43; assert( 43==sqlite3LogEst(20) );
drhb50596d2013-10-08 20:42:41 +00004959 pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut);
drh986b3872013-06-28 21:12:20 +00004960 pNew->wsFlags = WHERE_AUTO_INDEX;
drheb04de32013-05-10 15:16:30 +00004961 pNew->prereq = mExtra | pTerm->prereqRight;
drhcf8fa7a2013-05-10 20:26:22 +00004962 rc = whereLoopInsert(pBuilder, pNew);
drheb04de32013-05-10 15:16:30 +00004963 }
4964 }
4965 }
drhfeb56e02013-08-23 17:33:46 +00004966#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
drh1c8148f2013-05-04 20:25:23 +00004967
4968 /* Loop over all indices
4969 */
drh23f98da2013-05-21 15:52:07 +00004970 for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){
drh4bd5f732013-07-31 23:22:39 +00004971 if( pProbe->pPartIdxWhere!=0
dan08291692014-08-27 17:37:20 +00004972 && !whereUsablePartialIndex(pSrc->iCursor, pWC, pProbe->pPartIdxWhere) ){
4973 testcase( pNew->iTab!=pSrc->iCursor ); /* See ticket [98d973b8f5] */
drh4bd5f732013-07-31 23:22:39 +00004974 continue; /* Partial index inappropriate for this query */
4975 }
dan7de2a1f2014-04-28 20:11:20 +00004976 rSize = pProbe->aiRowLogEst[0];
drh5346e952013-05-08 14:14:26 +00004977 pNew->u.btree.nEq = 0;
drhc8bbce12014-10-21 01:05:09 +00004978 pNew->nSkip = 0;
drh4efc9292013-06-06 23:02:03 +00004979 pNew->nLTerm = 0;
drh23f98da2013-05-21 15:52:07 +00004980 pNew->iSortIdx = 0;
drhb8a8e8a2013-06-10 19:12:39 +00004981 pNew->rSetup = 0;
drh23f98da2013-05-21 15:52:07 +00004982 pNew->prereq = mExtra;
drh74f91d42013-06-19 18:01:44 +00004983 pNew->nOut = rSize;
drh23f98da2013-05-21 15:52:07 +00004984 pNew->u.btree.pIndex = pProbe;
4985 b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
drh53cfbe92013-06-13 17:28:22 +00004986 /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
4987 assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
drh43fe25f2013-05-07 23:06:23 +00004988 if( pProbe->tnum<=0 ){
4989 /* Integer primary key index */
4990 pNew->wsFlags = WHERE_IPK;
drh23f98da2013-05-21 15:52:07 +00004991
4992 /* Full table scan */
drhd044d202013-05-31 12:43:55 +00004993 pNew->iSortIdx = b ? iSortIdx : 0;
danaa9933c2014-04-24 20:04:49 +00004994 /* TUNING: Cost of full table scan is (N*3.0). */
4995 pNew->rRun = rSize + 16;
drhdbd94862014-07-23 23:57:42 +00004996 ApplyCostMultiplier(pNew->rRun, pTab->costMult);
drhd8b77e22014-09-06 01:35:57 +00004997 whereLoopOutputAdjust(pWC, pNew, rSize);
drh23f98da2013-05-21 15:52:07 +00004998 rc = whereLoopInsert(pBuilder, pNew);
drhcca9f3d2013-09-06 15:23:29 +00004999 pNew->nOut = rSize;
drh23f98da2013-05-21 15:52:07 +00005000 if( rc ) break;
drh43fe25f2013-05-07 23:06:23 +00005001 }else{
drhec95c442013-10-23 01:57:32 +00005002 Bitmask m;
5003 if( pProbe->isCovering ){
5004 pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
5005 m = 0;
5006 }else{
5007 m = pSrc->colUsed & ~columnsInIndex(pProbe);
5008 pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
5009 }
drh1c8148f2013-05-04 20:25:23 +00005010
drh23f98da2013-05-21 15:52:07 +00005011 /* Full scan via index */
drh53cfbe92013-06-13 17:28:22 +00005012 if( b
drh702ba9f2013-11-07 21:25:13 +00005013 || !HasRowid(pTab)
drh53cfbe92013-06-13 17:28:22 +00005014 || ( m==0
5015 && pProbe->bUnordered==0
drh702ba9f2013-11-07 21:25:13 +00005016 && (pProbe->szIdxRow<pTab->szTabRow)
drh53cfbe92013-06-13 17:28:22 +00005017 && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
5018 && sqlite3GlobalConfig.bUseCis
5019 && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
5020 )
drhe3b7c922013-06-03 19:17:40 +00005021 ){
drh23f98da2013-05-21 15:52:07 +00005022 pNew->iSortIdx = b ? iSortIdx : 0;
danaa9933c2014-04-24 20:04:49 +00005023
5024 /* The cost of visiting the index rows is N*K, where K is
5025 ** between 1.1 and 3.0, depending on the relative sizes of the
5026 ** index and table rows. If this is a non-covering index scan,
5027 ** also add the cost of visiting table rows (N*3.0). */
5028 pNew->rRun = rSize + 1 + (15*pProbe->szIdxRow)/pTab->szTabRow;
5029 if( m!=0 ){
5030 pNew->rRun = sqlite3LogEstAdd(pNew->rRun, rSize+16);
drhe1e2e9a2013-06-13 15:16:53 +00005031 }
drhdbd94862014-07-23 23:57:42 +00005032 ApplyCostMultiplier(pNew->rRun, pTab->costMult);
drhd8b77e22014-09-06 01:35:57 +00005033 whereLoopOutputAdjust(pWC, pNew, rSize);
drh23f98da2013-05-21 15:52:07 +00005034 rc = whereLoopInsert(pBuilder, pNew);
drhcca9f3d2013-09-06 15:23:29 +00005035 pNew->nOut = rSize;
drh23f98da2013-05-21 15:52:07 +00005036 if( rc ) break;
5037 }
5038 }
dan7a419232013-08-06 20:01:43 +00005039
drhb8a8e8a2013-06-10 19:12:39 +00005040 rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
drh1435a9a2013-08-27 23:15:44 +00005041#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
dan87cd9322013-08-07 15:52:41 +00005042 sqlite3Stat4ProbeFree(pBuilder->pRec);
5043 pBuilder->nRecValid = 0;
5044 pBuilder->pRec = 0;
danddc2d6e2013-08-06 20:15:06 +00005045#endif
drh1c8148f2013-05-04 20:25:23 +00005046
5047 /* If there was an INDEXED BY clause, then only that one index is
5048 ** considered. */
5049 if( pSrc->pIndex ) break;
5050 }
drh5346e952013-05-08 14:14:26 +00005051 return rc;
drhf1b5f5b2013-05-02 00:15:01 +00005052}
5053
drh8636e9c2013-06-11 01:50:08 +00005054#ifndef SQLITE_OMIT_VIRTUALTABLE
drhf1b5f5b2013-05-02 00:15:01 +00005055/*
drh0823c892013-05-11 00:06:23 +00005056** Add all WhereLoop objects for a table of the join identified by
5057** pBuilder->pNew->iTab. That table is guaranteed to be a virtual table.
drhf1b5f5b2013-05-02 00:15:01 +00005058*/
drh5346e952013-05-08 14:14:26 +00005059static int whereLoopAddVirtual(
danff4b23b2013-11-12 12:17:16 +00005060 WhereLoopBuilder *pBuilder, /* WHERE clause information */
5061 Bitmask mExtra
drhf1b5f5b2013-05-02 00:15:01 +00005062){
drh70d18342013-06-06 19:16:33 +00005063 WhereInfo *pWInfo; /* WHERE analysis context */
drh5346e952013-05-08 14:14:26 +00005064 Parse *pParse; /* The parsing context */
5065 WhereClause *pWC; /* The WHERE clause */
5066 struct SrcList_item *pSrc; /* The FROM clause term to search */
5067 Table *pTab;
5068 sqlite3 *db;
5069 sqlite3_index_info *pIdxInfo;
5070 struct sqlite3_index_constraint *pIdxCons;
5071 struct sqlite3_index_constraint_usage *pUsage;
5072 WhereTerm *pTerm;
5073 int i, j;
5074 int iTerm, mxTerm;
drh4efc9292013-06-06 23:02:03 +00005075 int nConstraint;
drh5346e952013-05-08 14:14:26 +00005076 int seenIn = 0; /* True if an IN operator is seen */
5077 int seenVar = 0; /* True if a non-constant constraint is seen */
5078 int iPhase; /* 0: const w/o IN, 1: const, 2: no IN, 2: IN */
5079 WhereLoop *pNew;
drh5346e952013-05-08 14:14:26 +00005080 int rc = SQLITE_OK;
5081
drh70d18342013-06-06 19:16:33 +00005082 pWInfo = pBuilder->pWInfo;
5083 pParse = pWInfo->pParse;
drh5346e952013-05-08 14:14:26 +00005084 db = pParse->db;
5085 pWC = pBuilder->pWC;
drh5346e952013-05-08 14:14:26 +00005086 pNew = pBuilder->pNew;
drh70d18342013-06-06 19:16:33 +00005087 pSrc = &pWInfo->pTabList->a[pNew->iTab];
drhb2a90f02013-05-10 03:30:49 +00005088 pTab = pSrc->pTab;
drh0823c892013-05-11 00:06:23 +00005089 assert( IsVirtual(pTab) );
drhb2a90f02013-05-10 03:30:49 +00005090 pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pBuilder->pOrderBy);
drh5346e952013-05-08 14:14:26 +00005091 if( pIdxInfo==0 ) return SQLITE_NOMEM;
drh5346e952013-05-08 14:14:26 +00005092 pNew->prereq = 0;
drh5346e952013-05-08 14:14:26 +00005093 pNew->rSetup = 0;
5094 pNew->wsFlags = WHERE_VIRTUALTABLE;
drh4efc9292013-06-06 23:02:03 +00005095 pNew->nLTerm = 0;
drh5346e952013-05-08 14:14:26 +00005096 pNew->u.vtab.needFree = 0;
5097 pUsage = pIdxInfo->aConstraintUsage;
drh4efc9292013-06-06 23:02:03 +00005098 nConstraint = pIdxInfo->nConstraint;
drh7963b0e2013-06-17 21:37:40 +00005099 if( whereLoopResize(db, pNew, nConstraint) ){
5100 sqlite3DbFree(db, pIdxInfo);
5101 return SQLITE_NOMEM;
5102 }
drh5346e952013-05-08 14:14:26 +00005103
drh0823c892013-05-11 00:06:23 +00005104 for(iPhase=0; iPhase<=3; iPhase++){
drh5346e952013-05-08 14:14:26 +00005105 if( !seenIn && (iPhase&1)!=0 ){
5106 iPhase++;
5107 if( iPhase>3 ) break;
5108 }
5109 if( !seenVar && iPhase>1 ) break;
5110 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
5111 for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
5112 j = pIdxCons->iTermOffset;
5113 pTerm = &pWC->a[j];
5114 switch( iPhase ){
5115 case 0: /* Constants without IN operator */
5116 pIdxCons->usable = 0;
5117 if( (pTerm->eOperator & WO_IN)!=0 ){
5118 seenIn = 1;
drh7963b0e2013-06-17 21:37:40 +00005119 }
5120 if( pTerm->prereqRight!=0 ){
drh5346e952013-05-08 14:14:26 +00005121 seenVar = 1;
drh7963b0e2013-06-17 21:37:40 +00005122 }else if( (pTerm->eOperator & WO_IN)==0 ){
drh5346e952013-05-08 14:14:26 +00005123 pIdxCons->usable = 1;
5124 }
5125 break;
5126 case 1: /* Constants with IN operators */
5127 assert( seenIn );
5128 pIdxCons->usable = (pTerm->prereqRight==0);
5129 break;
5130 case 2: /* Variables without IN */
5131 assert( seenVar );
5132 pIdxCons->usable = (pTerm->eOperator & WO_IN)==0;
5133 break;
5134 default: /* Variables with IN */
5135 assert( seenVar && seenIn );
5136 pIdxCons->usable = 1;
5137 break;
5138 }
5139 }
5140 memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
5141 if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
5142 pIdxInfo->idxStr = 0;
5143 pIdxInfo->idxNum = 0;
5144 pIdxInfo->needToFreeIdxStr = 0;
5145 pIdxInfo->orderByConsumed = 0;
drh8636e9c2013-06-11 01:50:08 +00005146 pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
dana9f58152013-11-11 19:01:33 +00005147 pIdxInfo->estimatedRows = 25;
drh5346e952013-05-08 14:14:26 +00005148 rc = vtabBestIndex(pParse, pTab, pIdxInfo);
5149 if( rc ) goto whereLoopAddVtab_exit;
5150 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
danff4b23b2013-11-12 12:17:16 +00005151 pNew->prereq = mExtra;
drhc718f1c2013-05-08 20:05:58 +00005152 mxTerm = -1;
drh4efc9292013-06-06 23:02:03 +00005153 assert( pNew->nLSlot>=nConstraint );
5154 for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
drh3bd26f02013-05-24 14:52:03 +00005155 pNew->u.vtab.omitMask = 0;
drh4efc9292013-06-06 23:02:03 +00005156 for(i=0; i<nConstraint; i++, pIdxCons++){
drh5346e952013-05-08 14:14:26 +00005157 if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
5158 j = pIdxCons->iTermOffset;
drh4efc9292013-06-06 23:02:03 +00005159 if( iTerm>=nConstraint
drh5346e952013-05-08 14:14:26 +00005160 || j<0
5161 || j>=pWC->nTerm
drh4efc9292013-06-06 23:02:03 +00005162 || pNew->aLTerm[iTerm]!=0
drh5346e952013-05-08 14:14:26 +00005163 ){
5164 rc = SQLITE_ERROR;
5165 sqlite3ErrorMsg(pParse, "%s.xBestIndex() malfunction", pTab->zName);
5166 goto whereLoopAddVtab_exit;
5167 }
drh7963b0e2013-06-17 21:37:40 +00005168 testcase( iTerm==nConstraint-1 );
5169 testcase( j==0 );
5170 testcase( j==pWC->nTerm-1 );
drh5346e952013-05-08 14:14:26 +00005171 pTerm = &pWC->a[j];
5172 pNew->prereq |= pTerm->prereqRight;
drh4efc9292013-06-06 23:02:03 +00005173 assert( iTerm<pNew->nLSlot );
5174 pNew->aLTerm[iTerm] = pTerm;
drh5346e952013-05-08 14:14:26 +00005175 if( iTerm>mxTerm ) mxTerm = iTerm;
drh7963b0e2013-06-17 21:37:40 +00005176 testcase( iTerm==15 );
5177 testcase( iTerm==16 );
drh52986302013-06-03 16:03:16 +00005178 if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm;
drh5346e952013-05-08 14:14:26 +00005179 if( (pTerm->eOperator & WO_IN)!=0 ){
5180 if( pUsage[i].omit==0 ){
5181 /* Do not attempt to use an IN constraint if the virtual table
5182 ** says that the equivalent EQ constraint cannot be safely omitted.
5183 ** If we do attempt to use such a constraint, some rows might be
5184 ** repeated in the output. */
5185 break;
5186 }
5187 /* A virtual table that is constrained by an IN clause may not
5188 ** consume the ORDER BY clause because (1) the order of IN terms
5189 ** is not necessarily related to the order of output terms and
5190 ** (2) Multiple outputs from a single IN value will not merge
5191 ** together. */
5192 pIdxInfo->orderByConsumed = 0;
5193 }
5194 }
5195 }
drh4efc9292013-06-06 23:02:03 +00005196 if( i>=nConstraint ){
5197 pNew->nLTerm = mxTerm+1;
5198 assert( pNew->nLTerm<=pNew->nLSlot );
drh5346e952013-05-08 14:14:26 +00005199 pNew->u.vtab.idxNum = pIdxInfo->idxNum;
5200 pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
5201 pIdxInfo->needToFreeIdxStr = 0;
5202 pNew->u.vtab.idxStr = pIdxInfo->idxStr;
drh0401ace2014-03-18 15:30:27 +00005203 pNew->u.vtab.isOrdered = (i8)(pIdxInfo->orderByConsumed ?
5204 pIdxInfo->nOrderBy : 0);
drhb8a8e8a2013-06-10 19:12:39 +00005205 pNew->rSetup = 0;
drhb50596d2013-10-08 20:42:41 +00005206 pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost);
dana9f58152013-11-11 19:01:33 +00005207 pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows);
drhcf8fa7a2013-05-10 20:26:22 +00005208 whereLoopInsert(pBuilder, pNew);
drh5346e952013-05-08 14:14:26 +00005209 if( pNew->u.vtab.needFree ){
5210 sqlite3_free(pNew->u.vtab.idxStr);
5211 pNew->u.vtab.needFree = 0;
5212 }
5213 }
5214 }
5215
5216whereLoopAddVtab_exit:
5217 if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
5218 sqlite3DbFree(db, pIdxInfo);
5219 return rc;
drhf1b5f5b2013-05-02 00:15:01 +00005220}
drh8636e9c2013-06-11 01:50:08 +00005221#endif /* SQLITE_OMIT_VIRTUALTABLE */
drhf1b5f5b2013-05-02 00:15:01 +00005222
5223/*
drhcf8fa7a2013-05-10 20:26:22 +00005224** Add WhereLoop entries to handle OR terms. This works for either
5225** btrees or virtual tables.
5226*/
5227static int whereLoopAddOr(WhereLoopBuilder *pBuilder, Bitmask mExtra){
drh70d18342013-06-06 19:16:33 +00005228 WhereInfo *pWInfo = pBuilder->pWInfo;
drhcf8fa7a2013-05-10 20:26:22 +00005229 WhereClause *pWC;
5230 WhereLoop *pNew;
5231 WhereTerm *pTerm, *pWCEnd;
5232 int rc = SQLITE_OK;
5233 int iCur;
5234 WhereClause tempWC;
5235 WhereLoopBuilder sSubBuild;
dan5da73e12014-04-30 18:11:55 +00005236 WhereOrSet sSum, sCur;
drhcf8fa7a2013-05-10 20:26:22 +00005237 struct SrcList_item *pItem;
5238
drhcf8fa7a2013-05-10 20:26:22 +00005239 pWC = pBuilder->pWC;
drhcf8fa7a2013-05-10 20:26:22 +00005240 pWCEnd = pWC->a + pWC->nTerm;
5241 pNew = pBuilder->pNew;
drh77dfd5b2013-08-19 11:15:48 +00005242 memset(&sSum, 0, sizeof(sSum));
drh186ad8c2013-10-08 18:40:37 +00005243 pItem = pWInfo->pTabList->a + pNew->iTab;
5244 iCur = pItem->iCursor;
drhcf8fa7a2013-05-10 20:26:22 +00005245
5246 for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
5247 if( (pTerm->eOperator & WO_OR)!=0
5248 && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
5249 ){
5250 WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
5251 WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
5252 WhereTerm *pOrTerm;
drhaa32e3c2013-07-16 21:31:23 +00005253 int once = 1;
5254 int i, j;
drh783dece2013-06-05 17:53:43 +00005255
drh783dece2013-06-05 17:53:43 +00005256 sSubBuild = *pBuilder;
5257 sSubBuild.pOrderBy = 0;
drhaa32e3c2013-07-16 21:31:23 +00005258 sSubBuild.pOrSet = &sCur;
drhcf8fa7a2013-05-10 20:26:22 +00005259
drh0a99ba32014-09-30 17:03:35 +00005260 WHERETRACE(0x200, ("Begin processing OR-clause %p\n", pTerm));
drhc7f0d222013-06-19 03:27:12 +00005261 for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
drh783dece2013-06-05 17:53:43 +00005262 if( (pOrTerm->eOperator & WO_AND)!=0 ){
drhcf8fa7a2013-05-10 20:26:22 +00005263 sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
5264 }else if( pOrTerm->leftCursor==iCur ){
drh70d18342013-06-06 19:16:33 +00005265 tempWC.pWInfo = pWC->pWInfo;
drh783dece2013-06-05 17:53:43 +00005266 tempWC.pOuter = pWC;
5267 tempWC.op = TK_AND;
drh783dece2013-06-05 17:53:43 +00005268 tempWC.nTerm = 1;
drhcf8fa7a2013-05-10 20:26:22 +00005269 tempWC.a = pOrTerm;
5270 sSubBuild.pWC = &tempWC;
5271 }else{
5272 continue;
5273 }
drhaa32e3c2013-07-16 21:31:23 +00005274 sCur.n = 0;
drh52651492014-09-30 14:14:19 +00005275#ifdef WHERETRACE_ENABLED
drh0a99ba32014-09-30 17:03:35 +00005276 WHERETRACE(0x200, ("OR-term %d of %p has %d subterms:\n",
5277 (int)(pOrTerm-pOrWC->a), pTerm, sSubBuild.pWC->nTerm));
5278 if( sqlite3WhereTrace & 0x400 ){
5279 for(i=0; i<sSubBuild.pWC->nTerm; i++){
5280 whereTermPrint(&sSubBuild.pWC->a[i], i);
5281 }
drh52651492014-09-30 14:14:19 +00005282 }
5283#endif
drh8636e9c2013-06-11 01:50:08 +00005284#ifndef SQLITE_OMIT_VIRTUALTABLE
drhcf8fa7a2013-05-10 20:26:22 +00005285 if( IsVirtual(pItem->pTab) ){
danff4b23b2013-11-12 12:17:16 +00005286 rc = whereLoopAddVirtual(&sSubBuild, mExtra);
drh8636e9c2013-06-11 01:50:08 +00005287 }else
5288#endif
5289 {
drhcf8fa7a2013-05-10 20:26:22 +00005290 rc = whereLoopAddBtree(&sSubBuild, mExtra);
5291 }
drh36be4c42014-09-30 17:31:23 +00005292 if( rc==SQLITE_OK ){
5293 rc = whereLoopAddOr(&sSubBuild, mExtra);
5294 }
drhaa32e3c2013-07-16 21:31:23 +00005295 assert( rc==SQLITE_OK || sCur.n==0 );
5296 if( sCur.n==0 ){
5297 sSum.n = 0;
5298 break;
5299 }else if( once ){
5300 whereOrMove(&sSum, &sCur);
5301 once = 0;
5302 }else{
dan5da73e12014-04-30 18:11:55 +00005303 WhereOrSet sPrev;
drhaa32e3c2013-07-16 21:31:23 +00005304 whereOrMove(&sPrev, &sSum);
5305 sSum.n = 0;
5306 for(i=0; i<sPrev.n; i++){
5307 for(j=0; j<sCur.n; j++){
5308 whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,
drhbf539c42013-10-05 18:16:02 +00005309 sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
5310 sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
drhaa32e3c2013-07-16 21:31:23 +00005311 }
5312 }
5313 }
drhcf8fa7a2013-05-10 20:26:22 +00005314 }
drhaa32e3c2013-07-16 21:31:23 +00005315 pNew->nLTerm = 1;
5316 pNew->aLTerm[0] = pTerm;
5317 pNew->wsFlags = WHERE_MULTI_OR;
5318 pNew->rSetup = 0;
5319 pNew->iSortIdx = 0;
5320 memset(&pNew->u, 0, sizeof(pNew->u));
5321 for(i=0; rc==SQLITE_OK && i<sSum.n; i++){
dan5da73e12014-04-30 18:11:55 +00005322 /* TUNING: Currently sSum.a[i].rRun is set to the sum of the costs
5323 ** of all sub-scans required by the OR-scan. However, due to rounding
5324 ** errors, it may be that the cost of the OR-scan is equal to its
5325 ** most expensive sub-scan. Add the smallest possible penalty
5326 ** (equivalent to multiplying the cost by 1.07) to ensure that
5327 ** this does not happen. Otherwise, for WHERE clauses such as the
5328 ** following where there is an index on "y":
5329 **
5330 ** WHERE likelihood(x=?, 0.99) OR y=?
5331 **
5332 ** the planner may elect to "OR" together a full-table scan and an
5333 ** index lookup. And other similarly odd results. */
5334 pNew->rRun = sSum.a[i].rRun + 1;
drhaa32e3c2013-07-16 21:31:23 +00005335 pNew->nOut = sSum.a[i].nOut;
5336 pNew->prereq = sSum.a[i].prereq;
drhfd5874d2013-06-12 14:52:39 +00005337 rc = whereLoopInsert(pBuilder, pNew);
5338 }
drh0a99ba32014-09-30 17:03:35 +00005339 WHERETRACE(0x200, ("End processing OR-clause %p\n", pTerm));
drhcf8fa7a2013-05-10 20:26:22 +00005340 }
5341 }
5342 return rc;
5343}
5344
5345/*
drhf1b5f5b2013-05-02 00:15:01 +00005346** Add all WhereLoop objects for all tables
5347*/
drh5346e952013-05-08 14:14:26 +00005348static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
drh70d18342013-06-06 19:16:33 +00005349 WhereInfo *pWInfo = pBuilder->pWInfo;
drhf1b5f5b2013-05-02 00:15:01 +00005350 Bitmask mExtra = 0;
5351 Bitmask mPrior = 0;
5352 int iTab;
drh70d18342013-06-06 19:16:33 +00005353 SrcList *pTabList = pWInfo->pTabList;
drhf1b5f5b2013-05-02 00:15:01 +00005354 struct SrcList_item *pItem;
drh70d18342013-06-06 19:16:33 +00005355 sqlite3 *db = pWInfo->pParse->db;
5356 int nTabList = pWInfo->nLevel;
drh5346e952013-05-08 14:14:26 +00005357 int rc = SQLITE_OK;
drhc63367e2013-06-10 20:46:50 +00005358 u8 priorJoinType = 0;
drhb8a8e8a2013-06-10 19:12:39 +00005359 WhereLoop *pNew;
drhf1b5f5b2013-05-02 00:15:01 +00005360
5361 /* Loop over the tables in the join, from left to right */
drhb8a8e8a2013-06-10 19:12:39 +00005362 pNew = pBuilder->pNew;
drha2014152013-06-07 00:29:23 +00005363 whereLoopInit(pNew);
drha18f3d22013-05-08 03:05:41 +00005364 for(iTab=0, pItem=pTabList->a; iTab<nTabList; iTab++, pItem++){
drhb2a90f02013-05-10 03:30:49 +00005365 pNew->iTab = iTab;
drh70d18342013-06-06 19:16:33 +00005366 pNew->maskSelf = getMask(&pWInfo->sMaskSet, pItem->iCursor);
drhc63367e2013-06-10 20:46:50 +00005367 if( ((pItem->jointype|priorJoinType) & (JT_LEFT|JT_CROSS))!=0 ){
drhf1b5f5b2013-05-02 00:15:01 +00005368 mExtra = mPrior;
5369 }
drhc63367e2013-06-10 20:46:50 +00005370 priorJoinType = pItem->jointype;
drhb2a90f02013-05-10 03:30:49 +00005371 if( IsVirtual(pItem->pTab) ){
danff4b23b2013-11-12 12:17:16 +00005372 rc = whereLoopAddVirtual(pBuilder, mExtra);
drhb2a90f02013-05-10 03:30:49 +00005373 }else{
5374 rc = whereLoopAddBtree(pBuilder, mExtra);
5375 }
drhb2a90f02013-05-10 03:30:49 +00005376 if( rc==SQLITE_OK ){
5377 rc = whereLoopAddOr(pBuilder, mExtra);
5378 }
drhb2a90f02013-05-10 03:30:49 +00005379 mPrior |= pNew->maskSelf;
drh5346e952013-05-08 14:14:26 +00005380 if( rc || db->mallocFailed ) break;
drhf1b5f5b2013-05-02 00:15:01 +00005381 }
drha2014152013-06-07 00:29:23 +00005382 whereLoopClear(db, pNew);
drh5346e952013-05-08 14:14:26 +00005383 return rc;
drhf1b5f5b2013-05-02 00:15:01 +00005384}
5385
drha18f3d22013-05-08 03:05:41 +00005386/*
drh7699d1c2013-06-04 12:42:29 +00005387** Examine a WherePath (with the addition of the extra WhereLoop of the 5th
drh319f6772013-05-14 15:31:07 +00005388** parameters) to see if it outputs rows in the requested ORDER BY
drh0401ace2014-03-18 15:30:27 +00005389** (or GROUP BY) without requiring a separate sort operation. Return N:
drh319f6772013-05-14 15:31:07 +00005390**
drh0401ace2014-03-18 15:30:27 +00005391** N>0: N terms of the ORDER BY clause are satisfied
5392** N==0: No terms of the ORDER BY clause are satisfied
5393** N<0: Unknown yet how many terms of ORDER BY might be satisfied.
drh319f6772013-05-14 15:31:07 +00005394**
drh94433422013-07-01 11:05:50 +00005395** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
5396** strict. With GROUP BY and DISTINCT the only requirement is that
5397** equivalent rows appear immediately adjacent to one another. GROUP BY
dan374cd782014-04-21 13:21:56 +00005398** and DISTINCT do not require rows to appear in any particular order as long
peter.d.reid60ec9142014-09-06 16:39:46 +00005399** as equivalent rows are grouped together. Thus for GROUP BY and DISTINCT
drh94433422013-07-01 11:05:50 +00005400** the pOrderBy terms can be matched in any order. With ORDER BY, the
5401** pOrderBy terms must be matched in strict left-to-right order.
drh6b7157b2013-05-10 02:00:35 +00005402*/
drh0401ace2014-03-18 15:30:27 +00005403static i8 wherePathSatisfiesOrderBy(
drh6b7157b2013-05-10 02:00:35 +00005404 WhereInfo *pWInfo, /* The WHERE clause */
drh4f402f22013-06-11 18:59:38 +00005405 ExprList *pOrderBy, /* ORDER BY or GROUP BY or DISTINCT clause to check */
drh6b7157b2013-05-10 02:00:35 +00005406 WherePath *pPath, /* The WherePath to check */
drh4f402f22013-06-11 18:59:38 +00005407 u16 wctrlFlags, /* Might contain WHERE_GROUPBY or WHERE_DISTINCTBY */
5408 u16 nLoop, /* Number of entries in pPath->aLoop[] */
drh319f6772013-05-14 15:31:07 +00005409 WhereLoop *pLast, /* Add this WhereLoop to the end of pPath->aLoop[] */
drh4f402f22013-06-11 18:59:38 +00005410 Bitmask *pRevMask /* OUT: Mask of WhereLoops to run in reverse order */
drh6b7157b2013-05-10 02:00:35 +00005411){
drh88da6442013-05-27 17:59:37 +00005412 u8 revSet; /* True if rev is known */
5413 u8 rev; /* Composite sort order */
5414 u8 revIdx; /* Index sort order */
drhe353ee32013-06-04 23:40:53 +00005415 u8 isOrderDistinct; /* All prior WhereLoops are order-distinct */
5416 u8 distinctColumns; /* True if the loop has UNIQUE NOT NULL columns */
5417 u8 isMatch; /* iColumn matches a term of the ORDER BY clause */
drh416846a2013-11-06 12:56:04 +00005418 u16 nKeyCol; /* Number of key columns in pIndex */
5419 u16 nColumn; /* Total number of ordered columns in the index */
drh7699d1c2013-06-04 12:42:29 +00005420 u16 nOrderBy; /* Number terms in the ORDER BY clause */
5421 int iLoop; /* Index of WhereLoop in pPath being processed */
5422 int i, j; /* Loop counters */
5423 int iCur; /* Cursor number for current WhereLoop */
5424 int iColumn; /* A column number within table iCur */
drhe8ae5832013-06-19 13:32:46 +00005425 WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
drh7699d1c2013-06-04 12:42:29 +00005426 WhereTerm *pTerm; /* A single term of the WHERE clause */
5427 Expr *pOBExpr; /* An expression from the ORDER BY clause */
5428 CollSeq *pColl; /* COLLATE function from an ORDER BY clause term */
5429 Index *pIndex; /* The index associated with pLoop */
5430 sqlite3 *db = pWInfo->pParse->db; /* Database connection */
5431 Bitmask obSat = 0; /* Mask of ORDER BY terms satisfied so far */
5432 Bitmask obDone; /* Mask of all ORDER BY terms */
drhe353ee32013-06-04 23:40:53 +00005433 Bitmask orderDistinctMask; /* Mask of all well-ordered loops */
drhb8916be2013-06-14 02:51:48 +00005434 Bitmask ready; /* Mask of inner loops */
drh319f6772013-05-14 15:31:07 +00005435
5436 /*
drh7699d1c2013-06-04 12:42:29 +00005437 ** We say the WhereLoop is "one-row" if it generates no more than one
5438 ** row of output. A WhereLoop is one-row if all of the following are true:
drh319f6772013-05-14 15:31:07 +00005439 ** (a) All index columns match with WHERE_COLUMN_EQ.
5440 ** (b) The index is unique
drh7699d1c2013-06-04 12:42:29 +00005441 ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
5442 ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
drh319f6772013-05-14 15:31:07 +00005443 **
drhe353ee32013-06-04 23:40:53 +00005444 ** We say the WhereLoop is "order-distinct" if the set of columns from
5445 ** that WhereLoop that are in the ORDER BY clause are different for every
5446 ** row of the WhereLoop. Every one-row WhereLoop is automatically
5447 ** order-distinct. A WhereLoop that has no columns in the ORDER BY clause
5448 ** is not order-distinct. To be order-distinct is not quite the same as being
5449 ** UNIQUE since a UNIQUE column or index can have multiple rows that
5450 ** are NULL and NULL values are equivalent for the purpose of order-distinct.
5451 ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
5452 **
5453 ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
5454 ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
5455 ** automatically order-distinct.
drh319f6772013-05-14 15:31:07 +00005456 */
5457
5458 assert( pOrderBy!=0 );
drh7699d1c2013-06-04 12:42:29 +00005459 if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
drh319f6772013-05-14 15:31:07 +00005460
drh319f6772013-05-14 15:31:07 +00005461 nOrderBy = pOrderBy->nExpr;
drh7963b0e2013-06-17 21:37:40 +00005462 testcase( nOrderBy==BMS-1 );
drhe353ee32013-06-04 23:40:53 +00005463 if( nOrderBy>BMS-1 ) return 0; /* Cannot optimize overly large ORDER BYs */
5464 isOrderDistinct = 1;
drh7699d1c2013-06-04 12:42:29 +00005465 obDone = MASKBIT(nOrderBy)-1;
drhe353ee32013-06-04 23:40:53 +00005466 orderDistinctMask = 0;
drhb8916be2013-06-14 02:51:48 +00005467 ready = 0;
drhe353ee32013-06-04 23:40:53 +00005468 for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
drhb8916be2013-06-14 02:51:48 +00005469 if( iLoop>0 ) ready |= pLoop->maskSelf;
drh7699d1c2013-06-04 12:42:29 +00005470 pLoop = iLoop<nLoop ? pPath->aLoop[iLoop] : pLast;
drh9dfaf622014-04-25 14:42:17 +00005471 if( pLoop->wsFlags & WHERE_VIRTUALTABLE ){
5472 if( pLoop->u.vtab.isOrdered ) obSat = obDone;
5473 break;
5474 }
drh319f6772013-05-14 15:31:07 +00005475 iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
drhb8916be2013-06-14 02:51:48 +00005476
5477 /* Mark off any ORDER BY term X that is a column in the table of
5478 ** the current loop for which there is term in the WHERE
5479 ** clause of the form X IS NULL or X=? that reference only outer
5480 ** loops.
5481 */
5482 for(i=0; i<nOrderBy; i++){
5483 if( MASKBIT(i) & obSat ) continue;
5484 pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
5485 if( pOBExpr->op!=TK_COLUMN ) continue;
5486 if( pOBExpr->iTable!=iCur ) continue;
5487 pTerm = findTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
5488 ~ready, WO_EQ|WO_ISNULL, 0);
5489 if( pTerm==0 ) continue;
drh7963b0e2013-06-17 21:37:40 +00005490 if( (pTerm->eOperator&WO_EQ)!=0 && pOBExpr->iColumn>=0 ){
drhb8916be2013-06-14 02:51:48 +00005491 const char *z1, *z2;
5492 pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
5493 if( !pColl ) pColl = db->pDfltColl;
5494 z1 = pColl->zName;
5495 pColl = sqlite3ExprCollSeq(pWInfo->pParse, pTerm->pExpr);
5496 if( !pColl ) pColl = db->pDfltColl;
5497 z2 = pColl->zName;
5498 if( sqlite3StrICmp(z1, z2)!=0 ) continue;
5499 }
5500 obSat |= MASKBIT(i);
5501 }
5502
drh7699d1c2013-06-04 12:42:29 +00005503 if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
5504 if( pLoop->wsFlags & WHERE_IPK ){
5505 pIndex = 0;
drhbbbdc832013-10-22 18:01:40 +00005506 nKeyCol = 0;
drh416846a2013-11-06 12:56:04 +00005507 nColumn = 1;
drh7699d1c2013-06-04 12:42:29 +00005508 }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
drh1b0f0262013-05-30 22:27:09 +00005509 return 0;
drh7699d1c2013-06-04 12:42:29 +00005510 }else{
drhbbbdc832013-10-22 18:01:40 +00005511 nKeyCol = pIndex->nKeyCol;
drh416846a2013-11-06 12:56:04 +00005512 nColumn = pIndex->nColumn;
5513 assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) );
5514 assert( pIndex->aiColumn[nColumn-1]==(-1) || !HasRowid(pIndex->pTable));
drh5f1d1d92014-07-31 22:59:04 +00005515 isOrderDistinct = IsUniqueIndex(pIndex);
drh1b0f0262013-05-30 22:27:09 +00005516 }
drh7699d1c2013-06-04 12:42:29 +00005517
drh7699d1c2013-06-04 12:42:29 +00005518 /* Loop through all columns of the index and deal with the ones
5519 ** that are not constrained by == or IN.
5520 */
5521 rev = revSet = 0;
drhe353ee32013-06-04 23:40:53 +00005522 distinctColumns = 0;
drh416846a2013-11-06 12:56:04 +00005523 for(j=0; j<nColumn; j++){
drh7699d1c2013-06-04 12:42:29 +00005524 u8 bOnce; /* True to run the ORDER BY search loop */
5525
drhe353ee32013-06-04 23:40:53 +00005526 /* Skip over == and IS NULL terms */
drh7699d1c2013-06-04 12:42:29 +00005527 if( j<pLoop->u.btree.nEq
drhc8bbce12014-10-21 01:05:09 +00005528 && pLoop->nSkip==0
drh4efc9292013-06-06 23:02:03 +00005529 && ((i = pLoop->aLTerm[j]->eOperator) & (WO_EQ|WO_ISNULL))!=0
drh7699d1c2013-06-04 12:42:29 +00005530 ){
drh7963b0e2013-06-17 21:37:40 +00005531 if( i & WO_ISNULL ){
5532 testcase( isOrderDistinct );
5533 isOrderDistinct = 0;
5534 }
drhe353ee32013-06-04 23:40:53 +00005535 continue;
drh7699d1c2013-06-04 12:42:29 +00005536 }
5537
drhe353ee32013-06-04 23:40:53 +00005538 /* Get the column number in the table (iColumn) and sort order
5539 ** (revIdx) for the j-th column of the index.
drh7699d1c2013-06-04 12:42:29 +00005540 */
drh416846a2013-11-06 12:56:04 +00005541 if( pIndex ){
drh7699d1c2013-06-04 12:42:29 +00005542 iColumn = pIndex->aiColumn[j];
5543 revIdx = pIndex->aSortOrder[j];
5544 if( iColumn==pIndex->pTable->iPKey ) iColumn = -1;
drhdc3cd4b2013-05-30 23:21:20 +00005545 }else{
drh7699d1c2013-06-04 12:42:29 +00005546 iColumn = -1;
5547 revIdx = 0;
drhdc3cd4b2013-05-30 23:21:20 +00005548 }
drh7699d1c2013-06-04 12:42:29 +00005549
5550 /* An unconstrained column that might be NULL means that this
drh416846a2013-11-06 12:56:04 +00005551 ** WhereLoop is not well-ordered
drh7699d1c2013-06-04 12:42:29 +00005552 */
drhe353ee32013-06-04 23:40:53 +00005553 if( isOrderDistinct
5554 && iColumn>=0
drh7699d1c2013-06-04 12:42:29 +00005555 && j>=pLoop->u.btree.nEq
5556 && pIndex->pTable->aCol[iColumn].notNull==0
5557 ){
drhe353ee32013-06-04 23:40:53 +00005558 isOrderDistinct = 0;
drh7699d1c2013-06-04 12:42:29 +00005559 }
5560
5561 /* Find the ORDER BY term that corresponds to the j-th column
dan374cd782014-04-21 13:21:56 +00005562 ** of the index and mark that ORDER BY term off
drh7699d1c2013-06-04 12:42:29 +00005563 */
5564 bOnce = 1;
drhe353ee32013-06-04 23:40:53 +00005565 isMatch = 0;
drh7699d1c2013-06-04 12:42:29 +00005566 for(i=0; bOnce && i<nOrderBy; i++){
5567 if( MASKBIT(i) & obSat ) continue;
5568 pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
drh93ec45d2013-06-17 18:20:48 +00005569 testcase( wctrlFlags & WHERE_GROUPBY );
5570 testcase( wctrlFlags & WHERE_DISTINCTBY );
drh4f402f22013-06-11 18:59:38 +00005571 if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
drhe353ee32013-06-04 23:40:53 +00005572 if( pOBExpr->op!=TK_COLUMN ) continue;
drh7699d1c2013-06-04 12:42:29 +00005573 if( pOBExpr->iTable!=iCur ) continue;
5574 if( pOBExpr->iColumn!=iColumn ) continue;
5575 if( iColumn>=0 ){
5576 pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
5577 if( !pColl ) pColl = db->pDfltColl;
5578 if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
5579 }
drhe353ee32013-06-04 23:40:53 +00005580 isMatch = 1;
drh7699d1c2013-06-04 12:42:29 +00005581 break;
5582 }
drh49290472014-10-11 02:12:58 +00005583 if( isMatch && (wctrlFlags & WHERE_GROUPBY)==0 ){
drh59b8f2e2014-03-22 00:27:14 +00005584 /* Make sure the sort order is compatible in an ORDER BY clause.
5585 ** Sort order is irrelevant for a GROUP BY clause. */
5586 if( revSet ){
5587 if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) isMatch = 0;
5588 }else{
5589 rev = revIdx ^ pOrderBy->a[i].sortOrder;
5590 if( rev ) *pRevMask |= MASKBIT(iLoop);
5591 revSet = 1;
5592 }
5593 }
drhe353ee32013-06-04 23:40:53 +00005594 if( isMatch ){
drh7963b0e2013-06-17 21:37:40 +00005595 if( iColumn<0 ){
5596 testcase( distinctColumns==0 );
5597 distinctColumns = 1;
5598 }
drh7699d1c2013-06-04 12:42:29 +00005599 obSat |= MASKBIT(i);
drh7699d1c2013-06-04 12:42:29 +00005600 }else{
5601 /* No match found */
drhbbbdc832013-10-22 18:01:40 +00005602 if( j==0 || j<nKeyCol ){
drh7963b0e2013-06-17 21:37:40 +00005603 testcase( isOrderDistinct!=0 );
5604 isOrderDistinct = 0;
5605 }
drh7699d1c2013-06-04 12:42:29 +00005606 break;
5607 }
5608 } /* end Loop over all index columns */
drh81186b42013-06-18 01:52:41 +00005609 if( distinctColumns ){
5610 testcase( isOrderDistinct==0 );
5611 isOrderDistinct = 1;
5612 }
drh7699d1c2013-06-04 12:42:29 +00005613 } /* end-if not one-row */
5614
5615 /* Mark off any other ORDER BY terms that reference pLoop */
drhe353ee32013-06-04 23:40:53 +00005616 if( isOrderDistinct ){
5617 orderDistinctMask |= pLoop->maskSelf;
drh7699d1c2013-06-04 12:42:29 +00005618 for(i=0; i<nOrderBy; i++){
5619 Expr *p;
drh434a9312014-02-26 02:26:09 +00005620 Bitmask mTerm;
drh7699d1c2013-06-04 12:42:29 +00005621 if( MASKBIT(i) & obSat ) continue;
5622 p = pOrderBy->a[i].pExpr;
drh434a9312014-02-26 02:26:09 +00005623 mTerm = exprTableUsage(&pWInfo->sMaskSet,p);
5624 if( mTerm==0 && !sqlite3ExprIsConstant(p) ) continue;
5625 if( (mTerm&~orderDistinctMask)==0 ){
drh7699d1c2013-06-04 12:42:29 +00005626 obSat |= MASKBIT(i);
5627 }
drh0afb4232013-05-31 13:36:32 +00005628 }
drh319f6772013-05-14 15:31:07 +00005629 }
drhb8916be2013-06-14 02:51:48 +00005630 } /* End the loop over all WhereLoops from outer-most down to inner-most */
drh36ed0342014-03-28 12:56:57 +00005631 if( obSat==obDone ) return (i8)nOrderBy;
drhd2de8612014-03-18 18:59:07 +00005632 if( !isOrderDistinct ){
5633 for(i=nOrderBy-1; i>0; i--){
5634 Bitmask m = MASKBIT(i) - 1;
5635 if( (obSat&m)==m ) return i;
5636 }
5637 return 0;
5638 }
drh319f6772013-05-14 15:31:07 +00005639 return -1;
drh6b7157b2013-05-10 02:00:35 +00005640}
5641
dan374cd782014-04-21 13:21:56 +00005642
5643/*
5644** If the WHERE_GROUPBY flag is set in the mask passed to sqlite3WhereBegin(),
5645** the planner assumes that the specified pOrderBy list is actually a GROUP
5646** BY clause - and so any order that groups rows as required satisfies the
5647** request.
5648**
5649** Normally, in this case it is not possible for the caller to determine
5650** whether or not the rows are really being delivered in sorted order, or
5651** just in some other order that provides the required grouping. However,
5652** if the WHERE_SORTBYGROUP flag is also passed to sqlite3WhereBegin(), then
5653** this function may be called on the returned WhereInfo object. It returns
5654** true if the rows really will be sorted in the specified order, or false
5655** otherwise.
5656**
5657** For example, assuming:
5658**
5659** CREATE INDEX i1 ON t1(x, Y);
5660**
5661** then
5662**
5663** SELECT * FROM t1 GROUP BY x,y ORDER BY x,y; -- IsSorted()==1
5664** SELECT * FROM t1 GROUP BY y,x ORDER BY y,x; -- IsSorted()==0
5665*/
5666int sqlite3WhereIsSorted(WhereInfo *pWInfo){
5667 assert( pWInfo->wctrlFlags & WHERE_GROUPBY );
5668 assert( pWInfo->wctrlFlags & WHERE_SORTBYGROUP );
5669 return pWInfo->sorted;
5670}
5671
drhd15cb172013-05-21 19:23:10 +00005672#ifdef WHERETRACE_ENABLED
5673/* For debugging use only: */
5674static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
5675 static char zName[65];
5676 int i;
5677 for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
5678 if( pLast ) zName[i++] = pLast->cId;
5679 zName[i] = 0;
5680 return zName;
5681}
5682#endif
5683
drh6b7157b2013-05-10 02:00:35 +00005684/*
dan50ae31e2014-08-08 16:52:28 +00005685** Return the cost of sorting nRow rows, assuming that the keys have
5686** nOrderby columns and that the first nSorted columns are already in
5687** order.
5688*/
5689static LogEst whereSortingCost(
5690 WhereInfo *pWInfo,
5691 LogEst nRow,
5692 int nOrderBy,
5693 int nSorted
5694){
5695 /* TUNING: Estimated cost of a full external sort, where N is
5696 ** the number of rows to sort is:
5697 **
5698 ** cost = (3.0 * N * log(N)).
5699 **
5700 ** Or, if the order-by clause has X terms but only the last Y
5701 ** terms are out of order, then block-sorting will reduce the
5702 ** sorting cost to:
5703 **
5704 ** cost = (3.0 * N * log(N)) * (Y/X)
5705 **
5706 ** The (Y/X) term is implemented using stack variable rScale
5707 ** below. */
5708 LogEst rScale, rSortCost;
5709 assert( nOrderBy>0 && 66==sqlite3LogEst(100) );
5710 rScale = sqlite3LogEst((nOrderBy-nSorted)*100/nOrderBy) - 66;
5711 rSortCost = nRow + estLog(nRow) + rScale + 16;
5712
5713 /* TUNING: The cost of implementing DISTINCT using a B-TREE is
5714 ** similar but with a larger constant of proportionality.
5715 ** Multiply by an additional factor of 3.0. */
5716 if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
5717 rSortCost += 16;
5718 }
5719
5720 return rSortCost;
5721}
5722
5723/*
dan51576f42013-07-02 10:06:15 +00005724** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
drha18f3d22013-05-08 03:05:41 +00005725** attempts to find the lowest cost path that visits each WhereLoop
5726** once. This path is then loaded into the pWInfo->a[].pWLoop fields.
5727**
drhc7f0d222013-06-19 03:27:12 +00005728** Assume that the total number of output rows that will need to be sorted
5729** will be nRowEst (in the 10*log2 representation). Or, ignore sorting
5730** costs if nRowEst==0.
5731**
drha18f3d22013-05-08 03:05:41 +00005732** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
5733** error occurs.
5734*/
drhbf539c42013-10-05 18:16:02 +00005735static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
drh783dece2013-06-05 17:53:43 +00005736 int mxChoice; /* Maximum number of simultaneous paths tracked */
drha18f3d22013-05-08 03:05:41 +00005737 int nLoop; /* Number of terms in the join */
drhe1e2e9a2013-06-13 15:16:53 +00005738 Parse *pParse; /* Parsing context */
drha18f3d22013-05-08 03:05:41 +00005739 sqlite3 *db; /* The database connection */
5740 int iLoop; /* Loop counter over the terms of the join */
5741 int ii, jj; /* Loop counters */
drhfde1e6b2013-09-06 17:45:42 +00005742 int mxI = 0; /* Index of next entry to replace */
drhd2de8612014-03-18 18:59:07 +00005743 int nOrderBy; /* Number of ORDER BY clause terms */
drhbf539c42013-10-05 18:16:02 +00005744 LogEst mxCost = 0; /* Maximum cost of a set of paths */
dan50ae31e2014-08-08 16:52:28 +00005745 LogEst mxUnsorted = 0; /* Maximum unsorted cost of a set of path */
drha18f3d22013-05-08 03:05:41 +00005746 int nTo, nFrom; /* Number of valid entries in aTo[] and aFrom[] */
5747 WherePath *aFrom; /* All nFrom paths at the previous level */
5748 WherePath *aTo; /* The nTo best paths at the current level */
5749 WherePath *pFrom; /* An element of aFrom[] that we are working on */
5750 WherePath *pTo; /* An element of aTo[] that we are working on */
5751 WhereLoop *pWLoop; /* One of the WhereLoop objects */
5752 WhereLoop **pX; /* Used to divy up the pSpace memory */
dan50ae31e2014-08-08 16:52:28 +00005753 LogEst *aSortCost = 0; /* Sorting and partial sorting costs */
drha18f3d22013-05-08 03:05:41 +00005754 char *pSpace; /* Temporary memory used by this routine */
dane2c27852014-08-08 17:25:33 +00005755 int nSpace; /* Bytes of space allocated at pSpace */
drha18f3d22013-05-08 03:05:41 +00005756
drhe1e2e9a2013-06-13 15:16:53 +00005757 pParse = pWInfo->pParse;
5758 db = pParse->db;
drha18f3d22013-05-08 03:05:41 +00005759 nLoop = pWInfo->nLevel;
drhe1e2e9a2013-06-13 15:16:53 +00005760 /* TUNING: For simple queries, only the best path is tracked.
5761 ** For 2-way joins, the 5 best paths are followed.
5762 ** For joins of 3 or more tables, track the 10 best paths */
drh2504c6c2014-06-02 11:26:33 +00005763 mxChoice = (nLoop<=1) ? 1 : (nLoop==2 ? 5 : 10);
drha18f3d22013-05-08 03:05:41 +00005764 assert( nLoop<=pWInfo->pTabList->nSrc );
drhddef5dc2014-08-07 16:50:00 +00005765 WHERETRACE(0x002, ("---- begin solver. (nRowEst=%d)\n", nRowEst));
drha18f3d22013-05-08 03:05:41 +00005766
dan50ae31e2014-08-08 16:52:28 +00005767 /* If nRowEst is zero and there is an ORDER BY clause, ignore it. In this
5768 ** case the purpose of this call is to estimate the number of rows returned
5769 ** by the overall query. Once this estimate has been obtained, the caller
5770 ** will invoke this function a second time, passing the estimate as the
5771 ** nRowEst parameter. */
5772 if( pWInfo->pOrderBy==0 || nRowEst==0 ){
5773 nOrderBy = 0;
5774 }else{
5775 nOrderBy = pWInfo->pOrderBy->nExpr;
5776 }
5777
5778 /* Allocate and initialize space for aTo, aFrom and aSortCost[] */
dane2c27852014-08-08 17:25:33 +00005779 nSpace = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
5780 nSpace += sizeof(LogEst) * nOrderBy;
5781 pSpace = sqlite3DbMallocRaw(db, nSpace);
drha18f3d22013-05-08 03:05:41 +00005782 if( pSpace==0 ) return SQLITE_NOMEM;
5783 aTo = (WherePath*)pSpace;
5784 aFrom = aTo+mxChoice;
5785 memset(aFrom, 0, sizeof(aFrom[0]));
5786 pX = (WhereLoop**)(aFrom+mxChoice);
drhe9d935a2013-06-05 16:19:59 +00005787 for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
drha18f3d22013-05-08 03:05:41 +00005788 pFrom->aLoop = pX;
5789 }
dan50ae31e2014-08-08 16:52:28 +00005790 if( nOrderBy ){
5791 /* If there is an ORDER BY clause and it is not being ignored, set up
5792 ** space for the aSortCost[] array. Each element of the aSortCost array
5793 ** is either zero - meaning it has not yet been initialized - or the
5794 ** cost of sorting nRowEst rows of data where the first X terms of
5795 ** the ORDER BY clause are already in order, where X is the array
5796 ** index. */
5797 aSortCost = (LogEst*)pX;
dane2c27852014-08-08 17:25:33 +00005798 memset(aSortCost, 0, sizeof(LogEst) * nOrderBy);
dan50ae31e2014-08-08 16:52:28 +00005799 }
dane2c27852014-08-08 17:25:33 +00005800 assert( aSortCost==0 || &pSpace[nSpace]==(char*)&aSortCost[nOrderBy] );
5801 assert( aSortCost!=0 || &pSpace[nSpace]==(char*)pX );
drha18f3d22013-05-08 03:05:41 +00005802
drhe1e2e9a2013-06-13 15:16:53 +00005803 /* Seed the search with a single WherePath containing zero WhereLoops.
5804 **
5805 ** TUNING: Do not let the number of iterations go above 25. If the cost
5806 ** of computing an automatic index is not paid back within the first 25
5807 ** rows, then do not use the automatic index. */
drhbf539c42013-10-05 18:16:02 +00005808 aFrom[0].nRow = MIN(pParse->nQueryLoop, 46); assert( 46==sqlite3LogEst(25) );
drha18f3d22013-05-08 03:05:41 +00005809 nFrom = 1;
dan50ae31e2014-08-08 16:52:28 +00005810 assert( aFrom[0].isOrdered==0 );
5811 if( nOrderBy ){
5812 /* If nLoop is zero, then there are no FROM terms in the query. Since
5813 ** in this case the query may return a maximum of one row, the results
5814 ** are already in the requested order. Set isOrdered to nOrderBy to
5815 ** indicate this. Or, if nLoop is greater than zero, set isOrdered to
5816 ** -1, indicating that the result set may or may not be ordered,
5817 ** depending on the loops added to the current plan. */
5818 aFrom[0].isOrdered = nLoop>0 ? -1 : nOrderBy;
drh6b7157b2013-05-10 02:00:35 +00005819 }
5820
5821 /* Compute successively longer WherePaths using the previous generation
5822 ** of WherePaths as the basis for the next. Keep track of the mxChoice
5823 ** best paths at each generation */
drha18f3d22013-05-08 03:05:41 +00005824 for(iLoop=0; iLoop<nLoop; iLoop++){
5825 nTo = 0;
5826 for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
5827 for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
dan50ae31e2014-08-08 16:52:28 +00005828 LogEst nOut; /* Rows visited by (pFrom+pWLoop) */
5829 LogEst rCost; /* Cost of path (pFrom+pWLoop) */
5830 LogEst rUnsorted; /* Unsorted cost of (pFrom+pWLoop) */
5831 i8 isOrdered = pFrom->isOrdered; /* isOrdered for (pFrom+pWLoop) */
5832 Bitmask maskNew; /* Mask of src visited by (..) */
5833 Bitmask revMask = 0; /* Mask of rev-order loops for (..) */
5834
drha18f3d22013-05-08 03:05:41 +00005835 if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
5836 if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
drh6b7157b2013-05-10 02:00:35 +00005837 /* At this point, pWLoop is a candidate to be the next loop.
5838 ** Compute its cost */
dan50ae31e2014-08-08 16:52:28 +00005839 rUnsorted = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
5840 rUnsorted = sqlite3LogEstAdd(rUnsorted, pFrom->rUnsorted);
drhfde1e6b2013-09-06 17:45:42 +00005841 nOut = pFrom->nRow + pWLoop->nOut;
drha18f3d22013-05-08 03:05:41 +00005842 maskNew = pFrom->maskLoop | pWLoop->maskSelf;
drh0401ace2014-03-18 15:30:27 +00005843 if( isOrdered<0 ){
5844 isOrdered = wherePathSatisfiesOrderBy(pWInfo,
drh4f402f22013-06-11 18:59:38 +00005845 pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
drh0401ace2014-03-18 15:30:27 +00005846 iLoop, pWLoop, &revMask);
drh3a5ba8b2013-06-03 15:34:48 +00005847 }else{
5848 revMask = pFrom->revLoop;
drh6b7157b2013-05-10 02:00:35 +00005849 }
dan50ae31e2014-08-08 16:52:28 +00005850 if( isOrdered>=0 && isOrdered<nOrderBy ){
5851 if( aSortCost[isOrdered]==0 ){
5852 aSortCost[isOrdered] = whereSortingCost(
5853 pWInfo, nRowEst, nOrderBy, isOrdered
5854 );
5855 }
5856 rCost = sqlite3LogEstAdd(rUnsorted, aSortCost[isOrdered]);
5857
5858 WHERETRACE(0x002,
5859 ("---- sort cost=%-3d (%d/%d) increases cost %3d to %-3d\n",
5860 aSortCost[isOrdered], (nOrderBy-isOrdered), nOrderBy,
5861 rUnsorted, rCost));
5862 }else{
5863 rCost = rUnsorted;
5864 }
5865
drhddef5dc2014-08-07 16:50:00 +00005866 /* Check to see if pWLoop should be added to the set of
5867 ** mxChoice best-so-far paths.
5868 **
5869 ** First look for an existing path among best-so-far paths
5870 ** that covers the same set of loops and has the same isOrdered
5871 ** setting as the current path candidate.
drhf2a90302014-08-07 20:37:01 +00005872 **
5873 ** The term "((pTo->isOrdered^isOrdered)&0x80)==0" is equivalent
5874 ** to (pTo->isOrdered==(-1))==(isOrdered==(-1))" for the range
5875 ** of legal values for isOrdered, -1..64.
drhddef5dc2014-08-07 16:50:00 +00005876 */
drh6b7157b2013-05-10 02:00:35 +00005877 for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
drhfde1e6b2013-09-06 17:45:42 +00005878 if( pTo->maskLoop==maskNew
drhf2a90302014-08-07 20:37:01 +00005879 && ((pTo->isOrdered^isOrdered)&0x80)==0
drhfde1e6b2013-09-06 17:45:42 +00005880 ){
drh7963b0e2013-06-17 21:37:40 +00005881 testcase( jj==nTo-1 );
drh6b7157b2013-05-10 02:00:35 +00005882 break;
5883 }
5884 }
drha18f3d22013-05-08 03:05:41 +00005885 if( jj>=nTo ){
drhddef5dc2014-08-07 16:50:00 +00005886 /* None of the existing best-so-far paths match the candidate. */
drhddef5dc2014-08-07 16:50:00 +00005887 if( nTo>=mxChoice
dan50ae31e2014-08-08 16:52:28 +00005888 && (rCost>mxCost || (rCost==mxCost && rUnsorted>=mxUnsorted))
drhddef5dc2014-08-07 16:50:00 +00005889 ){
5890 /* The current candidate is no better than any of the mxChoice
5891 ** paths currently in the best-so-far buffer. So discard
5892 ** this candidate as not viable. */
drh989578e2013-10-28 14:34:35 +00005893#ifdef WHERETRACE_ENABLED /* 0x4 */
drhae70cf12013-05-31 15:18:46 +00005894 if( sqlite3WhereTrace&0x4 ){
drhfde1e6b2013-09-06 17:45:42 +00005895 sqlite3DebugPrintf("Skip %s cost=%-3d,%3d order=%c\n",
5896 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
drh0401ace2014-03-18 15:30:27 +00005897 isOrdered>=0 ? isOrdered+'0' : '?');
drhd15cb172013-05-21 19:23:10 +00005898 }
5899#endif
5900 continue;
5901 }
drhddef5dc2014-08-07 16:50:00 +00005902 /* If we reach this points it means that the new candidate path
5903 ** needs to be added to the set of best-so-far paths. */
drha18f3d22013-05-08 03:05:41 +00005904 if( nTo<mxChoice ){
drhd15cb172013-05-21 19:23:10 +00005905 /* Increase the size of the aTo set by one */
drha18f3d22013-05-08 03:05:41 +00005906 jj = nTo++;
5907 }else{
drhd15cb172013-05-21 19:23:10 +00005908 /* New path replaces the prior worst to keep count below mxChoice */
drhfde1e6b2013-09-06 17:45:42 +00005909 jj = mxI;
drha18f3d22013-05-08 03:05:41 +00005910 }
5911 pTo = &aTo[jj];
drh989578e2013-10-28 14:34:35 +00005912#ifdef WHERETRACE_ENABLED /* 0x4 */
drhae70cf12013-05-31 15:18:46 +00005913 if( sqlite3WhereTrace&0x4 ){
drhfde1e6b2013-09-06 17:45:42 +00005914 sqlite3DebugPrintf("New %s cost=%-3d,%3d order=%c\n",
5915 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
drh0401ace2014-03-18 15:30:27 +00005916 isOrdered>=0 ? isOrdered+'0' : '?');
drhd15cb172013-05-21 19:23:10 +00005917 }
5918#endif
drhf204dac2013-05-08 03:22:07 +00005919 }else{
drhddef5dc2014-08-07 16:50:00 +00005920 /* Control reaches here if best-so-far path pTo=aTo[jj] covers the
5921 ** same set of loops and has the sam isOrdered setting as the
5922 ** candidate path. Check to see if the candidate should replace
5923 ** pTo or if the candidate should be skipped */
5924 if( pTo->rCost<rCost || (pTo->rCost==rCost && pTo->nRow<=nOut) ){
drh989578e2013-10-28 14:34:35 +00005925#ifdef WHERETRACE_ENABLED /* 0x4 */
drhae70cf12013-05-31 15:18:46 +00005926 if( sqlite3WhereTrace&0x4 ){
drhd15cb172013-05-21 19:23:10 +00005927 sqlite3DebugPrintf(
drhfde1e6b2013-09-06 17:45:42 +00005928 "Skip %s cost=%-3d,%3d order=%c",
5929 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
drh0401ace2014-03-18 15:30:27 +00005930 isOrdered>=0 ? isOrdered+'0' : '?');
drhfde1e6b2013-09-06 17:45:42 +00005931 sqlite3DebugPrintf(" vs %s cost=%-3d,%d order=%c\n",
5932 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
drh0401ace2014-03-18 15:30:27 +00005933 pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
drhd15cb172013-05-21 19:23:10 +00005934 }
5935#endif
drhddef5dc2014-08-07 16:50:00 +00005936 /* Discard the candidate path from further consideration */
drh7963b0e2013-06-17 21:37:40 +00005937 testcase( pTo->rCost==rCost );
drhd15cb172013-05-21 19:23:10 +00005938 continue;
5939 }
drh7963b0e2013-06-17 21:37:40 +00005940 testcase( pTo->rCost==rCost+1 );
drhddef5dc2014-08-07 16:50:00 +00005941 /* Control reaches here if the candidate path is better than the
5942 ** pTo path. Replace pTo with the candidate. */
drh989578e2013-10-28 14:34:35 +00005943#ifdef WHERETRACE_ENABLED /* 0x4 */
drhae70cf12013-05-31 15:18:46 +00005944 if( sqlite3WhereTrace&0x4 ){
drhd15cb172013-05-21 19:23:10 +00005945 sqlite3DebugPrintf(
drhfde1e6b2013-09-06 17:45:42 +00005946 "Update %s cost=%-3d,%3d order=%c",
5947 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
drh0401ace2014-03-18 15:30:27 +00005948 isOrdered>=0 ? isOrdered+'0' : '?');
drhfde1e6b2013-09-06 17:45:42 +00005949 sqlite3DebugPrintf(" was %s cost=%-3d,%3d order=%c\n",
5950 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
drh0401ace2014-03-18 15:30:27 +00005951 pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
drhd15cb172013-05-21 19:23:10 +00005952 }
5953#endif
drha18f3d22013-05-08 03:05:41 +00005954 }
drh6b7157b2013-05-10 02:00:35 +00005955 /* pWLoop is a winner. Add it to the set of best so far */
drha18f3d22013-05-08 03:05:41 +00005956 pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
drh319f6772013-05-14 15:31:07 +00005957 pTo->revLoop = revMask;
drhfde1e6b2013-09-06 17:45:42 +00005958 pTo->nRow = nOut;
drha18f3d22013-05-08 03:05:41 +00005959 pTo->rCost = rCost;
dan50ae31e2014-08-08 16:52:28 +00005960 pTo->rUnsorted = rUnsorted;
drh6b7157b2013-05-10 02:00:35 +00005961 pTo->isOrdered = isOrdered;
drha18f3d22013-05-08 03:05:41 +00005962 memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
5963 pTo->aLoop[iLoop] = pWLoop;
5964 if( nTo>=mxChoice ){
drhfde1e6b2013-09-06 17:45:42 +00005965 mxI = 0;
drha18f3d22013-05-08 03:05:41 +00005966 mxCost = aTo[0].rCost;
dan50ae31e2014-08-08 16:52:28 +00005967 mxUnsorted = aTo[0].nRow;
drha18f3d22013-05-08 03:05:41 +00005968 for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
dan50ae31e2014-08-08 16:52:28 +00005969 if( pTo->rCost>mxCost
5970 || (pTo->rCost==mxCost && pTo->rUnsorted>mxUnsorted)
5971 ){
drhfde1e6b2013-09-06 17:45:42 +00005972 mxCost = pTo->rCost;
dan50ae31e2014-08-08 16:52:28 +00005973 mxUnsorted = pTo->rUnsorted;
drhfde1e6b2013-09-06 17:45:42 +00005974 mxI = jj;
5975 }
drha18f3d22013-05-08 03:05:41 +00005976 }
5977 }
5978 }
5979 }
5980
drh989578e2013-10-28 14:34:35 +00005981#ifdef WHERETRACE_ENABLED /* >=2 */
drh1b131b72014-10-21 16:01:40 +00005982 if( sqlite3WhereTrace & 0x02 ){
drha50ef112013-05-22 02:06:59 +00005983 sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
drhd15cb172013-05-21 19:23:10 +00005984 for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
drhb8a8e8a2013-06-10 19:12:39 +00005985 sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
drha50ef112013-05-22 02:06:59 +00005986 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
drh0401ace2014-03-18 15:30:27 +00005987 pTo->isOrdered>=0 ? (pTo->isOrdered+'0') : '?');
5988 if( pTo->isOrdered>0 ){
drh88da6442013-05-27 17:59:37 +00005989 sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
5990 }else{
5991 sqlite3DebugPrintf("\n");
5992 }
drhf204dac2013-05-08 03:22:07 +00005993 }
5994 }
5995#endif
5996
drh6b7157b2013-05-10 02:00:35 +00005997 /* Swap the roles of aFrom and aTo for the next generation */
drha18f3d22013-05-08 03:05:41 +00005998 pFrom = aTo;
5999 aTo = aFrom;
6000 aFrom = pFrom;
6001 nFrom = nTo;
6002 }
6003
drh75b93402013-05-31 20:43:57 +00006004 if( nFrom==0 ){
drhe1e2e9a2013-06-13 15:16:53 +00006005 sqlite3ErrorMsg(pParse, "no query solution");
drh75b93402013-05-31 20:43:57 +00006006 sqlite3DbFree(db, pSpace);
6007 return SQLITE_ERROR;
6008 }
drha18f3d22013-05-08 03:05:41 +00006009
drh6b7157b2013-05-10 02:00:35 +00006010 /* Find the lowest cost path. pFrom will be left pointing to that path */
drha18f3d22013-05-08 03:05:41 +00006011 pFrom = aFrom;
6012 for(ii=1; ii<nFrom; ii++){
6013 if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
6014 }
6015 assert( pWInfo->nLevel==nLoop );
drh6b7157b2013-05-10 02:00:35 +00006016 /* Load the lowest cost path into pWInfo */
drha18f3d22013-05-08 03:05:41 +00006017 for(iLoop=0; iLoop<nLoop; iLoop++){
drh7ba39a92013-05-30 17:43:19 +00006018 WhereLevel *pLevel = pWInfo->a + iLoop;
6019 pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
drhe217efc2013-06-12 03:48:41 +00006020 pLevel->iFrom = pWLoop->iTab;
drh7ba39a92013-05-30 17:43:19 +00006021 pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
drha18f3d22013-05-08 03:05:41 +00006022 }
drhfd636c72013-06-21 02:05:06 +00006023 if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0
6024 && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
6025 && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
drh4f402f22013-06-11 18:59:38 +00006026 && nRowEst
6027 ){
6028 Bitmask notUsed;
drh6457a352013-06-21 00:35:37 +00006029 int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom,
drh93ec45d2013-06-17 18:20:48 +00006030 WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
drh0401ace2014-03-18 15:30:27 +00006031 if( rc==pWInfo->pResultSet->nExpr ){
6032 pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
6033 }
drh4f402f22013-06-11 18:59:38 +00006034 }
drh079a3072014-03-19 14:10:55 +00006035 if( pWInfo->pOrderBy ){
drh4f402f22013-06-11 18:59:38 +00006036 if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
drh079a3072014-03-19 14:10:55 +00006037 if( pFrom->isOrdered==pWInfo->pOrderBy->nExpr ){
6038 pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
6039 }
drh4f402f22013-06-11 18:59:38 +00006040 }else{
drhddba0c22014-03-18 20:33:42 +00006041 pWInfo->nOBSat = pFrom->isOrdered;
drhea6c36e2014-03-19 14:30:55 +00006042 if( pWInfo->nOBSat<0 ) pWInfo->nOBSat = 0;
drh4f402f22013-06-11 18:59:38 +00006043 pWInfo->revMask = pFrom->revLoop;
6044 }
dan374cd782014-04-21 13:21:56 +00006045 if( (pWInfo->wctrlFlags & WHERE_SORTBYGROUP)
6046 && pWInfo->nOBSat==pWInfo->pOrderBy->nExpr
6047 ){
danb6453202014-10-10 20:52:53 +00006048 Bitmask revMask = 0;
dan374cd782014-04-21 13:21:56 +00006049 int nOrder = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy,
danb6453202014-10-10 20:52:53 +00006050 pFrom, 0, nLoop-1, pFrom->aLoop[nLoop-1], &revMask
dan374cd782014-04-21 13:21:56 +00006051 );
6052 assert( pWInfo->sorted==0 );
danb6453202014-10-10 20:52:53 +00006053 if( nOrder==pWInfo->pOrderBy->nExpr ){
6054 pWInfo->sorted = 1;
6055 pWInfo->revMask = revMask;
6056 }
dan374cd782014-04-21 13:21:56 +00006057 }
drh6b7157b2013-05-10 02:00:35 +00006058 }
dan374cd782014-04-21 13:21:56 +00006059
6060
drha50ef112013-05-22 02:06:59 +00006061 pWInfo->nRowOut = pFrom->nRow;
drha18f3d22013-05-08 03:05:41 +00006062
6063 /* Free temporary memory and return success */
6064 sqlite3DbFree(db, pSpace);
6065 return SQLITE_OK;
6066}
drh75897232000-05-29 14:26:00 +00006067
6068/*
drh60c96cd2013-06-09 17:21:25 +00006069** Most queries use only a single table (they are not joins) and have
6070** simple == constraints against indexed fields. This routine attempts
6071** to plan those simple cases using much less ceremony than the
6072** general-purpose query planner, and thereby yield faster sqlite3_prepare()
6073** times for the common case.
6074**
6075** Return non-zero on success, if this query can be handled by this
6076** no-frills query planner. Return zero if this query needs the
6077** general-purpose query planner.
6078*/
drhb8a8e8a2013-06-10 19:12:39 +00006079static int whereShortCut(WhereLoopBuilder *pBuilder){
drh60c96cd2013-06-09 17:21:25 +00006080 WhereInfo *pWInfo;
6081 struct SrcList_item *pItem;
6082 WhereClause *pWC;
6083 WhereTerm *pTerm;
6084 WhereLoop *pLoop;
6085 int iCur;
drh92a121f2013-06-10 12:15:47 +00006086 int j;
drh60c96cd2013-06-09 17:21:25 +00006087 Table *pTab;
6088 Index *pIdx;
6089
6090 pWInfo = pBuilder->pWInfo;
drh5822d6f2013-06-10 23:30:09 +00006091 if( pWInfo->wctrlFlags & WHERE_FORCE_TABLE ) return 0;
drh60c96cd2013-06-09 17:21:25 +00006092 assert( pWInfo->pTabList->nSrc>=1 );
6093 pItem = pWInfo->pTabList->a;
6094 pTab = pItem->pTab;
6095 if( IsVirtual(pTab) ) return 0;
6096 if( pItem->zIndex ) return 0;
6097 iCur = pItem->iCursor;
6098 pWC = &pWInfo->sWC;
6099 pLoop = pBuilder->pNew;
drh60c96cd2013-06-09 17:21:25 +00006100 pLoop->wsFlags = 0;
drhc8bbce12014-10-21 01:05:09 +00006101 pLoop->nSkip = 0;
drh3b75ffa2013-06-10 14:56:25 +00006102 pTerm = findTerm(pWC, iCur, -1, 0, WO_EQ, 0);
drh60c96cd2013-06-09 17:21:25 +00006103 if( pTerm ){
6104 pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
6105 pLoop->aLTerm[0] = pTerm;
6106 pLoop->nLTerm = 1;
6107 pLoop->u.btree.nEq = 1;
drhe1e2e9a2013-06-13 15:16:53 +00006108 /* TUNING: Cost of a rowid lookup is 10 */
drhbf539c42013-10-05 18:16:02 +00006109 pLoop->rRun = 33; /* 33==sqlite3LogEst(10) */
drh60c96cd2013-06-09 17:21:25 +00006110 }else{
6111 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
dancd40abb2013-08-29 10:46:05 +00006112 assert( pLoop->aLTermSpace==pLoop->aLTerm );
drh5f1d1d92014-07-31 22:59:04 +00006113 if( !IsUniqueIndex(pIdx)
dancd40abb2013-08-29 10:46:05 +00006114 || pIdx->pPartIdxWhere!=0
drhbbbdc832013-10-22 18:01:40 +00006115 || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace)
dancd40abb2013-08-29 10:46:05 +00006116 ) continue;
drhbbbdc832013-10-22 18:01:40 +00006117 for(j=0; j<pIdx->nKeyCol; j++){
drh3b75ffa2013-06-10 14:56:25 +00006118 pTerm = findTerm(pWC, iCur, pIdx->aiColumn[j], 0, WO_EQ, pIdx);
drh60c96cd2013-06-09 17:21:25 +00006119 if( pTerm==0 ) break;
drh60c96cd2013-06-09 17:21:25 +00006120 pLoop->aLTerm[j] = pTerm;
6121 }
drhbbbdc832013-10-22 18:01:40 +00006122 if( j!=pIdx->nKeyCol ) continue;
drh92a121f2013-06-10 12:15:47 +00006123 pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
drhec95c442013-10-23 01:57:32 +00006124 if( pIdx->isCovering || (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){
drh92a121f2013-06-10 12:15:47 +00006125 pLoop->wsFlags |= WHERE_IDX_ONLY;
6126 }
drh60c96cd2013-06-09 17:21:25 +00006127 pLoop->nLTerm = j;
6128 pLoop->u.btree.nEq = j;
6129 pLoop->u.btree.pIndex = pIdx;
drhe1e2e9a2013-06-13 15:16:53 +00006130 /* TUNING: Cost of a unique index lookup is 15 */
drhbf539c42013-10-05 18:16:02 +00006131 pLoop->rRun = 39; /* 39==sqlite3LogEst(15) */
drh60c96cd2013-06-09 17:21:25 +00006132 break;
6133 }
6134 }
drh3b75ffa2013-06-10 14:56:25 +00006135 if( pLoop->wsFlags ){
drhbf539c42013-10-05 18:16:02 +00006136 pLoop->nOut = (LogEst)1;
drh3b75ffa2013-06-10 14:56:25 +00006137 pWInfo->a[0].pWLoop = pLoop;
6138 pLoop->maskSelf = getMask(&pWInfo->sMaskSet, iCur);
6139 pWInfo->a[0].iTabCur = iCur;
6140 pWInfo->nRowOut = 1;
drhddba0c22014-03-18 20:33:42 +00006141 if( pWInfo->pOrderBy ) pWInfo->nOBSat = pWInfo->pOrderBy->nExpr;
drh6457a352013-06-21 00:35:37 +00006142 if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
6143 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
6144 }
drh3b75ffa2013-06-10 14:56:25 +00006145#ifdef SQLITE_DEBUG
6146 pLoop->cId = '0';
6147#endif
6148 return 1;
6149 }
6150 return 0;
drh60c96cd2013-06-09 17:21:25 +00006151}
6152
6153/*
drh75897232000-05-29 14:26:00 +00006154** Generate the beginning of the loop used for WHERE clause processing.
6155** The return value is a pointer to an opaque structure that contains
6156** information needed to terminate the loop. Later, the calling routine
6157** should invoke sqlite3WhereEnd() with the return value of this function
6158** in order to complete the WHERE clause processing.
6159**
6160** If an error occurs, this routine returns NULL.
drhc27a1ce2002-06-14 20:58:45 +00006161**
6162** The basic idea is to do a nested loop, one loop for each table in
6163** the FROM clause of a select. (INSERT and UPDATE statements are the
6164** same as a SELECT with only a single table in the FROM clause.) For
6165** example, if the SQL is this:
6166**
6167** SELECT * FROM t1, t2, t3 WHERE ...;
6168**
6169** Then the code generated is conceptually like the following:
6170**
6171** foreach row1 in t1 do \ Code generated
danielk19774adee202004-05-08 08:23:19 +00006172** foreach row2 in t2 do |-- by sqlite3WhereBegin()
drhc27a1ce2002-06-14 20:58:45 +00006173** foreach row3 in t3 do /
6174** ...
6175** end \ Code generated
danielk19774adee202004-05-08 08:23:19 +00006176** end |-- by sqlite3WhereEnd()
drhc27a1ce2002-06-14 20:58:45 +00006177** end /
6178**
drh29dda4a2005-07-21 18:23:20 +00006179** Note that the loops might not be nested in the order in which they
6180** appear in the FROM clause if a different order is better able to make
drh51147ba2005-07-23 22:59:55 +00006181** use of indices. Note also that when the IN operator appears in
6182** the WHERE clause, it might result in additional nested loops for
6183** scanning through all values on the right-hand side of the IN.
drh29dda4a2005-07-21 18:23:20 +00006184**
drhc27a1ce2002-06-14 20:58:45 +00006185** There are Btree cursors associated with each table. t1 uses cursor
drh6a3ea0e2003-05-02 14:32:12 +00006186** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
6187** And so forth. This routine generates code to open those VDBE cursors
danielk19774adee202004-05-08 08:23:19 +00006188** and sqlite3WhereEnd() generates the code to close them.
drhc27a1ce2002-06-14 20:58:45 +00006189**
drhe6f85e72004-12-25 01:03:13 +00006190** The code that sqlite3WhereBegin() generates leaves the cursors named
6191** in pTabList pointing at their appropriate entries. The [...] code
drhf0863fe2005-06-12 21:35:51 +00006192** can use OP_Column and OP_Rowid opcodes on these cursors to extract
drhe6f85e72004-12-25 01:03:13 +00006193** data from the various tables of the loop.
6194**
drhc27a1ce2002-06-14 20:58:45 +00006195** If the WHERE clause is empty, the foreach loops must each scan their
6196** entire tables. Thus a three-way join is an O(N^3) operation. But if
6197** the tables have indices and there are terms in the WHERE clause that
6198** refer to those indices, a complete table scan can be avoided and the
6199** code will run much faster. Most of the work of this routine is checking
6200** to see if there are indices that can be used to speed up the loop.
6201**
6202** Terms of the WHERE clause are also used to limit which rows actually
6203** make it to the "..." in the middle of the loop. After each "foreach",
6204** terms of the WHERE clause that use only terms in that loop and outer
6205** loops are evaluated and if false a jump is made around all subsequent
6206** inner loops (or around the "..." if the test occurs within the inner-
6207** most loop)
6208**
6209** OUTER JOINS
6210**
6211** An outer join of tables t1 and t2 is conceptally coded as follows:
6212**
6213** foreach row1 in t1 do
6214** flag = 0
6215** foreach row2 in t2 do
6216** start:
6217** ...
6218** flag = 1
6219** end
drhe3184742002-06-19 14:27:05 +00006220** if flag==0 then
6221** move the row2 cursor to a null row
6222** goto start
6223** fi
drhc27a1ce2002-06-14 20:58:45 +00006224** end
6225**
drhe3184742002-06-19 14:27:05 +00006226** ORDER BY CLAUSE PROCESSING
6227**
drh94433422013-07-01 11:05:50 +00006228** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause
6229** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement
drhe3184742002-06-19 14:27:05 +00006230** if there is one. If there is no ORDER BY clause or if this routine
drh46ec5b62012-09-24 15:30:54 +00006231** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
drhfc8d4f92013-11-08 15:19:46 +00006232**
6233** The iIdxCur parameter is the cursor number of an index. If
6234** WHERE_ONETABLE_ONLY is set, iIdxCur is the cursor number of an index
6235** to use for OR clause processing. The WHERE clause should use this
6236** specific cursor. If WHERE_ONEPASS_DESIRED is set, then iIdxCur is
6237** the first cursor in an array of cursors for all indices. iIdxCur should
6238** be used to compute the appropriate cursor depending on which index is
6239** used.
drh75897232000-05-29 14:26:00 +00006240*/
danielk19774adee202004-05-08 08:23:19 +00006241WhereInfo *sqlite3WhereBegin(
danielk1977ed326d72004-11-16 15:50:19 +00006242 Parse *pParse, /* The parser context */
drh6457a352013-06-21 00:35:37 +00006243 SrcList *pTabList, /* FROM clause: A list of all tables to be scanned */
danielk1977ed326d72004-11-16 15:50:19 +00006244 Expr *pWhere, /* The WHERE clause */
drh0401ace2014-03-18 15:30:27 +00006245 ExprList *pOrderBy, /* An ORDER BY (or GROUP BY) clause, or NULL */
drh6457a352013-06-21 00:35:37 +00006246 ExprList *pResultSet, /* Result set of the query */
dan0efb72c2012-08-24 18:44:56 +00006247 u16 wctrlFlags, /* One of the WHERE_* flags defined in sqliteInt.h */
6248 int iIdxCur /* If WHERE_ONETABLE_ONLY is set, index cursor number */
drh75897232000-05-29 14:26:00 +00006249){
danielk1977be229652009-03-20 14:18:51 +00006250 int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
drhc01a3c12009-12-16 22:10:49 +00006251 int nTabList; /* Number of elements in pTabList */
drh75897232000-05-29 14:26:00 +00006252 WhereInfo *pWInfo; /* Will become the return value of this function */
6253 Vdbe *v = pParse->pVdbe; /* The virtual database engine */
drhfe05af82005-07-21 03:14:59 +00006254 Bitmask notReady; /* Cursors that are not yet positioned */
drh1c8148f2013-05-04 20:25:23 +00006255 WhereLoopBuilder sWLB; /* The WhereLoop builder */
drh111a6a72008-12-21 03:51:16 +00006256 WhereMaskSet *pMaskSet; /* The expression mask set */
drh56f1b992012-09-25 14:29:39 +00006257 WhereLevel *pLevel; /* A single level in pWInfo->a[] */
drhfd636c72013-06-21 02:05:06 +00006258 WhereLoop *pLoop; /* Pointer to a single WhereLoop object */
drh9cd1c992012-09-25 20:43:35 +00006259 int ii; /* Loop counter */
drh17435752007-08-16 04:30:38 +00006260 sqlite3 *db; /* Database connection */
drh5346e952013-05-08 14:14:26 +00006261 int rc; /* Return code */
drh75897232000-05-29 14:26:00 +00006262
drh56f1b992012-09-25 14:29:39 +00006263
6264 /* Variable initialization */
drhfd636c72013-06-21 02:05:06 +00006265 db = pParse->db;
drh1c8148f2013-05-04 20:25:23 +00006266 memset(&sWLB, 0, sizeof(sWLB));
drh0401ace2014-03-18 15:30:27 +00006267
6268 /* An ORDER/GROUP BY clause of more than 63 terms cannot be optimized */
6269 testcase( pOrderBy && pOrderBy->nExpr==BMS-1 );
6270 if( pOrderBy && pOrderBy->nExpr>=BMS ) pOrderBy = 0;
drh1c8148f2013-05-04 20:25:23 +00006271 sWLB.pOrderBy = pOrderBy;
drh56f1b992012-09-25 14:29:39 +00006272
drhfd636c72013-06-21 02:05:06 +00006273 /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
6274 ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
6275 if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
6276 wctrlFlags &= ~WHERE_WANT_DISTINCT;
6277 }
6278
drh29dda4a2005-07-21 18:23:20 +00006279 /* The number of tables in the FROM clause is limited by the number of
drh1398ad32005-01-19 23:24:50 +00006280 ** bits in a Bitmask
6281 */
drh67ae0cb2010-04-08 14:38:51 +00006282 testcase( pTabList->nSrc==BMS );
drh29dda4a2005-07-21 18:23:20 +00006283 if( pTabList->nSrc>BMS ){
6284 sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
drh1398ad32005-01-19 23:24:50 +00006285 return 0;
6286 }
6287
drhc01a3c12009-12-16 22:10:49 +00006288 /* This function normally generates a nested loop for all tables in
6289 ** pTabList. But if the WHERE_ONETABLE_ONLY flag is set, then we should
6290 ** only generate code for the first table in pTabList and assume that
6291 ** any cursors associated with subsequent tables are uninitialized.
6292 */
6293 nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
6294
drh75897232000-05-29 14:26:00 +00006295 /* Allocate and initialize the WhereInfo structure that will become the
danielk1977be229652009-03-20 14:18:51 +00006296 ** return value. A single allocation is used to store the WhereInfo
6297 ** struct, the contents of WhereInfo.a[], the WhereClause structure
6298 ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
6299 ** field (type Bitmask) it must be aligned on an 8-byte boundary on
6300 ** some architectures. Hence the ROUND8() below.
drh75897232000-05-29 14:26:00 +00006301 */
drhc01a3c12009-12-16 22:10:49 +00006302 nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
drh60c96cd2013-06-09 17:21:25 +00006303 pWInfo = sqlite3DbMallocZero(db, nByteWInfo + sizeof(WhereLoop));
drh17435752007-08-16 04:30:38 +00006304 if( db->mallocFailed ){
drh8b307fb2010-04-06 15:57:05 +00006305 sqlite3DbFree(db, pWInfo);
6306 pWInfo = 0;
danielk197785574e32008-10-06 05:32:18 +00006307 goto whereBeginError;
drh75897232000-05-29 14:26:00 +00006308 }
drhfc8d4f92013-11-08 15:19:46 +00006309 pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1;
drhc01a3c12009-12-16 22:10:49 +00006310 pWInfo->nLevel = nTabList;
drh75897232000-05-29 14:26:00 +00006311 pWInfo->pParse = pParse;
6312 pWInfo->pTabList = pTabList;
drh6b7157b2013-05-10 02:00:35 +00006313 pWInfo->pOrderBy = pOrderBy;
drh6457a352013-06-21 00:35:37 +00006314 pWInfo->pResultSet = pResultSet;
drha22a75e2014-03-21 18:16:23 +00006315 pWInfo->iBreak = pWInfo->iContinue = sqlite3VdbeMakeLabel(v);
drh6df2acd2008-12-28 16:55:25 +00006316 pWInfo->wctrlFlags = wctrlFlags;
drh8b307fb2010-04-06 15:57:05 +00006317 pWInfo->savedNQueryLoop = pParse->nQueryLoop;
drh70d18342013-06-06 19:16:33 +00006318 pMaskSet = &pWInfo->sMaskSet;
drh1c8148f2013-05-04 20:25:23 +00006319 sWLB.pWInfo = pWInfo;
drh70d18342013-06-06 19:16:33 +00006320 sWLB.pWC = &pWInfo->sWC;
drh1ac87e12013-07-18 14:50:56 +00006321 sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);
6322 assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) );
drh60c96cd2013-06-09 17:21:25 +00006323 whereLoopInit(sWLB.pNew);
drhb8a8e8a2013-06-10 19:12:39 +00006324#ifdef SQLITE_DEBUG
6325 sWLB.pNew->cId = '*';
6326#endif
drh08192d52002-04-30 19:20:28 +00006327
drh111a6a72008-12-21 03:51:16 +00006328 /* Split the WHERE clause into separate subexpressions where each
6329 ** subexpression is separated by an AND operator.
6330 */
6331 initMaskSet(pMaskSet);
drh70d18342013-06-06 19:16:33 +00006332 whereClauseInit(&pWInfo->sWC, pWInfo);
drh39759742013-08-02 23:40:45 +00006333 whereSplit(&pWInfo->sWC, pWhere, TK_AND);
drh111a6a72008-12-21 03:51:16 +00006334
drh08192d52002-04-30 19:20:28 +00006335 /* Special case: a WHERE clause that is constant. Evaluate the
6336 ** expression and either jump over all of the code or fall thru.
6337 */
drh759e8582014-01-02 21:05:10 +00006338 for(ii=0; ii<sWLB.pWC->nTerm; ii++){
6339 if( nTabList==0 || sqlite3ExprIsConstantNotJoin(sWLB.pWC->a[ii].pExpr) ){
6340 sqlite3ExprIfFalse(pParse, sWLB.pWC->a[ii].pExpr, pWInfo->iBreak,
6341 SQLITE_JUMPIFNULL);
6342 sWLB.pWC->a[ii].wtFlags |= TERM_CODED;
6343 }
drh08192d52002-04-30 19:20:28 +00006344 }
drh75897232000-05-29 14:26:00 +00006345
drh4fe425a2013-06-12 17:08:06 +00006346 /* Special case: No FROM clause
6347 */
6348 if( nTabList==0 ){
drhddba0c22014-03-18 20:33:42 +00006349 if( pOrderBy ) pWInfo->nOBSat = pOrderBy->nExpr;
drh6457a352013-06-21 00:35:37 +00006350 if( wctrlFlags & WHERE_WANT_DISTINCT ){
6351 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
6352 }
drh4fe425a2013-06-12 17:08:06 +00006353 }
6354
drh42165be2008-03-26 14:56:34 +00006355 /* Assign a bit from the bitmask to every term in the FROM clause.
6356 **
6357 ** When assigning bitmask values to FROM clause cursors, it must be
6358 ** the case that if X is the bitmask for the N-th FROM clause term then
6359 ** the bitmask for all FROM clause terms to the left of the N-th term
6360 ** is (X-1). An expression from the ON clause of a LEFT JOIN can use
6361 ** its Expr.iRightJoinTable value to find the bitmask of the right table
6362 ** of the join. Subtracting one from the right table bitmask gives a
6363 ** bitmask for all tables to the left of the join. Knowing the bitmask
6364 ** for all tables to the left of a left join is important. Ticket #3015.
danielk1977e672c8e2009-05-22 15:43:26 +00006365 **
drhc01a3c12009-12-16 22:10:49 +00006366 ** Note that bitmasks are created for all pTabList->nSrc tables in
6367 ** pTabList, not just the first nTabList tables. nTabList is normally
6368 ** equal to pTabList->nSrc but might be shortened to 1 if the
6369 ** WHERE_ONETABLE_ONLY flag is set.
drh42165be2008-03-26 14:56:34 +00006370 */
drh9cd1c992012-09-25 20:43:35 +00006371 for(ii=0; ii<pTabList->nSrc; ii++){
6372 createMask(pMaskSet, pTabList->a[ii].iCursor);
drh42165be2008-03-26 14:56:34 +00006373 }
6374#ifndef NDEBUG
6375 {
6376 Bitmask toTheLeft = 0;
drh9cd1c992012-09-25 20:43:35 +00006377 for(ii=0; ii<pTabList->nSrc; ii++){
6378 Bitmask m = getMask(pMaskSet, pTabList->a[ii].iCursor);
drh42165be2008-03-26 14:56:34 +00006379 assert( (m-1)==toTheLeft );
6380 toTheLeft |= m;
6381 }
6382 }
6383#endif
6384
drh29dda4a2005-07-21 18:23:20 +00006385 /* Analyze all of the subexpressions. Note that exprAnalyze() might
6386 ** add new virtual terms onto the end of the WHERE clause. We do not
6387 ** want to analyze these virtual terms, so start analyzing at the end
drhb6fb62d2005-09-20 08:47:20 +00006388 ** and work forward so that the added virtual terms are never processed.
drh75897232000-05-29 14:26:00 +00006389 */
drh70d18342013-06-06 19:16:33 +00006390 exprAnalyzeAll(pTabList, &pWInfo->sWC);
drh17435752007-08-16 04:30:38 +00006391 if( db->mallocFailed ){
danielk197785574e32008-10-06 05:32:18 +00006392 goto whereBeginError;
drh0bbaa1b2005-08-19 19:14:12 +00006393 }
drh75897232000-05-29 14:26:00 +00006394
drh6457a352013-06-21 00:35:37 +00006395 if( wctrlFlags & WHERE_WANT_DISTINCT ){
6396 if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){
6397 /* The DISTINCT marking is pointless. Ignore it. */
drh4f402f22013-06-11 18:59:38 +00006398 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
6399 }else if( pOrderBy==0 ){
drh6457a352013-06-21 00:35:37 +00006400 /* Try to ORDER BY the result set to make distinct processing easier */
drh4f402f22013-06-11 18:59:38 +00006401 pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
drh6457a352013-06-21 00:35:37 +00006402 pWInfo->pOrderBy = pResultSet;
drh4f402f22013-06-11 18:59:38 +00006403 }
dan38cc40c2011-06-30 20:17:15 +00006404 }
6405
drhf1b5f5b2013-05-02 00:15:01 +00006406 /* Construct the WhereLoop objects */
drh3b48e8c2013-06-12 20:18:16 +00006407 WHERETRACE(0xffff,("*** Optimizer Start ***\n"));
drhc90713d2014-09-30 13:46:49 +00006408#if defined(WHERETRACE_ENABLED)
6409 /* Display all terms of the WHERE clause */
6410 if( sqlite3WhereTrace & 0x100 ){
6411 int i;
6412 for(i=0; i<sWLB.pWC->nTerm; i++){
6413 whereTermPrint(&sWLB.pWC->a[i], i);
6414 }
6415 }
6416#endif
6417
drhb8a8e8a2013-06-10 19:12:39 +00006418 if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
drh60c96cd2013-06-09 17:21:25 +00006419 rc = whereLoopAddAll(&sWLB);
6420 if( rc ) goto whereBeginError;
6421
6422 /* Display all of the WhereLoop objects if wheretrace is enabled */
drh989578e2013-10-28 14:34:35 +00006423#ifdef WHERETRACE_ENABLED /* !=0 */
drh60c96cd2013-06-09 17:21:25 +00006424 if( sqlite3WhereTrace ){
6425 WhereLoop *p;
drhfd636c72013-06-21 02:05:06 +00006426 int i;
drh60c96cd2013-06-09 17:21:25 +00006427 static char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
6428 "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
drhfd636c72013-06-21 02:05:06 +00006429 for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
6430 p->cId = zLabel[i%sizeof(zLabel)];
drhc1ba2e72013-10-28 19:03:21 +00006431 whereLoopPrint(p, sWLB.pWC);
drh60c96cd2013-06-09 17:21:25 +00006432 }
6433 }
6434#endif
6435
drh4f402f22013-06-11 18:59:38 +00006436 wherePathSolver(pWInfo, 0);
drh60c96cd2013-06-09 17:21:25 +00006437 if( db->mallocFailed ) goto whereBeginError;
6438 if( pWInfo->pOrderBy ){
drhc7f0d222013-06-19 03:27:12 +00006439 wherePathSolver(pWInfo, pWInfo->nRowOut+1);
drh60c96cd2013-06-09 17:21:25 +00006440 if( db->mallocFailed ) goto whereBeginError;
drha18f3d22013-05-08 03:05:41 +00006441 }
6442 }
drh60c96cd2013-06-09 17:21:25 +00006443 if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
drhd84ce352013-06-04 18:27:41 +00006444 pWInfo->revMask = (Bitmask)(-1);
drha50ef112013-05-22 02:06:59 +00006445 }
drh81186b42013-06-18 01:52:41 +00006446 if( pParse->nErr || NEVER(db->mallocFailed) ){
drh75b93402013-05-31 20:43:57 +00006447 goto whereBeginError;
6448 }
drh989578e2013-10-28 14:34:35 +00006449#ifdef WHERETRACE_ENABLED /* !=0 */
drha18f3d22013-05-08 03:05:41 +00006450 if( sqlite3WhereTrace ){
6451 int ii;
drh4f402f22013-06-11 18:59:38 +00006452 sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
drhddba0c22014-03-18 20:33:42 +00006453 if( pWInfo->nOBSat>0 ){
6454 sqlite3DebugPrintf(" ORDERBY=%d,0x%llx", pWInfo->nOBSat, pWInfo->revMask);
drh319f6772013-05-14 15:31:07 +00006455 }
drh4f402f22013-06-11 18:59:38 +00006456 switch( pWInfo->eDistinct ){
6457 case WHERE_DISTINCT_UNIQUE: {
6458 sqlite3DebugPrintf(" DISTINCT=unique");
6459 break;
6460 }
6461 case WHERE_DISTINCT_ORDERED: {
6462 sqlite3DebugPrintf(" DISTINCT=ordered");
6463 break;
6464 }
6465 case WHERE_DISTINCT_UNORDERED: {
6466 sqlite3DebugPrintf(" DISTINCT=unordered");
6467 break;
6468 }
6469 }
6470 sqlite3DebugPrintf("\n");
drhfd636c72013-06-21 02:05:06 +00006471 for(ii=0; ii<pWInfo->nLevel; ii++){
drhc1ba2e72013-10-28 19:03:21 +00006472 whereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC);
drhf1b5f5b2013-05-02 00:15:01 +00006473 }
6474 }
6475#endif
drhfd636c72013-06-21 02:05:06 +00006476 /* Attempt to omit tables from the join that do not effect the result */
drh1031bd92013-06-22 15:44:26 +00006477 if( pWInfo->nLevel>=2
6478 && pResultSet!=0
6479 && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
6480 ){
drhfd636c72013-06-21 02:05:06 +00006481 Bitmask tabUsed = exprListTableUsage(pMaskSet, pResultSet);
drh67a5ec72013-09-03 14:03:47 +00006482 if( sWLB.pOrderBy ) tabUsed |= exprListTableUsage(pMaskSet, sWLB.pOrderBy);
drhfd636c72013-06-21 02:05:06 +00006483 while( pWInfo->nLevel>=2 ){
drh9d5a5792013-06-28 13:43:33 +00006484 WhereTerm *pTerm, *pEnd;
drhfd636c72013-06-21 02:05:06 +00006485 pLoop = pWInfo->a[pWInfo->nLevel-1].pWLoop;
drhbc71b1d2013-06-21 02:15:48 +00006486 if( (pWInfo->pTabList->a[pLoop->iTab].jointype & JT_LEFT)==0 ) break;
6487 if( (wctrlFlags & WHERE_WANT_DISTINCT)==0
6488 && (pLoop->wsFlags & WHERE_ONEROW)==0
drhfd636c72013-06-21 02:05:06 +00006489 ){
drhfd636c72013-06-21 02:05:06 +00006490 break;
6491 }
drhbc71b1d2013-06-21 02:15:48 +00006492 if( (tabUsed & pLoop->maskSelf)!=0 ) break;
drh9d5a5792013-06-28 13:43:33 +00006493 pEnd = sWLB.pWC->a + sWLB.pWC->nTerm;
6494 for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
6495 if( (pTerm->prereqAll & pLoop->maskSelf)!=0
6496 && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
6497 ){
6498 break;
6499 }
6500 }
6501 if( pTerm<pEnd ) break;
drhbc71b1d2013-06-21 02:15:48 +00006502 WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId));
6503 pWInfo->nLevel--;
6504 nTabList--;
drhfd636c72013-06-21 02:05:06 +00006505 }
6506 }
drh3b48e8c2013-06-12 20:18:16 +00006507 WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
drh8e23daf2013-06-11 13:30:04 +00006508 pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
drhf1b5f5b2013-05-02 00:15:01 +00006509
drh08c88eb2008-04-10 13:33:18 +00006510 /* If the caller is an UPDATE or DELETE statement that is requesting
6511 ** to use a one-pass algorithm, determine if this is appropriate.
drh24b7fe92013-09-30 19:33:06 +00006512 ** The one-pass algorithm only works if the WHERE clause constrains
drh08c88eb2008-04-10 13:33:18 +00006513 ** the statement to update a single row.
6514 */
drh165be382008-12-05 02:36:33 +00006515 assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
drh3b48e8c2013-06-12 20:18:16 +00006516 if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
6517 && (pWInfo->a[0].pWLoop->wsFlags & WHERE_ONEROW)!=0 ){
drh08c88eb2008-04-10 13:33:18 +00006518 pWInfo->okOnePass = 1;
drh702ba9f2013-11-07 21:25:13 +00006519 if( HasRowid(pTabList->a[0].pTab) ){
6520 pWInfo->a[0].pWLoop->wsFlags &= ~WHERE_IDX_ONLY;
6521 }
drh08c88eb2008-04-10 13:33:18 +00006522 }
drheb04de32013-05-10 15:16:30 +00006523
drh9012bcb2004-12-19 00:11:35 +00006524 /* Open all tables in the pTabList and any indices selected for
6525 ** searching those tables.
6526 */
drh8b307fb2010-04-06 15:57:05 +00006527 notReady = ~(Bitmask)0;
drh9cd1c992012-09-25 20:43:35 +00006528 for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
danielk1977da184232006-01-05 11:34:32 +00006529 Table *pTab; /* Table to open */
danielk1977da184232006-01-05 11:34:32 +00006530 int iDb; /* Index of database containing table/index */
drh56f1b992012-09-25 14:29:39 +00006531 struct SrcList_item *pTabItem;
drh9012bcb2004-12-19 00:11:35 +00006532
drh29dda4a2005-07-21 18:23:20 +00006533 pTabItem = &pTabList->a[pLevel->iFrom];
drh9012bcb2004-12-19 00:11:35 +00006534 pTab = pTabItem->pTab;
danielk1977595a5232009-07-24 17:58:53 +00006535 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
drh7ba39a92013-05-30 17:43:19 +00006536 pLoop = pLevel->pWLoop;
drh424aab82010-04-06 18:28:20 +00006537 if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
drh75bb9f52010-04-06 18:51:42 +00006538 /* Do nothing */
6539 }else
drh9eff6162006-06-12 21:59:13 +00006540#ifndef SQLITE_OMIT_VIRTUALTABLE
drh7ba39a92013-05-30 17:43:19 +00006541 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
danielk1977595a5232009-07-24 17:58:53 +00006542 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
danielk197793626f42006-06-20 13:07:27 +00006543 int iCur = pTabItem->iCursor;
danielk1977595a5232009-07-24 17:58:53 +00006544 sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
drhfc5e5462012-12-03 17:04:40 +00006545 }else if( IsVirtual(pTab) ){
6546 /* noop */
drh9eff6162006-06-12 21:59:13 +00006547 }else
6548#endif
drh7ba39a92013-05-30 17:43:19 +00006549 if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
drh9ef61f42011-10-07 14:40:59 +00006550 && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){
drhfc8d4f92013-11-08 15:19:46 +00006551 int op = OP_OpenRead;
6552 if( pWInfo->okOnePass ){
6553 op = OP_OpenWrite;
6554 pWInfo->aiCurOnePass[0] = pTabItem->iCursor;
6555 };
drh08c88eb2008-04-10 13:33:18 +00006556 sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
drhfc8d4f92013-11-08 15:19:46 +00006557 assert( pTabItem->iCursor==pLevel->iTabCur );
drh7963b0e2013-06-17 21:37:40 +00006558 testcase( !pWInfo->okOnePass && pTab->nCol==BMS-1 );
6559 testcase( !pWInfo->okOnePass && pTab->nCol==BMS );
drhdd9930e2013-10-23 23:37:02 +00006560 if( !pWInfo->okOnePass && pTab->nCol<BMS && HasRowid(pTab) ){
danielk19779792eef2006-01-13 15:58:43 +00006561 Bitmask b = pTabItem->colUsed;
6562 int n = 0;
drh74161702006-02-24 02:53:49 +00006563 for(; b; b=b>>1, n++){}
drh8cff69d2009-11-12 19:59:44 +00006564 sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
6565 SQLITE_INT_TO_PTR(n), P4_INT32);
danielk19779792eef2006-01-13 15:58:43 +00006566 assert( n<=pTab->nCol );
6567 }
danielk1977c00da102006-01-07 13:21:04 +00006568 }else{
6569 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
drh9012bcb2004-12-19 00:11:35 +00006570 }
drh7e47cb82013-05-31 17:55:27 +00006571 if( pLoop->wsFlags & WHERE_INDEXED ){
drh7ba39a92013-05-30 17:43:19 +00006572 Index *pIx = pLoop->u.btree.pIndex;
drhfc8d4f92013-11-08 15:19:46 +00006573 int iIndexCur;
6574 int op = OP_OpenRead;
drh4308e342013-11-11 16:55:52 +00006575 /* iIdxCur is always set if to a positive value if ONEPASS is possible */
6576 assert( iIdxCur!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 );
drh48dd1d82014-05-27 18:18:58 +00006577 if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIx)
drha3bc66a2014-05-27 17:57:32 +00006578 && (wctrlFlags & WHERE_ONETABLE_ONLY)!=0
6579 ){
6580 /* This is one term of an OR-optimization using the PRIMARY KEY of a
6581 ** WITHOUT ROWID table. No need for a separate index */
6582 iIndexCur = pLevel->iTabCur;
6583 op = 0;
6584 }else if( pWInfo->okOnePass ){
drhfc8d4f92013-11-08 15:19:46 +00006585 Index *pJ = pTabItem->pTab->pIndex;
6586 iIndexCur = iIdxCur;
6587 assert( wctrlFlags & WHERE_ONEPASS_DESIRED );
6588 while( ALWAYS(pJ) && pJ!=pIx ){
6589 iIndexCur++;
6590 pJ = pJ->pNext;
6591 }
6592 op = OP_OpenWrite;
6593 pWInfo->aiCurOnePass[1] = iIndexCur;
6594 }else if( iIdxCur && (wctrlFlags & WHERE_ONETABLE_ONLY)!=0 ){
6595 iIndexCur = iIdxCur;
drh35263192014-07-22 20:02:19 +00006596 if( wctrlFlags & WHERE_REOPEN_IDX ) op = OP_ReopenIdx;
drhfc8d4f92013-11-08 15:19:46 +00006597 }else{
6598 iIndexCur = pParse->nTab++;
6599 }
6600 pLevel->iIdxCur = iIndexCur;
danielk1977da184232006-01-05 11:34:32 +00006601 assert( pIx->pSchema==pTab->pSchema );
drhb0367fb2012-08-25 02:11:13 +00006602 assert( iIndexCur>=0 );
drha3bc66a2014-05-27 17:57:32 +00006603 if( op ){
6604 sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb);
6605 sqlite3VdbeSetP4KeyInfo(pParse, pIx);
6606 VdbeComment((v, "%s", pIx->zName));
6607 }
drh9012bcb2004-12-19 00:11:35 +00006608 }
drhaceb31b2014-02-08 01:40:27 +00006609 if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb);
drh70d18342013-06-06 19:16:33 +00006610 notReady &= ~getMask(&pWInfo->sMaskSet, pTabItem->iCursor);
drh9012bcb2004-12-19 00:11:35 +00006611 }
6612 pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
drha21a64d2010-04-06 22:33:55 +00006613 if( db->mallocFailed ) goto whereBeginError;
drh9012bcb2004-12-19 00:11:35 +00006614
drh29dda4a2005-07-21 18:23:20 +00006615 /* Generate the code to do the search. Each iteration of the for
6616 ** loop below generates code for a single nested loop of the VM
6617 ** program.
drh75897232000-05-29 14:26:00 +00006618 */
drhfe05af82005-07-21 03:14:59 +00006619 notReady = ~(Bitmask)0;
drh9cd1c992012-09-25 20:43:35 +00006620 for(ii=0; ii<nTabList; ii++){
dan6f9702e2014-11-01 20:38:06 +00006621 int addrExplain;
6622 int wsFlags;
drh9cd1c992012-09-25 20:43:35 +00006623 pLevel = &pWInfo->a[ii];
dan6f9702e2014-11-01 20:38:06 +00006624 wsFlags = pLevel->pWLoop->wsFlags;
drhcc04afd2013-08-22 02:56:28 +00006625#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
6626 if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){
6627 constructAutomaticIndex(pParse, &pWInfo->sWC,
6628 &pTabList->a[pLevel->iFrom], notReady, pLevel);
6629 if( db->mallocFailed ) goto whereBeginError;
6630 }
6631#endif
dan6f9702e2014-11-01 20:38:06 +00006632 addrExplain = explainOneScan(
6633 pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags
6634 );
drhcc04afd2013-08-22 02:56:28 +00006635 pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
drh70d18342013-06-06 19:16:33 +00006636 notReady = codeOneLoopStart(pWInfo, ii, notReady);
dan4a07e3d2010-11-09 14:48:59 +00006637 pWInfo->iContinue = pLevel->addrCont;
dan6f9702e2014-11-01 20:38:06 +00006638 if( (wsFlags&WHERE_MULTI_OR)==0 && (wctrlFlags&WHERE_ONETABLE_ONLY)==0 ){
6639 addScanStatus(v, pTabList, pLevel, addrExplain);
6640 }
drh75897232000-05-29 14:26:00 +00006641 }
drh7ec764a2005-07-21 03:48:20 +00006642
drh6fa978d2013-05-30 19:29:19 +00006643 /* Done. */
drh6bc69a22013-11-19 12:33:23 +00006644 VdbeModuleComment((v, "Begin WHERE-core"));
drh75897232000-05-29 14:26:00 +00006645 return pWInfo;
drhe23399f2005-07-22 00:31:39 +00006646
6647 /* Jump here if malloc fails */
danielk197785574e32008-10-06 05:32:18 +00006648whereBeginError:
drh8b307fb2010-04-06 15:57:05 +00006649 if( pWInfo ){
6650 pParse->nQueryLoop = pWInfo->savedNQueryLoop;
6651 whereInfoFree(db, pWInfo);
6652 }
drhe23399f2005-07-22 00:31:39 +00006653 return 0;
drh75897232000-05-29 14:26:00 +00006654}
6655
6656/*
drhc27a1ce2002-06-14 20:58:45 +00006657** Generate the end of the WHERE loop. See comments on
danielk19774adee202004-05-08 08:23:19 +00006658** sqlite3WhereBegin() for additional information.
drh75897232000-05-29 14:26:00 +00006659*/
danielk19774adee202004-05-08 08:23:19 +00006660void sqlite3WhereEnd(WhereInfo *pWInfo){
drh633e6d52008-07-28 19:34:53 +00006661 Parse *pParse = pWInfo->pParse;
6662 Vdbe *v = pParse->pVdbe;
drh19a775c2000-06-05 18:54:46 +00006663 int i;
drh6b563442001-11-07 16:48:26 +00006664 WhereLevel *pLevel;
drh7ba39a92013-05-30 17:43:19 +00006665 WhereLoop *pLoop;
drhad3cab52002-05-24 02:04:32 +00006666 SrcList *pTabList = pWInfo->pTabList;
drh633e6d52008-07-28 19:34:53 +00006667 sqlite3 *db = pParse->db;
drh19a775c2000-06-05 18:54:46 +00006668
drh9012bcb2004-12-19 00:11:35 +00006669 /* Generate loop termination code.
6670 */
drh6bc69a22013-11-19 12:33:23 +00006671 VdbeModuleComment((v, "End WHERE-core"));
drhceea3322009-04-23 13:22:42 +00006672 sqlite3ExprCacheClear(pParse);
drhc01a3c12009-12-16 22:10:49 +00006673 for(i=pWInfo->nLevel-1; i>=0; i--){
drhcd8629e2013-11-13 12:27:25 +00006674 int addr;
drh6b563442001-11-07 16:48:26 +00006675 pLevel = &pWInfo->a[i];
drh7ba39a92013-05-30 17:43:19 +00006676 pLoop = pLevel->pWLoop;
drhb3190c12008-12-08 21:37:14 +00006677 sqlite3VdbeResolveLabel(v, pLevel->addrCont);
drh6b563442001-11-07 16:48:26 +00006678 if( pLevel->op!=OP_Noop ){
drhe39a7322014-02-03 14:04:11 +00006679 sqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3);
drhd1d38482008-10-07 23:46:38 +00006680 sqlite3VdbeChangeP5(v, pLevel->p5);
drh688852a2014-02-17 22:40:43 +00006681 VdbeCoverage(v);
drh7d176102014-02-18 03:07:12 +00006682 VdbeCoverageIf(v, pLevel->op==OP_Next);
6683 VdbeCoverageIf(v, pLevel->op==OP_Prev);
6684 VdbeCoverageIf(v, pLevel->op==OP_VNext);
drh19a775c2000-06-05 18:54:46 +00006685 }
drh7ba39a92013-05-30 17:43:19 +00006686 if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
drh72e8fa42007-03-28 14:30:06 +00006687 struct InLoop *pIn;
drhe23399f2005-07-22 00:31:39 +00006688 int j;
drhb3190c12008-12-08 21:37:14 +00006689 sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
drh111a6a72008-12-21 03:51:16 +00006690 for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
drhb3190c12008-12-08 21:37:14 +00006691 sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
drh2d96b932013-02-08 18:48:23 +00006692 sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
drh688852a2014-02-17 22:40:43 +00006693 VdbeCoverage(v);
drh7d176102014-02-18 03:07:12 +00006694 VdbeCoverageIf(v, pIn->eEndLoopOp==OP_PrevIfOpen);
6695 VdbeCoverageIf(v, pIn->eEndLoopOp==OP_NextIfOpen);
drhb3190c12008-12-08 21:37:14 +00006696 sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
drhe23399f2005-07-22 00:31:39 +00006697 }
drh111a6a72008-12-21 03:51:16 +00006698 sqlite3DbFree(db, pLevel->u.in.aInLoop);
drhd99f7062002-06-08 23:25:08 +00006699 }
drhb3190c12008-12-08 21:37:14 +00006700 sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
drhcd8629e2013-11-13 12:27:25 +00006701 if( pLevel->addrSkip ){
drhcd8629e2013-11-13 12:27:25 +00006702 sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrSkip);
drhe084f402013-11-13 17:24:38 +00006703 VdbeComment((v, "next skip-scan on %s", pLoop->u.btree.pIndex->zName));
drh2e5ef4e2013-11-13 16:58:54 +00006704 sqlite3VdbeJumpHere(v, pLevel->addrSkip);
6705 sqlite3VdbeJumpHere(v, pLevel->addrSkip-2);
drhcd8629e2013-11-13 12:27:25 +00006706 }
drhf07cf6e2015-03-06 16:45:16 +00006707 if( pLevel->addrLikeRep ){
drhb7c60ba2015-03-07 02:51:59 +00006708 int op;
6709 if( sqlite3VdbeGetOp(v, pLevel->addrLikeRep-1)->p1 ){
6710 op = OP_DecrJumpZero;
6711 }else{
6712 op = OP_JumpZeroIncr;
6713 }
6714 sqlite3VdbeAddOp2(v, op, pLevel->iLikeRepCntr, pLevel->addrLikeRep);
drhf07cf6e2015-03-06 16:45:16 +00006715 VdbeCoverage(v);
drhf07cf6e2015-03-06 16:45:16 +00006716 }
drhad2d8302002-05-24 20:31:36 +00006717 if( pLevel->iLeftJoin ){
drh688852a2014-02-17 22:40:43 +00006718 addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v);
drh7ba39a92013-05-30 17:43:19 +00006719 assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
6720 || (pLoop->wsFlags & WHERE_INDEXED)!=0 );
6721 if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 ){
drh35451c62009-11-12 04:26:39 +00006722 sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
6723 }
drh76f4cfb2013-05-31 18:20:52 +00006724 if( pLoop->wsFlags & WHERE_INDEXED ){
drh3c84ddf2008-01-09 02:15:38 +00006725 sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
drh7f09b3e2002-08-13 13:15:49 +00006726 }
drh336a5302009-04-24 15:46:21 +00006727 if( pLevel->op==OP_Return ){
6728 sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
6729 }else{
6730 sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
6731 }
drhd654be82005-09-20 17:42:23 +00006732 sqlite3VdbeJumpHere(v, addr);
drhad2d8302002-05-24 20:31:36 +00006733 }
drh6bc69a22013-11-19 12:33:23 +00006734 VdbeModuleComment((v, "End WHERE-loop%d: %s", i,
drhfc8d4f92013-11-08 15:19:46 +00006735 pWInfo->pTabList->a[pLevel->iFrom].pTab->zName));
drh19a775c2000-06-05 18:54:46 +00006736 }
drh9012bcb2004-12-19 00:11:35 +00006737
6738 /* The "break" point is here, just past the end of the outer loop.
6739 ** Set it.
6740 */
danielk19774adee202004-05-08 08:23:19 +00006741 sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
drh9012bcb2004-12-19 00:11:35 +00006742
drhfd636c72013-06-21 02:05:06 +00006743 assert( pWInfo->nLevel<=pTabList->nSrc );
drhc01a3c12009-12-16 22:10:49 +00006744 for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
drh5f612292014-02-08 23:20:32 +00006745 int k, last;
6746 VdbeOp *pOp;
danbfca6a42012-08-24 10:52:35 +00006747 Index *pIdx = 0;
drh29dda4a2005-07-21 18:23:20 +00006748 struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
drh9012bcb2004-12-19 00:11:35 +00006749 Table *pTab = pTabItem->pTab;
drh5cf590c2003-04-24 01:45:04 +00006750 assert( pTab!=0 );
drh7ba39a92013-05-30 17:43:19 +00006751 pLoop = pLevel->pWLoop;
drhfc8d4f92013-11-08 15:19:46 +00006752
drh5f612292014-02-08 23:20:32 +00006753 /* For a co-routine, change all OP_Column references to the table of
6754 ** the co-routine into OP_SCopy of result contained in a register.
6755 ** OP_Rowid becomes OP_Null.
6756 */
danfbf0f0e2014-03-03 14:20:30 +00006757 if( pTabItem->viaCoroutine && !db->mallocFailed ){
drh5f612292014-02-08 23:20:32 +00006758 last = sqlite3VdbeCurrentAddr(v);
6759 k = pLevel->addrBody;
6760 pOp = sqlite3VdbeGetOp(v, k);
6761 for(; k<last; k++, pOp++){
6762 if( pOp->p1!=pLevel->iTabCur ) continue;
6763 if( pOp->opcode==OP_Column ){
drhc438df12014-04-03 16:29:31 +00006764 pOp->opcode = OP_Copy;
drh5f612292014-02-08 23:20:32 +00006765 pOp->p1 = pOp->p2 + pTabItem->regResult;
6766 pOp->p2 = pOp->p3;
6767 pOp->p3 = 0;
6768 }else if( pOp->opcode==OP_Rowid ){
6769 pOp->opcode = OP_Null;
6770 pOp->p1 = 0;
6771 pOp->p3 = 0;
6772 }
6773 }
6774 continue;
6775 }
6776
drhfc8d4f92013-11-08 15:19:46 +00006777 /* Close all of the cursors that were opened by sqlite3WhereBegin.
6778 ** Except, do not close cursors that will be reused by the OR optimization
6779 ** (WHERE_OMIT_OPEN_CLOSE). And do not close the OP_OpenWrite cursors
6780 ** created for the ONEPASS optimization.
6781 */
drh4139c992010-04-07 14:59:45 +00006782 if( (pTab->tabFlags & TF_Ephemeral)==0
6783 && pTab->pSelect==0
drh9ef61f42011-10-07 14:40:59 +00006784 && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
drh4139c992010-04-07 14:59:45 +00006785 ){
drh7ba39a92013-05-30 17:43:19 +00006786 int ws = pLoop->wsFlags;
drh8b307fb2010-04-06 15:57:05 +00006787 if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
drh6df2acd2008-12-28 16:55:25 +00006788 sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
6789 }
drhfc8d4f92013-11-08 15:19:46 +00006790 if( (ws & WHERE_INDEXED)!=0
6791 && (ws & (WHERE_IPK|WHERE_AUTO_INDEX))==0
6792 && pLevel->iIdxCur!=pWInfo->aiCurOnePass[1]
6793 ){
drh6df2acd2008-12-28 16:55:25 +00006794 sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
6795 }
drh9012bcb2004-12-19 00:11:35 +00006796 }
6797
drhf0030762013-06-14 13:27:01 +00006798 /* If this scan uses an index, make VDBE code substitutions to read data
6799 ** from the index instead of from the table where possible. In some cases
6800 ** this optimization prevents the table from ever being read, which can
6801 ** yield a significant performance boost.
drh9012bcb2004-12-19 00:11:35 +00006802 **
6803 ** Calls to the code generator in between sqlite3WhereBegin and
6804 ** sqlite3WhereEnd will have created code that references the table
6805 ** directly. This loop scans all that code looking for opcodes
6806 ** that reference the table and converts them into opcodes that
6807 ** reference the index.
6808 */
drh7ba39a92013-05-30 17:43:19 +00006809 if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
6810 pIdx = pLoop->u.btree.pIndex;
6811 }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
drhd40e2082012-08-24 23:24:15 +00006812 pIdx = pLevel->u.pCovidx;
danbfca6a42012-08-24 10:52:35 +00006813 }
drh7ba39a92013-05-30 17:43:19 +00006814 if( pIdx && !db->mallocFailed ){
drh9012bcb2004-12-19 00:11:35 +00006815 last = sqlite3VdbeCurrentAddr(v);
drhcc04afd2013-08-22 02:56:28 +00006816 k = pLevel->addrBody;
6817 pOp = sqlite3VdbeGetOp(v, k);
6818 for(; k<last; k++, pOp++){
drh9012bcb2004-12-19 00:11:35 +00006819 if( pOp->p1!=pLevel->iTabCur ) continue;
6820 if( pOp->opcode==OP_Column ){
drhee0ec8e2013-10-31 17:38:01 +00006821 int x = pOp->p2;
drh511717c2013-11-08 17:13:23 +00006822 assert( pIdx->pTable==pTab );
drhee0ec8e2013-10-31 17:38:01 +00006823 if( !HasRowid(pTab) ){
6824 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
6825 x = pPk->aiColumn[x];
6826 }
6827 x = sqlite3ColumnOfIndex(pIdx, x);
drh44156282013-10-23 22:23:03 +00006828 if( x>=0 ){
6829 pOp->p2 = x;
6830 pOp->p1 = pLevel->iIdxCur;
drh9012bcb2004-12-19 00:11:35 +00006831 }
drh44156282013-10-23 22:23:03 +00006832 assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || x>=0 );
drhf0863fe2005-06-12 21:35:51 +00006833 }else if( pOp->opcode==OP_Rowid ){
drh9012bcb2004-12-19 00:11:35 +00006834 pOp->p1 = pLevel->iIdxCur;
drhf0863fe2005-06-12 21:35:51 +00006835 pOp->opcode = OP_IdxRowid;
drh9012bcb2004-12-19 00:11:35 +00006836 }
6837 }
drh6b563442001-11-07 16:48:26 +00006838 }
drh19a775c2000-06-05 18:54:46 +00006839 }
drh9012bcb2004-12-19 00:11:35 +00006840
6841 /* Final cleanup
6842 */
drhf12cde52010-04-08 17:28:00 +00006843 pParse->nQueryLoop = pWInfo->savedNQueryLoop;
6844 whereInfoFree(db, pWInfo);
drh75897232000-05-29 14:26:00 +00006845 return;
6846}