blob: 10383ce4119594a32665e1eb1ddcebd6781d6d83 [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){
drh4f402f22013-06-11 18:59:38 +000042 return pWInfo->bOBSat!=0;
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){
50 return pWInfo->iContinue;
51}
52
53/*
54** Return the VDBE address or label to jump to in order to break
55** out of a WHERE loop.
56*/
57int sqlite3WhereBreakLabel(WhereInfo *pWInfo){
58 return pWInfo->iBreak;
59}
60
61/*
62** Return TRUE if an UPDATE or DELETE statement can operate directly on
63** the rowids returned by a WHERE clause. Return FALSE if doing an
64** UPDATE or DELETE might change subsequent WHERE clause results.
drhfc8d4f92013-11-08 15:19:46 +000065**
66** If the ONEPASS optimization is used (if this routine returns true)
67** then also write the indices of open cursors used by ONEPASS
68** into aiCur[0] and aiCur[1]. iaCur[0] gets the cursor of the data
69** table and iaCur[1] gets the cursor used by an auxiliary index.
70** Either value may be -1, indicating that cursor is not used.
71** Any cursors returned will have been opened for writing.
72**
73** aiCur[0] and aiCur[1] both get -1 if the where-clause logic is
74** unable to use the ONEPASS optimization.
drh6f328482013-06-05 23:39:34 +000075*/
drhfc8d4f92013-11-08 15:19:46 +000076int sqlite3WhereOkOnePass(WhereInfo *pWInfo, int *aiCur){
77 memcpy(aiCur, pWInfo->aiCurOnePass, sizeof(int)*2);
drh6f328482013-06-05 23:39:34 +000078 return pWInfo->okOnePass;
79}
80
81/*
drhaa32e3c2013-07-16 21:31:23 +000082** Move the content of pSrc into pDest
83*/
84static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){
85 pDest->n = pSrc->n;
86 memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0]));
87}
88
89/*
90** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet.
91**
92** The new entry might overwrite an existing entry, or it might be
93** appended, or it might be discarded. Do whatever is the right thing
94** so that pSet keeps the N_OR_COST best entries seen so far.
95*/
96static int whereOrInsert(
97 WhereOrSet *pSet, /* The WhereOrSet to be updated */
98 Bitmask prereq, /* Prerequisites of the new entry */
drhbf539c42013-10-05 18:16:02 +000099 LogEst rRun, /* Run-cost of the new entry */
100 LogEst nOut /* Number of outputs for the new entry */
drhaa32e3c2013-07-16 21:31:23 +0000101){
102 u16 i;
103 WhereOrCost *p;
104 for(i=pSet->n, p=pSet->a; i>0; i--, p++){
105 if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){
106 goto whereOrInsert_done;
107 }
108 if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){
109 return 0;
110 }
111 }
112 if( pSet->n<N_OR_COST ){
113 p = &pSet->a[pSet->n++];
114 p->nOut = nOut;
115 }else{
116 p = pSet->a;
117 for(i=1; i<pSet->n; i++){
118 if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i;
119 }
120 if( p->rRun<=rRun ) return 0;
121 }
122whereOrInsert_done:
123 p->prereq = prereq;
124 p->rRun = rRun;
125 if( p->nOut>nOut ) p->nOut = nOut;
126 return 1;
127}
128
129/*
drh0aa74ed2005-07-16 13:33:20 +0000130** Initialize a preallocated WhereClause structure.
drh75897232000-05-29 14:26:00 +0000131*/
drh7b4fc6a2007-02-06 13:26:32 +0000132static void whereClauseInit(
133 WhereClause *pWC, /* The WhereClause to be initialized */
drh70d18342013-06-06 19:16:33 +0000134 WhereInfo *pWInfo /* The WHERE processing context */
drh7b4fc6a2007-02-06 13:26:32 +0000135){
drh70d18342013-06-06 19:16:33 +0000136 pWC->pWInfo = pWInfo;
drh8871ef52011-10-07 13:33:10 +0000137 pWC->pOuter = 0;
drh0aa74ed2005-07-16 13:33:20 +0000138 pWC->nTerm = 0;
drhcad651e2007-04-20 12:22:01 +0000139 pWC->nSlot = ArraySize(pWC->aStatic);
drh0aa74ed2005-07-16 13:33:20 +0000140 pWC->a = pWC->aStatic;
141}
142
drh700a2262008-12-17 19:22:15 +0000143/* Forward reference */
144static void whereClauseClear(WhereClause*);
145
146/*
147** Deallocate all memory associated with a WhereOrInfo object.
148*/
149static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
drh5bd98ae2009-01-07 18:24:03 +0000150 whereClauseClear(&p->wc);
151 sqlite3DbFree(db, p);
drh700a2262008-12-17 19:22:15 +0000152}
153
154/*
155** Deallocate all memory associated with a WhereAndInfo object.
156*/
157static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
drh5bd98ae2009-01-07 18:24:03 +0000158 whereClauseClear(&p->wc);
159 sqlite3DbFree(db, p);
drh700a2262008-12-17 19:22:15 +0000160}
161
drh0aa74ed2005-07-16 13:33:20 +0000162/*
163** Deallocate a WhereClause structure. The WhereClause structure
164** itself is not freed. This routine is the inverse of whereClauseInit().
165*/
166static void whereClauseClear(WhereClause *pWC){
167 int i;
168 WhereTerm *a;
drh70d18342013-06-06 19:16:33 +0000169 sqlite3 *db = pWC->pWInfo->pParse->db;
drh0aa74ed2005-07-16 13:33:20 +0000170 for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
drh165be382008-12-05 02:36:33 +0000171 if( a->wtFlags & TERM_DYNAMIC ){
drh633e6d52008-07-28 19:34:53 +0000172 sqlite3ExprDelete(db, a->pExpr);
drh0aa74ed2005-07-16 13:33:20 +0000173 }
drh700a2262008-12-17 19:22:15 +0000174 if( a->wtFlags & TERM_ORINFO ){
175 whereOrInfoDelete(db, a->u.pOrInfo);
176 }else if( a->wtFlags & TERM_ANDINFO ){
177 whereAndInfoDelete(db, a->u.pAndInfo);
178 }
drh0aa74ed2005-07-16 13:33:20 +0000179 }
180 if( pWC->a!=pWC->aStatic ){
drh633e6d52008-07-28 19:34:53 +0000181 sqlite3DbFree(db, pWC->a);
drh0aa74ed2005-07-16 13:33:20 +0000182 }
183}
184
185/*
drh6a1e0712008-12-05 15:24:15 +0000186** Add a single new WhereTerm entry to the WhereClause object pWC.
187** The new WhereTerm object is constructed from Expr p and with wtFlags.
188** The index in pWC->a[] of the new WhereTerm is returned on success.
189** 0 is returned if the new WhereTerm could not be added due to a memory
190** allocation error. The memory allocation failure will be recorded in
191** the db->mallocFailed flag so that higher-level functions can detect it.
192**
193** This routine will increase the size of the pWC->a[] array as necessary.
drh9eb20282005-08-24 03:52:18 +0000194**
drh165be382008-12-05 02:36:33 +0000195** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
drh6a1e0712008-12-05 15:24:15 +0000196** for freeing the expression p is assumed by the WhereClause object pWC.
197** This is true even if this routine fails to allocate a new WhereTerm.
drhb63a53d2007-03-31 01:34:44 +0000198**
drh9eb20282005-08-24 03:52:18 +0000199** WARNING: This routine might reallocate the space used to store
drh909626d2008-05-30 14:58:37 +0000200** WhereTerms. All pointers to WhereTerms should be invalidated after
drh9eb20282005-08-24 03:52:18 +0000201** calling this routine. Such pointers may be reinitialized by referencing
202** the pWC->a[] array.
drh0aa74ed2005-07-16 13:33:20 +0000203*/
drhec1724e2008-12-09 01:32:03 +0000204static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
drh0aa74ed2005-07-16 13:33:20 +0000205 WhereTerm *pTerm;
drh9eb20282005-08-24 03:52:18 +0000206 int idx;
drh39759742013-08-02 23:40:45 +0000207 testcase( wtFlags & TERM_VIRTUAL );
drh0aa74ed2005-07-16 13:33:20 +0000208 if( pWC->nTerm>=pWC->nSlot ){
209 WhereTerm *pOld = pWC->a;
drh70d18342013-06-06 19:16:33 +0000210 sqlite3 *db = pWC->pWInfo->pParse->db;
drh633e6d52008-07-28 19:34:53 +0000211 pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
drhb63a53d2007-03-31 01:34:44 +0000212 if( pWC->a==0 ){
drh165be382008-12-05 02:36:33 +0000213 if( wtFlags & TERM_DYNAMIC ){
drh633e6d52008-07-28 19:34:53 +0000214 sqlite3ExprDelete(db, p);
drhb63a53d2007-03-31 01:34:44 +0000215 }
drhf998b732007-11-26 13:36:00 +0000216 pWC->a = pOld;
drhb63a53d2007-03-31 01:34:44 +0000217 return 0;
218 }
drh0aa74ed2005-07-16 13:33:20 +0000219 memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
220 if( pOld!=pWC->aStatic ){
drh633e6d52008-07-28 19:34:53 +0000221 sqlite3DbFree(db, pOld);
drh0aa74ed2005-07-16 13:33:20 +0000222 }
drh6a1e0712008-12-05 15:24:15 +0000223 pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
drh0aa74ed2005-07-16 13:33:20 +0000224 }
drh6a1e0712008-12-05 15:24:15 +0000225 pTerm = &pWC->a[idx = pWC->nTerm++];
drha4c3c872013-09-12 17:29:25 +0000226 if( p && ExprHasProperty(p, EP_Unlikely) ){
drhbf539c42013-10-05 18:16:02 +0000227 pTerm->truthProb = sqlite3LogEst(p->iTable) - 99;
drhcca9f3d2013-09-06 15:23:29 +0000228 }else{
229 pTerm->truthProb = -1;
230 }
drh7ee751d2012-12-19 15:53:51 +0000231 pTerm->pExpr = sqlite3ExprSkipCollate(p);
drh165be382008-12-05 02:36:33 +0000232 pTerm->wtFlags = wtFlags;
drh0fcef5e2005-07-19 17:38:22 +0000233 pTerm->pWC = pWC;
drh45b1ee42005-08-02 17:48:22 +0000234 pTerm->iParent = -1;
drh9eb20282005-08-24 03:52:18 +0000235 return idx;
drh0aa74ed2005-07-16 13:33:20 +0000236}
drh75897232000-05-29 14:26:00 +0000237
238/*
drh51669862004-12-18 18:40:26 +0000239** This routine identifies subexpressions in the WHERE clause where
drhb6fb62d2005-09-20 08:47:20 +0000240** each subexpression is separated by the AND operator or some other
drh6c30be82005-07-29 15:10:17 +0000241** operator specified in the op parameter. The WhereClause structure
242** is filled with pointers to subexpressions. For example:
drh75897232000-05-29 14:26:00 +0000243**
drh51669862004-12-18 18:40:26 +0000244** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
245** \________/ \_______________/ \________________/
246** slot[0] slot[1] slot[2]
247**
248** The original WHERE clause in pExpr is unaltered. All this routine
drh51147ba2005-07-23 22:59:55 +0000249** does is make slot[] entries point to substructure within pExpr.
drh51669862004-12-18 18:40:26 +0000250**
drh51147ba2005-07-23 22:59:55 +0000251** In the previous sentence and in the diagram, "slot[]" refers to
drh902b9ee2008-12-05 17:17:07 +0000252** the WhereClause.a[] array. The slot[] array grows as needed to contain
drh51147ba2005-07-23 22:59:55 +0000253** all terms of the WHERE clause.
drh75897232000-05-29 14:26:00 +0000254*/
drh74f91d42013-06-19 18:01:44 +0000255static void whereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
256 pWC->op = op;
drh0aa74ed2005-07-16 13:33:20 +0000257 if( pExpr==0 ) return;
drh6c30be82005-07-29 15:10:17 +0000258 if( pExpr->op!=op ){
drh0aa74ed2005-07-16 13:33:20 +0000259 whereClauseInsert(pWC, pExpr, 0);
drh75897232000-05-29 14:26:00 +0000260 }else{
drh6c30be82005-07-29 15:10:17 +0000261 whereSplit(pWC, pExpr->pLeft, op);
262 whereSplit(pWC, pExpr->pRight, op);
drh75897232000-05-29 14:26:00 +0000263 }
drh75897232000-05-29 14:26:00 +0000264}
265
266/*
drh3b48e8c2013-06-12 20:18:16 +0000267** Initialize a WhereMaskSet object
drh6a3ea0e2003-05-02 14:32:12 +0000268*/
drhfd5874d2013-06-12 14:52:39 +0000269#define initMaskSet(P) (P)->n=0
drh6a3ea0e2003-05-02 14:32:12 +0000270
271/*
drh1398ad32005-01-19 23:24:50 +0000272** Return the bitmask for the given cursor number. Return 0 if
273** iCursor is not in the set.
drh6a3ea0e2003-05-02 14:32:12 +0000274*/
drh111a6a72008-12-21 03:51:16 +0000275static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
drh6a3ea0e2003-05-02 14:32:12 +0000276 int i;
drhfcd71b62011-04-05 22:08:24 +0000277 assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
drh6a3ea0e2003-05-02 14:32:12 +0000278 for(i=0; i<pMaskSet->n; i++){
drh51669862004-12-18 18:40:26 +0000279 if( pMaskSet->ix[i]==iCursor ){
drh7699d1c2013-06-04 12:42:29 +0000280 return MASKBIT(i);
drh51669862004-12-18 18:40:26 +0000281 }
drh6a3ea0e2003-05-02 14:32:12 +0000282 }
drh6a3ea0e2003-05-02 14:32:12 +0000283 return 0;
284}
285
286/*
drh1398ad32005-01-19 23:24:50 +0000287** Create a new mask for cursor iCursor.
drh0fcef5e2005-07-19 17:38:22 +0000288**
289** There is one cursor per table in the FROM clause. The number of
290** tables in the FROM clause is limited by a test early in the
drhb6fb62d2005-09-20 08:47:20 +0000291** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[]
drh0fcef5e2005-07-19 17:38:22 +0000292** array will never overflow.
drh1398ad32005-01-19 23:24:50 +0000293*/
drh111a6a72008-12-21 03:51:16 +0000294static void createMask(WhereMaskSet *pMaskSet, int iCursor){
drhcad651e2007-04-20 12:22:01 +0000295 assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
drh0fcef5e2005-07-19 17:38:22 +0000296 pMaskSet->ix[pMaskSet->n++] = iCursor;
drh1398ad32005-01-19 23:24:50 +0000297}
298
299/*
drh4a6fc352013-08-07 01:18:38 +0000300** These routines walk (recursively) an expression tree and generate
drh75897232000-05-29 14:26:00 +0000301** a bitmask indicating which tables are used in that expression
drh6a3ea0e2003-05-02 14:32:12 +0000302** tree.
drh75897232000-05-29 14:26:00 +0000303*/
drh111a6a72008-12-21 03:51:16 +0000304static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
305static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
306static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
drh51669862004-12-18 18:40:26 +0000307 Bitmask mask = 0;
drh75897232000-05-29 14:26:00 +0000308 if( p==0 ) return 0;
drh967e8b72000-06-21 13:59:10 +0000309 if( p->op==TK_COLUMN ){
drh8feb4b12004-07-19 02:12:14 +0000310 mask = getMask(pMaskSet, p->iTable);
drh8feb4b12004-07-19 02:12:14 +0000311 return mask;
drh75897232000-05-29 14:26:00 +0000312 }
danielk1977b3bce662005-01-29 08:32:43 +0000313 mask = exprTableUsage(pMaskSet, p->pRight);
314 mask |= exprTableUsage(pMaskSet, p->pLeft);
danielk19776ab3a2e2009-02-19 14:39:25 +0000315 if( ExprHasProperty(p, EP_xIsSelect) ){
316 mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
317 }else{
318 mask |= exprListTableUsage(pMaskSet, p->x.pList);
319 }
danielk1977b3bce662005-01-29 08:32:43 +0000320 return mask;
321}
drh111a6a72008-12-21 03:51:16 +0000322static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
danielk1977b3bce662005-01-29 08:32:43 +0000323 int i;
324 Bitmask mask = 0;
325 if( pList ){
326 for(i=0; i<pList->nExpr; i++){
327 mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
drhdd579122002-04-02 01:58:57 +0000328 }
329 }
drh75897232000-05-29 14:26:00 +0000330 return mask;
331}
drh111a6a72008-12-21 03:51:16 +0000332static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
drha430ae82007-09-12 15:41:01 +0000333 Bitmask mask = 0;
334 while( pS ){
drha464c232011-09-16 19:04:03 +0000335 SrcList *pSrc = pS->pSrc;
drha430ae82007-09-12 15:41:01 +0000336 mask |= exprListTableUsage(pMaskSet, pS->pEList);
drhf5b11382005-09-17 13:07:13 +0000337 mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
338 mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
339 mask |= exprTableUsage(pMaskSet, pS->pWhere);
340 mask |= exprTableUsage(pMaskSet, pS->pHaving);
drha464c232011-09-16 19:04:03 +0000341 if( ALWAYS(pSrc!=0) ){
drh88501772011-09-16 17:43:06 +0000342 int i;
343 for(i=0; i<pSrc->nSrc; i++){
344 mask |= exprSelectTableUsage(pMaskSet, pSrc->a[i].pSelect);
345 mask |= exprTableUsage(pMaskSet, pSrc->a[i].pOn);
346 }
347 }
drha430ae82007-09-12 15:41:01 +0000348 pS = pS->pPrior;
drhf5b11382005-09-17 13:07:13 +0000349 }
350 return mask;
351}
drh75897232000-05-29 14:26:00 +0000352
353/*
drh487ab3c2001-11-08 00:45:21 +0000354** Return TRUE if the given operator is one of the operators that is
drh51669862004-12-18 18:40:26 +0000355** allowed for an indexable WHERE clause term. The allowed operators are
drh3b48e8c2013-06-12 20:18:16 +0000356** "=", "<", ">", "<=", ">=", "IN", and "IS NULL"
drh487ab3c2001-11-08 00:45:21 +0000357*/
358static int allowedOp(int op){
drhfe05af82005-07-21 03:14:59 +0000359 assert( TK_GT>TK_EQ && TK_GT<TK_GE );
360 assert( TK_LT>TK_EQ && TK_LT<TK_GE );
361 assert( TK_LE>TK_EQ && TK_LE<TK_GE );
362 assert( TK_GE==TK_EQ+4 );
drh50b39962006-10-28 00:28:09 +0000363 return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
drh487ab3c2001-11-08 00:45:21 +0000364}
365
366/*
drh902b9ee2008-12-05 17:17:07 +0000367** Swap two objects of type TYPE.
drh193bd772004-07-20 18:23:14 +0000368*/
369#define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
370
371/*
drh909626d2008-05-30 14:58:37 +0000372** Commute a comparison operator. Expressions of the form "X op Y"
drh0fcef5e2005-07-19 17:38:22 +0000373** are converted into "Y op X".
danielk1977eb5453d2007-07-30 14:40:48 +0000374**
mistachkin48864df2013-03-21 21:20:32 +0000375** If left/right precedence rules come into play when determining the
drh3b48e8c2013-06-12 20:18:16 +0000376** collating sequence, then COLLATE operators are adjusted to ensure
377** that the collating sequence does not change. For example:
378** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on
danielk1977eb5453d2007-07-30 14:40:48 +0000379** the left hand side of a comparison overrides any collation sequence
drhae80dde2012-12-06 21:16:43 +0000380** attached to the right. For the same reason the EP_Collate flag
danielk1977eb5453d2007-07-30 14:40:48 +0000381** is not commuted.
drh193bd772004-07-20 18:23:14 +0000382*/
drh7d10d5a2008-08-20 16:35:10 +0000383static void exprCommute(Parse *pParse, Expr *pExpr){
drhae80dde2012-12-06 21:16:43 +0000384 u16 expRight = (pExpr->pRight->flags & EP_Collate);
385 u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
drhfe05af82005-07-21 03:14:59 +0000386 assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
drhae80dde2012-12-06 21:16:43 +0000387 if( expRight==expLeft ){
388 /* Either X and Y both have COLLATE operator or neither do */
389 if( expRight ){
390 /* Both X and Y have COLLATE operators. Make sure X is always
391 ** used by clearing the EP_Collate flag from Y. */
392 pExpr->pRight->flags &= ~EP_Collate;
393 }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
394 /* Neither X nor Y have COLLATE operators, but X has a non-default
395 ** collating sequence. So add the EP_Collate marker on X to cause
396 ** it to be searched first. */
397 pExpr->pLeft->flags |= EP_Collate;
398 }
399 }
drh0fcef5e2005-07-19 17:38:22 +0000400 SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
401 if( pExpr->op>=TK_GT ){
402 assert( TK_LT==TK_GT+2 );
403 assert( TK_GE==TK_LE+2 );
404 assert( TK_GT>TK_EQ );
405 assert( TK_GT<TK_LE );
406 assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
407 pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
drh193bd772004-07-20 18:23:14 +0000408 }
drh193bd772004-07-20 18:23:14 +0000409}
410
411/*
drhfe05af82005-07-21 03:14:59 +0000412** Translate from TK_xx operator to WO_xx bitmask.
413*/
drhec1724e2008-12-09 01:32:03 +0000414static u16 operatorMask(int op){
415 u16 c;
drhfe05af82005-07-21 03:14:59 +0000416 assert( allowedOp(op) );
417 if( op==TK_IN ){
drh51147ba2005-07-23 22:59:55 +0000418 c = WO_IN;
drh50b39962006-10-28 00:28:09 +0000419 }else if( op==TK_ISNULL ){
420 c = WO_ISNULL;
drhfe05af82005-07-21 03:14:59 +0000421 }else{
drhec1724e2008-12-09 01:32:03 +0000422 assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
423 c = (u16)(WO_EQ<<(op-TK_EQ));
drhfe05af82005-07-21 03:14:59 +0000424 }
drh50b39962006-10-28 00:28:09 +0000425 assert( op!=TK_ISNULL || c==WO_ISNULL );
drh51147ba2005-07-23 22:59:55 +0000426 assert( op!=TK_IN || c==WO_IN );
427 assert( op!=TK_EQ || c==WO_EQ );
428 assert( op!=TK_LT || c==WO_LT );
429 assert( op!=TK_LE || c==WO_LE );
430 assert( op!=TK_GT || c==WO_GT );
431 assert( op!=TK_GE || c==WO_GE );
432 return c;
drhfe05af82005-07-21 03:14:59 +0000433}
434
435/*
drh1c8148f2013-05-04 20:25:23 +0000436** Advance to the next WhereTerm that matches according to the criteria
437** established when the pScan object was initialized by whereScanInit().
438** Return NULL if there are no more matching WhereTerms.
439*/
danb2cfc142013-07-05 11:10:54 +0000440static WhereTerm *whereScanNext(WhereScan *pScan){
drh1c8148f2013-05-04 20:25:23 +0000441 int iCur; /* The cursor on the LHS of the term */
442 int iColumn; /* The column on the LHS of the term. -1 for IPK */
443 Expr *pX; /* An expression being tested */
444 WhereClause *pWC; /* Shorthand for pScan->pWC */
445 WhereTerm *pTerm; /* The term being tested */
drh43b85ef2013-06-10 12:34:45 +0000446 int k = pScan->k; /* Where to start scanning */
drh1c8148f2013-05-04 20:25:23 +0000447
448 while( pScan->iEquiv<=pScan->nEquiv ){
449 iCur = pScan->aEquiv[pScan->iEquiv-2];
450 iColumn = pScan->aEquiv[pScan->iEquiv-1];
451 while( (pWC = pScan->pWC)!=0 ){
drh43b85ef2013-06-10 12:34:45 +0000452 for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
drhe1a086e2013-10-28 20:15:56 +0000453 if( pTerm->leftCursor==iCur
454 && pTerm->u.leftColumn==iColumn
455 && (pScan->iEquiv<=2 || !ExprHasProperty(pTerm->pExpr, EP_FromJoin))
456 ){
drh1c8148f2013-05-04 20:25:23 +0000457 if( (pTerm->eOperator & WO_EQUIV)!=0
458 && pScan->nEquiv<ArraySize(pScan->aEquiv)
459 ){
460 int j;
461 pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight);
462 assert( pX->op==TK_COLUMN );
463 for(j=0; j<pScan->nEquiv; j+=2){
464 if( pScan->aEquiv[j]==pX->iTable
465 && pScan->aEquiv[j+1]==pX->iColumn ){
466 break;
467 }
468 }
469 if( j==pScan->nEquiv ){
470 pScan->aEquiv[j] = pX->iTable;
471 pScan->aEquiv[j+1] = pX->iColumn;
472 pScan->nEquiv += 2;
473 }
474 }
475 if( (pTerm->eOperator & pScan->opMask)!=0 ){
476 /* Verify the affinity and collating sequence match */
477 if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
478 CollSeq *pColl;
drh70d18342013-06-06 19:16:33 +0000479 Parse *pParse = pWC->pWInfo->pParse;
drh1c8148f2013-05-04 20:25:23 +0000480 pX = pTerm->pExpr;
481 if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
482 continue;
483 }
484 assert(pX->pLeft);
drh70d18342013-06-06 19:16:33 +0000485 pColl = sqlite3BinaryCompareCollSeq(pParse,
drh1c8148f2013-05-04 20:25:23 +0000486 pX->pLeft, pX->pRight);
drh70d18342013-06-06 19:16:33 +0000487 if( pColl==0 ) pColl = pParse->db->pDfltColl;
drh1c8148f2013-05-04 20:25:23 +0000488 if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
489 continue;
490 }
491 }
drha184fb82013-05-08 04:22:59 +0000492 if( (pTerm->eOperator & WO_EQ)!=0
493 && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN
494 && pX->iTable==pScan->aEquiv[0]
495 && pX->iColumn==pScan->aEquiv[1]
496 ){
497 continue;
498 }
drh43b85ef2013-06-10 12:34:45 +0000499 pScan->k = k+1;
drh1c8148f2013-05-04 20:25:23 +0000500 return pTerm;
501 }
502 }
503 }
drhad01d892013-06-19 13:59:49 +0000504 pScan->pWC = pScan->pWC->pOuter;
drh43b85ef2013-06-10 12:34:45 +0000505 k = 0;
drh1c8148f2013-05-04 20:25:23 +0000506 }
507 pScan->pWC = pScan->pOrigWC;
drh43b85ef2013-06-10 12:34:45 +0000508 k = 0;
drh1c8148f2013-05-04 20:25:23 +0000509 pScan->iEquiv += 2;
510 }
drh1c8148f2013-05-04 20:25:23 +0000511 return 0;
512}
513
514/*
515** Initialize a WHERE clause scanner object. Return a pointer to the
516** first match. Return NULL if there are no matches.
517**
518** The scanner will be searching the WHERE clause pWC. It will look
519** for terms of the form "X <op> <expr>" where X is column iColumn of table
520** iCur. The <op> must be one of the operators described by opMask.
521**
drh3b48e8c2013-06-12 20:18:16 +0000522** If the search is for X and the WHERE clause contains terms of the
523** form X=Y then this routine might also return terms of the form
524** "Y <op> <expr>". The number of levels of transitivity is limited,
525** but is enough to handle most commonly occurring SQL statements.
526**
drh1c8148f2013-05-04 20:25:23 +0000527** If X is not the INTEGER PRIMARY KEY then X must be compatible with
528** index pIdx.
529*/
danb2cfc142013-07-05 11:10:54 +0000530static WhereTerm *whereScanInit(
drh1c8148f2013-05-04 20:25:23 +0000531 WhereScan *pScan, /* The WhereScan object being initialized */
532 WhereClause *pWC, /* The WHERE clause to be scanned */
533 int iCur, /* Cursor to scan for */
534 int iColumn, /* Column to scan for */
535 u32 opMask, /* Operator(s) to scan for */
536 Index *pIdx /* Must be compatible with this index */
537){
538 int j;
539
drhe9d935a2013-06-05 16:19:59 +0000540 /* memset(pScan, 0, sizeof(*pScan)); */
drh1c8148f2013-05-04 20:25:23 +0000541 pScan->pOrigWC = pWC;
542 pScan->pWC = pWC;
543 if( pIdx && iColumn>=0 ){
544 pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
545 for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
drhbbbdc832013-10-22 18:01:40 +0000546 if( NEVER(j>=pIdx->nKeyCol) ) return 0;
drh1c8148f2013-05-04 20:25:23 +0000547 }
548 pScan->zCollName = pIdx->azColl[j];
drhe9d935a2013-06-05 16:19:59 +0000549 }else{
550 pScan->idxaff = 0;
551 pScan->zCollName = 0;
drh1c8148f2013-05-04 20:25:23 +0000552 }
553 pScan->opMask = opMask;
drhe9d935a2013-06-05 16:19:59 +0000554 pScan->k = 0;
drh1c8148f2013-05-04 20:25:23 +0000555 pScan->aEquiv[0] = iCur;
556 pScan->aEquiv[1] = iColumn;
557 pScan->nEquiv = 2;
558 pScan->iEquiv = 2;
559 return whereScanNext(pScan);
560}
561
562/*
drhfe05af82005-07-21 03:14:59 +0000563** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
564** where X is a reference to the iColumn of table iCur and <op> is one of
565** the WO_xx operator codes specified by the op parameter.
566** Return a pointer to the term. Return 0 if not found.
drh58eb1c02013-01-17 00:08:42 +0000567**
568** The term returned might by Y=<expr> if there is another constraint in
569** the WHERE clause that specifies that X=Y. Any such constraints will be
570** identified by the WO_EQUIV bit in the pTerm->eOperator field. The
571** aEquiv[] array holds X and all its equivalents, with each SQL variable
572** taking up two slots in aEquiv[]. The first slot is for the cursor number
573** and the second is for the column number. There are 22 slots in aEquiv[]
574** so that means we can look for X plus up to 10 other equivalent values.
575** Hence a search for X will return <expr> if X=A1 and A1=A2 and A2=A3
576** and ... and A9=A10 and A10=<expr>.
577**
578** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
579** then try for the one with no dependencies on <expr> - in other words where
580** <expr> is a constant expression of some kind. Only return entries of
581** the form "X <op> Y" where Y is a column in another table if no terms of
drh459f63e2013-03-06 01:55:27 +0000582** the form "X <op> <const-expr>" exist. If no terms with a constant RHS
583** exist, try to return a term that does not use WO_EQUIV.
drhfe05af82005-07-21 03:14:59 +0000584*/
585static WhereTerm *findTerm(
586 WhereClause *pWC, /* The WHERE clause to be searched */
587 int iCur, /* Cursor number of LHS */
588 int iColumn, /* Column number of LHS */
589 Bitmask notReady, /* RHS must not overlap with this mask */
drhec1724e2008-12-09 01:32:03 +0000590 u32 op, /* Mask of WO_xx values describing operator */
drhfe05af82005-07-21 03:14:59 +0000591 Index *pIdx /* Must be compatible with this index, if not NULL */
592){
drh1c8148f2013-05-04 20:25:23 +0000593 WhereTerm *pResult = 0;
594 WhereTerm *p;
595 WhereScan scan;
drh7a5bcc02013-01-16 17:08:58 +0000596
drh1c8148f2013-05-04 20:25:23 +0000597 p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
598 while( p ){
599 if( (p->prereqRight & notReady)==0 ){
600 if( p->prereqRight==0 && (p->eOperator&WO_EQ)!=0 ){
601 return p;
drhfe05af82005-07-21 03:14:59 +0000602 }
drh1c8148f2013-05-04 20:25:23 +0000603 if( pResult==0 ) pResult = p;
drhfe05af82005-07-21 03:14:59 +0000604 }
drh1c8148f2013-05-04 20:25:23 +0000605 p = whereScanNext(&scan);
drhfe05af82005-07-21 03:14:59 +0000606 }
drh7a5bcc02013-01-16 17:08:58 +0000607 return pResult;
drhfe05af82005-07-21 03:14:59 +0000608}
609
drh6c30be82005-07-29 15:10:17 +0000610/* Forward reference */
drh7b4fc6a2007-02-06 13:26:32 +0000611static void exprAnalyze(SrcList*, WhereClause*, int);
drh6c30be82005-07-29 15:10:17 +0000612
613/*
614** Call exprAnalyze on all terms in a WHERE clause.
drh6c30be82005-07-29 15:10:17 +0000615*/
616static void exprAnalyzeAll(
617 SrcList *pTabList, /* the FROM clause */
drh6c30be82005-07-29 15:10:17 +0000618 WhereClause *pWC /* the WHERE clause to be analyzed */
619){
drh6c30be82005-07-29 15:10:17 +0000620 int i;
drh9eb20282005-08-24 03:52:18 +0000621 for(i=pWC->nTerm-1; i>=0; i--){
drh7b4fc6a2007-02-06 13:26:32 +0000622 exprAnalyze(pTabList, pWC, i);
drh6c30be82005-07-29 15:10:17 +0000623 }
624}
625
drhd2687b72005-08-12 22:56:09 +0000626#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
627/*
628** Check to see if the given expression is a LIKE or GLOB operator that
629** can be optimized using inequality constraints. Return TRUE if it is
630** so and false if not.
631**
632** In order for the operator to be optimizible, the RHS must be a string
633** literal that does not begin with a wildcard.
634*/
635static int isLikeOrGlob(
drh7d10d5a2008-08-20 16:35:10 +0000636 Parse *pParse, /* Parsing and code generating context */
drhd2687b72005-08-12 22:56:09 +0000637 Expr *pExpr, /* Test this expression */
dan937d0de2009-10-15 18:35:38 +0000638 Expr **ppPrefix, /* Pointer to TK_STRING expression with pattern prefix */
drh9f504ea2008-02-23 21:55:39 +0000639 int *pisComplete, /* True if the only wildcard is % in the last character */
640 int *pnoCase /* True if uppercase is equivalent to lowercase */
drhd2687b72005-08-12 22:56:09 +0000641){
dan937d0de2009-10-15 18:35:38 +0000642 const char *z = 0; /* String on RHS of LIKE operator */
drh5bd98ae2009-01-07 18:24:03 +0000643 Expr *pRight, *pLeft; /* Right and left size of LIKE operator */
644 ExprList *pList; /* List of operands to the LIKE operator */
645 int c; /* One character in z[] */
646 int cnt; /* Number of non-wildcard prefix characters */
647 char wc[3]; /* Wildcard characters */
drh5bd98ae2009-01-07 18:24:03 +0000648 sqlite3 *db = pParse->db; /* Database connection */
dan937d0de2009-10-15 18:35:38 +0000649 sqlite3_value *pVal = 0;
650 int op; /* Opcode of pRight */
drhd64fe2f2005-08-28 17:00:23 +0000651
drh9f504ea2008-02-23 21:55:39 +0000652 if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
drhd2687b72005-08-12 22:56:09 +0000653 return 0;
654 }
drh9f504ea2008-02-23 21:55:39 +0000655#ifdef SQLITE_EBCDIC
656 if( *pnoCase ) return 0;
657#endif
danielk19776ab3a2e2009-02-19 14:39:25 +0000658 pList = pExpr->x.pList;
drh55ef4d92005-08-14 01:20:37 +0000659 pLeft = pList->a[1].pExpr;
danc68939e2012-03-29 14:29:07 +0000660 if( pLeft->op!=TK_COLUMN
661 || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
662 || IsVirtual(pLeft->pTab)
663 ){
drhd91ca492009-10-22 20:50:36 +0000664 /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
665 ** be the name of an indexed column with TEXT affinity. */
drhd2687b72005-08-12 22:56:09 +0000666 return 0;
667 }
drhd91ca492009-10-22 20:50:36 +0000668 assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
dan937d0de2009-10-15 18:35:38 +0000669
670 pRight = pList->a[0].pExpr;
671 op = pRight->op;
672 if( op==TK_REGISTER ){
673 op = pRight->op2;
674 }
675 if( op==TK_VARIABLE ){
676 Vdbe *pReprepare = pParse->pReprepare;
drha7044002010-09-14 18:22:59 +0000677 int iCol = pRight->iColumn;
drhcf0fd4a2013-08-01 12:21:58 +0000678 pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_NONE);
dan937d0de2009-10-15 18:35:38 +0000679 if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
680 z = (char *)sqlite3_value_text(pVal);
681 }
drhf9b22ca2011-10-21 16:47:31 +0000682 sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
dan937d0de2009-10-15 18:35:38 +0000683 assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
684 }else if( op==TK_STRING ){
685 z = pRight->u.zToken;
686 }
687 if( z ){
shane85095702009-06-15 16:27:08 +0000688 cnt = 0;
drhb7916a72009-05-27 10:31:29 +0000689 while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
drh24fb6272009-05-01 21:13:36 +0000690 cnt++;
691 }
drh93ee23c2010-07-22 12:33:57 +0000692 if( cnt!=0 && 255!=(u8)z[cnt-1] ){
dan937d0de2009-10-15 18:35:38 +0000693 Expr *pPrefix;
drh93ee23c2010-07-22 12:33:57 +0000694 *pisComplete = c==wc[0] && z[cnt+1]==0;
dan937d0de2009-10-15 18:35:38 +0000695 pPrefix = sqlite3Expr(db, TK_STRING, z);
696 if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
697 *ppPrefix = pPrefix;
698 if( op==TK_VARIABLE ){
699 Vdbe *v = pParse->pVdbe;
drhf9b22ca2011-10-21 16:47:31 +0000700 sqlite3VdbeSetVarmask(v, pRight->iColumn);
dan937d0de2009-10-15 18:35:38 +0000701 if( *pisComplete && pRight->u.zToken[1] ){
702 /* If the rhs of the LIKE expression is a variable, and the current
703 ** value of the variable means there is no need to invoke the LIKE
704 ** function, then no OP_Variable will be added to the program.
705 ** This causes problems for the sqlite3_bind_parameter_name()
drhbec451f2009-10-17 13:13:02 +0000706 ** API. To workaround them, add a dummy OP_Variable here.
707 */
708 int r1 = sqlite3GetTempReg(pParse);
709 sqlite3ExprCodeTarget(pParse, pRight, r1);
dan937d0de2009-10-15 18:35:38 +0000710 sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
drhbec451f2009-10-17 13:13:02 +0000711 sqlite3ReleaseTempReg(pParse, r1);
dan937d0de2009-10-15 18:35:38 +0000712 }
713 }
714 }else{
715 z = 0;
shane85095702009-06-15 16:27:08 +0000716 }
drhf998b732007-11-26 13:36:00 +0000717 }
dan937d0de2009-10-15 18:35:38 +0000718
719 sqlite3ValueFree(pVal);
720 return (z!=0);
drhd2687b72005-08-12 22:56:09 +0000721}
722#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
723
drhedb193b2006-06-27 13:20:21 +0000724
725#ifndef SQLITE_OMIT_VIRTUALTABLE
drhfe05af82005-07-21 03:14:59 +0000726/*
drh7f375902006-06-13 17:38:59 +0000727** Check to see if the given expression is of the form
728**
729** column MATCH expr
730**
731** If it is then return TRUE. If not, return FALSE.
732*/
733static int isMatchOfColumn(
734 Expr *pExpr /* Test this expression */
735){
736 ExprList *pList;
737
738 if( pExpr->op!=TK_FUNCTION ){
739 return 0;
740 }
drh33e619f2009-05-28 01:00:55 +0000741 if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
drh7f375902006-06-13 17:38:59 +0000742 return 0;
743 }
danielk19776ab3a2e2009-02-19 14:39:25 +0000744 pList = pExpr->x.pList;
drh7f375902006-06-13 17:38:59 +0000745 if( pList->nExpr!=2 ){
746 return 0;
747 }
748 if( pList->a[1].pExpr->op != TK_COLUMN ){
749 return 0;
750 }
751 return 1;
752}
drhedb193b2006-06-27 13:20:21 +0000753#endif /* SQLITE_OMIT_VIRTUALTABLE */
drh7f375902006-06-13 17:38:59 +0000754
755/*
drh54a167d2005-11-26 14:08:07 +0000756** If the pBase expression originated in the ON or USING clause of
757** a join, then transfer the appropriate markings over to derived.
758*/
759static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
drhd41d39f2013-08-28 16:27:01 +0000760 if( pDerived ){
761 pDerived->flags |= pBase->flags & EP_FromJoin;
762 pDerived->iRightJoinTable = pBase->iRightJoinTable;
763 }
drh54a167d2005-11-26 14:08:07 +0000764}
765
drh3e355802007-02-23 23:13:33 +0000766#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
767/*
drh1a58fe02008-12-20 02:06:13 +0000768** Analyze a term that consists of two or more OR-connected
769** subterms. So in:
drh3e355802007-02-23 23:13:33 +0000770**
drh1a58fe02008-12-20 02:06:13 +0000771** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
772** ^^^^^^^^^^^^^^^^^^^^
drh3e355802007-02-23 23:13:33 +0000773**
drh1a58fe02008-12-20 02:06:13 +0000774** This routine analyzes terms such as the middle term in the above example.
775** A WhereOrTerm object is computed and attached to the term under
776** analysis, regardless of the outcome of the analysis. Hence:
drh3e355802007-02-23 23:13:33 +0000777**
drh1a58fe02008-12-20 02:06:13 +0000778** WhereTerm.wtFlags |= TERM_ORINFO
779** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object
drh3e355802007-02-23 23:13:33 +0000780**
drh1a58fe02008-12-20 02:06:13 +0000781** The term being analyzed must have two or more of OR-connected subterms.
danielk1977fdc40192008-12-29 18:33:32 +0000782** A single subterm might be a set of AND-connected sub-subterms.
drh1a58fe02008-12-20 02:06:13 +0000783** Examples of terms under analysis:
drh3e355802007-02-23 23:13:33 +0000784**
drh1a58fe02008-12-20 02:06:13 +0000785** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
786** (B) x=expr1 OR expr2=x OR x=expr3
787** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
788** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
789** (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 +0000790**
drh1a58fe02008-12-20 02:06:13 +0000791** CASE 1:
792**
drhc3e552f2013-02-08 16:04:19 +0000793** If all subterms are of the form T.C=expr for some single column of C and
drh1a58fe02008-12-20 02:06:13 +0000794** a single table T (as shown in example B above) then create a new virtual
795** term that is an equivalent IN expression. In other words, if the term
796** being analyzed is:
797**
798** x = expr1 OR expr2 = x OR x = expr3
799**
800** then create a new virtual term like this:
801**
802** x IN (expr1,expr2,expr3)
803**
804** CASE 2:
805**
806** If all subterms are indexable by a single table T, then set
807**
808** WhereTerm.eOperator = WO_OR
809** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T
810**
811** A subterm is "indexable" if it is of the form
812** "T.C <op> <expr>" where C is any column of table T and
813** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
814** A subterm is also indexable if it is an AND of two or more
815** subsubterms at least one of which is indexable. Indexable AND
816** subterms have their eOperator set to WO_AND and they have
817** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
818**
819** From another point of view, "indexable" means that the subterm could
820** potentially be used with an index if an appropriate index exists.
821** This analysis does not consider whether or not the index exists; that
drh4a6fc352013-08-07 01:18:38 +0000822** is decided elsewhere. This analysis only looks at whether subterms
823** appropriate for indexing exist.
drh1a58fe02008-12-20 02:06:13 +0000824**
drh4a6fc352013-08-07 01:18:38 +0000825** All examples A through E above satisfy case 2. But if a term
drh1a58fe02008-12-20 02:06:13 +0000826** also statisfies case 1 (such as B) we know that the optimizer will
827** always prefer case 1, so in that case we pretend that case 2 is not
828** satisfied.
829**
830** It might be the case that multiple tables are indexable. For example,
831** (E) above is indexable on tables P, Q, and R.
832**
833** Terms that satisfy case 2 are candidates for lookup by using
834** separate indices to find rowids for each subterm and composing
835** the union of all rowids using a RowSet object. This is similar
836** to "bitmap indices" in other database engines.
837**
838** OTHERWISE:
839**
840** If neither case 1 nor case 2 apply, then leave the eOperator set to
841** zero. This term is not useful for search.
drh3e355802007-02-23 23:13:33 +0000842*/
drh1a58fe02008-12-20 02:06:13 +0000843static void exprAnalyzeOrTerm(
844 SrcList *pSrc, /* the FROM clause */
845 WhereClause *pWC, /* the complete WHERE clause */
846 int idxTerm /* Index of the OR-term to be analyzed */
847){
drh70d18342013-06-06 19:16:33 +0000848 WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
849 Parse *pParse = pWInfo->pParse; /* Parser context */
drh1a58fe02008-12-20 02:06:13 +0000850 sqlite3 *db = pParse->db; /* Database connection */
851 WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */
852 Expr *pExpr = pTerm->pExpr; /* The expression of the term */
drh1a58fe02008-12-20 02:06:13 +0000853 int i; /* Loop counters */
854 WhereClause *pOrWc; /* Breakup of pTerm into subterms */
855 WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */
856 WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */
857 Bitmask chngToIN; /* Tables that might satisfy case 1 */
858 Bitmask indexable; /* Tables that are indexable, satisfying case 2 */
drh3e355802007-02-23 23:13:33 +0000859
drh1a58fe02008-12-20 02:06:13 +0000860 /*
861 ** Break the OR clause into its separate subterms. The subterms are
862 ** stored in a WhereClause structure containing within the WhereOrInfo
863 ** object that is attached to the original OR clause term.
864 */
865 assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
866 assert( pExpr->op==TK_OR );
drh954701a2008-12-29 23:45:07 +0000867 pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
drh1a58fe02008-12-20 02:06:13 +0000868 if( pOrInfo==0 ) return;
869 pTerm->wtFlags |= TERM_ORINFO;
870 pOrWc = &pOrInfo->wc;
drh70d18342013-06-06 19:16:33 +0000871 whereClauseInit(pOrWc, pWInfo);
drh1a58fe02008-12-20 02:06:13 +0000872 whereSplit(pOrWc, pExpr, TK_OR);
873 exprAnalyzeAll(pSrc, pOrWc);
874 if( db->mallocFailed ) return;
875 assert( pOrWc->nTerm>=2 );
876
877 /*
878 ** Compute the set of tables that might satisfy cases 1 or 2.
879 */
danielk1977e672c8e2009-05-22 15:43:26 +0000880 indexable = ~(Bitmask)0;
drhc3e552f2013-02-08 16:04:19 +0000881 chngToIN = ~(Bitmask)0;
drh1a58fe02008-12-20 02:06:13 +0000882 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
883 if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
drh29435252008-12-28 18:35:08 +0000884 WhereAndInfo *pAndInfo;
drh29435252008-12-28 18:35:08 +0000885 assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
drh1a58fe02008-12-20 02:06:13 +0000886 chngToIN = 0;
drh29435252008-12-28 18:35:08 +0000887 pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
888 if( pAndInfo ){
889 WhereClause *pAndWC;
890 WhereTerm *pAndTerm;
891 int j;
892 Bitmask b = 0;
893 pOrTerm->u.pAndInfo = pAndInfo;
894 pOrTerm->wtFlags |= TERM_ANDINFO;
895 pOrTerm->eOperator = WO_AND;
896 pAndWC = &pAndInfo->wc;
drh70d18342013-06-06 19:16:33 +0000897 whereClauseInit(pAndWC, pWC->pWInfo);
drh29435252008-12-28 18:35:08 +0000898 whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
899 exprAnalyzeAll(pSrc, pAndWC);
drh8871ef52011-10-07 13:33:10 +0000900 pAndWC->pOuter = pWC;
drh7c2fbde2009-01-07 20:58:57 +0000901 testcase( db->mallocFailed );
drh96c7a7d2009-01-10 15:34:12 +0000902 if( !db->mallocFailed ){
903 for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
904 assert( pAndTerm->pExpr );
905 if( allowedOp(pAndTerm->pExpr->op) ){
drh70d18342013-06-06 19:16:33 +0000906 b |= getMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
drh96c7a7d2009-01-10 15:34:12 +0000907 }
drh29435252008-12-28 18:35:08 +0000908 }
909 }
910 indexable &= b;
911 }
drh1a58fe02008-12-20 02:06:13 +0000912 }else if( pOrTerm->wtFlags & TERM_COPIED ){
913 /* Skip this term for now. We revisit it when we process the
914 ** corresponding TERM_VIRTUAL term */
915 }else{
916 Bitmask b;
drh70d18342013-06-06 19:16:33 +0000917 b = getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
drh1a58fe02008-12-20 02:06:13 +0000918 if( pOrTerm->wtFlags & TERM_VIRTUAL ){
919 WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
drh70d18342013-06-06 19:16:33 +0000920 b |= getMask(&pWInfo->sMaskSet, pOther->leftCursor);
drh1a58fe02008-12-20 02:06:13 +0000921 }
922 indexable &= b;
drh7a5bcc02013-01-16 17:08:58 +0000923 if( (pOrTerm->eOperator & WO_EQ)==0 ){
drh1a58fe02008-12-20 02:06:13 +0000924 chngToIN = 0;
925 }else{
926 chngToIN &= b;
927 }
928 }
drh3e355802007-02-23 23:13:33 +0000929 }
drh1a58fe02008-12-20 02:06:13 +0000930
931 /*
932 ** Record the set of tables that satisfy case 2. The set might be
drh111a6a72008-12-21 03:51:16 +0000933 ** empty.
drh1a58fe02008-12-20 02:06:13 +0000934 */
935 pOrInfo->indexable = indexable;
drh111a6a72008-12-21 03:51:16 +0000936 pTerm->eOperator = indexable==0 ? 0 : WO_OR;
drh1a58fe02008-12-20 02:06:13 +0000937
938 /*
939 ** chngToIN holds a set of tables that *might* satisfy case 1. But
940 ** we have to do some additional checking to see if case 1 really
941 ** is satisfied.
drh4e8be3b2009-06-08 17:11:08 +0000942 **
943 ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means
944 ** that there is no possibility of transforming the OR clause into an
945 ** IN operator because one or more terms in the OR clause contain
946 ** something other than == on a column in the single table. The 1-bit
947 ** case means that every term of the OR clause is of the form
948 ** "table.column=expr" for some single table. The one bit that is set
949 ** will correspond to the common table. We still need to check to make
950 ** sure the same column is used on all terms. The 2-bit case is when
951 ** the all terms are of the form "table1.column=table2.column". It
952 ** might be possible to form an IN operator with either table1.column
953 ** or table2.column as the LHS if either is common to every term of
954 ** the OR clause.
955 **
956 ** Note that terms of the form "table.column1=table.column2" (the
957 ** same table on both sizes of the ==) cannot be optimized.
drh1a58fe02008-12-20 02:06:13 +0000958 */
959 if( chngToIN ){
960 int okToChngToIN = 0; /* True if the conversion to IN is valid */
961 int iColumn = -1; /* Column index on lhs of IN operator */
shane63207ab2009-02-04 01:49:30 +0000962 int iCursor = -1; /* Table cursor common to all terms */
drh1a58fe02008-12-20 02:06:13 +0000963 int j = 0; /* Loop counter */
964
965 /* Search for a table and column that appears on one side or the
966 ** other of the == operator in every subterm. That table and column
967 ** will be recorded in iCursor and iColumn. There might not be any
968 ** such table and column. Set okToChngToIN if an appropriate table
969 ** and column is found but leave okToChngToIN false if not found.
970 */
971 for(j=0; j<2 && !okToChngToIN; j++){
972 pOrTerm = pOrWc->a;
973 for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
drh7a5bcc02013-01-16 17:08:58 +0000974 assert( pOrTerm->eOperator & WO_EQ );
drh1a58fe02008-12-20 02:06:13 +0000975 pOrTerm->wtFlags &= ~TERM_OR_OK;
drh4e8be3b2009-06-08 17:11:08 +0000976 if( pOrTerm->leftCursor==iCursor ){
977 /* This is the 2-bit case and we are on the second iteration and
978 ** current term is from the first iteration. So skip this term. */
979 assert( j==1 );
980 continue;
981 }
drh70d18342013-06-06 19:16:33 +0000982 if( (chngToIN & getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor))==0 ){
drh4e8be3b2009-06-08 17:11:08 +0000983 /* This term must be of the form t1.a==t2.b where t2 is in the
984 ** chngToIN set but t1 is not. This term will be either preceeded
985 ** or follwed by an inverted copy (t2.b==t1.a). Skip this term
986 ** and use its inversion. */
987 testcase( pOrTerm->wtFlags & TERM_COPIED );
988 testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
989 assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
990 continue;
991 }
drh1a58fe02008-12-20 02:06:13 +0000992 iColumn = pOrTerm->u.leftColumn;
993 iCursor = pOrTerm->leftCursor;
994 break;
995 }
996 if( i<0 ){
drh4e8be3b2009-06-08 17:11:08 +0000997 /* No candidate table+column was found. This can only occur
998 ** on the second iteration */
drh1a58fe02008-12-20 02:06:13 +0000999 assert( j==1 );
drh7a5bcc02013-01-16 17:08:58 +00001000 assert( IsPowerOfTwo(chngToIN) );
drh70d18342013-06-06 19:16:33 +00001001 assert( chngToIN==getMask(&pWInfo->sMaskSet, iCursor) );
drh1a58fe02008-12-20 02:06:13 +00001002 break;
1003 }
drh4e8be3b2009-06-08 17:11:08 +00001004 testcase( j==1 );
1005
1006 /* We have found a candidate table and column. Check to see if that
1007 ** table and column is common to every term in the OR clause */
drh1a58fe02008-12-20 02:06:13 +00001008 okToChngToIN = 1;
1009 for(; i>=0 && okToChngToIN; i--, pOrTerm++){
drh7a5bcc02013-01-16 17:08:58 +00001010 assert( pOrTerm->eOperator & WO_EQ );
drh1a58fe02008-12-20 02:06:13 +00001011 if( pOrTerm->leftCursor!=iCursor ){
1012 pOrTerm->wtFlags &= ~TERM_OR_OK;
1013 }else if( pOrTerm->u.leftColumn!=iColumn ){
1014 okToChngToIN = 0;
1015 }else{
1016 int affLeft, affRight;
1017 /* If the right-hand side is also a column, then the affinities
1018 ** of both right and left sides must be such that no type
1019 ** conversions are required on the right. (Ticket #2249)
1020 */
1021 affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
1022 affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
1023 if( affRight!=0 && affRight!=affLeft ){
1024 okToChngToIN = 0;
1025 }else{
1026 pOrTerm->wtFlags |= TERM_OR_OK;
1027 }
1028 }
1029 }
1030 }
1031
1032 /* At this point, okToChngToIN is true if original pTerm satisfies
1033 ** case 1. In that case, construct a new virtual term that is
1034 ** pTerm converted into an IN operator.
1035 */
1036 if( okToChngToIN ){
1037 Expr *pDup; /* A transient duplicate expression */
1038 ExprList *pList = 0; /* The RHS of the IN operator */
1039 Expr *pLeft = 0; /* The LHS of the IN operator */
1040 Expr *pNew; /* The complete IN operator */
1041
1042 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
1043 if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
drh7a5bcc02013-01-16 17:08:58 +00001044 assert( pOrTerm->eOperator & WO_EQ );
drh1a58fe02008-12-20 02:06:13 +00001045 assert( pOrTerm->leftCursor==iCursor );
1046 assert( pOrTerm->u.leftColumn==iColumn );
danielk19776ab3a2e2009-02-19 14:39:25 +00001047 pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
drh70d18342013-06-06 19:16:33 +00001048 pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
drh1a58fe02008-12-20 02:06:13 +00001049 pLeft = pOrTerm->pExpr->pLeft;
1050 }
1051 assert( pLeft!=0 );
danielk19776ab3a2e2009-02-19 14:39:25 +00001052 pDup = sqlite3ExprDup(db, pLeft, 0);
drhb7916a72009-05-27 10:31:29 +00001053 pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
drh1a58fe02008-12-20 02:06:13 +00001054 if( pNew ){
1055 int idxNew;
1056 transferJoinMarkings(pNew, pExpr);
danielk19776ab3a2e2009-02-19 14:39:25 +00001057 assert( !ExprHasProperty(pNew, EP_xIsSelect) );
1058 pNew->x.pList = pList;
drh1a58fe02008-12-20 02:06:13 +00001059 idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
1060 testcase( idxNew==0 );
1061 exprAnalyze(pSrc, pWC, idxNew);
1062 pTerm = &pWC->a[idxTerm];
1063 pWC->a[idxNew].iParent = idxTerm;
1064 pTerm->nChild = 1;
1065 }else{
1066 sqlite3ExprListDelete(db, pList);
1067 }
drh534230c2011-01-22 00:10:45 +00001068 pTerm->eOperator = WO_NOOP; /* case 1 trumps case 2 */
drh1a58fe02008-12-20 02:06:13 +00001069 }
drh3e355802007-02-23 23:13:33 +00001070 }
drh3e355802007-02-23 23:13:33 +00001071}
1072#endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
drh54a167d2005-11-26 14:08:07 +00001073
drh7a5bcc02013-01-16 17:08:58 +00001074/*
drh0aa74ed2005-07-16 13:33:20 +00001075** The input to this routine is an WhereTerm structure with only the
drh51147ba2005-07-23 22:59:55 +00001076** "pExpr" field filled in. The job of this routine is to analyze the
drh0aa74ed2005-07-16 13:33:20 +00001077** subexpression and populate all the other fields of the WhereTerm
drh75897232000-05-29 14:26:00 +00001078** structure.
drh51147ba2005-07-23 22:59:55 +00001079**
1080** If the expression is of the form "<expr> <op> X" it gets commuted
drh1a58fe02008-12-20 02:06:13 +00001081** to the standard form of "X <op> <expr>".
1082**
1083** If the expression is of the form "X <op> Y" where both X and Y are
1084** columns, then the original expression is unchanged and a new virtual
1085** term of the form "Y <op> X" is added to the WHERE clause and
1086** analyzed separately. The original term is marked with TERM_COPIED
1087** and the new term is marked with TERM_DYNAMIC (because it's pExpr
1088** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
1089** is a commuted copy of a prior term.) The original term has nChild=1
1090** and the copy has idxParent set to the index of the original term.
drh75897232000-05-29 14:26:00 +00001091*/
drh0fcef5e2005-07-19 17:38:22 +00001092static void exprAnalyze(
1093 SrcList *pSrc, /* the FROM clause */
drh9eb20282005-08-24 03:52:18 +00001094 WhereClause *pWC, /* the WHERE clause */
1095 int idxTerm /* Index of the term to be analyzed */
drh0fcef5e2005-07-19 17:38:22 +00001096){
drh70d18342013-06-06 19:16:33 +00001097 WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
drh1a58fe02008-12-20 02:06:13 +00001098 WhereTerm *pTerm; /* The term to be analyzed */
drh111a6a72008-12-21 03:51:16 +00001099 WhereMaskSet *pMaskSet; /* Set of table index masks */
drh1a58fe02008-12-20 02:06:13 +00001100 Expr *pExpr; /* The expression to be analyzed */
1101 Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */
1102 Bitmask prereqAll; /* Prerequesites of pExpr */
drh5e767c52010-02-25 04:15:47 +00001103 Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */
drh1d452e12009-11-01 19:26:59 +00001104 Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */
1105 int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */
1106 int noCase = 0; /* LIKE/GLOB distinguishes case */
drh1a58fe02008-12-20 02:06:13 +00001107 int op; /* Top-level operator. pExpr->op */
drh70d18342013-06-06 19:16:33 +00001108 Parse *pParse = pWInfo->pParse; /* Parsing context */
drh1a58fe02008-12-20 02:06:13 +00001109 sqlite3 *db = pParse->db; /* Database connection */
drh0fcef5e2005-07-19 17:38:22 +00001110
drhf998b732007-11-26 13:36:00 +00001111 if( db->mallocFailed ){
1112 return;
1113 }
1114 pTerm = &pWC->a[idxTerm];
drh70d18342013-06-06 19:16:33 +00001115 pMaskSet = &pWInfo->sMaskSet;
drh7ee751d2012-12-19 15:53:51 +00001116 pExpr = pTerm->pExpr;
1117 assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
drh0fcef5e2005-07-19 17:38:22 +00001118 prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
drh50b39962006-10-28 00:28:09 +00001119 op = pExpr->op;
1120 if( op==TK_IN ){
drhf5b11382005-09-17 13:07:13 +00001121 assert( pExpr->pRight==0 );
danielk19776ab3a2e2009-02-19 14:39:25 +00001122 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
1123 pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
1124 }else{
1125 pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
1126 }
drh50b39962006-10-28 00:28:09 +00001127 }else if( op==TK_ISNULL ){
1128 pTerm->prereqRight = 0;
drhf5b11382005-09-17 13:07:13 +00001129 }else{
1130 pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
1131 }
drh22d6a532005-09-19 21:05:48 +00001132 prereqAll = exprTableUsage(pMaskSet, pExpr);
1133 if( ExprHasProperty(pExpr, EP_FromJoin) ){
drh42165be2008-03-26 14:56:34 +00001134 Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
1135 prereqAll |= x;
drhdafc0ce2008-04-17 19:14:02 +00001136 extraRight = x-1; /* ON clause terms may not be used with an index
1137 ** on left table of a LEFT JOIN. Ticket #3015 */
drh22d6a532005-09-19 21:05:48 +00001138 }
1139 pTerm->prereqAll = prereqAll;
drh0fcef5e2005-07-19 17:38:22 +00001140 pTerm->leftCursor = -1;
drh45b1ee42005-08-02 17:48:22 +00001141 pTerm->iParent = -1;
drhb52076c2006-01-23 13:22:09 +00001142 pTerm->eOperator = 0;
drh738fc792013-01-17 15:05:17 +00001143 if( allowedOp(op) ){
drh7a66da12012-12-07 20:31:11 +00001144 Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
1145 Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
drh738fc792013-01-17 15:05:17 +00001146 u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
drh0fcef5e2005-07-19 17:38:22 +00001147 if( pLeft->op==TK_COLUMN ){
1148 pTerm->leftCursor = pLeft->iTable;
drh700a2262008-12-17 19:22:15 +00001149 pTerm->u.leftColumn = pLeft->iColumn;
drh738fc792013-01-17 15:05:17 +00001150 pTerm->eOperator = operatorMask(op) & opMask;
drh75897232000-05-29 14:26:00 +00001151 }
drh0fcef5e2005-07-19 17:38:22 +00001152 if( pRight && pRight->op==TK_COLUMN ){
1153 WhereTerm *pNew;
1154 Expr *pDup;
drh7a5bcc02013-01-16 17:08:58 +00001155 u16 eExtraOp = 0; /* Extra bits for pNew->eOperator */
drh0fcef5e2005-07-19 17:38:22 +00001156 if( pTerm->leftCursor>=0 ){
drh9eb20282005-08-24 03:52:18 +00001157 int idxNew;
danielk19776ab3a2e2009-02-19 14:39:25 +00001158 pDup = sqlite3ExprDup(db, pExpr, 0);
drh17435752007-08-16 04:30:38 +00001159 if( db->mallocFailed ){
drh633e6d52008-07-28 19:34:53 +00001160 sqlite3ExprDelete(db, pDup);
drh28f45912006-10-18 23:26:38 +00001161 return;
1162 }
drh9eb20282005-08-24 03:52:18 +00001163 idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
1164 if( idxNew==0 ) return;
1165 pNew = &pWC->a[idxNew];
1166 pNew->iParent = idxTerm;
1167 pTerm = &pWC->a[idxTerm];
drh45b1ee42005-08-02 17:48:22 +00001168 pTerm->nChild = 1;
drh165be382008-12-05 02:36:33 +00001169 pTerm->wtFlags |= TERM_COPIED;
drheb5bc922013-01-17 16:43:33 +00001170 if( pExpr->op==TK_EQ
1171 && !ExprHasProperty(pExpr, EP_FromJoin)
1172 && OptimizationEnabled(db, SQLITE_Transitive)
1173 ){
drh7a5bcc02013-01-16 17:08:58 +00001174 pTerm->eOperator |= WO_EQUIV;
1175 eExtraOp = WO_EQUIV;
1176 }
drh0fcef5e2005-07-19 17:38:22 +00001177 }else{
1178 pDup = pExpr;
1179 pNew = pTerm;
1180 }
drh7d10d5a2008-08-20 16:35:10 +00001181 exprCommute(pParse, pDup);
drhfb76f5a2012-12-08 14:16:47 +00001182 pLeft = sqlite3ExprSkipCollate(pDup->pLeft);
drh0fcef5e2005-07-19 17:38:22 +00001183 pNew->leftCursor = pLeft->iTable;
drh700a2262008-12-17 19:22:15 +00001184 pNew->u.leftColumn = pLeft->iColumn;
drh5e767c52010-02-25 04:15:47 +00001185 testcase( (prereqLeft | extraRight) != prereqLeft );
1186 pNew->prereqRight = prereqLeft | extraRight;
drh0fcef5e2005-07-19 17:38:22 +00001187 pNew->prereqAll = prereqAll;
drh738fc792013-01-17 15:05:17 +00001188 pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
drh75897232000-05-29 14:26:00 +00001189 }
1190 }
drhed378002005-07-28 23:12:08 +00001191
drhd2687b72005-08-12 22:56:09 +00001192#ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
drhed378002005-07-28 23:12:08 +00001193 /* If a term is the BETWEEN operator, create two new virtual terms
drh1a58fe02008-12-20 02:06:13 +00001194 ** that define the range that the BETWEEN implements. For example:
1195 **
1196 ** a BETWEEN b AND c
1197 **
1198 ** is converted into:
1199 **
1200 ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
1201 **
1202 ** The two new terms are added onto the end of the WhereClause object.
1203 ** The new terms are "dynamic" and are children of the original BETWEEN
1204 ** term. That means that if the BETWEEN term is coded, the children are
1205 ** skipped. Or, if the children are satisfied by an index, the original
1206 ** BETWEEN term is skipped.
drhed378002005-07-28 23:12:08 +00001207 */
drh29435252008-12-28 18:35:08 +00001208 else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
danielk19776ab3a2e2009-02-19 14:39:25 +00001209 ExprList *pList = pExpr->x.pList;
drhed378002005-07-28 23:12:08 +00001210 int i;
1211 static const u8 ops[] = {TK_GE, TK_LE};
1212 assert( pList!=0 );
1213 assert( pList->nExpr==2 );
1214 for(i=0; i<2; i++){
1215 Expr *pNewExpr;
drh9eb20282005-08-24 03:52:18 +00001216 int idxNew;
drhb7916a72009-05-27 10:31:29 +00001217 pNewExpr = sqlite3PExpr(pParse, ops[i],
1218 sqlite3ExprDup(db, pExpr->pLeft, 0),
danielk19776ab3a2e2009-02-19 14:39:25 +00001219 sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
drhd41d39f2013-08-28 16:27:01 +00001220 transferJoinMarkings(pNewExpr, pExpr);
drh9eb20282005-08-24 03:52:18 +00001221 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
drh6a1e0712008-12-05 15:24:15 +00001222 testcase( idxNew==0 );
drh7b4fc6a2007-02-06 13:26:32 +00001223 exprAnalyze(pSrc, pWC, idxNew);
drh9eb20282005-08-24 03:52:18 +00001224 pTerm = &pWC->a[idxTerm];
1225 pWC->a[idxNew].iParent = idxTerm;
drhed378002005-07-28 23:12:08 +00001226 }
drh45b1ee42005-08-02 17:48:22 +00001227 pTerm->nChild = 2;
drhed378002005-07-28 23:12:08 +00001228 }
drhd2687b72005-08-12 22:56:09 +00001229#endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
drhed378002005-07-28 23:12:08 +00001230
danielk19771576cd92006-01-14 08:02:28 +00001231#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
drh1a58fe02008-12-20 02:06:13 +00001232 /* Analyze a term that is composed of two or more subterms connected by
1233 ** an OR operator.
drh6c30be82005-07-29 15:10:17 +00001234 */
1235 else if( pExpr->op==TK_OR ){
drh29435252008-12-28 18:35:08 +00001236 assert( pWC->op==TK_AND );
drh1a58fe02008-12-20 02:06:13 +00001237 exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
danielk1977f51d1bd2009-07-31 06:14:51 +00001238 pTerm = &pWC->a[idxTerm];
drh6c30be82005-07-29 15:10:17 +00001239 }
drhd2687b72005-08-12 22:56:09 +00001240#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
1241
1242#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
1243 /* Add constraints to reduce the search space on a LIKE or GLOB
1244 ** operator.
drh9f504ea2008-02-23 21:55:39 +00001245 **
1246 ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
1247 **
1248 ** x>='abc' AND x<'abd' AND x LIKE 'abc%'
1249 **
1250 ** The last character of the prefix "abc" is incremented to form the
shane7bc71e52008-05-28 18:01:44 +00001251 ** termination condition "abd".
drhd2687b72005-08-12 22:56:09 +00001252 */
dan937d0de2009-10-15 18:35:38 +00001253 if( pWC->op==TK_AND
1254 && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
1255 ){
drh1d452e12009-11-01 19:26:59 +00001256 Expr *pLeft; /* LHS of LIKE/GLOB operator */
1257 Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */
1258 Expr *pNewExpr1;
1259 Expr *pNewExpr2;
1260 int idxNew1;
1261 int idxNew2;
drhae80dde2012-12-06 21:16:43 +00001262 Token sCollSeqName; /* Name of collating sequence */
drh9eb20282005-08-24 03:52:18 +00001263
danielk19776ab3a2e2009-02-19 14:39:25 +00001264 pLeft = pExpr->x.pList->a[1].pExpr;
danielk19776ab3a2e2009-02-19 14:39:25 +00001265 pStr2 = sqlite3ExprDup(db, pStr1, 0);
drhf998b732007-11-26 13:36:00 +00001266 if( !db->mallocFailed ){
drh254993e2009-06-08 19:44:36 +00001267 u8 c, *pC; /* Last character before the first wildcard */
dan937d0de2009-10-15 18:35:38 +00001268 pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
drh9f504ea2008-02-23 21:55:39 +00001269 c = *pC;
drh02a50b72008-05-26 18:33:40 +00001270 if( noCase ){
drh254993e2009-06-08 19:44:36 +00001271 /* The point is to increment the last character before the first
1272 ** wildcard. But if we increment '@', that will push it into the
1273 ** alphabetic range where case conversions will mess up the
1274 ** inequality. To avoid this, make sure to also run the full
1275 ** LIKE on all candidate expressions by clearing the isComplete flag
1276 */
drh39759742013-08-02 23:40:45 +00001277 if( c=='A'-1 ) isComplete = 0;
drh02a50b72008-05-26 18:33:40 +00001278 c = sqlite3UpperToLower[c];
1279 }
drh9f504ea2008-02-23 21:55:39 +00001280 *pC = c + 1;
drhd2687b72005-08-12 22:56:09 +00001281 }
drhae80dde2012-12-06 21:16:43 +00001282 sCollSeqName.z = noCase ? "NOCASE" : "BINARY";
1283 sCollSeqName.n = 6;
1284 pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
drh8342e492010-07-22 17:49:52 +00001285 pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
drh0a8a4062012-12-07 18:38:16 +00001286 sqlite3ExprAddCollateToken(pParse,pNewExpr1,&sCollSeqName),
drhae80dde2012-12-06 21:16:43 +00001287 pStr1, 0);
drhd41d39f2013-08-28 16:27:01 +00001288 transferJoinMarkings(pNewExpr1, pExpr);
drh9eb20282005-08-24 03:52:18 +00001289 idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
drh6a1e0712008-12-05 15:24:15 +00001290 testcase( idxNew1==0 );
drh7b4fc6a2007-02-06 13:26:32 +00001291 exprAnalyze(pSrc, pWC, idxNew1);
drhae80dde2012-12-06 21:16:43 +00001292 pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
drh8342e492010-07-22 17:49:52 +00001293 pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
drh0a8a4062012-12-07 18:38:16 +00001294 sqlite3ExprAddCollateToken(pParse,pNewExpr2,&sCollSeqName),
drhae80dde2012-12-06 21:16:43 +00001295 pStr2, 0);
drhd41d39f2013-08-28 16:27:01 +00001296 transferJoinMarkings(pNewExpr2, pExpr);
drh9eb20282005-08-24 03:52:18 +00001297 idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
drh6a1e0712008-12-05 15:24:15 +00001298 testcase( idxNew2==0 );
drh7b4fc6a2007-02-06 13:26:32 +00001299 exprAnalyze(pSrc, pWC, idxNew2);
drh9eb20282005-08-24 03:52:18 +00001300 pTerm = &pWC->a[idxTerm];
drhd2687b72005-08-12 22:56:09 +00001301 if( isComplete ){
drh9eb20282005-08-24 03:52:18 +00001302 pWC->a[idxNew1].iParent = idxTerm;
1303 pWC->a[idxNew2].iParent = idxTerm;
drhd2687b72005-08-12 22:56:09 +00001304 pTerm->nChild = 2;
1305 }
1306 }
1307#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
drh7f375902006-06-13 17:38:59 +00001308
1309#ifndef SQLITE_OMIT_VIRTUALTABLE
1310 /* Add a WO_MATCH auxiliary term to the constraint set if the
1311 ** current expression is of the form: column MATCH expr.
1312 ** This information is used by the xBestIndex methods of
1313 ** virtual tables. The native query optimizer does not attempt
1314 ** to do anything with MATCH functions.
1315 */
1316 if( isMatchOfColumn(pExpr) ){
1317 int idxNew;
1318 Expr *pRight, *pLeft;
1319 WhereTerm *pNewTerm;
1320 Bitmask prereqColumn, prereqExpr;
1321
danielk19776ab3a2e2009-02-19 14:39:25 +00001322 pRight = pExpr->x.pList->a[0].pExpr;
1323 pLeft = pExpr->x.pList->a[1].pExpr;
drh7f375902006-06-13 17:38:59 +00001324 prereqExpr = exprTableUsage(pMaskSet, pRight);
1325 prereqColumn = exprTableUsage(pMaskSet, pLeft);
1326 if( (prereqExpr & prereqColumn)==0 ){
drh1a90e092006-06-14 22:07:10 +00001327 Expr *pNewExpr;
drhb7916a72009-05-27 10:31:29 +00001328 pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
1329 0, sqlite3ExprDup(db, pRight, 0), 0);
drh1a90e092006-06-14 22:07:10 +00001330 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
drh6a1e0712008-12-05 15:24:15 +00001331 testcase( idxNew==0 );
drh7f375902006-06-13 17:38:59 +00001332 pNewTerm = &pWC->a[idxNew];
1333 pNewTerm->prereqRight = prereqExpr;
1334 pNewTerm->leftCursor = pLeft->iTable;
drh700a2262008-12-17 19:22:15 +00001335 pNewTerm->u.leftColumn = pLeft->iColumn;
drh7f375902006-06-13 17:38:59 +00001336 pNewTerm->eOperator = WO_MATCH;
1337 pNewTerm->iParent = idxTerm;
drhd2ca60d2006-06-27 02:36:58 +00001338 pTerm = &pWC->a[idxTerm];
drh7f375902006-06-13 17:38:59 +00001339 pTerm->nChild = 1;
drh165be382008-12-05 02:36:33 +00001340 pTerm->wtFlags |= TERM_COPIED;
drh7f375902006-06-13 17:38:59 +00001341 pNewTerm->prereqAll = pTerm->prereqAll;
1342 }
1343 }
1344#endif /* SQLITE_OMIT_VIRTUALTABLE */
drhdafc0ce2008-04-17 19:14:02 +00001345
drh1435a9a2013-08-27 23:15:44 +00001346#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drhd3ed7342011-09-21 00:09:41 +00001347 /* When sqlite_stat3 histogram data is available an operator of the
drh534230c2011-01-22 00:10:45 +00001348 ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
1349 ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a
1350 ** virtual term of that form.
1351 **
1352 ** Note that the virtual term must be tagged with TERM_VNULL. This
1353 ** TERM_VNULL tag will suppress the not-null check at the beginning
1354 ** of the loop. Without the TERM_VNULL flag, the not-null check at
1355 ** the start of the loop will prevent any results from being returned.
1356 */
drhea6dc442011-04-08 21:35:26 +00001357 if( pExpr->op==TK_NOTNULL
1358 && pExpr->pLeft->op==TK_COLUMN
1359 && pExpr->pLeft->iColumn>=0
drh40aa9362013-06-28 17:29:25 +00001360 && OptimizationEnabled(db, SQLITE_Stat3)
drhea6dc442011-04-08 21:35:26 +00001361 ){
drh534230c2011-01-22 00:10:45 +00001362 Expr *pNewExpr;
1363 Expr *pLeft = pExpr->pLeft;
1364 int idxNew;
1365 WhereTerm *pNewTerm;
1366
1367 pNewExpr = sqlite3PExpr(pParse, TK_GT,
1368 sqlite3ExprDup(db, pLeft, 0),
1369 sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
1370
1371 idxNew = whereClauseInsert(pWC, pNewExpr,
1372 TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
drhda91e712011-02-11 06:59:02 +00001373 if( idxNew ){
1374 pNewTerm = &pWC->a[idxNew];
1375 pNewTerm->prereqRight = 0;
1376 pNewTerm->leftCursor = pLeft->iTable;
1377 pNewTerm->u.leftColumn = pLeft->iColumn;
1378 pNewTerm->eOperator = WO_GT;
1379 pNewTerm->iParent = idxTerm;
1380 pTerm = &pWC->a[idxTerm];
1381 pTerm->nChild = 1;
1382 pTerm->wtFlags |= TERM_COPIED;
1383 pNewTerm->prereqAll = pTerm->prereqAll;
1384 }
drh534230c2011-01-22 00:10:45 +00001385 }
drh1435a9a2013-08-27 23:15:44 +00001386#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
drh534230c2011-01-22 00:10:45 +00001387
drhdafc0ce2008-04-17 19:14:02 +00001388 /* Prevent ON clause terms of a LEFT JOIN from being used to drive
1389 ** an index for tables to the left of the join.
1390 */
1391 pTerm->prereqRight |= extraRight;
drh75897232000-05-29 14:26:00 +00001392}
1393
drh7b4fc6a2007-02-06 13:26:32 +00001394/*
drh3b48e8c2013-06-12 20:18:16 +00001395** This function searches pList for a entry that matches the iCol-th column
1396** of index pIdx.
dan6f343962011-07-01 18:26:40 +00001397**
1398** If such an expression is found, its index in pList->a[] is returned. If
1399** no expression is found, -1 is returned.
1400*/
1401static int findIndexCol(
1402 Parse *pParse, /* Parse context */
1403 ExprList *pList, /* Expression list to search */
1404 int iBase, /* Cursor for table associated with pIdx */
1405 Index *pIdx, /* Index to match column of */
1406 int iCol /* Column of index to match */
1407){
1408 int i;
1409 const char *zColl = pIdx->azColl[iCol];
1410
1411 for(i=0; i<pList->nExpr; i++){
drh580c8c12012-12-08 03:34:04 +00001412 Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
drhf1d3e322011-07-09 13:00:41 +00001413 if( p->op==TK_COLUMN
1414 && p->iColumn==pIdx->aiColumn[iCol]
1415 && p->iTable==iBase
1416 ){
drh580c8c12012-12-08 03:34:04 +00001417 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
drhf1d3e322011-07-09 13:00:41 +00001418 if( ALWAYS(pColl) && 0==sqlite3StrICmp(pColl->zName, zColl) ){
dan6f343962011-07-01 18:26:40 +00001419 return i;
1420 }
1421 }
1422 }
1423
1424 return -1;
1425}
1426
1427/*
dan6f343962011-07-01 18:26:40 +00001428** Return true if the DISTINCT expression-list passed as the third argument
drh4f402f22013-06-11 18:59:38 +00001429** is redundant.
1430**
drh3b48e8c2013-06-12 20:18:16 +00001431** A DISTINCT list is redundant if the database contains some subset of
drh4f402f22013-06-11 18:59:38 +00001432** columns that are unique and non-null.
dan6f343962011-07-01 18:26:40 +00001433*/
1434static int isDistinctRedundant(
drh4f402f22013-06-11 18:59:38 +00001435 Parse *pParse, /* Parsing context */
1436 SrcList *pTabList, /* The FROM clause */
1437 WhereClause *pWC, /* The WHERE clause */
1438 ExprList *pDistinct /* The result set that needs to be DISTINCT */
dan6f343962011-07-01 18:26:40 +00001439){
1440 Table *pTab;
1441 Index *pIdx;
1442 int i;
1443 int iBase;
1444
1445 /* If there is more than one table or sub-select in the FROM clause of
1446 ** this query, then it will not be possible to show that the DISTINCT
1447 ** clause is redundant. */
1448 if( pTabList->nSrc!=1 ) return 0;
1449 iBase = pTabList->a[0].iCursor;
1450 pTab = pTabList->a[0].pTab;
1451
dan94e08d92011-07-02 06:44:05 +00001452 /* If any of the expressions is an IPK column on table iBase, then return
1453 ** true. Note: The (p->iTable==iBase) part of this test may be false if the
1454 ** current SELECT is a correlated sub-query.
1455 */
dan6f343962011-07-01 18:26:40 +00001456 for(i=0; i<pDistinct->nExpr; i++){
drh580c8c12012-12-08 03:34:04 +00001457 Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
dan94e08d92011-07-02 06:44:05 +00001458 if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
dan6f343962011-07-01 18:26:40 +00001459 }
1460
1461 /* Loop through all indices on the table, checking each to see if it makes
1462 ** the DISTINCT qualifier redundant. It does so if:
1463 **
1464 ** 1. The index is itself UNIQUE, and
1465 **
1466 ** 2. All of the columns in the index are either part of the pDistinct
1467 ** list, or else the WHERE clause contains a term of the form "col=X",
1468 ** where X is a constant value. The collation sequences of the
1469 ** comparison and select-list expressions must match those of the index.
dan6a36f432012-04-20 16:59:24 +00001470 **
1471 ** 3. All of those index columns for which the WHERE clause does not
1472 ** contain a "col=X" term are subject to a NOT NULL constraint.
dan6f343962011-07-01 18:26:40 +00001473 */
1474 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1475 if( pIdx->onError==OE_None ) continue;
drhbbbdc832013-10-22 18:01:40 +00001476 for(i=0; i<pIdx->nKeyCol; i++){
1477 i16 iCol = pIdx->aiColumn[i];
dan6a36f432012-04-20 16:59:24 +00001478 if( 0==findTerm(pWC, iBase, iCol, ~(Bitmask)0, WO_EQ, pIdx) ){
1479 int iIdxCol = findIndexCol(pParse, pDistinct, iBase, pIdx, i);
drhbbbdc832013-10-22 18:01:40 +00001480 if( iIdxCol<0 || pTab->aCol[iCol].notNull==0 ){
dan6a36f432012-04-20 16:59:24 +00001481 break;
1482 }
dan6f343962011-07-01 18:26:40 +00001483 }
1484 }
drhbbbdc832013-10-22 18:01:40 +00001485 if( i==pIdx->nKeyCol ){
dan6f343962011-07-01 18:26:40 +00001486 /* This index implies that the DISTINCT qualifier is redundant. */
1487 return 1;
1488 }
1489 }
1490
1491 return 0;
1492}
drh0fcef5e2005-07-19 17:38:22 +00001493
drh8636e9c2013-06-11 01:50:08 +00001494
drh75897232000-05-29 14:26:00 +00001495/*
drh3b48e8c2013-06-12 20:18:16 +00001496** Estimate the logarithm of the input value to base 2.
drh28c4cf42005-07-27 20:41:43 +00001497*/
drhbf539c42013-10-05 18:16:02 +00001498static LogEst estLog(LogEst N){
1499 LogEst x = sqlite3LogEst(N);
drh4fe425a2013-06-12 17:08:06 +00001500 return x>33 ? x - 33 : 0;
drh28c4cf42005-07-27 20:41:43 +00001501}
1502
drh6d209d82006-06-27 01:54:26 +00001503/*
1504** Two routines for printing the content of an sqlite3_index_info
1505** structure. Used for testing and debugging only. If neither
1506** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
1507** are no-ops.
1508*/
drhd15cb172013-05-21 19:23:10 +00001509#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
drh6d209d82006-06-27 01:54:26 +00001510static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
1511 int i;
mlcreech3a00f902008-03-04 17:45:01 +00001512 if( !sqlite3WhereTrace ) return;
drh6d209d82006-06-27 01:54:26 +00001513 for(i=0; i<p->nConstraint; i++){
1514 sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
1515 i,
1516 p->aConstraint[i].iColumn,
1517 p->aConstraint[i].iTermOffset,
1518 p->aConstraint[i].op,
1519 p->aConstraint[i].usable);
1520 }
1521 for(i=0; i<p->nOrderBy; i++){
1522 sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n",
1523 i,
1524 p->aOrderBy[i].iColumn,
1525 p->aOrderBy[i].desc);
1526 }
1527}
1528static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
1529 int i;
mlcreech3a00f902008-03-04 17:45:01 +00001530 if( !sqlite3WhereTrace ) return;
drh6d209d82006-06-27 01:54:26 +00001531 for(i=0; i<p->nConstraint; i++){
1532 sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n",
1533 i,
1534 p->aConstraintUsage[i].argvIndex,
1535 p->aConstraintUsage[i].omit);
1536 }
1537 sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum);
1538 sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr);
1539 sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed);
1540 sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost);
dana9f58152013-11-11 19:01:33 +00001541 sqlite3DebugPrintf(" estimatedRows=%lld\n", p->estimatedRows);
drh6d209d82006-06-27 01:54:26 +00001542}
1543#else
1544#define TRACE_IDX_INPUTS(A)
1545#define TRACE_IDX_OUTPUTS(A)
1546#endif
1547
drhc6339082010-04-07 16:54:58 +00001548#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
drh8b307fb2010-04-06 15:57:05 +00001549/*
drh4139c992010-04-07 14:59:45 +00001550** Return TRUE if the WHERE clause term pTerm is of a form where it
1551** could be used with an index to access pSrc, assuming an appropriate
1552** index existed.
1553*/
1554static int termCanDriveIndex(
1555 WhereTerm *pTerm, /* WHERE clause term to check */
1556 struct SrcList_item *pSrc, /* Table we are trying to access */
1557 Bitmask notReady /* Tables in outer loops of the join */
1558){
1559 char aff;
1560 if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
drh7a5bcc02013-01-16 17:08:58 +00001561 if( (pTerm->eOperator & WO_EQ)==0 ) return 0;
drh4139c992010-04-07 14:59:45 +00001562 if( (pTerm->prereqRight & notReady)!=0 ) return 0;
drh23f98da2013-05-21 15:52:07 +00001563 if( pTerm->u.leftColumn<0 ) return 0;
drh4139c992010-04-07 14:59:45 +00001564 aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
1565 if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
1566 return 1;
1567}
drhc6339082010-04-07 16:54:58 +00001568#endif
drh4139c992010-04-07 14:59:45 +00001569
drhc6339082010-04-07 16:54:58 +00001570
1571#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
drh8b307fb2010-04-06 15:57:05 +00001572/*
drhc6339082010-04-07 16:54:58 +00001573** Generate code to construct the Index object for an automatic index
1574** and to set up the WhereLevel object pLevel so that the code generator
1575** makes use of the automatic index.
drh8b307fb2010-04-06 15:57:05 +00001576*/
drhc6339082010-04-07 16:54:58 +00001577static void constructAutomaticIndex(
drh8b307fb2010-04-06 15:57:05 +00001578 Parse *pParse, /* The parsing context */
1579 WhereClause *pWC, /* The WHERE clause */
1580 struct SrcList_item *pSrc, /* The FROM clause term to get the next index */
1581 Bitmask notReady, /* Mask of cursors that are not available */
1582 WhereLevel *pLevel /* Write new index here */
1583){
drhbbbdc832013-10-22 18:01:40 +00001584 int nKeyCol; /* Number of columns in the constructed index */
drh8b307fb2010-04-06 15:57:05 +00001585 WhereTerm *pTerm; /* A single term of the WHERE clause */
1586 WhereTerm *pWCEnd; /* End of pWC->a[] */
drh8b307fb2010-04-06 15:57:05 +00001587 Index *pIdx; /* Object describing the transient index */
1588 Vdbe *v; /* Prepared statement under construction */
drh8b307fb2010-04-06 15:57:05 +00001589 int addrInit; /* Address of the initialization bypass jump */
1590 Table *pTable; /* The table being indexed */
drh8b307fb2010-04-06 15:57:05 +00001591 int addrTop; /* Top of the index fill loop */
1592 int regRecord; /* Register holding an index record */
1593 int n; /* Column counter */
drh4139c992010-04-07 14:59:45 +00001594 int i; /* Loop counter */
1595 int mxBitCol; /* Maximum column in pSrc->colUsed */
drh424aab82010-04-06 18:28:20 +00001596 CollSeq *pColl; /* Collating sequence to on a column */
drh7ba39a92013-05-30 17:43:19 +00001597 WhereLoop *pLoop; /* The Loop object */
drh77e57df2013-10-22 14:28:02 +00001598 char *zNotUsed; /* Extra space on the end of pIdx */
drh4139c992010-04-07 14:59:45 +00001599 Bitmask idxCols; /* Bitmap of columns used for indexing */
1600 Bitmask extraCols; /* Bitmap of additional columns */
drh8d56e202013-06-28 23:55:45 +00001601 u8 sentWarning = 0; /* True if a warnning has been issued */
drh8b307fb2010-04-06 15:57:05 +00001602
1603 /* Generate code to skip over the creation and initialization of the
1604 ** transient index on 2nd and subsequent iterations of the loop. */
1605 v = pParse->pVdbe;
1606 assert( v!=0 );
dan1d8cb212011-12-09 13:24:16 +00001607 addrInit = sqlite3CodeOnce(pParse);
drh8b307fb2010-04-06 15:57:05 +00001608
drh4139c992010-04-07 14:59:45 +00001609 /* Count the number of columns that will be added to the index
1610 ** and used to match WHERE clause constraints */
drhbbbdc832013-10-22 18:01:40 +00001611 nKeyCol = 0;
drh424aab82010-04-06 18:28:20 +00001612 pTable = pSrc->pTab;
drh8b307fb2010-04-06 15:57:05 +00001613 pWCEnd = &pWC->a[pWC->nTerm];
drh7ba39a92013-05-30 17:43:19 +00001614 pLoop = pLevel->pWLoop;
drh4139c992010-04-07 14:59:45 +00001615 idxCols = 0;
drh81186b42013-06-18 01:52:41 +00001616 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
drh4139c992010-04-07 14:59:45 +00001617 if( termCanDriveIndex(pTerm, pSrc, notReady) ){
1618 int iCol = pTerm->u.leftColumn;
drh7699d1c2013-06-04 12:42:29 +00001619 Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
drh52ff8ea2010-04-08 14:15:56 +00001620 testcase( iCol==BMS );
1621 testcase( iCol==BMS-1 );
drh8d56e202013-06-28 23:55:45 +00001622 if( !sentWarning ){
1623 sqlite3_log(SQLITE_WARNING_AUTOINDEX,
1624 "automatic index on %s(%s)", pTable->zName,
1625 pTable->aCol[iCol].zName);
1626 sentWarning = 1;
1627 }
drh0013e722010-04-08 00:40:15 +00001628 if( (idxCols & cMask)==0 ){
drhbbbdc832013-10-22 18:01:40 +00001629 if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ) return;
1630 pLoop->aLTerm[nKeyCol++] = pTerm;
drh0013e722010-04-08 00:40:15 +00001631 idxCols |= cMask;
1632 }
drh8b307fb2010-04-06 15:57:05 +00001633 }
1634 }
drhbbbdc832013-10-22 18:01:40 +00001635 assert( nKeyCol>0 );
1636 pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol;
drh53b52f72013-05-31 11:57:39 +00001637 pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
drh986b3872013-06-28 21:12:20 +00001638 | WHERE_AUTO_INDEX;
drh4139c992010-04-07 14:59:45 +00001639
1640 /* Count the number of additional columns needed to create a
1641 ** covering index. A "covering index" is an index that contains all
1642 ** columns that are needed by the query. With a covering index, the
1643 ** original table never needs to be accessed. Automatic indices must
1644 ** be a covering index because the index will not be updated if the
1645 ** original table changes and the index and table cannot both be used
1646 ** if they go out of sync.
1647 */
drh7699d1c2013-06-04 12:42:29 +00001648 extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
drh4139c992010-04-07 14:59:45 +00001649 mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol;
drh52ff8ea2010-04-08 14:15:56 +00001650 testcase( pTable->nCol==BMS-1 );
1651 testcase( pTable->nCol==BMS-2 );
drh4139c992010-04-07 14:59:45 +00001652 for(i=0; i<mxBitCol; i++){
drhbbbdc832013-10-22 18:01:40 +00001653 if( extraCols & MASKBIT(i) ) nKeyCol++;
drh4139c992010-04-07 14:59:45 +00001654 }
drh7699d1c2013-06-04 12:42:29 +00001655 if( pSrc->colUsed & MASKBIT(BMS-1) ){
drhbbbdc832013-10-22 18:01:40 +00001656 nKeyCol += pTable->nCol - BMS + 1;
drh4139c992010-04-07 14:59:45 +00001657 }
drh7ba39a92013-05-30 17:43:19 +00001658 pLoop->wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY;
drh8b307fb2010-04-06 15:57:05 +00001659
1660 /* Construct the Index object to describe this index */
drhbbbdc832013-10-22 18:01:40 +00001661 pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed);
drh8b307fb2010-04-06 15:57:05 +00001662 if( pIdx==0 ) return;
drh7ba39a92013-05-30 17:43:19 +00001663 pLoop->u.btree.pIndex = pIdx;
drh8b307fb2010-04-06 15:57:05 +00001664 pIdx->zName = "auto-index";
drh424aab82010-04-06 18:28:20 +00001665 pIdx->pTable = pTable;
drh8b307fb2010-04-06 15:57:05 +00001666 n = 0;
drh0013e722010-04-08 00:40:15 +00001667 idxCols = 0;
drh8b307fb2010-04-06 15:57:05 +00001668 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
drh4139c992010-04-07 14:59:45 +00001669 if( termCanDriveIndex(pTerm, pSrc, notReady) ){
drh0013e722010-04-08 00:40:15 +00001670 int iCol = pTerm->u.leftColumn;
drh7699d1c2013-06-04 12:42:29 +00001671 Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
drh7963b0e2013-06-17 21:37:40 +00001672 testcase( iCol==BMS-1 );
1673 testcase( iCol==BMS );
drh0013e722010-04-08 00:40:15 +00001674 if( (idxCols & cMask)==0 ){
1675 Expr *pX = pTerm->pExpr;
1676 idxCols |= cMask;
1677 pIdx->aiColumn[n] = pTerm->u.leftColumn;
1678 pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
drh6f2e6c02011-02-17 13:33:15 +00001679 pIdx->azColl[n] = ALWAYS(pColl) ? pColl->zName : "BINARY";
drh0013e722010-04-08 00:40:15 +00001680 n++;
1681 }
drh8b307fb2010-04-06 15:57:05 +00001682 }
1683 }
drh7ba39a92013-05-30 17:43:19 +00001684 assert( (u32)n==pLoop->u.btree.nEq );
drh4139c992010-04-07 14:59:45 +00001685
drhc6339082010-04-07 16:54:58 +00001686 /* Add additional columns needed to make the automatic index into
1687 ** a covering index */
drh4139c992010-04-07 14:59:45 +00001688 for(i=0; i<mxBitCol; i++){
drh7699d1c2013-06-04 12:42:29 +00001689 if( extraCols & MASKBIT(i) ){
drh4139c992010-04-07 14:59:45 +00001690 pIdx->aiColumn[n] = i;
1691 pIdx->azColl[n] = "BINARY";
1692 n++;
1693 }
1694 }
drh7699d1c2013-06-04 12:42:29 +00001695 if( pSrc->colUsed & MASKBIT(BMS-1) ){
drh4139c992010-04-07 14:59:45 +00001696 for(i=BMS-1; i<pTable->nCol; i++){
1697 pIdx->aiColumn[n] = i;
1698 pIdx->azColl[n] = "BINARY";
1699 n++;
1700 }
1701 }
drhbbbdc832013-10-22 18:01:40 +00001702 assert( n==nKeyCol );
drh44156282013-10-23 22:23:03 +00001703 pIdx->aiColumn[n] = -1;
1704 pIdx->azColl[n] = "BINARY";
drh8b307fb2010-04-06 15:57:05 +00001705
drhc6339082010-04-07 16:54:58 +00001706 /* Create the automatic index */
drh8b307fb2010-04-06 15:57:05 +00001707 assert( pLevel->iIdxCur>=0 );
drha1f41242013-05-31 20:00:58 +00001708 pLevel->iIdxCur = pParse->nTab++;
drh2ec2fb22013-11-06 19:59:23 +00001709 sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1);
1710 sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
drha21a64d2010-04-06 22:33:55 +00001711 VdbeComment((v, "for %s", pTable->zName));
drh8b307fb2010-04-06 15:57:05 +00001712
drhc6339082010-04-07 16:54:58 +00001713 /* Fill the automatic index with content */
drh8b307fb2010-04-06 15:57:05 +00001714 addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur);
1715 regRecord = sqlite3GetTempReg(pParse);
drh9eade082013-10-24 14:16:10 +00001716 sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0);
drh8b307fb2010-04-06 15:57:05 +00001717 sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
1718 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
1719 sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1);
drha21a64d2010-04-06 22:33:55 +00001720 sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
drh8b307fb2010-04-06 15:57:05 +00001721 sqlite3VdbeJumpHere(v, addrTop);
1722 sqlite3ReleaseTempReg(pParse, regRecord);
1723
1724 /* Jump here when skipping the initialization */
1725 sqlite3VdbeJumpHere(v, addrInit);
1726}
drhc6339082010-04-07 16:54:58 +00001727#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
drh8b307fb2010-04-06 15:57:05 +00001728
drh9eff6162006-06-12 21:59:13 +00001729#ifndef SQLITE_OMIT_VIRTUALTABLE
1730/*
danielk19771d461462009-04-21 09:02:45 +00001731** Allocate and populate an sqlite3_index_info structure. It is the
1732** responsibility of the caller to eventually release the structure
1733** by passing the pointer returned by this function to sqlite3_free().
1734*/
drh5346e952013-05-08 14:14:26 +00001735static sqlite3_index_info *allocateIndexInfo(
1736 Parse *pParse,
1737 WhereClause *pWC,
1738 struct SrcList_item *pSrc,
1739 ExprList *pOrderBy
1740){
danielk19771d461462009-04-21 09:02:45 +00001741 int i, j;
1742 int nTerm;
1743 struct sqlite3_index_constraint *pIdxCons;
1744 struct sqlite3_index_orderby *pIdxOrderBy;
1745 struct sqlite3_index_constraint_usage *pUsage;
1746 WhereTerm *pTerm;
1747 int nOrderBy;
1748 sqlite3_index_info *pIdxInfo;
1749
danielk19771d461462009-04-21 09:02:45 +00001750 /* Count the number of possible WHERE clause constraints referring
1751 ** to this virtual table */
1752 for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
1753 if( pTerm->leftCursor != pSrc->iCursor ) continue;
drh7a5bcc02013-01-16 17:08:58 +00001754 assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
1755 testcase( pTerm->eOperator & WO_IN );
1756 testcase( pTerm->eOperator & WO_ISNULL );
drh281bbe22012-10-16 23:17:14 +00001757 if( pTerm->eOperator & (WO_ISNULL) ) continue;
drhb4256992011-08-02 01:57:39 +00001758 if( pTerm->wtFlags & TERM_VNULL ) continue;
danielk19771d461462009-04-21 09:02:45 +00001759 nTerm++;
1760 }
1761
1762 /* If the ORDER BY clause contains only columns in the current
1763 ** virtual table then allocate space for the aOrderBy part of
1764 ** the sqlite3_index_info structure.
1765 */
1766 nOrderBy = 0;
1767 if( pOrderBy ){
drh56f1b992012-09-25 14:29:39 +00001768 int n = pOrderBy->nExpr;
1769 for(i=0; i<n; i++){
danielk19771d461462009-04-21 09:02:45 +00001770 Expr *pExpr = pOrderBy->a[i].pExpr;
1771 if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
1772 }
drh56f1b992012-09-25 14:29:39 +00001773 if( i==n){
1774 nOrderBy = n;
danielk19771d461462009-04-21 09:02:45 +00001775 }
1776 }
1777
1778 /* Allocate the sqlite3_index_info structure
1779 */
1780 pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
1781 + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
1782 + sizeof(*pIdxOrderBy)*nOrderBy );
1783 if( pIdxInfo==0 ){
1784 sqlite3ErrorMsg(pParse, "out of memory");
danielk19771d461462009-04-21 09:02:45 +00001785 return 0;
1786 }
1787
1788 /* Initialize the structure. The sqlite3_index_info structure contains
1789 ** many fields that are declared "const" to prevent xBestIndex from
1790 ** changing them. We have to do some funky casting in order to
1791 ** initialize those fields.
1792 */
1793 pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
1794 pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
1795 pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
1796 *(int*)&pIdxInfo->nConstraint = nTerm;
1797 *(int*)&pIdxInfo->nOrderBy = nOrderBy;
1798 *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
1799 *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
1800 *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
1801 pUsage;
1802
1803 for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
drh281bbe22012-10-16 23:17:14 +00001804 u8 op;
danielk19771d461462009-04-21 09:02:45 +00001805 if( pTerm->leftCursor != pSrc->iCursor ) continue;
drh7a5bcc02013-01-16 17:08:58 +00001806 assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
1807 testcase( pTerm->eOperator & WO_IN );
1808 testcase( pTerm->eOperator & WO_ISNULL );
drh281bbe22012-10-16 23:17:14 +00001809 if( pTerm->eOperator & (WO_ISNULL) ) continue;
drhb4256992011-08-02 01:57:39 +00001810 if( pTerm->wtFlags & TERM_VNULL ) continue;
danielk19771d461462009-04-21 09:02:45 +00001811 pIdxCons[j].iColumn = pTerm->u.leftColumn;
1812 pIdxCons[j].iTermOffset = i;
drh7a5bcc02013-01-16 17:08:58 +00001813 op = (u8)pTerm->eOperator & WO_ALL;
drh281bbe22012-10-16 23:17:14 +00001814 if( op==WO_IN ) op = WO_EQ;
1815 pIdxCons[j].op = op;
danielk19771d461462009-04-21 09:02:45 +00001816 /* The direct assignment in the previous line is possible only because
1817 ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The
1818 ** following asserts verify this fact. */
1819 assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
1820 assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
1821 assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
1822 assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
1823 assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
1824 assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
drh281bbe22012-10-16 23:17:14 +00001825 assert( pTerm->eOperator & (WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
danielk19771d461462009-04-21 09:02:45 +00001826 j++;
1827 }
1828 for(i=0; i<nOrderBy; i++){
1829 Expr *pExpr = pOrderBy->a[i].pExpr;
1830 pIdxOrderBy[i].iColumn = pExpr->iColumn;
1831 pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
1832 }
1833
1834 return pIdxInfo;
1835}
1836
1837/*
1838** The table object reference passed as the second argument to this function
1839** must represent a virtual table. This function invokes the xBestIndex()
drh3b48e8c2013-06-12 20:18:16 +00001840** method of the virtual table with the sqlite3_index_info object that
1841** comes in as the 3rd argument to this function.
danielk19771d461462009-04-21 09:02:45 +00001842**
1843** If an error occurs, pParse is populated with an error message and a
1844** non-zero value is returned. Otherwise, 0 is returned and the output
1845** part of the sqlite3_index_info structure is left populated.
1846**
1847** Whether or not an error is returned, it is the responsibility of the
1848** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
1849** that this is required.
1850*/
1851static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
danielk1977595a5232009-07-24 17:58:53 +00001852 sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
danielk19771d461462009-04-21 09:02:45 +00001853 int i;
1854 int rc;
1855
danielk19771d461462009-04-21 09:02:45 +00001856 TRACE_IDX_INPUTS(p);
1857 rc = pVtab->pModule->xBestIndex(pVtab, p);
1858 TRACE_IDX_OUTPUTS(p);
danielk19771d461462009-04-21 09:02:45 +00001859
1860 if( rc!=SQLITE_OK ){
1861 if( rc==SQLITE_NOMEM ){
1862 pParse->db->mallocFailed = 1;
1863 }else if( !pVtab->zErrMsg ){
1864 sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
1865 }else{
1866 sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
1867 }
1868 }
drhb9755982010-07-24 16:34:37 +00001869 sqlite3_free(pVtab->zErrMsg);
danielk19771d461462009-04-21 09:02:45 +00001870 pVtab->zErrMsg = 0;
1871
1872 for(i=0; i<p->nConstraint; i++){
1873 if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
1874 sqlite3ErrorMsg(pParse,
1875 "table %s: xBestIndex returned an invalid plan", pTab->zName);
1876 }
1877 }
1878
1879 return pParse->nErr;
1880}
drh7ba39a92013-05-30 17:43:19 +00001881#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
danielk19771d461462009-04-21 09:02:45 +00001882
1883
drh1435a9a2013-08-27 23:15:44 +00001884#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drh28c4cf42005-07-27 20:41:43 +00001885/*
drhfaacf172011-08-12 01:51:45 +00001886** Estimate the location of a particular key among all keys in an
1887** index. Store the results in aStat as follows:
drhe847d322011-01-20 02:56:37 +00001888**
drhfaacf172011-08-12 01:51:45 +00001889** aStat[0] Est. number of rows less than pVal
1890** aStat[1] Est. number of rows equal to pVal
dan02fa4692009-08-17 17:06:58 +00001891**
drhfaacf172011-08-12 01:51:45 +00001892** Return SQLITE_OK on success.
dan02fa4692009-08-17 17:06:58 +00001893*/
danb3c02e22013-08-08 19:38:40 +00001894static void whereKeyStats(
dan02fa4692009-08-17 17:06:58 +00001895 Parse *pParse, /* Database connection */
1896 Index *pIdx, /* Index to consider domain of */
dan7a419232013-08-06 20:01:43 +00001897 UnpackedRecord *pRec, /* Vector of values to consider */
drhfaacf172011-08-12 01:51:45 +00001898 int roundUp, /* Round up if true. Round down if false */
1899 tRowcnt *aStat /* OUT: stats written here */
dan02fa4692009-08-17 17:06:58 +00001900){
danf52bb8d2013-08-03 20:24:58 +00001901 IndexSample *aSample = pIdx->aSample;
drhfbc38de2013-09-03 19:26:22 +00001902 int iCol; /* Index of required stats in anEq[] etc. */
dan84c309b2013-08-08 16:17:12 +00001903 int iMin = 0; /* Smallest sample not yet tested */
1904 int i = pIdx->nSample; /* Smallest sample larger than or equal to pRec */
1905 int iTest; /* Next sample to test */
1906 int res; /* Result of comparison operation */
dan02fa4692009-08-17 17:06:58 +00001907
drh4f991892013-10-11 15:05:05 +00001908#ifndef SQLITE_DEBUG
1909 UNUSED_PARAMETER( pParse );
1910#endif
drhfbc38de2013-09-03 19:26:22 +00001911 assert( pRec!=0 || pParse->db->mallocFailed );
1912 if( pRec==0 ) return;
1913 iCol = pRec->nField - 1;
drh5c624862011-09-22 18:46:34 +00001914 assert( pIdx->nSample>0 );
dan8ad169a2013-08-12 20:14:04 +00001915 assert( pRec->nField>0 && iCol<pIdx->nSampleCol );
dan84c309b2013-08-08 16:17:12 +00001916 do{
1917 iTest = (iMin+i)/2;
1918 res = sqlite3VdbeRecordCompare(aSample[iTest].n, aSample[iTest].p, pRec);
1919 if( res<0 ){
1920 iMin = iTest+1;
1921 }else{
1922 i = iTest;
dan02fa4692009-08-17 17:06:58 +00001923 }
dan84c309b2013-08-08 16:17:12 +00001924 }while( res && iMin<i );
drh51147ba2005-07-23 22:59:55 +00001925
dan84c309b2013-08-08 16:17:12 +00001926#ifdef SQLITE_DEBUG
1927 /* The following assert statements check that the binary search code
1928 ** above found the right answer. This block serves no purpose other
1929 ** than to invoke the asserts. */
1930 if( res==0 ){
1931 /* If (res==0) is true, then sample $i must be equal to pRec */
1932 assert( i<pIdx->nSample );
drh0e1f0022013-08-16 14:49:00 +00001933 assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)
1934 || pParse->db->mallocFailed );
dan02fa4692009-08-17 17:06:58 +00001935 }else{
dan84c309b2013-08-08 16:17:12 +00001936 /* Otherwise, pRec must be smaller than sample $i and larger than
1937 ** sample ($i-1). */
1938 assert( i==pIdx->nSample
drh0e1f0022013-08-16 14:49:00 +00001939 || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0
1940 || pParse->db->mallocFailed );
dan84c309b2013-08-08 16:17:12 +00001941 assert( i==0
drh0e1f0022013-08-16 14:49:00 +00001942 || sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0
1943 || pParse->db->mallocFailed );
drhfaacf172011-08-12 01:51:45 +00001944 }
dan84c309b2013-08-08 16:17:12 +00001945#endif /* ifdef SQLITE_DEBUG */
dan02fa4692009-08-17 17:06:58 +00001946
drhfaacf172011-08-12 01:51:45 +00001947 /* At this point, aSample[i] is the first sample that is greater than
1948 ** or equal to pVal. Or if i==pIdx->nSample, then all samples are less
dan84c309b2013-08-08 16:17:12 +00001949 ** than pVal. If aSample[i]==pVal, then res==0.
drhfaacf172011-08-12 01:51:45 +00001950 */
dan84c309b2013-08-08 16:17:12 +00001951 if( res==0 ){
daneea568d2013-08-07 19:46:15 +00001952 aStat[0] = aSample[i].anLt[iCol];
1953 aStat[1] = aSample[i].anEq[iCol];
drhfaacf172011-08-12 01:51:45 +00001954 }else{
1955 tRowcnt iLower, iUpper, iGap;
1956 if( i==0 ){
1957 iLower = 0;
daneea568d2013-08-07 19:46:15 +00001958 iUpper = aSample[0].anLt[iCol];
drhfaacf172011-08-12 01:51:45 +00001959 }else{
daneea568d2013-08-07 19:46:15 +00001960 iUpper = i>=pIdx->nSample ? pIdx->aiRowEst[0] : aSample[i].anLt[iCol];
1961 iLower = aSample[i-1].anEq[iCol] + aSample[i-1].anLt[iCol];
drhfaacf172011-08-12 01:51:45 +00001962 }
drhbbbdc832013-10-22 18:01:40 +00001963 aStat[1] = (pIdx->nKeyCol>iCol ? pIdx->aAvgEq[iCol] : 1);
drhfaacf172011-08-12 01:51:45 +00001964 if( iLower>=iUpper ){
1965 iGap = 0;
1966 }else{
1967 iGap = iUpper - iLower;
drhfaacf172011-08-12 01:51:45 +00001968 }
1969 if( roundUp ){
1970 iGap = (iGap*2)/3;
1971 }else{
1972 iGap = iGap/3;
1973 }
1974 aStat[0] = iLower + iGap;
dan02fa4692009-08-17 17:06:58 +00001975 }
dan02fa4692009-08-17 17:06:58 +00001976}
drh1435a9a2013-08-27 23:15:44 +00001977#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
dan937d0de2009-10-15 18:35:38 +00001978
1979/*
dan02fa4692009-08-17 17:06:58 +00001980** This function is used to estimate the number of rows that will be visited
1981** by scanning an index for a range of values. The range may have an upper
1982** bound, a lower bound, or both. The WHERE clause terms that set the upper
1983** and lower bounds are represented by pLower and pUpper respectively. For
1984** example, assuming that index p is on t1(a):
1985**
1986** ... FROM t1 WHERE a > ? AND a < ? ...
1987** |_____| |_____|
1988** | |
1989** pLower pUpper
1990**
drh98cdf622009-08-20 18:14:42 +00001991** If either of the upper or lower bound is not present, then NULL is passed in
drhcdaca552009-08-20 13:45:07 +00001992** place of the corresponding WhereTerm.
dan02fa4692009-08-17 17:06:58 +00001993**
dan6cb8d762013-08-08 11:48:57 +00001994** The value in (pBuilder->pNew->u.btree.nEq) is the index of the index
1995** column subject to the range constraint. Or, equivalently, the number of
1996** equality constraints optimized by the proposed index scan. For example,
1997** assuming index p is on t1(a, b), and the SQL query is:
dan02fa4692009-08-17 17:06:58 +00001998**
1999** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
2000**
dan6cb8d762013-08-08 11:48:57 +00002001** then nEq is set to 1 (as the range restricted column, b, is the second
2002** left-most column of the index). Or, if the query is:
dan02fa4692009-08-17 17:06:58 +00002003**
2004** ... FROM t1 WHERE a > ? AND a < ? ...
2005**
dan6cb8d762013-08-08 11:48:57 +00002006** then nEq is set to 0.
dan02fa4692009-08-17 17:06:58 +00002007**
drhbf539c42013-10-05 18:16:02 +00002008** When this function is called, *pnOut is set to the sqlite3LogEst() of the
dan6cb8d762013-08-08 11:48:57 +00002009** number of rows that the index scan is expected to visit without
2010** considering the range constraints. If nEq is 0, this is the number of
2011** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced)
2012** to account for the range contraints pLower and pUpper.
2013**
2014** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be
2015** used, each range inequality reduces the search space by a factor of 4.
2016** Hence a pair of constraints (x>? AND x<?) reduces the expected number of
2017** rows visited by a factor of 16.
dan02fa4692009-08-17 17:06:58 +00002018*/
2019static int whereRangeScanEst(
drhcdaca552009-08-20 13:45:07 +00002020 Parse *pParse, /* Parsing & code generating context */
dan7a419232013-08-06 20:01:43 +00002021 WhereLoopBuilder *pBuilder,
drhcdaca552009-08-20 13:45:07 +00002022 WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
2023 WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
drh186ad8c2013-10-08 18:40:37 +00002024 WhereLoop *pLoop /* Modify the .nOut and maybe .rRun fields */
dan02fa4692009-08-17 17:06:58 +00002025){
dan69188d92009-08-19 08:18:32 +00002026 int rc = SQLITE_OK;
drh186ad8c2013-10-08 18:40:37 +00002027 int nOut = pLoop->nOut;
drhbf539c42013-10-05 18:16:02 +00002028 LogEst nNew;
dan69188d92009-08-19 08:18:32 +00002029
drh1435a9a2013-08-27 23:15:44 +00002030#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drh186ad8c2013-10-08 18:40:37 +00002031 Index *p = pLoop->u.btree.pIndex;
drh4f991892013-10-11 15:05:05 +00002032 int nEq = pLoop->u.btree.nEq;
dan02fa4692009-08-17 17:06:58 +00002033
drh74dade22013-09-04 18:14:53 +00002034 if( p->nSample>0
2035 && nEq==pBuilder->nRecValid
dan8ad169a2013-08-12 20:14:04 +00002036 && nEq<p->nSampleCol
dan7a419232013-08-06 20:01:43 +00002037 && OptimizationEnabled(pParse->db, SQLITE_Stat3)
2038 ){
2039 UnpackedRecord *pRec = pBuilder->pRec;
drhfaacf172011-08-12 01:51:45 +00002040 tRowcnt a[2];
dan575ab2f2013-09-02 07:16:40 +00002041 u8 aff;
drh98cdf622009-08-20 18:14:42 +00002042
danb3c02e22013-08-08 19:38:40 +00002043 /* Variable iLower will be set to the estimate of the number of rows in
2044 ** the index that are less than the lower bound of the range query. The
2045 ** lower bound being the concatenation of $P and $L, where $P is the
2046 ** key-prefix formed by the nEq values matched against the nEq left-most
2047 ** columns of the index, and $L is the value in pLower.
2048 **
2049 ** Or, if pLower is NULL or $L cannot be extracted from it (because it
2050 ** is not a simple variable or literal value), the lower bound of the
2051 ** range is $P. Due to a quirk in the way whereKeyStats() works, even
2052 ** if $L is available, whereKeyStats() is called for both ($P) and
2053 ** ($P:$L) and the larger of the two returned values used.
2054 **
2055 ** Similarly, iUpper is to be set to the estimate of the number of rows
2056 ** less than the upper bound of the range query. Where the upper bound
2057 ** is either ($P) or ($P:$U). Again, even if $U is available, both values
2058 ** of iUpper are requested of whereKeyStats() and the smaller used.
2059 */
2060 tRowcnt iLower;
2061 tRowcnt iUpper;
2062
drhbbbdc832013-10-22 18:01:40 +00002063 if( nEq==p->nKeyCol ){
mistachkinc2cfb512013-09-04 04:04:08 +00002064 aff = SQLITE_AFF_INTEGER;
2065 }else{
2066 aff = p->pTable->aCol[p->aiColumn[nEq]].affinity;
2067 }
danb3c02e22013-08-08 19:38:40 +00002068 /* Determine iLower and iUpper using ($P) only. */
2069 if( nEq==0 ){
2070 iLower = 0;
2071 iUpper = p->aiRowEst[0];
2072 }else{
2073 /* Note: this call could be optimized away - since the same values must
2074 ** have been requested when testing key $P in whereEqualScanEst(). */
2075 whereKeyStats(pParse, p, pRec, 0, a);
2076 iLower = a[0];
2077 iUpper = a[0] + a[1];
2078 }
2079
2080 /* If possible, improve on the iLower estimate using ($P:$L). */
dan02fa4692009-08-17 17:06:58 +00002081 if( pLower ){
dan7a419232013-08-06 20:01:43 +00002082 int bOk; /* True if value is extracted from pExpr */
dan02fa4692009-08-17 17:06:58 +00002083 Expr *pExpr = pLower->pExpr->pRight;
drh7a5bcc02013-01-16 17:08:58 +00002084 assert( (pLower->eOperator & (WO_GT|WO_GE))!=0 );
dan87cd9322013-08-07 15:52:41 +00002085 rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
danb3c02e22013-08-08 19:38:40 +00002086 if( rc==SQLITE_OK && bOk ){
2087 tRowcnt iNew;
2088 whereKeyStats(pParse, p, pRec, 0, a);
2089 iNew = a[0] + ((pLower->eOperator & WO_GT) ? a[1] : 0);
2090 if( iNew>iLower ) iLower = iNew;
drhabfa6d52013-09-11 03:53:22 +00002091 nOut--;
drhfaacf172011-08-12 01:51:45 +00002092 }
dan02fa4692009-08-17 17:06:58 +00002093 }
danb3c02e22013-08-08 19:38:40 +00002094
2095 /* If possible, improve on the iUpper estimate using ($P:$U). */
2096 if( pUpper ){
dan7a419232013-08-06 20:01:43 +00002097 int bOk; /* True if value is extracted from pExpr */
dan02fa4692009-08-17 17:06:58 +00002098 Expr *pExpr = pUpper->pExpr->pRight;
drh7a5bcc02013-01-16 17:08:58 +00002099 assert( (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
dan87cd9322013-08-07 15:52:41 +00002100 rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
danb3c02e22013-08-08 19:38:40 +00002101 if( rc==SQLITE_OK && bOk ){
2102 tRowcnt iNew;
2103 whereKeyStats(pParse, p, pRec, 1, a);
2104 iNew = a[0] + ((pUpper->eOperator & WO_LE) ? a[1] : 0);
2105 if( iNew<iUpper ) iUpper = iNew;
drhabfa6d52013-09-11 03:53:22 +00002106 nOut--;
dan02fa4692009-08-17 17:06:58 +00002107 }
2108 }
danb3c02e22013-08-08 19:38:40 +00002109
dan87cd9322013-08-07 15:52:41 +00002110 pBuilder->pRec = pRec;
drhfaacf172011-08-12 01:51:45 +00002111 if( rc==SQLITE_OK ){
drhb8a8e8a2013-06-10 19:12:39 +00002112 if( iUpper>iLower ){
drhbf539c42013-10-05 18:16:02 +00002113 nNew = sqlite3LogEst(iUpper - iLower);
dan7a419232013-08-06 20:01:43 +00002114 }else{
drhbf539c42013-10-05 18:16:02 +00002115 nNew = 10; assert( 10==sqlite3LogEst(2) );
drhfaacf172011-08-12 01:51:45 +00002116 }
dan6cb8d762013-08-08 11:48:57 +00002117 if( nNew<nOut ){
2118 nOut = nNew;
2119 }
drh186ad8c2013-10-08 18:40:37 +00002120 pLoop->nOut = (LogEst)nOut;
drh989578e2013-10-28 14:34:35 +00002121 WHERETRACE(0x10, ("range scan regions: %u..%u est=%d\n",
dan6cb8d762013-08-08 11:48:57 +00002122 (u32)iLower, (u32)iUpper, nOut));
drhfaacf172011-08-12 01:51:45 +00002123 return SQLITE_OK;
drh98cdf622009-08-20 18:14:42 +00002124 }
dan02fa4692009-08-17 17:06:58 +00002125 }
drh3f022182009-09-09 16:10:50 +00002126#else
2127 UNUSED_PARAMETER(pParse);
dan7a419232013-08-06 20:01:43 +00002128 UNUSED_PARAMETER(pBuilder);
dan69188d92009-08-19 08:18:32 +00002129#endif
dan02fa4692009-08-17 17:06:58 +00002130 assert( pLower || pUpper );
drhe1e2e9a2013-06-13 15:16:53 +00002131 /* TUNING: Each inequality constraint reduces the search space 4-fold.
2132 ** A BETWEEN operator, therefore, reduces the search space 16-fold */
drhabfa6d52013-09-11 03:53:22 +00002133 nNew = nOut;
drhb8a8e8a2013-06-10 19:12:39 +00002134 if( pLower && (pLower->wtFlags & TERM_VNULL)==0 ){
drhbf539c42013-10-05 18:16:02 +00002135 nNew -= 20; assert( 20==sqlite3LogEst(4) );
drhabfa6d52013-09-11 03:53:22 +00002136 nOut--;
drhb8a8e8a2013-06-10 19:12:39 +00002137 }
2138 if( pUpper ){
drhbf539c42013-10-05 18:16:02 +00002139 nNew -= 20; assert( 20==sqlite3LogEst(4) );
drhabfa6d52013-09-11 03:53:22 +00002140 nOut--;
drhb8a8e8a2013-06-10 19:12:39 +00002141 }
drhabfa6d52013-09-11 03:53:22 +00002142 if( nNew<10 ) nNew = 10;
2143 if( nNew<nOut ) nOut = nNew;
drh186ad8c2013-10-08 18:40:37 +00002144 pLoop->nOut = (LogEst)nOut;
dan02fa4692009-08-17 17:06:58 +00002145 return rc;
2146}
2147
drh1435a9a2013-08-27 23:15:44 +00002148#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drh82759752011-01-20 16:52:09 +00002149/*
2150** Estimate the number of rows that will be returned based on
2151** an equality constraint x=VALUE and where that VALUE occurs in
2152** the histogram data. This only works when x is the left-most
drhfaacf172011-08-12 01:51:45 +00002153** column of an index and sqlite_stat3 histogram data is available
drhac8eb112011-03-17 01:58:21 +00002154** for that index. When pExpr==NULL that means the constraint is
2155** "x IS NULL" instead of "x=VALUE".
drh82759752011-01-20 16:52:09 +00002156**
drh0c50fa02011-01-21 16:27:18 +00002157** Write the estimated row count into *pnRow and return SQLITE_OK.
2158** If unable to make an estimate, leave *pnRow unchanged and return
2159** non-zero.
drh9b3eb0a2011-01-21 14:37:04 +00002160**
2161** This routine can fail if it is unable to load a collating sequence
2162** required for string comparison, or if unable to allocate memory
2163** for a UTF conversion required for comparison. The error is stored
2164** in the pParse structure.
drh82759752011-01-20 16:52:09 +00002165*/
drh041e09f2011-04-07 19:56:21 +00002166static int whereEqualScanEst(
drh82759752011-01-20 16:52:09 +00002167 Parse *pParse, /* Parsing & code generating context */
dan7a419232013-08-06 20:01:43 +00002168 WhereLoopBuilder *pBuilder,
drh0c50fa02011-01-21 16:27:18 +00002169 Expr *pExpr, /* Expression for VALUE in the x=VALUE constraint */
drhb8a8e8a2013-06-10 19:12:39 +00002170 tRowcnt *pnRow /* Write the revised row estimate here */
drh82759752011-01-20 16:52:09 +00002171){
dan7a419232013-08-06 20:01:43 +00002172 Index *p = pBuilder->pNew->u.btree.pIndex;
2173 int nEq = pBuilder->pNew->u.btree.nEq;
2174 UnpackedRecord *pRec = pBuilder->pRec;
drh82759752011-01-20 16:52:09 +00002175 u8 aff; /* Column affinity */
2176 int rc; /* Subfunction return code */
drhfaacf172011-08-12 01:51:45 +00002177 tRowcnt a[2]; /* Statistics */
dan7a419232013-08-06 20:01:43 +00002178 int bOk;
drh82759752011-01-20 16:52:09 +00002179
dan7a419232013-08-06 20:01:43 +00002180 assert( nEq>=1 );
drhbbbdc832013-10-22 18:01:40 +00002181 assert( nEq<=(p->nKeyCol+1) );
drh82759752011-01-20 16:52:09 +00002182 assert( p->aSample!=0 );
drh5c624862011-09-22 18:46:34 +00002183 assert( p->nSample>0 );
dan7a419232013-08-06 20:01:43 +00002184 assert( pBuilder->nRecValid<nEq );
2185
2186 /* If values are not available for all fields of the index to the left
2187 ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */
2188 if( pBuilder->nRecValid<(nEq-1) ){
2189 return SQLITE_NOTFOUND;
drh1f9c7662011-03-17 01:34:26 +00002190 }
dan7a419232013-08-06 20:01:43 +00002191
dandd6e1f12013-08-10 19:08:30 +00002192 /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue()
2193 ** below would return the same value. */
drhbbbdc832013-10-22 18:01:40 +00002194 if( nEq>p->nKeyCol ){
dan7a419232013-08-06 20:01:43 +00002195 *pnRow = 1;
2196 return SQLITE_OK;
drh82759752011-01-20 16:52:09 +00002197 }
dan7a419232013-08-06 20:01:43 +00002198
daneea568d2013-08-07 19:46:15 +00002199 aff = p->pTable->aCol[p->aiColumn[nEq-1]].affinity;
dan87cd9322013-08-07 15:52:41 +00002200 rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq-1, &bOk);
2201 pBuilder->pRec = pRec;
dan7a419232013-08-06 20:01:43 +00002202 if( rc!=SQLITE_OK ) return rc;
2203 if( bOk==0 ) return SQLITE_NOTFOUND;
dan7a419232013-08-06 20:01:43 +00002204 pBuilder->nRecValid = nEq;
dan7a419232013-08-06 20:01:43 +00002205
danb3c02e22013-08-08 19:38:40 +00002206 whereKeyStats(pParse, p, pRec, 0, a);
drh989578e2013-10-28 14:34:35 +00002207 WHERETRACE(0x10,("equality scan regions: %d\n", (int)a[1]));
danb3c02e22013-08-08 19:38:40 +00002208 *pnRow = a[1];
daneea568d2013-08-07 19:46:15 +00002209
drh0c50fa02011-01-21 16:27:18 +00002210 return rc;
2211}
drh1435a9a2013-08-27 23:15:44 +00002212#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
drh0c50fa02011-01-21 16:27:18 +00002213
drh1435a9a2013-08-27 23:15:44 +00002214#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drh0c50fa02011-01-21 16:27:18 +00002215/*
2216** Estimate the number of rows that will be returned based on
drh5ac06072011-01-21 18:18:13 +00002217** an IN constraint where the right-hand side of the IN operator
2218** is a list of values. Example:
2219**
2220** WHERE x IN (1,2,3,4)
drh0c50fa02011-01-21 16:27:18 +00002221**
2222** Write the estimated row count into *pnRow and return SQLITE_OK.
2223** If unable to make an estimate, leave *pnRow unchanged and return
2224** non-zero.
2225**
2226** This routine can fail if it is unable to load a collating sequence
2227** required for string comparison, or if unable to allocate memory
2228** for a UTF conversion required for comparison. The error is stored
2229** in the pParse structure.
2230*/
drh041e09f2011-04-07 19:56:21 +00002231static int whereInScanEst(
drh0c50fa02011-01-21 16:27:18 +00002232 Parse *pParse, /* Parsing & code generating context */
dan7a419232013-08-06 20:01:43 +00002233 WhereLoopBuilder *pBuilder,
drh0c50fa02011-01-21 16:27:18 +00002234 ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
drhb8a8e8a2013-06-10 19:12:39 +00002235 tRowcnt *pnRow /* Write the revised row estimate here */
drh0c50fa02011-01-21 16:27:18 +00002236){
dan7a419232013-08-06 20:01:43 +00002237 Index *p = pBuilder->pNew->u.btree.pIndex;
2238 int nRecValid = pBuilder->nRecValid;
drhb8a8e8a2013-06-10 19:12:39 +00002239 int rc = SQLITE_OK; /* Subfunction return code */
2240 tRowcnt nEst; /* Number of rows for a single term */
2241 tRowcnt nRowEst = 0; /* New estimate of the number of rows */
2242 int i; /* Loop counter */
drh0c50fa02011-01-21 16:27:18 +00002243
2244 assert( p->aSample!=0 );
drhfaacf172011-08-12 01:51:45 +00002245 for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
2246 nEst = p->aiRowEst[0];
dan7a419232013-08-06 20:01:43 +00002247 rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst);
drhfaacf172011-08-12 01:51:45 +00002248 nRowEst += nEst;
dan7a419232013-08-06 20:01:43 +00002249 pBuilder->nRecValid = nRecValid;
drh0c50fa02011-01-21 16:27:18 +00002250 }
dan7a419232013-08-06 20:01:43 +00002251
drh0c50fa02011-01-21 16:27:18 +00002252 if( rc==SQLITE_OK ){
drh0c50fa02011-01-21 16:27:18 +00002253 if( nRowEst > p->aiRowEst[0] ) nRowEst = p->aiRowEst[0];
2254 *pnRow = nRowEst;
drh989578e2013-10-28 14:34:35 +00002255 WHERETRACE(0x10,("IN row estimate: est=%g\n", nRowEst));
drh0c50fa02011-01-21 16:27:18 +00002256 }
dan7a419232013-08-06 20:01:43 +00002257 assert( pBuilder->nRecValid==nRecValid );
drh0c50fa02011-01-21 16:27:18 +00002258 return rc;
drh82759752011-01-20 16:52:09 +00002259}
drh1435a9a2013-08-27 23:15:44 +00002260#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
drh82759752011-01-20 16:52:09 +00002261
drh46c35f92012-09-26 23:17:01 +00002262/*
drh2ffb1182004-07-19 19:14:01 +00002263** Disable a term in the WHERE clause. Except, do not disable the term
2264** if it controls a LEFT OUTER JOIN and it did not originate in the ON
2265** or USING clause of that join.
2266**
2267** Consider the term t2.z='ok' in the following queries:
2268**
2269** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
2270** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
2271** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
2272**
drh23bf66d2004-12-14 03:34:34 +00002273** The t2.z='ok' is disabled in the in (2) because it originates
drh2ffb1182004-07-19 19:14:01 +00002274** in the ON clause. The term is disabled in (3) because it is not part
2275** of a LEFT OUTER JOIN. In (1), the term is not disabled.
2276**
2277** Disabling a term causes that term to not be tested in the inner loop
drhb6fb62d2005-09-20 08:47:20 +00002278** of the join. Disabling is an optimization. When terms are satisfied
2279** by indices, we disable them to prevent redundant tests in the inner
2280** loop. We would get the correct results if nothing were ever disabled,
2281** but joins might run a little slower. The trick is to disable as much
2282** as we can without disabling too much. If we disabled in (1), we'd get
2283** the wrong answer. See ticket #813.
drh2ffb1182004-07-19 19:14:01 +00002284*/
drh0fcef5e2005-07-19 17:38:22 +00002285static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
2286 if( pTerm
drhbe837bd2010-04-30 21:03:24 +00002287 && (pTerm->wtFlags & TERM_CODED)==0
drh0fcef5e2005-07-19 17:38:22 +00002288 && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
drh0259bc32013-09-09 19:37:46 +00002289 && (pLevel->notReady & pTerm->prereqAll)==0
drh0fcef5e2005-07-19 17:38:22 +00002290 ){
drh165be382008-12-05 02:36:33 +00002291 pTerm->wtFlags |= TERM_CODED;
drh45b1ee42005-08-02 17:48:22 +00002292 if( pTerm->iParent>=0 ){
2293 WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
2294 if( (--pOther->nChild)==0 ){
drhed378002005-07-28 23:12:08 +00002295 disableTerm(pLevel, pOther);
2296 }
drh0fcef5e2005-07-19 17:38:22 +00002297 }
drh2ffb1182004-07-19 19:14:01 +00002298 }
2299}
2300
2301/*
dan69f8bb92009-08-13 19:21:16 +00002302** Code an OP_Affinity opcode to apply the column affinity string zAff
2303** to the n registers starting at base.
2304**
drh039fc322009-11-17 18:31:47 +00002305** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
2306** beginning and end of zAff are ignored. If all entries in zAff are
2307** SQLITE_AFF_NONE, then no code gets generated.
2308**
2309** This routine makes its own copy of zAff so that the caller is free
2310** to modify zAff after this routine returns.
drh94a11212004-09-25 13:12:14 +00002311*/
dan69f8bb92009-08-13 19:21:16 +00002312static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
2313 Vdbe *v = pParse->pVdbe;
drh039fc322009-11-17 18:31:47 +00002314 if( zAff==0 ){
2315 assert( pParse->db->mallocFailed );
2316 return;
2317 }
dan69f8bb92009-08-13 19:21:16 +00002318 assert( v!=0 );
drh039fc322009-11-17 18:31:47 +00002319
2320 /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
2321 ** and end of the affinity string.
2322 */
2323 while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
2324 n--;
2325 base++;
2326 zAff++;
2327 }
2328 while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
2329 n--;
2330 }
2331
2332 /* Code the OP_Affinity opcode if there is anything left to do. */
2333 if( n>0 ){
2334 sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
2335 sqlite3VdbeChangeP4(v, -1, zAff, n);
2336 sqlite3ExprCacheAffinityChange(pParse, base, n);
2337 }
drh94a11212004-09-25 13:12:14 +00002338}
2339
drhe8b97272005-07-19 22:22:12 +00002340
2341/*
drh51147ba2005-07-23 22:59:55 +00002342** Generate code for a single equality term of the WHERE clause. An equality
2343** term can be either X=expr or X IN (...). pTerm is the term to be
2344** coded.
2345**
drh1db639c2008-01-17 02:36:28 +00002346** The current value for the constraint is left in register iReg.
drh51147ba2005-07-23 22:59:55 +00002347**
2348** For a constraint of the form X=expr, the expression is evaluated and its
2349** result is left on the stack. For constraints of the form X IN (...)
2350** this routine sets up a loop that will iterate over all values of X.
drh94a11212004-09-25 13:12:14 +00002351*/
drh678ccce2008-03-31 18:19:54 +00002352static int codeEqualityTerm(
drh94a11212004-09-25 13:12:14 +00002353 Parse *pParse, /* The parsing context */
drhe23399f2005-07-22 00:31:39 +00002354 WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
drh0fe456b2013-03-12 18:34:50 +00002355 WhereLevel *pLevel, /* The level of the FROM clause we are working on */
2356 int iEq, /* Index of the equality term within this level */
drh7ba39a92013-05-30 17:43:19 +00002357 int bRev, /* True for reverse-order IN operations */
drh678ccce2008-03-31 18:19:54 +00002358 int iTarget /* Attempt to leave results in this register */
drh94a11212004-09-25 13:12:14 +00002359){
drh0fcef5e2005-07-19 17:38:22 +00002360 Expr *pX = pTerm->pExpr;
drh50b39962006-10-28 00:28:09 +00002361 Vdbe *v = pParse->pVdbe;
drh678ccce2008-03-31 18:19:54 +00002362 int iReg; /* Register holding results */
drh1db639c2008-01-17 02:36:28 +00002363
danielk19772d605492008-10-01 08:43:03 +00002364 assert( iTarget>0 );
drh50b39962006-10-28 00:28:09 +00002365 if( pX->op==TK_EQ ){
drh678ccce2008-03-31 18:19:54 +00002366 iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
drh50b39962006-10-28 00:28:09 +00002367 }else if( pX->op==TK_ISNULL ){
drh678ccce2008-03-31 18:19:54 +00002368 iReg = iTarget;
drh1db639c2008-01-17 02:36:28 +00002369 sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
danielk1977b3bce662005-01-29 08:32:43 +00002370#ifndef SQLITE_OMIT_SUBQUERY
drh94a11212004-09-25 13:12:14 +00002371 }else{
danielk19779a96b662007-11-29 17:05:18 +00002372 int eType;
danielk1977b3bce662005-01-29 08:32:43 +00002373 int iTab;
drh72e8fa42007-03-28 14:30:06 +00002374 struct InLoop *pIn;
drh7ba39a92013-05-30 17:43:19 +00002375 WhereLoop *pLoop = pLevel->pWLoop;
danielk1977b3bce662005-01-29 08:32:43 +00002376
drh7ba39a92013-05-30 17:43:19 +00002377 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
2378 && pLoop->u.btree.pIndex!=0
2379 && pLoop->u.btree.pIndex->aSortOrder[iEq]
drhd3832162013-03-12 18:49:25 +00002380 ){
drh725e1ae2013-03-12 23:58:42 +00002381 testcase( iEq==0 );
drh725e1ae2013-03-12 23:58:42 +00002382 testcase( bRev );
drh1ccce442013-03-12 20:38:51 +00002383 bRev = !bRev;
drh0fe456b2013-03-12 18:34:50 +00002384 }
drh50b39962006-10-28 00:28:09 +00002385 assert( pX->op==TK_IN );
drh678ccce2008-03-31 18:19:54 +00002386 iReg = iTarget;
danielk19770cdc0222008-06-26 18:04:03 +00002387 eType = sqlite3FindInIndex(pParse, pX, 0);
drh725e1ae2013-03-12 23:58:42 +00002388 if( eType==IN_INDEX_INDEX_DESC ){
2389 testcase( bRev );
2390 bRev = !bRev;
2391 }
danielk1977b3bce662005-01-29 08:32:43 +00002392 iTab = pX->iTable;
drh2d96b932013-02-08 18:48:23 +00002393 sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
drh6fa978d2013-05-30 19:29:19 +00002394 assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
2395 pLoop->wsFlags |= WHERE_IN_ABLE;
drh111a6a72008-12-21 03:51:16 +00002396 if( pLevel->u.in.nIn==0 ){
drhb3190c12008-12-08 21:37:14 +00002397 pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
drh72e8fa42007-03-28 14:30:06 +00002398 }
drh111a6a72008-12-21 03:51:16 +00002399 pLevel->u.in.nIn++;
2400 pLevel->u.in.aInLoop =
2401 sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
2402 sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
2403 pIn = pLevel->u.in.aInLoop;
drh72e8fa42007-03-28 14:30:06 +00002404 if( pIn ){
drh111a6a72008-12-21 03:51:16 +00002405 pIn += pLevel->u.in.nIn - 1;
drh72e8fa42007-03-28 14:30:06 +00002406 pIn->iCur = iTab;
drh1db639c2008-01-17 02:36:28 +00002407 if( eType==IN_INDEX_ROWID ){
drhb3190c12008-12-08 21:37:14 +00002408 pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
drh1db639c2008-01-17 02:36:28 +00002409 }else{
drhb3190c12008-12-08 21:37:14 +00002410 pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
drh1db639c2008-01-17 02:36:28 +00002411 }
drh2d96b932013-02-08 18:48:23 +00002412 pIn->eEndLoopOp = bRev ? OP_Prev : OP_Next;
drh1db639c2008-01-17 02:36:28 +00002413 sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
drha6110402005-07-28 20:51:19 +00002414 }else{
drh111a6a72008-12-21 03:51:16 +00002415 pLevel->u.in.nIn = 0;
drhe23399f2005-07-22 00:31:39 +00002416 }
danielk1977b3bce662005-01-29 08:32:43 +00002417#endif
drh94a11212004-09-25 13:12:14 +00002418 }
drh0fcef5e2005-07-19 17:38:22 +00002419 disableTerm(pLevel, pTerm);
drh678ccce2008-03-31 18:19:54 +00002420 return iReg;
drh94a11212004-09-25 13:12:14 +00002421}
2422
drh51147ba2005-07-23 22:59:55 +00002423/*
2424** Generate code that will evaluate all == and IN constraints for an
drh039fc322009-11-17 18:31:47 +00002425** index.
drh51147ba2005-07-23 22:59:55 +00002426**
2427** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
2428** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
2429** The index has as many as three equality constraints, but in this
2430** example, the third "c" value is an inequality. So only two
2431** constraints are coded. This routine will generate code to evaluate
drh6df2acd2008-12-28 16:55:25 +00002432** a==5 and b IN (1,2,3). The current values for a and b will be stored
2433** in consecutive registers and the index of the first register is returned.
drh51147ba2005-07-23 22:59:55 +00002434**
2435** In the example above nEq==2. But this subroutine works for any value
2436** of nEq including 0. If nEq==0, this routine is nearly a no-op.
drh039fc322009-11-17 18:31:47 +00002437** The only thing it does is allocate the pLevel->iMem memory cell and
2438** compute the affinity string.
drh51147ba2005-07-23 22:59:55 +00002439**
drh700a2262008-12-17 19:22:15 +00002440** This routine always allocates at least one memory cell and returns
2441** the index of that memory cell. The code that
2442** calls this routine will use that memory cell to store the termination
drh51147ba2005-07-23 22:59:55 +00002443** key value of the loop. If one or more IN operators appear, then
2444** this routine allocates an additional nEq memory cells for internal
2445** use.
dan69f8bb92009-08-13 19:21:16 +00002446**
2447** Before returning, *pzAff is set to point to a buffer containing a
2448** copy of the column affinity string of the index allocated using
2449** sqlite3DbMalloc(). Except, entries in the copy of the string associated
2450** with equality constraints that use NONE affinity are set to
2451** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
2452**
2453** CREATE TABLE t1(a TEXT PRIMARY KEY, b);
2454** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
2455**
2456** In the example above, the index on t1(a) has TEXT affinity. But since
2457** the right hand side of the equality constraint (t2.b) has NONE affinity,
2458** no conversion should be attempted before using a t2.b value as part of
2459** a key to search the index. Hence the first byte in the returned affinity
2460** string in this example would be set to SQLITE_AFF_NONE.
drh51147ba2005-07-23 22:59:55 +00002461*/
drh1db639c2008-01-17 02:36:28 +00002462static int codeAllEqualityTerms(
drh51147ba2005-07-23 22:59:55 +00002463 Parse *pParse, /* Parsing context */
2464 WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
drh7ba39a92013-05-30 17:43:19 +00002465 int bRev, /* Reverse the order of IN operators */
dan69f8bb92009-08-13 19:21:16 +00002466 int nExtraReg, /* Number of extra registers to allocate */
2467 char **pzAff /* OUT: Set to point to affinity string */
drh51147ba2005-07-23 22:59:55 +00002468){
drh7ba39a92013-05-30 17:43:19 +00002469 int nEq; /* The number of == or IN constraints to code */
drh111a6a72008-12-21 03:51:16 +00002470 Vdbe *v = pParse->pVdbe; /* The vm under construction */
2471 Index *pIdx; /* The index being used for this loop */
drh51147ba2005-07-23 22:59:55 +00002472 WhereTerm *pTerm; /* A single constraint term */
drh7ba39a92013-05-30 17:43:19 +00002473 WhereLoop *pLoop; /* The WhereLoop object */
drh51147ba2005-07-23 22:59:55 +00002474 int j; /* Loop counter */
drh1db639c2008-01-17 02:36:28 +00002475 int regBase; /* Base register */
drh6df2acd2008-12-28 16:55:25 +00002476 int nReg; /* Number of registers to allocate */
dan69f8bb92009-08-13 19:21:16 +00002477 char *zAff; /* Affinity string to return */
drh51147ba2005-07-23 22:59:55 +00002478
drh111a6a72008-12-21 03:51:16 +00002479 /* This module is only called on query plans that use an index. */
drh7ba39a92013-05-30 17:43:19 +00002480 pLoop = pLevel->pWLoop;
2481 assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
2482 nEq = pLoop->u.btree.nEq;
2483 pIdx = pLoop->u.btree.pIndex;
2484 assert( pIdx!=0 );
drh111a6a72008-12-21 03:51:16 +00002485
drh51147ba2005-07-23 22:59:55 +00002486 /* Figure out how many memory cells we will need then allocate them.
drh51147ba2005-07-23 22:59:55 +00002487 */
drh700a2262008-12-17 19:22:15 +00002488 regBase = pParse->nMem + 1;
drh7ba39a92013-05-30 17:43:19 +00002489 nReg = pLoop->u.btree.nEq + nExtraReg;
drh6df2acd2008-12-28 16:55:25 +00002490 pParse->nMem += nReg;
drh51147ba2005-07-23 22:59:55 +00002491
dan69f8bb92009-08-13 19:21:16 +00002492 zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
2493 if( !zAff ){
2494 pParse->db->mallocFailed = 1;
2495 }
2496
drh51147ba2005-07-23 22:59:55 +00002497 /* Evaluate the equality constraints
2498 */
mistachkinf6418892013-08-28 01:54:12 +00002499 assert( zAff==0 || (int)strlen(zAff)>=nEq );
drhc49de5d2007-01-19 01:06:01 +00002500 for(j=0; j<nEq; j++){
drh678ccce2008-03-31 18:19:54 +00002501 int r1;
drh4efc9292013-06-06 23:02:03 +00002502 pTerm = pLoop->aLTerm[j];
drh7ba39a92013-05-30 17:43:19 +00002503 assert( pTerm!=0 );
drhbe837bd2010-04-30 21:03:24 +00002504 /* The following true for indices with redundant columns.
2505 ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
2506 testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
drh39759742013-08-02 23:40:45 +00002507 testcase( pTerm->wtFlags & TERM_VIRTUAL );
drh7ba39a92013-05-30 17:43:19 +00002508 r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
drh678ccce2008-03-31 18:19:54 +00002509 if( r1!=regBase+j ){
drh6df2acd2008-12-28 16:55:25 +00002510 if( nReg==1 ){
2511 sqlite3ReleaseTempReg(pParse, regBase);
2512 regBase = r1;
2513 }else{
2514 sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
2515 }
drh678ccce2008-03-31 18:19:54 +00002516 }
drh981642f2008-04-19 14:40:43 +00002517 testcase( pTerm->eOperator & WO_ISNULL );
2518 testcase( pTerm->eOperator & WO_IN );
drh72e8fa42007-03-28 14:30:06 +00002519 if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
drh039fc322009-11-17 18:31:47 +00002520 Expr *pRight = pTerm->pExpr->pRight;
drh2f2855b2009-11-18 01:25:26 +00002521 sqlite3ExprCodeIsNullJump(v, pRight, regBase+j, pLevel->addrBrk);
drh039fc322009-11-17 18:31:47 +00002522 if( zAff ){
2523 if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
2524 zAff[j] = SQLITE_AFF_NONE;
2525 }
2526 if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
2527 zAff[j] = SQLITE_AFF_NONE;
2528 }
dan69f8bb92009-08-13 19:21:16 +00002529 }
drh51147ba2005-07-23 22:59:55 +00002530 }
2531 }
dan69f8bb92009-08-13 19:21:16 +00002532 *pzAff = zAff;
drh1db639c2008-01-17 02:36:28 +00002533 return regBase;
drh51147ba2005-07-23 22:59:55 +00002534}
2535
dan2ce22452010-11-08 19:01:16 +00002536#ifndef SQLITE_OMIT_EXPLAIN
dan17c0bc02010-11-09 17:35:19 +00002537/*
drh69174c42010-11-12 15:35:59 +00002538** This routine is a helper for explainIndexRange() below
2539**
2540** pStr holds the text of an expression that we are building up one term
2541** at a time. This routine adds a new term to the end of the expression.
2542** Terms are separated by AND so add the "AND" text for second and subsequent
2543** terms only.
2544*/
2545static void explainAppendTerm(
2546 StrAccum *pStr, /* The text expression being built */
2547 int iTerm, /* Index of this term. First is zero */
2548 const char *zColumn, /* Name of the column */
2549 const char *zOp /* Name of the operator */
2550){
2551 if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
2552 sqlite3StrAccumAppend(pStr, zColumn, -1);
2553 sqlite3StrAccumAppend(pStr, zOp, 1);
2554 sqlite3StrAccumAppend(pStr, "?", 1);
2555}
2556
2557/*
dan17c0bc02010-11-09 17:35:19 +00002558** Argument pLevel describes a strategy for scanning table pTab. This
2559** function returns a pointer to a string buffer containing a description
2560** of the subset of table rows scanned by the strategy in the form of an
2561** SQL expression. Or, if all rows are scanned, NULL is returned.
2562**
2563** For example, if the query:
2564**
2565** SELECT * FROM t1 WHERE a=1 AND b>2;
2566**
2567** is run and there is an index on (a, b), then this function returns a
2568** string similar to:
2569**
2570** "a=? AND b>?"
2571**
2572** The returned pointer points to memory obtained from sqlite3DbMalloc().
2573** It is the responsibility of the caller to free the buffer when it is
2574** no longer required.
2575*/
drhef866372013-05-22 20:49:02 +00002576static char *explainIndexRange(sqlite3 *db, WhereLoop *pLoop, Table *pTab){
2577 Index *pIndex = pLoop->u.btree.pIndex;
2578 int nEq = pLoop->u.btree.nEq;
drh69174c42010-11-12 15:35:59 +00002579 int i, j;
2580 Column *aCol = pTab->aCol;
drhbbbdc832013-10-22 18:01:40 +00002581 i16 *aiColumn = pIndex->aiColumn;
drh69174c42010-11-12 15:35:59 +00002582 StrAccum txt;
dan2ce22452010-11-08 19:01:16 +00002583
drhef866372013-05-22 20:49:02 +00002584 if( nEq==0 && (pLoop->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ){
drh69174c42010-11-12 15:35:59 +00002585 return 0;
2586 }
2587 sqlite3StrAccumInit(&txt, 0, 0, SQLITE_MAX_LENGTH);
drh03b6df12010-11-15 16:29:30 +00002588 txt.db = db;
drh69174c42010-11-12 15:35:59 +00002589 sqlite3StrAccumAppend(&txt, " (", 2);
dan2ce22452010-11-08 19:01:16 +00002590 for(i=0; i<nEq; i++){
drhbbbdc832013-10-22 18:01:40 +00002591 char *z = (i==pIndex->nKeyCol ) ? "rowid" : aCol[aiColumn[i]].zName;
dane934e632013-08-20 17:14:57 +00002592 explainAppendTerm(&txt, i, z, "=");
dan2ce22452010-11-08 19:01:16 +00002593 }
2594
drh69174c42010-11-12 15:35:59 +00002595 j = i;
drhef866372013-05-22 20:49:02 +00002596 if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
drhbbbdc832013-10-22 18:01:40 +00002597 char *z = (j==pIndex->nKeyCol ) ? "rowid" : aCol[aiColumn[j]].zName;
dan0c733f62011-11-16 15:27:09 +00002598 explainAppendTerm(&txt, i++, z, ">");
dan2ce22452010-11-08 19:01:16 +00002599 }
drhef866372013-05-22 20:49:02 +00002600 if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
drhbbbdc832013-10-22 18:01:40 +00002601 char *z = (j==pIndex->nKeyCol ) ? "rowid" : aCol[aiColumn[j]].zName;
dan0c733f62011-11-16 15:27:09 +00002602 explainAppendTerm(&txt, i, z, "<");
dan2ce22452010-11-08 19:01:16 +00002603 }
drh69174c42010-11-12 15:35:59 +00002604 sqlite3StrAccumAppend(&txt, ")", 1);
2605 return sqlite3StrAccumFinish(&txt);
dan2ce22452010-11-08 19:01:16 +00002606}
2607
dan17c0bc02010-11-09 17:35:19 +00002608/*
2609** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
2610** command. If the query being compiled is an EXPLAIN QUERY PLAN, a single
2611** record is added to the output to describe the table scan strategy in
2612** pLevel.
2613*/
2614static void explainOneScan(
dan2ce22452010-11-08 19:01:16 +00002615 Parse *pParse, /* Parse context */
2616 SrcList *pTabList, /* Table list this loop refers to */
2617 WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
2618 int iLevel, /* Value for "level" column of output */
dan4a07e3d2010-11-09 14:48:59 +00002619 int iFrom, /* Value for "from" column of output */
2620 u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
dan2ce22452010-11-08 19:01:16 +00002621){
2622 if( pParse->explain==2 ){
dan2ce22452010-11-08 19:01:16 +00002623 struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
dan17c0bc02010-11-09 17:35:19 +00002624 Vdbe *v = pParse->pVdbe; /* VM being constructed */
2625 sqlite3 *db = pParse->db; /* Database handle */
2626 char *zMsg; /* Text to add to EQP output */
dan4a07e3d2010-11-09 14:48:59 +00002627 int iId = pParse->iSelectId; /* Select id (left-most output column) */
dan4bc39fa2010-11-13 16:42:27 +00002628 int isSearch; /* True for a SEARCH. False for SCAN. */
drhef866372013-05-22 20:49:02 +00002629 WhereLoop *pLoop; /* The controlling WhereLoop object */
2630 u32 flags; /* Flags that describe this loop */
dan2ce22452010-11-08 19:01:16 +00002631
drhef866372013-05-22 20:49:02 +00002632 pLoop = pLevel->pWLoop;
2633 flags = pLoop->wsFlags;
dan4a07e3d2010-11-09 14:48:59 +00002634 if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return;
dan2ce22452010-11-08 19:01:16 +00002635
drhef866372013-05-22 20:49:02 +00002636 isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
2637 || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
2638 || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
dan4bc39fa2010-11-13 16:42:27 +00002639
2640 zMsg = sqlite3MPrintf(db, "%s", isSearch?"SEARCH":"SCAN");
dan4a07e3d2010-11-09 14:48:59 +00002641 if( pItem->pSelect ){
dan4bc39fa2010-11-13 16:42:27 +00002642 zMsg = sqlite3MAppendf(db, zMsg, "%s SUBQUERY %d", zMsg,pItem->iSelectId);
dan4a07e3d2010-11-09 14:48:59 +00002643 }else{
dan4bc39fa2010-11-13 16:42:27 +00002644 zMsg = sqlite3MAppendf(db, zMsg, "%s TABLE %s", zMsg, pItem->zName);
dan4a07e3d2010-11-09 14:48:59 +00002645 }
2646
dan2ce22452010-11-08 19:01:16 +00002647 if( pItem->zAlias ){
2648 zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
2649 }
drhef866372013-05-22 20:49:02 +00002650 if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0
drh7963b0e2013-06-17 21:37:40 +00002651 && ALWAYS(pLoop->u.btree.pIndex!=0)
drhef866372013-05-22 20:49:02 +00002652 ){
2653 char *zWhere = explainIndexRange(db, pLoop, pItem->pTab);
drh986b3872013-06-28 21:12:20 +00002654 zMsg = sqlite3MAppendf(db, zMsg,
2655 ((flags & WHERE_AUTO_INDEX) ?
2656 "%s USING AUTOMATIC %sINDEX%.0s%s" :
2657 "%s USING %sINDEX %s%s"),
2658 zMsg, ((flags & WHERE_IDX_ONLY) ? "COVERING " : ""),
2659 pLoop->u.btree.pIndex->zName, zWhere);
dan2ce22452010-11-08 19:01:16 +00002660 sqlite3DbFree(db, zWhere);
drhef71c1f2013-06-04 12:58:02 +00002661 }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
dan4bc39fa2010-11-13 16:42:27 +00002662 zMsg = sqlite3MAppendf(db, zMsg, "%s USING INTEGER PRIMARY KEY", zMsg);
dan2ce22452010-11-08 19:01:16 +00002663
drh8e23daf2013-06-11 13:30:04 +00002664 if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
dan2ce22452010-11-08 19:01:16 +00002665 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid=?)", zMsg);
drh04098e62010-11-15 21:50:19 +00002666 }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
dan2ce22452010-11-08 19:01:16 +00002667 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>? AND rowid<?)", zMsg);
2668 }else if( flags&WHERE_BTM_LIMIT ){
2669 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>?)", zMsg);
drh7963b0e2013-06-17 21:37:40 +00002670 }else if( ALWAYS(flags&WHERE_TOP_LIMIT) ){
dan2ce22452010-11-08 19:01:16 +00002671 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid<?)", zMsg);
2672 }
2673 }
2674#ifndef SQLITE_OMIT_VIRTUALTABLE
2675 else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
dan2ce22452010-11-08 19:01:16 +00002676 zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
drhef866372013-05-22 20:49:02 +00002677 pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
dan2ce22452010-11-08 19:01:16 +00002678 }
2679#endif
drhb8a8e8a2013-06-10 19:12:39 +00002680 zMsg = sqlite3MAppendf(db, zMsg, "%s", zMsg);
dan4a07e3d2010-11-09 14:48:59 +00002681 sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg, P4_DYNAMIC);
dan2ce22452010-11-08 19:01:16 +00002682 }
2683}
2684#else
dan17c0bc02010-11-09 17:35:19 +00002685# define explainOneScan(u,v,w,x,y,z)
dan2ce22452010-11-08 19:01:16 +00002686#endif /* SQLITE_OMIT_EXPLAIN */
2687
2688
drh111a6a72008-12-21 03:51:16 +00002689/*
2690** Generate code for the start of the iLevel-th loop in the WHERE clause
2691** implementation described by pWInfo.
2692*/
2693static Bitmask codeOneLoopStart(
2694 WhereInfo *pWInfo, /* Complete information about the WHERE clause */
2695 int iLevel, /* Which level of pWInfo->a[] should be coded */
drh7a484802012-03-16 00:28:11 +00002696 Bitmask notReady /* Which tables are currently available */
drh111a6a72008-12-21 03:51:16 +00002697){
2698 int j, k; /* Loop counters */
2699 int iCur; /* The VDBE cursor for the table */
2700 int addrNxt; /* Where to jump to continue with the next IN case */
2701 int omitTable; /* True if we use the index only */
2702 int bRev; /* True if we need to scan in reverse order */
2703 WhereLevel *pLevel; /* The where level to be coded */
drh7ba39a92013-05-30 17:43:19 +00002704 WhereLoop *pLoop; /* The WhereLoop object being coded */
drh111a6a72008-12-21 03:51:16 +00002705 WhereClause *pWC; /* Decomposition of the entire WHERE clause */
2706 WhereTerm *pTerm; /* A WHERE clause term */
2707 Parse *pParse; /* Parsing context */
drh6b36e822013-07-30 15:10:32 +00002708 sqlite3 *db; /* Database connection */
drh111a6a72008-12-21 03:51:16 +00002709 Vdbe *v; /* The prepared stmt under constructions */
2710 struct SrcList_item *pTabItem; /* FROM clause term being coded */
drh23d04d52008-12-23 23:56:22 +00002711 int addrBrk; /* Jump here to break out of the loop */
2712 int addrCont; /* Jump here to continue with next cycle */
drh61495262009-04-22 15:32:59 +00002713 int iRowidReg = 0; /* Rowid is stored in this register, if not zero */
2714 int iReleaseReg = 0; /* Temp register to free before returning */
drh111a6a72008-12-21 03:51:16 +00002715
2716 pParse = pWInfo->pParse;
2717 v = pParse->pVdbe;
drh70d18342013-06-06 19:16:33 +00002718 pWC = &pWInfo->sWC;
drh6b36e822013-07-30 15:10:32 +00002719 db = pParse->db;
drh111a6a72008-12-21 03:51:16 +00002720 pLevel = &pWInfo->a[iLevel];
drh7ba39a92013-05-30 17:43:19 +00002721 pLoop = pLevel->pWLoop;
drh111a6a72008-12-21 03:51:16 +00002722 pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
2723 iCur = pTabItem->iCursor;
drh0259bc32013-09-09 19:37:46 +00002724 pLevel->notReady = notReady & ~getMask(&pWInfo->sMaskSet, iCur);
drh7ba39a92013-05-30 17:43:19 +00002725 bRev = (pWInfo->revMask>>iLevel)&1;
2726 omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
drh70d18342013-06-06 19:16:33 +00002727 && (pWInfo->wctrlFlags & WHERE_FORCE_TABLE)==0;
drh5e6790c2013-11-12 20:18:14 +00002728 VdbeNoopComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName));
drh111a6a72008-12-21 03:51:16 +00002729
2730 /* Create labels for the "break" and "continue" instructions
2731 ** for the current loop. Jump to addrBrk to break out of a loop.
2732 ** Jump to cont to go immediately to the next iteration of the
2733 ** loop.
2734 **
2735 ** When there is an IN operator, we also have a "addrNxt" label that
2736 ** means to continue with the next IN value combination. When
2737 ** there are no IN operators in the constraints, the "addrNxt" label
2738 ** is the same as "addrBrk".
2739 */
2740 addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
2741 addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
2742
2743 /* If this is the right table of a LEFT OUTER JOIN, allocate and
2744 ** initialize a memory cell that records if this table matches any
2745 ** row of the left table of the join.
2746 */
2747 if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
2748 pLevel->iLeftJoin = ++pParse->nMem;
2749 sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
2750 VdbeComment((v, "init LEFT JOIN no-match flag"));
2751 }
2752
drh21172c42012-10-30 00:29:07 +00002753 /* Special case of a FROM clause subquery implemented as a co-routine */
2754 if( pTabItem->viaCoroutine ){
2755 int regYield = pTabItem->regReturn;
2756 sqlite3VdbeAddOp2(v, OP_Integer, pTabItem->addrFillSub-1, regYield);
2757 pLevel->p2 = sqlite3VdbeAddOp1(v, OP_Yield, regYield);
2758 VdbeComment((v, "next row of co-routine %s", pTabItem->pTab->zName));
2759 sqlite3VdbeAddOp2(v, OP_If, regYield+1, addrBrk);
2760 pLevel->op = OP_Goto;
2761 }else
2762
drh111a6a72008-12-21 03:51:16 +00002763#ifndef SQLITE_OMIT_VIRTUALTABLE
drh7ba39a92013-05-30 17:43:19 +00002764 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
2765 /* Case 1: The table is a virtual-table. Use the VFilter and VNext
drh111a6a72008-12-21 03:51:16 +00002766 ** to access the data.
2767 */
2768 int iReg; /* P3 Value for OP_VFilter */
drh281bbe22012-10-16 23:17:14 +00002769 int addrNotFound;
drh4efc9292013-06-06 23:02:03 +00002770 int nConstraint = pLoop->nLTerm;
drh111a6a72008-12-21 03:51:16 +00002771
drha62bb8d2009-11-23 21:23:45 +00002772 sqlite3ExprCachePush(pParse);
drh111a6a72008-12-21 03:51:16 +00002773 iReg = sqlite3GetTempRange(pParse, nConstraint+2);
drh281bbe22012-10-16 23:17:14 +00002774 addrNotFound = pLevel->addrBrk;
drh111a6a72008-12-21 03:51:16 +00002775 for(j=0; j<nConstraint; j++){
drhe2250172013-05-31 18:13:50 +00002776 int iTarget = iReg+j+2;
drh4efc9292013-06-06 23:02:03 +00002777 pTerm = pLoop->aLTerm[j];
drh95ed68d2013-06-12 17:55:50 +00002778 if( pTerm==0 ) continue;
drh7ba39a92013-05-30 17:43:19 +00002779 if( pTerm->eOperator & WO_IN ){
2780 codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
2781 addrNotFound = pLevel->addrNxt;
2782 }else{
2783 sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget);
2784 }
2785 }
2786 sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
drh7e47cb82013-05-31 17:55:27 +00002787 sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
drh7ba39a92013-05-30 17:43:19 +00002788 sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
2789 pLoop->u.vtab.idxStr,
2790 pLoop->u.vtab.needFree ? P4_MPRINTF : P4_STATIC);
2791 pLoop->u.vtab.needFree = 0;
2792 for(j=0; j<nConstraint && j<16; j++){
2793 if( (pLoop->u.vtab.omitMask>>j)&1 ){
drh4efc9292013-06-06 23:02:03 +00002794 disableTerm(pLevel, pLoop->aLTerm[j]);
drh111a6a72008-12-21 03:51:16 +00002795 }
2796 }
2797 pLevel->op = OP_VNext;
2798 pLevel->p1 = iCur;
2799 pLevel->p2 = sqlite3VdbeCurrentAddr(v);
drh23d04d52008-12-23 23:56:22 +00002800 sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
drha62bb8d2009-11-23 21:23:45 +00002801 sqlite3ExprCachePop(pParse, 1);
drh111a6a72008-12-21 03:51:16 +00002802 }else
2803#endif /* SQLITE_OMIT_VIRTUALTABLE */
2804
drh7ba39a92013-05-30 17:43:19 +00002805 if( (pLoop->wsFlags & WHERE_IPK)!=0
2806 && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
2807 ){
2808 /* Case 2: We can directly reference a single row using an
drh111a6a72008-12-21 03:51:16 +00002809 ** equality comparison against the ROWID field. Or
2810 ** we reference multiple rows using a "rowid IN (...)"
2811 ** construct.
2812 */
drh7ba39a92013-05-30 17:43:19 +00002813 assert( pLoop->u.btree.nEq==1 );
danielk19771d461462009-04-21 09:02:45 +00002814 iReleaseReg = sqlite3GetTempReg(pParse);
drh4efc9292013-06-06 23:02:03 +00002815 pTerm = pLoop->aLTerm[0];
drh111a6a72008-12-21 03:51:16 +00002816 assert( pTerm!=0 );
2817 assert( pTerm->pExpr!=0 );
drh111a6a72008-12-21 03:51:16 +00002818 assert( omitTable==0 );
drh39759742013-08-02 23:40:45 +00002819 testcase( pTerm->wtFlags & TERM_VIRTUAL );
drh7ba39a92013-05-30 17:43:19 +00002820 iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
drh111a6a72008-12-21 03:51:16 +00002821 addrNxt = pLevel->addrNxt;
danielk19771d461462009-04-21 09:02:45 +00002822 sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
2823 sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
drh459f63e2013-03-06 01:55:27 +00002824 sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
drhceea3322009-04-23 13:22:42 +00002825 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
drh111a6a72008-12-21 03:51:16 +00002826 VdbeComment((v, "pk"));
2827 pLevel->op = OP_Noop;
drh7ba39a92013-05-30 17:43:19 +00002828 }else if( (pLoop->wsFlags & WHERE_IPK)!=0
2829 && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
2830 ){
2831 /* Case 3: We have an inequality comparison against the ROWID field.
drh111a6a72008-12-21 03:51:16 +00002832 */
2833 int testOp = OP_Noop;
2834 int start;
2835 int memEndValue = 0;
2836 WhereTerm *pStart, *pEnd;
2837
2838 assert( omitTable==0 );
drh7ba39a92013-05-30 17:43:19 +00002839 j = 0;
2840 pStart = pEnd = 0;
drh4efc9292013-06-06 23:02:03 +00002841 if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
2842 if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
drh81186b42013-06-18 01:52:41 +00002843 assert( pStart!=0 || pEnd!=0 );
drh111a6a72008-12-21 03:51:16 +00002844 if( bRev ){
2845 pTerm = pStart;
2846 pStart = pEnd;
2847 pEnd = pTerm;
2848 }
2849 if( pStart ){
2850 Expr *pX; /* The expression that defines the start bound */
2851 int r1, rTemp; /* Registers for holding the start boundary */
2852
2853 /* The following constant maps TK_xx codes into corresponding
2854 ** seek opcodes. It depends on a particular ordering of TK_xx
2855 */
2856 const u8 aMoveOp[] = {
2857 /* TK_GT */ OP_SeekGt,
2858 /* TK_LE */ OP_SeekLe,
2859 /* TK_LT */ OP_SeekLt,
2860 /* TK_GE */ OP_SeekGe
2861 };
2862 assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */
2863 assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */
2864 assert( TK_GE==TK_GT+3 ); /* ... is correcct. */
2865
drhb5246e52013-07-08 21:12:57 +00002866 assert( (pStart->wtFlags & TERM_VNULL)==0 );
drh39759742013-08-02 23:40:45 +00002867 testcase( pStart->wtFlags & TERM_VIRTUAL );
drh111a6a72008-12-21 03:51:16 +00002868 pX = pStart->pExpr;
2869 assert( pX!=0 );
drhb5246e52013-07-08 21:12:57 +00002870 testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
drh111a6a72008-12-21 03:51:16 +00002871 r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
2872 sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
2873 VdbeComment((v, "pk"));
2874 sqlite3ExprCacheAffinityChange(pParse, r1, 1);
2875 sqlite3ReleaseTempReg(pParse, rTemp);
2876 disableTerm(pLevel, pStart);
2877 }else{
2878 sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
2879 }
2880 if( pEnd ){
2881 Expr *pX;
2882 pX = pEnd->pExpr;
2883 assert( pX!=0 );
drhb5246e52013-07-08 21:12:57 +00002884 assert( (pEnd->wtFlags & TERM_VNULL)==0 );
2885 testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
drh39759742013-08-02 23:40:45 +00002886 testcase( pEnd->wtFlags & TERM_VIRTUAL );
drh111a6a72008-12-21 03:51:16 +00002887 memEndValue = ++pParse->nMem;
2888 sqlite3ExprCode(pParse, pX->pRight, memEndValue);
2889 if( pX->op==TK_LT || pX->op==TK_GT ){
2890 testOp = bRev ? OP_Le : OP_Ge;
2891 }else{
2892 testOp = bRev ? OP_Lt : OP_Gt;
2893 }
2894 disableTerm(pLevel, pEnd);
2895 }
2896 start = sqlite3VdbeCurrentAddr(v);
2897 pLevel->op = bRev ? OP_Prev : OP_Next;
2898 pLevel->p1 = iCur;
2899 pLevel->p2 = start;
drh81186b42013-06-18 01:52:41 +00002900 assert( pLevel->p5==0 );
danielk19771d461462009-04-21 09:02:45 +00002901 if( testOp!=OP_Noop ){
2902 iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
2903 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
drhceea3322009-04-23 13:22:42 +00002904 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
danielk19771d461462009-04-21 09:02:45 +00002905 sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
2906 sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
drh111a6a72008-12-21 03:51:16 +00002907 }
drh1b0f0262013-05-30 22:27:09 +00002908 }else if( pLoop->wsFlags & WHERE_INDEXED ){
drh7ba39a92013-05-30 17:43:19 +00002909 /* Case 4: A scan using an index.
drh111a6a72008-12-21 03:51:16 +00002910 **
2911 ** The WHERE clause may contain zero or more equality
2912 ** terms ("==" or "IN" operators) that refer to the N
2913 ** left-most columns of the index. It may also contain
2914 ** inequality constraints (>, <, >= or <=) on the indexed
2915 ** column that immediately follows the N equalities. Only
2916 ** the right-most column can be an inequality - the rest must
2917 ** use the "==" and "IN" operators. For example, if the
2918 ** index is on (x,y,z), then the following clauses are all
2919 ** optimized:
2920 **
2921 ** x=5
2922 ** x=5 AND y=10
2923 ** x=5 AND y<10
2924 ** x=5 AND y>5 AND y<10
2925 ** x=5 AND y=5 AND z<=10
2926 **
2927 ** The z<10 term of the following cannot be used, only
2928 ** the x=5 term:
2929 **
2930 ** x=5 AND z<10
2931 **
2932 ** N may be zero if there are inequality constraints.
2933 ** If there are no inequality constraints, then N is at
2934 ** least one.
2935 **
2936 ** This case is also used when there are no WHERE clause
2937 ** constraints but an index is selected anyway, in order
2938 ** to force the output order to conform to an ORDER BY.
2939 */
drh3bb9b932010-08-06 02:10:00 +00002940 static const u8 aStartOp[] = {
drh111a6a72008-12-21 03:51:16 +00002941 0,
2942 0,
2943 OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */
2944 OP_Last, /* 3: (!start_constraints && startEq && bRev) */
2945 OP_SeekGt, /* 4: (start_constraints && !startEq && !bRev) */
2946 OP_SeekLt, /* 5: (start_constraints && !startEq && bRev) */
2947 OP_SeekGe, /* 6: (start_constraints && startEq && !bRev) */
2948 OP_SeekLe /* 7: (start_constraints && startEq && bRev) */
2949 };
drh3bb9b932010-08-06 02:10:00 +00002950 static const u8 aEndOp[] = {
drh111a6a72008-12-21 03:51:16 +00002951 OP_Noop, /* 0: (!end_constraints) */
2952 OP_IdxGE, /* 1: (end_constraints && !bRev) */
2953 OP_IdxLT /* 2: (end_constraints && bRev) */
2954 };
drh7ba39a92013-05-30 17:43:19 +00002955 int nEq = pLoop->u.btree.nEq; /* Number of == or IN terms */
2956 int isMinQuery = 0; /* If this is an optimized SELECT min(x).. */
drh111a6a72008-12-21 03:51:16 +00002957 int regBase; /* Base register holding constraint values */
2958 int r1; /* Temp register */
2959 WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */
2960 WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */
2961 int startEq; /* True if range start uses ==, >= or <= */
2962 int endEq; /* True if range end uses ==, >= or <= */
2963 int start_constraints; /* Start of range is constrained */
2964 int nConstraint; /* Number of constraint terms */
drh3bb9b932010-08-06 02:10:00 +00002965 Index *pIdx; /* The index we will be using */
2966 int iIdxCur; /* The VDBE cursor for the index */
2967 int nExtraReg = 0; /* Number of extra registers needed */
2968 int op; /* Instruction opcode */
dan6ac43392010-06-09 15:47:11 +00002969 char *zStartAff; /* Affinity for start of range constraint */
2970 char *zEndAff; /* Affinity for end of range constraint */
drh111a6a72008-12-21 03:51:16 +00002971
drh7ba39a92013-05-30 17:43:19 +00002972 pIdx = pLoop->u.btree.pIndex;
drh111a6a72008-12-21 03:51:16 +00002973 iIdxCur = pLevel->iIdxCur;
drh111a6a72008-12-21 03:51:16 +00002974
drh111a6a72008-12-21 03:51:16 +00002975 /* If this loop satisfies a sort order (pOrderBy) request that
2976 ** was passed to this function to implement a "SELECT min(x) ..."
2977 ** query, then the caller will only allow the loop to run for
2978 ** a single iteration. This means that the first row returned
2979 ** should not have a NULL value stored in 'x'. If column 'x' is
2980 ** the first one after the nEq equality constraints in the index,
2981 ** this requires some special handling.
2982 */
drh70d18342013-06-06 19:16:33 +00002983 if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
drh4f402f22013-06-11 18:59:38 +00002984 && (pWInfo->bOBSat!=0)
drhbbbdc832013-10-22 18:01:40 +00002985 && (pIdx->nKeyCol>nEq)
drh111a6a72008-12-21 03:51:16 +00002986 ){
2987 /* assert( pOrderBy->nExpr==1 ); */
2988 /* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */
2989 isMinQuery = 1;
drh6df2acd2008-12-28 16:55:25 +00002990 nExtraReg = 1;
drh111a6a72008-12-21 03:51:16 +00002991 }
2992
2993 /* Find any inequality constraint terms for the start and end
2994 ** of the range.
2995 */
drh7ba39a92013-05-30 17:43:19 +00002996 j = nEq;
2997 if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
drh4efc9292013-06-06 23:02:03 +00002998 pRangeStart = pLoop->aLTerm[j++];
drh6df2acd2008-12-28 16:55:25 +00002999 nExtraReg = 1;
drh111a6a72008-12-21 03:51:16 +00003000 }
drh7ba39a92013-05-30 17:43:19 +00003001 if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
drh4efc9292013-06-06 23:02:03 +00003002 pRangeEnd = pLoop->aLTerm[j++];
drh6df2acd2008-12-28 16:55:25 +00003003 nExtraReg = 1;
drh111a6a72008-12-21 03:51:16 +00003004 }
3005
drh6df2acd2008-12-28 16:55:25 +00003006 /* Generate code to evaluate all constraint terms using == or IN
3007 ** and store the values of those terms in an array of registers
3008 ** starting at regBase.
3009 */
drh613ba1e2013-06-15 15:11:45 +00003010 regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
drh6b36e822013-07-30 15:10:32 +00003011 zEndAff = sqlite3DbStrDup(db, zStartAff);
drh6df2acd2008-12-28 16:55:25 +00003012 addrNxt = pLevel->addrNxt;
3013
drh111a6a72008-12-21 03:51:16 +00003014 /* If we are doing a reverse order scan on an ascending index, or
3015 ** a forward order scan on a descending index, interchange the
3016 ** start and end terms (pRangeStart and pRangeEnd).
3017 */
drhbbbdc832013-10-22 18:01:40 +00003018 if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
3019 || (bRev && pIdx->nKeyCol==nEq)
dan0c733f62011-11-16 15:27:09 +00003020 ){
drh111a6a72008-12-21 03:51:16 +00003021 SWAP(WhereTerm *, pRangeEnd, pRangeStart);
3022 }
3023
drh7963b0e2013-06-17 21:37:40 +00003024 testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
3025 testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
3026 testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
3027 testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
drh111a6a72008-12-21 03:51:16 +00003028 startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
3029 endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
3030 start_constraints = pRangeStart || nEq>0;
3031
3032 /* Seek the index cursor to the start of the range. */
3033 nConstraint = nEq;
3034 if( pRangeStart ){
dan69f8bb92009-08-13 19:21:16 +00003035 Expr *pRight = pRangeStart->pExpr->pRight;
3036 sqlite3ExprCode(pParse, pRight, regBase+nEq);
drh534230c2011-01-22 00:10:45 +00003037 if( (pRangeStart->wtFlags & TERM_VNULL)==0 ){
3038 sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
3039 }
dan6ac43392010-06-09 15:47:11 +00003040 if( zStartAff ){
3041 if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
drh039fc322009-11-17 18:31:47 +00003042 /* Since the comparison is to be performed with no conversions
3043 ** applied to the operands, set the affinity to apply to pRight to
3044 ** SQLITE_AFF_NONE. */
dan6ac43392010-06-09 15:47:11 +00003045 zStartAff[nEq] = SQLITE_AFF_NONE;
drh039fc322009-11-17 18:31:47 +00003046 }
dan6ac43392010-06-09 15:47:11 +00003047 if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
3048 zStartAff[nEq] = SQLITE_AFF_NONE;
drh039fc322009-11-17 18:31:47 +00003049 }
3050 }
drh111a6a72008-12-21 03:51:16 +00003051 nConstraint++;
drh39759742013-08-02 23:40:45 +00003052 testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
drh111a6a72008-12-21 03:51:16 +00003053 }else if( isMinQuery ){
3054 sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
3055 nConstraint++;
3056 startEq = 0;
3057 start_constraints = 1;
3058 }
dan6ac43392010-06-09 15:47:11 +00003059 codeApplyAffinity(pParse, regBase, nConstraint, zStartAff);
drh111a6a72008-12-21 03:51:16 +00003060 op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
3061 assert( op!=0 );
3062 testcase( op==OP_Rewind );
3063 testcase( op==OP_Last );
3064 testcase( op==OP_SeekGt );
3065 testcase( op==OP_SeekGe );
3066 testcase( op==OP_SeekLe );
3067 testcase( op==OP_SeekLt );
drh8cff69d2009-11-12 19:59:44 +00003068 sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
drh111a6a72008-12-21 03:51:16 +00003069
3070 /* Load the value for the inequality constraint at the end of the
3071 ** range (if any).
3072 */
3073 nConstraint = nEq;
3074 if( pRangeEnd ){
dan69f8bb92009-08-13 19:21:16 +00003075 Expr *pRight = pRangeEnd->pExpr->pRight;
drhf49f3522009-12-30 14:12:38 +00003076 sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
dan69f8bb92009-08-13 19:21:16 +00003077 sqlite3ExprCode(pParse, pRight, regBase+nEq);
drh534230c2011-01-22 00:10:45 +00003078 if( (pRangeEnd->wtFlags & TERM_VNULL)==0 ){
3079 sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
3080 }
dan6ac43392010-06-09 15:47:11 +00003081 if( zEndAff ){
3082 if( sqlite3CompareAffinity(pRight, zEndAff[nEq])==SQLITE_AFF_NONE){
drh039fc322009-11-17 18:31:47 +00003083 /* Since the comparison is to be performed with no conversions
3084 ** applied to the operands, set the affinity to apply to pRight to
3085 ** SQLITE_AFF_NONE. */
dan6ac43392010-06-09 15:47:11 +00003086 zEndAff[nEq] = SQLITE_AFF_NONE;
drh039fc322009-11-17 18:31:47 +00003087 }
dan6ac43392010-06-09 15:47:11 +00003088 if( sqlite3ExprNeedsNoAffinityChange(pRight, zEndAff[nEq]) ){
3089 zEndAff[nEq] = SQLITE_AFF_NONE;
drh039fc322009-11-17 18:31:47 +00003090 }
3091 }
dan6ac43392010-06-09 15:47:11 +00003092 codeApplyAffinity(pParse, regBase, nEq+1, zEndAff);
drh111a6a72008-12-21 03:51:16 +00003093 nConstraint++;
drh39759742013-08-02 23:40:45 +00003094 testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
drh111a6a72008-12-21 03:51:16 +00003095 }
drh6b36e822013-07-30 15:10:32 +00003096 sqlite3DbFree(db, zStartAff);
3097 sqlite3DbFree(db, zEndAff);
drh111a6a72008-12-21 03:51:16 +00003098
3099 /* Top of the loop body */
3100 pLevel->p2 = sqlite3VdbeCurrentAddr(v);
3101
3102 /* Check if the index cursor is past the end of the range. */
3103 op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
3104 testcase( op==OP_Noop );
3105 testcase( op==OP_IdxGE );
3106 testcase( op==OP_IdxLT );
drh6df2acd2008-12-28 16:55:25 +00003107 if( op!=OP_Noop ){
drh8cff69d2009-11-12 19:59:44 +00003108 sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
drh6df2acd2008-12-28 16:55:25 +00003109 sqlite3VdbeChangeP5(v, endEq!=bRev ?1:0);
3110 }
drh111a6a72008-12-21 03:51:16 +00003111
3112 /* If there are inequality constraints, check that the value
3113 ** of the table column that the inequality contrains is not NULL.
3114 ** If it is, jump to the next iteration of the loop.
3115 */
3116 r1 = sqlite3GetTempReg(pParse);
drh37ca0482013-06-12 17:17:45 +00003117 testcase( pLoop->wsFlags & WHERE_BTM_LIMIT );
3118 testcase( pLoop->wsFlags & WHERE_TOP_LIMIT );
drh7ba39a92013-05-30 17:43:19 +00003119 if( (pLoop->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0 ){
drh111a6a72008-12-21 03:51:16 +00003120 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
3121 sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
3122 }
danielk19771d461462009-04-21 09:02:45 +00003123 sqlite3ReleaseTempReg(pParse, r1);
drh111a6a72008-12-21 03:51:16 +00003124
3125 /* Seek the table cursor, if required */
drh23d04d52008-12-23 23:56:22 +00003126 disableTerm(pLevel, pRangeStart);
3127 disableTerm(pLevel, pRangeEnd);
drh85c1c552013-10-24 00:18:18 +00003128 if( omitTable ){
3129 /* pIdx is a covering index. No need to access the main table. */
3130 }else if( HasRowid(pIdx->pTable) ){
danielk19771d461462009-04-21 09:02:45 +00003131 iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
3132 sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
drhceea3322009-04-23 13:22:42 +00003133 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
danielk19771d461462009-04-21 09:02:45 +00003134 sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg); /* Deferred seek */
drh85c1c552013-10-24 00:18:18 +00003135 }else{
3136 Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
3137 iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol);
3138 for(j=0; j<pPk->nKeyCol; j++){
3139 k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
3140 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j);
3141 }
drh261c02d2013-10-25 14:46:15 +00003142 sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont,
3143 iRowidReg, pPk->nKeyCol);
drh111a6a72008-12-21 03:51:16 +00003144 }
drh111a6a72008-12-21 03:51:16 +00003145
3146 /* Record the instruction used to terminate the loop. Disable
3147 ** WHERE clause terms made redundant by the index range scan.
3148 */
drh7699d1c2013-06-04 12:42:29 +00003149 if( pLoop->wsFlags & WHERE_ONEROW ){
drh95e037b2011-03-09 21:02:31 +00003150 pLevel->op = OP_Noop;
3151 }else if( bRev ){
3152 pLevel->op = OP_Prev;
3153 }else{
3154 pLevel->op = OP_Next;
3155 }
drh111a6a72008-12-21 03:51:16 +00003156 pLevel->p1 = iIdxCur;
drh53cfbe92013-06-13 17:28:22 +00003157 if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
drh3f4d1d12012-09-15 18:45:54 +00003158 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
3159 }else{
3160 assert( pLevel->p5==0 );
3161 }
drhdd5f5a62008-12-23 13:35:23 +00003162 }else
3163
drh23d04d52008-12-23 23:56:22 +00003164#ifndef SQLITE_OMIT_OR_OPTIMIZATION
drh7ba39a92013-05-30 17:43:19 +00003165 if( pLoop->wsFlags & WHERE_MULTI_OR ){
3166 /* Case 5: Two or more separately indexed terms connected by OR
drh111a6a72008-12-21 03:51:16 +00003167 **
3168 ** Example:
3169 **
3170 ** CREATE TABLE t1(a,b,c,d);
3171 ** CREATE INDEX i1 ON t1(a);
3172 ** CREATE INDEX i2 ON t1(b);
3173 ** CREATE INDEX i3 ON t1(c);
3174 **
3175 ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
3176 **
3177 ** In the example, there are three indexed terms connected by OR.
danielk19771d461462009-04-21 09:02:45 +00003178 ** The top of the loop looks like this:
drh111a6a72008-12-21 03:51:16 +00003179 **
drh1b26c7c2009-04-22 02:15:47 +00003180 ** Null 1 # Zero the rowset in reg 1
drh111a6a72008-12-21 03:51:16 +00003181 **
danielk19771d461462009-04-21 09:02:45 +00003182 ** Then, for each indexed term, the following. The arguments to
drh1b26c7c2009-04-22 02:15:47 +00003183 ** RowSetTest are such that the rowid of the current row is inserted
3184 ** into the RowSet. If it is already present, control skips the
danielk19771d461462009-04-21 09:02:45 +00003185 ** Gosub opcode and jumps straight to the code generated by WhereEnd().
drh111a6a72008-12-21 03:51:16 +00003186 **
danielk19771d461462009-04-21 09:02:45 +00003187 ** sqlite3WhereBegin(<term>)
drh1b26c7c2009-04-22 02:15:47 +00003188 ** RowSetTest # Insert rowid into rowset
danielk19771d461462009-04-21 09:02:45 +00003189 ** Gosub 2 A
3190 ** sqlite3WhereEnd()
3191 **
3192 ** Following the above, code to terminate the loop. Label A, the target
3193 ** of the Gosub above, jumps to the instruction right after the Goto.
3194 **
drh1b26c7c2009-04-22 02:15:47 +00003195 ** Null 1 # Zero the rowset in reg 1
danielk19771d461462009-04-21 09:02:45 +00003196 ** Goto B # The loop is finished.
3197 **
3198 ** A: <loop body> # Return data, whatever.
3199 **
3200 ** Return 2 # Jump back to the Gosub
3201 **
3202 ** B: <after the loop>
3203 **
drh111a6a72008-12-21 03:51:16 +00003204 */
drh111a6a72008-12-21 03:51:16 +00003205 WhereClause *pOrWc; /* The OR-clause broken out into subterms */
drhc01a3c12009-12-16 22:10:49 +00003206 SrcList *pOrTab; /* Shortened table list or OR-clause generation */
dan0efb72c2012-08-24 18:44:56 +00003207 Index *pCov = 0; /* Potential covering index (or NULL) */
3208 int iCovCur = pParse->nTab++; /* Cursor used for index scans (if any) */
danielk19771d461462009-04-21 09:02:45 +00003209
3210 int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */
shane85095702009-06-15 16:27:08 +00003211 int regRowset = 0; /* Register for RowSet object */
3212 int regRowid = 0; /* Register holding rowid */
danielk19771d461462009-04-21 09:02:45 +00003213 int iLoopBody = sqlite3VdbeMakeLabel(v); /* Start of loop body */
3214 int iRetInit; /* Address of regReturn init */
drhc01a3c12009-12-16 22:10:49 +00003215 int untestedTerms = 0; /* Some terms not completely tested */
drh8871ef52011-10-07 13:33:10 +00003216 int ii; /* Loop counter */
3217 Expr *pAndExpr = 0; /* An ".. AND (...)" expression */
drh111a6a72008-12-21 03:51:16 +00003218
drh4efc9292013-06-06 23:02:03 +00003219 pTerm = pLoop->aLTerm[0];
drh111a6a72008-12-21 03:51:16 +00003220 assert( pTerm!=0 );
drh7a5bcc02013-01-16 17:08:58 +00003221 assert( pTerm->eOperator & WO_OR );
drh111a6a72008-12-21 03:51:16 +00003222 assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
3223 pOrWc = &pTerm->u.pOrInfo->wc;
drhc01a3c12009-12-16 22:10:49 +00003224 pLevel->op = OP_Return;
3225 pLevel->p1 = regReturn;
drh23d04d52008-12-23 23:56:22 +00003226
danbfca6a42012-08-24 10:52:35 +00003227 /* Set up a new SrcList in pOrTab containing the table being scanned
drhc01a3c12009-12-16 22:10:49 +00003228 ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
3229 ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
3230 */
3231 if( pWInfo->nLevel>1 ){
3232 int nNotReady; /* The number of notReady tables */
3233 struct SrcList_item *origSrc; /* Original list of tables */
3234 nNotReady = pWInfo->nLevel - iLevel - 1;
drh6b36e822013-07-30 15:10:32 +00003235 pOrTab = sqlite3StackAllocRaw(db,
drhc01a3c12009-12-16 22:10:49 +00003236 sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
3237 if( pOrTab==0 ) return notReady;
drhad01d892013-06-19 13:59:49 +00003238 pOrTab->nAlloc = (u8)(nNotReady + 1);
shaneh46aae3c2009-12-31 19:06:23 +00003239 pOrTab->nSrc = pOrTab->nAlloc;
drhc01a3c12009-12-16 22:10:49 +00003240 memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
3241 origSrc = pWInfo->pTabList->a;
3242 for(k=1; k<=nNotReady; k++){
3243 memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
3244 }
3245 }else{
3246 pOrTab = pWInfo->pTabList;
3247 }
danielk19771d461462009-04-21 09:02:45 +00003248
drh1b26c7c2009-04-22 02:15:47 +00003249 /* Initialize the rowset register to contain NULL. An SQL NULL is
3250 ** equivalent to an empty rowset.
danielk19771d461462009-04-21 09:02:45 +00003251 **
3252 ** Also initialize regReturn to contain the address of the instruction
3253 ** immediately following the OP_Return at the bottom of the loop. This
3254 ** is required in a few obscure LEFT JOIN cases where control jumps
3255 ** over the top of the loop into the body of it. In this case the
3256 ** correct response for the end-of-loop code (the OP_Return) is to
3257 ** fall through to the next instruction, just as an OP_Next does if
3258 ** called on an uninitialized cursor.
3259 */
drh70d18342013-06-06 19:16:33 +00003260 if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
drh336a5302009-04-24 15:46:21 +00003261 regRowset = ++pParse->nMem;
3262 regRowid = ++pParse->nMem;
3263 sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
3264 }
danielk19771d461462009-04-21 09:02:45 +00003265 iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
3266
drh8871ef52011-10-07 13:33:10 +00003267 /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y
3268 ** Then for every term xN, evaluate as the subexpression: xN AND z
3269 ** That way, terms in y that are factored into the disjunction will
3270 ** be picked up by the recursive calls to sqlite3WhereBegin() below.
drh331b67c2012-03-09 22:02:08 +00003271 **
3272 ** Actually, each subexpression is converted to "xN AND w" where w is
3273 ** the "interesting" terms of z - terms that did not originate in the
3274 ** ON or USING clause of a LEFT JOIN, and terms that are usable as
3275 ** indices.
drhb3129fa2013-05-09 14:20:11 +00003276 **
3277 ** This optimization also only applies if the (x1 OR x2 OR ...) term
3278 ** is not contained in the ON clause of a LEFT JOIN.
3279 ** See ticket http://www.sqlite.org/src/info/f2369304e4
drh8871ef52011-10-07 13:33:10 +00003280 */
3281 if( pWC->nTerm>1 ){
drh7a484802012-03-16 00:28:11 +00003282 int iTerm;
3283 for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
3284 Expr *pExpr = pWC->a[iTerm].pExpr;
drhaa32e3c2013-07-16 21:31:23 +00003285 if( &pWC->a[iTerm] == pTerm ) continue;
drh331b67c2012-03-09 22:02:08 +00003286 if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
drhaa32e3c2013-07-16 21:31:23 +00003287 if( pWC->a[iTerm].wtFlags & (TERM_ORINFO) ) continue;
drh7a484802012-03-16 00:28:11 +00003288 if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
drh6b36e822013-07-30 15:10:32 +00003289 pExpr = sqlite3ExprDup(db, pExpr, 0);
3290 pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr);
drh331b67c2012-03-09 22:02:08 +00003291 }
3292 if( pAndExpr ){
3293 pAndExpr = sqlite3PExpr(pParse, TK_AND, 0, pAndExpr, 0);
3294 }
drh8871ef52011-10-07 13:33:10 +00003295 }
3296
danielk19771d461462009-04-21 09:02:45 +00003297 for(ii=0; ii<pOrWc->nTerm; ii++){
3298 WhereTerm *pOrTerm = &pOrWc->a[ii];
drh7a5bcc02013-01-16 17:08:58 +00003299 if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
danielk19771d461462009-04-21 09:02:45 +00003300 WhereInfo *pSubWInfo; /* Info for single OR-term scan */
drh8871ef52011-10-07 13:33:10 +00003301 Expr *pOrExpr = pOrTerm->pExpr;
drhb3129fa2013-05-09 14:20:11 +00003302 if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){
drh8871ef52011-10-07 13:33:10 +00003303 pAndExpr->pLeft = pOrExpr;
3304 pOrExpr = pAndExpr;
3305 }
danielk19771d461462009-04-21 09:02:45 +00003306 /* Loop through table entries that match term pOrTerm. */
drh8871ef52011-10-07 13:33:10 +00003307 pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
drh9ef61f42011-10-07 14:40:59 +00003308 WHERE_OMIT_OPEN_CLOSE | WHERE_AND_ONLY |
dan0efb72c2012-08-24 18:44:56 +00003309 WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY, iCovCur);
drh6b36e822013-07-30 15:10:32 +00003310 assert( pSubWInfo || pParse->nErr || db->mallocFailed );
danielk19771d461462009-04-21 09:02:45 +00003311 if( pSubWInfo ){
drh7ba39a92013-05-30 17:43:19 +00003312 WhereLoop *pSubLoop;
dan17c0bc02010-11-09 17:35:19 +00003313 explainOneScan(
dan4a07e3d2010-11-09 14:48:59 +00003314 pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
dan2ce22452010-11-08 19:01:16 +00003315 );
drh70d18342013-06-06 19:16:33 +00003316 if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
drh336a5302009-04-24 15:46:21 +00003317 int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
3318 int r;
3319 r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur,
drha748fdc2012-03-28 01:34:47 +00003320 regRowid, 0);
drh8cff69d2009-11-12 19:59:44 +00003321 sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset,
3322 sqlite3VdbeCurrentAddr(v)+2, r, iSet);
drh336a5302009-04-24 15:46:21 +00003323 }
danielk19771d461462009-04-21 09:02:45 +00003324 sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
3325
drhc01a3c12009-12-16 22:10:49 +00003326 /* The pSubWInfo->untestedTerms flag means that this OR term
3327 ** contained one or more AND term from a notReady table. The
3328 ** terms from the notReady table could not be tested and will
3329 ** need to be tested later.
3330 */
3331 if( pSubWInfo->untestedTerms ) untestedTerms = 1;
3332
danbfca6a42012-08-24 10:52:35 +00003333 /* If all of the OR-connected terms are optimized using the same
3334 ** index, and the index is opened using the same cursor number
3335 ** by each call to sqlite3WhereBegin() made by this loop, it may
3336 ** be possible to use that index as a covering index.
3337 **
3338 ** If the call to sqlite3WhereBegin() above resulted in a scan that
3339 ** uses an index, and this is either the first OR-connected term
3340 ** processed or the index is the same as that used by all previous
dan0efb72c2012-08-24 18:44:56 +00003341 ** terms, set pCov to the candidate covering index. Otherwise, set
3342 ** pCov to NULL to indicate that no candidate covering index will
3343 ** be available.
danbfca6a42012-08-24 10:52:35 +00003344 */
drh7ba39a92013-05-30 17:43:19 +00003345 pSubLoop = pSubWInfo->a[0].pWLoop;
drh986b3872013-06-28 21:12:20 +00003346 assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
drh7ba39a92013-05-30 17:43:19 +00003347 if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
drh7ba39a92013-05-30 17:43:19 +00003348 && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
danbfca6a42012-08-24 10:52:35 +00003349 ){
drh7ba39a92013-05-30 17:43:19 +00003350 assert( pSubWInfo->a[0].iIdxCur==iCovCur );
drh907717f2013-06-04 18:03:22 +00003351 pCov = pSubLoop->u.btree.pIndex;
danbfca6a42012-08-24 10:52:35 +00003352 }else{
3353 pCov = 0;
3354 }
3355
danielk19771d461462009-04-21 09:02:45 +00003356 /* Finish the loop through table entries that match term pOrTerm. */
3357 sqlite3WhereEnd(pSubWInfo);
3358 }
drhdd5f5a62008-12-23 13:35:23 +00003359 }
3360 }
drhd40e2082012-08-24 23:24:15 +00003361 pLevel->u.pCovidx = pCov;
drh90abfd02012-10-09 21:07:23 +00003362 if( pCov ) pLevel->iIdxCur = iCovCur;
drh331b67c2012-03-09 22:02:08 +00003363 if( pAndExpr ){
3364 pAndExpr->pLeft = 0;
drh6b36e822013-07-30 15:10:32 +00003365 sqlite3ExprDelete(db, pAndExpr);
drh331b67c2012-03-09 22:02:08 +00003366 }
danielk19771d461462009-04-21 09:02:45 +00003367 sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
danielk19771d461462009-04-21 09:02:45 +00003368 sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
3369 sqlite3VdbeResolveLabel(v, iLoopBody);
3370
drh6b36e822013-07-30 15:10:32 +00003371 if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab);
drhc01a3c12009-12-16 22:10:49 +00003372 if( !untestedTerms ) disableTerm(pLevel, pTerm);
drhdd5f5a62008-12-23 13:35:23 +00003373 }else
drh23d04d52008-12-23 23:56:22 +00003374#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
drhdd5f5a62008-12-23 13:35:23 +00003375
3376 {
drh7ba39a92013-05-30 17:43:19 +00003377 /* Case 6: There is no usable index. We must do a complete
drh111a6a72008-12-21 03:51:16 +00003378 ** scan of the entire table.
3379 */
drh699b3d42009-02-23 16:52:07 +00003380 static const u8 aStep[] = { OP_Next, OP_Prev };
3381 static const u8 aStart[] = { OP_Rewind, OP_Last };
3382 assert( bRev==0 || bRev==1 );
drh699b3d42009-02-23 16:52:07 +00003383 pLevel->op = aStep[bRev];
drh111a6a72008-12-21 03:51:16 +00003384 pLevel->p1 = iCur;
drh699b3d42009-02-23 16:52:07 +00003385 pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
drh111a6a72008-12-21 03:51:16 +00003386 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
3387 }
drh111a6a72008-12-21 03:51:16 +00003388
3389 /* Insert code to test every subexpression that can be completely
3390 ** computed using the current set of tables.
3391 */
drh111a6a72008-12-21 03:51:16 +00003392 for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
3393 Expr *pE;
drh39759742013-08-02 23:40:45 +00003394 testcase( pTerm->wtFlags & TERM_VIRTUAL );
drh111a6a72008-12-21 03:51:16 +00003395 testcase( pTerm->wtFlags & TERM_CODED );
3396 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
drh0259bc32013-09-09 19:37:46 +00003397 if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
drhc01a3c12009-12-16 22:10:49 +00003398 testcase( pWInfo->untestedTerms==0
3399 && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
3400 pWInfo->untestedTerms = 1;
3401 continue;
3402 }
drh111a6a72008-12-21 03:51:16 +00003403 pE = pTerm->pExpr;
3404 assert( pE!=0 );
3405 if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
3406 continue;
3407 }
drh111a6a72008-12-21 03:51:16 +00003408 sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
drh111a6a72008-12-21 03:51:16 +00003409 pTerm->wtFlags |= TERM_CODED;
3410 }
3411
drh0c41d222013-04-22 02:39:10 +00003412 /* Insert code to test for implied constraints based on transitivity
3413 ** of the "==" operator.
3414 **
3415 ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
3416 ** and we are coding the t1 loop and the t2 loop has not yet coded,
3417 ** then we cannot use the "t1.a=t2.b" constraint, but we can code
3418 ** the implied "t1.a=123" constraint.
3419 */
3420 for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
drh6b36e822013-07-30 15:10:32 +00003421 Expr *pE, *pEAlt;
drh0c41d222013-04-22 02:39:10 +00003422 WhereTerm *pAlt;
drh0c41d222013-04-22 02:39:10 +00003423 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
3424 if( pTerm->eOperator!=(WO_EQUIV|WO_EQ) ) continue;
3425 if( pTerm->leftCursor!=iCur ) continue;
drhcdc2e432013-07-01 17:27:19 +00003426 if( pLevel->iLeftJoin ) continue;
drh0c41d222013-04-22 02:39:10 +00003427 pE = pTerm->pExpr;
3428 assert( !ExprHasProperty(pE, EP_FromJoin) );
drh0259bc32013-09-09 19:37:46 +00003429 assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
drh0c41d222013-04-22 02:39:10 +00003430 pAlt = findTerm(pWC, iCur, pTerm->u.leftColumn, notReady, WO_EQ|WO_IN, 0);
3431 if( pAlt==0 ) continue;
drh5c10f3b2013-05-01 17:22:38 +00003432 if( pAlt->wtFlags & (TERM_CODED) ) continue;
drh7963b0e2013-06-17 21:37:40 +00003433 testcase( pAlt->eOperator & WO_EQ );
3434 testcase( pAlt->eOperator & WO_IN );
drh0c41d222013-04-22 02:39:10 +00003435 VdbeNoopComment((v, "begin transitive constraint"));
drh6b36e822013-07-30 15:10:32 +00003436 pEAlt = sqlite3StackAllocRaw(db, sizeof(*pEAlt));
3437 if( pEAlt ){
3438 *pEAlt = *pAlt->pExpr;
3439 pEAlt->pLeft = pE->pLeft;
3440 sqlite3ExprIfFalse(pParse, pEAlt, addrCont, SQLITE_JUMPIFNULL);
3441 sqlite3StackFree(db, pEAlt);
3442 }
drh0c41d222013-04-22 02:39:10 +00003443 }
3444
drh111a6a72008-12-21 03:51:16 +00003445 /* For a LEFT OUTER JOIN, generate code that will record the fact that
3446 ** at least one row of the right table has matched the left table.
3447 */
3448 if( pLevel->iLeftJoin ){
3449 pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
3450 sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
3451 VdbeComment((v, "record LEFT JOIN hit"));
drhceea3322009-04-23 13:22:42 +00003452 sqlite3ExprCacheClear(pParse);
drh111a6a72008-12-21 03:51:16 +00003453 for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
drh39759742013-08-02 23:40:45 +00003454 testcase( pTerm->wtFlags & TERM_VIRTUAL );
drh111a6a72008-12-21 03:51:16 +00003455 testcase( pTerm->wtFlags & TERM_CODED );
3456 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
drh0259bc32013-09-09 19:37:46 +00003457 if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
drhb057e562009-12-16 23:43:55 +00003458 assert( pWInfo->untestedTerms );
drhc01a3c12009-12-16 22:10:49 +00003459 continue;
3460 }
drh111a6a72008-12-21 03:51:16 +00003461 assert( pTerm->pExpr );
3462 sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
3463 pTerm->wtFlags |= TERM_CODED;
3464 }
3465 }
danielk19771d461462009-04-21 09:02:45 +00003466 sqlite3ReleaseTempReg(pParse, iReleaseReg);
drh23d04d52008-12-23 23:56:22 +00003467
drh0259bc32013-09-09 19:37:46 +00003468 return pLevel->notReady;
drh111a6a72008-12-21 03:51:16 +00003469}
3470
drhf4e9cb02013-10-28 19:59:59 +00003471#if defined(WHERETRACE_ENABLED) && defined(SQLITE_ENABLE_TREE_EXPLAIN)
3472/*
3473** Generate "Explanation" text for a WhereTerm.
3474*/
3475static void whereExplainTerm(Vdbe *v, WhereTerm *pTerm){
3476 char zType[4];
3477 memcpy(zType, "...", 4);
3478 if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V';
3479 if( pTerm->eOperator & WO_EQUIV ) zType[1] = 'E';
3480 if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) zType[2] = 'L';
3481 sqlite3ExplainPrintf(v, "%s ", zType);
drhf4e9cb02013-10-28 19:59:59 +00003482 sqlite3ExplainExpr(v, pTerm->pExpr);
3483}
3484#endif /* WHERETRACE_ENABLED && SQLITE_ENABLE_TREE_EXPLAIN */
3485
3486
drhd15cb172013-05-21 19:23:10 +00003487#ifdef WHERETRACE_ENABLED
drha18f3d22013-05-08 03:05:41 +00003488/*
3489** Print a WhereLoop object for debugging purposes
3490*/
drhc1ba2e72013-10-28 19:03:21 +00003491static void whereLoopPrint(WhereLoop *p, WhereClause *pWC){
3492 WhereInfo *pWInfo = pWC->pWInfo;
drh989578e2013-10-28 14:34:35 +00003493 int nb = 1+(pWInfo->pTabList->nSrc+7)/8;
3494 struct SrcList_item *pItem = pWInfo->pTabList->a + p->iTab;
drha18f3d22013-05-08 03:05:41 +00003495 Table *pTab = pItem->pTab;
drh6457a352013-06-21 00:35:37 +00003496 sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
drha184fb82013-05-08 04:22:59 +00003497 p->iTab, nb, p->maskSelf, nb, p->prereq);
drh6457a352013-06-21 00:35:37 +00003498 sqlite3DebugPrintf(" %12s",
drha18f3d22013-05-08 03:05:41 +00003499 pItem->zAlias ? pItem->zAlias : pTab->zName);
drh5346e952013-05-08 14:14:26 +00003500 if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
drhc1ba2e72013-10-28 19:03:21 +00003501 const char *zName;
3502 if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){
drh319f6772013-05-14 15:31:07 +00003503 if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
3504 int i = sqlite3Strlen30(zName) - 1;
3505 while( zName[i]!='_' ) i--;
3506 zName += i;
3507 }
drh6457a352013-06-21 00:35:37 +00003508 sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq);
drh5346e952013-05-08 14:14:26 +00003509 }else{
drh6457a352013-06-21 00:35:37 +00003510 sqlite3DebugPrintf("%20s","");
drh5346e952013-05-08 14:14:26 +00003511 }
drha18f3d22013-05-08 03:05:41 +00003512 }else{
drh5346e952013-05-08 14:14:26 +00003513 char *z;
3514 if( p->u.vtab.idxStr ){
drh3bd26f02013-05-24 14:52:03 +00003515 z = sqlite3_mprintf("(%d,\"%s\",%x)",
3516 p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
drh5346e952013-05-08 14:14:26 +00003517 }else{
drh3bd26f02013-05-24 14:52:03 +00003518 z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
drh5346e952013-05-08 14:14:26 +00003519 }
drh6457a352013-06-21 00:35:37 +00003520 sqlite3DebugPrintf(" %-19s", z);
drh5346e952013-05-08 14:14:26 +00003521 sqlite3_free(z);
drha18f3d22013-05-08 03:05:41 +00003522 }
drh6457a352013-06-21 00:35:37 +00003523 sqlite3DebugPrintf(" f %04x N %d", p->wsFlags, p->nLTerm);
drhb8a8e8a2013-06-10 19:12:39 +00003524 sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
drh989578e2013-10-28 14:34:35 +00003525#ifdef SQLITE_ENABLE_TREE_EXPLAIN
3526 /* If the 0x100 bit of wheretracing is set, then show all of the constraint
3527 ** expressions in the WhereLoop.aLTerm[] array.
3528 */
3529 if( p->nLTerm && (sqlite3WhereTrace & 0x100)!=0 ){ /* WHERETRACE 0x100 */
3530 int i;
3531 Vdbe *v = pWInfo->pParse->pVdbe;
3532 sqlite3ExplainBegin(v);
3533 for(i=0; i<p->nLTerm; i++){
drhc1ba2e72013-10-28 19:03:21 +00003534 WhereTerm *pTerm = p->aLTerm[i];
drh7afc8b02013-10-28 22:33:36 +00003535 sqlite3ExplainPrintf(v, " (%d) #%-2d ", i+1, (int)(pTerm-pWC->a));
drh989578e2013-10-28 14:34:35 +00003536 sqlite3ExplainPush(v);
drhf4e9cb02013-10-28 19:59:59 +00003537 whereExplainTerm(v, pTerm);
drh989578e2013-10-28 14:34:35 +00003538 sqlite3ExplainPop(v);
3539 sqlite3ExplainNL(v);
3540 }
drh989578e2013-10-28 14:34:35 +00003541 sqlite3ExplainFinish(v);
drhc1ba2e72013-10-28 19:03:21 +00003542 sqlite3DebugPrintf("%s", sqlite3VdbeExplanation(v));
drh989578e2013-10-28 14:34:35 +00003543 }
3544#endif
drha18f3d22013-05-08 03:05:41 +00003545}
3546#endif
3547
drhf1b5f5b2013-05-02 00:15:01 +00003548/*
drh4efc9292013-06-06 23:02:03 +00003549** Convert bulk memory into a valid WhereLoop that can be passed
3550** to whereLoopClear harmlessly.
drh5346e952013-05-08 14:14:26 +00003551*/
drh4efc9292013-06-06 23:02:03 +00003552static void whereLoopInit(WhereLoop *p){
3553 p->aLTerm = p->aLTermSpace;
3554 p->nLTerm = 0;
3555 p->nLSlot = ArraySize(p->aLTermSpace);
3556 p->wsFlags = 0;
3557}
3558
3559/*
3560** Clear the WhereLoop.u union. Leave WhereLoop.pLTerm intact.
3561*/
3562static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
drh986b3872013-06-28 21:12:20 +00003563 if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){
drh13e11b42013-06-06 23:44:25 +00003564 if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
3565 sqlite3_free(p->u.vtab.idxStr);
3566 p->u.vtab.needFree = 0;
3567 p->u.vtab.idxStr = 0;
drh986b3872013-06-28 21:12:20 +00003568 }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){
drh13e11b42013-06-06 23:44:25 +00003569 sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
drh2ec2fb22013-11-06 19:59:23 +00003570 sqlite3KeyInfoUnref(p->u.btree.pIndex->pKeyInfo);
drh13e11b42013-06-06 23:44:25 +00003571 sqlite3DbFree(db, p->u.btree.pIndex);
3572 p->u.btree.pIndex = 0;
3573 }
drh5346e952013-05-08 14:14:26 +00003574 }
3575}
3576
drh4efc9292013-06-06 23:02:03 +00003577/*
3578** Deallocate internal memory used by a WhereLoop object
3579*/
3580static void whereLoopClear(sqlite3 *db, WhereLoop *p){
3581 if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
3582 whereLoopClearUnion(db, p);
3583 whereLoopInit(p);
3584}
3585
3586/*
3587** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
3588*/
3589static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
3590 WhereTerm **paNew;
3591 if( p->nLSlot>=n ) return SQLITE_OK;
3592 n = (n+7)&~7;
3593 paNew = sqlite3DbMallocRaw(db, sizeof(p->aLTerm[0])*n);
3594 if( paNew==0 ) return SQLITE_NOMEM;
3595 memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
3596 if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
3597 p->aLTerm = paNew;
3598 p->nLSlot = n;
3599 return SQLITE_OK;
3600}
3601
3602/*
3603** Transfer content from the second pLoop into the first.
3604*/
3605static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
drh4efc9292013-06-06 23:02:03 +00003606 whereLoopClearUnion(db, pTo);
drh0d31dc32013-09-06 00:40:59 +00003607 if( whereLoopResize(db, pTo, pFrom->nLTerm) ){
3608 memset(&pTo->u, 0, sizeof(pTo->u));
3609 return SQLITE_NOMEM;
3610 }
drha2014152013-06-07 00:29:23 +00003611 memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
3612 memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
drh4efc9292013-06-06 23:02:03 +00003613 if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
3614 pFrom->u.vtab.needFree = 0;
drh986b3872013-06-28 21:12:20 +00003615 }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){
drh4efc9292013-06-06 23:02:03 +00003616 pFrom->u.btree.pIndex = 0;
3617 }
3618 return SQLITE_OK;
3619}
3620
drh5346e952013-05-08 14:14:26 +00003621/*
drhf1b5f5b2013-05-02 00:15:01 +00003622** Delete a WhereLoop object
3623*/
3624static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
drh5346e952013-05-08 14:14:26 +00003625 whereLoopClear(db, p);
drhf1b5f5b2013-05-02 00:15:01 +00003626 sqlite3DbFree(db, p);
3627}
drh84bfda42005-07-15 13:05:21 +00003628
drh9eff6162006-06-12 21:59:13 +00003629/*
3630** Free a WhereInfo structure
3631*/
drh10fe8402008-10-11 16:47:35 +00003632static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
drh52ff8ea2010-04-08 14:15:56 +00003633 if( ALWAYS(pWInfo) ){
drh70d18342013-06-06 19:16:33 +00003634 whereClauseClear(&pWInfo->sWC);
drhf1b5f5b2013-05-02 00:15:01 +00003635 while( pWInfo->pLoops ){
3636 WhereLoop *p = pWInfo->pLoops;
3637 pWInfo->pLoops = p->pNextLoop;
3638 whereLoopDelete(db, p);
3639 }
drh633e6d52008-07-28 19:34:53 +00003640 sqlite3DbFree(db, pWInfo);
drh9eff6162006-06-12 21:59:13 +00003641 }
3642}
3643
drhf1b5f5b2013-05-02 00:15:01 +00003644/*
3645** Insert or replace a WhereLoop entry using the template supplied.
3646**
3647** An existing WhereLoop entry might be overwritten if the new template
3648** is better and has fewer dependencies. Or the template will be ignored
3649** and no insert will occur if an existing WhereLoop is faster and has
3650** fewer dependencies than the template. Otherwise a new WhereLoop is
drhd044d202013-05-31 12:43:55 +00003651** added based on the template.
drh23f98da2013-05-21 15:52:07 +00003652**
drhaa32e3c2013-07-16 21:31:23 +00003653** If pBuilder->pOrSet is not NULL then we only care about only the
3654** prerequisites and rRun and nOut costs of the N best loops. That
3655** information is gathered in the pBuilder->pOrSet object. This special
3656** processing mode is used only for OR clause processing.
drh23f98da2013-05-21 15:52:07 +00003657**
drhaa32e3c2013-07-16 21:31:23 +00003658** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
drh23f98da2013-05-21 15:52:07 +00003659** still might overwrite similar loops with the new template if the
3660** template is better. Loops may be overwritten if the following
3661** conditions are met:
3662**
3663** (1) They have the same iTab.
3664** (2) They have the same iSortIdx.
3665** (3) The template has same or fewer dependencies than the current loop
3666** (4) The template has the same or lower cost than the current loop
drhd044d202013-05-31 12:43:55 +00003667** (5) The template uses more terms of the same index but has no additional
3668** dependencies
drhf1b5f5b2013-05-02 00:15:01 +00003669*/
drhcf8fa7a2013-05-10 20:26:22 +00003670static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
drh4efc9292013-06-06 23:02:03 +00003671 WhereLoop **ppPrev, *p, *pNext = 0;
drhcf8fa7a2013-05-10 20:26:22 +00003672 WhereInfo *pWInfo = pBuilder->pWInfo;
drh70d18342013-06-06 19:16:33 +00003673 sqlite3 *db = pWInfo->pParse->db;
drhcf8fa7a2013-05-10 20:26:22 +00003674
drhaa32e3c2013-07-16 21:31:23 +00003675 /* If pBuilder->pOrSet is defined, then only keep track of the costs
3676 ** and prereqs.
drh23f98da2013-05-21 15:52:07 +00003677 */
drhaa32e3c2013-07-16 21:31:23 +00003678 if( pBuilder->pOrSet!=0 ){
3679#if WHERETRACE_ENABLED
3680 u16 n = pBuilder->pOrSet->n;
3681 int x =
3682#endif
3683 whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
3684 pTemplate->nOut);
drh989578e2013-10-28 14:34:35 +00003685#if WHERETRACE_ENABLED /* 0x8 */
drhae70cf12013-05-31 15:18:46 +00003686 if( sqlite3WhereTrace & 0x8 ){
drhaa32e3c2013-07-16 21:31:23 +00003687 sqlite3DebugPrintf(x?" or-%d: ":" or-X: ", n);
drhc1ba2e72013-10-28 19:03:21 +00003688 whereLoopPrint(pTemplate, pBuilder->pWC);
drhae70cf12013-05-31 15:18:46 +00003689 }
3690#endif
drhcf8fa7a2013-05-10 20:26:22 +00003691 return SQLITE_OK;
3692 }
drhf1b5f5b2013-05-02 00:15:01 +00003693
3694 /* Search for an existing WhereLoop to overwrite, or which takes
3695 ** priority over pTemplate.
3696 */
3697 for(ppPrev=&pWInfo->pLoops, p=*ppPrev; p; ppPrev=&p->pNextLoop, p=*ppPrev){
drhdbb80232013-06-19 12:34:13 +00003698 if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
3699 /* If either the iTab or iSortIdx values for two WhereLoop are different
3700 ** then those WhereLoops need to be considered separately. Neither is
3701 ** a candidate to replace the other. */
3702 continue;
3703 }
3704 /* In the current implementation, the rSetup value is either zero
3705 ** or the cost of building an automatic index (NlogN) and the NlogN
3706 ** is the same for compatible WhereLoops. */
3707 assert( p->rSetup==0 || pTemplate->rSetup==0
3708 || p->rSetup==pTemplate->rSetup );
3709
3710 /* whereLoopAddBtree() always generates and inserts the automatic index
3711 ** case first. Hence compatible candidate WhereLoops never have a larger
3712 ** rSetup. Call this SETUP-INVARIANT */
3713 assert( p->rSetup>=pTemplate->rSetup );
3714
drhf1b5f5b2013-05-02 00:15:01 +00003715 if( (p->prereq & pTemplate->prereq)==p->prereq
drhf1b5f5b2013-05-02 00:15:01 +00003716 && p->rSetup<=pTemplate->rSetup
3717 && p->rRun<=pTemplate->rRun
drhf46af732013-08-30 17:35:44 +00003718 && p->nOut<=pTemplate->nOut
drhf1b5f5b2013-05-02 00:15:01 +00003719 ){
drh4a5acf82013-06-18 20:06:23 +00003720 /* This branch taken when p is equal or better than pTemplate in
drhe56dd3a2013-08-30 17:50:35 +00003721 ** all of (1) dependencies (2) setup-cost, (3) run-cost, and
drhf46af732013-08-30 17:35:44 +00003722 ** (4) number of output rows. */
drhdbb80232013-06-19 12:34:13 +00003723 assert( p->rSetup==pTemplate->rSetup );
drh05db3c72013-09-02 20:22:18 +00003724 if( p->prereq==pTemplate->prereq
3725 && p->nLTerm<pTemplate->nLTerm
drhadd5ce32013-09-07 00:29:06 +00003726 && (p->wsFlags & pTemplate->wsFlags & WHERE_INDEXED)!=0
3727 && (p->u.btree.pIndex==pTemplate->u.btree.pIndex
drhabfa6d52013-09-11 03:53:22 +00003728 || pTemplate->rRun+p->nLTerm<=p->rRun+pTemplate->nLTerm)
drhcd0f4072013-06-05 12:47:59 +00003729 ){
3730 /* Overwrite an existing WhereLoop with an similar one that uses
3731 ** more terms of the index */
3732 pNext = p->pNextLoop;
drhcd0f4072013-06-05 12:47:59 +00003733 break;
3734 }else{
3735 /* pTemplate is not helpful.
3736 ** Return without changing or adding anything */
3737 goto whereLoopInsert_noop;
3738 }
drhf1b5f5b2013-05-02 00:15:01 +00003739 }
3740 if( (p->prereq & pTemplate->prereq)==pTemplate->prereq
drhf1b5f5b2013-05-02 00:15:01 +00003741 && p->rRun>=pTemplate->rRun
drhf46af732013-08-30 17:35:44 +00003742 && p->nOut>=pTemplate->nOut
drhf1b5f5b2013-05-02 00:15:01 +00003743 ){
drh4a5acf82013-06-18 20:06:23 +00003744 /* Overwrite an existing WhereLoop with a better one: one that is
drhe56dd3a2013-08-30 17:50:35 +00003745 ** better at one of (1) dependencies, (2) setup-cost, (3) run-cost
drhf46af732013-08-30 17:35:44 +00003746 ** or (4) number of output rows, and is no worse in any of those
3747 ** categories. */
drhadd5ce32013-09-07 00:29:06 +00003748 assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */
drh43fe25f2013-05-07 23:06:23 +00003749 pNext = p->pNextLoop;
drhf1b5f5b2013-05-02 00:15:01 +00003750 break;
3751 }
3752 }
3753
3754 /* If we reach this point it means that either p[] should be overwritten
3755 ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
3756 ** WhereLoop and insert it.
3757 */
drh989578e2013-10-28 14:34:35 +00003758#if WHERETRACE_ENABLED /* 0x8 */
drhae70cf12013-05-31 15:18:46 +00003759 if( sqlite3WhereTrace & 0x8 ){
3760 if( p!=0 ){
3761 sqlite3DebugPrintf("ins-del: ");
drhc1ba2e72013-10-28 19:03:21 +00003762 whereLoopPrint(p, pBuilder->pWC);
drhae70cf12013-05-31 15:18:46 +00003763 }
3764 sqlite3DebugPrintf("ins-new: ");
drhc1ba2e72013-10-28 19:03:21 +00003765 whereLoopPrint(pTemplate, pBuilder->pWC);
drhae70cf12013-05-31 15:18:46 +00003766 }
3767#endif
drhf1b5f5b2013-05-02 00:15:01 +00003768 if( p==0 ){
drh4efc9292013-06-06 23:02:03 +00003769 p = sqlite3DbMallocRaw(db, sizeof(WhereLoop));
drhf1b5f5b2013-05-02 00:15:01 +00003770 if( p==0 ) return SQLITE_NOMEM;
drh4efc9292013-06-06 23:02:03 +00003771 whereLoopInit(p);
drhf1b5f5b2013-05-02 00:15:01 +00003772 }
drh4efc9292013-06-06 23:02:03 +00003773 whereLoopXfer(db, p, pTemplate);
drh43fe25f2013-05-07 23:06:23 +00003774 p->pNextLoop = pNext;
3775 *ppPrev = p;
drh5346e952013-05-08 14:14:26 +00003776 if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
drhef866372013-05-22 20:49:02 +00003777 Index *pIndex = p->u.btree.pIndex;
3778 if( pIndex && pIndex->tnum==0 ){
drhcf8fa7a2013-05-10 20:26:22 +00003779 p->u.btree.pIndex = 0;
3780 }
drh5346e952013-05-08 14:14:26 +00003781 }
drhf1b5f5b2013-05-02 00:15:01 +00003782 return SQLITE_OK;
drhae70cf12013-05-31 15:18:46 +00003783
3784 /* Jump here if the insert is a no-op */
3785whereLoopInsert_noop:
drh989578e2013-10-28 14:34:35 +00003786#if WHERETRACE_ENABLED /* 0x8 */
drhae70cf12013-05-31 15:18:46 +00003787 if( sqlite3WhereTrace & 0x8 ){
drhaa32e3c2013-07-16 21:31:23 +00003788 sqlite3DebugPrintf("ins-noop: ");
drhc1ba2e72013-10-28 19:03:21 +00003789 whereLoopPrint(pTemplate, pBuilder->pWC);
drhae70cf12013-05-31 15:18:46 +00003790 }
3791#endif
3792 return SQLITE_OK;
drhf1b5f5b2013-05-02 00:15:01 +00003793}
3794
3795/*
drhcca9f3d2013-09-06 15:23:29 +00003796** Adjust the WhereLoop.nOut value downward to account for terms of the
3797** WHERE clause that reference the loop but which are not used by an
3798** index.
3799**
3800** In the current implementation, the first extra WHERE clause term reduces
3801** the number of output rows by a factor of 10 and each additional term
3802** reduces the number of output rows by sqrt(2).
3803*/
drh4f991892013-10-11 15:05:05 +00003804static void whereLoopOutputAdjust(WhereClause *pWC, WhereLoop *pLoop){
drh7d9e7d82013-09-11 17:39:09 +00003805 WhereTerm *pTerm, *pX;
drhcca9f3d2013-09-06 15:23:29 +00003806 Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf);
drh7d9e7d82013-09-11 17:39:09 +00003807 int i, j;
drhadd5ce32013-09-07 00:29:06 +00003808
3809 if( !OptimizationEnabled(pWC->pWInfo->pParse->db, SQLITE_AdjustOutEst) ){
3810 return;
3811 }
drhcca9f3d2013-09-06 15:23:29 +00003812 for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){
drh7d9e7d82013-09-11 17:39:09 +00003813 if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break;
drhcca9f3d2013-09-06 15:23:29 +00003814 if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;
3815 if( (pTerm->prereqAll & notAllowed)!=0 ) continue;
drh7d9e7d82013-09-11 17:39:09 +00003816 for(j=pLoop->nLTerm-1; j>=0; j--){
3817 pX = pLoop->aLTerm[j];
3818 if( pX==pTerm ) break;
3819 if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break;
3820 }
3821 if( j<0 ) pLoop->nOut += pTerm->truthProb;
drhcca9f3d2013-09-06 15:23:29 +00003822 }
drhcca9f3d2013-09-06 15:23:29 +00003823}
3824
3825/*
drh5346e952013-05-08 14:14:26 +00003826** We have so far matched pBuilder->pNew->u.btree.nEq terms of the index pIndex.
drh1c8148f2013-05-04 20:25:23 +00003827** Try to match one more.
3828**
3829** If pProbe->tnum==0, that means pIndex is a fake index used for the
3830** INTEGER PRIMARY KEY.
3831*/
drh5346e952013-05-08 14:14:26 +00003832static int whereLoopAddBtreeIndex(
drh1c8148f2013-05-04 20:25:23 +00003833 WhereLoopBuilder *pBuilder, /* The WhereLoop factory */
3834 struct SrcList_item *pSrc, /* FROM clause term being analyzed */
3835 Index *pProbe, /* An index on pSrc */
drhbf539c42013-10-05 18:16:02 +00003836 LogEst nInMul /* log(Number of iterations due to IN) */
drh1c8148f2013-05-04 20:25:23 +00003837){
drh70d18342013-06-06 19:16:33 +00003838 WhereInfo *pWInfo = pBuilder->pWInfo; /* WHERE analyse context */
3839 Parse *pParse = pWInfo->pParse; /* Parsing context */
3840 sqlite3 *db = pParse->db; /* Database connection malloc context */
drh1c8148f2013-05-04 20:25:23 +00003841 WhereLoop *pNew; /* Template WhereLoop under construction */
3842 WhereTerm *pTerm; /* A WhereTerm under consideration */
drh43fe25f2013-05-07 23:06:23 +00003843 int opMask; /* Valid operators for constraints */
drh1c8148f2013-05-04 20:25:23 +00003844 WhereScan scan; /* Iterator for WHERE terms */
drh4efc9292013-06-06 23:02:03 +00003845 Bitmask saved_prereq; /* Original value of pNew->prereq */
3846 u16 saved_nLTerm; /* Original value of pNew->nLTerm */
3847 int saved_nEq; /* Original value of pNew->u.btree.nEq */
3848 u32 saved_wsFlags; /* Original value of pNew->wsFlags */
drhbf539c42013-10-05 18:16:02 +00003849 LogEst saved_nOut; /* Original value of pNew->nOut */
drha18f3d22013-05-08 03:05:41 +00003850 int iCol; /* Index of the column in the table */
drh5346e952013-05-08 14:14:26 +00003851 int rc = SQLITE_OK; /* Return code */
drhbf539c42013-10-05 18:16:02 +00003852 LogEst nRowEst; /* Estimated index selectivity */
3853 LogEst rLogSize; /* Logarithm of table size */
drhc7f0d222013-06-19 03:27:12 +00003854 WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
drh1c8148f2013-05-04 20:25:23 +00003855
drh1c8148f2013-05-04 20:25:23 +00003856 pNew = pBuilder->pNew;
drh5346e952013-05-08 14:14:26 +00003857 if( db->mallocFailed ) return SQLITE_NOMEM;
drh1c8148f2013-05-04 20:25:23 +00003858
drh5346e952013-05-08 14:14:26 +00003859 assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
drh43fe25f2013-05-07 23:06:23 +00003860 assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
3861 if( pNew->wsFlags & WHERE_BTM_LIMIT ){
3862 opMask = WO_LT|WO_LE;
3863 }else if( pProbe->tnum<=0 || (pSrc->jointype & JT_LEFT)!=0 ){
3864 opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE;
drh1c8148f2013-05-04 20:25:23 +00003865 }else{
drh43fe25f2013-05-07 23:06:23 +00003866 opMask = WO_EQ|WO_IN|WO_ISNULL|WO_GT|WO_GE|WO_LT|WO_LE;
drh1c8148f2013-05-04 20:25:23 +00003867 }
drhef866372013-05-22 20:49:02 +00003868 if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
drh1c8148f2013-05-04 20:25:23 +00003869
drhbbbdc832013-10-22 18:01:40 +00003870 assert( pNew->u.btree.nEq<=pProbe->nKeyCol );
3871 if( pNew->u.btree.nEq < pProbe->nKeyCol ){
drh0f133a42013-05-22 17:01:17 +00003872 iCol = pProbe->aiColumn[pNew->u.btree.nEq];
drhbf539c42013-10-05 18:16:02 +00003873 nRowEst = sqlite3LogEst(pProbe->aiRowEst[pNew->u.btree.nEq+1]);
drhc7f0d222013-06-19 03:27:12 +00003874 if( nRowEst==0 && pProbe->onError==OE_None ) nRowEst = 1;
drh0f133a42013-05-22 17:01:17 +00003875 }else{
3876 iCol = -1;
drhb8a8e8a2013-06-10 19:12:39 +00003877 nRowEst = 0;
drh0f133a42013-05-22 17:01:17 +00003878 }
drha18f3d22013-05-08 03:05:41 +00003879 pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, iCol,
drh0f133a42013-05-22 17:01:17 +00003880 opMask, pProbe);
drh4efc9292013-06-06 23:02:03 +00003881 saved_nEq = pNew->u.btree.nEq;
3882 saved_nLTerm = pNew->nLTerm;
3883 saved_wsFlags = pNew->wsFlags;
3884 saved_prereq = pNew->prereq;
3885 saved_nOut = pNew->nOut;
drhb8a8e8a2013-06-10 19:12:39 +00003886 pNew->rSetup = 0;
drhbf539c42013-10-05 18:16:02 +00003887 rLogSize = estLog(sqlite3LogEst(pProbe->aiRowEst[0]));
drh5346e952013-05-08 14:14:26 +00003888 for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
drhb8a8e8a2013-06-10 19:12:39 +00003889 int nIn = 0;
drh1435a9a2013-08-27 23:15:44 +00003890#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
dan7a419232013-08-06 20:01:43 +00003891 int nRecValid = pBuilder->nRecValid;
drhb5246e52013-07-08 21:12:57 +00003892#endif
dan8bff07a2013-08-29 14:56:14 +00003893 if( (pTerm->eOperator==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)
3894 && (iCol<0 || pSrc->pTab->aCol[iCol].notNull)
3895 ){
3896 continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */
3897 }
dan7a419232013-08-06 20:01:43 +00003898 if( pTerm->prereqRight & pNew->maskSelf ) continue;
3899
danad45ed72013-08-08 12:21:32 +00003900 assert( pNew->nOut==saved_nOut );
3901
drh4efc9292013-06-06 23:02:03 +00003902 pNew->wsFlags = saved_wsFlags;
3903 pNew->u.btree.nEq = saved_nEq;
3904 pNew->nLTerm = saved_nLTerm;
3905 if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
3906 pNew->aLTerm[pNew->nLTerm++] = pTerm;
3907 pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
drhe1e2e9a2013-06-13 15:16:53 +00003908 pNew->rRun = rLogSize; /* Baseline cost is log2(N). Adjustments below */
drha18f3d22013-05-08 03:05:41 +00003909 if( pTerm->eOperator & WO_IN ){
3910 Expr *pExpr = pTerm->pExpr;
3911 pNew->wsFlags |= WHERE_COLUMN_IN;
3912 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
drhe1e2e9a2013-06-13 15:16:53 +00003913 /* "x IN (SELECT ...)": TUNING: the SELECT returns 25 rows */
drhbf539c42013-10-05 18:16:02 +00003914 nIn = 46; assert( 46==sqlite3LogEst(25) );
drha18f3d22013-05-08 03:05:41 +00003915 }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
3916 /* "x IN (value, value, ...)" */
drhbf539c42013-10-05 18:16:02 +00003917 nIn = sqlite3LogEst(pExpr->x.pList->nExpr);
drhf1645f02013-05-07 19:44:38 +00003918 }
drhb8a8e8a2013-06-10 19:12:39 +00003919 pNew->rRun += nIn;
drh5346e952013-05-08 14:14:26 +00003920 pNew->u.btree.nEq++;
drhb8a8e8a2013-06-10 19:12:39 +00003921 pNew->nOut = nRowEst + nInMul + nIn;
drh6fa978d2013-05-30 19:29:19 +00003922 }else if( pTerm->eOperator & (WO_EQ) ){
drh7699d1c2013-06-04 12:42:29 +00003923 assert( (pNew->wsFlags & (WHERE_COLUMN_NULL|WHERE_COLUMN_IN))!=0
drhb8a8e8a2013-06-10 19:12:39 +00003924 || nInMul==0 );
drha18f3d22013-05-08 03:05:41 +00003925 pNew->wsFlags |= WHERE_COLUMN_EQ;
drh7699d1c2013-06-04 12:42:29 +00003926 if( iCol<0
drhb8a8e8a2013-06-10 19:12:39 +00003927 || (pProbe->onError!=OE_None && nInMul==0
drhbbbdc832013-10-22 18:01:40 +00003928 && pNew->u.btree.nEq==pProbe->nKeyCol-1)
drh21f7ff72013-06-03 15:07:23 +00003929 ){
drh4a5acf82013-06-18 20:06:23 +00003930 assert( (pNew->wsFlags & WHERE_COLUMN_IN)==0 || iCol<0 );
drh7699d1c2013-06-04 12:42:29 +00003931 pNew->wsFlags |= WHERE_ONEROW;
drh21f7ff72013-06-03 15:07:23 +00003932 }
drh5346e952013-05-08 14:14:26 +00003933 pNew->u.btree.nEq++;
drhb8a8e8a2013-06-10 19:12:39 +00003934 pNew->nOut = nRowEst + nInMul;
drh6fa978d2013-05-30 19:29:19 +00003935 }else if( pTerm->eOperator & (WO_ISNULL) ){
3936 pNew->wsFlags |= WHERE_COLUMN_NULL;
3937 pNew->u.btree.nEq++;
drhe1e2e9a2013-06-13 15:16:53 +00003938 /* TUNING: IS NULL selects 2 rows */
drhbf539c42013-10-05 18:16:02 +00003939 nIn = 10; assert( 10==sqlite3LogEst(2) );
drhb8a8e8a2013-06-10 19:12:39 +00003940 pNew->nOut = nRowEst + nInMul + nIn;
drha18f3d22013-05-08 03:05:41 +00003941 }else if( pTerm->eOperator & (WO_GT|WO_GE) ){
drh7963b0e2013-06-17 21:37:40 +00003942 testcase( pTerm->eOperator & WO_GT );
3943 testcase( pTerm->eOperator & WO_GE );
drha18f3d22013-05-08 03:05:41 +00003944 pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
drh6f2bfad2013-06-03 17:35:22 +00003945 pBtm = pTerm;
3946 pTop = 0;
drh7963b0e2013-06-17 21:37:40 +00003947 }else{
3948 assert( pTerm->eOperator & (WO_LT|WO_LE) );
3949 testcase( pTerm->eOperator & WO_LT );
3950 testcase( pTerm->eOperator & WO_LE );
drha18f3d22013-05-08 03:05:41 +00003951 pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
drh6f2bfad2013-06-03 17:35:22 +00003952 pTop = pTerm;
3953 pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
drh4efc9292013-06-06 23:02:03 +00003954 pNew->aLTerm[pNew->nLTerm-2] : 0;
drh1c8148f2013-05-04 20:25:23 +00003955 }
drh6f2bfad2013-06-03 17:35:22 +00003956 if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
3957 /* Adjust nOut and rRun for STAT3 range values */
dan6cb8d762013-08-08 11:48:57 +00003958 assert( pNew->nOut==saved_nOut );
drh186ad8c2013-10-08 18:40:37 +00003959 whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew);
drh6f2bfad2013-06-03 17:35:22 +00003960 }
drh1435a9a2013-08-27 23:15:44 +00003961#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
dan8ad169a2013-08-12 20:14:04 +00003962 if( nInMul==0
3963 && pProbe->nSample
3964 && pNew->u.btree.nEq<=pProbe->nSampleCol
3965 && OptimizationEnabled(db, SQLITE_Stat3)
3966 ){
dan7a419232013-08-06 20:01:43 +00003967 Expr *pExpr = pTerm->pExpr;
drhb8a8e8a2013-06-10 19:12:39 +00003968 tRowcnt nOut = 0;
drh6f2bfad2013-06-03 17:35:22 +00003969 if( (pTerm->eOperator & (WO_EQ|WO_ISNULL))!=0 ){
drh93ec45d2013-06-17 18:20:48 +00003970 testcase( pTerm->eOperator & WO_EQ );
3971 testcase( pTerm->eOperator & WO_ISNULL );
dan7a419232013-08-06 20:01:43 +00003972 rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut);
drh6f2bfad2013-06-03 17:35:22 +00003973 }else if( (pTerm->eOperator & WO_IN)
dan7a419232013-08-06 20:01:43 +00003974 && !ExprHasProperty(pExpr, EP_xIsSelect) ){
3975 rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut);
drh6f2bfad2013-06-03 17:35:22 +00003976 }
drh82846332013-08-01 17:21:26 +00003977 assert( nOut==0 || rc==SQLITE_OK );
dan6cb8d762013-08-08 11:48:57 +00003978 if( nOut ){
drh4f991892013-10-11 15:05:05 +00003979 pNew->nOut = sqlite3LogEst(nOut);
3980 if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut;
dan6cb8d762013-08-08 11:48:57 +00003981 }
drh6f2bfad2013-06-03 17:35:22 +00003982 }
3983#endif
drhe217efc2013-06-12 03:48:41 +00003984 if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
drheb04de32013-05-10 15:16:30 +00003985 /* Each row involves a step of the index, then a binary search of
3986 ** the main table */
drhbf539c42013-10-05 18:16:02 +00003987 pNew->rRun = sqlite3LogEstAdd(pNew->rRun,rLogSize>27 ? rLogSize-17 : 10);
drheb04de32013-05-10 15:16:30 +00003988 }
drhe217efc2013-06-12 03:48:41 +00003989 /* Step cost for each output row */
drhb50596d2013-10-08 20:42:41 +00003990 pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut);
drh4f991892013-10-11 15:05:05 +00003991 whereLoopOutputAdjust(pBuilder->pWC, pNew);
drhcf8fa7a2013-05-10 20:26:22 +00003992 rc = whereLoopInsert(pBuilder, pNew);
drh5346e952013-05-08 14:14:26 +00003993 if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
drhbbbdc832013-10-22 18:01:40 +00003994 && pNew->u.btree.nEq<(pProbe->nKeyCol + (pProbe->zName!=0))
drh5346e952013-05-08 14:14:26 +00003995 ){
drhb8a8e8a2013-06-10 19:12:39 +00003996 whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
drha18f3d22013-05-08 03:05:41 +00003997 }
danad45ed72013-08-08 12:21:32 +00003998 pNew->nOut = saved_nOut;
drh1435a9a2013-08-27 23:15:44 +00003999#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
dan7a419232013-08-06 20:01:43 +00004000 pBuilder->nRecValid = nRecValid;
dan7a419232013-08-06 20:01:43 +00004001#endif
drh1c8148f2013-05-04 20:25:23 +00004002 }
drh4efc9292013-06-06 23:02:03 +00004003 pNew->prereq = saved_prereq;
4004 pNew->u.btree.nEq = saved_nEq;
4005 pNew->wsFlags = saved_wsFlags;
4006 pNew->nOut = saved_nOut;
4007 pNew->nLTerm = saved_nLTerm;
drh5346e952013-05-08 14:14:26 +00004008 return rc;
drh1c8148f2013-05-04 20:25:23 +00004009}
4010
4011/*
drh23f98da2013-05-21 15:52:07 +00004012** Return True if it is possible that pIndex might be useful in
4013** implementing the ORDER BY clause in pBuilder.
4014**
4015** Return False if pBuilder does not contain an ORDER BY clause or
4016** if there is no way for pIndex to be useful in implementing that
4017** ORDER BY clause.
4018*/
4019static int indexMightHelpWithOrderBy(
4020 WhereLoopBuilder *pBuilder,
4021 Index *pIndex,
4022 int iCursor
4023){
4024 ExprList *pOB;
drh6d381472013-06-13 17:58:08 +00004025 int ii, jj;
drh23f98da2013-05-21 15:52:07 +00004026
drh53cfbe92013-06-13 17:28:22 +00004027 if( pIndex->bUnordered ) return 0;
drh70d18342013-06-06 19:16:33 +00004028 if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
drh23f98da2013-05-21 15:52:07 +00004029 for(ii=0; ii<pOB->nExpr; ii++){
drh45c154a2013-06-03 20:46:35 +00004030 Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr);
drh23f98da2013-05-21 15:52:07 +00004031 if( pExpr->op!=TK_COLUMN ) return 0;
4032 if( pExpr->iTable==iCursor ){
drhbbbdc832013-10-22 18:01:40 +00004033 for(jj=0; jj<pIndex->nKeyCol; jj++){
drh6d381472013-06-13 17:58:08 +00004034 if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
4035 }
drh23f98da2013-05-21 15:52:07 +00004036 }
4037 }
4038 return 0;
4039}
4040
4041/*
drh92a121f2013-06-10 12:15:47 +00004042** Return a bitmask where 1s indicate that the corresponding column of
4043** the table is used by an index. Only the first 63 columns are considered.
4044*/
drhfd5874d2013-06-12 14:52:39 +00004045static Bitmask columnsInIndex(Index *pIdx){
drh92a121f2013-06-10 12:15:47 +00004046 Bitmask m = 0;
4047 int j;
drhec95c442013-10-23 01:57:32 +00004048 for(j=pIdx->nColumn-1; j>=0; j--){
drh92a121f2013-06-10 12:15:47 +00004049 int x = pIdx->aiColumn[j];
drhec95c442013-10-23 01:57:32 +00004050 if( x>=0 ){
4051 testcase( x==BMS-1 );
4052 testcase( x==BMS-2 );
4053 if( x<BMS-1 ) m |= MASKBIT(x);
4054 }
drh92a121f2013-06-10 12:15:47 +00004055 }
4056 return m;
4057}
4058
drh4bd5f732013-07-31 23:22:39 +00004059/* Check to see if a partial index with pPartIndexWhere can be used
4060** in the current query. Return true if it can be and false if not.
4061*/
4062static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere){
4063 int i;
4064 WhereTerm *pTerm;
4065 for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
4066 if( sqlite3ExprImpliesExpr(pTerm->pExpr, pWhere, iTab) ) return 1;
4067 }
4068 return 0;
4069}
drh92a121f2013-06-10 12:15:47 +00004070
4071/*
dan51576f42013-07-02 10:06:15 +00004072** Add all WhereLoop objects for a single table of the join where the table
drh0823c892013-05-11 00:06:23 +00004073** is idenfied by pBuilder->pNew->iTab. That table is guaranteed to be
4074** a b-tree table, not a virtual table.
drhf1b5f5b2013-05-02 00:15:01 +00004075*/
drh5346e952013-05-08 14:14:26 +00004076static int whereLoopAddBtree(
drh1c8148f2013-05-04 20:25:23 +00004077 WhereLoopBuilder *pBuilder, /* WHERE clause information */
drh1c8148f2013-05-04 20:25:23 +00004078 Bitmask mExtra /* Extra prerequesites for using this table */
drhf1b5f5b2013-05-02 00:15:01 +00004079){
drh70d18342013-06-06 19:16:33 +00004080 WhereInfo *pWInfo; /* WHERE analysis context */
drh1c8148f2013-05-04 20:25:23 +00004081 Index *pProbe; /* An index we are evaluating */
drh1c8148f2013-05-04 20:25:23 +00004082 Index sPk; /* A fake index object for the primary key */
4083 tRowcnt aiRowEstPk[2]; /* The aiRowEst[] value for the sPk index */
drhbbbdc832013-10-22 18:01:40 +00004084 i16 aiColumnPk = -1; /* The aColumn[] value for the sPk index */
drh70d18342013-06-06 19:16:33 +00004085 SrcList *pTabList; /* The FROM clause */
drh1c8148f2013-05-04 20:25:23 +00004086 struct SrcList_item *pSrc; /* The FROM clause btree term to add */
drh1c8148f2013-05-04 20:25:23 +00004087 WhereLoop *pNew; /* Template WhereLoop object */
drh5346e952013-05-08 14:14:26 +00004088 int rc = SQLITE_OK; /* Return code */
drhd044d202013-05-31 12:43:55 +00004089 int iSortIdx = 1; /* Index number */
drh23f98da2013-05-21 15:52:07 +00004090 int b; /* A boolean value */
drhbf539c42013-10-05 18:16:02 +00004091 LogEst rSize; /* number of rows in the table */
4092 LogEst rLogSize; /* Logarithm of the number of rows in the table */
drh4bd5f732013-07-31 23:22:39 +00004093 WhereClause *pWC; /* The parsed WHERE clause */
drh3495d202013-10-07 17:32:15 +00004094 Table *pTab; /* Table being queried */
drh23f98da2013-05-21 15:52:07 +00004095
drh1c8148f2013-05-04 20:25:23 +00004096 pNew = pBuilder->pNew;
drh70d18342013-06-06 19:16:33 +00004097 pWInfo = pBuilder->pWInfo;
4098 pTabList = pWInfo->pTabList;
4099 pSrc = pTabList->a + pNew->iTab;
drh3495d202013-10-07 17:32:15 +00004100 pTab = pSrc->pTab;
drh4bd5f732013-07-31 23:22:39 +00004101 pWC = pBuilder->pWC;
drh0823c892013-05-11 00:06:23 +00004102 assert( !IsVirtual(pSrc->pTab) );
drh1c8148f2013-05-04 20:25:23 +00004103
4104 if( pSrc->pIndex ){
4105 /* An INDEXED BY clause specifies a particular index to use */
4106 pProbe = pSrc->pIndex;
drhec95c442013-10-23 01:57:32 +00004107 }else if( !HasRowid(pTab) ){
4108 pProbe = pTab->pIndex;
drh1c8148f2013-05-04 20:25:23 +00004109 }else{
4110 /* There is no INDEXED BY clause. Create a fake Index object in local
4111 ** variable sPk to represent the rowid primary key index. Make this
4112 ** fake index the first in a chain of Index objects with all of the real
4113 ** indices to follow */
4114 Index *pFirst; /* First of real indices on the table */
4115 memset(&sPk, 0, sizeof(Index));
drhbbbdc832013-10-22 18:01:40 +00004116 sPk.nKeyCol = 1;
drh1c8148f2013-05-04 20:25:23 +00004117 sPk.aiColumn = &aiColumnPk;
4118 sPk.aiRowEst = aiRowEstPk;
4119 sPk.onError = OE_Replace;
drh3495d202013-10-07 17:32:15 +00004120 sPk.pTable = pTab;
4121 aiRowEstPk[0] = pTab->nRowEst;
drh1c8148f2013-05-04 20:25:23 +00004122 aiRowEstPk[1] = 1;
4123 pFirst = pSrc->pTab->pIndex;
4124 if( pSrc->notIndexed==0 ){
4125 /* The real indices of the table are only considered if the
4126 ** NOT INDEXED qualifier is omitted from the FROM clause */
4127 sPk.pNext = pFirst;
4128 }
4129 pProbe = &sPk;
4130 }
drh3495d202013-10-07 17:32:15 +00004131 rSize = sqlite3LogEst(pTab->nRowEst);
drheb04de32013-05-10 15:16:30 +00004132 rLogSize = estLog(rSize);
4133
drhfeb56e02013-08-23 17:33:46 +00004134#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
drheb04de32013-05-10 15:16:30 +00004135 /* Automatic indexes */
drhaa32e3c2013-07-16 21:31:23 +00004136 if( !pBuilder->pOrSet
drh4fe425a2013-06-12 17:08:06 +00004137 && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
4138 && pSrc->pIndex==0
drheb04de32013-05-10 15:16:30 +00004139 && !pSrc->viaCoroutine
4140 && !pSrc->notIndexed
drhec95c442013-10-23 01:57:32 +00004141 && HasRowid(pTab)
drheb04de32013-05-10 15:16:30 +00004142 && !pSrc->isCorrelated
4143 ){
4144 /* Generate auto-index WhereLoops */
drheb04de32013-05-10 15:16:30 +00004145 WhereTerm *pTerm;
4146 WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
4147 for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
drh79a13bf2013-05-31 20:28:28 +00004148 if( pTerm->prereqRight & pNew->maskSelf ) continue;
drheb04de32013-05-10 15:16:30 +00004149 if( termCanDriveIndex(pTerm, pSrc, 0) ){
4150 pNew->u.btree.nEq = 1;
drhef866372013-05-22 20:49:02 +00004151 pNew->u.btree.pIndex = 0;
drh4efc9292013-06-06 23:02:03 +00004152 pNew->nLTerm = 1;
4153 pNew->aLTerm[0] = pTerm;
drhe1e2e9a2013-06-13 15:16:53 +00004154 /* TUNING: One-time cost for computing the automatic index is
drh986b3872013-06-28 21:12:20 +00004155 ** approximately 7*N*log2(N) where N is the number of rows in
drhe1e2e9a2013-06-13 15:16:53 +00004156 ** the table being indexed. */
drhbf539c42013-10-05 18:16:02 +00004157 pNew->rSetup = rLogSize + rSize + 28; assert( 28==sqlite3LogEst(7) );
drh986b3872013-06-28 21:12:20 +00004158 /* TUNING: Each index lookup yields 20 rows in the table. This
4159 ** is more than the usual guess of 10 rows, since we have no way
4160 ** of knowning how selective the index will ultimately be. It would
4161 ** not be unreasonable to make this value much larger. */
drhbf539c42013-10-05 18:16:02 +00004162 pNew->nOut = 43; assert( 43==sqlite3LogEst(20) );
drhb50596d2013-10-08 20:42:41 +00004163 pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut);
drh986b3872013-06-28 21:12:20 +00004164 pNew->wsFlags = WHERE_AUTO_INDEX;
drheb04de32013-05-10 15:16:30 +00004165 pNew->prereq = mExtra | pTerm->prereqRight;
drhcf8fa7a2013-05-10 20:26:22 +00004166 rc = whereLoopInsert(pBuilder, pNew);
drheb04de32013-05-10 15:16:30 +00004167 }
4168 }
4169 }
drhfeb56e02013-08-23 17:33:46 +00004170#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
drh1c8148f2013-05-04 20:25:23 +00004171
4172 /* Loop over all indices
4173 */
drh23f98da2013-05-21 15:52:07 +00004174 for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){
drh4bd5f732013-07-31 23:22:39 +00004175 if( pProbe->pPartIdxWhere!=0
4176 && !whereUsablePartialIndex(pNew->iTab, pWC, pProbe->pPartIdxWhere) ){
4177 continue; /* Partial index inappropriate for this query */
4178 }
drh5346e952013-05-08 14:14:26 +00004179 pNew->u.btree.nEq = 0;
drh4efc9292013-06-06 23:02:03 +00004180 pNew->nLTerm = 0;
drh23f98da2013-05-21 15:52:07 +00004181 pNew->iSortIdx = 0;
drhb8a8e8a2013-06-10 19:12:39 +00004182 pNew->rSetup = 0;
drh23f98da2013-05-21 15:52:07 +00004183 pNew->prereq = mExtra;
drh74f91d42013-06-19 18:01:44 +00004184 pNew->nOut = rSize;
drh23f98da2013-05-21 15:52:07 +00004185 pNew->u.btree.pIndex = pProbe;
4186 b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
drh53cfbe92013-06-13 17:28:22 +00004187 /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
4188 assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
drh43fe25f2013-05-07 23:06:23 +00004189 if( pProbe->tnum<=0 ){
4190 /* Integer primary key index */
4191 pNew->wsFlags = WHERE_IPK;
drh23f98da2013-05-21 15:52:07 +00004192
4193 /* Full table scan */
drhd044d202013-05-31 12:43:55 +00004194 pNew->iSortIdx = b ? iSortIdx : 0;
drhe1e2e9a2013-06-13 15:16:53 +00004195 /* TUNING: Cost of full table scan is 3*(N + log2(N)).
drhbf539c42013-10-05 18:16:02 +00004196 ** + The extra 3 factor is to encourage the use of indexed lookups
drhe13e9f52013-10-05 19:18:00 +00004197 ** over full scans. FIXME */
drhb50596d2013-10-08 20:42:41 +00004198 pNew->rRun = sqlite3LogEstAdd(rSize,rLogSize) + 16;
drh4f991892013-10-11 15:05:05 +00004199 whereLoopOutputAdjust(pWC, pNew);
drh23f98da2013-05-21 15:52:07 +00004200 rc = whereLoopInsert(pBuilder, pNew);
drhcca9f3d2013-09-06 15:23:29 +00004201 pNew->nOut = rSize;
drh23f98da2013-05-21 15:52:07 +00004202 if( rc ) break;
drh43fe25f2013-05-07 23:06:23 +00004203 }else{
drhec95c442013-10-23 01:57:32 +00004204 Bitmask m;
4205 if( pProbe->isCovering ){
4206 pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
4207 m = 0;
4208 }else{
4209 m = pSrc->colUsed & ~columnsInIndex(pProbe);
4210 pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
4211 }
drh1c8148f2013-05-04 20:25:23 +00004212
drh23f98da2013-05-21 15:52:07 +00004213 /* Full scan via index */
drh53cfbe92013-06-13 17:28:22 +00004214 if( b
drh702ba9f2013-11-07 21:25:13 +00004215 || !HasRowid(pTab)
drh53cfbe92013-06-13 17:28:22 +00004216 || ( m==0
4217 && pProbe->bUnordered==0
drh702ba9f2013-11-07 21:25:13 +00004218 && (pProbe->szIdxRow<pTab->szTabRow)
drh53cfbe92013-06-13 17:28:22 +00004219 && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
4220 && sqlite3GlobalConfig.bUseCis
4221 && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
4222 )
drhe3b7c922013-06-03 19:17:40 +00004223 ){
drh23f98da2013-05-21 15:52:07 +00004224 pNew->iSortIdx = b ? iSortIdx : 0;
drhe1e2e9a2013-06-13 15:16:53 +00004225 if( m==0 ){
drhd9e3cad2013-10-04 02:36:19 +00004226 /* TUNING: Cost of a covering index scan is K*(N + log2(N)).
drhb50596d2013-10-08 20:42:41 +00004227 ** + The extra factor K of between 1.1 and 3.0 that depends
4228 ** on the relative sizes of the table and the index. K
4229 ** is smaller for smaller indices, thus favoring them.
drhd9e3cad2013-10-04 02:36:19 +00004230 */
drhb50596d2013-10-08 20:42:41 +00004231 pNew->rRun = sqlite3LogEstAdd(rSize,rLogSize) + 1 +
4232 (15*pProbe->szIdxRow)/pTab->szTabRow;
drhe1e2e9a2013-06-13 15:16:53 +00004233 }else{
drhe1e2e9a2013-06-13 15:16:53 +00004234 /* TUNING: Cost of scanning a non-covering index is (N+1)*log2(N)
4235 ** which we will simplify to just N*log2(N) */
4236 pNew->rRun = rSize + rLogSize;
4237 }
drh4f991892013-10-11 15:05:05 +00004238 whereLoopOutputAdjust(pWC, pNew);
drh23f98da2013-05-21 15:52:07 +00004239 rc = whereLoopInsert(pBuilder, pNew);
drhcca9f3d2013-09-06 15:23:29 +00004240 pNew->nOut = rSize;
drh23f98da2013-05-21 15:52:07 +00004241 if( rc ) break;
4242 }
4243 }
dan7a419232013-08-06 20:01:43 +00004244
drhb8a8e8a2013-06-10 19:12:39 +00004245 rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
drh1435a9a2013-08-27 23:15:44 +00004246#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
dan87cd9322013-08-07 15:52:41 +00004247 sqlite3Stat4ProbeFree(pBuilder->pRec);
4248 pBuilder->nRecValid = 0;
4249 pBuilder->pRec = 0;
danddc2d6e2013-08-06 20:15:06 +00004250#endif
drh1c8148f2013-05-04 20:25:23 +00004251
4252 /* If there was an INDEXED BY clause, then only that one index is
4253 ** considered. */
4254 if( pSrc->pIndex ) break;
4255 }
drh5346e952013-05-08 14:14:26 +00004256 return rc;
drhf1b5f5b2013-05-02 00:15:01 +00004257}
4258
drh8636e9c2013-06-11 01:50:08 +00004259#ifndef SQLITE_OMIT_VIRTUALTABLE
drhf1b5f5b2013-05-02 00:15:01 +00004260/*
drh0823c892013-05-11 00:06:23 +00004261** Add all WhereLoop objects for a table of the join identified by
4262** pBuilder->pNew->iTab. That table is guaranteed to be a virtual table.
drhf1b5f5b2013-05-02 00:15:01 +00004263*/
drh5346e952013-05-08 14:14:26 +00004264static int whereLoopAddVirtual(
danff4b23b2013-11-12 12:17:16 +00004265 WhereLoopBuilder *pBuilder, /* WHERE clause information */
4266 Bitmask mExtra
drhf1b5f5b2013-05-02 00:15:01 +00004267){
drh70d18342013-06-06 19:16:33 +00004268 WhereInfo *pWInfo; /* WHERE analysis context */
drh5346e952013-05-08 14:14:26 +00004269 Parse *pParse; /* The parsing context */
4270 WhereClause *pWC; /* The WHERE clause */
4271 struct SrcList_item *pSrc; /* The FROM clause term to search */
4272 Table *pTab;
4273 sqlite3 *db;
4274 sqlite3_index_info *pIdxInfo;
4275 struct sqlite3_index_constraint *pIdxCons;
4276 struct sqlite3_index_constraint_usage *pUsage;
4277 WhereTerm *pTerm;
4278 int i, j;
4279 int iTerm, mxTerm;
drh4efc9292013-06-06 23:02:03 +00004280 int nConstraint;
drh5346e952013-05-08 14:14:26 +00004281 int seenIn = 0; /* True if an IN operator is seen */
4282 int seenVar = 0; /* True if a non-constant constraint is seen */
4283 int iPhase; /* 0: const w/o IN, 1: const, 2: no IN, 2: IN */
4284 WhereLoop *pNew;
drh5346e952013-05-08 14:14:26 +00004285 int rc = SQLITE_OK;
4286
drh70d18342013-06-06 19:16:33 +00004287 pWInfo = pBuilder->pWInfo;
4288 pParse = pWInfo->pParse;
drh5346e952013-05-08 14:14:26 +00004289 db = pParse->db;
4290 pWC = pBuilder->pWC;
drh5346e952013-05-08 14:14:26 +00004291 pNew = pBuilder->pNew;
drh70d18342013-06-06 19:16:33 +00004292 pSrc = &pWInfo->pTabList->a[pNew->iTab];
drhb2a90f02013-05-10 03:30:49 +00004293 pTab = pSrc->pTab;
drh0823c892013-05-11 00:06:23 +00004294 assert( IsVirtual(pTab) );
drhb2a90f02013-05-10 03:30:49 +00004295 pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pBuilder->pOrderBy);
drh5346e952013-05-08 14:14:26 +00004296 if( pIdxInfo==0 ) return SQLITE_NOMEM;
drh5346e952013-05-08 14:14:26 +00004297 pNew->prereq = 0;
drh5346e952013-05-08 14:14:26 +00004298 pNew->rSetup = 0;
4299 pNew->wsFlags = WHERE_VIRTUALTABLE;
drh4efc9292013-06-06 23:02:03 +00004300 pNew->nLTerm = 0;
drh5346e952013-05-08 14:14:26 +00004301 pNew->u.vtab.needFree = 0;
4302 pUsage = pIdxInfo->aConstraintUsage;
drh4efc9292013-06-06 23:02:03 +00004303 nConstraint = pIdxInfo->nConstraint;
drh7963b0e2013-06-17 21:37:40 +00004304 if( whereLoopResize(db, pNew, nConstraint) ){
4305 sqlite3DbFree(db, pIdxInfo);
4306 return SQLITE_NOMEM;
4307 }
drh5346e952013-05-08 14:14:26 +00004308
drh0823c892013-05-11 00:06:23 +00004309 for(iPhase=0; iPhase<=3; iPhase++){
drh5346e952013-05-08 14:14:26 +00004310 if( !seenIn && (iPhase&1)!=0 ){
4311 iPhase++;
4312 if( iPhase>3 ) break;
4313 }
4314 if( !seenVar && iPhase>1 ) break;
4315 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
4316 for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
4317 j = pIdxCons->iTermOffset;
4318 pTerm = &pWC->a[j];
4319 switch( iPhase ){
4320 case 0: /* Constants without IN operator */
4321 pIdxCons->usable = 0;
4322 if( (pTerm->eOperator & WO_IN)!=0 ){
4323 seenIn = 1;
drh7963b0e2013-06-17 21:37:40 +00004324 }
4325 if( pTerm->prereqRight!=0 ){
drh5346e952013-05-08 14:14:26 +00004326 seenVar = 1;
drh7963b0e2013-06-17 21:37:40 +00004327 }else if( (pTerm->eOperator & WO_IN)==0 ){
drh5346e952013-05-08 14:14:26 +00004328 pIdxCons->usable = 1;
4329 }
4330 break;
4331 case 1: /* Constants with IN operators */
4332 assert( seenIn );
4333 pIdxCons->usable = (pTerm->prereqRight==0);
4334 break;
4335 case 2: /* Variables without IN */
4336 assert( seenVar );
4337 pIdxCons->usable = (pTerm->eOperator & WO_IN)==0;
4338 break;
4339 default: /* Variables with IN */
4340 assert( seenVar && seenIn );
4341 pIdxCons->usable = 1;
4342 break;
4343 }
4344 }
4345 memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
4346 if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
4347 pIdxInfo->idxStr = 0;
4348 pIdxInfo->idxNum = 0;
4349 pIdxInfo->needToFreeIdxStr = 0;
4350 pIdxInfo->orderByConsumed = 0;
drh8636e9c2013-06-11 01:50:08 +00004351 pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
dana9f58152013-11-11 19:01:33 +00004352 pIdxInfo->estimatedRows = 25;
drh5346e952013-05-08 14:14:26 +00004353 rc = vtabBestIndex(pParse, pTab, pIdxInfo);
4354 if( rc ) goto whereLoopAddVtab_exit;
4355 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
danff4b23b2013-11-12 12:17:16 +00004356 pNew->prereq = mExtra;
drhc718f1c2013-05-08 20:05:58 +00004357 mxTerm = -1;
drh4efc9292013-06-06 23:02:03 +00004358 assert( pNew->nLSlot>=nConstraint );
4359 for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
drh3bd26f02013-05-24 14:52:03 +00004360 pNew->u.vtab.omitMask = 0;
drh4efc9292013-06-06 23:02:03 +00004361 for(i=0; i<nConstraint; i++, pIdxCons++){
drh5346e952013-05-08 14:14:26 +00004362 if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
4363 j = pIdxCons->iTermOffset;
drh4efc9292013-06-06 23:02:03 +00004364 if( iTerm>=nConstraint
drh5346e952013-05-08 14:14:26 +00004365 || j<0
4366 || j>=pWC->nTerm
drh4efc9292013-06-06 23:02:03 +00004367 || pNew->aLTerm[iTerm]!=0
drh5346e952013-05-08 14:14:26 +00004368 ){
4369 rc = SQLITE_ERROR;
4370 sqlite3ErrorMsg(pParse, "%s.xBestIndex() malfunction", pTab->zName);
4371 goto whereLoopAddVtab_exit;
4372 }
drh7963b0e2013-06-17 21:37:40 +00004373 testcase( iTerm==nConstraint-1 );
4374 testcase( j==0 );
4375 testcase( j==pWC->nTerm-1 );
drh5346e952013-05-08 14:14:26 +00004376 pTerm = &pWC->a[j];
4377 pNew->prereq |= pTerm->prereqRight;
drh4efc9292013-06-06 23:02:03 +00004378 assert( iTerm<pNew->nLSlot );
4379 pNew->aLTerm[iTerm] = pTerm;
drh5346e952013-05-08 14:14:26 +00004380 if( iTerm>mxTerm ) mxTerm = iTerm;
drh7963b0e2013-06-17 21:37:40 +00004381 testcase( iTerm==15 );
4382 testcase( iTerm==16 );
drh52986302013-06-03 16:03:16 +00004383 if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm;
drh5346e952013-05-08 14:14:26 +00004384 if( (pTerm->eOperator & WO_IN)!=0 ){
4385 if( pUsage[i].omit==0 ){
4386 /* Do not attempt to use an IN constraint if the virtual table
4387 ** says that the equivalent EQ constraint cannot be safely omitted.
4388 ** If we do attempt to use such a constraint, some rows might be
4389 ** repeated in the output. */
4390 break;
4391 }
4392 /* A virtual table that is constrained by an IN clause may not
4393 ** consume the ORDER BY clause because (1) the order of IN terms
4394 ** is not necessarily related to the order of output terms and
4395 ** (2) Multiple outputs from a single IN value will not merge
4396 ** together. */
4397 pIdxInfo->orderByConsumed = 0;
4398 }
4399 }
4400 }
drh4efc9292013-06-06 23:02:03 +00004401 if( i>=nConstraint ){
4402 pNew->nLTerm = mxTerm+1;
4403 assert( pNew->nLTerm<=pNew->nLSlot );
drh5346e952013-05-08 14:14:26 +00004404 pNew->u.vtab.idxNum = pIdxInfo->idxNum;
4405 pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
4406 pIdxInfo->needToFreeIdxStr = 0;
4407 pNew->u.vtab.idxStr = pIdxInfo->idxStr;
drh3b1d8082013-06-03 16:56:37 +00004408 pNew->u.vtab.isOrdered = (u8)((pIdxInfo->nOrderBy!=0)
4409 && pIdxInfo->orderByConsumed);
drhb8a8e8a2013-06-10 19:12:39 +00004410 pNew->rSetup = 0;
drhb50596d2013-10-08 20:42:41 +00004411 pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost);
dana9f58152013-11-11 19:01:33 +00004412 pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows);
drhcf8fa7a2013-05-10 20:26:22 +00004413 whereLoopInsert(pBuilder, pNew);
drh5346e952013-05-08 14:14:26 +00004414 if( pNew->u.vtab.needFree ){
4415 sqlite3_free(pNew->u.vtab.idxStr);
4416 pNew->u.vtab.needFree = 0;
4417 }
4418 }
4419 }
4420
4421whereLoopAddVtab_exit:
4422 if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
4423 sqlite3DbFree(db, pIdxInfo);
4424 return rc;
drhf1b5f5b2013-05-02 00:15:01 +00004425}
drh8636e9c2013-06-11 01:50:08 +00004426#endif /* SQLITE_OMIT_VIRTUALTABLE */
drhf1b5f5b2013-05-02 00:15:01 +00004427
4428/*
drhcf8fa7a2013-05-10 20:26:22 +00004429** Add WhereLoop entries to handle OR terms. This works for either
4430** btrees or virtual tables.
4431*/
4432static int whereLoopAddOr(WhereLoopBuilder *pBuilder, Bitmask mExtra){
drh70d18342013-06-06 19:16:33 +00004433 WhereInfo *pWInfo = pBuilder->pWInfo;
drhcf8fa7a2013-05-10 20:26:22 +00004434 WhereClause *pWC;
4435 WhereLoop *pNew;
4436 WhereTerm *pTerm, *pWCEnd;
4437 int rc = SQLITE_OK;
4438 int iCur;
4439 WhereClause tempWC;
4440 WhereLoopBuilder sSubBuild;
drhaa32e3c2013-07-16 21:31:23 +00004441 WhereOrSet sSum, sCur, sPrev;
drhcf8fa7a2013-05-10 20:26:22 +00004442 struct SrcList_item *pItem;
4443
drhcf8fa7a2013-05-10 20:26:22 +00004444 pWC = pBuilder->pWC;
drh70d18342013-06-06 19:16:33 +00004445 if( pWInfo->wctrlFlags & WHERE_AND_ONLY ) return SQLITE_OK;
drhcf8fa7a2013-05-10 20:26:22 +00004446 pWCEnd = pWC->a + pWC->nTerm;
4447 pNew = pBuilder->pNew;
drh77dfd5b2013-08-19 11:15:48 +00004448 memset(&sSum, 0, sizeof(sSum));
drh186ad8c2013-10-08 18:40:37 +00004449 pItem = pWInfo->pTabList->a + pNew->iTab;
drhd4ddae92013-11-06 12:05:57 +00004450 if( !HasRowid(pItem->pTab) ) return SQLITE_OK;
drh186ad8c2013-10-08 18:40:37 +00004451 iCur = pItem->iCursor;
drhcf8fa7a2013-05-10 20:26:22 +00004452
4453 for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
4454 if( (pTerm->eOperator & WO_OR)!=0
4455 && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
4456 ){
4457 WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
4458 WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
4459 WhereTerm *pOrTerm;
drhaa32e3c2013-07-16 21:31:23 +00004460 int once = 1;
4461 int i, j;
drh783dece2013-06-05 17:53:43 +00004462
drh783dece2013-06-05 17:53:43 +00004463 sSubBuild = *pBuilder;
4464 sSubBuild.pOrderBy = 0;
drhaa32e3c2013-07-16 21:31:23 +00004465 sSubBuild.pOrSet = &sCur;
drhcf8fa7a2013-05-10 20:26:22 +00004466
drhc7f0d222013-06-19 03:27:12 +00004467 for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
drh783dece2013-06-05 17:53:43 +00004468 if( (pOrTerm->eOperator & WO_AND)!=0 ){
drhcf8fa7a2013-05-10 20:26:22 +00004469 sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
4470 }else if( pOrTerm->leftCursor==iCur ){
drh70d18342013-06-06 19:16:33 +00004471 tempWC.pWInfo = pWC->pWInfo;
drh783dece2013-06-05 17:53:43 +00004472 tempWC.pOuter = pWC;
4473 tempWC.op = TK_AND;
drh783dece2013-06-05 17:53:43 +00004474 tempWC.nTerm = 1;
drhcf8fa7a2013-05-10 20:26:22 +00004475 tempWC.a = pOrTerm;
4476 sSubBuild.pWC = &tempWC;
4477 }else{
4478 continue;
4479 }
drhaa32e3c2013-07-16 21:31:23 +00004480 sCur.n = 0;
drh8636e9c2013-06-11 01:50:08 +00004481#ifndef SQLITE_OMIT_VIRTUALTABLE
drhcf8fa7a2013-05-10 20:26:22 +00004482 if( IsVirtual(pItem->pTab) ){
danff4b23b2013-11-12 12:17:16 +00004483 rc = whereLoopAddVirtual(&sSubBuild, mExtra);
drh8636e9c2013-06-11 01:50:08 +00004484 }else
4485#endif
4486 {
drhcf8fa7a2013-05-10 20:26:22 +00004487 rc = whereLoopAddBtree(&sSubBuild, mExtra);
4488 }
drhaa32e3c2013-07-16 21:31:23 +00004489 assert( rc==SQLITE_OK || sCur.n==0 );
4490 if( sCur.n==0 ){
4491 sSum.n = 0;
4492 break;
4493 }else if( once ){
4494 whereOrMove(&sSum, &sCur);
4495 once = 0;
4496 }else{
4497 whereOrMove(&sPrev, &sSum);
4498 sSum.n = 0;
4499 for(i=0; i<sPrev.n; i++){
4500 for(j=0; j<sCur.n; j++){
4501 whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,
drhbf539c42013-10-05 18:16:02 +00004502 sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
4503 sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
drhaa32e3c2013-07-16 21:31:23 +00004504 }
4505 }
4506 }
drhcf8fa7a2013-05-10 20:26:22 +00004507 }
drhaa32e3c2013-07-16 21:31:23 +00004508 pNew->nLTerm = 1;
4509 pNew->aLTerm[0] = pTerm;
4510 pNew->wsFlags = WHERE_MULTI_OR;
4511 pNew->rSetup = 0;
4512 pNew->iSortIdx = 0;
4513 memset(&pNew->u, 0, sizeof(pNew->u));
4514 for(i=0; rc==SQLITE_OK && i<sSum.n; i++){
drh74f91d42013-06-19 18:01:44 +00004515 /* TUNING: Multiple by 3.5 for the secondary table lookup */
drhaa32e3c2013-07-16 21:31:23 +00004516 pNew->rRun = sSum.a[i].rRun + 18;
4517 pNew->nOut = sSum.a[i].nOut;
4518 pNew->prereq = sSum.a[i].prereq;
drhfd5874d2013-06-12 14:52:39 +00004519 rc = whereLoopInsert(pBuilder, pNew);
4520 }
drhcf8fa7a2013-05-10 20:26:22 +00004521 }
4522 }
4523 return rc;
4524}
4525
4526/*
drhf1b5f5b2013-05-02 00:15:01 +00004527** Add all WhereLoop objects for all tables
4528*/
drh5346e952013-05-08 14:14:26 +00004529static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
drh70d18342013-06-06 19:16:33 +00004530 WhereInfo *pWInfo = pBuilder->pWInfo;
drhf1b5f5b2013-05-02 00:15:01 +00004531 Bitmask mExtra = 0;
4532 Bitmask mPrior = 0;
4533 int iTab;
drh70d18342013-06-06 19:16:33 +00004534 SrcList *pTabList = pWInfo->pTabList;
drhf1b5f5b2013-05-02 00:15:01 +00004535 struct SrcList_item *pItem;
drh70d18342013-06-06 19:16:33 +00004536 sqlite3 *db = pWInfo->pParse->db;
4537 int nTabList = pWInfo->nLevel;
drh5346e952013-05-08 14:14:26 +00004538 int rc = SQLITE_OK;
drhc63367e2013-06-10 20:46:50 +00004539 u8 priorJoinType = 0;
drhb8a8e8a2013-06-10 19:12:39 +00004540 WhereLoop *pNew;
drhf1b5f5b2013-05-02 00:15:01 +00004541
4542 /* Loop over the tables in the join, from left to right */
drhb8a8e8a2013-06-10 19:12:39 +00004543 pNew = pBuilder->pNew;
drha2014152013-06-07 00:29:23 +00004544 whereLoopInit(pNew);
drha18f3d22013-05-08 03:05:41 +00004545 for(iTab=0, pItem=pTabList->a; iTab<nTabList; iTab++, pItem++){
drhb2a90f02013-05-10 03:30:49 +00004546 pNew->iTab = iTab;
drh70d18342013-06-06 19:16:33 +00004547 pNew->maskSelf = getMask(&pWInfo->sMaskSet, pItem->iCursor);
drhc63367e2013-06-10 20:46:50 +00004548 if( ((pItem->jointype|priorJoinType) & (JT_LEFT|JT_CROSS))!=0 ){
drhf1b5f5b2013-05-02 00:15:01 +00004549 mExtra = mPrior;
4550 }
drhc63367e2013-06-10 20:46:50 +00004551 priorJoinType = pItem->jointype;
drhb2a90f02013-05-10 03:30:49 +00004552 if( IsVirtual(pItem->pTab) ){
danff4b23b2013-11-12 12:17:16 +00004553 rc = whereLoopAddVirtual(pBuilder, mExtra);
drhb2a90f02013-05-10 03:30:49 +00004554 }else{
4555 rc = whereLoopAddBtree(pBuilder, mExtra);
4556 }
drhb2a90f02013-05-10 03:30:49 +00004557 if( rc==SQLITE_OK ){
4558 rc = whereLoopAddOr(pBuilder, mExtra);
4559 }
drhb2a90f02013-05-10 03:30:49 +00004560 mPrior |= pNew->maskSelf;
drh5346e952013-05-08 14:14:26 +00004561 if( rc || db->mallocFailed ) break;
drhf1b5f5b2013-05-02 00:15:01 +00004562 }
drha2014152013-06-07 00:29:23 +00004563 whereLoopClear(db, pNew);
drh5346e952013-05-08 14:14:26 +00004564 return rc;
drhf1b5f5b2013-05-02 00:15:01 +00004565}
4566
drha18f3d22013-05-08 03:05:41 +00004567/*
drh7699d1c2013-06-04 12:42:29 +00004568** Examine a WherePath (with the addition of the extra WhereLoop of the 5th
drh319f6772013-05-14 15:31:07 +00004569** parameters) to see if it outputs rows in the requested ORDER BY
drh94433422013-07-01 11:05:50 +00004570** (or GROUP BY) without requiring a separate sort operation. Return:
drh319f6772013-05-14 15:31:07 +00004571**
4572** 0: ORDER BY is not satisfied. Sorting required
4573** 1: ORDER BY is satisfied. Omit sorting
4574** -1: Unknown at this time
4575**
drh94433422013-07-01 11:05:50 +00004576** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
4577** strict. With GROUP BY and DISTINCT the only requirement is that
4578** equivalent rows appear immediately adjacent to one another. GROUP BY
4579** and DISTINT do not require rows to appear in any particular order as long
4580** as equivelent rows are grouped together. Thus for GROUP BY and DISTINCT
4581** the pOrderBy terms can be matched in any order. With ORDER BY, the
4582** pOrderBy terms must be matched in strict left-to-right order.
drh6b7157b2013-05-10 02:00:35 +00004583*/
4584static int wherePathSatisfiesOrderBy(
4585 WhereInfo *pWInfo, /* The WHERE clause */
drh4f402f22013-06-11 18:59:38 +00004586 ExprList *pOrderBy, /* ORDER BY or GROUP BY or DISTINCT clause to check */
drh6b7157b2013-05-10 02:00:35 +00004587 WherePath *pPath, /* The WherePath to check */
drh4f402f22013-06-11 18:59:38 +00004588 u16 wctrlFlags, /* Might contain WHERE_GROUPBY or WHERE_DISTINCTBY */
4589 u16 nLoop, /* Number of entries in pPath->aLoop[] */
drh319f6772013-05-14 15:31:07 +00004590 WhereLoop *pLast, /* Add this WhereLoop to the end of pPath->aLoop[] */
drh4f402f22013-06-11 18:59:38 +00004591 Bitmask *pRevMask /* OUT: Mask of WhereLoops to run in reverse order */
drh6b7157b2013-05-10 02:00:35 +00004592){
drh88da6442013-05-27 17:59:37 +00004593 u8 revSet; /* True if rev is known */
4594 u8 rev; /* Composite sort order */
4595 u8 revIdx; /* Index sort order */
drhe353ee32013-06-04 23:40:53 +00004596 u8 isOrderDistinct; /* All prior WhereLoops are order-distinct */
4597 u8 distinctColumns; /* True if the loop has UNIQUE NOT NULL columns */
4598 u8 isMatch; /* iColumn matches a term of the ORDER BY clause */
drh416846a2013-11-06 12:56:04 +00004599 u16 nKeyCol; /* Number of key columns in pIndex */
4600 u16 nColumn; /* Total number of ordered columns in the index */
drh7699d1c2013-06-04 12:42:29 +00004601 u16 nOrderBy; /* Number terms in the ORDER BY clause */
4602 int iLoop; /* Index of WhereLoop in pPath being processed */
4603 int i, j; /* Loop counters */
4604 int iCur; /* Cursor number for current WhereLoop */
4605 int iColumn; /* A column number within table iCur */
drhe8ae5832013-06-19 13:32:46 +00004606 WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
drh7699d1c2013-06-04 12:42:29 +00004607 WhereTerm *pTerm; /* A single term of the WHERE clause */
4608 Expr *pOBExpr; /* An expression from the ORDER BY clause */
4609 CollSeq *pColl; /* COLLATE function from an ORDER BY clause term */
4610 Index *pIndex; /* The index associated with pLoop */
4611 sqlite3 *db = pWInfo->pParse->db; /* Database connection */
4612 Bitmask obSat = 0; /* Mask of ORDER BY terms satisfied so far */
4613 Bitmask obDone; /* Mask of all ORDER BY terms */
drhe353ee32013-06-04 23:40:53 +00004614 Bitmask orderDistinctMask; /* Mask of all well-ordered loops */
drhb8916be2013-06-14 02:51:48 +00004615 Bitmask ready; /* Mask of inner loops */
drh319f6772013-05-14 15:31:07 +00004616
4617 /*
drh7699d1c2013-06-04 12:42:29 +00004618 ** We say the WhereLoop is "one-row" if it generates no more than one
4619 ** row of output. A WhereLoop is one-row if all of the following are true:
drh319f6772013-05-14 15:31:07 +00004620 ** (a) All index columns match with WHERE_COLUMN_EQ.
4621 ** (b) The index is unique
drh7699d1c2013-06-04 12:42:29 +00004622 ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
4623 ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
drh319f6772013-05-14 15:31:07 +00004624 **
drhe353ee32013-06-04 23:40:53 +00004625 ** We say the WhereLoop is "order-distinct" if the set of columns from
4626 ** that WhereLoop that are in the ORDER BY clause are different for every
4627 ** row of the WhereLoop. Every one-row WhereLoop is automatically
4628 ** order-distinct. A WhereLoop that has no columns in the ORDER BY clause
4629 ** is not order-distinct. To be order-distinct is not quite the same as being
4630 ** UNIQUE since a UNIQUE column or index can have multiple rows that
4631 ** are NULL and NULL values are equivalent for the purpose of order-distinct.
4632 ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
4633 **
4634 ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
4635 ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
4636 ** automatically order-distinct.
drh319f6772013-05-14 15:31:07 +00004637 */
4638
4639 assert( pOrderBy!=0 );
4640
4641 /* Sortability of virtual tables is determined by the xBestIndex method
4642 ** of the virtual table itself */
4643 if( pLast->wsFlags & WHERE_VIRTUALTABLE ){
drh7699d1c2013-06-04 12:42:29 +00004644 testcase( nLoop>0 ); /* True when outer loops are one-row and match
4645 ** no ORDER BY terms */
drh319f6772013-05-14 15:31:07 +00004646 return pLast->u.vtab.isOrdered;
drh6b7157b2013-05-10 02:00:35 +00004647 }
drh7699d1c2013-06-04 12:42:29 +00004648 if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
drh319f6772013-05-14 15:31:07 +00004649
drh319f6772013-05-14 15:31:07 +00004650 nOrderBy = pOrderBy->nExpr;
drh7963b0e2013-06-17 21:37:40 +00004651 testcase( nOrderBy==BMS-1 );
drhe353ee32013-06-04 23:40:53 +00004652 if( nOrderBy>BMS-1 ) return 0; /* Cannot optimize overly large ORDER BYs */
4653 isOrderDistinct = 1;
drh7699d1c2013-06-04 12:42:29 +00004654 obDone = MASKBIT(nOrderBy)-1;
drhe353ee32013-06-04 23:40:53 +00004655 orderDistinctMask = 0;
drhb8916be2013-06-14 02:51:48 +00004656 ready = 0;
drhe353ee32013-06-04 23:40:53 +00004657 for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
drhb8916be2013-06-14 02:51:48 +00004658 if( iLoop>0 ) ready |= pLoop->maskSelf;
drh7699d1c2013-06-04 12:42:29 +00004659 pLoop = iLoop<nLoop ? pPath->aLoop[iLoop] : pLast;
drh319f6772013-05-14 15:31:07 +00004660 assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
drh319f6772013-05-14 15:31:07 +00004661 iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
drhb8916be2013-06-14 02:51:48 +00004662
4663 /* Mark off any ORDER BY term X that is a column in the table of
4664 ** the current loop for which there is term in the WHERE
4665 ** clause of the form X IS NULL or X=? that reference only outer
4666 ** loops.
4667 */
4668 for(i=0; i<nOrderBy; i++){
4669 if( MASKBIT(i) & obSat ) continue;
4670 pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
4671 if( pOBExpr->op!=TK_COLUMN ) continue;
4672 if( pOBExpr->iTable!=iCur ) continue;
4673 pTerm = findTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
4674 ~ready, WO_EQ|WO_ISNULL, 0);
4675 if( pTerm==0 ) continue;
drh7963b0e2013-06-17 21:37:40 +00004676 if( (pTerm->eOperator&WO_EQ)!=0 && pOBExpr->iColumn>=0 ){
drhb8916be2013-06-14 02:51:48 +00004677 const char *z1, *z2;
4678 pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
4679 if( !pColl ) pColl = db->pDfltColl;
4680 z1 = pColl->zName;
4681 pColl = sqlite3ExprCollSeq(pWInfo->pParse, pTerm->pExpr);
4682 if( !pColl ) pColl = db->pDfltColl;
4683 z2 = pColl->zName;
4684 if( sqlite3StrICmp(z1, z2)!=0 ) continue;
4685 }
4686 obSat |= MASKBIT(i);
4687 }
4688
drh7699d1c2013-06-04 12:42:29 +00004689 if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
4690 if( pLoop->wsFlags & WHERE_IPK ){
4691 pIndex = 0;
drhbbbdc832013-10-22 18:01:40 +00004692 nKeyCol = 0;
drh416846a2013-11-06 12:56:04 +00004693 nColumn = 1;
drh7699d1c2013-06-04 12:42:29 +00004694 }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
drh1b0f0262013-05-30 22:27:09 +00004695 return 0;
drh7699d1c2013-06-04 12:42:29 +00004696 }else{
drhbbbdc832013-10-22 18:01:40 +00004697 nKeyCol = pIndex->nKeyCol;
drh416846a2013-11-06 12:56:04 +00004698 nColumn = pIndex->nColumn;
4699 assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) );
4700 assert( pIndex->aiColumn[nColumn-1]==(-1) || !HasRowid(pIndex->pTable));
drhe353ee32013-06-04 23:40:53 +00004701 isOrderDistinct = pIndex->onError!=OE_None;
drh1b0f0262013-05-30 22:27:09 +00004702 }
drh7699d1c2013-06-04 12:42:29 +00004703
drh7699d1c2013-06-04 12:42:29 +00004704 /* Loop through all columns of the index and deal with the ones
4705 ** that are not constrained by == or IN.
4706 */
4707 rev = revSet = 0;
drhe353ee32013-06-04 23:40:53 +00004708 distinctColumns = 0;
drh416846a2013-11-06 12:56:04 +00004709 for(j=0; j<nColumn; j++){
drh7699d1c2013-06-04 12:42:29 +00004710 u8 bOnce; /* True to run the ORDER BY search loop */
4711
drhe353ee32013-06-04 23:40:53 +00004712 /* Skip over == and IS NULL terms */
drh7699d1c2013-06-04 12:42:29 +00004713 if( j<pLoop->u.btree.nEq
drh4efc9292013-06-06 23:02:03 +00004714 && ((i = pLoop->aLTerm[j]->eOperator) & (WO_EQ|WO_ISNULL))!=0
drh7699d1c2013-06-04 12:42:29 +00004715 ){
drh7963b0e2013-06-17 21:37:40 +00004716 if( i & WO_ISNULL ){
4717 testcase( isOrderDistinct );
4718 isOrderDistinct = 0;
4719 }
drhe353ee32013-06-04 23:40:53 +00004720 continue;
drh7699d1c2013-06-04 12:42:29 +00004721 }
4722
drhe353ee32013-06-04 23:40:53 +00004723 /* Get the column number in the table (iColumn) and sort order
4724 ** (revIdx) for the j-th column of the index.
drh7699d1c2013-06-04 12:42:29 +00004725 */
drh416846a2013-11-06 12:56:04 +00004726 if( pIndex ){
drh7699d1c2013-06-04 12:42:29 +00004727 iColumn = pIndex->aiColumn[j];
4728 revIdx = pIndex->aSortOrder[j];
4729 if( iColumn==pIndex->pTable->iPKey ) iColumn = -1;
drhdc3cd4b2013-05-30 23:21:20 +00004730 }else{
drh7699d1c2013-06-04 12:42:29 +00004731 iColumn = -1;
4732 revIdx = 0;
drhdc3cd4b2013-05-30 23:21:20 +00004733 }
drh7699d1c2013-06-04 12:42:29 +00004734
4735 /* An unconstrained column that might be NULL means that this
drh416846a2013-11-06 12:56:04 +00004736 ** WhereLoop is not well-ordered
drh7699d1c2013-06-04 12:42:29 +00004737 */
drhe353ee32013-06-04 23:40:53 +00004738 if( isOrderDistinct
4739 && iColumn>=0
drh7699d1c2013-06-04 12:42:29 +00004740 && j>=pLoop->u.btree.nEq
4741 && pIndex->pTable->aCol[iColumn].notNull==0
4742 ){
drhe353ee32013-06-04 23:40:53 +00004743 isOrderDistinct = 0;
drh7699d1c2013-06-04 12:42:29 +00004744 }
4745
4746 /* Find the ORDER BY term that corresponds to the j-th column
4747 ** of the index and and mark that ORDER BY term off
4748 */
4749 bOnce = 1;
drhe353ee32013-06-04 23:40:53 +00004750 isMatch = 0;
drh7699d1c2013-06-04 12:42:29 +00004751 for(i=0; bOnce && i<nOrderBy; i++){
4752 if( MASKBIT(i) & obSat ) continue;
4753 pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
drh93ec45d2013-06-17 18:20:48 +00004754 testcase( wctrlFlags & WHERE_GROUPBY );
4755 testcase( wctrlFlags & WHERE_DISTINCTBY );
drh4f402f22013-06-11 18:59:38 +00004756 if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
drhe353ee32013-06-04 23:40:53 +00004757 if( pOBExpr->op!=TK_COLUMN ) continue;
drh7699d1c2013-06-04 12:42:29 +00004758 if( pOBExpr->iTable!=iCur ) continue;
4759 if( pOBExpr->iColumn!=iColumn ) continue;
4760 if( iColumn>=0 ){
4761 pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
4762 if( !pColl ) pColl = db->pDfltColl;
4763 if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
4764 }
drhe353ee32013-06-04 23:40:53 +00004765 isMatch = 1;
drh7699d1c2013-06-04 12:42:29 +00004766 break;
4767 }
drhe353ee32013-06-04 23:40:53 +00004768 if( isMatch ){
drh7963b0e2013-06-17 21:37:40 +00004769 if( iColumn<0 ){
4770 testcase( distinctColumns==0 );
4771 distinctColumns = 1;
4772 }
drh7699d1c2013-06-04 12:42:29 +00004773 obSat |= MASKBIT(i);
4774 if( (pWInfo->wctrlFlags & WHERE_GROUPBY)==0 ){
drhe353ee32013-06-04 23:40:53 +00004775 /* Make sure the sort order is compatible in an ORDER BY clause.
4776 ** Sort order is irrelevant for a GROUP BY clause. */
drh7699d1c2013-06-04 12:42:29 +00004777 if( revSet ){
4778 if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) return 0;
4779 }else{
4780 rev = revIdx ^ pOrderBy->a[i].sortOrder;
4781 if( rev ) *pRevMask |= MASKBIT(iLoop);
4782 revSet = 1;
4783 }
4784 }
4785 }else{
4786 /* No match found */
drhbbbdc832013-10-22 18:01:40 +00004787 if( j==0 || j<nKeyCol ){
drh7963b0e2013-06-17 21:37:40 +00004788 testcase( isOrderDistinct!=0 );
4789 isOrderDistinct = 0;
4790 }
drh7699d1c2013-06-04 12:42:29 +00004791 break;
4792 }
4793 } /* end Loop over all index columns */
drh81186b42013-06-18 01:52:41 +00004794 if( distinctColumns ){
4795 testcase( isOrderDistinct==0 );
4796 isOrderDistinct = 1;
4797 }
drh7699d1c2013-06-04 12:42:29 +00004798 } /* end-if not one-row */
4799
4800 /* Mark off any other ORDER BY terms that reference pLoop */
drhe353ee32013-06-04 23:40:53 +00004801 if( isOrderDistinct ){
4802 orderDistinctMask |= pLoop->maskSelf;
drh7699d1c2013-06-04 12:42:29 +00004803 for(i=0; i<nOrderBy; i++){
4804 Expr *p;
4805 if( MASKBIT(i) & obSat ) continue;
4806 p = pOrderBy->a[i].pExpr;
drh70d18342013-06-06 19:16:33 +00004807 if( (exprTableUsage(&pWInfo->sMaskSet, p)&~orderDistinctMask)==0 ){
drh7699d1c2013-06-04 12:42:29 +00004808 obSat |= MASKBIT(i);
4809 }
drh0afb4232013-05-31 13:36:32 +00004810 }
drh319f6772013-05-14 15:31:07 +00004811 }
drhb8916be2013-06-14 02:51:48 +00004812 } /* End the loop over all WhereLoops from outer-most down to inner-most */
drh7699d1c2013-06-04 12:42:29 +00004813 if( obSat==obDone ) return 1;
drhe353ee32013-06-04 23:40:53 +00004814 if( !isOrderDistinct ) return 0;
drh319f6772013-05-14 15:31:07 +00004815 return -1;
drh6b7157b2013-05-10 02:00:35 +00004816}
4817
drhd15cb172013-05-21 19:23:10 +00004818#ifdef WHERETRACE_ENABLED
4819/* For debugging use only: */
4820static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
4821 static char zName[65];
4822 int i;
4823 for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
4824 if( pLast ) zName[i++] = pLast->cId;
4825 zName[i] = 0;
4826 return zName;
4827}
4828#endif
4829
drh6b7157b2013-05-10 02:00:35 +00004830
4831/*
dan51576f42013-07-02 10:06:15 +00004832** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
drha18f3d22013-05-08 03:05:41 +00004833** attempts to find the lowest cost path that visits each WhereLoop
4834** once. This path is then loaded into the pWInfo->a[].pWLoop fields.
4835**
drhc7f0d222013-06-19 03:27:12 +00004836** Assume that the total number of output rows that will need to be sorted
4837** will be nRowEst (in the 10*log2 representation). Or, ignore sorting
4838** costs if nRowEst==0.
4839**
drha18f3d22013-05-08 03:05:41 +00004840** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
4841** error occurs.
4842*/
drhbf539c42013-10-05 18:16:02 +00004843static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
drh783dece2013-06-05 17:53:43 +00004844 int mxChoice; /* Maximum number of simultaneous paths tracked */
drha18f3d22013-05-08 03:05:41 +00004845 int nLoop; /* Number of terms in the join */
drhe1e2e9a2013-06-13 15:16:53 +00004846 Parse *pParse; /* Parsing context */
drha18f3d22013-05-08 03:05:41 +00004847 sqlite3 *db; /* The database connection */
4848 int iLoop; /* Loop counter over the terms of the join */
4849 int ii, jj; /* Loop counters */
drhfde1e6b2013-09-06 17:45:42 +00004850 int mxI = 0; /* Index of next entry to replace */
drhbf539c42013-10-05 18:16:02 +00004851 LogEst rCost; /* Cost of a path */
4852 LogEst nOut; /* Number of outputs */
4853 LogEst mxCost = 0; /* Maximum cost of a set of paths */
4854 LogEst mxOut = 0; /* Maximum nOut value on the set of paths */
4855 LogEst rSortCost; /* Cost to do a sort */
drha18f3d22013-05-08 03:05:41 +00004856 int nTo, nFrom; /* Number of valid entries in aTo[] and aFrom[] */
4857 WherePath *aFrom; /* All nFrom paths at the previous level */
4858 WherePath *aTo; /* The nTo best paths at the current level */
4859 WherePath *pFrom; /* An element of aFrom[] that we are working on */
4860 WherePath *pTo; /* An element of aTo[] that we are working on */
4861 WhereLoop *pWLoop; /* One of the WhereLoop objects */
4862 WhereLoop **pX; /* Used to divy up the pSpace memory */
4863 char *pSpace; /* Temporary memory used by this routine */
4864
drhe1e2e9a2013-06-13 15:16:53 +00004865 pParse = pWInfo->pParse;
4866 db = pParse->db;
drha18f3d22013-05-08 03:05:41 +00004867 nLoop = pWInfo->nLevel;
drhe1e2e9a2013-06-13 15:16:53 +00004868 /* TUNING: For simple queries, only the best path is tracked.
4869 ** For 2-way joins, the 5 best paths are followed.
4870 ** For joins of 3 or more tables, track the 10 best paths */
drhe9d935a2013-06-05 16:19:59 +00004871 mxChoice = (nLoop==1) ? 1 : (nLoop==2 ? 5 : 10);
drha18f3d22013-05-08 03:05:41 +00004872 assert( nLoop<=pWInfo->pTabList->nSrc );
drh3b48e8c2013-06-12 20:18:16 +00004873 WHERETRACE(0x002, ("---- begin solver\n"));
drha18f3d22013-05-08 03:05:41 +00004874
4875 /* Allocate and initialize space for aTo and aFrom */
4876 ii = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
4877 pSpace = sqlite3DbMallocRaw(db, ii);
4878 if( pSpace==0 ) return SQLITE_NOMEM;
4879 aTo = (WherePath*)pSpace;
4880 aFrom = aTo+mxChoice;
4881 memset(aFrom, 0, sizeof(aFrom[0]));
4882 pX = (WhereLoop**)(aFrom+mxChoice);
drhe9d935a2013-06-05 16:19:59 +00004883 for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
drha18f3d22013-05-08 03:05:41 +00004884 pFrom->aLoop = pX;
4885 }
4886
drhe1e2e9a2013-06-13 15:16:53 +00004887 /* Seed the search with a single WherePath containing zero WhereLoops.
4888 **
4889 ** TUNING: Do not let the number of iterations go above 25. If the cost
4890 ** of computing an automatic index is not paid back within the first 25
4891 ** rows, then do not use the automatic index. */
drhbf539c42013-10-05 18:16:02 +00004892 aFrom[0].nRow = MIN(pParse->nQueryLoop, 46); assert( 46==sqlite3LogEst(25) );
drha18f3d22013-05-08 03:05:41 +00004893 nFrom = 1;
drh6b7157b2013-05-10 02:00:35 +00004894
4895 /* Precompute the cost of sorting the final result set, if the caller
4896 ** to sqlite3WhereBegin() was concerned about sorting */
drhb8a8e8a2013-06-10 19:12:39 +00004897 rSortCost = 0;
4898 if( pWInfo->pOrderBy==0 || nRowEst==0 ){
drh6b7157b2013-05-10 02:00:35 +00004899 aFrom[0].isOrderedValid = 1;
4900 }else{
drh186ad8c2013-10-08 18:40:37 +00004901 /* TUNING: Estimated cost of sorting is 48*N*log2(N) where N is the
4902 ** number of output rows. The 48 is the expected size of a row to sort.
4903 ** FIXME: compute a better estimate of the 48 multiplier based on the
4904 ** result set expressions. */
drhb50596d2013-10-08 20:42:41 +00004905 rSortCost = nRowEst + estLog(nRowEst);
drh3b48e8c2013-06-12 20:18:16 +00004906 WHERETRACE(0x002,("---- sort cost=%-3d\n", rSortCost));
drh6b7157b2013-05-10 02:00:35 +00004907 }
4908
4909 /* Compute successively longer WherePaths using the previous generation
4910 ** of WherePaths as the basis for the next. Keep track of the mxChoice
4911 ** best paths at each generation */
drha18f3d22013-05-08 03:05:41 +00004912 for(iLoop=0; iLoop<nLoop; iLoop++){
4913 nTo = 0;
4914 for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
4915 for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
4916 Bitmask maskNew;
drh319f6772013-05-14 15:31:07 +00004917 Bitmask revMask = 0;
drh6b7157b2013-05-10 02:00:35 +00004918 u8 isOrderedValid = pFrom->isOrderedValid;
4919 u8 isOrdered = pFrom->isOrdered;
drha18f3d22013-05-08 03:05:41 +00004920 if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
4921 if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
drh6b7157b2013-05-10 02:00:35 +00004922 /* At this point, pWLoop is a candidate to be the next loop.
4923 ** Compute its cost */
drhbf539c42013-10-05 18:16:02 +00004924 rCost = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
4925 rCost = sqlite3LogEstAdd(rCost, pFrom->rCost);
drhfde1e6b2013-09-06 17:45:42 +00004926 nOut = pFrom->nRow + pWLoop->nOut;
drha18f3d22013-05-08 03:05:41 +00004927 maskNew = pFrom->maskLoop | pWLoop->maskSelf;
drh6b7157b2013-05-10 02:00:35 +00004928 if( !isOrderedValid ){
drh4f402f22013-06-11 18:59:38 +00004929 switch( wherePathSatisfiesOrderBy(pWInfo,
4930 pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
drh93ec45d2013-06-17 18:20:48 +00004931 iLoop, pWLoop, &revMask) ){
drh6b7157b2013-05-10 02:00:35 +00004932 case 1: /* Yes. pFrom+pWLoop does satisfy the ORDER BY clause */
4933 isOrdered = 1;
4934 isOrderedValid = 1;
4935 break;
4936 case 0: /* No. pFrom+pWLoop will require a separate sort */
4937 isOrdered = 0;
4938 isOrderedValid = 1;
drhbf539c42013-10-05 18:16:02 +00004939 rCost = sqlite3LogEstAdd(rCost, rSortCost);
drh6b7157b2013-05-10 02:00:35 +00004940 break;
4941 default: /* Cannot tell yet. Try again on the next iteration */
4942 break;
4943 }
drh3a5ba8b2013-06-03 15:34:48 +00004944 }else{
4945 revMask = pFrom->revLoop;
drh6b7157b2013-05-10 02:00:35 +00004946 }
4947 /* Check to see if pWLoop should be added to the mxChoice best so far */
4948 for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
drhfde1e6b2013-09-06 17:45:42 +00004949 if( pTo->maskLoop==maskNew
4950 && pTo->isOrderedValid==isOrderedValid
4951 && ((pTo->rCost<=rCost && pTo->nRow<=nOut) ||
4952 (pTo->rCost>=rCost && pTo->nRow>=nOut))
4953 ){
drh7963b0e2013-06-17 21:37:40 +00004954 testcase( jj==nTo-1 );
drh6b7157b2013-05-10 02:00:35 +00004955 break;
4956 }
4957 }
drha18f3d22013-05-08 03:05:41 +00004958 if( jj>=nTo ){
drh7d9e7d82013-09-11 17:39:09 +00004959 if( nTo>=mxChoice && rCost>=mxCost ){
drh989578e2013-10-28 14:34:35 +00004960#ifdef WHERETRACE_ENABLED /* 0x4 */
drhae70cf12013-05-31 15:18:46 +00004961 if( sqlite3WhereTrace&0x4 ){
drhfde1e6b2013-09-06 17:45:42 +00004962 sqlite3DebugPrintf("Skip %s cost=%-3d,%3d order=%c\n",
4963 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
drhd15cb172013-05-21 19:23:10 +00004964 isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
4965 }
4966#endif
4967 continue;
4968 }
4969 /* Add a new Path to the aTo[] set */
drha18f3d22013-05-08 03:05:41 +00004970 if( nTo<mxChoice ){
drhd15cb172013-05-21 19:23:10 +00004971 /* Increase the size of the aTo set by one */
drha18f3d22013-05-08 03:05:41 +00004972 jj = nTo++;
4973 }else{
drhd15cb172013-05-21 19:23:10 +00004974 /* New path replaces the prior worst to keep count below mxChoice */
drhfde1e6b2013-09-06 17:45:42 +00004975 jj = mxI;
drha18f3d22013-05-08 03:05:41 +00004976 }
4977 pTo = &aTo[jj];
drh989578e2013-10-28 14:34:35 +00004978#ifdef WHERETRACE_ENABLED /* 0x4 */
drhae70cf12013-05-31 15:18:46 +00004979 if( sqlite3WhereTrace&0x4 ){
drhfde1e6b2013-09-06 17:45:42 +00004980 sqlite3DebugPrintf("New %s cost=%-3d,%3d order=%c\n",
4981 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
drhd15cb172013-05-21 19:23:10 +00004982 isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
4983 }
4984#endif
drhf204dac2013-05-08 03:22:07 +00004985 }else{
drhfde1e6b2013-09-06 17:45:42 +00004986 if( pTo->rCost<=rCost && pTo->nRow<=nOut ){
drh989578e2013-10-28 14:34:35 +00004987#ifdef WHERETRACE_ENABLED /* 0x4 */
drhae70cf12013-05-31 15:18:46 +00004988 if( sqlite3WhereTrace&0x4 ){
drhd15cb172013-05-21 19:23:10 +00004989 sqlite3DebugPrintf(
drhfde1e6b2013-09-06 17:45:42 +00004990 "Skip %s cost=%-3d,%3d order=%c",
4991 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
drhd15cb172013-05-21 19:23:10 +00004992 isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
drhfde1e6b2013-09-06 17:45:42 +00004993 sqlite3DebugPrintf(" vs %s cost=%-3d,%d order=%c\n",
4994 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
drhd15cb172013-05-21 19:23:10 +00004995 pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?');
4996 }
4997#endif
drh7963b0e2013-06-17 21:37:40 +00004998 testcase( pTo->rCost==rCost );
drhd15cb172013-05-21 19:23:10 +00004999 continue;
5000 }
drh7963b0e2013-06-17 21:37:40 +00005001 testcase( pTo->rCost==rCost+1 );
drhd15cb172013-05-21 19:23:10 +00005002 /* A new and better score for a previously created equivalent path */
drh989578e2013-10-28 14:34:35 +00005003#ifdef WHERETRACE_ENABLED /* 0x4 */
drhae70cf12013-05-31 15:18:46 +00005004 if( sqlite3WhereTrace&0x4 ){
drhd15cb172013-05-21 19:23:10 +00005005 sqlite3DebugPrintf(
drhfde1e6b2013-09-06 17:45:42 +00005006 "Update %s cost=%-3d,%3d order=%c",
5007 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
drhd15cb172013-05-21 19:23:10 +00005008 isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
drhfde1e6b2013-09-06 17:45:42 +00005009 sqlite3DebugPrintf(" was %s cost=%-3d,%3d order=%c\n",
5010 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
drhd15cb172013-05-21 19:23:10 +00005011 pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?');
5012 }
5013#endif
drha18f3d22013-05-08 03:05:41 +00005014 }
drh6b7157b2013-05-10 02:00:35 +00005015 /* pWLoop is a winner. Add it to the set of best so far */
drha18f3d22013-05-08 03:05:41 +00005016 pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
drh319f6772013-05-14 15:31:07 +00005017 pTo->revLoop = revMask;
drhfde1e6b2013-09-06 17:45:42 +00005018 pTo->nRow = nOut;
drha18f3d22013-05-08 03:05:41 +00005019 pTo->rCost = rCost;
drh6b7157b2013-05-10 02:00:35 +00005020 pTo->isOrderedValid = isOrderedValid;
5021 pTo->isOrdered = isOrdered;
drha18f3d22013-05-08 03:05:41 +00005022 memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
5023 pTo->aLoop[iLoop] = pWLoop;
5024 if( nTo>=mxChoice ){
drhfde1e6b2013-09-06 17:45:42 +00005025 mxI = 0;
drha18f3d22013-05-08 03:05:41 +00005026 mxCost = aTo[0].rCost;
drhfde1e6b2013-09-06 17:45:42 +00005027 mxOut = aTo[0].nRow;
drha18f3d22013-05-08 03:05:41 +00005028 for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
drhfde1e6b2013-09-06 17:45:42 +00005029 if( pTo->rCost>mxCost || (pTo->rCost==mxCost && pTo->nRow>mxOut) ){
5030 mxCost = pTo->rCost;
5031 mxOut = pTo->nRow;
5032 mxI = jj;
5033 }
drha18f3d22013-05-08 03:05:41 +00005034 }
5035 }
5036 }
5037 }
5038
drh989578e2013-10-28 14:34:35 +00005039#ifdef WHERETRACE_ENABLED /* >=2 */
drhd15cb172013-05-21 19:23:10 +00005040 if( sqlite3WhereTrace>=2 ){
drha50ef112013-05-22 02:06:59 +00005041 sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
drhd15cb172013-05-21 19:23:10 +00005042 for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
drhb8a8e8a2013-06-10 19:12:39 +00005043 sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
drha50ef112013-05-22 02:06:59 +00005044 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
drhd15cb172013-05-21 19:23:10 +00005045 pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?');
drh88da6442013-05-27 17:59:37 +00005046 if( pTo->isOrderedValid && pTo->isOrdered ){
5047 sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
5048 }else{
5049 sqlite3DebugPrintf("\n");
5050 }
drhf204dac2013-05-08 03:22:07 +00005051 }
5052 }
5053#endif
5054
drh6b7157b2013-05-10 02:00:35 +00005055 /* Swap the roles of aFrom and aTo for the next generation */
drha18f3d22013-05-08 03:05:41 +00005056 pFrom = aTo;
5057 aTo = aFrom;
5058 aFrom = pFrom;
5059 nFrom = nTo;
5060 }
5061
drh75b93402013-05-31 20:43:57 +00005062 if( nFrom==0 ){
drhe1e2e9a2013-06-13 15:16:53 +00005063 sqlite3ErrorMsg(pParse, "no query solution");
drh75b93402013-05-31 20:43:57 +00005064 sqlite3DbFree(db, pSpace);
5065 return SQLITE_ERROR;
5066 }
drha18f3d22013-05-08 03:05:41 +00005067
drh6b7157b2013-05-10 02:00:35 +00005068 /* Find the lowest cost path. pFrom will be left pointing to that path */
drha18f3d22013-05-08 03:05:41 +00005069 pFrom = aFrom;
5070 for(ii=1; ii<nFrom; ii++){
5071 if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
5072 }
5073 assert( pWInfo->nLevel==nLoop );
drh6b7157b2013-05-10 02:00:35 +00005074 /* Load the lowest cost path into pWInfo */
drha18f3d22013-05-08 03:05:41 +00005075 for(iLoop=0; iLoop<nLoop; iLoop++){
drh7ba39a92013-05-30 17:43:19 +00005076 WhereLevel *pLevel = pWInfo->a + iLoop;
5077 pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
drhe217efc2013-06-12 03:48:41 +00005078 pLevel->iFrom = pWLoop->iTab;
drh7ba39a92013-05-30 17:43:19 +00005079 pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
drha18f3d22013-05-08 03:05:41 +00005080 }
drhfd636c72013-06-21 02:05:06 +00005081 if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0
5082 && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
5083 && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
drh4f402f22013-06-11 18:59:38 +00005084 && nRowEst
5085 ){
5086 Bitmask notUsed;
drh6457a352013-06-21 00:35:37 +00005087 int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom,
drh93ec45d2013-06-17 18:20:48 +00005088 WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
drh4f402f22013-06-11 18:59:38 +00005089 if( rc==1 ) pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
5090 }
drh6b7157b2013-05-10 02:00:35 +00005091 if( pFrom->isOrdered ){
drh4f402f22013-06-11 18:59:38 +00005092 if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
5093 pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
5094 }else{
5095 pWInfo->bOBSat = 1;
5096 pWInfo->revMask = pFrom->revLoop;
5097 }
drh6b7157b2013-05-10 02:00:35 +00005098 }
drha50ef112013-05-22 02:06:59 +00005099 pWInfo->nRowOut = pFrom->nRow;
drha18f3d22013-05-08 03:05:41 +00005100
5101 /* Free temporary memory and return success */
5102 sqlite3DbFree(db, pSpace);
5103 return SQLITE_OK;
5104}
drh94a11212004-09-25 13:12:14 +00005105
5106/*
drh60c96cd2013-06-09 17:21:25 +00005107** Most queries use only a single table (they are not joins) and have
5108** simple == constraints against indexed fields. This routine attempts
5109** to plan those simple cases using much less ceremony than the
5110** general-purpose query planner, and thereby yield faster sqlite3_prepare()
5111** times for the common case.
5112**
5113** Return non-zero on success, if this query can be handled by this
5114** no-frills query planner. Return zero if this query needs the
5115** general-purpose query planner.
5116*/
drhb8a8e8a2013-06-10 19:12:39 +00005117static int whereShortCut(WhereLoopBuilder *pBuilder){
drh60c96cd2013-06-09 17:21:25 +00005118 WhereInfo *pWInfo;
5119 struct SrcList_item *pItem;
5120 WhereClause *pWC;
5121 WhereTerm *pTerm;
5122 WhereLoop *pLoop;
5123 int iCur;
drh92a121f2013-06-10 12:15:47 +00005124 int j;
drh60c96cd2013-06-09 17:21:25 +00005125 Table *pTab;
5126 Index *pIdx;
5127
5128 pWInfo = pBuilder->pWInfo;
drh5822d6f2013-06-10 23:30:09 +00005129 if( pWInfo->wctrlFlags & WHERE_FORCE_TABLE ) return 0;
drh60c96cd2013-06-09 17:21:25 +00005130 assert( pWInfo->pTabList->nSrc>=1 );
5131 pItem = pWInfo->pTabList->a;
5132 pTab = pItem->pTab;
5133 if( IsVirtual(pTab) ) return 0;
5134 if( pItem->zIndex ) return 0;
5135 iCur = pItem->iCursor;
5136 pWC = &pWInfo->sWC;
5137 pLoop = pBuilder->pNew;
drh60c96cd2013-06-09 17:21:25 +00005138 pLoop->wsFlags = 0;
drh3b75ffa2013-06-10 14:56:25 +00005139 pTerm = findTerm(pWC, iCur, -1, 0, WO_EQ, 0);
drh60c96cd2013-06-09 17:21:25 +00005140 if( pTerm ){
5141 pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
5142 pLoop->aLTerm[0] = pTerm;
5143 pLoop->nLTerm = 1;
5144 pLoop->u.btree.nEq = 1;
drhe1e2e9a2013-06-13 15:16:53 +00005145 /* TUNING: Cost of a rowid lookup is 10 */
drhbf539c42013-10-05 18:16:02 +00005146 pLoop->rRun = 33; /* 33==sqlite3LogEst(10) */
drh60c96cd2013-06-09 17:21:25 +00005147 }else{
5148 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
dancd40abb2013-08-29 10:46:05 +00005149 assert( pLoop->aLTermSpace==pLoop->aLTerm );
5150 assert( ArraySize(pLoop->aLTermSpace)==4 );
5151 if( pIdx->onError==OE_None
5152 || pIdx->pPartIdxWhere!=0
drhbbbdc832013-10-22 18:01:40 +00005153 || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace)
dancd40abb2013-08-29 10:46:05 +00005154 ) continue;
drhbbbdc832013-10-22 18:01:40 +00005155 for(j=0; j<pIdx->nKeyCol; j++){
drh3b75ffa2013-06-10 14:56:25 +00005156 pTerm = findTerm(pWC, iCur, pIdx->aiColumn[j], 0, WO_EQ, pIdx);
drh60c96cd2013-06-09 17:21:25 +00005157 if( pTerm==0 ) break;
drh60c96cd2013-06-09 17:21:25 +00005158 pLoop->aLTerm[j] = pTerm;
5159 }
drhbbbdc832013-10-22 18:01:40 +00005160 if( j!=pIdx->nKeyCol ) continue;
drh92a121f2013-06-10 12:15:47 +00005161 pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
drhec95c442013-10-23 01:57:32 +00005162 if( pIdx->isCovering || (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){
drh92a121f2013-06-10 12:15:47 +00005163 pLoop->wsFlags |= WHERE_IDX_ONLY;
5164 }
drh60c96cd2013-06-09 17:21:25 +00005165 pLoop->nLTerm = j;
5166 pLoop->u.btree.nEq = j;
5167 pLoop->u.btree.pIndex = pIdx;
drhe1e2e9a2013-06-13 15:16:53 +00005168 /* TUNING: Cost of a unique index lookup is 15 */
drhbf539c42013-10-05 18:16:02 +00005169 pLoop->rRun = 39; /* 39==sqlite3LogEst(15) */
drh60c96cd2013-06-09 17:21:25 +00005170 break;
5171 }
5172 }
drh3b75ffa2013-06-10 14:56:25 +00005173 if( pLoop->wsFlags ){
drhbf539c42013-10-05 18:16:02 +00005174 pLoop->nOut = (LogEst)1;
drh3b75ffa2013-06-10 14:56:25 +00005175 pWInfo->a[0].pWLoop = pLoop;
5176 pLoop->maskSelf = getMask(&pWInfo->sMaskSet, iCur);
5177 pWInfo->a[0].iTabCur = iCur;
5178 pWInfo->nRowOut = 1;
drh4f402f22013-06-11 18:59:38 +00005179 if( pWInfo->pOrderBy ) pWInfo->bOBSat = 1;
drh6457a352013-06-21 00:35:37 +00005180 if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
5181 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
5182 }
drh3b75ffa2013-06-10 14:56:25 +00005183#ifdef SQLITE_DEBUG
5184 pLoop->cId = '0';
5185#endif
5186 return 1;
5187 }
5188 return 0;
drh60c96cd2013-06-09 17:21:25 +00005189}
5190
5191/*
drhe3184742002-06-19 14:27:05 +00005192** Generate the beginning of the loop used for WHERE clause processing.
drhacf3b982005-01-03 01:27:18 +00005193** The return value is a pointer to an opaque structure that contains
drh75897232000-05-29 14:26:00 +00005194** information needed to terminate the loop. Later, the calling routine
danielk19774adee202004-05-08 08:23:19 +00005195** should invoke sqlite3WhereEnd() with the return value of this function
drh75897232000-05-29 14:26:00 +00005196** in order to complete the WHERE clause processing.
5197**
5198** If an error occurs, this routine returns NULL.
drhc27a1ce2002-06-14 20:58:45 +00005199**
5200** The basic idea is to do a nested loop, one loop for each table in
5201** the FROM clause of a select. (INSERT and UPDATE statements are the
5202** same as a SELECT with only a single table in the FROM clause.) For
5203** example, if the SQL is this:
5204**
5205** SELECT * FROM t1, t2, t3 WHERE ...;
5206**
5207** Then the code generated is conceptually like the following:
5208**
5209** foreach row1 in t1 do \ Code generated
danielk19774adee202004-05-08 08:23:19 +00005210** foreach row2 in t2 do |-- by sqlite3WhereBegin()
drhc27a1ce2002-06-14 20:58:45 +00005211** foreach row3 in t3 do /
5212** ...
5213** end \ Code generated
danielk19774adee202004-05-08 08:23:19 +00005214** end |-- by sqlite3WhereEnd()
drhc27a1ce2002-06-14 20:58:45 +00005215** end /
5216**
drh29dda4a2005-07-21 18:23:20 +00005217** Note that the loops might not be nested in the order in which they
5218** appear in the FROM clause if a different order is better able to make
drh51147ba2005-07-23 22:59:55 +00005219** use of indices. Note also that when the IN operator appears in
5220** the WHERE clause, it might result in additional nested loops for
5221** scanning through all values on the right-hand side of the IN.
drh29dda4a2005-07-21 18:23:20 +00005222**
drhc27a1ce2002-06-14 20:58:45 +00005223** There are Btree cursors associated with each table. t1 uses cursor
drh6a3ea0e2003-05-02 14:32:12 +00005224** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
5225** And so forth. This routine generates code to open those VDBE cursors
danielk19774adee202004-05-08 08:23:19 +00005226** and sqlite3WhereEnd() generates the code to close them.
drhc27a1ce2002-06-14 20:58:45 +00005227**
drhe6f85e72004-12-25 01:03:13 +00005228** The code that sqlite3WhereBegin() generates leaves the cursors named
5229** in pTabList pointing at their appropriate entries. The [...] code
drhf0863fe2005-06-12 21:35:51 +00005230** can use OP_Column and OP_Rowid opcodes on these cursors to extract
drhe6f85e72004-12-25 01:03:13 +00005231** data from the various tables of the loop.
5232**
drhc27a1ce2002-06-14 20:58:45 +00005233** If the WHERE clause is empty, the foreach loops must each scan their
5234** entire tables. Thus a three-way join is an O(N^3) operation. But if
5235** the tables have indices and there are terms in the WHERE clause that
5236** refer to those indices, a complete table scan can be avoided and the
5237** code will run much faster. Most of the work of this routine is checking
5238** to see if there are indices that can be used to speed up the loop.
5239**
5240** Terms of the WHERE clause are also used to limit which rows actually
5241** make it to the "..." in the middle of the loop. After each "foreach",
5242** terms of the WHERE clause that use only terms in that loop and outer
5243** loops are evaluated and if false a jump is made around all subsequent
5244** inner loops (or around the "..." if the test occurs within the inner-
5245** most loop)
5246**
5247** OUTER JOINS
5248**
5249** An outer join of tables t1 and t2 is conceptally coded as follows:
5250**
5251** foreach row1 in t1 do
5252** flag = 0
5253** foreach row2 in t2 do
5254** start:
5255** ...
5256** flag = 1
5257** end
drhe3184742002-06-19 14:27:05 +00005258** if flag==0 then
5259** move the row2 cursor to a null row
5260** goto start
5261** fi
drhc27a1ce2002-06-14 20:58:45 +00005262** end
5263**
drhe3184742002-06-19 14:27:05 +00005264** ORDER BY CLAUSE PROCESSING
5265**
drh94433422013-07-01 11:05:50 +00005266** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause
5267** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement
drhe3184742002-06-19 14:27:05 +00005268** if there is one. If there is no ORDER BY clause or if this routine
drh46ec5b62012-09-24 15:30:54 +00005269** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
drhfc8d4f92013-11-08 15:19:46 +00005270**
5271** The iIdxCur parameter is the cursor number of an index. If
5272** WHERE_ONETABLE_ONLY is set, iIdxCur is the cursor number of an index
5273** to use for OR clause processing. The WHERE clause should use this
5274** specific cursor. If WHERE_ONEPASS_DESIRED is set, then iIdxCur is
5275** the first cursor in an array of cursors for all indices. iIdxCur should
5276** be used to compute the appropriate cursor depending on which index is
5277** used.
drh75897232000-05-29 14:26:00 +00005278*/
danielk19774adee202004-05-08 08:23:19 +00005279WhereInfo *sqlite3WhereBegin(
danielk1977ed326d72004-11-16 15:50:19 +00005280 Parse *pParse, /* The parser context */
drh6457a352013-06-21 00:35:37 +00005281 SrcList *pTabList, /* FROM clause: A list of all tables to be scanned */
danielk1977ed326d72004-11-16 15:50:19 +00005282 Expr *pWhere, /* The WHERE clause */
drh46ec5b62012-09-24 15:30:54 +00005283 ExprList *pOrderBy, /* An ORDER BY clause, or NULL */
drh6457a352013-06-21 00:35:37 +00005284 ExprList *pResultSet, /* Result set of the query */
dan0efb72c2012-08-24 18:44:56 +00005285 u16 wctrlFlags, /* One of the WHERE_* flags defined in sqliteInt.h */
5286 int iIdxCur /* If WHERE_ONETABLE_ONLY is set, index cursor number */
drh75897232000-05-29 14:26:00 +00005287){
danielk1977be229652009-03-20 14:18:51 +00005288 int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
drhc01a3c12009-12-16 22:10:49 +00005289 int nTabList; /* Number of elements in pTabList */
drh75897232000-05-29 14:26:00 +00005290 WhereInfo *pWInfo; /* Will become the return value of this function */
5291 Vdbe *v = pParse->pVdbe; /* The virtual database engine */
drhfe05af82005-07-21 03:14:59 +00005292 Bitmask notReady; /* Cursors that are not yet positioned */
drh1c8148f2013-05-04 20:25:23 +00005293 WhereLoopBuilder sWLB; /* The WhereLoop builder */
drh111a6a72008-12-21 03:51:16 +00005294 WhereMaskSet *pMaskSet; /* The expression mask set */
drh56f1b992012-09-25 14:29:39 +00005295 WhereLevel *pLevel; /* A single level in pWInfo->a[] */
drhfd636c72013-06-21 02:05:06 +00005296 WhereLoop *pLoop; /* Pointer to a single WhereLoop object */
drh9cd1c992012-09-25 20:43:35 +00005297 int ii; /* Loop counter */
drh17435752007-08-16 04:30:38 +00005298 sqlite3 *db; /* Database connection */
drh5346e952013-05-08 14:14:26 +00005299 int rc; /* Return code */
drh75897232000-05-29 14:26:00 +00005300
drh56f1b992012-09-25 14:29:39 +00005301
5302 /* Variable initialization */
drhfd636c72013-06-21 02:05:06 +00005303 db = pParse->db;
drh1c8148f2013-05-04 20:25:23 +00005304 memset(&sWLB, 0, sizeof(sWLB));
drh1c8148f2013-05-04 20:25:23 +00005305 sWLB.pOrderBy = pOrderBy;
drh56f1b992012-09-25 14:29:39 +00005306
drhfd636c72013-06-21 02:05:06 +00005307 /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
5308 ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
5309 if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
5310 wctrlFlags &= ~WHERE_WANT_DISTINCT;
5311 }
5312
drh29dda4a2005-07-21 18:23:20 +00005313 /* The number of tables in the FROM clause is limited by the number of
drh1398ad32005-01-19 23:24:50 +00005314 ** bits in a Bitmask
5315 */
drh67ae0cb2010-04-08 14:38:51 +00005316 testcase( pTabList->nSrc==BMS );
drh29dda4a2005-07-21 18:23:20 +00005317 if( pTabList->nSrc>BMS ){
5318 sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
drh1398ad32005-01-19 23:24:50 +00005319 return 0;
5320 }
5321
drhc01a3c12009-12-16 22:10:49 +00005322 /* This function normally generates a nested loop for all tables in
5323 ** pTabList. But if the WHERE_ONETABLE_ONLY flag is set, then we should
5324 ** only generate code for the first table in pTabList and assume that
5325 ** any cursors associated with subsequent tables are uninitialized.
5326 */
5327 nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
5328
drh75897232000-05-29 14:26:00 +00005329 /* Allocate and initialize the WhereInfo structure that will become the
danielk1977be229652009-03-20 14:18:51 +00005330 ** return value. A single allocation is used to store the WhereInfo
5331 ** struct, the contents of WhereInfo.a[], the WhereClause structure
5332 ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
5333 ** field (type Bitmask) it must be aligned on an 8-byte boundary on
5334 ** some architectures. Hence the ROUND8() below.
drh75897232000-05-29 14:26:00 +00005335 */
drhc01a3c12009-12-16 22:10:49 +00005336 nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
drh60c96cd2013-06-09 17:21:25 +00005337 pWInfo = sqlite3DbMallocZero(db, nByteWInfo + sizeof(WhereLoop));
drh17435752007-08-16 04:30:38 +00005338 if( db->mallocFailed ){
drh8b307fb2010-04-06 15:57:05 +00005339 sqlite3DbFree(db, pWInfo);
5340 pWInfo = 0;
danielk197785574e32008-10-06 05:32:18 +00005341 goto whereBeginError;
drh75897232000-05-29 14:26:00 +00005342 }
drhfc8d4f92013-11-08 15:19:46 +00005343 pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1;
drhc01a3c12009-12-16 22:10:49 +00005344 pWInfo->nLevel = nTabList;
drh75897232000-05-29 14:26:00 +00005345 pWInfo->pParse = pParse;
5346 pWInfo->pTabList = pTabList;
drh6b7157b2013-05-10 02:00:35 +00005347 pWInfo->pOrderBy = pOrderBy;
drh6457a352013-06-21 00:35:37 +00005348 pWInfo->pResultSet = pResultSet;
danielk19774adee202004-05-08 08:23:19 +00005349 pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
drh6df2acd2008-12-28 16:55:25 +00005350 pWInfo->wctrlFlags = wctrlFlags;
drh8b307fb2010-04-06 15:57:05 +00005351 pWInfo->savedNQueryLoop = pParse->nQueryLoop;
drh70d18342013-06-06 19:16:33 +00005352 pMaskSet = &pWInfo->sMaskSet;
drh1c8148f2013-05-04 20:25:23 +00005353 sWLB.pWInfo = pWInfo;
drh70d18342013-06-06 19:16:33 +00005354 sWLB.pWC = &pWInfo->sWC;
drh1ac87e12013-07-18 14:50:56 +00005355 sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);
5356 assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) );
drh60c96cd2013-06-09 17:21:25 +00005357 whereLoopInit(sWLB.pNew);
drhb8a8e8a2013-06-10 19:12:39 +00005358#ifdef SQLITE_DEBUG
5359 sWLB.pNew->cId = '*';
5360#endif
drh08192d52002-04-30 19:20:28 +00005361
drh111a6a72008-12-21 03:51:16 +00005362 /* Split the WHERE clause into separate subexpressions where each
5363 ** subexpression is separated by an AND operator.
5364 */
5365 initMaskSet(pMaskSet);
drh70d18342013-06-06 19:16:33 +00005366 whereClauseInit(&pWInfo->sWC, pWInfo);
drh111a6a72008-12-21 03:51:16 +00005367 sqlite3ExprCodeConstants(pParse, pWhere);
drh39759742013-08-02 23:40:45 +00005368 whereSplit(&pWInfo->sWC, pWhere, TK_AND);
drh5e128b22013-07-09 03:04:32 +00005369 sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
drh111a6a72008-12-21 03:51:16 +00005370
drh08192d52002-04-30 19:20:28 +00005371 /* Special case: a WHERE clause that is constant. Evaluate the
5372 ** expression and either jump over all of the code or fall thru.
5373 */
drhc01a3c12009-12-16 22:10:49 +00005374 if( pWhere && (nTabList==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
drh35573352008-01-08 23:54:25 +00005375 sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
drhdf199a22002-06-14 22:38:41 +00005376 pWhere = 0;
drh08192d52002-04-30 19:20:28 +00005377 }
drh75897232000-05-29 14:26:00 +00005378
drh4fe425a2013-06-12 17:08:06 +00005379 /* Special case: No FROM clause
5380 */
5381 if( nTabList==0 ){
5382 if( pOrderBy ) pWInfo->bOBSat = 1;
drh6457a352013-06-21 00:35:37 +00005383 if( wctrlFlags & WHERE_WANT_DISTINCT ){
5384 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
5385 }
drh4fe425a2013-06-12 17:08:06 +00005386 }
5387
drh42165be2008-03-26 14:56:34 +00005388 /* Assign a bit from the bitmask to every term in the FROM clause.
5389 **
5390 ** When assigning bitmask values to FROM clause cursors, it must be
5391 ** the case that if X is the bitmask for the N-th FROM clause term then
5392 ** the bitmask for all FROM clause terms to the left of the N-th term
5393 ** is (X-1). An expression from the ON clause of a LEFT JOIN can use
5394 ** its Expr.iRightJoinTable value to find the bitmask of the right table
5395 ** of the join. Subtracting one from the right table bitmask gives a
5396 ** bitmask for all tables to the left of the join. Knowing the bitmask
5397 ** for all tables to the left of a left join is important. Ticket #3015.
danielk1977e672c8e2009-05-22 15:43:26 +00005398 **
drhc01a3c12009-12-16 22:10:49 +00005399 ** Note that bitmasks are created for all pTabList->nSrc tables in
5400 ** pTabList, not just the first nTabList tables. nTabList is normally
5401 ** equal to pTabList->nSrc but might be shortened to 1 if the
5402 ** WHERE_ONETABLE_ONLY flag is set.
drh42165be2008-03-26 14:56:34 +00005403 */
drh9cd1c992012-09-25 20:43:35 +00005404 for(ii=0; ii<pTabList->nSrc; ii++){
5405 createMask(pMaskSet, pTabList->a[ii].iCursor);
drh42165be2008-03-26 14:56:34 +00005406 }
5407#ifndef NDEBUG
5408 {
5409 Bitmask toTheLeft = 0;
drh9cd1c992012-09-25 20:43:35 +00005410 for(ii=0; ii<pTabList->nSrc; ii++){
5411 Bitmask m = getMask(pMaskSet, pTabList->a[ii].iCursor);
drh42165be2008-03-26 14:56:34 +00005412 assert( (m-1)==toTheLeft );
5413 toTheLeft |= m;
5414 }
5415 }
5416#endif
5417
drh29dda4a2005-07-21 18:23:20 +00005418 /* Analyze all of the subexpressions. Note that exprAnalyze() might
5419 ** add new virtual terms onto the end of the WHERE clause. We do not
5420 ** want to analyze these virtual terms, so start analyzing at the end
drhb6fb62d2005-09-20 08:47:20 +00005421 ** and work forward so that the added virtual terms are never processed.
drh75897232000-05-29 14:26:00 +00005422 */
drh70d18342013-06-06 19:16:33 +00005423 exprAnalyzeAll(pTabList, &pWInfo->sWC);
drh17435752007-08-16 04:30:38 +00005424 if( db->mallocFailed ){
danielk197785574e32008-10-06 05:32:18 +00005425 goto whereBeginError;
drh0bbaa1b2005-08-19 19:14:12 +00005426 }
drh75897232000-05-29 14:26:00 +00005427
drh4f402f22013-06-11 18:59:38 +00005428 /* If the ORDER BY (or GROUP BY) clause contains references to general
5429 ** expressions, then we won't be able to satisfy it using indices, so
5430 ** go ahead and disable it now.
5431 */
drh6457a352013-06-21 00:35:37 +00005432 if( pOrderBy && (wctrlFlags & WHERE_WANT_DISTINCT)!=0 ){
drh4f402f22013-06-11 18:59:38 +00005433 for(ii=0; ii<pOrderBy->nExpr; ii++){
5434 Expr *pExpr = sqlite3ExprSkipCollate(pOrderBy->a[ii].pExpr);
5435 if( pExpr->op!=TK_COLUMN ){
5436 pWInfo->pOrderBy = pOrderBy = 0;
5437 break;
drhe217efc2013-06-12 03:48:41 +00005438 }else if( pExpr->iColumn<0 ){
5439 break;
drh4f402f22013-06-11 18:59:38 +00005440 }
5441 }
5442 }
5443
drh6457a352013-06-21 00:35:37 +00005444 if( wctrlFlags & WHERE_WANT_DISTINCT ){
5445 if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){
5446 /* The DISTINCT marking is pointless. Ignore it. */
drh4f402f22013-06-11 18:59:38 +00005447 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
5448 }else if( pOrderBy==0 ){
drh6457a352013-06-21 00:35:37 +00005449 /* Try to ORDER BY the result set to make distinct processing easier */
drh4f402f22013-06-11 18:59:38 +00005450 pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
drh6457a352013-06-21 00:35:37 +00005451 pWInfo->pOrderBy = pResultSet;
drh4f402f22013-06-11 18:59:38 +00005452 }
dan38cc40c2011-06-30 20:17:15 +00005453 }
5454
drhf1b5f5b2013-05-02 00:15:01 +00005455 /* Construct the WhereLoop objects */
drh3b48e8c2013-06-12 20:18:16 +00005456 WHERETRACE(0xffff,("*** Optimizer Start ***\n"));
drhf4e9cb02013-10-28 19:59:59 +00005457 /* Display all terms of the WHERE clause */
5458#if defined(WHERETRACE_ENABLED) && defined(SQLITE_ENABLE_TREE_EXPLAIN)
5459 if( sqlite3WhereTrace & 0x100 ){
5460 int i;
5461 Vdbe *v = pParse->pVdbe;
5462 sqlite3ExplainBegin(v);
5463 for(i=0; i<sWLB.pWC->nTerm; i++){
drh7afc8b02013-10-28 22:33:36 +00005464 sqlite3ExplainPrintf(v, "#%-2d ", i);
drhf4e9cb02013-10-28 19:59:59 +00005465 sqlite3ExplainPush(v);
5466 whereExplainTerm(v, &sWLB.pWC->a[i]);
5467 sqlite3ExplainPop(v);
5468 sqlite3ExplainNL(v);
5469 }
5470 sqlite3ExplainFinish(v);
5471 sqlite3DebugPrintf("%s", sqlite3VdbeExplanation(v));
5472 }
5473#endif
drhb8a8e8a2013-06-10 19:12:39 +00005474 if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
drh60c96cd2013-06-09 17:21:25 +00005475 rc = whereLoopAddAll(&sWLB);
5476 if( rc ) goto whereBeginError;
5477
5478 /* Display all of the WhereLoop objects if wheretrace is enabled */
drh989578e2013-10-28 14:34:35 +00005479#ifdef WHERETRACE_ENABLED /* !=0 */
drh60c96cd2013-06-09 17:21:25 +00005480 if( sqlite3WhereTrace ){
5481 WhereLoop *p;
drhfd636c72013-06-21 02:05:06 +00005482 int i;
drh60c96cd2013-06-09 17:21:25 +00005483 static char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
5484 "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
drhfd636c72013-06-21 02:05:06 +00005485 for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
5486 p->cId = zLabel[i%sizeof(zLabel)];
drhc1ba2e72013-10-28 19:03:21 +00005487 whereLoopPrint(p, sWLB.pWC);
drh60c96cd2013-06-09 17:21:25 +00005488 }
5489 }
5490#endif
5491
drh4f402f22013-06-11 18:59:38 +00005492 wherePathSolver(pWInfo, 0);
drh60c96cd2013-06-09 17:21:25 +00005493 if( db->mallocFailed ) goto whereBeginError;
5494 if( pWInfo->pOrderBy ){
drhc7f0d222013-06-19 03:27:12 +00005495 wherePathSolver(pWInfo, pWInfo->nRowOut+1);
drh60c96cd2013-06-09 17:21:25 +00005496 if( db->mallocFailed ) goto whereBeginError;
drha18f3d22013-05-08 03:05:41 +00005497 }
5498 }
drh60c96cd2013-06-09 17:21:25 +00005499 if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
drhd84ce352013-06-04 18:27:41 +00005500 pWInfo->revMask = (Bitmask)(-1);
drha50ef112013-05-22 02:06:59 +00005501 }
drh81186b42013-06-18 01:52:41 +00005502 if( pParse->nErr || NEVER(db->mallocFailed) ){
drh75b93402013-05-31 20:43:57 +00005503 goto whereBeginError;
5504 }
drh989578e2013-10-28 14:34:35 +00005505#ifdef WHERETRACE_ENABLED /* !=0 */
drha18f3d22013-05-08 03:05:41 +00005506 if( sqlite3WhereTrace ){
5507 int ii;
drh4f402f22013-06-11 18:59:38 +00005508 sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
5509 if( pWInfo->bOBSat ){
5510 sqlite3DebugPrintf(" ORDERBY=0x%llx", pWInfo->revMask);
drh319f6772013-05-14 15:31:07 +00005511 }
drh4f402f22013-06-11 18:59:38 +00005512 switch( pWInfo->eDistinct ){
5513 case WHERE_DISTINCT_UNIQUE: {
5514 sqlite3DebugPrintf(" DISTINCT=unique");
5515 break;
5516 }
5517 case WHERE_DISTINCT_ORDERED: {
5518 sqlite3DebugPrintf(" DISTINCT=ordered");
5519 break;
5520 }
5521 case WHERE_DISTINCT_UNORDERED: {
5522 sqlite3DebugPrintf(" DISTINCT=unordered");
5523 break;
5524 }
5525 }
5526 sqlite3DebugPrintf("\n");
drhfd636c72013-06-21 02:05:06 +00005527 for(ii=0; ii<pWInfo->nLevel; ii++){
drhc1ba2e72013-10-28 19:03:21 +00005528 whereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC);
drhf1b5f5b2013-05-02 00:15:01 +00005529 }
5530 }
5531#endif
drhfd636c72013-06-21 02:05:06 +00005532 /* Attempt to omit tables from the join that do not effect the result */
drh1031bd92013-06-22 15:44:26 +00005533 if( pWInfo->nLevel>=2
5534 && pResultSet!=0
5535 && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
5536 ){
drhfd636c72013-06-21 02:05:06 +00005537 Bitmask tabUsed = exprListTableUsage(pMaskSet, pResultSet);
drh67a5ec72013-09-03 14:03:47 +00005538 if( sWLB.pOrderBy ) tabUsed |= exprListTableUsage(pMaskSet, sWLB.pOrderBy);
drhfd636c72013-06-21 02:05:06 +00005539 while( pWInfo->nLevel>=2 ){
drh9d5a5792013-06-28 13:43:33 +00005540 WhereTerm *pTerm, *pEnd;
drhfd636c72013-06-21 02:05:06 +00005541 pLoop = pWInfo->a[pWInfo->nLevel-1].pWLoop;
drhbc71b1d2013-06-21 02:15:48 +00005542 if( (pWInfo->pTabList->a[pLoop->iTab].jointype & JT_LEFT)==0 ) break;
5543 if( (wctrlFlags & WHERE_WANT_DISTINCT)==0
5544 && (pLoop->wsFlags & WHERE_ONEROW)==0
drhfd636c72013-06-21 02:05:06 +00005545 ){
drhfd636c72013-06-21 02:05:06 +00005546 break;
5547 }
drhbc71b1d2013-06-21 02:15:48 +00005548 if( (tabUsed & pLoop->maskSelf)!=0 ) break;
drh9d5a5792013-06-28 13:43:33 +00005549 pEnd = sWLB.pWC->a + sWLB.pWC->nTerm;
5550 for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
5551 if( (pTerm->prereqAll & pLoop->maskSelf)!=0
5552 && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
5553 ){
5554 break;
5555 }
5556 }
5557 if( pTerm<pEnd ) break;
drhbc71b1d2013-06-21 02:15:48 +00005558 WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId));
5559 pWInfo->nLevel--;
5560 nTabList--;
drhfd636c72013-06-21 02:05:06 +00005561 }
5562 }
drh3b48e8c2013-06-12 20:18:16 +00005563 WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
drh8e23daf2013-06-11 13:30:04 +00005564 pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
drhf1b5f5b2013-05-02 00:15:01 +00005565
drh08c88eb2008-04-10 13:33:18 +00005566 /* If the caller is an UPDATE or DELETE statement that is requesting
5567 ** to use a one-pass algorithm, determine if this is appropriate.
drh24b7fe92013-09-30 19:33:06 +00005568 ** The one-pass algorithm only works if the WHERE clause constrains
drh08c88eb2008-04-10 13:33:18 +00005569 ** the statement to update a single row.
5570 */
drh165be382008-12-05 02:36:33 +00005571 assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
drh3b48e8c2013-06-12 20:18:16 +00005572 if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
5573 && (pWInfo->a[0].pWLoop->wsFlags & WHERE_ONEROW)!=0 ){
drh08c88eb2008-04-10 13:33:18 +00005574 pWInfo->okOnePass = 1;
drh702ba9f2013-11-07 21:25:13 +00005575 if( HasRowid(pTabList->a[0].pTab) ){
5576 pWInfo->a[0].pWLoop->wsFlags &= ~WHERE_IDX_ONLY;
5577 }
drh08c88eb2008-04-10 13:33:18 +00005578 }
drheb04de32013-05-10 15:16:30 +00005579
drh9012bcb2004-12-19 00:11:35 +00005580 /* Open all tables in the pTabList and any indices selected for
5581 ** searching those tables.
5582 */
drh8b307fb2010-04-06 15:57:05 +00005583 notReady = ~(Bitmask)0;
drh9cd1c992012-09-25 20:43:35 +00005584 for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
danielk1977da184232006-01-05 11:34:32 +00005585 Table *pTab; /* Table to open */
danielk1977da184232006-01-05 11:34:32 +00005586 int iDb; /* Index of database containing table/index */
drh56f1b992012-09-25 14:29:39 +00005587 struct SrcList_item *pTabItem;
drh9012bcb2004-12-19 00:11:35 +00005588
drh29dda4a2005-07-21 18:23:20 +00005589 pTabItem = &pTabList->a[pLevel->iFrom];
drh9012bcb2004-12-19 00:11:35 +00005590 pTab = pTabItem->pTab;
danielk1977595a5232009-07-24 17:58:53 +00005591 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
drh7ba39a92013-05-30 17:43:19 +00005592 pLoop = pLevel->pWLoop;
drh424aab82010-04-06 18:28:20 +00005593 if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
drh75bb9f52010-04-06 18:51:42 +00005594 /* Do nothing */
5595 }else
drh9eff6162006-06-12 21:59:13 +00005596#ifndef SQLITE_OMIT_VIRTUALTABLE
drh7ba39a92013-05-30 17:43:19 +00005597 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
danielk1977595a5232009-07-24 17:58:53 +00005598 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
danielk197793626f42006-06-20 13:07:27 +00005599 int iCur = pTabItem->iCursor;
danielk1977595a5232009-07-24 17:58:53 +00005600 sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
drhfc5e5462012-12-03 17:04:40 +00005601 }else if( IsVirtual(pTab) ){
5602 /* noop */
drh9eff6162006-06-12 21:59:13 +00005603 }else
5604#endif
drh7ba39a92013-05-30 17:43:19 +00005605 if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
drh9ef61f42011-10-07 14:40:59 +00005606 && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){
drhfc8d4f92013-11-08 15:19:46 +00005607 int op = OP_OpenRead;
5608 if( pWInfo->okOnePass ){
5609 op = OP_OpenWrite;
5610 pWInfo->aiCurOnePass[0] = pTabItem->iCursor;
5611 };
drh08c88eb2008-04-10 13:33:18 +00005612 sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
drhfc8d4f92013-11-08 15:19:46 +00005613 assert( pTabItem->iCursor==pLevel->iTabCur );
drh7963b0e2013-06-17 21:37:40 +00005614 testcase( !pWInfo->okOnePass && pTab->nCol==BMS-1 );
5615 testcase( !pWInfo->okOnePass && pTab->nCol==BMS );
drhdd9930e2013-10-23 23:37:02 +00005616 if( !pWInfo->okOnePass && pTab->nCol<BMS && HasRowid(pTab) ){
danielk19779792eef2006-01-13 15:58:43 +00005617 Bitmask b = pTabItem->colUsed;
5618 int n = 0;
drh74161702006-02-24 02:53:49 +00005619 for(; b; b=b>>1, n++){}
drh8cff69d2009-11-12 19:59:44 +00005620 sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
5621 SQLITE_INT_TO_PTR(n), P4_INT32);
danielk19779792eef2006-01-13 15:58:43 +00005622 assert( n<=pTab->nCol );
5623 }
danielk1977c00da102006-01-07 13:21:04 +00005624 }else{
5625 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
drh9012bcb2004-12-19 00:11:35 +00005626 }
drh7e47cb82013-05-31 17:55:27 +00005627 if( pLoop->wsFlags & WHERE_INDEXED ){
drh7ba39a92013-05-30 17:43:19 +00005628 Index *pIx = pLoop->u.btree.pIndex;
drhfc8d4f92013-11-08 15:19:46 +00005629 int iIndexCur;
5630 int op = OP_OpenRead;
drh4308e342013-11-11 16:55:52 +00005631 /* iIdxCur is always set if to a positive value if ONEPASS is possible */
5632 assert( iIdxCur!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 );
5633 if( pWInfo->okOnePass ){
drhfc8d4f92013-11-08 15:19:46 +00005634 Index *pJ = pTabItem->pTab->pIndex;
5635 iIndexCur = iIdxCur;
5636 assert( wctrlFlags & WHERE_ONEPASS_DESIRED );
5637 while( ALWAYS(pJ) && pJ!=pIx ){
5638 iIndexCur++;
5639 pJ = pJ->pNext;
5640 }
5641 op = OP_OpenWrite;
5642 pWInfo->aiCurOnePass[1] = iIndexCur;
5643 }else if( iIdxCur && (wctrlFlags & WHERE_ONETABLE_ONLY)!=0 ){
5644 iIndexCur = iIdxCur;
5645 }else{
5646 iIndexCur = pParse->nTab++;
5647 }
5648 pLevel->iIdxCur = iIndexCur;
danielk1977da184232006-01-05 11:34:32 +00005649 assert( pIx->pSchema==pTab->pSchema );
drhb0367fb2012-08-25 02:11:13 +00005650 assert( iIndexCur>=0 );
drhfc8d4f92013-11-08 15:19:46 +00005651 sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb);
drh2ec2fb22013-11-06 19:59:23 +00005652 sqlite3VdbeSetP4KeyInfo(pParse, pIx);
danielk1977207872a2008-01-03 07:54:23 +00005653 VdbeComment((v, "%s", pIx->zName));
drh9012bcb2004-12-19 00:11:35 +00005654 }
danielk1977da184232006-01-05 11:34:32 +00005655 sqlite3CodeVerifySchema(pParse, iDb);
drh70d18342013-06-06 19:16:33 +00005656 notReady &= ~getMask(&pWInfo->sMaskSet, pTabItem->iCursor);
drh9012bcb2004-12-19 00:11:35 +00005657 }
5658 pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
drha21a64d2010-04-06 22:33:55 +00005659 if( db->mallocFailed ) goto whereBeginError;
drh9012bcb2004-12-19 00:11:35 +00005660
drh29dda4a2005-07-21 18:23:20 +00005661 /* Generate the code to do the search. Each iteration of the for
5662 ** loop below generates code for a single nested loop of the VM
5663 ** program.
drh75897232000-05-29 14:26:00 +00005664 */
drhfe05af82005-07-21 03:14:59 +00005665 notReady = ~(Bitmask)0;
drh9cd1c992012-09-25 20:43:35 +00005666 for(ii=0; ii<nTabList; ii++){
5667 pLevel = &pWInfo->a[ii];
drhcc04afd2013-08-22 02:56:28 +00005668#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
5669 if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){
5670 constructAutomaticIndex(pParse, &pWInfo->sWC,
5671 &pTabList->a[pLevel->iFrom], notReady, pLevel);
5672 if( db->mallocFailed ) goto whereBeginError;
5673 }
5674#endif
drh9cd1c992012-09-25 20:43:35 +00005675 explainOneScan(pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags);
drhcc04afd2013-08-22 02:56:28 +00005676 pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
drh70d18342013-06-06 19:16:33 +00005677 notReady = codeOneLoopStart(pWInfo, ii, notReady);
dan4a07e3d2010-11-09 14:48:59 +00005678 pWInfo->iContinue = pLevel->addrCont;
drh75897232000-05-29 14:26:00 +00005679 }
drh7ec764a2005-07-21 03:48:20 +00005680
drh6fa978d2013-05-30 19:29:19 +00005681 /* Done. */
drh5e6790c2013-11-12 20:18:14 +00005682 VdbeNoopComment((v, "Begin WHERE-core"));
drh75897232000-05-29 14:26:00 +00005683 return pWInfo;
drhe23399f2005-07-22 00:31:39 +00005684
5685 /* Jump here if malloc fails */
danielk197785574e32008-10-06 05:32:18 +00005686whereBeginError:
drh8b307fb2010-04-06 15:57:05 +00005687 if( pWInfo ){
5688 pParse->nQueryLoop = pWInfo->savedNQueryLoop;
5689 whereInfoFree(db, pWInfo);
5690 }
drhe23399f2005-07-22 00:31:39 +00005691 return 0;
drh75897232000-05-29 14:26:00 +00005692}
5693
5694/*
drhc27a1ce2002-06-14 20:58:45 +00005695** Generate the end of the WHERE loop. See comments on
danielk19774adee202004-05-08 08:23:19 +00005696** sqlite3WhereBegin() for additional information.
drh75897232000-05-29 14:26:00 +00005697*/
danielk19774adee202004-05-08 08:23:19 +00005698void sqlite3WhereEnd(WhereInfo *pWInfo){
drh633e6d52008-07-28 19:34:53 +00005699 Parse *pParse = pWInfo->pParse;
5700 Vdbe *v = pParse->pVdbe;
drh19a775c2000-06-05 18:54:46 +00005701 int i;
drh6b563442001-11-07 16:48:26 +00005702 WhereLevel *pLevel;
drh7ba39a92013-05-30 17:43:19 +00005703 WhereLoop *pLoop;
drhad3cab52002-05-24 02:04:32 +00005704 SrcList *pTabList = pWInfo->pTabList;
drh633e6d52008-07-28 19:34:53 +00005705 sqlite3 *db = pParse->db;
drh19a775c2000-06-05 18:54:46 +00005706
drh9012bcb2004-12-19 00:11:35 +00005707 /* Generate loop termination code.
5708 */
drh5e6790c2013-11-12 20:18:14 +00005709 VdbeNoopComment((v, "End WHERE-core"));
drhceea3322009-04-23 13:22:42 +00005710 sqlite3ExprCacheClear(pParse);
drhc01a3c12009-12-16 22:10:49 +00005711 for(i=pWInfo->nLevel-1; i>=0; i--){
drh6b563442001-11-07 16:48:26 +00005712 pLevel = &pWInfo->a[i];
drh7ba39a92013-05-30 17:43:19 +00005713 pLoop = pLevel->pWLoop;
drhb3190c12008-12-08 21:37:14 +00005714 sqlite3VdbeResolveLabel(v, pLevel->addrCont);
drh6b563442001-11-07 16:48:26 +00005715 if( pLevel->op!=OP_Noop ){
drh66a51672008-01-03 00:01:23 +00005716 sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
drhd1d38482008-10-07 23:46:38 +00005717 sqlite3VdbeChangeP5(v, pLevel->p5);
drh19a775c2000-06-05 18:54:46 +00005718 }
drh7ba39a92013-05-30 17:43:19 +00005719 if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
drh72e8fa42007-03-28 14:30:06 +00005720 struct InLoop *pIn;
drhe23399f2005-07-22 00:31:39 +00005721 int j;
drhb3190c12008-12-08 21:37:14 +00005722 sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
drh111a6a72008-12-21 03:51:16 +00005723 for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
drhb3190c12008-12-08 21:37:14 +00005724 sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
drh2d96b932013-02-08 18:48:23 +00005725 sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
drhb3190c12008-12-08 21:37:14 +00005726 sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
drhe23399f2005-07-22 00:31:39 +00005727 }
drh111a6a72008-12-21 03:51:16 +00005728 sqlite3DbFree(db, pLevel->u.in.aInLoop);
drhd99f7062002-06-08 23:25:08 +00005729 }
drhb3190c12008-12-08 21:37:14 +00005730 sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
drhad2d8302002-05-24 20:31:36 +00005731 if( pLevel->iLeftJoin ){
5732 int addr;
drh3c84ddf2008-01-09 02:15:38 +00005733 addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
drh7ba39a92013-05-30 17:43:19 +00005734 assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
5735 || (pLoop->wsFlags & WHERE_INDEXED)!=0 );
5736 if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 ){
drh35451c62009-11-12 04:26:39 +00005737 sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
5738 }
drh76f4cfb2013-05-31 18:20:52 +00005739 if( pLoop->wsFlags & WHERE_INDEXED ){
drh3c84ddf2008-01-09 02:15:38 +00005740 sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
drh7f09b3e2002-08-13 13:15:49 +00005741 }
drh336a5302009-04-24 15:46:21 +00005742 if( pLevel->op==OP_Return ){
5743 sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
5744 }else{
5745 sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
5746 }
drhd654be82005-09-20 17:42:23 +00005747 sqlite3VdbeJumpHere(v, addr);
drhad2d8302002-05-24 20:31:36 +00005748 }
drh5e6790c2013-11-12 20:18:14 +00005749 VdbeNoopComment((v, "End WHERE-loop%d: %s", i,
drhfc8d4f92013-11-08 15:19:46 +00005750 pWInfo->pTabList->a[pLevel->iFrom].pTab->zName));
drh19a775c2000-06-05 18:54:46 +00005751 }
drh9012bcb2004-12-19 00:11:35 +00005752
5753 /* The "break" point is here, just past the end of the outer loop.
5754 ** Set it.
5755 */
danielk19774adee202004-05-08 08:23:19 +00005756 sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
drh9012bcb2004-12-19 00:11:35 +00005757
drhfd636c72013-06-21 02:05:06 +00005758 assert( pWInfo->nLevel<=pTabList->nSrc );
drhc01a3c12009-12-16 22:10:49 +00005759 for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
danbfca6a42012-08-24 10:52:35 +00005760 Index *pIdx = 0;
drh29dda4a2005-07-21 18:23:20 +00005761 struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
drh9012bcb2004-12-19 00:11:35 +00005762 Table *pTab = pTabItem->pTab;
drh5cf590c2003-04-24 01:45:04 +00005763 assert( pTab!=0 );
drh7ba39a92013-05-30 17:43:19 +00005764 pLoop = pLevel->pWLoop;
drhfc8d4f92013-11-08 15:19:46 +00005765
5766 /* Close all of the cursors that were opened by sqlite3WhereBegin.
5767 ** Except, do not close cursors that will be reused by the OR optimization
5768 ** (WHERE_OMIT_OPEN_CLOSE). And do not close the OP_OpenWrite cursors
5769 ** created for the ONEPASS optimization.
5770 */
drh4139c992010-04-07 14:59:45 +00005771 if( (pTab->tabFlags & TF_Ephemeral)==0
5772 && pTab->pSelect==0
drh9ef61f42011-10-07 14:40:59 +00005773 && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
drh4139c992010-04-07 14:59:45 +00005774 ){
drh7ba39a92013-05-30 17:43:19 +00005775 int ws = pLoop->wsFlags;
drh8b307fb2010-04-06 15:57:05 +00005776 if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
drh6df2acd2008-12-28 16:55:25 +00005777 sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
5778 }
drhfc8d4f92013-11-08 15:19:46 +00005779 if( (ws & WHERE_INDEXED)!=0
5780 && (ws & (WHERE_IPK|WHERE_AUTO_INDEX))==0
5781 && pLevel->iIdxCur!=pWInfo->aiCurOnePass[1]
5782 ){
drh6df2acd2008-12-28 16:55:25 +00005783 sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
5784 }
drh9012bcb2004-12-19 00:11:35 +00005785 }
5786
drhf0030762013-06-14 13:27:01 +00005787 /* If this scan uses an index, make VDBE code substitutions to read data
5788 ** from the index instead of from the table where possible. In some cases
5789 ** this optimization prevents the table from ever being read, which can
5790 ** yield a significant performance boost.
drh9012bcb2004-12-19 00:11:35 +00005791 **
5792 ** Calls to the code generator in between sqlite3WhereBegin and
5793 ** sqlite3WhereEnd will have created code that references the table
5794 ** directly. This loop scans all that code looking for opcodes
5795 ** that reference the table and converts them into opcodes that
5796 ** reference the index.
5797 */
drh7ba39a92013-05-30 17:43:19 +00005798 if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
5799 pIdx = pLoop->u.btree.pIndex;
5800 }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
drhd40e2082012-08-24 23:24:15 +00005801 pIdx = pLevel->u.pCovidx;
danbfca6a42012-08-24 10:52:35 +00005802 }
drh7ba39a92013-05-30 17:43:19 +00005803 if( pIdx && !db->mallocFailed ){
drh44156282013-10-23 22:23:03 +00005804 int k, last;
drh9012bcb2004-12-19 00:11:35 +00005805 VdbeOp *pOp;
drh9012bcb2004-12-19 00:11:35 +00005806
drh9012bcb2004-12-19 00:11:35 +00005807 last = sqlite3VdbeCurrentAddr(v);
drhcc04afd2013-08-22 02:56:28 +00005808 k = pLevel->addrBody;
5809 pOp = sqlite3VdbeGetOp(v, k);
5810 for(; k<last; k++, pOp++){
drh9012bcb2004-12-19 00:11:35 +00005811 if( pOp->p1!=pLevel->iTabCur ) continue;
5812 if( pOp->opcode==OP_Column ){
drhee0ec8e2013-10-31 17:38:01 +00005813 int x = pOp->p2;
drh511717c2013-11-08 17:13:23 +00005814 assert( pIdx->pTable==pTab );
drhee0ec8e2013-10-31 17:38:01 +00005815 if( !HasRowid(pTab) ){
5816 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
5817 x = pPk->aiColumn[x];
5818 }
5819 x = sqlite3ColumnOfIndex(pIdx, x);
drh44156282013-10-23 22:23:03 +00005820 if( x>=0 ){
5821 pOp->p2 = x;
5822 pOp->p1 = pLevel->iIdxCur;
drh9012bcb2004-12-19 00:11:35 +00005823 }
drh44156282013-10-23 22:23:03 +00005824 assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || x>=0 );
drhf0863fe2005-06-12 21:35:51 +00005825 }else if( pOp->opcode==OP_Rowid ){
drh9012bcb2004-12-19 00:11:35 +00005826 pOp->p1 = pLevel->iIdxCur;
drhf0863fe2005-06-12 21:35:51 +00005827 pOp->opcode = OP_IdxRowid;
drh9012bcb2004-12-19 00:11:35 +00005828 }
5829 }
drh6b563442001-11-07 16:48:26 +00005830 }
drh19a775c2000-06-05 18:54:46 +00005831 }
drh9012bcb2004-12-19 00:11:35 +00005832
5833 /* Final cleanup
5834 */
drhf12cde52010-04-08 17:28:00 +00005835 pParse->nQueryLoop = pWInfo->savedNQueryLoop;
5836 whereInfoFree(db, pWInfo);
drh75897232000-05-29 14:26:00 +00005837 return;
5838}