blob: 15bcb1ebde501f55ff60239fc42eea2f27e6b009 [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
drh6ade4532014-01-16 15:31:41 +0000670 pRight = sqlite3ExprSkipCollate(pList->a[0].pExpr);
dan937d0de2009-10-15 18:35:38 +0000671 op = pRight->op;
dan937d0de2009-10-15 18:35:38 +0000672 if( op==TK_VARIABLE ){
673 Vdbe *pReprepare = pParse->pReprepare;
drha7044002010-09-14 18:22:59 +0000674 int iCol = pRight->iColumn;
drhcf0fd4a2013-08-01 12:21:58 +0000675 pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_NONE);
dan937d0de2009-10-15 18:35:38 +0000676 if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
677 z = (char *)sqlite3_value_text(pVal);
678 }
drhf9b22ca2011-10-21 16:47:31 +0000679 sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
dan937d0de2009-10-15 18:35:38 +0000680 assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
681 }else if( op==TK_STRING ){
682 z = pRight->u.zToken;
683 }
684 if( z ){
shane85095702009-06-15 16:27:08 +0000685 cnt = 0;
drhb7916a72009-05-27 10:31:29 +0000686 while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
drh24fb6272009-05-01 21:13:36 +0000687 cnt++;
688 }
drh93ee23c2010-07-22 12:33:57 +0000689 if( cnt!=0 && 255!=(u8)z[cnt-1] ){
dan937d0de2009-10-15 18:35:38 +0000690 Expr *pPrefix;
drh93ee23c2010-07-22 12:33:57 +0000691 *pisComplete = c==wc[0] && z[cnt+1]==0;
dan937d0de2009-10-15 18:35:38 +0000692 pPrefix = sqlite3Expr(db, TK_STRING, z);
693 if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
694 *ppPrefix = pPrefix;
695 if( op==TK_VARIABLE ){
696 Vdbe *v = pParse->pVdbe;
drhf9b22ca2011-10-21 16:47:31 +0000697 sqlite3VdbeSetVarmask(v, pRight->iColumn);
dan937d0de2009-10-15 18:35:38 +0000698 if( *pisComplete && pRight->u.zToken[1] ){
699 /* If the rhs of the LIKE expression is a variable, and the current
700 ** value of the variable means there is no need to invoke the LIKE
701 ** function, then no OP_Variable will be added to the program.
702 ** This causes problems for the sqlite3_bind_parameter_name()
drhbec451f2009-10-17 13:13:02 +0000703 ** API. To workaround them, add a dummy OP_Variable here.
704 */
705 int r1 = sqlite3GetTempReg(pParse);
706 sqlite3ExprCodeTarget(pParse, pRight, r1);
dan937d0de2009-10-15 18:35:38 +0000707 sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
drhbec451f2009-10-17 13:13:02 +0000708 sqlite3ReleaseTempReg(pParse, r1);
dan937d0de2009-10-15 18:35:38 +0000709 }
710 }
711 }else{
712 z = 0;
shane85095702009-06-15 16:27:08 +0000713 }
drhf998b732007-11-26 13:36:00 +0000714 }
dan937d0de2009-10-15 18:35:38 +0000715
716 sqlite3ValueFree(pVal);
717 return (z!=0);
drhd2687b72005-08-12 22:56:09 +0000718}
719#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
720
drhedb193b2006-06-27 13:20:21 +0000721
722#ifndef SQLITE_OMIT_VIRTUALTABLE
drhfe05af82005-07-21 03:14:59 +0000723/*
drh7f375902006-06-13 17:38:59 +0000724** Check to see if the given expression is of the form
725**
726** column MATCH expr
727**
728** If it is then return TRUE. If not, return FALSE.
729*/
730static int isMatchOfColumn(
731 Expr *pExpr /* Test this expression */
732){
733 ExprList *pList;
734
735 if( pExpr->op!=TK_FUNCTION ){
736 return 0;
737 }
drh33e619f2009-05-28 01:00:55 +0000738 if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
drh7f375902006-06-13 17:38:59 +0000739 return 0;
740 }
danielk19776ab3a2e2009-02-19 14:39:25 +0000741 pList = pExpr->x.pList;
drh7f375902006-06-13 17:38:59 +0000742 if( pList->nExpr!=2 ){
743 return 0;
744 }
745 if( pList->a[1].pExpr->op != TK_COLUMN ){
746 return 0;
747 }
748 return 1;
749}
drhedb193b2006-06-27 13:20:21 +0000750#endif /* SQLITE_OMIT_VIRTUALTABLE */
drh7f375902006-06-13 17:38:59 +0000751
752/*
drh54a167d2005-11-26 14:08:07 +0000753** If the pBase expression originated in the ON or USING clause of
754** a join, then transfer the appropriate markings over to derived.
755*/
756static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
drhd41d39f2013-08-28 16:27:01 +0000757 if( pDerived ){
758 pDerived->flags |= pBase->flags & EP_FromJoin;
759 pDerived->iRightJoinTable = pBase->iRightJoinTable;
760 }
drh54a167d2005-11-26 14:08:07 +0000761}
762
drh3e355802007-02-23 23:13:33 +0000763#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
764/*
drh1a58fe02008-12-20 02:06:13 +0000765** Analyze a term that consists of two or more OR-connected
766** subterms. So in:
drh3e355802007-02-23 23:13:33 +0000767**
drh1a58fe02008-12-20 02:06:13 +0000768** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
769** ^^^^^^^^^^^^^^^^^^^^
drh3e355802007-02-23 23:13:33 +0000770**
drh1a58fe02008-12-20 02:06:13 +0000771** This routine analyzes terms such as the middle term in the above example.
772** A WhereOrTerm object is computed and attached to the term under
773** analysis, regardless of the outcome of the analysis. Hence:
drh3e355802007-02-23 23:13:33 +0000774**
drh1a58fe02008-12-20 02:06:13 +0000775** WhereTerm.wtFlags |= TERM_ORINFO
776** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object
drh3e355802007-02-23 23:13:33 +0000777**
drh1a58fe02008-12-20 02:06:13 +0000778** The term being analyzed must have two or more of OR-connected subterms.
danielk1977fdc40192008-12-29 18:33:32 +0000779** A single subterm might be a set of AND-connected sub-subterms.
drh1a58fe02008-12-20 02:06:13 +0000780** Examples of terms under analysis:
drh3e355802007-02-23 23:13:33 +0000781**
drh1a58fe02008-12-20 02:06:13 +0000782** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
783** (B) x=expr1 OR expr2=x OR x=expr3
784** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
785** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
786** (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 +0000787**
drh1a58fe02008-12-20 02:06:13 +0000788** CASE 1:
789**
drhc3e552f2013-02-08 16:04:19 +0000790** If all subterms are of the form T.C=expr for some single column of C and
drh1a58fe02008-12-20 02:06:13 +0000791** a single table T (as shown in example B above) then create a new virtual
792** term that is an equivalent IN expression. In other words, if the term
793** being analyzed is:
794**
795** x = expr1 OR expr2 = x OR x = expr3
796**
797** then create a new virtual term like this:
798**
799** x IN (expr1,expr2,expr3)
800**
801** CASE 2:
802**
803** If all subterms are indexable by a single table T, then set
804**
805** WhereTerm.eOperator = WO_OR
806** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T
807**
808** A subterm is "indexable" if it is of the form
809** "T.C <op> <expr>" where C is any column of table T and
810** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
811** A subterm is also indexable if it is an AND of two or more
812** subsubterms at least one of which is indexable. Indexable AND
813** subterms have their eOperator set to WO_AND and they have
814** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
815**
816** From another point of view, "indexable" means that the subterm could
817** potentially be used with an index if an appropriate index exists.
818** This analysis does not consider whether or not the index exists; that
drh4a6fc352013-08-07 01:18:38 +0000819** is decided elsewhere. This analysis only looks at whether subterms
820** appropriate for indexing exist.
drh1a58fe02008-12-20 02:06:13 +0000821**
drh4a6fc352013-08-07 01:18:38 +0000822** All examples A through E above satisfy case 2. But if a term
drh1a58fe02008-12-20 02:06:13 +0000823** also statisfies case 1 (such as B) we know that the optimizer will
824** always prefer case 1, so in that case we pretend that case 2 is not
825** satisfied.
826**
827** It might be the case that multiple tables are indexable. For example,
828** (E) above is indexable on tables P, Q, and R.
829**
830** Terms that satisfy case 2 are candidates for lookup by using
831** separate indices to find rowids for each subterm and composing
832** the union of all rowids using a RowSet object. This is similar
833** to "bitmap indices" in other database engines.
834**
835** OTHERWISE:
836**
837** If neither case 1 nor case 2 apply, then leave the eOperator set to
838** zero. This term is not useful for search.
drh3e355802007-02-23 23:13:33 +0000839*/
drh1a58fe02008-12-20 02:06:13 +0000840static void exprAnalyzeOrTerm(
841 SrcList *pSrc, /* the FROM clause */
842 WhereClause *pWC, /* the complete WHERE clause */
843 int idxTerm /* Index of the OR-term to be analyzed */
844){
drh70d18342013-06-06 19:16:33 +0000845 WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
846 Parse *pParse = pWInfo->pParse; /* Parser context */
drh1a58fe02008-12-20 02:06:13 +0000847 sqlite3 *db = pParse->db; /* Database connection */
848 WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */
849 Expr *pExpr = pTerm->pExpr; /* The expression of the term */
drh1a58fe02008-12-20 02:06:13 +0000850 int i; /* Loop counters */
851 WhereClause *pOrWc; /* Breakup of pTerm into subterms */
852 WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */
853 WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */
854 Bitmask chngToIN; /* Tables that might satisfy case 1 */
855 Bitmask indexable; /* Tables that are indexable, satisfying case 2 */
drh3e355802007-02-23 23:13:33 +0000856
drh1a58fe02008-12-20 02:06:13 +0000857 /*
858 ** Break the OR clause into its separate subterms. The subterms are
859 ** stored in a WhereClause structure containing within the WhereOrInfo
860 ** object that is attached to the original OR clause term.
861 */
862 assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
863 assert( pExpr->op==TK_OR );
drh954701a2008-12-29 23:45:07 +0000864 pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
drh1a58fe02008-12-20 02:06:13 +0000865 if( pOrInfo==0 ) return;
866 pTerm->wtFlags |= TERM_ORINFO;
867 pOrWc = &pOrInfo->wc;
drh70d18342013-06-06 19:16:33 +0000868 whereClauseInit(pOrWc, pWInfo);
drh1a58fe02008-12-20 02:06:13 +0000869 whereSplit(pOrWc, pExpr, TK_OR);
870 exprAnalyzeAll(pSrc, pOrWc);
871 if( db->mallocFailed ) return;
872 assert( pOrWc->nTerm>=2 );
873
874 /*
875 ** Compute the set of tables that might satisfy cases 1 or 2.
876 */
danielk1977e672c8e2009-05-22 15:43:26 +0000877 indexable = ~(Bitmask)0;
drhc3e552f2013-02-08 16:04:19 +0000878 chngToIN = ~(Bitmask)0;
drh1a58fe02008-12-20 02:06:13 +0000879 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
880 if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
drh29435252008-12-28 18:35:08 +0000881 WhereAndInfo *pAndInfo;
drh29435252008-12-28 18:35:08 +0000882 assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
drh1a58fe02008-12-20 02:06:13 +0000883 chngToIN = 0;
drh29435252008-12-28 18:35:08 +0000884 pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
885 if( pAndInfo ){
886 WhereClause *pAndWC;
887 WhereTerm *pAndTerm;
888 int j;
889 Bitmask b = 0;
890 pOrTerm->u.pAndInfo = pAndInfo;
891 pOrTerm->wtFlags |= TERM_ANDINFO;
892 pOrTerm->eOperator = WO_AND;
893 pAndWC = &pAndInfo->wc;
drh70d18342013-06-06 19:16:33 +0000894 whereClauseInit(pAndWC, pWC->pWInfo);
drh29435252008-12-28 18:35:08 +0000895 whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
896 exprAnalyzeAll(pSrc, pAndWC);
drh8871ef52011-10-07 13:33:10 +0000897 pAndWC->pOuter = pWC;
drh7c2fbde2009-01-07 20:58:57 +0000898 testcase( db->mallocFailed );
drh96c7a7d2009-01-10 15:34:12 +0000899 if( !db->mallocFailed ){
900 for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
901 assert( pAndTerm->pExpr );
902 if( allowedOp(pAndTerm->pExpr->op) ){
drh70d18342013-06-06 19:16:33 +0000903 b |= getMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
drh96c7a7d2009-01-10 15:34:12 +0000904 }
drh29435252008-12-28 18:35:08 +0000905 }
906 }
907 indexable &= b;
908 }
drh1a58fe02008-12-20 02:06:13 +0000909 }else if( pOrTerm->wtFlags & TERM_COPIED ){
910 /* Skip this term for now. We revisit it when we process the
911 ** corresponding TERM_VIRTUAL term */
912 }else{
913 Bitmask b;
drh70d18342013-06-06 19:16:33 +0000914 b = getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
drh1a58fe02008-12-20 02:06:13 +0000915 if( pOrTerm->wtFlags & TERM_VIRTUAL ){
916 WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
drh70d18342013-06-06 19:16:33 +0000917 b |= getMask(&pWInfo->sMaskSet, pOther->leftCursor);
drh1a58fe02008-12-20 02:06:13 +0000918 }
919 indexable &= b;
drh7a5bcc02013-01-16 17:08:58 +0000920 if( (pOrTerm->eOperator & WO_EQ)==0 ){
drh1a58fe02008-12-20 02:06:13 +0000921 chngToIN = 0;
922 }else{
923 chngToIN &= b;
924 }
925 }
drh3e355802007-02-23 23:13:33 +0000926 }
drh1a58fe02008-12-20 02:06:13 +0000927
928 /*
929 ** Record the set of tables that satisfy case 2. The set might be
drh111a6a72008-12-21 03:51:16 +0000930 ** empty.
drh1a58fe02008-12-20 02:06:13 +0000931 */
932 pOrInfo->indexable = indexable;
drh111a6a72008-12-21 03:51:16 +0000933 pTerm->eOperator = indexable==0 ? 0 : WO_OR;
drh1a58fe02008-12-20 02:06:13 +0000934
935 /*
936 ** chngToIN holds a set of tables that *might* satisfy case 1. But
937 ** we have to do some additional checking to see if case 1 really
938 ** is satisfied.
drh4e8be3b2009-06-08 17:11:08 +0000939 **
940 ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means
941 ** that there is no possibility of transforming the OR clause into an
942 ** IN operator because one or more terms in the OR clause contain
943 ** something other than == on a column in the single table. The 1-bit
944 ** case means that every term of the OR clause is of the form
945 ** "table.column=expr" for some single table. The one bit that is set
946 ** will correspond to the common table. We still need to check to make
947 ** sure the same column is used on all terms. The 2-bit case is when
948 ** the all terms are of the form "table1.column=table2.column". It
949 ** might be possible to form an IN operator with either table1.column
950 ** or table2.column as the LHS if either is common to every term of
951 ** the OR clause.
952 **
953 ** Note that terms of the form "table.column1=table.column2" (the
954 ** same table on both sizes of the ==) cannot be optimized.
drh1a58fe02008-12-20 02:06:13 +0000955 */
956 if( chngToIN ){
957 int okToChngToIN = 0; /* True if the conversion to IN is valid */
958 int iColumn = -1; /* Column index on lhs of IN operator */
shane63207ab2009-02-04 01:49:30 +0000959 int iCursor = -1; /* Table cursor common to all terms */
drh1a58fe02008-12-20 02:06:13 +0000960 int j = 0; /* Loop counter */
961
962 /* Search for a table and column that appears on one side or the
963 ** other of the == operator in every subterm. That table and column
964 ** will be recorded in iCursor and iColumn. There might not be any
965 ** such table and column. Set okToChngToIN if an appropriate table
966 ** and column is found but leave okToChngToIN false if not found.
967 */
968 for(j=0; j<2 && !okToChngToIN; j++){
969 pOrTerm = pOrWc->a;
970 for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
drh7a5bcc02013-01-16 17:08:58 +0000971 assert( pOrTerm->eOperator & WO_EQ );
drh1a58fe02008-12-20 02:06:13 +0000972 pOrTerm->wtFlags &= ~TERM_OR_OK;
drh4e8be3b2009-06-08 17:11:08 +0000973 if( pOrTerm->leftCursor==iCursor ){
974 /* This is the 2-bit case and we are on the second iteration and
975 ** current term is from the first iteration. So skip this term. */
976 assert( j==1 );
977 continue;
978 }
drh70d18342013-06-06 19:16:33 +0000979 if( (chngToIN & getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor))==0 ){
drh4e8be3b2009-06-08 17:11:08 +0000980 /* This term must be of the form t1.a==t2.b where t2 is in the
981 ** chngToIN set but t1 is not. This term will be either preceeded
982 ** or follwed by an inverted copy (t2.b==t1.a). Skip this term
983 ** and use its inversion. */
984 testcase( pOrTerm->wtFlags & TERM_COPIED );
985 testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
986 assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
987 continue;
988 }
drh1a58fe02008-12-20 02:06:13 +0000989 iColumn = pOrTerm->u.leftColumn;
990 iCursor = pOrTerm->leftCursor;
991 break;
992 }
993 if( i<0 ){
drh4e8be3b2009-06-08 17:11:08 +0000994 /* No candidate table+column was found. This can only occur
995 ** on the second iteration */
drh1a58fe02008-12-20 02:06:13 +0000996 assert( j==1 );
drh7a5bcc02013-01-16 17:08:58 +0000997 assert( IsPowerOfTwo(chngToIN) );
drh70d18342013-06-06 19:16:33 +0000998 assert( chngToIN==getMask(&pWInfo->sMaskSet, iCursor) );
drh1a58fe02008-12-20 02:06:13 +0000999 break;
1000 }
drh4e8be3b2009-06-08 17:11:08 +00001001 testcase( j==1 );
1002
1003 /* We have found a candidate table and column. Check to see if that
1004 ** table and column is common to every term in the OR clause */
drh1a58fe02008-12-20 02:06:13 +00001005 okToChngToIN = 1;
1006 for(; i>=0 && okToChngToIN; i--, pOrTerm++){
drh7a5bcc02013-01-16 17:08:58 +00001007 assert( pOrTerm->eOperator & WO_EQ );
drh1a58fe02008-12-20 02:06:13 +00001008 if( pOrTerm->leftCursor!=iCursor ){
1009 pOrTerm->wtFlags &= ~TERM_OR_OK;
1010 }else if( pOrTerm->u.leftColumn!=iColumn ){
1011 okToChngToIN = 0;
1012 }else{
1013 int affLeft, affRight;
1014 /* If the right-hand side is also a column, then the affinities
1015 ** of both right and left sides must be such that no type
1016 ** conversions are required on the right. (Ticket #2249)
1017 */
1018 affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
1019 affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
1020 if( affRight!=0 && affRight!=affLeft ){
1021 okToChngToIN = 0;
1022 }else{
1023 pOrTerm->wtFlags |= TERM_OR_OK;
1024 }
1025 }
1026 }
1027 }
1028
1029 /* At this point, okToChngToIN is true if original pTerm satisfies
1030 ** case 1. In that case, construct a new virtual term that is
1031 ** pTerm converted into an IN operator.
1032 */
1033 if( okToChngToIN ){
1034 Expr *pDup; /* A transient duplicate expression */
1035 ExprList *pList = 0; /* The RHS of the IN operator */
1036 Expr *pLeft = 0; /* The LHS of the IN operator */
1037 Expr *pNew; /* The complete IN operator */
1038
1039 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
1040 if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
drh7a5bcc02013-01-16 17:08:58 +00001041 assert( pOrTerm->eOperator & WO_EQ );
drh1a58fe02008-12-20 02:06:13 +00001042 assert( pOrTerm->leftCursor==iCursor );
1043 assert( pOrTerm->u.leftColumn==iColumn );
danielk19776ab3a2e2009-02-19 14:39:25 +00001044 pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
drh70d18342013-06-06 19:16:33 +00001045 pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
drh1a58fe02008-12-20 02:06:13 +00001046 pLeft = pOrTerm->pExpr->pLeft;
1047 }
1048 assert( pLeft!=0 );
danielk19776ab3a2e2009-02-19 14:39:25 +00001049 pDup = sqlite3ExprDup(db, pLeft, 0);
drhb7916a72009-05-27 10:31:29 +00001050 pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
drh1a58fe02008-12-20 02:06:13 +00001051 if( pNew ){
1052 int idxNew;
1053 transferJoinMarkings(pNew, pExpr);
danielk19776ab3a2e2009-02-19 14:39:25 +00001054 assert( !ExprHasProperty(pNew, EP_xIsSelect) );
1055 pNew->x.pList = pList;
drh1a58fe02008-12-20 02:06:13 +00001056 idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
1057 testcase( idxNew==0 );
1058 exprAnalyze(pSrc, pWC, idxNew);
1059 pTerm = &pWC->a[idxTerm];
1060 pWC->a[idxNew].iParent = idxTerm;
1061 pTerm->nChild = 1;
1062 }else{
1063 sqlite3ExprListDelete(db, pList);
1064 }
drh534230c2011-01-22 00:10:45 +00001065 pTerm->eOperator = WO_NOOP; /* case 1 trumps case 2 */
drh1a58fe02008-12-20 02:06:13 +00001066 }
drh3e355802007-02-23 23:13:33 +00001067 }
drh3e355802007-02-23 23:13:33 +00001068}
1069#endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
drh54a167d2005-11-26 14:08:07 +00001070
drh7a5bcc02013-01-16 17:08:58 +00001071/*
drh0aa74ed2005-07-16 13:33:20 +00001072** The input to this routine is an WhereTerm structure with only the
drh51147ba2005-07-23 22:59:55 +00001073** "pExpr" field filled in. The job of this routine is to analyze the
drh0aa74ed2005-07-16 13:33:20 +00001074** subexpression and populate all the other fields of the WhereTerm
drh75897232000-05-29 14:26:00 +00001075** structure.
drh51147ba2005-07-23 22:59:55 +00001076**
1077** If the expression is of the form "<expr> <op> X" it gets commuted
drh1a58fe02008-12-20 02:06:13 +00001078** to the standard form of "X <op> <expr>".
1079**
1080** If the expression is of the form "X <op> Y" where both X and Y are
1081** columns, then the original expression is unchanged and a new virtual
1082** term of the form "Y <op> X" is added to the WHERE clause and
1083** analyzed separately. The original term is marked with TERM_COPIED
1084** and the new term is marked with TERM_DYNAMIC (because it's pExpr
1085** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
1086** is a commuted copy of a prior term.) The original term has nChild=1
1087** and the copy has idxParent set to the index of the original term.
drh75897232000-05-29 14:26:00 +00001088*/
drh0fcef5e2005-07-19 17:38:22 +00001089static void exprAnalyze(
1090 SrcList *pSrc, /* the FROM clause */
drh9eb20282005-08-24 03:52:18 +00001091 WhereClause *pWC, /* the WHERE clause */
1092 int idxTerm /* Index of the term to be analyzed */
drh0fcef5e2005-07-19 17:38:22 +00001093){
drh70d18342013-06-06 19:16:33 +00001094 WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
drh1a58fe02008-12-20 02:06:13 +00001095 WhereTerm *pTerm; /* The term to be analyzed */
drh111a6a72008-12-21 03:51:16 +00001096 WhereMaskSet *pMaskSet; /* Set of table index masks */
drh1a58fe02008-12-20 02:06:13 +00001097 Expr *pExpr; /* The expression to be analyzed */
1098 Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */
1099 Bitmask prereqAll; /* Prerequesites of pExpr */
drh5e767c52010-02-25 04:15:47 +00001100 Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */
drh1d452e12009-11-01 19:26:59 +00001101 Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */
1102 int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */
1103 int noCase = 0; /* LIKE/GLOB distinguishes case */
drh1a58fe02008-12-20 02:06:13 +00001104 int op; /* Top-level operator. pExpr->op */
drh70d18342013-06-06 19:16:33 +00001105 Parse *pParse = pWInfo->pParse; /* Parsing context */
drh1a58fe02008-12-20 02:06:13 +00001106 sqlite3 *db = pParse->db; /* Database connection */
drh0fcef5e2005-07-19 17:38:22 +00001107
drhf998b732007-11-26 13:36:00 +00001108 if( db->mallocFailed ){
1109 return;
1110 }
1111 pTerm = &pWC->a[idxTerm];
drh70d18342013-06-06 19:16:33 +00001112 pMaskSet = &pWInfo->sMaskSet;
drh7ee751d2012-12-19 15:53:51 +00001113 pExpr = pTerm->pExpr;
1114 assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
drh0fcef5e2005-07-19 17:38:22 +00001115 prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
drh50b39962006-10-28 00:28:09 +00001116 op = pExpr->op;
1117 if( op==TK_IN ){
drhf5b11382005-09-17 13:07:13 +00001118 assert( pExpr->pRight==0 );
danielk19776ab3a2e2009-02-19 14:39:25 +00001119 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
1120 pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
1121 }else{
1122 pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
1123 }
drh50b39962006-10-28 00:28:09 +00001124 }else if( op==TK_ISNULL ){
1125 pTerm->prereqRight = 0;
drhf5b11382005-09-17 13:07:13 +00001126 }else{
1127 pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
1128 }
drh22d6a532005-09-19 21:05:48 +00001129 prereqAll = exprTableUsage(pMaskSet, pExpr);
1130 if( ExprHasProperty(pExpr, EP_FromJoin) ){
drh42165be2008-03-26 14:56:34 +00001131 Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
1132 prereqAll |= x;
drhdafc0ce2008-04-17 19:14:02 +00001133 extraRight = x-1; /* ON clause terms may not be used with an index
1134 ** on left table of a LEFT JOIN. Ticket #3015 */
drh22d6a532005-09-19 21:05:48 +00001135 }
1136 pTerm->prereqAll = prereqAll;
drh0fcef5e2005-07-19 17:38:22 +00001137 pTerm->leftCursor = -1;
drh45b1ee42005-08-02 17:48:22 +00001138 pTerm->iParent = -1;
drhb52076c2006-01-23 13:22:09 +00001139 pTerm->eOperator = 0;
drh738fc792013-01-17 15:05:17 +00001140 if( allowedOp(op) ){
drh7a66da12012-12-07 20:31:11 +00001141 Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
1142 Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
drh738fc792013-01-17 15:05:17 +00001143 u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
drh0fcef5e2005-07-19 17:38:22 +00001144 if( pLeft->op==TK_COLUMN ){
1145 pTerm->leftCursor = pLeft->iTable;
drh700a2262008-12-17 19:22:15 +00001146 pTerm->u.leftColumn = pLeft->iColumn;
drh738fc792013-01-17 15:05:17 +00001147 pTerm->eOperator = operatorMask(op) & opMask;
drh75897232000-05-29 14:26:00 +00001148 }
drh0fcef5e2005-07-19 17:38:22 +00001149 if( pRight && pRight->op==TK_COLUMN ){
1150 WhereTerm *pNew;
1151 Expr *pDup;
drh7a5bcc02013-01-16 17:08:58 +00001152 u16 eExtraOp = 0; /* Extra bits for pNew->eOperator */
drh0fcef5e2005-07-19 17:38:22 +00001153 if( pTerm->leftCursor>=0 ){
drh9eb20282005-08-24 03:52:18 +00001154 int idxNew;
danielk19776ab3a2e2009-02-19 14:39:25 +00001155 pDup = sqlite3ExprDup(db, pExpr, 0);
drh17435752007-08-16 04:30:38 +00001156 if( db->mallocFailed ){
drh633e6d52008-07-28 19:34:53 +00001157 sqlite3ExprDelete(db, pDup);
drh28f45912006-10-18 23:26:38 +00001158 return;
1159 }
drh9eb20282005-08-24 03:52:18 +00001160 idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
1161 if( idxNew==0 ) return;
1162 pNew = &pWC->a[idxNew];
1163 pNew->iParent = idxTerm;
1164 pTerm = &pWC->a[idxTerm];
drh45b1ee42005-08-02 17:48:22 +00001165 pTerm->nChild = 1;
drh165be382008-12-05 02:36:33 +00001166 pTerm->wtFlags |= TERM_COPIED;
drheb5bc922013-01-17 16:43:33 +00001167 if( pExpr->op==TK_EQ
1168 && !ExprHasProperty(pExpr, EP_FromJoin)
1169 && OptimizationEnabled(db, SQLITE_Transitive)
1170 ){
drh7a5bcc02013-01-16 17:08:58 +00001171 pTerm->eOperator |= WO_EQUIV;
1172 eExtraOp = WO_EQUIV;
1173 }
drh0fcef5e2005-07-19 17:38:22 +00001174 }else{
1175 pDup = pExpr;
1176 pNew = pTerm;
1177 }
drh7d10d5a2008-08-20 16:35:10 +00001178 exprCommute(pParse, pDup);
drhfb76f5a2012-12-08 14:16:47 +00001179 pLeft = sqlite3ExprSkipCollate(pDup->pLeft);
drh0fcef5e2005-07-19 17:38:22 +00001180 pNew->leftCursor = pLeft->iTable;
drh700a2262008-12-17 19:22:15 +00001181 pNew->u.leftColumn = pLeft->iColumn;
drh5e767c52010-02-25 04:15:47 +00001182 testcase( (prereqLeft | extraRight) != prereqLeft );
1183 pNew->prereqRight = prereqLeft | extraRight;
drh0fcef5e2005-07-19 17:38:22 +00001184 pNew->prereqAll = prereqAll;
drh738fc792013-01-17 15:05:17 +00001185 pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
drh75897232000-05-29 14:26:00 +00001186 }
1187 }
drhed378002005-07-28 23:12:08 +00001188
drhd2687b72005-08-12 22:56:09 +00001189#ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
drhed378002005-07-28 23:12:08 +00001190 /* If a term is the BETWEEN operator, create two new virtual terms
drh1a58fe02008-12-20 02:06:13 +00001191 ** that define the range that the BETWEEN implements. For example:
1192 **
1193 ** a BETWEEN b AND c
1194 **
1195 ** is converted into:
1196 **
1197 ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
1198 **
1199 ** The two new terms are added onto the end of the WhereClause object.
1200 ** The new terms are "dynamic" and are children of the original BETWEEN
1201 ** term. That means that if the BETWEEN term is coded, the children are
1202 ** skipped. Or, if the children are satisfied by an index, the original
1203 ** BETWEEN term is skipped.
drhed378002005-07-28 23:12:08 +00001204 */
drh29435252008-12-28 18:35:08 +00001205 else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
danielk19776ab3a2e2009-02-19 14:39:25 +00001206 ExprList *pList = pExpr->x.pList;
drhed378002005-07-28 23:12:08 +00001207 int i;
1208 static const u8 ops[] = {TK_GE, TK_LE};
1209 assert( pList!=0 );
1210 assert( pList->nExpr==2 );
1211 for(i=0; i<2; i++){
1212 Expr *pNewExpr;
drh9eb20282005-08-24 03:52:18 +00001213 int idxNew;
drhb7916a72009-05-27 10:31:29 +00001214 pNewExpr = sqlite3PExpr(pParse, ops[i],
1215 sqlite3ExprDup(db, pExpr->pLeft, 0),
danielk19776ab3a2e2009-02-19 14:39:25 +00001216 sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
drhd41d39f2013-08-28 16:27:01 +00001217 transferJoinMarkings(pNewExpr, pExpr);
drh9eb20282005-08-24 03:52:18 +00001218 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
drh6a1e0712008-12-05 15:24:15 +00001219 testcase( idxNew==0 );
drh7b4fc6a2007-02-06 13:26:32 +00001220 exprAnalyze(pSrc, pWC, idxNew);
drh9eb20282005-08-24 03:52:18 +00001221 pTerm = &pWC->a[idxTerm];
1222 pWC->a[idxNew].iParent = idxTerm;
drhed378002005-07-28 23:12:08 +00001223 }
drh45b1ee42005-08-02 17:48:22 +00001224 pTerm->nChild = 2;
drhed378002005-07-28 23:12:08 +00001225 }
drhd2687b72005-08-12 22:56:09 +00001226#endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
drhed378002005-07-28 23:12:08 +00001227
danielk19771576cd92006-01-14 08:02:28 +00001228#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
drh1a58fe02008-12-20 02:06:13 +00001229 /* Analyze a term that is composed of two or more subterms connected by
1230 ** an OR operator.
drh6c30be82005-07-29 15:10:17 +00001231 */
1232 else if( pExpr->op==TK_OR ){
drh29435252008-12-28 18:35:08 +00001233 assert( pWC->op==TK_AND );
drh1a58fe02008-12-20 02:06:13 +00001234 exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
danielk1977f51d1bd2009-07-31 06:14:51 +00001235 pTerm = &pWC->a[idxTerm];
drh6c30be82005-07-29 15:10:17 +00001236 }
drhd2687b72005-08-12 22:56:09 +00001237#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
1238
1239#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
1240 /* Add constraints to reduce the search space on a LIKE or GLOB
1241 ** operator.
drh9f504ea2008-02-23 21:55:39 +00001242 **
1243 ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
1244 **
1245 ** x>='abc' AND x<'abd' AND x LIKE 'abc%'
1246 **
1247 ** The last character of the prefix "abc" is incremented to form the
shane7bc71e52008-05-28 18:01:44 +00001248 ** termination condition "abd".
drhd2687b72005-08-12 22:56:09 +00001249 */
dan937d0de2009-10-15 18:35:38 +00001250 if( pWC->op==TK_AND
1251 && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
1252 ){
drh1d452e12009-11-01 19:26:59 +00001253 Expr *pLeft; /* LHS of LIKE/GLOB operator */
1254 Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */
1255 Expr *pNewExpr1;
1256 Expr *pNewExpr2;
1257 int idxNew1;
1258 int idxNew2;
drhae80dde2012-12-06 21:16:43 +00001259 Token sCollSeqName; /* Name of collating sequence */
drh9eb20282005-08-24 03:52:18 +00001260
danielk19776ab3a2e2009-02-19 14:39:25 +00001261 pLeft = pExpr->x.pList->a[1].pExpr;
danielk19776ab3a2e2009-02-19 14:39:25 +00001262 pStr2 = sqlite3ExprDup(db, pStr1, 0);
drhf998b732007-11-26 13:36:00 +00001263 if( !db->mallocFailed ){
drh254993e2009-06-08 19:44:36 +00001264 u8 c, *pC; /* Last character before the first wildcard */
dan937d0de2009-10-15 18:35:38 +00001265 pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
drh9f504ea2008-02-23 21:55:39 +00001266 c = *pC;
drh02a50b72008-05-26 18:33:40 +00001267 if( noCase ){
drh254993e2009-06-08 19:44:36 +00001268 /* The point is to increment the last character before the first
1269 ** wildcard. But if we increment '@', that will push it into the
1270 ** alphabetic range where case conversions will mess up the
1271 ** inequality. To avoid this, make sure to also run the full
1272 ** LIKE on all candidate expressions by clearing the isComplete flag
1273 */
drh39759742013-08-02 23:40:45 +00001274 if( c=='A'-1 ) isComplete = 0;
drh02a50b72008-05-26 18:33:40 +00001275 c = sqlite3UpperToLower[c];
1276 }
drh9f504ea2008-02-23 21:55:39 +00001277 *pC = c + 1;
drhd2687b72005-08-12 22:56:09 +00001278 }
drhae80dde2012-12-06 21:16:43 +00001279 sCollSeqName.z = noCase ? "NOCASE" : "BINARY";
1280 sCollSeqName.n = 6;
1281 pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
drh8342e492010-07-22 17:49:52 +00001282 pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
drh0a8a4062012-12-07 18:38:16 +00001283 sqlite3ExprAddCollateToken(pParse,pNewExpr1,&sCollSeqName),
drhae80dde2012-12-06 21:16:43 +00001284 pStr1, 0);
drhd41d39f2013-08-28 16:27:01 +00001285 transferJoinMarkings(pNewExpr1, pExpr);
drh9eb20282005-08-24 03:52:18 +00001286 idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
drh6a1e0712008-12-05 15:24:15 +00001287 testcase( idxNew1==0 );
drh7b4fc6a2007-02-06 13:26:32 +00001288 exprAnalyze(pSrc, pWC, idxNew1);
drhae80dde2012-12-06 21:16:43 +00001289 pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
drh8342e492010-07-22 17:49:52 +00001290 pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
drh0a8a4062012-12-07 18:38:16 +00001291 sqlite3ExprAddCollateToken(pParse,pNewExpr2,&sCollSeqName),
drhae80dde2012-12-06 21:16:43 +00001292 pStr2, 0);
drhd41d39f2013-08-28 16:27:01 +00001293 transferJoinMarkings(pNewExpr2, pExpr);
drh9eb20282005-08-24 03:52:18 +00001294 idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
drh6a1e0712008-12-05 15:24:15 +00001295 testcase( idxNew2==0 );
drh7b4fc6a2007-02-06 13:26:32 +00001296 exprAnalyze(pSrc, pWC, idxNew2);
drh9eb20282005-08-24 03:52:18 +00001297 pTerm = &pWC->a[idxTerm];
drhd2687b72005-08-12 22:56:09 +00001298 if( isComplete ){
drh9eb20282005-08-24 03:52:18 +00001299 pWC->a[idxNew1].iParent = idxTerm;
1300 pWC->a[idxNew2].iParent = idxTerm;
drhd2687b72005-08-12 22:56:09 +00001301 pTerm->nChild = 2;
1302 }
1303 }
1304#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
drh7f375902006-06-13 17:38:59 +00001305
1306#ifndef SQLITE_OMIT_VIRTUALTABLE
1307 /* Add a WO_MATCH auxiliary term to the constraint set if the
1308 ** current expression is of the form: column MATCH expr.
1309 ** This information is used by the xBestIndex methods of
1310 ** virtual tables. The native query optimizer does not attempt
1311 ** to do anything with MATCH functions.
1312 */
1313 if( isMatchOfColumn(pExpr) ){
1314 int idxNew;
1315 Expr *pRight, *pLeft;
1316 WhereTerm *pNewTerm;
1317 Bitmask prereqColumn, prereqExpr;
1318
danielk19776ab3a2e2009-02-19 14:39:25 +00001319 pRight = pExpr->x.pList->a[0].pExpr;
1320 pLeft = pExpr->x.pList->a[1].pExpr;
drh7f375902006-06-13 17:38:59 +00001321 prereqExpr = exprTableUsage(pMaskSet, pRight);
1322 prereqColumn = exprTableUsage(pMaskSet, pLeft);
1323 if( (prereqExpr & prereqColumn)==0 ){
drh1a90e092006-06-14 22:07:10 +00001324 Expr *pNewExpr;
drhb7916a72009-05-27 10:31:29 +00001325 pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
1326 0, sqlite3ExprDup(db, pRight, 0), 0);
drh1a90e092006-06-14 22:07:10 +00001327 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
drh6a1e0712008-12-05 15:24:15 +00001328 testcase( idxNew==0 );
drh7f375902006-06-13 17:38:59 +00001329 pNewTerm = &pWC->a[idxNew];
1330 pNewTerm->prereqRight = prereqExpr;
1331 pNewTerm->leftCursor = pLeft->iTable;
drh700a2262008-12-17 19:22:15 +00001332 pNewTerm->u.leftColumn = pLeft->iColumn;
drh7f375902006-06-13 17:38:59 +00001333 pNewTerm->eOperator = WO_MATCH;
1334 pNewTerm->iParent = idxTerm;
drhd2ca60d2006-06-27 02:36:58 +00001335 pTerm = &pWC->a[idxTerm];
drh7f375902006-06-13 17:38:59 +00001336 pTerm->nChild = 1;
drh165be382008-12-05 02:36:33 +00001337 pTerm->wtFlags |= TERM_COPIED;
drh7f375902006-06-13 17:38:59 +00001338 pNewTerm->prereqAll = pTerm->prereqAll;
1339 }
1340 }
1341#endif /* SQLITE_OMIT_VIRTUALTABLE */
drhdafc0ce2008-04-17 19:14:02 +00001342
drh1435a9a2013-08-27 23:15:44 +00001343#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drhd3ed7342011-09-21 00:09:41 +00001344 /* When sqlite_stat3 histogram data is available an operator of the
drh534230c2011-01-22 00:10:45 +00001345 ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
1346 ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a
1347 ** virtual term of that form.
1348 **
1349 ** Note that the virtual term must be tagged with TERM_VNULL. This
1350 ** TERM_VNULL tag will suppress the not-null check at the beginning
1351 ** of the loop. Without the TERM_VNULL flag, the not-null check at
1352 ** the start of the loop will prevent any results from being returned.
1353 */
drhea6dc442011-04-08 21:35:26 +00001354 if( pExpr->op==TK_NOTNULL
1355 && pExpr->pLeft->op==TK_COLUMN
1356 && pExpr->pLeft->iColumn>=0
drh40aa9362013-06-28 17:29:25 +00001357 && OptimizationEnabled(db, SQLITE_Stat3)
drhea6dc442011-04-08 21:35:26 +00001358 ){
drh534230c2011-01-22 00:10:45 +00001359 Expr *pNewExpr;
1360 Expr *pLeft = pExpr->pLeft;
1361 int idxNew;
1362 WhereTerm *pNewTerm;
1363
1364 pNewExpr = sqlite3PExpr(pParse, TK_GT,
1365 sqlite3ExprDup(db, pLeft, 0),
1366 sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
1367
1368 idxNew = whereClauseInsert(pWC, pNewExpr,
1369 TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
drhda91e712011-02-11 06:59:02 +00001370 if( idxNew ){
1371 pNewTerm = &pWC->a[idxNew];
1372 pNewTerm->prereqRight = 0;
1373 pNewTerm->leftCursor = pLeft->iTable;
1374 pNewTerm->u.leftColumn = pLeft->iColumn;
1375 pNewTerm->eOperator = WO_GT;
1376 pNewTerm->iParent = idxTerm;
1377 pTerm = &pWC->a[idxTerm];
1378 pTerm->nChild = 1;
1379 pTerm->wtFlags |= TERM_COPIED;
1380 pNewTerm->prereqAll = pTerm->prereqAll;
1381 }
drh534230c2011-01-22 00:10:45 +00001382 }
drh1435a9a2013-08-27 23:15:44 +00001383#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
drh534230c2011-01-22 00:10:45 +00001384
drhdafc0ce2008-04-17 19:14:02 +00001385 /* Prevent ON clause terms of a LEFT JOIN from being used to drive
1386 ** an index for tables to the left of the join.
1387 */
1388 pTerm->prereqRight |= extraRight;
drh75897232000-05-29 14:26:00 +00001389}
1390
drh7b4fc6a2007-02-06 13:26:32 +00001391/*
drh3b48e8c2013-06-12 20:18:16 +00001392** This function searches pList for a entry that matches the iCol-th column
1393** of index pIdx.
dan6f343962011-07-01 18:26:40 +00001394**
1395** If such an expression is found, its index in pList->a[] is returned. If
1396** no expression is found, -1 is returned.
1397*/
1398static int findIndexCol(
1399 Parse *pParse, /* Parse context */
1400 ExprList *pList, /* Expression list to search */
1401 int iBase, /* Cursor for table associated with pIdx */
1402 Index *pIdx, /* Index to match column of */
1403 int iCol /* Column of index to match */
1404){
1405 int i;
1406 const char *zColl = pIdx->azColl[iCol];
1407
1408 for(i=0; i<pList->nExpr; i++){
drh580c8c12012-12-08 03:34:04 +00001409 Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
drhf1d3e322011-07-09 13:00:41 +00001410 if( p->op==TK_COLUMN
1411 && p->iColumn==pIdx->aiColumn[iCol]
1412 && p->iTable==iBase
1413 ){
drh580c8c12012-12-08 03:34:04 +00001414 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
drhf1d3e322011-07-09 13:00:41 +00001415 if( ALWAYS(pColl) && 0==sqlite3StrICmp(pColl->zName, zColl) ){
dan6f343962011-07-01 18:26:40 +00001416 return i;
1417 }
1418 }
1419 }
1420
1421 return -1;
1422}
1423
1424/*
dan6f343962011-07-01 18:26:40 +00001425** Return true if the DISTINCT expression-list passed as the third argument
drh4f402f22013-06-11 18:59:38 +00001426** is redundant.
1427**
drh3b48e8c2013-06-12 20:18:16 +00001428** A DISTINCT list is redundant if the database contains some subset of
drh4f402f22013-06-11 18:59:38 +00001429** columns that are unique and non-null.
dan6f343962011-07-01 18:26:40 +00001430*/
1431static int isDistinctRedundant(
drh4f402f22013-06-11 18:59:38 +00001432 Parse *pParse, /* Parsing context */
1433 SrcList *pTabList, /* The FROM clause */
1434 WhereClause *pWC, /* The WHERE clause */
1435 ExprList *pDistinct /* The result set that needs to be DISTINCT */
dan6f343962011-07-01 18:26:40 +00001436){
1437 Table *pTab;
1438 Index *pIdx;
1439 int i;
1440 int iBase;
1441
1442 /* If there is more than one table or sub-select in the FROM clause of
1443 ** this query, then it will not be possible to show that the DISTINCT
1444 ** clause is redundant. */
1445 if( pTabList->nSrc!=1 ) return 0;
1446 iBase = pTabList->a[0].iCursor;
1447 pTab = pTabList->a[0].pTab;
1448
dan94e08d92011-07-02 06:44:05 +00001449 /* If any of the expressions is an IPK column on table iBase, then return
1450 ** true. Note: The (p->iTable==iBase) part of this test may be false if the
1451 ** current SELECT is a correlated sub-query.
1452 */
dan6f343962011-07-01 18:26:40 +00001453 for(i=0; i<pDistinct->nExpr; i++){
drh580c8c12012-12-08 03:34:04 +00001454 Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
dan94e08d92011-07-02 06:44:05 +00001455 if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
dan6f343962011-07-01 18:26:40 +00001456 }
1457
1458 /* Loop through all indices on the table, checking each to see if it makes
1459 ** the DISTINCT qualifier redundant. It does so if:
1460 **
1461 ** 1. The index is itself UNIQUE, and
1462 **
1463 ** 2. All of the columns in the index are either part of the pDistinct
1464 ** list, or else the WHERE clause contains a term of the form "col=X",
1465 ** where X is a constant value. The collation sequences of the
1466 ** comparison and select-list expressions must match those of the index.
dan6a36f432012-04-20 16:59:24 +00001467 **
1468 ** 3. All of those index columns for which the WHERE clause does not
1469 ** contain a "col=X" term are subject to a NOT NULL constraint.
dan6f343962011-07-01 18:26:40 +00001470 */
1471 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1472 if( pIdx->onError==OE_None ) continue;
drhbbbdc832013-10-22 18:01:40 +00001473 for(i=0; i<pIdx->nKeyCol; i++){
1474 i16 iCol = pIdx->aiColumn[i];
dan6a36f432012-04-20 16:59:24 +00001475 if( 0==findTerm(pWC, iBase, iCol, ~(Bitmask)0, WO_EQ, pIdx) ){
1476 int iIdxCol = findIndexCol(pParse, pDistinct, iBase, pIdx, i);
drhbbbdc832013-10-22 18:01:40 +00001477 if( iIdxCol<0 || pTab->aCol[iCol].notNull==0 ){
dan6a36f432012-04-20 16:59:24 +00001478 break;
1479 }
dan6f343962011-07-01 18:26:40 +00001480 }
1481 }
drhbbbdc832013-10-22 18:01:40 +00001482 if( i==pIdx->nKeyCol ){
dan6f343962011-07-01 18:26:40 +00001483 /* This index implies that the DISTINCT qualifier is redundant. */
1484 return 1;
1485 }
1486 }
1487
1488 return 0;
1489}
drh0fcef5e2005-07-19 17:38:22 +00001490
drh8636e9c2013-06-11 01:50:08 +00001491
drh75897232000-05-29 14:26:00 +00001492/*
drh3b48e8c2013-06-12 20:18:16 +00001493** Estimate the logarithm of the input value to base 2.
drh28c4cf42005-07-27 20:41:43 +00001494*/
drhbf539c42013-10-05 18:16:02 +00001495static LogEst estLog(LogEst N){
1496 LogEst x = sqlite3LogEst(N);
drh4fe425a2013-06-12 17:08:06 +00001497 return x>33 ? x - 33 : 0;
drh28c4cf42005-07-27 20:41:43 +00001498}
1499
drh6d209d82006-06-27 01:54:26 +00001500/*
1501** Two routines for printing the content of an sqlite3_index_info
1502** structure. Used for testing and debugging only. If neither
1503** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
1504** are no-ops.
1505*/
drhd15cb172013-05-21 19:23:10 +00001506#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
drh6d209d82006-06-27 01:54:26 +00001507static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
1508 int i;
mlcreech3a00f902008-03-04 17:45:01 +00001509 if( !sqlite3WhereTrace ) return;
drh6d209d82006-06-27 01:54:26 +00001510 for(i=0; i<p->nConstraint; i++){
1511 sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
1512 i,
1513 p->aConstraint[i].iColumn,
1514 p->aConstraint[i].iTermOffset,
1515 p->aConstraint[i].op,
1516 p->aConstraint[i].usable);
1517 }
1518 for(i=0; i<p->nOrderBy; i++){
1519 sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n",
1520 i,
1521 p->aOrderBy[i].iColumn,
1522 p->aOrderBy[i].desc);
1523 }
1524}
1525static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
1526 int i;
mlcreech3a00f902008-03-04 17:45:01 +00001527 if( !sqlite3WhereTrace ) return;
drh6d209d82006-06-27 01:54:26 +00001528 for(i=0; i<p->nConstraint; i++){
1529 sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n",
1530 i,
1531 p->aConstraintUsage[i].argvIndex,
1532 p->aConstraintUsage[i].omit);
1533 }
1534 sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum);
1535 sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr);
1536 sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed);
1537 sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost);
dana9f58152013-11-11 19:01:33 +00001538 sqlite3DebugPrintf(" estimatedRows=%lld\n", p->estimatedRows);
drh6d209d82006-06-27 01:54:26 +00001539}
1540#else
1541#define TRACE_IDX_INPUTS(A)
1542#define TRACE_IDX_OUTPUTS(A)
1543#endif
1544
drhc6339082010-04-07 16:54:58 +00001545#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
drh8b307fb2010-04-06 15:57:05 +00001546/*
drh4139c992010-04-07 14:59:45 +00001547** Return TRUE if the WHERE clause term pTerm is of a form where it
1548** could be used with an index to access pSrc, assuming an appropriate
1549** index existed.
1550*/
1551static int termCanDriveIndex(
1552 WhereTerm *pTerm, /* WHERE clause term to check */
1553 struct SrcList_item *pSrc, /* Table we are trying to access */
1554 Bitmask notReady /* Tables in outer loops of the join */
1555){
1556 char aff;
1557 if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
drh7a5bcc02013-01-16 17:08:58 +00001558 if( (pTerm->eOperator & WO_EQ)==0 ) return 0;
drh4139c992010-04-07 14:59:45 +00001559 if( (pTerm->prereqRight & notReady)!=0 ) return 0;
drh23f98da2013-05-21 15:52:07 +00001560 if( pTerm->u.leftColumn<0 ) return 0;
drh4139c992010-04-07 14:59:45 +00001561 aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
1562 if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
1563 return 1;
1564}
drhc6339082010-04-07 16:54:58 +00001565#endif
drh4139c992010-04-07 14:59:45 +00001566
drhc6339082010-04-07 16:54:58 +00001567
1568#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
drh8b307fb2010-04-06 15:57:05 +00001569/*
drhc6339082010-04-07 16:54:58 +00001570** Generate code to construct the Index object for an automatic index
1571** and to set up the WhereLevel object pLevel so that the code generator
1572** makes use of the automatic index.
drh8b307fb2010-04-06 15:57:05 +00001573*/
drhc6339082010-04-07 16:54:58 +00001574static void constructAutomaticIndex(
drh8b307fb2010-04-06 15:57:05 +00001575 Parse *pParse, /* The parsing context */
1576 WhereClause *pWC, /* The WHERE clause */
1577 struct SrcList_item *pSrc, /* The FROM clause term to get the next index */
1578 Bitmask notReady, /* Mask of cursors that are not available */
1579 WhereLevel *pLevel /* Write new index here */
1580){
drhbbbdc832013-10-22 18:01:40 +00001581 int nKeyCol; /* Number of columns in the constructed index */
drh8b307fb2010-04-06 15:57:05 +00001582 WhereTerm *pTerm; /* A single term of the WHERE clause */
1583 WhereTerm *pWCEnd; /* End of pWC->a[] */
drh8b307fb2010-04-06 15:57:05 +00001584 Index *pIdx; /* Object describing the transient index */
1585 Vdbe *v; /* Prepared statement under construction */
drh8b307fb2010-04-06 15:57:05 +00001586 int addrInit; /* Address of the initialization bypass jump */
1587 Table *pTable; /* The table being indexed */
drh8b307fb2010-04-06 15:57:05 +00001588 int addrTop; /* Top of the index fill loop */
1589 int regRecord; /* Register holding an index record */
1590 int n; /* Column counter */
drh4139c992010-04-07 14:59:45 +00001591 int i; /* Loop counter */
1592 int mxBitCol; /* Maximum column in pSrc->colUsed */
drh424aab82010-04-06 18:28:20 +00001593 CollSeq *pColl; /* Collating sequence to on a column */
drh7ba39a92013-05-30 17:43:19 +00001594 WhereLoop *pLoop; /* The Loop object */
drh77e57df2013-10-22 14:28:02 +00001595 char *zNotUsed; /* Extra space on the end of pIdx */
drh4139c992010-04-07 14:59:45 +00001596 Bitmask idxCols; /* Bitmap of columns used for indexing */
1597 Bitmask extraCols; /* Bitmap of additional columns */
drh8d56e202013-06-28 23:55:45 +00001598 u8 sentWarning = 0; /* True if a warnning has been issued */
drh8b307fb2010-04-06 15:57:05 +00001599
1600 /* Generate code to skip over the creation and initialization of the
1601 ** transient index on 2nd and subsequent iterations of the loop. */
1602 v = pParse->pVdbe;
1603 assert( v!=0 );
dan1d8cb212011-12-09 13:24:16 +00001604 addrInit = sqlite3CodeOnce(pParse);
drh8b307fb2010-04-06 15:57:05 +00001605
drh4139c992010-04-07 14:59:45 +00001606 /* Count the number of columns that will be added to the index
1607 ** and used to match WHERE clause constraints */
drhbbbdc832013-10-22 18:01:40 +00001608 nKeyCol = 0;
drh424aab82010-04-06 18:28:20 +00001609 pTable = pSrc->pTab;
drh8b307fb2010-04-06 15:57:05 +00001610 pWCEnd = &pWC->a[pWC->nTerm];
drh7ba39a92013-05-30 17:43:19 +00001611 pLoop = pLevel->pWLoop;
drh4139c992010-04-07 14:59:45 +00001612 idxCols = 0;
drh81186b42013-06-18 01:52:41 +00001613 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
drh4139c992010-04-07 14:59:45 +00001614 if( termCanDriveIndex(pTerm, pSrc, notReady) ){
1615 int iCol = pTerm->u.leftColumn;
drh7699d1c2013-06-04 12:42:29 +00001616 Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
drh52ff8ea2010-04-08 14:15:56 +00001617 testcase( iCol==BMS );
1618 testcase( iCol==BMS-1 );
drh8d56e202013-06-28 23:55:45 +00001619 if( !sentWarning ){
1620 sqlite3_log(SQLITE_WARNING_AUTOINDEX,
1621 "automatic index on %s(%s)", pTable->zName,
1622 pTable->aCol[iCol].zName);
1623 sentWarning = 1;
1624 }
drh0013e722010-04-08 00:40:15 +00001625 if( (idxCols & cMask)==0 ){
drhbbbdc832013-10-22 18:01:40 +00001626 if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ) return;
1627 pLoop->aLTerm[nKeyCol++] = pTerm;
drh0013e722010-04-08 00:40:15 +00001628 idxCols |= cMask;
1629 }
drh8b307fb2010-04-06 15:57:05 +00001630 }
1631 }
drhbbbdc832013-10-22 18:01:40 +00001632 assert( nKeyCol>0 );
1633 pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol;
drh53b52f72013-05-31 11:57:39 +00001634 pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
drh986b3872013-06-28 21:12:20 +00001635 | WHERE_AUTO_INDEX;
drh4139c992010-04-07 14:59:45 +00001636
1637 /* Count the number of additional columns needed to create a
1638 ** covering index. A "covering index" is an index that contains all
1639 ** columns that are needed by the query. With a covering index, the
1640 ** original table never needs to be accessed. Automatic indices must
1641 ** be a covering index because the index will not be updated if the
1642 ** original table changes and the index and table cannot both be used
1643 ** if they go out of sync.
1644 */
drh7699d1c2013-06-04 12:42:29 +00001645 extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
drh4139c992010-04-07 14:59:45 +00001646 mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol;
drh52ff8ea2010-04-08 14:15:56 +00001647 testcase( pTable->nCol==BMS-1 );
1648 testcase( pTable->nCol==BMS-2 );
drh4139c992010-04-07 14:59:45 +00001649 for(i=0; i<mxBitCol; i++){
drhbbbdc832013-10-22 18:01:40 +00001650 if( extraCols & MASKBIT(i) ) nKeyCol++;
drh4139c992010-04-07 14:59:45 +00001651 }
drh7699d1c2013-06-04 12:42:29 +00001652 if( pSrc->colUsed & MASKBIT(BMS-1) ){
drhbbbdc832013-10-22 18:01:40 +00001653 nKeyCol += pTable->nCol - BMS + 1;
drh4139c992010-04-07 14:59:45 +00001654 }
drh7ba39a92013-05-30 17:43:19 +00001655 pLoop->wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY;
drh8b307fb2010-04-06 15:57:05 +00001656
1657 /* Construct the Index object to describe this index */
drhbbbdc832013-10-22 18:01:40 +00001658 pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed);
drh8b307fb2010-04-06 15:57:05 +00001659 if( pIdx==0 ) return;
drh7ba39a92013-05-30 17:43:19 +00001660 pLoop->u.btree.pIndex = pIdx;
drh8b307fb2010-04-06 15:57:05 +00001661 pIdx->zName = "auto-index";
drh424aab82010-04-06 18:28:20 +00001662 pIdx->pTable = pTable;
drh8b307fb2010-04-06 15:57:05 +00001663 n = 0;
drh0013e722010-04-08 00:40:15 +00001664 idxCols = 0;
drh8b307fb2010-04-06 15:57:05 +00001665 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
drh4139c992010-04-07 14:59:45 +00001666 if( termCanDriveIndex(pTerm, pSrc, notReady) ){
drh0013e722010-04-08 00:40:15 +00001667 int iCol = pTerm->u.leftColumn;
drh7699d1c2013-06-04 12:42:29 +00001668 Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
drh7963b0e2013-06-17 21:37:40 +00001669 testcase( iCol==BMS-1 );
1670 testcase( iCol==BMS );
drh0013e722010-04-08 00:40:15 +00001671 if( (idxCols & cMask)==0 ){
1672 Expr *pX = pTerm->pExpr;
1673 idxCols |= cMask;
1674 pIdx->aiColumn[n] = pTerm->u.leftColumn;
1675 pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
drh6f2e6c02011-02-17 13:33:15 +00001676 pIdx->azColl[n] = ALWAYS(pColl) ? pColl->zName : "BINARY";
drh0013e722010-04-08 00:40:15 +00001677 n++;
1678 }
drh8b307fb2010-04-06 15:57:05 +00001679 }
1680 }
drh7ba39a92013-05-30 17:43:19 +00001681 assert( (u32)n==pLoop->u.btree.nEq );
drh4139c992010-04-07 14:59:45 +00001682
drhc6339082010-04-07 16:54:58 +00001683 /* Add additional columns needed to make the automatic index into
1684 ** a covering index */
drh4139c992010-04-07 14:59:45 +00001685 for(i=0; i<mxBitCol; i++){
drh7699d1c2013-06-04 12:42:29 +00001686 if( extraCols & MASKBIT(i) ){
drh4139c992010-04-07 14:59:45 +00001687 pIdx->aiColumn[n] = i;
1688 pIdx->azColl[n] = "BINARY";
1689 n++;
1690 }
1691 }
drh7699d1c2013-06-04 12:42:29 +00001692 if( pSrc->colUsed & MASKBIT(BMS-1) ){
drh4139c992010-04-07 14:59:45 +00001693 for(i=BMS-1; i<pTable->nCol; i++){
1694 pIdx->aiColumn[n] = i;
1695 pIdx->azColl[n] = "BINARY";
1696 n++;
1697 }
1698 }
drhbbbdc832013-10-22 18:01:40 +00001699 assert( n==nKeyCol );
drh44156282013-10-23 22:23:03 +00001700 pIdx->aiColumn[n] = -1;
1701 pIdx->azColl[n] = "BINARY";
drh8b307fb2010-04-06 15:57:05 +00001702
drhc6339082010-04-07 16:54:58 +00001703 /* Create the automatic index */
drh8b307fb2010-04-06 15:57:05 +00001704 assert( pLevel->iIdxCur>=0 );
drha1f41242013-05-31 20:00:58 +00001705 pLevel->iIdxCur = pParse->nTab++;
drh2ec2fb22013-11-06 19:59:23 +00001706 sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1);
1707 sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
drha21a64d2010-04-06 22:33:55 +00001708 VdbeComment((v, "for %s", pTable->zName));
drh8b307fb2010-04-06 15:57:05 +00001709
drhc6339082010-04-07 16:54:58 +00001710 /* Fill the automatic index with content */
drh688852a2014-02-17 22:40:43 +00001711 addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v);
drh8b307fb2010-04-06 15:57:05 +00001712 regRecord = sqlite3GetTempReg(pParse);
drh1c2c0b72014-01-04 19:27:05 +00001713 sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0);
drh8b307fb2010-04-06 15:57:05 +00001714 sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
1715 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
drh688852a2014-02-17 22:40:43 +00001716 sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v);
drha21a64d2010-04-06 22:33:55 +00001717 sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
drh8b307fb2010-04-06 15:57:05 +00001718 sqlite3VdbeJumpHere(v, addrTop);
1719 sqlite3ReleaseTempReg(pParse, regRecord);
1720
1721 /* Jump here when skipping the initialization */
1722 sqlite3VdbeJumpHere(v, addrInit);
1723}
drhc6339082010-04-07 16:54:58 +00001724#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
drh8b307fb2010-04-06 15:57:05 +00001725
drh9eff6162006-06-12 21:59:13 +00001726#ifndef SQLITE_OMIT_VIRTUALTABLE
1727/*
danielk19771d461462009-04-21 09:02:45 +00001728** Allocate and populate an sqlite3_index_info structure. It is the
1729** responsibility of the caller to eventually release the structure
1730** by passing the pointer returned by this function to sqlite3_free().
1731*/
drh5346e952013-05-08 14:14:26 +00001732static sqlite3_index_info *allocateIndexInfo(
1733 Parse *pParse,
1734 WhereClause *pWC,
1735 struct SrcList_item *pSrc,
1736 ExprList *pOrderBy
1737){
danielk19771d461462009-04-21 09:02:45 +00001738 int i, j;
1739 int nTerm;
1740 struct sqlite3_index_constraint *pIdxCons;
1741 struct sqlite3_index_orderby *pIdxOrderBy;
1742 struct sqlite3_index_constraint_usage *pUsage;
1743 WhereTerm *pTerm;
1744 int nOrderBy;
1745 sqlite3_index_info *pIdxInfo;
1746
danielk19771d461462009-04-21 09:02:45 +00001747 /* Count the number of possible WHERE clause constraints referring
1748 ** to this virtual table */
1749 for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
1750 if( pTerm->leftCursor != pSrc->iCursor ) continue;
drh7a5bcc02013-01-16 17:08:58 +00001751 assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
1752 testcase( pTerm->eOperator & WO_IN );
1753 testcase( pTerm->eOperator & WO_ISNULL );
dana4ff8252014-01-20 19:55:33 +00001754 testcase( pTerm->eOperator & WO_ALL );
1755 if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV))==0 ) continue;
drhb4256992011-08-02 01:57:39 +00001756 if( pTerm->wtFlags & TERM_VNULL ) continue;
danielk19771d461462009-04-21 09:02:45 +00001757 nTerm++;
1758 }
1759
1760 /* If the ORDER BY clause contains only columns in the current
1761 ** virtual table then allocate space for the aOrderBy part of
1762 ** the sqlite3_index_info structure.
1763 */
1764 nOrderBy = 0;
1765 if( pOrderBy ){
drh56f1b992012-09-25 14:29:39 +00001766 int n = pOrderBy->nExpr;
1767 for(i=0; i<n; i++){
danielk19771d461462009-04-21 09:02:45 +00001768 Expr *pExpr = pOrderBy->a[i].pExpr;
1769 if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
1770 }
drh56f1b992012-09-25 14:29:39 +00001771 if( i==n){
1772 nOrderBy = n;
danielk19771d461462009-04-21 09:02:45 +00001773 }
1774 }
1775
1776 /* Allocate the sqlite3_index_info structure
1777 */
1778 pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
1779 + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
1780 + sizeof(*pIdxOrderBy)*nOrderBy );
1781 if( pIdxInfo==0 ){
1782 sqlite3ErrorMsg(pParse, "out of memory");
danielk19771d461462009-04-21 09:02:45 +00001783 return 0;
1784 }
1785
1786 /* Initialize the structure. The sqlite3_index_info structure contains
1787 ** many fields that are declared "const" to prevent xBestIndex from
1788 ** changing them. We have to do some funky casting in order to
1789 ** initialize those fields.
1790 */
1791 pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
1792 pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
1793 pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
1794 *(int*)&pIdxInfo->nConstraint = nTerm;
1795 *(int*)&pIdxInfo->nOrderBy = nOrderBy;
1796 *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
1797 *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
1798 *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
1799 pUsage;
1800
1801 for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
drh281bbe22012-10-16 23:17:14 +00001802 u8 op;
danielk19771d461462009-04-21 09:02:45 +00001803 if( pTerm->leftCursor != pSrc->iCursor ) continue;
drh7a5bcc02013-01-16 17:08:58 +00001804 assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
1805 testcase( pTerm->eOperator & WO_IN );
1806 testcase( pTerm->eOperator & WO_ISNULL );
dana4ff8252014-01-20 19:55:33 +00001807 testcase( pTerm->eOperator & WO_ALL );
1808 if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV))==0 ) continue;
drhb4256992011-08-02 01:57:39 +00001809 if( pTerm->wtFlags & TERM_VNULL ) continue;
danielk19771d461462009-04-21 09:02:45 +00001810 pIdxCons[j].iColumn = pTerm->u.leftColumn;
1811 pIdxCons[j].iTermOffset = i;
drh7a5bcc02013-01-16 17:08:58 +00001812 op = (u8)pTerm->eOperator & WO_ALL;
drh281bbe22012-10-16 23:17:14 +00001813 if( op==WO_IN ) op = WO_EQ;
1814 pIdxCons[j].op = op;
danielk19771d461462009-04-21 09:02:45 +00001815 /* The direct assignment in the previous line is possible only because
1816 ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The
1817 ** following asserts verify this fact. */
1818 assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
1819 assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
1820 assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
1821 assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
1822 assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
1823 assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
drh281bbe22012-10-16 23:17:14 +00001824 assert( pTerm->eOperator & (WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
danielk19771d461462009-04-21 09:02:45 +00001825 j++;
1826 }
1827 for(i=0; i<nOrderBy; i++){
1828 Expr *pExpr = pOrderBy->a[i].pExpr;
1829 pIdxOrderBy[i].iColumn = pExpr->iColumn;
1830 pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
1831 }
1832
1833 return pIdxInfo;
1834}
1835
1836/*
1837** The table object reference passed as the second argument to this function
1838** must represent a virtual table. This function invokes the xBestIndex()
drh3b48e8c2013-06-12 20:18:16 +00001839** method of the virtual table with the sqlite3_index_info object that
1840** comes in as the 3rd argument to this function.
danielk19771d461462009-04-21 09:02:45 +00001841**
1842** If an error occurs, pParse is populated with an error message and a
1843** non-zero value is returned. Otherwise, 0 is returned and the output
1844** part of the sqlite3_index_info structure is left populated.
1845**
1846** Whether or not an error is returned, it is the responsibility of the
1847** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
1848** that this is required.
1849*/
1850static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
danielk1977595a5232009-07-24 17:58:53 +00001851 sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
danielk19771d461462009-04-21 09:02:45 +00001852 int i;
1853 int rc;
1854
danielk19771d461462009-04-21 09:02:45 +00001855 TRACE_IDX_INPUTS(p);
1856 rc = pVtab->pModule->xBestIndex(pVtab, p);
1857 TRACE_IDX_OUTPUTS(p);
danielk19771d461462009-04-21 09:02:45 +00001858
1859 if( rc!=SQLITE_OK ){
1860 if( rc==SQLITE_NOMEM ){
1861 pParse->db->mallocFailed = 1;
1862 }else if( !pVtab->zErrMsg ){
1863 sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
1864 }else{
1865 sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
1866 }
1867 }
drhb9755982010-07-24 16:34:37 +00001868 sqlite3_free(pVtab->zErrMsg);
danielk19771d461462009-04-21 09:02:45 +00001869 pVtab->zErrMsg = 0;
1870
1871 for(i=0; i<p->nConstraint; i++){
1872 if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
1873 sqlite3ErrorMsg(pParse,
1874 "table %s: xBestIndex returned an invalid plan", pTab->zName);
1875 }
1876 }
1877
1878 return pParse->nErr;
1879}
drh7ba39a92013-05-30 17:43:19 +00001880#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
danielk19771d461462009-04-21 09:02:45 +00001881
1882
drh1435a9a2013-08-27 23:15:44 +00001883#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drh28c4cf42005-07-27 20:41:43 +00001884/*
drhfaacf172011-08-12 01:51:45 +00001885** Estimate the location of a particular key among all keys in an
1886** index. Store the results in aStat as follows:
drhe847d322011-01-20 02:56:37 +00001887**
drhfaacf172011-08-12 01:51:45 +00001888** aStat[0] Est. number of rows less than pVal
1889** aStat[1] Est. number of rows equal to pVal
dan02fa4692009-08-17 17:06:58 +00001890**
drhfaacf172011-08-12 01:51:45 +00001891** Return SQLITE_OK on success.
dan02fa4692009-08-17 17:06:58 +00001892*/
danb3c02e22013-08-08 19:38:40 +00001893static void whereKeyStats(
dan02fa4692009-08-17 17:06:58 +00001894 Parse *pParse, /* Database connection */
1895 Index *pIdx, /* Index to consider domain of */
dan7a419232013-08-06 20:01:43 +00001896 UnpackedRecord *pRec, /* Vector of values to consider */
drhfaacf172011-08-12 01:51:45 +00001897 int roundUp, /* Round up if true. Round down if false */
1898 tRowcnt *aStat /* OUT: stats written here */
dan02fa4692009-08-17 17:06:58 +00001899){
danf52bb8d2013-08-03 20:24:58 +00001900 IndexSample *aSample = pIdx->aSample;
drhfbc38de2013-09-03 19:26:22 +00001901 int iCol; /* Index of required stats in anEq[] etc. */
dan84c309b2013-08-08 16:17:12 +00001902 int iMin = 0; /* Smallest sample not yet tested */
1903 int i = pIdx->nSample; /* Smallest sample larger than or equal to pRec */
1904 int iTest; /* Next sample to test */
1905 int res; /* Result of comparison operation */
dan02fa4692009-08-17 17:06:58 +00001906
drh4f991892013-10-11 15:05:05 +00001907#ifndef SQLITE_DEBUG
1908 UNUSED_PARAMETER( pParse );
1909#endif
drh7f594752013-12-03 19:49:55 +00001910 assert( pRec!=0 );
drhfbc38de2013-09-03 19:26:22 +00001911 iCol = pRec->nField - 1;
drh5c624862011-09-22 18:46:34 +00001912 assert( pIdx->nSample>0 );
dan8ad169a2013-08-12 20:14:04 +00001913 assert( pRec->nField>0 && iCol<pIdx->nSampleCol );
dan84c309b2013-08-08 16:17:12 +00001914 do{
1915 iTest = (iMin+i)/2;
1916 res = sqlite3VdbeRecordCompare(aSample[iTest].n, aSample[iTest].p, pRec);
1917 if( res<0 ){
1918 iMin = iTest+1;
1919 }else{
1920 i = iTest;
dan02fa4692009-08-17 17:06:58 +00001921 }
dan84c309b2013-08-08 16:17:12 +00001922 }while( res && iMin<i );
drh51147ba2005-07-23 22:59:55 +00001923
dan84c309b2013-08-08 16:17:12 +00001924#ifdef SQLITE_DEBUG
1925 /* The following assert statements check that the binary search code
1926 ** above found the right answer. This block serves no purpose other
1927 ** than to invoke the asserts. */
1928 if( res==0 ){
1929 /* If (res==0) is true, then sample $i must be equal to pRec */
1930 assert( i<pIdx->nSample );
drh0e1f0022013-08-16 14:49:00 +00001931 assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)
1932 || pParse->db->mallocFailed );
dan02fa4692009-08-17 17:06:58 +00001933 }else{
dan84c309b2013-08-08 16:17:12 +00001934 /* Otherwise, pRec must be smaller than sample $i and larger than
1935 ** sample ($i-1). */
1936 assert( i==pIdx->nSample
drh0e1f0022013-08-16 14:49:00 +00001937 || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0
1938 || pParse->db->mallocFailed );
dan84c309b2013-08-08 16:17:12 +00001939 assert( i==0
drh0e1f0022013-08-16 14:49:00 +00001940 || sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0
1941 || pParse->db->mallocFailed );
drhfaacf172011-08-12 01:51:45 +00001942 }
dan84c309b2013-08-08 16:17:12 +00001943#endif /* ifdef SQLITE_DEBUG */
dan02fa4692009-08-17 17:06:58 +00001944
drhfaacf172011-08-12 01:51:45 +00001945 /* At this point, aSample[i] is the first sample that is greater than
1946 ** or equal to pVal. Or if i==pIdx->nSample, then all samples are less
dan84c309b2013-08-08 16:17:12 +00001947 ** than pVal. If aSample[i]==pVal, then res==0.
drhfaacf172011-08-12 01:51:45 +00001948 */
dan84c309b2013-08-08 16:17:12 +00001949 if( res==0 ){
daneea568d2013-08-07 19:46:15 +00001950 aStat[0] = aSample[i].anLt[iCol];
1951 aStat[1] = aSample[i].anEq[iCol];
drhfaacf172011-08-12 01:51:45 +00001952 }else{
1953 tRowcnt iLower, iUpper, iGap;
1954 if( i==0 ){
1955 iLower = 0;
daneea568d2013-08-07 19:46:15 +00001956 iUpper = aSample[0].anLt[iCol];
drhfaacf172011-08-12 01:51:45 +00001957 }else{
daneea568d2013-08-07 19:46:15 +00001958 iUpper = i>=pIdx->nSample ? pIdx->aiRowEst[0] : aSample[i].anLt[iCol];
1959 iLower = aSample[i-1].anEq[iCol] + aSample[i-1].anLt[iCol];
drhfaacf172011-08-12 01:51:45 +00001960 }
drhbbbdc832013-10-22 18:01:40 +00001961 aStat[1] = (pIdx->nKeyCol>iCol ? pIdx->aAvgEq[iCol] : 1);
drhfaacf172011-08-12 01:51:45 +00001962 if( iLower>=iUpper ){
1963 iGap = 0;
1964 }else{
1965 iGap = iUpper - iLower;
drhfaacf172011-08-12 01:51:45 +00001966 }
1967 if( roundUp ){
1968 iGap = (iGap*2)/3;
1969 }else{
1970 iGap = iGap/3;
1971 }
1972 aStat[0] = iLower + iGap;
dan02fa4692009-08-17 17:06:58 +00001973 }
dan02fa4692009-08-17 17:06:58 +00001974}
drh1435a9a2013-08-27 23:15:44 +00001975#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
dan937d0de2009-10-15 18:35:38 +00001976
1977/*
dan02fa4692009-08-17 17:06:58 +00001978** This function is used to estimate the number of rows that will be visited
1979** by scanning an index for a range of values. The range may have an upper
1980** bound, a lower bound, or both. The WHERE clause terms that set the upper
1981** and lower bounds are represented by pLower and pUpper respectively. For
1982** example, assuming that index p is on t1(a):
1983**
1984** ... FROM t1 WHERE a > ? AND a < ? ...
1985** |_____| |_____|
1986** | |
1987** pLower pUpper
1988**
drh98cdf622009-08-20 18:14:42 +00001989** If either of the upper or lower bound is not present, then NULL is passed in
drhcdaca552009-08-20 13:45:07 +00001990** place of the corresponding WhereTerm.
dan02fa4692009-08-17 17:06:58 +00001991**
dan6cb8d762013-08-08 11:48:57 +00001992** The value in (pBuilder->pNew->u.btree.nEq) is the index of the index
1993** column subject to the range constraint. Or, equivalently, the number of
1994** equality constraints optimized by the proposed index scan. For example,
1995** assuming index p is on t1(a, b), and the SQL query is:
dan02fa4692009-08-17 17:06:58 +00001996**
1997** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
1998**
dan6cb8d762013-08-08 11:48:57 +00001999** then nEq is set to 1 (as the range restricted column, b, is the second
2000** left-most column of the index). Or, if the query is:
dan02fa4692009-08-17 17:06:58 +00002001**
2002** ... FROM t1 WHERE a > ? AND a < ? ...
2003**
dan6cb8d762013-08-08 11:48:57 +00002004** then nEq is set to 0.
dan02fa4692009-08-17 17:06:58 +00002005**
drhbf539c42013-10-05 18:16:02 +00002006** When this function is called, *pnOut is set to the sqlite3LogEst() of the
dan6cb8d762013-08-08 11:48:57 +00002007** number of rows that the index scan is expected to visit without
2008** considering the range constraints. If nEq is 0, this is the number of
2009** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced)
2010** to account for the range contraints pLower and pUpper.
2011**
2012** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be
2013** used, each range inequality reduces the search space by a factor of 4.
2014** Hence a pair of constraints (x>? AND x<?) reduces the expected number of
2015** rows visited by a factor of 16.
dan02fa4692009-08-17 17:06:58 +00002016*/
2017static int whereRangeScanEst(
drhcdaca552009-08-20 13:45:07 +00002018 Parse *pParse, /* Parsing & code generating context */
dan7a419232013-08-06 20:01:43 +00002019 WhereLoopBuilder *pBuilder,
drhcdaca552009-08-20 13:45:07 +00002020 WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
2021 WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
drh186ad8c2013-10-08 18:40:37 +00002022 WhereLoop *pLoop /* Modify the .nOut and maybe .rRun fields */
dan02fa4692009-08-17 17:06:58 +00002023){
dan69188d92009-08-19 08:18:32 +00002024 int rc = SQLITE_OK;
drh186ad8c2013-10-08 18:40:37 +00002025 int nOut = pLoop->nOut;
drhbf539c42013-10-05 18:16:02 +00002026 LogEst nNew;
dan69188d92009-08-19 08:18:32 +00002027
drh1435a9a2013-08-27 23:15:44 +00002028#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drh186ad8c2013-10-08 18:40:37 +00002029 Index *p = pLoop->u.btree.pIndex;
drh4f991892013-10-11 15:05:05 +00002030 int nEq = pLoop->u.btree.nEq;
dan02fa4692009-08-17 17:06:58 +00002031
drh74dade22013-09-04 18:14:53 +00002032 if( p->nSample>0
2033 && nEq==pBuilder->nRecValid
dan8ad169a2013-08-12 20:14:04 +00002034 && nEq<p->nSampleCol
dan7a419232013-08-06 20:01:43 +00002035 && OptimizationEnabled(pParse->db, SQLITE_Stat3)
2036 ){
2037 UnpackedRecord *pRec = pBuilder->pRec;
drhfaacf172011-08-12 01:51:45 +00002038 tRowcnt a[2];
dan575ab2f2013-09-02 07:16:40 +00002039 u8 aff;
drh98cdf622009-08-20 18:14:42 +00002040
danb3c02e22013-08-08 19:38:40 +00002041 /* Variable iLower will be set to the estimate of the number of rows in
2042 ** the index that are less than the lower bound of the range query. The
2043 ** lower bound being the concatenation of $P and $L, where $P is the
2044 ** key-prefix formed by the nEq values matched against the nEq left-most
2045 ** columns of the index, and $L is the value in pLower.
2046 **
2047 ** Or, if pLower is NULL or $L cannot be extracted from it (because it
2048 ** is not a simple variable or literal value), the lower bound of the
2049 ** range is $P. Due to a quirk in the way whereKeyStats() works, even
2050 ** if $L is available, whereKeyStats() is called for both ($P) and
2051 ** ($P:$L) and the larger of the two returned values used.
2052 **
2053 ** Similarly, iUpper is to be set to the estimate of the number of rows
2054 ** less than the upper bound of the range query. Where the upper bound
2055 ** is either ($P) or ($P:$U). Again, even if $U is available, both values
2056 ** of iUpper are requested of whereKeyStats() and the smaller used.
2057 */
2058 tRowcnt iLower;
2059 tRowcnt iUpper;
2060
drhbbbdc832013-10-22 18:01:40 +00002061 if( nEq==p->nKeyCol ){
mistachkinc2cfb512013-09-04 04:04:08 +00002062 aff = SQLITE_AFF_INTEGER;
2063 }else{
2064 aff = p->pTable->aCol[p->aiColumn[nEq]].affinity;
2065 }
danb3c02e22013-08-08 19:38:40 +00002066 /* Determine iLower and iUpper using ($P) only. */
2067 if( nEq==0 ){
2068 iLower = 0;
2069 iUpper = p->aiRowEst[0];
2070 }else{
2071 /* Note: this call could be optimized away - since the same values must
2072 ** have been requested when testing key $P in whereEqualScanEst(). */
2073 whereKeyStats(pParse, p, pRec, 0, a);
2074 iLower = a[0];
2075 iUpper = a[0] + a[1];
2076 }
2077
2078 /* If possible, improve on the iLower estimate using ($P:$L). */
dan02fa4692009-08-17 17:06:58 +00002079 if( pLower ){
dan7a419232013-08-06 20:01:43 +00002080 int bOk; /* True if value is extracted from pExpr */
dan02fa4692009-08-17 17:06:58 +00002081 Expr *pExpr = pLower->pExpr->pRight;
drh7a5bcc02013-01-16 17:08:58 +00002082 assert( (pLower->eOperator & (WO_GT|WO_GE))!=0 );
dan87cd9322013-08-07 15:52:41 +00002083 rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
danb3c02e22013-08-08 19:38:40 +00002084 if( rc==SQLITE_OK && bOk ){
2085 tRowcnt iNew;
2086 whereKeyStats(pParse, p, pRec, 0, a);
2087 iNew = a[0] + ((pLower->eOperator & WO_GT) ? a[1] : 0);
2088 if( iNew>iLower ) iLower = iNew;
drhabfa6d52013-09-11 03:53:22 +00002089 nOut--;
drhfaacf172011-08-12 01:51:45 +00002090 }
dan02fa4692009-08-17 17:06:58 +00002091 }
danb3c02e22013-08-08 19:38:40 +00002092
2093 /* If possible, improve on the iUpper estimate using ($P:$U). */
2094 if( pUpper ){
dan7a419232013-08-06 20:01:43 +00002095 int bOk; /* True if value is extracted from pExpr */
dan02fa4692009-08-17 17:06:58 +00002096 Expr *pExpr = pUpper->pExpr->pRight;
drh7a5bcc02013-01-16 17:08:58 +00002097 assert( (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
dan87cd9322013-08-07 15:52:41 +00002098 rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
danb3c02e22013-08-08 19:38:40 +00002099 if( rc==SQLITE_OK && bOk ){
2100 tRowcnt iNew;
2101 whereKeyStats(pParse, p, pRec, 1, a);
2102 iNew = a[0] + ((pUpper->eOperator & WO_LE) ? a[1] : 0);
2103 if( iNew<iUpper ) iUpper = iNew;
drhabfa6d52013-09-11 03:53:22 +00002104 nOut--;
dan02fa4692009-08-17 17:06:58 +00002105 }
2106 }
danb3c02e22013-08-08 19:38:40 +00002107
dan87cd9322013-08-07 15:52:41 +00002108 pBuilder->pRec = pRec;
drhfaacf172011-08-12 01:51:45 +00002109 if( rc==SQLITE_OK ){
drhb8a8e8a2013-06-10 19:12:39 +00002110 if( iUpper>iLower ){
drhbf539c42013-10-05 18:16:02 +00002111 nNew = sqlite3LogEst(iUpper - iLower);
dan7a419232013-08-06 20:01:43 +00002112 }else{
drhbf539c42013-10-05 18:16:02 +00002113 nNew = 10; assert( 10==sqlite3LogEst(2) );
drhfaacf172011-08-12 01:51:45 +00002114 }
dan6cb8d762013-08-08 11:48:57 +00002115 if( nNew<nOut ){
2116 nOut = nNew;
2117 }
drh186ad8c2013-10-08 18:40:37 +00002118 pLoop->nOut = (LogEst)nOut;
drh989578e2013-10-28 14:34:35 +00002119 WHERETRACE(0x10, ("range scan regions: %u..%u est=%d\n",
dan6cb8d762013-08-08 11:48:57 +00002120 (u32)iLower, (u32)iUpper, nOut));
drhfaacf172011-08-12 01:51:45 +00002121 return SQLITE_OK;
drh98cdf622009-08-20 18:14:42 +00002122 }
dan02fa4692009-08-17 17:06:58 +00002123 }
drh3f022182009-09-09 16:10:50 +00002124#else
2125 UNUSED_PARAMETER(pParse);
dan7a419232013-08-06 20:01:43 +00002126 UNUSED_PARAMETER(pBuilder);
dan69188d92009-08-19 08:18:32 +00002127#endif
dan02fa4692009-08-17 17:06:58 +00002128 assert( pLower || pUpper );
drhe1e2e9a2013-06-13 15:16:53 +00002129 /* TUNING: Each inequality constraint reduces the search space 4-fold.
2130 ** A BETWEEN operator, therefore, reduces the search space 16-fold */
drhabfa6d52013-09-11 03:53:22 +00002131 nNew = nOut;
drhb8a8e8a2013-06-10 19:12:39 +00002132 if( pLower && (pLower->wtFlags & TERM_VNULL)==0 ){
drhbf539c42013-10-05 18:16:02 +00002133 nNew -= 20; assert( 20==sqlite3LogEst(4) );
drhabfa6d52013-09-11 03:53:22 +00002134 nOut--;
drhb8a8e8a2013-06-10 19:12:39 +00002135 }
2136 if( pUpper ){
drhbf539c42013-10-05 18:16:02 +00002137 nNew -= 20; assert( 20==sqlite3LogEst(4) );
drhabfa6d52013-09-11 03:53:22 +00002138 nOut--;
drhb8a8e8a2013-06-10 19:12:39 +00002139 }
drhabfa6d52013-09-11 03:53:22 +00002140 if( nNew<10 ) nNew = 10;
2141 if( nNew<nOut ) nOut = nNew;
drh186ad8c2013-10-08 18:40:37 +00002142 pLoop->nOut = (LogEst)nOut;
dan02fa4692009-08-17 17:06:58 +00002143 return rc;
2144}
2145
drh1435a9a2013-08-27 23:15:44 +00002146#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drh82759752011-01-20 16:52:09 +00002147/*
2148** Estimate the number of rows that will be returned based on
2149** an equality constraint x=VALUE and where that VALUE occurs in
2150** the histogram data. This only works when x is the left-most
drhfaacf172011-08-12 01:51:45 +00002151** column of an index and sqlite_stat3 histogram data is available
drhac8eb112011-03-17 01:58:21 +00002152** for that index. When pExpr==NULL that means the constraint is
2153** "x IS NULL" instead of "x=VALUE".
drh82759752011-01-20 16:52:09 +00002154**
drh0c50fa02011-01-21 16:27:18 +00002155** Write the estimated row count into *pnRow and return SQLITE_OK.
2156** If unable to make an estimate, leave *pnRow unchanged and return
2157** non-zero.
drh9b3eb0a2011-01-21 14:37:04 +00002158**
2159** This routine can fail if it is unable to load a collating sequence
2160** required for string comparison, or if unable to allocate memory
2161** for a UTF conversion required for comparison. The error is stored
2162** in the pParse structure.
drh82759752011-01-20 16:52:09 +00002163*/
drh041e09f2011-04-07 19:56:21 +00002164static int whereEqualScanEst(
drh82759752011-01-20 16:52:09 +00002165 Parse *pParse, /* Parsing & code generating context */
dan7a419232013-08-06 20:01:43 +00002166 WhereLoopBuilder *pBuilder,
drh0c50fa02011-01-21 16:27:18 +00002167 Expr *pExpr, /* Expression for VALUE in the x=VALUE constraint */
drhb8a8e8a2013-06-10 19:12:39 +00002168 tRowcnt *pnRow /* Write the revised row estimate here */
drh82759752011-01-20 16:52:09 +00002169){
dan7a419232013-08-06 20:01:43 +00002170 Index *p = pBuilder->pNew->u.btree.pIndex;
2171 int nEq = pBuilder->pNew->u.btree.nEq;
2172 UnpackedRecord *pRec = pBuilder->pRec;
drh82759752011-01-20 16:52:09 +00002173 u8 aff; /* Column affinity */
2174 int rc; /* Subfunction return code */
drhfaacf172011-08-12 01:51:45 +00002175 tRowcnt a[2]; /* Statistics */
dan7a419232013-08-06 20:01:43 +00002176 int bOk;
drh82759752011-01-20 16:52:09 +00002177
dan7a419232013-08-06 20:01:43 +00002178 assert( nEq>=1 );
drhbbbdc832013-10-22 18:01:40 +00002179 assert( nEq<=(p->nKeyCol+1) );
drh82759752011-01-20 16:52:09 +00002180 assert( p->aSample!=0 );
drh5c624862011-09-22 18:46:34 +00002181 assert( p->nSample>0 );
dan7a419232013-08-06 20:01:43 +00002182 assert( pBuilder->nRecValid<nEq );
2183
2184 /* If values are not available for all fields of the index to the left
2185 ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */
2186 if( pBuilder->nRecValid<(nEq-1) ){
2187 return SQLITE_NOTFOUND;
drh1f9c7662011-03-17 01:34:26 +00002188 }
dan7a419232013-08-06 20:01:43 +00002189
dandd6e1f12013-08-10 19:08:30 +00002190 /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue()
2191 ** below would return the same value. */
drhbbbdc832013-10-22 18:01:40 +00002192 if( nEq>p->nKeyCol ){
dan7a419232013-08-06 20:01:43 +00002193 *pnRow = 1;
2194 return SQLITE_OK;
drh82759752011-01-20 16:52:09 +00002195 }
dan7a419232013-08-06 20:01:43 +00002196
daneea568d2013-08-07 19:46:15 +00002197 aff = p->pTable->aCol[p->aiColumn[nEq-1]].affinity;
dan87cd9322013-08-07 15:52:41 +00002198 rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq-1, &bOk);
2199 pBuilder->pRec = pRec;
dan7a419232013-08-06 20:01:43 +00002200 if( rc!=SQLITE_OK ) return rc;
2201 if( bOk==0 ) return SQLITE_NOTFOUND;
dan7a419232013-08-06 20:01:43 +00002202 pBuilder->nRecValid = nEq;
dan7a419232013-08-06 20:01:43 +00002203
danb3c02e22013-08-08 19:38:40 +00002204 whereKeyStats(pParse, p, pRec, 0, a);
drh989578e2013-10-28 14:34:35 +00002205 WHERETRACE(0x10,("equality scan regions: %d\n", (int)a[1]));
danb3c02e22013-08-08 19:38:40 +00002206 *pnRow = a[1];
daneea568d2013-08-07 19:46:15 +00002207
drh0c50fa02011-01-21 16:27:18 +00002208 return rc;
2209}
drh1435a9a2013-08-27 23:15:44 +00002210#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
drh0c50fa02011-01-21 16:27:18 +00002211
drh1435a9a2013-08-27 23:15:44 +00002212#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drh0c50fa02011-01-21 16:27:18 +00002213/*
2214** Estimate the number of rows that will be returned based on
drh5ac06072011-01-21 18:18:13 +00002215** an IN constraint where the right-hand side of the IN operator
2216** is a list of values. Example:
2217**
2218** WHERE x IN (1,2,3,4)
drh0c50fa02011-01-21 16:27:18 +00002219**
2220** Write the estimated row count into *pnRow and return SQLITE_OK.
2221** If unable to make an estimate, leave *pnRow unchanged and return
2222** non-zero.
2223**
2224** This routine can fail if it is unable to load a collating sequence
2225** required for string comparison, or if unable to allocate memory
2226** for a UTF conversion required for comparison. The error is stored
2227** in the pParse structure.
2228*/
drh041e09f2011-04-07 19:56:21 +00002229static int whereInScanEst(
drh0c50fa02011-01-21 16:27:18 +00002230 Parse *pParse, /* Parsing & code generating context */
dan7a419232013-08-06 20:01:43 +00002231 WhereLoopBuilder *pBuilder,
drh0c50fa02011-01-21 16:27:18 +00002232 ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
drhb8a8e8a2013-06-10 19:12:39 +00002233 tRowcnt *pnRow /* Write the revised row estimate here */
drh0c50fa02011-01-21 16:27:18 +00002234){
dan7a419232013-08-06 20:01:43 +00002235 Index *p = pBuilder->pNew->u.btree.pIndex;
2236 int nRecValid = pBuilder->nRecValid;
drhb8a8e8a2013-06-10 19:12:39 +00002237 int rc = SQLITE_OK; /* Subfunction return code */
2238 tRowcnt nEst; /* Number of rows for a single term */
2239 tRowcnt nRowEst = 0; /* New estimate of the number of rows */
2240 int i; /* Loop counter */
drh0c50fa02011-01-21 16:27:18 +00002241
2242 assert( p->aSample!=0 );
drhfaacf172011-08-12 01:51:45 +00002243 for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
2244 nEst = p->aiRowEst[0];
dan7a419232013-08-06 20:01:43 +00002245 rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst);
drhfaacf172011-08-12 01:51:45 +00002246 nRowEst += nEst;
dan7a419232013-08-06 20:01:43 +00002247 pBuilder->nRecValid = nRecValid;
drh0c50fa02011-01-21 16:27:18 +00002248 }
dan7a419232013-08-06 20:01:43 +00002249
drh0c50fa02011-01-21 16:27:18 +00002250 if( rc==SQLITE_OK ){
drh0c50fa02011-01-21 16:27:18 +00002251 if( nRowEst > p->aiRowEst[0] ) nRowEst = p->aiRowEst[0];
2252 *pnRow = nRowEst;
drh989578e2013-10-28 14:34:35 +00002253 WHERETRACE(0x10,("IN row estimate: est=%g\n", nRowEst));
drh0c50fa02011-01-21 16:27:18 +00002254 }
dan7a419232013-08-06 20:01:43 +00002255 assert( pBuilder->nRecValid==nRecValid );
drh0c50fa02011-01-21 16:27:18 +00002256 return rc;
drh82759752011-01-20 16:52:09 +00002257}
drh1435a9a2013-08-27 23:15:44 +00002258#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
drh82759752011-01-20 16:52:09 +00002259
drh46c35f92012-09-26 23:17:01 +00002260/*
drh2ffb1182004-07-19 19:14:01 +00002261** Disable a term in the WHERE clause. Except, do not disable the term
2262** if it controls a LEFT OUTER JOIN and it did not originate in the ON
2263** or USING clause of that join.
2264**
2265** Consider the term t2.z='ok' in the following queries:
2266**
2267** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
2268** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
2269** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
2270**
drh23bf66d2004-12-14 03:34:34 +00002271** The t2.z='ok' is disabled in the in (2) because it originates
drh2ffb1182004-07-19 19:14:01 +00002272** in the ON clause. The term is disabled in (3) because it is not part
2273** of a LEFT OUTER JOIN. In (1), the term is not disabled.
2274**
2275** Disabling a term causes that term to not be tested in the inner loop
drhb6fb62d2005-09-20 08:47:20 +00002276** of the join. Disabling is an optimization. When terms are satisfied
2277** by indices, we disable them to prevent redundant tests in the inner
2278** loop. We would get the correct results if nothing were ever disabled,
2279** but joins might run a little slower. The trick is to disable as much
2280** as we can without disabling too much. If we disabled in (1), we'd get
2281** the wrong answer. See ticket #813.
drh2ffb1182004-07-19 19:14:01 +00002282*/
drh0fcef5e2005-07-19 17:38:22 +00002283static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
2284 if( pTerm
drhbe837bd2010-04-30 21:03:24 +00002285 && (pTerm->wtFlags & TERM_CODED)==0
drh0fcef5e2005-07-19 17:38:22 +00002286 && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
drh0259bc32013-09-09 19:37:46 +00002287 && (pLevel->notReady & pTerm->prereqAll)==0
drh0fcef5e2005-07-19 17:38:22 +00002288 ){
drh165be382008-12-05 02:36:33 +00002289 pTerm->wtFlags |= TERM_CODED;
drh45b1ee42005-08-02 17:48:22 +00002290 if( pTerm->iParent>=0 ){
2291 WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
2292 if( (--pOther->nChild)==0 ){
drhed378002005-07-28 23:12:08 +00002293 disableTerm(pLevel, pOther);
2294 }
drh0fcef5e2005-07-19 17:38:22 +00002295 }
drh2ffb1182004-07-19 19:14:01 +00002296 }
2297}
2298
2299/*
dan69f8bb92009-08-13 19:21:16 +00002300** Code an OP_Affinity opcode to apply the column affinity string zAff
2301** to the n registers starting at base.
2302**
drh039fc322009-11-17 18:31:47 +00002303** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
2304** beginning and end of zAff are ignored. If all entries in zAff are
2305** SQLITE_AFF_NONE, then no code gets generated.
2306**
2307** This routine makes its own copy of zAff so that the caller is free
2308** to modify zAff after this routine returns.
drh94a11212004-09-25 13:12:14 +00002309*/
dan69f8bb92009-08-13 19:21:16 +00002310static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
2311 Vdbe *v = pParse->pVdbe;
drh039fc322009-11-17 18:31:47 +00002312 if( zAff==0 ){
2313 assert( pParse->db->mallocFailed );
2314 return;
2315 }
dan69f8bb92009-08-13 19:21:16 +00002316 assert( v!=0 );
drh039fc322009-11-17 18:31:47 +00002317
2318 /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
2319 ** and end of the affinity string.
2320 */
2321 while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
2322 n--;
2323 base++;
2324 zAff++;
2325 }
2326 while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
2327 n--;
2328 }
2329
2330 /* Code the OP_Affinity opcode if there is anything left to do. */
2331 if( n>0 ){
2332 sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
2333 sqlite3VdbeChangeP4(v, -1, zAff, n);
2334 sqlite3ExprCacheAffinityChange(pParse, base, n);
2335 }
drh94a11212004-09-25 13:12:14 +00002336}
2337
drhe8b97272005-07-19 22:22:12 +00002338
2339/*
drh51147ba2005-07-23 22:59:55 +00002340** Generate code for a single equality term of the WHERE clause. An equality
2341** term can be either X=expr or X IN (...). pTerm is the term to be
2342** coded.
2343**
drh1db639c2008-01-17 02:36:28 +00002344** The current value for the constraint is left in register iReg.
drh51147ba2005-07-23 22:59:55 +00002345**
2346** For a constraint of the form X=expr, the expression is evaluated and its
2347** result is left on the stack. For constraints of the form X IN (...)
2348** this routine sets up a loop that will iterate over all values of X.
drh94a11212004-09-25 13:12:14 +00002349*/
drh678ccce2008-03-31 18:19:54 +00002350static int codeEqualityTerm(
drh94a11212004-09-25 13:12:14 +00002351 Parse *pParse, /* The parsing context */
drhe23399f2005-07-22 00:31:39 +00002352 WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
drh0fe456b2013-03-12 18:34:50 +00002353 WhereLevel *pLevel, /* The level of the FROM clause we are working on */
2354 int iEq, /* Index of the equality term within this level */
drh7ba39a92013-05-30 17:43:19 +00002355 int bRev, /* True for reverse-order IN operations */
drh678ccce2008-03-31 18:19:54 +00002356 int iTarget /* Attempt to leave results in this register */
drh94a11212004-09-25 13:12:14 +00002357){
drh0fcef5e2005-07-19 17:38:22 +00002358 Expr *pX = pTerm->pExpr;
drh50b39962006-10-28 00:28:09 +00002359 Vdbe *v = pParse->pVdbe;
drh678ccce2008-03-31 18:19:54 +00002360 int iReg; /* Register holding results */
drh1db639c2008-01-17 02:36:28 +00002361
danielk19772d605492008-10-01 08:43:03 +00002362 assert( iTarget>0 );
drh50b39962006-10-28 00:28:09 +00002363 if( pX->op==TK_EQ ){
drh678ccce2008-03-31 18:19:54 +00002364 iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
drh50b39962006-10-28 00:28:09 +00002365 }else if( pX->op==TK_ISNULL ){
drh678ccce2008-03-31 18:19:54 +00002366 iReg = iTarget;
drh1db639c2008-01-17 02:36:28 +00002367 sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
danielk1977b3bce662005-01-29 08:32:43 +00002368#ifndef SQLITE_OMIT_SUBQUERY
drh94a11212004-09-25 13:12:14 +00002369 }else{
danielk19779a96b662007-11-29 17:05:18 +00002370 int eType;
danielk1977b3bce662005-01-29 08:32:43 +00002371 int iTab;
drh72e8fa42007-03-28 14:30:06 +00002372 struct InLoop *pIn;
drh7ba39a92013-05-30 17:43:19 +00002373 WhereLoop *pLoop = pLevel->pWLoop;
danielk1977b3bce662005-01-29 08:32:43 +00002374
drh7ba39a92013-05-30 17:43:19 +00002375 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
2376 && pLoop->u.btree.pIndex!=0
2377 && pLoop->u.btree.pIndex->aSortOrder[iEq]
drhd3832162013-03-12 18:49:25 +00002378 ){
drh725e1ae2013-03-12 23:58:42 +00002379 testcase( iEq==0 );
drh725e1ae2013-03-12 23:58:42 +00002380 testcase( bRev );
drh1ccce442013-03-12 20:38:51 +00002381 bRev = !bRev;
drh0fe456b2013-03-12 18:34:50 +00002382 }
drh50b39962006-10-28 00:28:09 +00002383 assert( pX->op==TK_IN );
drh678ccce2008-03-31 18:19:54 +00002384 iReg = iTarget;
danielk19770cdc0222008-06-26 18:04:03 +00002385 eType = sqlite3FindInIndex(pParse, pX, 0);
drh725e1ae2013-03-12 23:58:42 +00002386 if( eType==IN_INDEX_INDEX_DESC ){
2387 testcase( bRev );
2388 bRev = !bRev;
2389 }
danielk1977b3bce662005-01-29 08:32:43 +00002390 iTab = pX->iTable;
drh688852a2014-02-17 22:40:43 +00002391 sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0); VdbeCoverage(v);
drh6fa978d2013-05-30 19:29:19 +00002392 assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
2393 pLoop->wsFlags |= WHERE_IN_ABLE;
drh111a6a72008-12-21 03:51:16 +00002394 if( pLevel->u.in.nIn==0 ){
drhb3190c12008-12-08 21:37:14 +00002395 pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
drh72e8fa42007-03-28 14:30:06 +00002396 }
drh111a6a72008-12-21 03:51:16 +00002397 pLevel->u.in.nIn++;
2398 pLevel->u.in.aInLoop =
2399 sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
2400 sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
2401 pIn = pLevel->u.in.aInLoop;
drh72e8fa42007-03-28 14:30:06 +00002402 if( pIn ){
drh111a6a72008-12-21 03:51:16 +00002403 pIn += pLevel->u.in.nIn - 1;
drh72e8fa42007-03-28 14:30:06 +00002404 pIn->iCur = iTab;
drh1db639c2008-01-17 02:36:28 +00002405 if( eType==IN_INDEX_ROWID ){
drhb3190c12008-12-08 21:37:14 +00002406 pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
drh1db639c2008-01-17 02:36:28 +00002407 }else{
drhb3190c12008-12-08 21:37:14 +00002408 pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
drh1db639c2008-01-17 02:36:28 +00002409 }
drhf93cd942013-11-21 03:12:25 +00002410 pIn->eEndLoopOp = bRev ? OP_PrevIfOpen : OP_NextIfOpen;
drh688852a2014-02-17 22:40:43 +00002411 sqlite3VdbeAddOp1(v, OP_IsNull, iReg); VdbeCoverage(v);
drha6110402005-07-28 20:51:19 +00002412 }else{
drh111a6a72008-12-21 03:51:16 +00002413 pLevel->u.in.nIn = 0;
drhe23399f2005-07-22 00:31:39 +00002414 }
danielk1977b3bce662005-01-29 08:32:43 +00002415#endif
drh94a11212004-09-25 13:12:14 +00002416 }
drh0fcef5e2005-07-19 17:38:22 +00002417 disableTerm(pLevel, pTerm);
drh678ccce2008-03-31 18:19:54 +00002418 return iReg;
drh94a11212004-09-25 13:12:14 +00002419}
2420
drh51147ba2005-07-23 22:59:55 +00002421/*
2422** Generate code that will evaluate all == and IN constraints for an
drhcd8629e2013-11-13 12:27:25 +00002423** index scan.
drh51147ba2005-07-23 22:59:55 +00002424**
2425** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
2426** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
2427** The index has as many as three equality constraints, but in this
2428** example, the third "c" value is an inequality. So only two
2429** constraints are coded. This routine will generate code to evaluate
drh6df2acd2008-12-28 16:55:25 +00002430** a==5 and b IN (1,2,3). The current values for a and b will be stored
2431** in consecutive registers and the index of the first register is returned.
drh51147ba2005-07-23 22:59:55 +00002432**
2433** In the example above nEq==2. But this subroutine works for any value
2434** of nEq including 0. If nEq==0, this routine is nearly a no-op.
drh039fc322009-11-17 18:31:47 +00002435** The only thing it does is allocate the pLevel->iMem memory cell and
2436** compute the affinity string.
drh51147ba2005-07-23 22:59:55 +00002437**
drhcd8629e2013-11-13 12:27:25 +00002438** The nExtraReg parameter is 0 or 1. It is 0 if all WHERE clause constraints
2439** are == or IN and are covered by the nEq. nExtraReg is 1 if there is
2440** an inequality constraint (such as the "c>=5 AND c<10" in the example) that
2441** occurs after the nEq quality constraints.
2442**
2443** This routine allocates a range of nEq+nExtraReg memory cells and returns
2444** the index of the first memory cell in that range. The code that
2445** calls this routine will use that memory range to store keys for
2446** start and termination conditions of the loop.
drh51147ba2005-07-23 22:59:55 +00002447** key value of the loop. If one or more IN operators appear, then
2448** this routine allocates an additional nEq memory cells for internal
2449** use.
dan69f8bb92009-08-13 19:21:16 +00002450**
2451** Before returning, *pzAff is set to point to a buffer containing a
2452** copy of the column affinity string of the index allocated using
2453** sqlite3DbMalloc(). Except, entries in the copy of the string associated
2454** with equality constraints that use NONE affinity are set to
2455** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
2456**
2457** CREATE TABLE t1(a TEXT PRIMARY KEY, b);
2458** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
2459**
2460** In the example above, the index on t1(a) has TEXT affinity. But since
2461** the right hand side of the equality constraint (t2.b) has NONE affinity,
2462** no conversion should be attempted before using a t2.b value as part of
2463** a key to search the index. Hence the first byte in the returned affinity
2464** string in this example would be set to SQLITE_AFF_NONE.
drh51147ba2005-07-23 22:59:55 +00002465*/
drh1db639c2008-01-17 02:36:28 +00002466static int codeAllEqualityTerms(
drh51147ba2005-07-23 22:59:55 +00002467 Parse *pParse, /* Parsing context */
2468 WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
drh7ba39a92013-05-30 17:43:19 +00002469 int bRev, /* Reverse the order of IN operators */
dan69f8bb92009-08-13 19:21:16 +00002470 int nExtraReg, /* Number of extra registers to allocate */
2471 char **pzAff /* OUT: Set to point to affinity string */
drh51147ba2005-07-23 22:59:55 +00002472){
drhcd8629e2013-11-13 12:27:25 +00002473 u16 nEq; /* The number of == or IN constraints to code */
2474 u16 nSkip; /* Number of left-most columns to skip */
drh111a6a72008-12-21 03:51:16 +00002475 Vdbe *v = pParse->pVdbe; /* The vm under construction */
2476 Index *pIdx; /* The index being used for this loop */
drh51147ba2005-07-23 22:59:55 +00002477 WhereTerm *pTerm; /* A single constraint term */
drh7ba39a92013-05-30 17:43:19 +00002478 WhereLoop *pLoop; /* The WhereLoop object */
drh51147ba2005-07-23 22:59:55 +00002479 int j; /* Loop counter */
drh1db639c2008-01-17 02:36:28 +00002480 int regBase; /* Base register */
drh6df2acd2008-12-28 16:55:25 +00002481 int nReg; /* Number of registers to allocate */
dan69f8bb92009-08-13 19:21:16 +00002482 char *zAff; /* Affinity string to return */
drh51147ba2005-07-23 22:59:55 +00002483
drh111a6a72008-12-21 03:51:16 +00002484 /* This module is only called on query plans that use an index. */
drh7ba39a92013-05-30 17:43:19 +00002485 pLoop = pLevel->pWLoop;
2486 assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
2487 nEq = pLoop->u.btree.nEq;
drhcd8629e2013-11-13 12:27:25 +00002488 nSkip = pLoop->u.btree.nSkip;
drh7ba39a92013-05-30 17:43:19 +00002489 pIdx = pLoop->u.btree.pIndex;
2490 assert( pIdx!=0 );
drh111a6a72008-12-21 03:51:16 +00002491
drh51147ba2005-07-23 22:59:55 +00002492 /* Figure out how many memory cells we will need then allocate them.
drh51147ba2005-07-23 22:59:55 +00002493 */
drh700a2262008-12-17 19:22:15 +00002494 regBase = pParse->nMem + 1;
drh7ba39a92013-05-30 17:43:19 +00002495 nReg = pLoop->u.btree.nEq + nExtraReg;
drh6df2acd2008-12-28 16:55:25 +00002496 pParse->nMem += nReg;
drh51147ba2005-07-23 22:59:55 +00002497
dan69f8bb92009-08-13 19:21:16 +00002498 zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
2499 if( !zAff ){
2500 pParse->db->mallocFailed = 1;
2501 }
2502
drhcd8629e2013-11-13 12:27:25 +00002503 if( nSkip ){
2504 int iIdxCur = pLevel->iIdxCur;
drh688852a2014-02-17 22:40:43 +00002505 sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur); VdbeCoverage(v);
drhe084f402013-11-13 17:24:38 +00002506 VdbeComment((v, "begin skip-scan on %s", pIdx->zName));
drh2e5ef4e2013-11-13 16:58:54 +00002507 j = sqlite3VdbeAddOp0(v, OP_Goto);
drh4a1d3652014-02-14 15:13:36 +00002508 pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT),
drh688852a2014-02-17 22:40:43 +00002509 iIdxCur, 0, regBase, nSkip); VdbeCoverage(v);
drh2e5ef4e2013-11-13 16:58:54 +00002510 sqlite3VdbeJumpHere(v, j);
drhcd8629e2013-11-13 12:27:25 +00002511 for(j=0; j<nSkip; j++){
2512 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, j, regBase+j);
2513 assert( pIdx->aiColumn[j]>=0 );
2514 VdbeComment((v, "%s", pIdx->pTable->aCol[pIdx->aiColumn[j]].zName));
2515 }
2516 }
2517
drh51147ba2005-07-23 22:59:55 +00002518 /* Evaluate the equality constraints
2519 */
mistachkinf6418892013-08-28 01:54:12 +00002520 assert( zAff==0 || (int)strlen(zAff)>=nEq );
drhcd8629e2013-11-13 12:27:25 +00002521 for(j=nSkip; j<nEq; j++){
drh678ccce2008-03-31 18:19:54 +00002522 int r1;
drh4efc9292013-06-06 23:02:03 +00002523 pTerm = pLoop->aLTerm[j];
drh7ba39a92013-05-30 17:43:19 +00002524 assert( pTerm!=0 );
drhcd8629e2013-11-13 12:27:25 +00002525 /* The following testcase is true for indices with redundant columns.
drhbe837bd2010-04-30 21:03:24 +00002526 ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
2527 testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
drh39759742013-08-02 23:40:45 +00002528 testcase( pTerm->wtFlags & TERM_VIRTUAL );
drh7ba39a92013-05-30 17:43:19 +00002529 r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
drh678ccce2008-03-31 18:19:54 +00002530 if( r1!=regBase+j ){
drh6df2acd2008-12-28 16:55:25 +00002531 if( nReg==1 ){
2532 sqlite3ReleaseTempReg(pParse, regBase);
2533 regBase = r1;
2534 }else{
2535 sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
2536 }
drh678ccce2008-03-31 18:19:54 +00002537 }
drh981642f2008-04-19 14:40:43 +00002538 testcase( pTerm->eOperator & WO_ISNULL );
2539 testcase( pTerm->eOperator & WO_IN );
drh72e8fa42007-03-28 14:30:06 +00002540 if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
drh039fc322009-11-17 18:31:47 +00002541 Expr *pRight = pTerm->pExpr->pRight;
drh2f2855b2009-11-18 01:25:26 +00002542 sqlite3ExprCodeIsNullJump(v, pRight, regBase+j, pLevel->addrBrk);
drh039fc322009-11-17 18:31:47 +00002543 if( zAff ){
2544 if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
2545 zAff[j] = SQLITE_AFF_NONE;
2546 }
2547 if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
2548 zAff[j] = SQLITE_AFF_NONE;
2549 }
dan69f8bb92009-08-13 19:21:16 +00002550 }
drh51147ba2005-07-23 22:59:55 +00002551 }
2552 }
dan69f8bb92009-08-13 19:21:16 +00002553 *pzAff = zAff;
drh1db639c2008-01-17 02:36:28 +00002554 return regBase;
drh51147ba2005-07-23 22:59:55 +00002555}
2556
dan2ce22452010-11-08 19:01:16 +00002557#ifndef SQLITE_OMIT_EXPLAIN
dan17c0bc02010-11-09 17:35:19 +00002558/*
drh69174c42010-11-12 15:35:59 +00002559** This routine is a helper for explainIndexRange() below
2560**
2561** pStr holds the text of an expression that we are building up one term
2562** at a time. This routine adds a new term to the end of the expression.
2563** Terms are separated by AND so add the "AND" text for second and subsequent
2564** terms only.
2565*/
2566static void explainAppendTerm(
2567 StrAccum *pStr, /* The text expression being built */
2568 int iTerm, /* Index of this term. First is zero */
2569 const char *zColumn, /* Name of the column */
2570 const char *zOp /* Name of the operator */
2571){
2572 if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
drha6353a32013-12-09 19:03:26 +00002573 sqlite3StrAccumAppendAll(pStr, zColumn);
drh69174c42010-11-12 15:35:59 +00002574 sqlite3StrAccumAppend(pStr, zOp, 1);
2575 sqlite3StrAccumAppend(pStr, "?", 1);
2576}
2577
2578/*
dan17c0bc02010-11-09 17:35:19 +00002579** Argument pLevel describes a strategy for scanning table pTab. This
2580** function returns a pointer to a string buffer containing a description
2581** of the subset of table rows scanned by the strategy in the form of an
2582** SQL expression. Or, if all rows are scanned, NULL is returned.
2583**
2584** For example, if the query:
2585**
2586** SELECT * FROM t1 WHERE a=1 AND b>2;
2587**
2588** is run and there is an index on (a, b), then this function returns a
2589** string similar to:
2590**
2591** "a=? AND b>?"
2592**
2593** The returned pointer points to memory obtained from sqlite3DbMalloc().
2594** It is the responsibility of the caller to free the buffer when it is
2595** no longer required.
2596*/
drhef866372013-05-22 20:49:02 +00002597static char *explainIndexRange(sqlite3 *db, WhereLoop *pLoop, Table *pTab){
2598 Index *pIndex = pLoop->u.btree.pIndex;
drhcd8629e2013-11-13 12:27:25 +00002599 u16 nEq = pLoop->u.btree.nEq;
2600 u16 nSkip = pLoop->u.btree.nSkip;
drh69174c42010-11-12 15:35:59 +00002601 int i, j;
2602 Column *aCol = pTab->aCol;
drhbbbdc832013-10-22 18:01:40 +00002603 i16 *aiColumn = pIndex->aiColumn;
drh69174c42010-11-12 15:35:59 +00002604 StrAccum txt;
dan2ce22452010-11-08 19:01:16 +00002605
drhef866372013-05-22 20:49:02 +00002606 if( nEq==0 && (pLoop->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ){
drh69174c42010-11-12 15:35:59 +00002607 return 0;
2608 }
2609 sqlite3StrAccumInit(&txt, 0, 0, SQLITE_MAX_LENGTH);
drh03b6df12010-11-15 16:29:30 +00002610 txt.db = db;
drh69174c42010-11-12 15:35:59 +00002611 sqlite3StrAccumAppend(&txt, " (", 2);
dan2ce22452010-11-08 19:01:16 +00002612 for(i=0; i<nEq; i++){
drhbbbdc832013-10-22 18:01:40 +00002613 char *z = (i==pIndex->nKeyCol ) ? "rowid" : aCol[aiColumn[i]].zName;
drhcd8629e2013-11-13 12:27:25 +00002614 if( i>=nSkip ){
2615 explainAppendTerm(&txt, i, z, "=");
2616 }else{
2617 if( i ) sqlite3StrAccumAppend(&txt, " AND ", 5);
2618 sqlite3StrAccumAppend(&txt, "ANY(", 4);
drha6353a32013-12-09 19:03:26 +00002619 sqlite3StrAccumAppendAll(&txt, z);
drhcd8629e2013-11-13 12:27:25 +00002620 sqlite3StrAccumAppend(&txt, ")", 1);
2621 }
dan2ce22452010-11-08 19:01:16 +00002622 }
2623
drh69174c42010-11-12 15:35:59 +00002624 j = i;
drhef866372013-05-22 20:49:02 +00002625 if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
drhbbbdc832013-10-22 18:01:40 +00002626 char *z = (j==pIndex->nKeyCol ) ? "rowid" : aCol[aiColumn[j]].zName;
dan0c733f62011-11-16 15:27:09 +00002627 explainAppendTerm(&txt, i++, z, ">");
dan2ce22452010-11-08 19:01:16 +00002628 }
drhef866372013-05-22 20:49:02 +00002629 if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
drhbbbdc832013-10-22 18:01:40 +00002630 char *z = (j==pIndex->nKeyCol ) ? "rowid" : aCol[aiColumn[j]].zName;
dan0c733f62011-11-16 15:27:09 +00002631 explainAppendTerm(&txt, i, z, "<");
dan2ce22452010-11-08 19:01:16 +00002632 }
drh69174c42010-11-12 15:35:59 +00002633 sqlite3StrAccumAppend(&txt, ")", 1);
2634 return sqlite3StrAccumFinish(&txt);
dan2ce22452010-11-08 19:01:16 +00002635}
2636
dan17c0bc02010-11-09 17:35:19 +00002637/*
2638** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
2639** command. If the query being compiled is an EXPLAIN QUERY PLAN, a single
2640** record is added to the output to describe the table scan strategy in
2641** pLevel.
2642*/
2643static void explainOneScan(
dan2ce22452010-11-08 19:01:16 +00002644 Parse *pParse, /* Parse context */
2645 SrcList *pTabList, /* Table list this loop refers to */
2646 WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
2647 int iLevel, /* Value for "level" column of output */
dan4a07e3d2010-11-09 14:48:59 +00002648 int iFrom, /* Value for "from" column of output */
2649 u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
dan2ce22452010-11-08 19:01:16 +00002650){
drh84e55a82013-11-13 17:58:23 +00002651#ifndef SQLITE_DEBUG
2652 if( pParse->explain==2 )
2653#endif
2654 {
dan2ce22452010-11-08 19:01:16 +00002655 struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
dan17c0bc02010-11-09 17:35:19 +00002656 Vdbe *v = pParse->pVdbe; /* VM being constructed */
2657 sqlite3 *db = pParse->db; /* Database handle */
2658 char *zMsg; /* Text to add to EQP output */
dan4a07e3d2010-11-09 14:48:59 +00002659 int iId = pParse->iSelectId; /* Select id (left-most output column) */
dan4bc39fa2010-11-13 16:42:27 +00002660 int isSearch; /* True for a SEARCH. False for SCAN. */
drhef866372013-05-22 20:49:02 +00002661 WhereLoop *pLoop; /* The controlling WhereLoop object */
2662 u32 flags; /* Flags that describe this loop */
dan2ce22452010-11-08 19:01:16 +00002663
drhef866372013-05-22 20:49:02 +00002664 pLoop = pLevel->pWLoop;
2665 flags = pLoop->wsFlags;
dan4a07e3d2010-11-09 14:48:59 +00002666 if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return;
dan2ce22452010-11-08 19:01:16 +00002667
drhef866372013-05-22 20:49:02 +00002668 isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
2669 || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
2670 || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
dan4bc39fa2010-11-13 16:42:27 +00002671
2672 zMsg = sqlite3MPrintf(db, "%s", isSearch?"SEARCH":"SCAN");
dan4a07e3d2010-11-09 14:48:59 +00002673 if( pItem->pSelect ){
dan4bc39fa2010-11-13 16:42:27 +00002674 zMsg = sqlite3MAppendf(db, zMsg, "%s SUBQUERY %d", zMsg,pItem->iSelectId);
dan4a07e3d2010-11-09 14:48:59 +00002675 }else{
dan4bc39fa2010-11-13 16:42:27 +00002676 zMsg = sqlite3MAppendf(db, zMsg, "%s TABLE %s", zMsg, pItem->zName);
dan4a07e3d2010-11-09 14:48:59 +00002677 }
2678
dan2ce22452010-11-08 19:01:16 +00002679 if( pItem->zAlias ){
2680 zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
2681 }
drhef866372013-05-22 20:49:02 +00002682 if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0
drh7963b0e2013-06-17 21:37:40 +00002683 && ALWAYS(pLoop->u.btree.pIndex!=0)
drhef866372013-05-22 20:49:02 +00002684 ){
2685 char *zWhere = explainIndexRange(db, pLoop, pItem->pTab);
drh986b3872013-06-28 21:12:20 +00002686 zMsg = sqlite3MAppendf(db, zMsg,
2687 ((flags & WHERE_AUTO_INDEX) ?
2688 "%s USING AUTOMATIC %sINDEX%.0s%s" :
2689 "%s USING %sINDEX %s%s"),
2690 zMsg, ((flags & WHERE_IDX_ONLY) ? "COVERING " : ""),
2691 pLoop->u.btree.pIndex->zName, zWhere);
dan2ce22452010-11-08 19:01:16 +00002692 sqlite3DbFree(db, zWhere);
drhef71c1f2013-06-04 12:58:02 +00002693 }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
dan4bc39fa2010-11-13 16:42:27 +00002694 zMsg = sqlite3MAppendf(db, zMsg, "%s USING INTEGER PRIMARY KEY", zMsg);
dan2ce22452010-11-08 19:01:16 +00002695
drh8e23daf2013-06-11 13:30:04 +00002696 if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
dan2ce22452010-11-08 19:01:16 +00002697 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid=?)", zMsg);
drh04098e62010-11-15 21:50:19 +00002698 }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
dan2ce22452010-11-08 19:01:16 +00002699 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>? AND rowid<?)", zMsg);
2700 }else if( flags&WHERE_BTM_LIMIT ){
2701 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>?)", zMsg);
drh7963b0e2013-06-17 21:37:40 +00002702 }else if( ALWAYS(flags&WHERE_TOP_LIMIT) ){
dan2ce22452010-11-08 19:01:16 +00002703 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid<?)", zMsg);
2704 }
2705 }
2706#ifndef SQLITE_OMIT_VIRTUALTABLE
2707 else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
dan2ce22452010-11-08 19:01:16 +00002708 zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
drhef866372013-05-22 20:49:02 +00002709 pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
dan2ce22452010-11-08 19:01:16 +00002710 }
2711#endif
drhb8a8e8a2013-06-10 19:12:39 +00002712 zMsg = sqlite3MAppendf(db, zMsg, "%s", zMsg);
dan4a07e3d2010-11-09 14:48:59 +00002713 sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg, P4_DYNAMIC);
dan2ce22452010-11-08 19:01:16 +00002714 }
2715}
2716#else
dan17c0bc02010-11-09 17:35:19 +00002717# define explainOneScan(u,v,w,x,y,z)
dan2ce22452010-11-08 19:01:16 +00002718#endif /* SQLITE_OMIT_EXPLAIN */
2719
2720
drh111a6a72008-12-21 03:51:16 +00002721/*
2722** Generate code for the start of the iLevel-th loop in the WHERE clause
2723** implementation described by pWInfo.
2724*/
2725static Bitmask codeOneLoopStart(
2726 WhereInfo *pWInfo, /* Complete information about the WHERE clause */
2727 int iLevel, /* Which level of pWInfo->a[] should be coded */
drh7a484802012-03-16 00:28:11 +00002728 Bitmask notReady /* Which tables are currently available */
drh111a6a72008-12-21 03:51:16 +00002729){
2730 int j, k; /* Loop counters */
2731 int iCur; /* The VDBE cursor for the table */
2732 int addrNxt; /* Where to jump to continue with the next IN case */
2733 int omitTable; /* True if we use the index only */
2734 int bRev; /* True if we need to scan in reverse order */
2735 WhereLevel *pLevel; /* The where level to be coded */
drh7ba39a92013-05-30 17:43:19 +00002736 WhereLoop *pLoop; /* The WhereLoop object being coded */
drh111a6a72008-12-21 03:51:16 +00002737 WhereClause *pWC; /* Decomposition of the entire WHERE clause */
2738 WhereTerm *pTerm; /* A WHERE clause term */
2739 Parse *pParse; /* Parsing context */
drh6b36e822013-07-30 15:10:32 +00002740 sqlite3 *db; /* Database connection */
drh111a6a72008-12-21 03:51:16 +00002741 Vdbe *v; /* The prepared stmt under constructions */
2742 struct SrcList_item *pTabItem; /* FROM clause term being coded */
drh23d04d52008-12-23 23:56:22 +00002743 int addrBrk; /* Jump here to break out of the loop */
2744 int addrCont; /* Jump here to continue with next cycle */
drh61495262009-04-22 15:32:59 +00002745 int iRowidReg = 0; /* Rowid is stored in this register, if not zero */
2746 int iReleaseReg = 0; /* Temp register to free before returning */
drh111a6a72008-12-21 03:51:16 +00002747
2748 pParse = pWInfo->pParse;
2749 v = pParse->pVdbe;
drh70d18342013-06-06 19:16:33 +00002750 pWC = &pWInfo->sWC;
drh6b36e822013-07-30 15:10:32 +00002751 db = pParse->db;
drh111a6a72008-12-21 03:51:16 +00002752 pLevel = &pWInfo->a[iLevel];
drh7ba39a92013-05-30 17:43:19 +00002753 pLoop = pLevel->pWLoop;
drh111a6a72008-12-21 03:51:16 +00002754 pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
2755 iCur = pTabItem->iCursor;
drh0259bc32013-09-09 19:37:46 +00002756 pLevel->notReady = notReady & ~getMask(&pWInfo->sMaskSet, iCur);
drh7ba39a92013-05-30 17:43:19 +00002757 bRev = (pWInfo->revMask>>iLevel)&1;
2758 omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
drh70d18342013-06-06 19:16:33 +00002759 && (pWInfo->wctrlFlags & WHERE_FORCE_TABLE)==0;
drh6bc69a22013-11-19 12:33:23 +00002760 VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName));
drh111a6a72008-12-21 03:51:16 +00002761
2762 /* Create labels for the "break" and "continue" instructions
2763 ** for the current loop. Jump to addrBrk to break out of a loop.
2764 ** Jump to cont to go immediately to the next iteration of the
2765 ** loop.
2766 **
2767 ** When there is an IN operator, we also have a "addrNxt" label that
2768 ** means to continue with the next IN value combination. When
2769 ** there are no IN operators in the constraints, the "addrNxt" label
2770 ** is the same as "addrBrk".
2771 */
2772 addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
2773 addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
2774
2775 /* If this is the right table of a LEFT OUTER JOIN, allocate and
2776 ** initialize a memory cell that records if this table matches any
2777 ** row of the left table of the join.
2778 */
2779 if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
2780 pLevel->iLeftJoin = ++pParse->nMem;
2781 sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
2782 VdbeComment((v, "init LEFT JOIN no-match flag"));
2783 }
2784
drh21172c42012-10-30 00:29:07 +00002785 /* Special case of a FROM clause subquery implemented as a co-routine */
2786 if( pTabItem->viaCoroutine ){
2787 int regYield = pTabItem->regReturn;
drhed71a832014-02-07 19:18:10 +00002788 sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
drh81cf13e2014-02-07 18:27:53 +00002789 pLevel->p2 = sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk);
drh688852a2014-02-17 22:40:43 +00002790 VdbeCoverage(v);
drh725de292014-02-08 13:12:19 +00002791 VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
drh21172c42012-10-30 00:29:07 +00002792 pLevel->op = OP_Goto;
2793 }else
2794
drh111a6a72008-12-21 03:51:16 +00002795#ifndef SQLITE_OMIT_VIRTUALTABLE
drh7ba39a92013-05-30 17:43:19 +00002796 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
2797 /* Case 1: The table is a virtual-table. Use the VFilter and VNext
drh111a6a72008-12-21 03:51:16 +00002798 ** to access the data.
2799 */
2800 int iReg; /* P3 Value for OP_VFilter */
drh281bbe22012-10-16 23:17:14 +00002801 int addrNotFound;
drh4efc9292013-06-06 23:02:03 +00002802 int nConstraint = pLoop->nLTerm;
drh111a6a72008-12-21 03:51:16 +00002803
drha62bb8d2009-11-23 21:23:45 +00002804 sqlite3ExprCachePush(pParse);
drh111a6a72008-12-21 03:51:16 +00002805 iReg = sqlite3GetTempRange(pParse, nConstraint+2);
drh281bbe22012-10-16 23:17:14 +00002806 addrNotFound = pLevel->addrBrk;
drh111a6a72008-12-21 03:51:16 +00002807 for(j=0; j<nConstraint; j++){
drhe2250172013-05-31 18:13:50 +00002808 int iTarget = iReg+j+2;
drh4efc9292013-06-06 23:02:03 +00002809 pTerm = pLoop->aLTerm[j];
drh95ed68d2013-06-12 17:55:50 +00002810 if( pTerm==0 ) continue;
drh7ba39a92013-05-30 17:43:19 +00002811 if( pTerm->eOperator & WO_IN ){
2812 codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
2813 addrNotFound = pLevel->addrNxt;
2814 }else{
2815 sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget);
2816 }
2817 }
2818 sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
drh7e47cb82013-05-31 17:55:27 +00002819 sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
drh7ba39a92013-05-30 17:43:19 +00002820 sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
2821 pLoop->u.vtab.idxStr,
2822 pLoop->u.vtab.needFree ? P4_MPRINTF : P4_STATIC);
drh688852a2014-02-17 22:40:43 +00002823 VdbeCoverage(v);
drh7ba39a92013-05-30 17:43:19 +00002824 pLoop->u.vtab.needFree = 0;
2825 for(j=0; j<nConstraint && j<16; j++){
2826 if( (pLoop->u.vtab.omitMask>>j)&1 ){
drh4efc9292013-06-06 23:02:03 +00002827 disableTerm(pLevel, pLoop->aLTerm[j]);
drh111a6a72008-12-21 03:51:16 +00002828 }
2829 }
2830 pLevel->op = OP_VNext;
2831 pLevel->p1 = iCur;
2832 pLevel->p2 = sqlite3VdbeCurrentAddr(v);
drh23d04d52008-12-23 23:56:22 +00002833 sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
drha62bb8d2009-11-23 21:23:45 +00002834 sqlite3ExprCachePop(pParse, 1);
drh111a6a72008-12-21 03:51:16 +00002835 }else
2836#endif /* SQLITE_OMIT_VIRTUALTABLE */
2837
drh7ba39a92013-05-30 17:43:19 +00002838 if( (pLoop->wsFlags & WHERE_IPK)!=0
2839 && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
2840 ){
2841 /* Case 2: We can directly reference a single row using an
drh111a6a72008-12-21 03:51:16 +00002842 ** equality comparison against the ROWID field. Or
2843 ** we reference multiple rows using a "rowid IN (...)"
2844 ** construct.
2845 */
drh7ba39a92013-05-30 17:43:19 +00002846 assert( pLoop->u.btree.nEq==1 );
danielk19771d461462009-04-21 09:02:45 +00002847 iReleaseReg = sqlite3GetTempReg(pParse);
drh4efc9292013-06-06 23:02:03 +00002848 pTerm = pLoop->aLTerm[0];
drh111a6a72008-12-21 03:51:16 +00002849 assert( pTerm!=0 );
2850 assert( pTerm->pExpr!=0 );
drh111a6a72008-12-21 03:51:16 +00002851 assert( omitTable==0 );
drh39759742013-08-02 23:40:45 +00002852 testcase( pTerm->wtFlags & TERM_VIRTUAL );
drh7ba39a92013-05-30 17:43:19 +00002853 iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
drh111a6a72008-12-21 03:51:16 +00002854 addrNxt = pLevel->addrNxt;
drh688852a2014-02-17 22:40:43 +00002855 sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt); VdbeCoverage(v);
danielk19771d461462009-04-21 09:02:45 +00002856 sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
drh688852a2014-02-17 22:40:43 +00002857 VdbeCoverage(v);
drh459f63e2013-03-06 01:55:27 +00002858 sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
drhceea3322009-04-23 13:22:42 +00002859 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
drh111a6a72008-12-21 03:51:16 +00002860 VdbeComment((v, "pk"));
2861 pLevel->op = OP_Noop;
drh7ba39a92013-05-30 17:43:19 +00002862 }else if( (pLoop->wsFlags & WHERE_IPK)!=0
2863 && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
2864 ){
2865 /* Case 3: We have an inequality comparison against the ROWID field.
drh111a6a72008-12-21 03:51:16 +00002866 */
2867 int testOp = OP_Noop;
2868 int start;
2869 int memEndValue = 0;
2870 WhereTerm *pStart, *pEnd;
2871
2872 assert( omitTable==0 );
drh7ba39a92013-05-30 17:43:19 +00002873 j = 0;
2874 pStart = pEnd = 0;
drh4efc9292013-06-06 23:02:03 +00002875 if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
2876 if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
drh81186b42013-06-18 01:52:41 +00002877 assert( pStart!=0 || pEnd!=0 );
drh111a6a72008-12-21 03:51:16 +00002878 if( bRev ){
2879 pTerm = pStart;
2880 pStart = pEnd;
2881 pEnd = pTerm;
2882 }
2883 if( pStart ){
2884 Expr *pX; /* The expression that defines the start bound */
2885 int r1, rTemp; /* Registers for holding the start boundary */
2886
2887 /* The following constant maps TK_xx codes into corresponding
2888 ** seek opcodes. It depends on a particular ordering of TK_xx
2889 */
2890 const u8 aMoveOp[] = {
drh4a1d3652014-02-14 15:13:36 +00002891 /* TK_GT */ OP_SeekGT,
2892 /* TK_LE */ OP_SeekLE,
2893 /* TK_LT */ OP_SeekLT,
2894 /* TK_GE */ OP_SeekGE
drh111a6a72008-12-21 03:51:16 +00002895 };
2896 assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */
2897 assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */
2898 assert( TK_GE==TK_GT+3 ); /* ... is correcct. */
2899
drhb5246e52013-07-08 21:12:57 +00002900 assert( (pStart->wtFlags & TERM_VNULL)==0 );
drh39759742013-08-02 23:40:45 +00002901 testcase( pStart->wtFlags & TERM_VIRTUAL );
drh111a6a72008-12-21 03:51:16 +00002902 pX = pStart->pExpr;
2903 assert( pX!=0 );
drhb5246e52013-07-08 21:12:57 +00002904 testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
drh111a6a72008-12-21 03:51:16 +00002905 r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
2906 sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
drh688852a2014-02-17 22:40:43 +00002907 VdbeComment((v, "pk")); VdbeCoverage(v);
drh111a6a72008-12-21 03:51:16 +00002908 sqlite3ExprCacheAffinityChange(pParse, r1, 1);
2909 sqlite3ReleaseTempReg(pParse, rTemp);
2910 disableTerm(pLevel, pStart);
2911 }else{
2912 sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
drh688852a2014-02-17 22:40:43 +00002913 VdbeCoverage(v);
drh111a6a72008-12-21 03:51:16 +00002914 }
2915 if( pEnd ){
2916 Expr *pX;
2917 pX = pEnd->pExpr;
2918 assert( pX!=0 );
drhb5246e52013-07-08 21:12:57 +00002919 assert( (pEnd->wtFlags & TERM_VNULL)==0 );
2920 testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
drh39759742013-08-02 23:40:45 +00002921 testcase( pEnd->wtFlags & TERM_VIRTUAL );
drh111a6a72008-12-21 03:51:16 +00002922 memEndValue = ++pParse->nMem;
2923 sqlite3ExprCode(pParse, pX->pRight, memEndValue);
2924 if( pX->op==TK_LT || pX->op==TK_GT ){
2925 testOp = bRev ? OP_Le : OP_Ge;
2926 }else{
2927 testOp = bRev ? OP_Lt : OP_Gt;
2928 }
2929 disableTerm(pLevel, pEnd);
2930 }
2931 start = sqlite3VdbeCurrentAddr(v);
2932 pLevel->op = bRev ? OP_Prev : OP_Next;
2933 pLevel->p1 = iCur;
2934 pLevel->p2 = start;
drh81186b42013-06-18 01:52:41 +00002935 assert( pLevel->p5==0 );
danielk19771d461462009-04-21 09:02:45 +00002936 if( testOp!=OP_Noop ){
2937 iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
2938 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
drhceea3322009-04-23 13:22:42 +00002939 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
danielk19771d461462009-04-21 09:02:45 +00002940 sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
drh688852a2014-02-17 22:40:43 +00002941 VdbeCoverage(v);
danielk19771d461462009-04-21 09:02:45 +00002942 sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
drh111a6a72008-12-21 03:51:16 +00002943 }
drh1b0f0262013-05-30 22:27:09 +00002944 }else if( pLoop->wsFlags & WHERE_INDEXED ){
drh7ba39a92013-05-30 17:43:19 +00002945 /* Case 4: A scan using an index.
drh111a6a72008-12-21 03:51:16 +00002946 **
2947 ** The WHERE clause may contain zero or more equality
2948 ** terms ("==" or "IN" operators) that refer to the N
2949 ** left-most columns of the index. It may also contain
2950 ** inequality constraints (>, <, >= or <=) on the indexed
2951 ** column that immediately follows the N equalities. Only
2952 ** the right-most column can be an inequality - the rest must
2953 ** use the "==" and "IN" operators. For example, if the
2954 ** index is on (x,y,z), then the following clauses are all
2955 ** optimized:
2956 **
2957 ** x=5
2958 ** x=5 AND y=10
2959 ** x=5 AND y<10
2960 ** x=5 AND y>5 AND y<10
2961 ** x=5 AND y=5 AND z<=10
2962 **
2963 ** The z<10 term of the following cannot be used, only
2964 ** the x=5 term:
2965 **
2966 ** x=5 AND z<10
2967 **
2968 ** N may be zero if there are inequality constraints.
2969 ** If there are no inequality constraints, then N is at
2970 ** least one.
2971 **
2972 ** This case is also used when there are no WHERE clause
2973 ** constraints but an index is selected anyway, in order
2974 ** to force the output order to conform to an ORDER BY.
2975 */
drh3bb9b932010-08-06 02:10:00 +00002976 static const u8 aStartOp[] = {
drh111a6a72008-12-21 03:51:16 +00002977 0,
2978 0,
2979 OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */
2980 OP_Last, /* 3: (!start_constraints && startEq && bRev) */
drh4a1d3652014-02-14 15:13:36 +00002981 OP_SeekGT, /* 4: (start_constraints && !startEq && !bRev) */
2982 OP_SeekLT, /* 5: (start_constraints && !startEq && bRev) */
2983 OP_SeekGE, /* 6: (start_constraints && startEq && !bRev) */
2984 OP_SeekLE /* 7: (start_constraints && startEq && bRev) */
drh111a6a72008-12-21 03:51:16 +00002985 };
drh3bb9b932010-08-06 02:10:00 +00002986 static const u8 aEndOp[] = {
drh4a1d3652014-02-14 15:13:36 +00002987 OP_IdxGE, /* 0: (end_constraints && !bRev && !endEq) */
2988 OP_IdxGT, /* 1: (end_constraints && !bRev && endEq) */
2989 OP_IdxLE, /* 2: (end_constraints && bRev && !endEq) */
2990 OP_IdxLT, /* 3: (end_constraints && bRev && endEq) */
drh111a6a72008-12-21 03:51:16 +00002991 };
drhcd8629e2013-11-13 12:27:25 +00002992 u16 nEq = pLoop->u.btree.nEq; /* Number of == or IN terms */
drh111a6a72008-12-21 03:51:16 +00002993 int regBase; /* Base register holding constraint values */
drh111a6a72008-12-21 03:51:16 +00002994 WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */
2995 WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */
2996 int startEq; /* True if range start uses ==, >= or <= */
2997 int endEq; /* True if range end uses ==, >= or <= */
2998 int start_constraints; /* Start of range is constrained */
2999 int nConstraint; /* Number of constraint terms */
drh3bb9b932010-08-06 02:10:00 +00003000 Index *pIdx; /* The index we will be using */
3001 int iIdxCur; /* The VDBE cursor for the index */
3002 int nExtraReg = 0; /* Number of extra registers needed */
3003 int op; /* Instruction opcode */
dan6ac43392010-06-09 15:47:11 +00003004 char *zStartAff; /* Affinity for start of range constraint */
drh33cad2f2013-11-15 12:41:01 +00003005 char cEndAff = 0; /* Affinity for end of range constraint */
drhcfc6ca42014-02-14 23:49:13 +00003006 u8 bSeekPastNull = 0; /* True to seek past initial nulls */
3007 u8 bStopAtNull = 0; /* Add condition to terminate at NULLs */
drh111a6a72008-12-21 03:51:16 +00003008
drh7ba39a92013-05-30 17:43:19 +00003009 pIdx = pLoop->u.btree.pIndex;
drh111a6a72008-12-21 03:51:16 +00003010 iIdxCur = pLevel->iIdxCur;
drh052e6a82013-11-14 19:34:10 +00003011 assert( nEq>=pLoop->u.btree.nSkip );
drh111a6a72008-12-21 03:51:16 +00003012
drh111a6a72008-12-21 03:51:16 +00003013 /* If this loop satisfies a sort order (pOrderBy) request that
3014 ** was passed to this function to implement a "SELECT min(x) ..."
3015 ** query, then the caller will only allow the loop to run for
3016 ** a single iteration. This means that the first row returned
3017 ** should not have a NULL value stored in 'x'. If column 'x' is
3018 ** the first one after the nEq equality constraints in the index,
3019 ** this requires some special handling.
3020 */
drh70d18342013-06-06 19:16:33 +00003021 if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
drh4f402f22013-06-11 18:59:38 +00003022 && (pWInfo->bOBSat!=0)
drhbbbdc832013-10-22 18:01:40 +00003023 && (pIdx->nKeyCol>nEq)
drh111a6a72008-12-21 03:51:16 +00003024 ){
drh052e6a82013-11-14 19:34:10 +00003025 assert( pLoop->u.btree.nSkip==0 );
drhcfc6ca42014-02-14 23:49:13 +00003026 bSeekPastNull = 1;
drh6df2acd2008-12-28 16:55:25 +00003027 nExtraReg = 1;
drh111a6a72008-12-21 03:51:16 +00003028 }
3029
3030 /* Find any inequality constraint terms for the start and end
3031 ** of the range.
3032 */
drh7ba39a92013-05-30 17:43:19 +00003033 j = nEq;
3034 if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
drh4efc9292013-06-06 23:02:03 +00003035 pRangeStart = pLoop->aLTerm[j++];
drh6df2acd2008-12-28 16:55:25 +00003036 nExtraReg = 1;
drh111a6a72008-12-21 03:51:16 +00003037 }
drh7ba39a92013-05-30 17:43:19 +00003038 if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
drh4efc9292013-06-06 23:02:03 +00003039 pRangeEnd = pLoop->aLTerm[j++];
drh6df2acd2008-12-28 16:55:25 +00003040 nExtraReg = 1;
drhcfc6ca42014-02-14 23:49:13 +00003041 if( pRangeStart==0
3042 && (pRangeEnd->wtFlags & TERM_VNULL)==0
3043 && (j = pIdx->aiColumn[nEq])>=0
3044 && pIdx->pTable->aCol[j].notNull==0
3045 ){
3046 bSeekPastNull = 1;
3047 }
drh111a6a72008-12-21 03:51:16 +00003048 }
3049
drh6df2acd2008-12-28 16:55:25 +00003050 /* Generate code to evaluate all constraint terms using == or IN
3051 ** and store the values of those terms in an array of registers
3052 ** starting at regBase.
3053 */
drh613ba1e2013-06-15 15:11:45 +00003054 regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
drh33cad2f2013-11-15 12:41:01 +00003055 assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq );
3056 if( zStartAff ) cEndAff = zStartAff[nEq];
drh6df2acd2008-12-28 16:55:25 +00003057 addrNxt = pLevel->addrNxt;
3058
drh111a6a72008-12-21 03:51:16 +00003059 /* If we are doing a reverse order scan on an ascending index, or
3060 ** a forward order scan on a descending index, interchange the
3061 ** start and end terms (pRangeStart and pRangeEnd).
3062 */
drhbbbdc832013-10-22 18:01:40 +00003063 if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
3064 || (bRev && pIdx->nKeyCol==nEq)
dan0c733f62011-11-16 15:27:09 +00003065 ){
drh111a6a72008-12-21 03:51:16 +00003066 SWAP(WhereTerm *, pRangeEnd, pRangeStart);
drhcfc6ca42014-02-14 23:49:13 +00003067 SWAP(u8, bSeekPastNull, bStopAtNull);
drh111a6a72008-12-21 03:51:16 +00003068 }
3069
drh7963b0e2013-06-17 21:37:40 +00003070 testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
3071 testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
3072 testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
3073 testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
drh111a6a72008-12-21 03:51:16 +00003074 startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
3075 endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
3076 start_constraints = pRangeStart || nEq>0;
3077
3078 /* Seek the index cursor to the start of the range. */
3079 nConstraint = nEq;
3080 if( pRangeStart ){
dan69f8bb92009-08-13 19:21:16 +00003081 Expr *pRight = pRangeStart->pExpr->pRight;
3082 sqlite3ExprCode(pParse, pRight, regBase+nEq);
drh534230c2011-01-22 00:10:45 +00003083 if( (pRangeStart->wtFlags & TERM_VNULL)==0 ){
3084 sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
3085 }
dan6ac43392010-06-09 15:47:11 +00003086 if( zStartAff ){
3087 if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
drh039fc322009-11-17 18:31:47 +00003088 /* Since the comparison is to be performed with no conversions
3089 ** applied to the operands, set the affinity to apply to pRight to
3090 ** SQLITE_AFF_NONE. */
dan6ac43392010-06-09 15:47:11 +00003091 zStartAff[nEq] = SQLITE_AFF_NONE;
drh039fc322009-11-17 18:31:47 +00003092 }
dan6ac43392010-06-09 15:47:11 +00003093 if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
3094 zStartAff[nEq] = SQLITE_AFF_NONE;
drh039fc322009-11-17 18:31:47 +00003095 }
3096 }
drh111a6a72008-12-21 03:51:16 +00003097 nConstraint++;
drh39759742013-08-02 23:40:45 +00003098 testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
drhcfc6ca42014-02-14 23:49:13 +00003099 }else if( bSeekPastNull ){
drh111a6a72008-12-21 03:51:16 +00003100 sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
3101 nConstraint++;
3102 startEq = 0;
3103 start_constraints = 1;
3104 }
drhcfc6ca42014-02-14 23:49:13 +00003105 codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff);
drh111a6a72008-12-21 03:51:16 +00003106 op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
3107 assert( op!=0 );
3108 testcase( op==OP_Rewind );
3109 testcase( op==OP_Last );
drh4a1d3652014-02-14 15:13:36 +00003110 testcase( op==OP_SeekGT );
3111 testcase( op==OP_SeekGE );
3112 testcase( op==OP_SeekLE );
3113 testcase( op==OP_SeekLT );
drh8cff69d2009-11-12 19:59:44 +00003114 sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
drh688852a2014-02-17 22:40:43 +00003115 VdbeCoverage(v);
3116 VdbeCoverageIf(v, op==OP_Rewind);
3117 VdbeCoverageIf(v, op==OP_Last);
3118 VdbeCoverageIf(v, op==OP_SeekGT);
3119 VdbeCoverageIf(v, op==OP_SeekGE);
3120 VdbeCoverageIf(v, op==OP_SeekLE);
3121 VdbeCoverageIf(v, op==OP_SeekLT);
drh111a6a72008-12-21 03:51:16 +00003122
3123 /* Load the value for the inequality constraint at the end of the
3124 ** range (if any).
3125 */
3126 nConstraint = nEq;
3127 if( pRangeEnd ){
dan69f8bb92009-08-13 19:21:16 +00003128 Expr *pRight = pRangeEnd->pExpr->pRight;
drhf49f3522009-12-30 14:12:38 +00003129 sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
dan69f8bb92009-08-13 19:21:16 +00003130 sqlite3ExprCode(pParse, pRight, regBase+nEq);
drh534230c2011-01-22 00:10:45 +00003131 if( (pRangeEnd->wtFlags & TERM_VNULL)==0 ){
3132 sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
3133 }
drh33cad2f2013-11-15 12:41:01 +00003134 if( sqlite3CompareAffinity(pRight, cEndAff)!=SQLITE_AFF_NONE
3135 && !sqlite3ExprNeedsNoAffinityChange(pRight, cEndAff)
3136 ){
3137 codeApplyAffinity(pParse, regBase+nEq, 1, &cEndAff);
3138 }
drh111a6a72008-12-21 03:51:16 +00003139 nConstraint++;
drh39759742013-08-02 23:40:45 +00003140 testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
drhcfc6ca42014-02-14 23:49:13 +00003141 }else if( bStopAtNull ){
3142 sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
3143 endEq = 0;
3144 nConstraint++;
drh111a6a72008-12-21 03:51:16 +00003145 }
drh6b36e822013-07-30 15:10:32 +00003146 sqlite3DbFree(db, zStartAff);
drh111a6a72008-12-21 03:51:16 +00003147
3148 /* Top of the loop body */
3149 pLevel->p2 = sqlite3VdbeCurrentAddr(v);
3150
3151 /* Check if the index cursor is past the end of the range. */
drhcfc6ca42014-02-14 23:49:13 +00003152 if( nConstraint ){
drh4a1d3652014-02-14 15:13:36 +00003153 op = aEndOp[bRev*2 + endEq];
3154 testcase( op==OP_IdxGT );
3155 testcase( op==OP_IdxGE );
3156 testcase( op==OP_IdxLT );
3157 testcase( op==OP_IdxLE );
drh8cff69d2009-11-12 19:59:44 +00003158 sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
drh688852a2014-02-17 22:40:43 +00003159 VdbeCoverage(v);
drh6df2acd2008-12-28 16:55:25 +00003160 }
drh111a6a72008-12-21 03:51:16 +00003161
drh111a6a72008-12-21 03:51:16 +00003162 /* Seek the table cursor, if required */
drh23d04d52008-12-23 23:56:22 +00003163 disableTerm(pLevel, pRangeStart);
3164 disableTerm(pLevel, pRangeEnd);
drh85c1c552013-10-24 00:18:18 +00003165 if( omitTable ){
3166 /* pIdx is a covering index. No need to access the main table. */
3167 }else if( HasRowid(pIdx->pTable) ){
danielk19771d461462009-04-21 09:02:45 +00003168 iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
3169 sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
drhceea3322009-04-23 13:22:42 +00003170 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
danielk19771d461462009-04-21 09:02:45 +00003171 sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg); /* Deferred seek */
drh85c1c552013-10-24 00:18:18 +00003172 }else{
3173 Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
3174 iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol);
3175 for(j=0; j<pPk->nKeyCol; j++){
3176 k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
3177 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j);
3178 }
drh261c02d2013-10-25 14:46:15 +00003179 sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont,
drh688852a2014-02-17 22:40:43 +00003180 iRowidReg, pPk->nKeyCol); VdbeCoverage(v);
drh111a6a72008-12-21 03:51:16 +00003181 }
drh111a6a72008-12-21 03:51:16 +00003182
3183 /* Record the instruction used to terminate the loop. Disable
3184 ** WHERE clause terms made redundant by the index range scan.
3185 */
drh7699d1c2013-06-04 12:42:29 +00003186 if( pLoop->wsFlags & WHERE_ONEROW ){
drh95e037b2011-03-09 21:02:31 +00003187 pLevel->op = OP_Noop;
3188 }else if( bRev ){
3189 pLevel->op = OP_Prev;
3190 }else{
3191 pLevel->op = OP_Next;
3192 }
drh111a6a72008-12-21 03:51:16 +00003193 pLevel->p1 = iIdxCur;
drhe39a7322014-02-03 14:04:11 +00003194 assert( (WHERE_UNQ_WANTED>>16)==1 );
3195 pLevel->p3 = (pLoop->wsFlags>>16)&1;
drh53cfbe92013-06-13 17:28:22 +00003196 if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
drh3f4d1d12012-09-15 18:45:54 +00003197 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
3198 }else{
3199 assert( pLevel->p5==0 );
3200 }
drhdd5f5a62008-12-23 13:35:23 +00003201 }else
3202
drh23d04d52008-12-23 23:56:22 +00003203#ifndef SQLITE_OMIT_OR_OPTIMIZATION
drh7ba39a92013-05-30 17:43:19 +00003204 if( pLoop->wsFlags & WHERE_MULTI_OR ){
3205 /* Case 5: Two or more separately indexed terms connected by OR
drh111a6a72008-12-21 03:51:16 +00003206 **
3207 ** Example:
3208 **
3209 ** CREATE TABLE t1(a,b,c,d);
3210 ** CREATE INDEX i1 ON t1(a);
3211 ** CREATE INDEX i2 ON t1(b);
3212 ** CREATE INDEX i3 ON t1(c);
3213 **
3214 ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
3215 **
3216 ** In the example, there are three indexed terms connected by OR.
danielk19771d461462009-04-21 09:02:45 +00003217 ** The top of the loop looks like this:
drh111a6a72008-12-21 03:51:16 +00003218 **
drh1b26c7c2009-04-22 02:15:47 +00003219 ** Null 1 # Zero the rowset in reg 1
drh111a6a72008-12-21 03:51:16 +00003220 **
danielk19771d461462009-04-21 09:02:45 +00003221 ** Then, for each indexed term, the following. The arguments to
drh1b26c7c2009-04-22 02:15:47 +00003222 ** RowSetTest are such that the rowid of the current row is inserted
3223 ** into the RowSet. If it is already present, control skips the
danielk19771d461462009-04-21 09:02:45 +00003224 ** Gosub opcode and jumps straight to the code generated by WhereEnd().
drh111a6a72008-12-21 03:51:16 +00003225 **
danielk19771d461462009-04-21 09:02:45 +00003226 ** sqlite3WhereBegin(<term>)
drh1b26c7c2009-04-22 02:15:47 +00003227 ** RowSetTest # Insert rowid into rowset
danielk19771d461462009-04-21 09:02:45 +00003228 ** Gosub 2 A
3229 ** sqlite3WhereEnd()
3230 **
3231 ** Following the above, code to terminate the loop. Label A, the target
3232 ** of the Gosub above, jumps to the instruction right after the Goto.
3233 **
drh1b26c7c2009-04-22 02:15:47 +00003234 ** Null 1 # Zero the rowset in reg 1
danielk19771d461462009-04-21 09:02:45 +00003235 ** Goto B # The loop is finished.
3236 **
3237 ** A: <loop body> # Return data, whatever.
3238 **
3239 ** Return 2 # Jump back to the Gosub
3240 **
3241 ** B: <after the loop>
3242 **
drh111a6a72008-12-21 03:51:16 +00003243 */
drh111a6a72008-12-21 03:51:16 +00003244 WhereClause *pOrWc; /* The OR-clause broken out into subterms */
drhc01a3c12009-12-16 22:10:49 +00003245 SrcList *pOrTab; /* Shortened table list or OR-clause generation */
dan0efb72c2012-08-24 18:44:56 +00003246 Index *pCov = 0; /* Potential covering index (or NULL) */
3247 int iCovCur = pParse->nTab++; /* Cursor used for index scans (if any) */
danielk19771d461462009-04-21 09:02:45 +00003248
3249 int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */
shane85095702009-06-15 16:27:08 +00003250 int regRowset = 0; /* Register for RowSet object */
3251 int regRowid = 0; /* Register holding rowid */
danielk19771d461462009-04-21 09:02:45 +00003252 int iLoopBody = sqlite3VdbeMakeLabel(v); /* Start of loop body */
3253 int iRetInit; /* Address of regReturn init */
drhc01a3c12009-12-16 22:10:49 +00003254 int untestedTerms = 0; /* Some terms not completely tested */
drh8871ef52011-10-07 13:33:10 +00003255 int ii; /* Loop counter */
3256 Expr *pAndExpr = 0; /* An ".. AND (...)" expression */
drh111a6a72008-12-21 03:51:16 +00003257
drh4efc9292013-06-06 23:02:03 +00003258 pTerm = pLoop->aLTerm[0];
drh111a6a72008-12-21 03:51:16 +00003259 assert( pTerm!=0 );
drh7a5bcc02013-01-16 17:08:58 +00003260 assert( pTerm->eOperator & WO_OR );
drh111a6a72008-12-21 03:51:16 +00003261 assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
3262 pOrWc = &pTerm->u.pOrInfo->wc;
drhc01a3c12009-12-16 22:10:49 +00003263 pLevel->op = OP_Return;
3264 pLevel->p1 = regReturn;
drh23d04d52008-12-23 23:56:22 +00003265
danbfca6a42012-08-24 10:52:35 +00003266 /* Set up a new SrcList in pOrTab containing the table being scanned
drhc01a3c12009-12-16 22:10:49 +00003267 ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
3268 ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
3269 */
3270 if( pWInfo->nLevel>1 ){
3271 int nNotReady; /* The number of notReady tables */
3272 struct SrcList_item *origSrc; /* Original list of tables */
3273 nNotReady = pWInfo->nLevel - iLevel - 1;
drh6b36e822013-07-30 15:10:32 +00003274 pOrTab = sqlite3StackAllocRaw(db,
drhc01a3c12009-12-16 22:10:49 +00003275 sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
3276 if( pOrTab==0 ) return notReady;
drhad01d892013-06-19 13:59:49 +00003277 pOrTab->nAlloc = (u8)(nNotReady + 1);
shaneh46aae3c2009-12-31 19:06:23 +00003278 pOrTab->nSrc = pOrTab->nAlloc;
drhc01a3c12009-12-16 22:10:49 +00003279 memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
3280 origSrc = pWInfo->pTabList->a;
3281 for(k=1; k<=nNotReady; k++){
3282 memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
3283 }
3284 }else{
3285 pOrTab = pWInfo->pTabList;
3286 }
danielk19771d461462009-04-21 09:02:45 +00003287
drh1b26c7c2009-04-22 02:15:47 +00003288 /* Initialize the rowset register to contain NULL. An SQL NULL is
3289 ** equivalent to an empty rowset.
danielk19771d461462009-04-21 09:02:45 +00003290 **
3291 ** Also initialize regReturn to contain the address of the instruction
3292 ** immediately following the OP_Return at the bottom of the loop. This
3293 ** is required in a few obscure LEFT JOIN cases where control jumps
3294 ** over the top of the loop into the body of it. In this case the
3295 ** correct response for the end-of-loop code (the OP_Return) is to
3296 ** fall through to the next instruction, just as an OP_Next does if
3297 ** called on an uninitialized cursor.
3298 */
drh70d18342013-06-06 19:16:33 +00003299 if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
drh336a5302009-04-24 15:46:21 +00003300 regRowset = ++pParse->nMem;
3301 regRowid = ++pParse->nMem;
3302 sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
3303 }
danielk19771d461462009-04-21 09:02:45 +00003304 iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
3305
drh8871ef52011-10-07 13:33:10 +00003306 /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y
3307 ** Then for every term xN, evaluate as the subexpression: xN AND z
3308 ** That way, terms in y that are factored into the disjunction will
3309 ** be picked up by the recursive calls to sqlite3WhereBegin() below.
drh331b67c2012-03-09 22:02:08 +00003310 **
3311 ** Actually, each subexpression is converted to "xN AND w" where w is
3312 ** the "interesting" terms of z - terms that did not originate in the
3313 ** ON or USING clause of a LEFT JOIN, and terms that are usable as
3314 ** indices.
drhb3129fa2013-05-09 14:20:11 +00003315 **
3316 ** This optimization also only applies if the (x1 OR x2 OR ...) term
3317 ** is not contained in the ON clause of a LEFT JOIN.
3318 ** See ticket http://www.sqlite.org/src/info/f2369304e4
drh8871ef52011-10-07 13:33:10 +00003319 */
3320 if( pWC->nTerm>1 ){
drh7a484802012-03-16 00:28:11 +00003321 int iTerm;
3322 for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
3323 Expr *pExpr = pWC->a[iTerm].pExpr;
drhaa32e3c2013-07-16 21:31:23 +00003324 if( &pWC->a[iTerm] == pTerm ) continue;
drh331b67c2012-03-09 22:02:08 +00003325 if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
drh7c328062014-02-11 01:50:29 +00003326 testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO );
3327 testcase( pWC->a[iTerm].wtFlags & TERM_VIRTUAL );
3328 if( pWC->a[iTerm].wtFlags & (TERM_ORINFO|TERM_VIRTUAL) ) continue;
drh7a484802012-03-16 00:28:11 +00003329 if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
drh6b36e822013-07-30 15:10:32 +00003330 pExpr = sqlite3ExprDup(db, pExpr, 0);
3331 pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr);
drh331b67c2012-03-09 22:02:08 +00003332 }
3333 if( pAndExpr ){
3334 pAndExpr = sqlite3PExpr(pParse, TK_AND, 0, pAndExpr, 0);
3335 }
drh8871ef52011-10-07 13:33:10 +00003336 }
3337
danielk19771d461462009-04-21 09:02:45 +00003338 for(ii=0; ii<pOrWc->nTerm; ii++){
3339 WhereTerm *pOrTerm = &pOrWc->a[ii];
drh7a5bcc02013-01-16 17:08:58 +00003340 if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
danielk19771d461462009-04-21 09:02:45 +00003341 WhereInfo *pSubWInfo; /* Info for single OR-term scan */
drh8871ef52011-10-07 13:33:10 +00003342 Expr *pOrExpr = pOrTerm->pExpr;
drhb3129fa2013-05-09 14:20:11 +00003343 if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){
drh8871ef52011-10-07 13:33:10 +00003344 pAndExpr->pLeft = pOrExpr;
3345 pOrExpr = pAndExpr;
3346 }
danielk19771d461462009-04-21 09:02:45 +00003347 /* Loop through table entries that match term pOrTerm. */
drh8871ef52011-10-07 13:33:10 +00003348 pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
drh9ef61f42011-10-07 14:40:59 +00003349 WHERE_OMIT_OPEN_CLOSE | WHERE_AND_ONLY |
dan0efb72c2012-08-24 18:44:56 +00003350 WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY, iCovCur);
drh6b36e822013-07-30 15:10:32 +00003351 assert( pSubWInfo || pParse->nErr || db->mallocFailed );
danielk19771d461462009-04-21 09:02:45 +00003352 if( pSubWInfo ){
drh7ba39a92013-05-30 17:43:19 +00003353 WhereLoop *pSubLoop;
dan17c0bc02010-11-09 17:35:19 +00003354 explainOneScan(
dan4a07e3d2010-11-09 14:48:59 +00003355 pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
dan2ce22452010-11-08 19:01:16 +00003356 );
drh70d18342013-06-06 19:16:33 +00003357 if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
drh336a5302009-04-24 15:46:21 +00003358 int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
3359 int r;
3360 r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur,
drha748fdc2012-03-28 01:34:47 +00003361 regRowid, 0);
drh8cff69d2009-11-12 19:59:44 +00003362 sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset,
3363 sqlite3VdbeCurrentAddr(v)+2, r, iSet);
drh688852a2014-02-17 22:40:43 +00003364 VdbeCoverage(v);
drh336a5302009-04-24 15:46:21 +00003365 }
danielk19771d461462009-04-21 09:02:45 +00003366 sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
3367
drhc01a3c12009-12-16 22:10:49 +00003368 /* The pSubWInfo->untestedTerms flag means that this OR term
3369 ** contained one or more AND term from a notReady table. The
3370 ** terms from the notReady table could not be tested and will
3371 ** need to be tested later.
3372 */
3373 if( pSubWInfo->untestedTerms ) untestedTerms = 1;
3374
danbfca6a42012-08-24 10:52:35 +00003375 /* If all of the OR-connected terms are optimized using the same
3376 ** index, and the index is opened using the same cursor number
3377 ** by each call to sqlite3WhereBegin() made by this loop, it may
3378 ** be possible to use that index as a covering index.
3379 **
3380 ** If the call to sqlite3WhereBegin() above resulted in a scan that
3381 ** uses an index, and this is either the first OR-connected term
3382 ** processed or the index is the same as that used by all previous
dan0efb72c2012-08-24 18:44:56 +00003383 ** terms, set pCov to the candidate covering index. Otherwise, set
3384 ** pCov to NULL to indicate that no candidate covering index will
3385 ** be available.
danbfca6a42012-08-24 10:52:35 +00003386 */
drh7ba39a92013-05-30 17:43:19 +00003387 pSubLoop = pSubWInfo->a[0].pWLoop;
drh986b3872013-06-28 21:12:20 +00003388 assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
drh7ba39a92013-05-30 17:43:19 +00003389 if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
drh7ba39a92013-05-30 17:43:19 +00003390 && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
danbfca6a42012-08-24 10:52:35 +00003391 ){
drh7ba39a92013-05-30 17:43:19 +00003392 assert( pSubWInfo->a[0].iIdxCur==iCovCur );
drh907717f2013-06-04 18:03:22 +00003393 pCov = pSubLoop->u.btree.pIndex;
danbfca6a42012-08-24 10:52:35 +00003394 }else{
3395 pCov = 0;
3396 }
3397
danielk19771d461462009-04-21 09:02:45 +00003398 /* Finish the loop through table entries that match term pOrTerm. */
3399 sqlite3WhereEnd(pSubWInfo);
3400 }
drhdd5f5a62008-12-23 13:35:23 +00003401 }
3402 }
drhd40e2082012-08-24 23:24:15 +00003403 pLevel->u.pCovidx = pCov;
drh90abfd02012-10-09 21:07:23 +00003404 if( pCov ) pLevel->iIdxCur = iCovCur;
drh331b67c2012-03-09 22:02:08 +00003405 if( pAndExpr ){
3406 pAndExpr->pLeft = 0;
drh6b36e822013-07-30 15:10:32 +00003407 sqlite3ExprDelete(db, pAndExpr);
drh331b67c2012-03-09 22:02:08 +00003408 }
danielk19771d461462009-04-21 09:02:45 +00003409 sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
danielk19771d461462009-04-21 09:02:45 +00003410 sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
3411 sqlite3VdbeResolveLabel(v, iLoopBody);
3412
drh6b36e822013-07-30 15:10:32 +00003413 if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab);
drhc01a3c12009-12-16 22:10:49 +00003414 if( !untestedTerms ) disableTerm(pLevel, pTerm);
drhdd5f5a62008-12-23 13:35:23 +00003415 }else
drh23d04d52008-12-23 23:56:22 +00003416#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
drhdd5f5a62008-12-23 13:35:23 +00003417
3418 {
drh7ba39a92013-05-30 17:43:19 +00003419 /* Case 6: There is no usable index. We must do a complete
drh111a6a72008-12-21 03:51:16 +00003420 ** scan of the entire table.
3421 */
drh699b3d42009-02-23 16:52:07 +00003422 static const u8 aStep[] = { OP_Next, OP_Prev };
3423 static const u8 aStart[] = { OP_Rewind, OP_Last };
3424 assert( bRev==0 || bRev==1 );
drhe73f0592014-01-21 22:25:45 +00003425 if( pTabItem->isRecursive ){
drh340309f2014-01-22 00:23:49 +00003426 /* Tables marked isRecursive have only a single row that is stored in
dan41028152014-01-22 10:22:25 +00003427 ** a pseudo-cursor. No need to Rewind or Next such cursors. */
drhe73f0592014-01-21 22:25:45 +00003428 pLevel->op = OP_Noop;
3429 }else{
3430 pLevel->op = aStep[bRev];
3431 pLevel->p1 = iCur;
3432 pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
drh688852a2014-02-17 22:40:43 +00003433 VdbeCoverageIf(v, bRev);
3434 VdbeCoverageIf(v, !bRev);
drhe73f0592014-01-21 22:25:45 +00003435 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
3436 }
drh111a6a72008-12-21 03:51:16 +00003437 }
drh111a6a72008-12-21 03:51:16 +00003438
3439 /* Insert code to test every subexpression that can be completely
3440 ** computed using the current set of tables.
3441 */
drh111a6a72008-12-21 03:51:16 +00003442 for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
3443 Expr *pE;
drh39759742013-08-02 23:40:45 +00003444 testcase( pTerm->wtFlags & TERM_VIRTUAL );
drh111a6a72008-12-21 03:51:16 +00003445 testcase( pTerm->wtFlags & TERM_CODED );
3446 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
drh0259bc32013-09-09 19:37:46 +00003447 if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
drhc01a3c12009-12-16 22:10:49 +00003448 testcase( pWInfo->untestedTerms==0
3449 && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
3450 pWInfo->untestedTerms = 1;
3451 continue;
3452 }
drh111a6a72008-12-21 03:51:16 +00003453 pE = pTerm->pExpr;
3454 assert( pE!=0 );
3455 if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
3456 continue;
3457 }
drh111a6a72008-12-21 03:51:16 +00003458 sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
drh111a6a72008-12-21 03:51:16 +00003459 pTerm->wtFlags |= TERM_CODED;
3460 }
3461
drh0c41d222013-04-22 02:39:10 +00003462 /* Insert code to test for implied constraints based on transitivity
3463 ** of the "==" operator.
3464 **
3465 ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
3466 ** and we are coding the t1 loop and the t2 loop has not yet coded,
3467 ** then we cannot use the "t1.a=t2.b" constraint, but we can code
3468 ** the implied "t1.a=123" constraint.
3469 */
3470 for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
drh6b36e822013-07-30 15:10:32 +00003471 Expr *pE, *pEAlt;
drh0c41d222013-04-22 02:39:10 +00003472 WhereTerm *pAlt;
drh0c41d222013-04-22 02:39:10 +00003473 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
3474 if( pTerm->eOperator!=(WO_EQUIV|WO_EQ) ) continue;
3475 if( pTerm->leftCursor!=iCur ) continue;
drhcdc2e432013-07-01 17:27:19 +00003476 if( pLevel->iLeftJoin ) continue;
drh0c41d222013-04-22 02:39:10 +00003477 pE = pTerm->pExpr;
3478 assert( !ExprHasProperty(pE, EP_FromJoin) );
drh0259bc32013-09-09 19:37:46 +00003479 assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
drh0c41d222013-04-22 02:39:10 +00003480 pAlt = findTerm(pWC, iCur, pTerm->u.leftColumn, notReady, WO_EQ|WO_IN, 0);
3481 if( pAlt==0 ) continue;
drh5c10f3b2013-05-01 17:22:38 +00003482 if( pAlt->wtFlags & (TERM_CODED) ) continue;
drh7963b0e2013-06-17 21:37:40 +00003483 testcase( pAlt->eOperator & WO_EQ );
3484 testcase( pAlt->eOperator & WO_IN );
drh6bc69a22013-11-19 12:33:23 +00003485 VdbeModuleComment((v, "begin transitive constraint"));
drh6b36e822013-07-30 15:10:32 +00003486 pEAlt = sqlite3StackAllocRaw(db, sizeof(*pEAlt));
3487 if( pEAlt ){
3488 *pEAlt = *pAlt->pExpr;
3489 pEAlt->pLeft = pE->pLeft;
3490 sqlite3ExprIfFalse(pParse, pEAlt, addrCont, SQLITE_JUMPIFNULL);
3491 sqlite3StackFree(db, pEAlt);
3492 }
drh0c41d222013-04-22 02:39:10 +00003493 }
3494
drh111a6a72008-12-21 03:51:16 +00003495 /* For a LEFT OUTER JOIN, generate code that will record the fact that
3496 ** at least one row of the right table has matched the left table.
3497 */
3498 if( pLevel->iLeftJoin ){
3499 pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
3500 sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
3501 VdbeComment((v, "record LEFT JOIN hit"));
drhceea3322009-04-23 13:22:42 +00003502 sqlite3ExprCacheClear(pParse);
drh111a6a72008-12-21 03:51:16 +00003503 for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
drh39759742013-08-02 23:40:45 +00003504 testcase( pTerm->wtFlags & TERM_VIRTUAL );
drh111a6a72008-12-21 03:51:16 +00003505 testcase( pTerm->wtFlags & TERM_CODED );
3506 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
drh0259bc32013-09-09 19:37:46 +00003507 if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
drhb057e562009-12-16 23:43:55 +00003508 assert( pWInfo->untestedTerms );
drhc01a3c12009-12-16 22:10:49 +00003509 continue;
3510 }
drh111a6a72008-12-21 03:51:16 +00003511 assert( pTerm->pExpr );
3512 sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
3513 pTerm->wtFlags |= TERM_CODED;
3514 }
3515 }
danielk19771d461462009-04-21 09:02:45 +00003516 sqlite3ReleaseTempReg(pParse, iReleaseReg);
drh23d04d52008-12-23 23:56:22 +00003517
drh0259bc32013-09-09 19:37:46 +00003518 return pLevel->notReady;
drh111a6a72008-12-21 03:51:16 +00003519}
3520
drhf4e9cb02013-10-28 19:59:59 +00003521#if defined(WHERETRACE_ENABLED) && defined(SQLITE_ENABLE_TREE_EXPLAIN)
3522/*
3523** Generate "Explanation" text for a WhereTerm.
3524*/
3525static void whereExplainTerm(Vdbe *v, WhereTerm *pTerm){
3526 char zType[4];
3527 memcpy(zType, "...", 4);
3528 if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V';
3529 if( pTerm->eOperator & WO_EQUIV ) zType[1] = 'E';
3530 if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) zType[2] = 'L';
3531 sqlite3ExplainPrintf(v, "%s ", zType);
drhf4e9cb02013-10-28 19:59:59 +00003532 sqlite3ExplainExpr(v, pTerm->pExpr);
3533}
3534#endif /* WHERETRACE_ENABLED && SQLITE_ENABLE_TREE_EXPLAIN */
3535
3536
drhd15cb172013-05-21 19:23:10 +00003537#ifdef WHERETRACE_ENABLED
drha18f3d22013-05-08 03:05:41 +00003538/*
3539** Print a WhereLoop object for debugging purposes
3540*/
drhc1ba2e72013-10-28 19:03:21 +00003541static void whereLoopPrint(WhereLoop *p, WhereClause *pWC){
3542 WhereInfo *pWInfo = pWC->pWInfo;
drh989578e2013-10-28 14:34:35 +00003543 int nb = 1+(pWInfo->pTabList->nSrc+7)/8;
3544 struct SrcList_item *pItem = pWInfo->pTabList->a + p->iTab;
drha18f3d22013-05-08 03:05:41 +00003545 Table *pTab = pItem->pTab;
drh6457a352013-06-21 00:35:37 +00003546 sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
drha184fb82013-05-08 04:22:59 +00003547 p->iTab, nb, p->maskSelf, nb, p->prereq);
drh6457a352013-06-21 00:35:37 +00003548 sqlite3DebugPrintf(" %12s",
drha18f3d22013-05-08 03:05:41 +00003549 pItem->zAlias ? pItem->zAlias : pTab->zName);
drh5346e952013-05-08 14:14:26 +00003550 if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
drhc1ba2e72013-10-28 19:03:21 +00003551 const char *zName;
3552 if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){
drh319f6772013-05-14 15:31:07 +00003553 if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
3554 int i = sqlite3Strlen30(zName) - 1;
3555 while( zName[i]!='_' ) i--;
3556 zName += i;
3557 }
drh6457a352013-06-21 00:35:37 +00003558 sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq);
drh5346e952013-05-08 14:14:26 +00003559 }else{
drh6457a352013-06-21 00:35:37 +00003560 sqlite3DebugPrintf("%20s","");
drh5346e952013-05-08 14:14:26 +00003561 }
drha18f3d22013-05-08 03:05:41 +00003562 }else{
drh5346e952013-05-08 14:14:26 +00003563 char *z;
3564 if( p->u.vtab.idxStr ){
drh3bd26f02013-05-24 14:52:03 +00003565 z = sqlite3_mprintf("(%d,\"%s\",%x)",
3566 p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
drh5346e952013-05-08 14:14:26 +00003567 }else{
drh3bd26f02013-05-24 14:52:03 +00003568 z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
drh5346e952013-05-08 14:14:26 +00003569 }
drh6457a352013-06-21 00:35:37 +00003570 sqlite3DebugPrintf(" %-19s", z);
drh5346e952013-05-08 14:14:26 +00003571 sqlite3_free(z);
drha18f3d22013-05-08 03:05:41 +00003572 }
drh6457a352013-06-21 00:35:37 +00003573 sqlite3DebugPrintf(" f %04x N %d", p->wsFlags, p->nLTerm);
drhb8a8e8a2013-06-10 19:12:39 +00003574 sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
drh989578e2013-10-28 14:34:35 +00003575#ifdef SQLITE_ENABLE_TREE_EXPLAIN
3576 /* If the 0x100 bit of wheretracing is set, then show all of the constraint
3577 ** expressions in the WhereLoop.aLTerm[] array.
3578 */
3579 if( p->nLTerm && (sqlite3WhereTrace & 0x100)!=0 ){ /* WHERETRACE 0x100 */
3580 int i;
3581 Vdbe *v = pWInfo->pParse->pVdbe;
3582 sqlite3ExplainBegin(v);
3583 for(i=0; i<p->nLTerm; i++){
drhc1ba2e72013-10-28 19:03:21 +00003584 WhereTerm *pTerm = p->aLTerm[i];
drhcd8629e2013-11-13 12:27:25 +00003585 if( pTerm==0 ) continue;
drh7afc8b02013-10-28 22:33:36 +00003586 sqlite3ExplainPrintf(v, " (%d) #%-2d ", i+1, (int)(pTerm-pWC->a));
drh989578e2013-10-28 14:34:35 +00003587 sqlite3ExplainPush(v);
drhf4e9cb02013-10-28 19:59:59 +00003588 whereExplainTerm(v, pTerm);
drh989578e2013-10-28 14:34:35 +00003589 sqlite3ExplainPop(v);
3590 sqlite3ExplainNL(v);
3591 }
drh989578e2013-10-28 14:34:35 +00003592 sqlite3ExplainFinish(v);
drhc1ba2e72013-10-28 19:03:21 +00003593 sqlite3DebugPrintf("%s", sqlite3VdbeExplanation(v));
drh989578e2013-10-28 14:34:35 +00003594 }
3595#endif
drha18f3d22013-05-08 03:05:41 +00003596}
3597#endif
3598
drhf1b5f5b2013-05-02 00:15:01 +00003599/*
drh4efc9292013-06-06 23:02:03 +00003600** Convert bulk memory into a valid WhereLoop that can be passed
3601** to whereLoopClear harmlessly.
drh5346e952013-05-08 14:14:26 +00003602*/
drh4efc9292013-06-06 23:02:03 +00003603static void whereLoopInit(WhereLoop *p){
3604 p->aLTerm = p->aLTermSpace;
3605 p->nLTerm = 0;
3606 p->nLSlot = ArraySize(p->aLTermSpace);
3607 p->wsFlags = 0;
3608}
3609
3610/*
3611** Clear the WhereLoop.u union. Leave WhereLoop.pLTerm intact.
3612*/
3613static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
drh986b3872013-06-28 21:12:20 +00003614 if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){
drh13e11b42013-06-06 23:44:25 +00003615 if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
3616 sqlite3_free(p->u.vtab.idxStr);
3617 p->u.vtab.needFree = 0;
3618 p->u.vtab.idxStr = 0;
drh986b3872013-06-28 21:12:20 +00003619 }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){
drh13e11b42013-06-06 23:44:25 +00003620 sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
drh2ec2fb22013-11-06 19:59:23 +00003621 sqlite3KeyInfoUnref(p->u.btree.pIndex->pKeyInfo);
drh13e11b42013-06-06 23:44:25 +00003622 sqlite3DbFree(db, p->u.btree.pIndex);
3623 p->u.btree.pIndex = 0;
3624 }
drh5346e952013-05-08 14:14:26 +00003625 }
3626}
3627
drh4efc9292013-06-06 23:02:03 +00003628/*
3629** Deallocate internal memory used by a WhereLoop object
3630*/
3631static void whereLoopClear(sqlite3 *db, WhereLoop *p){
3632 if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
3633 whereLoopClearUnion(db, p);
3634 whereLoopInit(p);
3635}
3636
3637/*
3638** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
3639*/
3640static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
3641 WhereTerm **paNew;
3642 if( p->nLSlot>=n ) return SQLITE_OK;
3643 n = (n+7)&~7;
3644 paNew = sqlite3DbMallocRaw(db, sizeof(p->aLTerm[0])*n);
3645 if( paNew==0 ) return SQLITE_NOMEM;
3646 memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
3647 if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
3648 p->aLTerm = paNew;
3649 p->nLSlot = n;
3650 return SQLITE_OK;
3651}
3652
3653/*
3654** Transfer content from the second pLoop into the first.
3655*/
3656static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
drh4efc9292013-06-06 23:02:03 +00003657 whereLoopClearUnion(db, pTo);
drh0d31dc32013-09-06 00:40:59 +00003658 if( whereLoopResize(db, pTo, pFrom->nLTerm) ){
3659 memset(&pTo->u, 0, sizeof(pTo->u));
3660 return SQLITE_NOMEM;
3661 }
drha2014152013-06-07 00:29:23 +00003662 memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
3663 memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
drh4efc9292013-06-06 23:02:03 +00003664 if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
3665 pFrom->u.vtab.needFree = 0;
drh986b3872013-06-28 21:12:20 +00003666 }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){
drh4efc9292013-06-06 23:02:03 +00003667 pFrom->u.btree.pIndex = 0;
3668 }
3669 return SQLITE_OK;
3670}
3671
drh5346e952013-05-08 14:14:26 +00003672/*
drhf1b5f5b2013-05-02 00:15:01 +00003673** Delete a WhereLoop object
3674*/
3675static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
drh5346e952013-05-08 14:14:26 +00003676 whereLoopClear(db, p);
drhf1b5f5b2013-05-02 00:15:01 +00003677 sqlite3DbFree(db, p);
3678}
drh84bfda42005-07-15 13:05:21 +00003679
drh9eff6162006-06-12 21:59:13 +00003680/*
3681** Free a WhereInfo structure
3682*/
drh10fe8402008-10-11 16:47:35 +00003683static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
drh52ff8ea2010-04-08 14:15:56 +00003684 if( ALWAYS(pWInfo) ){
drh70d18342013-06-06 19:16:33 +00003685 whereClauseClear(&pWInfo->sWC);
drhf1b5f5b2013-05-02 00:15:01 +00003686 while( pWInfo->pLoops ){
3687 WhereLoop *p = pWInfo->pLoops;
3688 pWInfo->pLoops = p->pNextLoop;
3689 whereLoopDelete(db, p);
3690 }
drh633e6d52008-07-28 19:34:53 +00003691 sqlite3DbFree(db, pWInfo);
drh9eff6162006-06-12 21:59:13 +00003692 }
3693}
3694
drhf1b5f5b2013-05-02 00:15:01 +00003695/*
3696** Insert or replace a WhereLoop entry using the template supplied.
3697**
3698** An existing WhereLoop entry might be overwritten if the new template
3699** is better and has fewer dependencies. Or the template will be ignored
3700** and no insert will occur if an existing WhereLoop is faster and has
3701** fewer dependencies than the template. Otherwise a new WhereLoop is
drhd044d202013-05-31 12:43:55 +00003702** added based on the template.
drh23f98da2013-05-21 15:52:07 +00003703**
drhaa32e3c2013-07-16 21:31:23 +00003704** If pBuilder->pOrSet is not NULL then we only care about only the
3705** prerequisites and rRun and nOut costs of the N best loops. That
3706** information is gathered in the pBuilder->pOrSet object. This special
3707** processing mode is used only for OR clause processing.
drh23f98da2013-05-21 15:52:07 +00003708**
drhaa32e3c2013-07-16 21:31:23 +00003709** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
drh23f98da2013-05-21 15:52:07 +00003710** still might overwrite similar loops with the new template if the
3711** template is better. Loops may be overwritten if the following
3712** conditions are met:
3713**
3714** (1) They have the same iTab.
3715** (2) They have the same iSortIdx.
3716** (3) The template has same or fewer dependencies than the current loop
3717** (4) The template has the same or lower cost than the current loop
drhd044d202013-05-31 12:43:55 +00003718** (5) The template uses more terms of the same index but has no additional
3719** dependencies
drhf1b5f5b2013-05-02 00:15:01 +00003720*/
drhcf8fa7a2013-05-10 20:26:22 +00003721static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
drh4efc9292013-06-06 23:02:03 +00003722 WhereLoop **ppPrev, *p, *pNext = 0;
drhcf8fa7a2013-05-10 20:26:22 +00003723 WhereInfo *pWInfo = pBuilder->pWInfo;
drh70d18342013-06-06 19:16:33 +00003724 sqlite3 *db = pWInfo->pParse->db;
drhcf8fa7a2013-05-10 20:26:22 +00003725
drhaa32e3c2013-07-16 21:31:23 +00003726 /* If pBuilder->pOrSet is defined, then only keep track of the costs
3727 ** and prereqs.
drh23f98da2013-05-21 15:52:07 +00003728 */
drhaa32e3c2013-07-16 21:31:23 +00003729 if( pBuilder->pOrSet!=0 ){
3730#if WHERETRACE_ENABLED
3731 u16 n = pBuilder->pOrSet->n;
3732 int x =
3733#endif
3734 whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
3735 pTemplate->nOut);
drh989578e2013-10-28 14:34:35 +00003736#if WHERETRACE_ENABLED /* 0x8 */
drhae70cf12013-05-31 15:18:46 +00003737 if( sqlite3WhereTrace & 0x8 ){
drhaa32e3c2013-07-16 21:31:23 +00003738 sqlite3DebugPrintf(x?" or-%d: ":" or-X: ", n);
drhc1ba2e72013-10-28 19:03:21 +00003739 whereLoopPrint(pTemplate, pBuilder->pWC);
drhae70cf12013-05-31 15:18:46 +00003740 }
3741#endif
drhcf8fa7a2013-05-10 20:26:22 +00003742 return SQLITE_OK;
3743 }
drhf1b5f5b2013-05-02 00:15:01 +00003744
3745 /* Search for an existing WhereLoop to overwrite, or which takes
3746 ** priority over pTemplate.
3747 */
3748 for(ppPrev=&pWInfo->pLoops, p=*ppPrev; p; ppPrev=&p->pNextLoop, p=*ppPrev){
drhdbb80232013-06-19 12:34:13 +00003749 if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
3750 /* If either the iTab or iSortIdx values for two WhereLoop are different
3751 ** then those WhereLoops need to be considered separately. Neither is
3752 ** a candidate to replace the other. */
3753 continue;
3754 }
3755 /* In the current implementation, the rSetup value is either zero
3756 ** or the cost of building an automatic index (NlogN) and the NlogN
3757 ** is the same for compatible WhereLoops. */
3758 assert( p->rSetup==0 || pTemplate->rSetup==0
3759 || p->rSetup==pTemplate->rSetup );
3760
3761 /* whereLoopAddBtree() always generates and inserts the automatic index
3762 ** case first. Hence compatible candidate WhereLoops never have a larger
3763 ** rSetup. Call this SETUP-INVARIANT */
3764 assert( p->rSetup>=pTemplate->rSetup );
3765
drhf1b5f5b2013-05-02 00:15:01 +00003766 if( (p->prereq & pTemplate->prereq)==p->prereq
drhf1b5f5b2013-05-02 00:15:01 +00003767 && p->rSetup<=pTemplate->rSetup
3768 && p->rRun<=pTemplate->rRun
drhf46af732013-08-30 17:35:44 +00003769 && p->nOut<=pTemplate->nOut
drhf1b5f5b2013-05-02 00:15:01 +00003770 ){
drh4a5acf82013-06-18 20:06:23 +00003771 /* This branch taken when p is equal or better than pTemplate in
drhe56dd3a2013-08-30 17:50:35 +00003772 ** all of (1) dependencies (2) setup-cost, (3) run-cost, and
drhf46af732013-08-30 17:35:44 +00003773 ** (4) number of output rows. */
drhdbb80232013-06-19 12:34:13 +00003774 assert( p->rSetup==pTemplate->rSetup );
drh05db3c72013-09-02 20:22:18 +00003775 if( p->prereq==pTemplate->prereq
3776 && p->nLTerm<pTemplate->nLTerm
drhadd5ce32013-09-07 00:29:06 +00003777 && (p->wsFlags & pTemplate->wsFlags & WHERE_INDEXED)!=0
3778 && (p->u.btree.pIndex==pTemplate->u.btree.pIndex
drhabfa6d52013-09-11 03:53:22 +00003779 || pTemplate->rRun+p->nLTerm<=p->rRun+pTemplate->nLTerm)
drhcd0f4072013-06-05 12:47:59 +00003780 ){
3781 /* Overwrite an existing WhereLoop with an similar one that uses
3782 ** more terms of the index */
3783 pNext = p->pNextLoop;
drhcd0f4072013-06-05 12:47:59 +00003784 break;
3785 }else{
3786 /* pTemplate is not helpful.
3787 ** Return without changing or adding anything */
3788 goto whereLoopInsert_noop;
3789 }
drhf1b5f5b2013-05-02 00:15:01 +00003790 }
3791 if( (p->prereq & pTemplate->prereq)==pTemplate->prereq
drhf1b5f5b2013-05-02 00:15:01 +00003792 && p->rRun>=pTemplate->rRun
drhf46af732013-08-30 17:35:44 +00003793 && p->nOut>=pTemplate->nOut
drhf1b5f5b2013-05-02 00:15:01 +00003794 ){
drh4a5acf82013-06-18 20:06:23 +00003795 /* Overwrite an existing WhereLoop with a better one: one that is
drhe56dd3a2013-08-30 17:50:35 +00003796 ** better at one of (1) dependencies, (2) setup-cost, (3) run-cost
drhf46af732013-08-30 17:35:44 +00003797 ** or (4) number of output rows, and is no worse in any of those
3798 ** categories. */
drhadd5ce32013-09-07 00:29:06 +00003799 assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */
drh43fe25f2013-05-07 23:06:23 +00003800 pNext = p->pNextLoop;
drhf1b5f5b2013-05-02 00:15:01 +00003801 break;
3802 }
3803 }
3804
3805 /* If we reach this point it means that either p[] should be overwritten
3806 ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
3807 ** WhereLoop and insert it.
3808 */
drh989578e2013-10-28 14:34:35 +00003809#if WHERETRACE_ENABLED /* 0x8 */
drhae70cf12013-05-31 15:18:46 +00003810 if( sqlite3WhereTrace & 0x8 ){
3811 if( p!=0 ){
3812 sqlite3DebugPrintf("ins-del: ");
drhc1ba2e72013-10-28 19:03:21 +00003813 whereLoopPrint(p, pBuilder->pWC);
drhae70cf12013-05-31 15:18:46 +00003814 }
3815 sqlite3DebugPrintf("ins-new: ");
drhc1ba2e72013-10-28 19:03:21 +00003816 whereLoopPrint(pTemplate, pBuilder->pWC);
drhae70cf12013-05-31 15:18:46 +00003817 }
3818#endif
drhf1b5f5b2013-05-02 00:15:01 +00003819 if( p==0 ){
drh4efc9292013-06-06 23:02:03 +00003820 p = sqlite3DbMallocRaw(db, sizeof(WhereLoop));
drhf1b5f5b2013-05-02 00:15:01 +00003821 if( p==0 ) return SQLITE_NOMEM;
drh4efc9292013-06-06 23:02:03 +00003822 whereLoopInit(p);
drhf1b5f5b2013-05-02 00:15:01 +00003823 }
drh4efc9292013-06-06 23:02:03 +00003824 whereLoopXfer(db, p, pTemplate);
drh43fe25f2013-05-07 23:06:23 +00003825 p->pNextLoop = pNext;
3826 *ppPrev = p;
drh5346e952013-05-08 14:14:26 +00003827 if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
drhef866372013-05-22 20:49:02 +00003828 Index *pIndex = p->u.btree.pIndex;
3829 if( pIndex && pIndex->tnum==0 ){
drhcf8fa7a2013-05-10 20:26:22 +00003830 p->u.btree.pIndex = 0;
3831 }
drh5346e952013-05-08 14:14:26 +00003832 }
drhf1b5f5b2013-05-02 00:15:01 +00003833 return SQLITE_OK;
drhae70cf12013-05-31 15:18:46 +00003834
3835 /* Jump here if the insert is a no-op */
3836whereLoopInsert_noop:
drh989578e2013-10-28 14:34:35 +00003837#if WHERETRACE_ENABLED /* 0x8 */
drhae70cf12013-05-31 15:18:46 +00003838 if( sqlite3WhereTrace & 0x8 ){
drhaa32e3c2013-07-16 21:31:23 +00003839 sqlite3DebugPrintf("ins-noop: ");
drhc1ba2e72013-10-28 19:03:21 +00003840 whereLoopPrint(pTemplate, pBuilder->pWC);
drhae70cf12013-05-31 15:18:46 +00003841 }
3842#endif
3843 return SQLITE_OK;
drhf1b5f5b2013-05-02 00:15:01 +00003844}
3845
3846/*
drhcca9f3d2013-09-06 15:23:29 +00003847** Adjust the WhereLoop.nOut value downward to account for terms of the
3848** WHERE clause that reference the loop but which are not used by an
3849** index.
3850**
3851** In the current implementation, the first extra WHERE clause term reduces
3852** the number of output rows by a factor of 10 and each additional term
3853** reduces the number of output rows by sqrt(2).
3854*/
drh4f991892013-10-11 15:05:05 +00003855static void whereLoopOutputAdjust(WhereClause *pWC, WhereLoop *pLoop){
drh7d9e7d82013-09-11 17:39:09 +00003856 WhereTerm *pTerm, *pX;
drhcca9f3d2013-09-06 15:23:29 +00003857 Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf);
drh7d9e7d82013-09-11 17:39:09 +00003858 int i, j;
drhadd5ce32013-09-07 00:29:06 +00003859
3860 if( !OptimizationEnabled(pWC->pWInfo->pParse->db, SQLITE_AdjustOutEst) ){
3861 return;
3862 }
drhcca9f3d2013-09-06 15:23:29 +00003863 for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){
drh7d9e7d82013-09-11 17:39:09 +00003864 if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break;
drhcca9f3d2013-09-06 15:23:29 +00003865 if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;
3866 if( (pTerm->prereqAll & notAllowed)!=0 ) continue;
drh7d9e7d82013-09-11 17:39:09 +00003867 for(j=pLoop->nLTerm-1; j>=0; j--){
3868 pX = pLoop->aLTerm[j];
drhd2447442013-11-13 19:01:41 +00003869 if( pX==0 ) continue;
drh7d9e7d82013-09-11 17:39:09 +00003870 if( pX==pTerm ) break;
3871 if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break;
3872 }
3873 if( j<0 ) pLoop->nOut += pTerm->truthProb;
drhcca9f3d2013-09-06 15:23:29 +00003874 }
drhcca9f3d2013-09-06 15:23:29 +00003875}
3876
3877/*
drh5346e952013-05-08 14:14:26 +00003878** We have so far matched pBuilder->pNew->u.btree.nEq terms of the index pIndex.
drh1c8148f2013-05-04 20:25:23 +00003879** Try to match one more.
3880**
3881** If pProbe->tnum==0, that means pIndex is a fake index used for the
3882** INTEGER PRIMARY KEY.
3883*/
drh5346e952013-05-08 14:14:26 +00003884static int whereLoopAddBtreeIndex(
drh1c8148f2013-05-04 20:25:23 +00003885 WhereLoopBuilder *pBuilder, /* The WhereLoop factory */
3886 struct SrcList_item *pSrc, /* FROM clause term being analyzed */
3887 Index *pProbe, /* An index on pSrc */
drhbf539c42013-10-05 18:16:02 +00003888 LogEst nInMul /* log(Number of iterations due to IN) */
drh1c8148f2013-05-04 20:25:23 +00003889){
drh70d18342013-06-06 19:16:33 +00003890 WhereInfo *pWInfo = pBuilder->pWInfo; /* WHERE analyse context */
3891 Parse *pParse = pWInfo->pParse; /* Parsing context */
3892 sqlite3 *db = pParse->db; /* Database connection malloc context */
drh1c8148f2013-05-04 20:25:23 +00003893 WhereLoop *pNew; /* Template WhereLoop under construction */
3894 WhereTerm *pTerm; /* A WhereTerm under consideration */
drh43fe25f2013-05-07 23:06:23 +00003895 int opMask; /* Valid operators for constraints */
drh1c8148f2013-05-04 20:25:23 +00003896 WhereScan scan; /* Iterator for WHERE terms */
drh4efc9292013-06-06 23:02:03 +00003897 Bitmask saved_prereq; /* Original value of pNew->prereq */
3898 u16 saved_nLTerm; /* Original value of pNew->nLTerm */
drhcd8629e2013-11-13 12:27:25 +00003899 u16 saved_nEq; /* Original value of pNew->u.btree.nEq */
3900 u16 saved_nSkip; /* Original value of pNew->u.btree.nSkip */
drh4efc9292013-06-06 23:02:03 +00003901 u32 saved_wsFlags; /* Original value of pNew->wsFlags */
drhbf539c42013-10-05 18:16:02 +00003902 LogEst saved_nOut; /* Original value of pNew->nOut */
drha18f3d22013-05-08 03:05:41 +00003903 int iCol; /* Index of the column in the table */
drh5346e952013-05-08 14:14:26 +00003904 int rc = SQLITE_OK; /* Return code */
drhbf539c42013-10-05 18:16:02 +00003905 LogEst nRowEst; /* Estimated index selectivity */
3906 LogEst rLogSize; /* Logarithm of table size */
drhc7f0d222013-06-19 03:27:12 +00003907 WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
drh1c8148f2013-05-04 20:25:23 +00003908
drh1c8148f2013-05-04 20:25:23 +00003909 pNew = pBuilder->pNew;
drh5346e952013-05-08 14:14:26 +00003910 if( db->mallocFailed ) return SQLITE_NOMEM;
drh1c8148f2013-05-04 20:25:23 +00003911
drh5346e952013-05-08 14:14:26 +00003912 assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
drh43fe25f2013-05-07 23:06:23 +00003913 assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
3914 if( pNew->wsFlags & WHERE_BTM_LIMIT ){
3915 opMask = WO_LT|WO_LE;
3916 }else if( pProbe->tnum<=0 || (pSrc->jointype & JT_LEFT)!=0 ){
3917 opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE;
drh1c8148f2013-05-04 20:25:23 +00003918 }else{
drh43fe25f2013-05-07 23:06:23 +00003919 opMask = WO_EQ|WO_IN|WO_ISNULL|WO_GT|WO_GE|WO_LT|WO_LE;
drh1c8148f2013-05-04 20:25:23 +00003920 }
drhef866372013-05-22 20:49:02 +00003921 if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
drh1c8148f2013-05-04 20:25:23 +00003922
drhbbbdc832013-10-22 18:01:40 +00003923 assert( pNew->u.btree.nEq<=pProbe->nKeyCol );
3924 if( pNew->u.btree.nEq < pProbe->nKeyCol ){
drh0f133a42013-05-22 17:01:17 +00003925 iCol = pProbe->aiColumn[pNew->u.btree.nEq];
drhbf539c42013-10-05 18:16:02 +00003926 nRowEst = sqlite3LogEst(pProbe->aiRowEst[pNew->u.btree.nEq+1]);
drhc7f0d222013-06-19 03:27:12 +00003927 if( nRowEst==0 && pProbe->onError==OE_None ) nRowEst = 1;
drh0f133a42013-05-22 17:01:17 +00003928 }else{
3929 iCol = -1;
drhb8a8e8a2013-06-10 19:12:39 +00003930 nRowEst = 0;
drh0f133a42013-05-22 17:01:17 +00003931 }
drha18f3d22013-05-08 03:05:41 +00003932 pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, iCol,
drh0f133a42013-05-22 17:01:17 +00003933 opMask, pProbe);
drh4efc9292013-06-06 23:02:03 +00003934 saved_nEq = pNew->u.btree.nEq;
drhcd8629e2013-11-13 12:27:25 +00003935 saved_nSkip = pNew->u.btree.nSkip;
drh4efc9292013-06-06 23:02:03 +00003936 saved_nLTerm = pNew->nLTerm;
3937 saved_wsFlags = pNew->wsFlags;
3938 saved_prereq = pNew->prereq;
3939 saved_nOut = pNew->nOut;
drhb8a8e8a2013-06-10 19:12:39 +00003940 pNew->rSetup = 0;
drhbf539c42013-10-05 18:16:02 +00003941 rLogSize = estLog(sqlite3LogEst(pProbe->aiRowEst[0]));
drh64ff26f2013-11-18 19:32:15 +00003942
3943 /* Consider using a skip-scan if there are no WHERE clause constraints
3944 ** available for the left-most terms of the index, and if the average
drhc964c392013-11-27 04:22:27 +00003945 ** number of repeats in the left-most terms is at least 18. The magic
3946 ** number 18 was found by experimentation to be the payoff point where
3947 ** skip-scan become faster than a full-scan.
drh64ff26f2013-11-18 19:32:15 +00003948 */
drhcd8629e2013-11-13 12:27:25 +00003949 if( pTerm==0
3950 && saved_nEq==saved_nSkip
3951 && saved_nEq+1<pProbe->nKeyCol
drhc964c392013-11-27 04:22:27 +00003952 && pProbe->aiRowEst[saved_nEq+1]>=18 /* TUNING: Minimum for skip-scan */
drh6c1de302013-12-22 20:44:10 +00003953 && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK
drhcd8629e2013-11-13 12:27:25 +00003954 ){
drh2e5ef4e2013-11-13 16:58:54 +00003955 LogEst nIter;
drhcd8629e2013-11-13 12:27:25 +00003956 pNew->u.btree.nEq++;
3957 pNew->u.btree.nSkip++;
3958 pNew->aLTerm[pNew->nLTerm++] = 0;
drh2e5ef4e2013-11-13 16:58:54 +00003959 pNew->wsFlags |= WHERE_SKIPSCAN;
3960 nIter = sqlite3LogEst(pProbe->aiRowEst[0]/pProbe->aiRowEst[saved_nEq+1]);
3961 whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nIter);
drhcd8629e2013-11-13 12:27:25 +00003962 }
drh5346e952013-05-08 14:14:26 +00003963 for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
drhb8a8e8a2013-06-10 19:12:39 +00003964 int nIn = 0;
drh1435a9a2013-08-27 23:15:44 +00003965#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
dan7a419232013-08-06 20:01:43 +00003966 int nRecValid = pBuilder->nRecValid;
drhb5246e52013-07-08 21:12:57 +00003967#endif
dan8bff07a2013-08-29 14:56:14 +00003968 if( (pTerm->eOperator==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)
3969 && (iCol<0 || pSrc->pTab->aCol[iCol].notNull)
3970 ){
3971 continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */
3972 }
dan7a419232013-08-06 20:01:43 +00003973 if( pTerm->prereqRight & pNew->maskSelf ) continue;
3974
danad45ed72013-08-08 12:21:32 +00003975 assert( pNew->nOut==saved_nOut );
3976
drh4efc9292013-06-06 23:02:03 +00003977 pNew->wsFlags = saved_wsFlags;
3978 pNew->u.btree.nEq = saved_nEq;
3979 pNew->nLTerm = saved_nLTerm;
3980 if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
3981 pNew->aLTerm[pNew->nLTerm++] = pTerm;
3982 pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
drhe1e2e9a2013-06-13 15:16:53 +00003983 pNew->rRun = rLogSize; /* Baseline cost is log2(N). Adjustments below */
drha18f3d22013-05-08 03:05:41 +00003984 if( pTerm->eOperator & WO_IN ){
3985 Expr *pExpr = pTerm->pExpr;
3986 pNew->wsFlags |= WHERE_COLUMN_IN;
3987 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
drhe1e2e9a2013-06-13 15:16:53 +00003988 /* "x IN (SELECT ...)": TUNING: the SELECT returns 25 rows */
drhbf539c42013-10-05 18:16:02 +00003989 nIn = 46; assert( 46==sqlite3LogEst(25) );
drha18f3d22013-05-08 03:05:41 +00003990 }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
3991 /* "x IN (value, value, ...)" */
drhbf539c42013-10-05 18:16:02 +00003992 nIn = sqlite3LogEst(pExpr->x.pList->nExpr);
drhf1645f02013-05-07 19:44:38 +00003993 }
drhb8a8e8a2013-06-10 19:12:39 +00003994 pNew->rRun += nIn;
drh5346e952013-05-08 14:14:26 +00003995 pNew->u.btree.nEq++;
drhb8a8e8a2013-06-10 19:12:39 +00003996 pNew->nOut = nRowEst + nInMul + nIn;
drh6fa978d2013-05-30 19:29:19 +00003997 }else if( pTerm->eOperator & (WO_EQ) ){
drh2e5ef4e2013-11-13 16:58:54 +00003998 assert(
3999 (pNew->wsFlags & (WHERE_COLUMN_NULL|WHERE_COLUMN_IN|WHERE_SKIPSCAN))!=0
4000 || nInMul==0
4001 );
drha18f3d22013-05-08 03:05:41 +00004002 pNew->wsFlags |= WHERE_COLUMN_EQ;
drhe39a7322014-02-03 14:04:11 +00004003 if( iCol<0 || (nInMul==0 && pNew->u.btree.nEq==pProbe->nKeyCol-1)){
drh4a5acf82013-06-18 20:06:23 +00004004 assert( (pNew->wsFlags & WHERE_COLUMN_IN)==0 || iCol<0 );
drhe39a7322014-02-03 14:04:11 +00004005 if( iCol>=0 && pProbe->onError==OE_None ){
4006 pNew->wsFlags |= WHERE_UNQ_WANTED;
4007 }else{
4008 pNew->wsFlags |= WHERE_ONEROW;
4009 }
drh21f7ff72013-06-03 15:07:23 +00004010 }
drh5346e952013-05-08 14:14:26 +00004011 pNew->u.btree.nEq++;
drhb8a8e8a2013-06-10 19:12:39 +00004012 pNew->nOut = nRowEst + nInMul;
drh6fa978d2013-05-30 19:29:19 +00004013 }else if( pTerm->eOperator & (WO_ISNULL) ){
4014 pNew->wsFlags |= WHERE_COLUMN_NULL;
4015 pNew->u.btree.nEq++;
drhe1e2e9a2013-06-13 15:16:53 +00004016 /* TUNING: IS NULL selects 2 rows */
drhbf539c42013-10-05 18:16:02 +00004017 nIn = 10; assert( 10==sqlite3LogEst(2) );
drhb8a8e8a2013-06-10 19:12:39 +00004018 pNew->nOut = nRowEst + nInMul + nIn;
drha18f3d22013-05-08 03:05:41 +00004019 }else if( pTerm->eOperator & (WO_GT|WO_GE) ){
drh7963b0e2013-06-17 21:37:40 +00004020 testcase( pTerm->eOperator & WO_GT );
4021 testcase( pTerm->eOperator & WO_GE );
drha18f3d22013-05-08 03:05:41 +00004022 pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
drh6f2bfad2013-06-03 17:35:22 +00004023 pBtm = pTerm;
4024 pTop = 0;
drh7963b0e2013-06-17 21:37:40 +00004025 }else{
4026 assert( pTerm->eOperator & (WO_LT|WO_LE) );
4027 testcase( pTerm->eOperator & WO_LT );
4028 testcase( pTerm->eOperator & WO_LE );
drha18f3d22013-05-08 03:05:41 +00004029 pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
drh6f2bfad2013-06-03 17:35:22 +00004030 pTop = pTerm;
4031 pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
drh4efc9292013-06-06 23:02:03 +00004032 pNew->aLTerm[pNew->nLTerm-2] : 0;
drh1c8148f2013-05-04 20:25:23 +00004033 }
drh6f2bfad2013-06-03 17:35:22 +00004034 if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
4035 /* Adjust nOut and rRun for STAT3 range values */
dan6cb8d762013-08-08 11:48:57 +00004036 assert( pNew->nOut==saved_nOut );
drh186ad8c2013-10-08 18:40:37 +00004037 whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew);
drh6f2bfad2013-06-03 17:35:22 +00004038 }
drh1435a9a2013-08-27 23:15:44 +00004039#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
dan8ad169a2013-08-12 20:14:04 +00004040 if( nInMul==0
4041 && pProbe->nSample
4042 && pNew->u.btree.nEq<=pProbe->nSampleCol
4043 && OptimizationEnabled(db, SQLITE_Stat3)
4044 ){
dan7a419232013-08-06 20:01:43 +00004045 Expr *pExpr = pTerm->pExpr;
drhb8a8e8a2013-06-10 19:12:39 +00004046 tRowcnt nOut = 0;
drh6f2bfad2013-06-03 17:35:22 +00004047 if( (pTerm->eOperator & (WO_EQ|WO_ISNULL))!=0 ){
drh93ec45d2013-06-17 18:20:48 +00004048 testcase( pTerm->eOperator & WO_EQ );
4049 testcase( pTerm->eOperator & WO_ISNULL );
dan7a419232013-08-06 20:01:43 +00004050 rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut);
drh6f2bfad2013-06-03 17:35:22 +00004051 }else if( (pTerm->eOperator & WO_IN)
dan7a419232013-08-06 20:01:43 +00004052 && !ExprHasProperty(pExpr, EP_xIsSelect) ){
4053 rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut);
drh6f2bfad2013-06-03 17:35:22 +00004054 }
drh82846332013-08-01 17:21:26 +00004055 assert( nOut==0 || rc==SQLITE_OK );
dan6cb8d762013-08-08 11:48:57 +00004056 if( nOut ){
drh4f991892013-10-11 15:05:05 +00004057 pNew->nOut = sqlite3LogEst(nOut);
4058 if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut;
dan6cb8d762013-08-08 11:48:57 +00004059 }
drh6f2bfad2013-06-03 17:35:22 +00004060 }
4061#endif
drhe217efc2013-06-12 03:48:41 +00004062 if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
drheb04de32013-05-10 15:16:30 +00004063 /* Each row involves a step of the index, then a binary search of
4064 ** the main table */
drhbf539c42013-10-05 18:16:02 +00004065 pNew->rRun = sqlite3LogEstAdd(pNew->rRun,rLogSize>27 ? rLogSize-17 : 10);
drheb04de32013-05-10 15:16:30 +00004066 }
drhe217efc2013-06-12 03:48:41 +00004067 /* Step cost for each output row */
drhb50596d2013-10-08 20:42:41 +00004068 pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut);
drh4f991892013-10-11 15:05:05 +00004069 whereLoopOutputAdjust(pBuilder->pWC, pNew);
drhcf8fa7a2013-05-10 20:26:22 +00004070 rc = whereLoopInsert(pBuilder, pNew);
drh5346e952013-05-08 14:14:26 +00004071 if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
drhbbbdc832013-10-22 18:01:40 +00004072 && pNew->u.btree.nEq<(pProbe->nKeyCol + (pProbe->zName!=0))
drh5346e952013-05-08 14:14:26 +00004073 ){
drhb8a8e8a2013-06-10 19:12:39 +00004074 whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
drha18f3d22013-05-08 03:05:41 +00004075 }
danad45ed72013-08-08 12:21:32 +00004076 pNew->nOut = saved_nOut;
drh1435a9a2013-08-27 23:15:44 +00004077#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
dan7a419232013-08-06 20:01:43 +00004078 pBuilder->nRecValid = nRecValid;
dan7a419232013-08-06 20:01:43 +00004079#endif
drh1c8148f2013-05-04 20:25:23 +00004080 }
drh4efc9292013-06-06 23:02:03 +00004081 pNew->prereq = saved_prereq;
4082 pNew->u.btree.nEq = saved_nEq;
drhcd8629e2013-11-13 12:27:25 +00004083 pNew->u.btree.nSkip = saved_nSkip;
drh4efc9292013-06-06 23:02:03 +00004084 pNew->wsFlags = saved_wsFlags;
4085 pNew->nOut = saved_nOut;
4086 pNew->nLTerm = saved_nLTerm;
drh5346e952013-05-08 14:14:26 +00004087 return rc;
drh1c8148f2013-05-04 20:25:23 +00004088}
4089
4090/*
drh23f98da2013-05-21 15:52:07 +00004091** Return True if it is possible that pIndex might be useful in
4092** implementing the ORDER BY clause in pBuilder.
4093**
4094** Return False if pBuilder does not contain an ORDER BY clause or
4095** if there is no way for pIndex to be useful in implementing that
4096** ORDER BY clause.
4097*/
4098static int indexMightHelpWithOrderBy(
4099 WhereLoopBuilder *pBuilder,
4100 Index *pIndex,
4101 int iCursor
4102){
4103 ExprList *pOB;
drh6d381472013-06-13 17:58:08 +00004104 int ii, jj;
drh23f98da2013-05-21 15:52:07 +00004105
drh53cfbe92013-06-13 17:28:22 +00004106 if( pIndex->bUnordered ) return 0;
drh70d18342013-06-06 19:16:33 +00004107 if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
drh23f98da2013-05-21 15:52:07 +00004108 for(ii=0; ii<pOB->nExpr; ii++){
drh45c154a2013-06-03 20:46:35 +00004109 Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr);
drh23f98da2013-05-21 15:52:07 +00004110 if( pExpr->op!=TK_COLUMN ) return 0;
4111 if( pExpr->iTable==iCursor ){
drhbbbdc832013-10-22 18:01:40 +00004112 for(jj=0; jj<pIndex->nKeyCol; jj++){
drh6d381472013-06-13 17:58:08 +00004113 if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
4114 }
drh23f98da2013-05-21 15:52:07 +00004115 }
4116 }
4117 return 0;
4118}
4119
4120/*
drh92a121f2013-06-10 12:15:47 +00004121** Return a bitmask where 1s indicate that the corresponding column of
4122** the table is used by an index. Only the first 63 columns are considered.
4123*/
drhfd5874d2013-06-12 14:52:39 +00004124static Bitmask columnsInIndex(Index *pIdx){
drh92a121f2013-06-10 12:15:47 +00004125 Bitmask m = 0;
4126 int j;
drhec95c442013-10-23 01:57:32 +00004127 for(j=pIdx->nColumn-1; j>=0; j--){
drh92a121f2013-06-10 12:15:47 +00004128 int x = pIdx->aiColumn[j];
drhec95c442013-10-23 01:57:32 +00004129 if( x>=0 ){
4130 testcase( x==BMS-1 );
4131 testcase( x==BMS-2 );
4132 if( x<BMS-1 ) m |= MASKBIT(x);
4133 }
drh92a121f2013-06-10 12:15:47 +00004134 }
4135 return m;
4136}
4137
drh4bd5f732013-07-31 23:22:39 +00004138/* Check to see if a partial index with pPartIndexWhere can be used
4139** in the current query. Return true if it can be and false if not.
4140*/
4141static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere){
4142 int i;
4143 WhereTerm *pTerm;
4144 for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
4145 if( sqlite3ExprImpliesExpr(pTerm->pExpr, pWhere, iTab) ) return 1;
4146 }
4147 return 0;
4148}
drh92a121f2013-06-10 12:15:47 +00004149
4150/*
dan51576f42013-07-02 10:06:15 +00004151** Add all WhereLoop objects for a single table of the join where the table
drh0823c892013-05-11 00:06:23 +00004152** is idenfied by pBuilder->pNew->iTab. That table is guaranteed to be
4153** a b-tree table, not a virtual table.
drhf1b5f5b2013-05-02 00:15:01 +00004154*/
drh5346e952013-05-08 14:14:26 +00004155static int whereLoopAddBtree(
drh1c8148f2013-05-04 20:25:23 +00004156 WhereLoopBuilder *pBuilder, /* WHERE clause information */
drh1c8148f2013-05-04 20:25:23 +00004157 Bitmask mExtra /* Extra prerequesites for using this table */
drhf1b5f5b2013-05-02 00:15:01 +00004158){
drh70d18342013-06-06 19:16:33 +00004159 WhereInfo *pWInfo; /* WHERE analysis context */
drh1c8148f2013-05-04 20:25:23 +00004160 Index *pProbe; /* An index we are evaluating */
drh1c8148f2013-05-04 20:25:23 +00004161 Index sPk; /* A fake index object for the primary key */
4162 tRowcnt aiRowEstPk[2]; /* The aiRowEst[] value for the sPk index */
drhbbbdc832013-10-22 18:01:40 +00004163 i16 aiColumnPk = -1; /* The aColumn[] value for the sPk index */
drh70d18342013-06-06 19:16:33 +00004164 SrcList *pTabList; /* The FROM clause */
drh1c8148f2013-05-04 20:25:23 +00004165 struct SrcList_item *pSrc; /* The FROM clause btree term to add */
drh1c8148f2013-05-04 20:25:23 +00004166 WhereLoop *pNew; /* Template WhereLoop object */
drh5346e952013-05-08 14:14:26 +00004167 int rc = SQLITE_OK; /* Return code */
drhd044d202013-05-31 12:43:55 +00004168 int iSortIdx = 1; /* Index number */
drh23f98da2013-05-21 15:52:07 +00004169 int b; /* A boolean value */
drhbf539c42013-10-05 18:16:02 +00004170 LogEst rSize; /* number of rows in the table */
4171 LogEst rLogSize; /* Logarithm of the number of rows in the table */
drh4bd5f732013-07-31 23:22:39 +00004172 WhereClause *pWC; /* The parsed WHERE clause */
drh3495d202013-10-07 17:32:15 +00004173 Table *pTab; /* Table being queried */
drh23f98da2013-05-21 15:52:07 +00004174
drh1c8148f2013-05-04 20:25:23 +00004175 pNew = pBuilder->pNew;
drh70d18342013-06-06 19:16:33 +00004176 pWInfo = pBuilder->pWInfo;
4177 pTabList = pWInfo->pTabList;
4178 pSrc = pTabList->a + pNew->iTab;
drh3495d202013-10-07 17:32:15 +00004179 pTab = pSrc->pTab;
drh4bd5f732013-07-31 23:22:39 +00004180 pWC = pBuilder->pWC;
drh0823c892013-05-11 00:06:23 +00004181 assert( !IsVirtual(pSrc->pTab) );
drh1c8148f2013-05-04 20:25:23 +00004182
4183 if( pSrc->pIndex ){
4184 /* An INDEXED BY clause specifies a particular index to use */
4185 pProbe = pSrc->pIndex;
drhec95c442013-10-23 01:57:32 +00004186 }else if( !HasRowid(pTab) ){
4187 pProbe = pTab->pIndex;
drh1c8148f2013-05-04 20:25:23 +00004188 }else{
4189 /* There is no INDEXED BY clause. Create a fake Index object in local
4190 ** variable sPk to represent the rowid primary key index. Make this
4191 ** fake index the first in a chain of Index objects with all of the real
4192 ** indices to follow */
4193 Index *pFirst; /* First of real indices on the table */
4194 memset(&sPk, 0, sizeof(Index));
drhbbbdc832013-10-22 18:01:40 +00004195 sPk.nKeyCol = 1;
drh1c8148f2013-05-04 20:25:23 +00004196 sPk.aiColumn = &aiColumnPk;
4197 sPk.aiRowEst = aiRowEstPk;
4198 sPk.onError = OE_Replace;
drh3495d202013-10-07 17:32:15 +00004199 sPk.pTable = pTab;
4200 aiRowEstPk[0] = pTab->nRowEst;
drh1c8148f2013-05-04 20:25:23 +00004201 aiRowEstPk[1] = 1;
4202 pFirst = pSrc->pTab->pIndex;
4203 if( pSrc->notIndexed==0 ){
4204 /* The real indices of the table are only considered if the
4205 ** NOT INDEXED qualifier is omitted from the FROM clause */
4206 sPk.pNext = pFirst;
4207 }
4208 pProbe = &sPk;
4209 }
drh3495d202013-10-07 17:32:15 +00004210 rSize = sqlite3LogEst(pTab->nRowEst);
drheb04de32013-05-10 15:16:30 +00004211 rLogSize = estLog(rSize);
4212
drhfeb56e02013-08-23 17:33:46 +00004213#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
drheb04de32013-05-10 15:16:30 +00004214 /* Automatic indexes */
drhaa32e3c2013-07-16 21:31:23 +00004215 if( !pBuilder->pOrSet
drh4fe425a2013-06-12 17:08:06 +00004216 && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
4217 && pSrc->pIndex==0
drheb04de32013-05-10 15:16:30 +00004218 && !pSrc->viaCoroutine
4219 && !pSrc->notIndexed
drhec95c442013-10-23 01:57:32 +00004220 && HasRowid(pTab)
drheb04de32013-05-10 15:16:30 +00004221 && !pSrc->isCorrelated
dan62ba4e42014-01-15 18:21:41 +00004222 && !pSrc->isRecursive
drheb04de32013-05-10 15:16:30 +00004223 ){
4224 /* Generate auto-index WhereLoops */
drheb04de32013-05-10 15:16:30 +00004225 WhereTerm *pTerm;
4226 WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
4227 for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
drh79a13bf2013-05-31 20:28:28 +00004228 if( pTerm->prereqRight & pNew->maskSelf ) continue;
drheb04de32013-05-10 15:16:30 +00004229 if( termCanDriveIndex(pTerm, pSrc, 0) ){
4230 pNew->u.btree.nEq = 1;
drhcd8629e2013-11-13 12:27:25 +00004231 pNew->u.btree.nSkip = 0;
drhef866372013-05-22 20:49:02 +00004232 pNew->u.btree.pIndex = 0;
drh4efc9292013-06-06 23:02:03 +00004233 pNew->nLTerm = 1;
4234 pNew->aLTerm[0] = pTerm;
drhe1e2e9a2013-06-13 15:16:53 +00004235 /* TUNING: One-time cost for computing the automatic index is
drh986b3872013-06-28 21:12:20 +00004236 ** approximately 7*N*log2(N) where N is the number of rows in
drhe1e2e9a2013-06-13 15:16:53 +00004237 ** the table being indexed. */
drhbf539c42013-10-05 18:16:02 +00004238 pNew->rSetup = rLogSize + rSize + 28; assert( 28==sqlite3LogEst(7) );
drh986b3872013-06-28 21:12:20 +00004239 /* TUNING: Each index lookup yields 20 rows in the table. This
4240 ** is more than the usual guess of 10 rows, since we have no way
4241 ** of knowning how selective the index will ultimately be. It would
4242 ** not be unreasonable to make this value much larger. */
drhbf539c42013-10-05 18:16:02 +00004243 pNew->nOut = 43; assert( 43==sqlite3LogEst(20) );
drhb50596d2013-10-08 20:42:41 +00004244 pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut);
drh986b3872013-06-28 21:12:20 +00004245 pNew->wsFlags = WHERE_AUTO_INDEX;
drheb04de32013-05-10 15:16:30 +00004246 pNew->prereq = mExtra | pTerm->prereqRight;
drhcf8fa7a2013-05-10 20:26:22 +00004247 rc = whereLoopInsert(pBuilder, pNew);
drheb04de32013-05-10 15:16:30 +00004248 }
4249 }
4250 }
drhfeb56e02013-08-23 17:33:46 +00004251#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
drh1c8148f2013-05-04 20:25:23 +00004252
4253 /* Loop over all indices
4254 */
drh23f98da2013-05-21 15:52:07 +00004255 for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){
drh4bd5f732013-07-31 23:22:39 +00004256 if( pProbe->pPartIdxWhere!=0
4257 && !whereUsablePartialIndex(pNew->iTab, pWC, pProbe->pPartIdxWhere) ){
4258 continue; /* Partial index inappropriate for this query */
4259 }
drh5346e952013-05-08 14:14:26 +00004260 pNew->u.btree.nEq = 0;
drhcd8629e2013-11-13 12:27:25 +00004261 pNew->u.btree.nSkip = 0;
drh4efc9292013-06-06 23:02:03 +00004262 pNew->nLTerm = 0;
drh23f98da2013-05-21 15:52:07 +00004263 pNew->iSortIdx = 0;
drhb8a8e8a2013-06-10 19:12:39 +00004264 pNew->rSetup = 0;
drh23f98da2013-05-21 15:52:07 +00004265 pNew->prereq = mExtra;
drh74f91d42013-06-19 18:01:44 +00004266 pNew->nOut = rSize;
drh23f98da2013-05-21 15:52:07 +00004267 pNew->u.btree.pIndex = pProbe;
4268 b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
drh53cfbe92013-06-13 17:28:22 +00004269 /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
4270 assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
drh43fe25f2013-05-07 23:06:23 +00004271 if( pProbe->tnum<=0 ){
4272 /* Integer primary key index */
4273 pNew->wsFlags = WHERE_IPK;
drh23f98da2013-05-21 15:52:07 +00004274
4275 /* Full table scan */
drhd044d202013-05-31 12:43:55 +00004276 pNew->iSortIdx = b ? iSortIdx : 0;
drhe1e2e9a2013-06-13 15:16:53 +00004277 /* TUNING: Cost of full table scan is 3*(N + log2(N)).
drhbf539c42013-10-05 18:16:02 +00004278 ** + The extra 3 factor is to encourage the use of indexed lookups
drhe13e9f52013-10-05 19:18:00 +00004279 ** over full scans. FIXME */
drhb50596d2013-10-08 20:42:41 +00004280 pNew->rRun = sqlite3LogEstAdd(rSize,rLogSize) + 16;
drh4f991892013-10-11 15:05:05 +00004281 whereLoopOutputAdjust(pWC, pNew);
drh23f98da2013-05-21 15:52:07 +00004282 rc = whereLoopInsert(pBuilder, pNew);
drhcca9f3d2013-09-06 15:23:29 +00004283 pNew->nOut = rSize;
drh23f98da2013-05-21 15:52:07 +00004284 if( rc ) break;
drh43fe25f2013-05-07 23:06:23 +00004285 }else{
drhec95c442013-10-23 01:57:32 +00004286 Bitmask m;
4287 if( pProbe->isCovering ){
4288 pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
4289 m = 0;
4290 }else{
4291 m = pSrc->colUsed & ~columnsInIndex(pProbe);
4292 pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
4293 }
drh1c8148f2013-05-04 20:25:23 +00004294
drh23f98da2013-05-21 15:52:07 +00004295 /* Full scan via index */
drh53cfbe92013-06-13 17:28:22 +00004296 if( b
drh702ba9f2013-11-07 21:25:13 +00004297 || !HasRowid(pTab)
drh53cfbe92013-06-13 17:28:22 +00004298 || ( m==0
4299 && pProbe->bUnordered==0
drh702ba9f2013-11-07 21:25:13 +00004300 && (pProbe->szIdxRow<pTab->szTabRow)
drh53cfbe92013-06-13 17:28:22 +00004301 && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
4302 && sqlite3GlobalConfig.bUseCis
4303 && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
4304 )
drhe3b7c922013-06-03 19:17:40 +00004305 ){
drh23f98da2013-05-21 15:52:07 +00004306 pNew->iSortIdx = b ? iSortIdx : 0;
drhe1e2e9a2013-06-13 15:16:53 +00004307 if( m==0 ){
drhd9e3cad2013-10-04 02:36:19 +00004308 /* TUNING: Cost of a covering index scan is K*(N + log2(N)).
drhb50596d2013-10-08 20:42:41 +00004309 ** + The extra factor K of between 1.1 and 3.0 that depends
4310 ** on the relative sizes of the table and the index. K
4311 ** is smaller for smaller indices, thus favoring them.
drhd9e3cad2013-10-04 02:36:19 +00004312 */
drhb50596d2013-10-08 20:42:41 +00004313 pNew->rRun = sqlite3LogEstAdd(rSize,rLogSize) + 1 +
4314 (15*pProbe->szIdxRow)/pTab->szTabRow;
drhe1e2e9a2013-06-13 15:16:53 +00004315 }else{
drhe1e2e9a2013-06-13 15:16:53 +00004316 /* TUNING: Cost of scanning a non-covering index is (N+1)*log2(N)
4317 ** which we will simplify to just N*log2(N) */
4318 pNew->rRun = rSize + rLogSize;
4319 }
drh4f991892013-10-11 15:05:05 +00004320 whereLoopOutputAdjust(pWC, pNew);
drh23f98da2013-05-21 15:52:07 +00004321 rc = whereLoopInsert(pBuilder, pNew);
drhcca9f3d2013-09-06 15:23:29 +00004322 pNew->nOut = rSize;
drh23f98da2013-05-21 15:52:07 +00004323 if( rc ) break;
4324 }
4325 }
dan7a419232013-08-06 20:01:43 +00004326
drhb8a8e8a2013-06-10 19:12:39 +00004327 rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
drh1435a9a2013-08-27 23:15:44 +00004328#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
dan87cd9322013-08-07 15:52:41 +00004329 sqlite3Stat4ProbeFree(pBuilder->pRec);
4330 pBuilder->nRecValid = 0;
4331 pBuilder->pRec = 0;
danddc2d6e2013-08-06 20:15:06 +00004332#endif
drh1c8148f2013-05-04 20:25:23 +00004333
4334 /* If there was an INDEXED BY clause, then only that one index is
4335 ** considered. */
4336 if( pSrc->pIndex ) break;
4337 }
drh5346e952013-05-08 14:14:26 +00004338 return rc;
drhf1b5f5b2013-05-02 00:15:01 +00004339}
4340
drh8636e9c2013-06-11 01:50:08 +00004341#ifndef SQLITE_OMIT_VIRTUALTABLE
drhf1b5f5b2013-05-02 00:15:01 +00004342/*
drh0823c892013-05-11 00:06:23 +00004343** Add all WhereLoop objects for a table of the join identified by
4344** pBuilder->pNew->iTab. That table is guaranteed to be a virtual table.
drhf1b5f5b2013-05-02 00:15:01 +00004345*/
drh5346e952013-05-08 14:14:26 +00004346static int whereLoopAddVirtual(
danff4b23b2013-11-12 12:17:16 +00004347 WhereLoopBuilder *pBuilder, /* WHERE clause information */
4348 Bitmask mExtra
drhf1b5f5b2013-05-02 00:15:01 +00004349){
drh70d18342013-06-06 19:16:33 +00004350 WhereInfo *pWInfo; /* WHERE analysis context */
drh5346e952013-05-08 14:14:26 +00004351 Parse *pParse; /* The parsing context */
4352 WhereClause *pWC; /* The WHERE clause */
4353 struct SrcList_item *pSrc; /* The FROM clause term to search */
4354 Table *pTab;
4355 sqlite3 *db;
4356 sqlite3_index_info *pIdxInfo;
4357 struct sqlite3_index_constraint *pIdxCons;
4358 struct sqlite3_index_constraint_usage *pUsage;
4359 WhereTerm *pTerm;
4360 int i, j;
4361 int iTerm, mxTerm;
drh4efc9292013-06-06 23:02:03 +00004362 int nConstraint;
drh5346e952013-05-08 14:14:26 +00004363 int seenIn = 0; /* True if an IN operator is seen */
4364 int seenVar = 0; /* True if a non-constant constraint is seen */
4365 int iPhase; /* 0: const w/o IN, 1: const, 2: no IN, 2: IN */
4366 WhereLoop *pNew;
drh5346e952013-05-08 14:14:26 +00004367 int rc = SQLITE_OK;
4368
drh70d18342013-06-06 19:16:33 +00004369 pWInfo = pBuilder->pWInfo;
4370 pParse = pWInfo->pParse;
drh5346e952013-05-08 14:14:26 +00004371 db = pParse->db;
4372 pWC = pBuilder->pWC;
drh5346e952013-05-08 14:14:26 +00004373 pNew = pBuilder->pNew;
drh70d18342013-06-06 19:16:33 +00004374 pSrc = &pWInfo->pTabList->a[pNew->iTab];
drhb2a90f02013-05-10 03:30:49 +00004375 pTab = pSrc->pTab;
drh0823c892013-05-11 00:06:23 +00004376 assert( IsVirtual(pTab) );
drhb2a90f02013-05-10 03:30:49 +00004377 pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pBuilder->pOrderBy);
drh5346e952013-05-08 14:14:26 +00004378 if( pIdxInfo==0 ) return SQLITE_NOMEM;
drh5346e952013-05-08 14:14:26 +00004379 pNew->prereq = 0;
drh5346e952013-05-08 14:14:26 +00004380 pNew->rSetup = 0;
4381 pNew->wsFlags = WHERE_VIRTUALTABLE;
drh4efc9292013-06-06 23:02:03 +00004382 pNew->nLTerm = 0;
drh5346e952013-05-08 14:14:26 +00004383 pNew->u.vtab.needFree = 0;
4384 pUsage = pIdxInfo->aConstraintUsage;
drh4efc9292013-06-06 23:02:03 +00004385 nConstraint = pIdxInfo->nConstraint;
drh7963b0e2013-06-17 21:37:40 +00004386 if( whereLoopResize(db, pNew, nConstraint) ){
4387 sqlite3DbFree(db, pIdxInfo);
4388 return SQLITE_NOMEM;
4389 }
drh5346e952013-05-08 14:14:26 +00004390
drh0823c892013-05-11 00:06:23 +00004391 for(iPhase=0; iPhase<=3; iPhase++){
drh5346e952013-05-08 14:14:26 +00004392 if( !seenIn && (iPhase&1)!=0 ){
4393 iPhase++;
4394 if( iPhase>3 ) break;
4395 }
4396 if( !seenVar && iPhase>1 ) break;
4397 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
4398 for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
4399 j = pIdxCons->iTermOffset;
4400 pTerm = &pWC->a[j];
4401 switch( iPhase ){
4402 case 0: /* Constants without IN operator */
4403 pIdxCons->usable = 0;
4404 if( (pTerm->eOperator & WO_IN)!=0 ){
4405 seenIn = 1;
drh7963b0e2013-06-17 21:37:40 +00004406 }
4407 if( pTerm->prereqRight!=0 ){
drh5346e952013-05-08 14:14:26 +00004408 seenVar = 1;
drh7963b0e2013-06-17 21:37:40 +00004409 }else if( (pTerm->eOperator & WO_IN)==0 ){
drh5346e952013-05-08 14:14:26 +00004410 pIdxCons->usable = 1;
4411 }
4412 break;
4413 case 1: /* Constants with IN operators */
4414 assert( seenIn );
4415 pIdxCons->usable = (pTerm->prereqRight==0);
4416 break;
4417 case 2: /* Variables without IN */
4418 assert( seenVar );
4419 pIdxCons->usable = (pTerm->eOperator & WO_IN)==0;
4420 break;
4421 default: /* Variables with IN */
4422 assert( seenVar && seenIn );
4423 pIdxCons->usable = 1;
4424 break;
4425 }
4426 }
4427 memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
4428 if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
4429 pIdxInfo->idxStr = 0;
4430 pIdxInfo->idxNum = 0;
4431 pIdxInfo->needToFreeIdxStr = 0;
4432 pIdxInfo->orderByConsumed = 0;
drh8636e9c2013-06-11 01:50:08 +00004433 pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
dana9f58152013-11-11 19:01:33 +00004434 pIdxInfo->estimatedRows = 25;
drh5346e952013-05-08 14:14:26 +00004435 rc = vtabBestIndex(pParse, pTab, pIdxInfo);
4436 if( rc ) goto whereLoopAddVtab_exit;
4437 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
danff4b23b2013-11-12 12:17:16 +00004438 pNew->prereq = mExtra;
drhc718f1c2013-05-08 20:05:58 +00004439 mxTerm = -1;
drh4efc9292013-06-06 23:02:03 +00004440 assert( pNew->nLSlot>=nConstraint );
4441 for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
drh3bd26f02013-05-24 14:52:03 +00004442 pNew->u.vtab.omitMask = 0;
drh4efc9292013-06-06 23:02:03 +00004443 for(i=0; i<nConstraint; i++, pIdxCons++){
drh5346e952013-05-08 14:14:26 +00004444 if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
4445 j = pIdxCons->iTermOffset;
drh4efc9292013-06-06 23:02:03 +00004446 if( iTerm>=nConstraint
drh5346e952013-05-08 14:14:26 +00004447 || j<0
4448 || j>=pWC->nTerm
drh4efc9292013-06-06 23:02:03 +00004449 || pNew->aLTerm[iTerm]!=0
drh5346e952013-05-08 14:14:26 +00004450 ){
4451 rc = SQLITE_ERROR;
4452 sqlite3ErrorMsg(pParse, "%s.xBestIndex() malfunction", pTab->zName);
4453 goto whereLoopAddVtab_exit;
4454 }
drh7963b0e2013-06-17 21:37:40 +00004455 testcase( iTerm==nConstraint-1 );
4456 testcase( j==0 );
4457 testcase( j==pWC->nTerm-1 );
drh5346e952013-05-08 14:14:26 +00004458 pTerm = &pWC->a[j];
4459 pNew->prereq |= pTerm->prereqRight;
drh4efc9292013-06-06 23:02:03 +00004460 assert( iTerm<pNew->nLSlot );
4461 pNew->aLTerm[iTerm] = pTerm;
drh5346e952013-05-08 14:14:26 +00004462 if( iTerm>mxTerm ) mxTerm = iTerm;
drh7963b0e2013-06-17 21:37:40 +00004463 testcase( iTerm==15 );
4464 testcase( iTerm==16 );
drh52986302013-06-03 16:03:16 +00004465 if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm;
drh5346e952013-05-08 14:14:26 +00004466 if( (pTerm->eOperator & WO_IN)!=0 ){
4467 if( pUsage[i].omit==0 ){
4468 /* Do not attempt to use an IN constraint if the virtual table
4469 ** says that the equivalent EQ constraint cannot be safely omitted.
4470 ** If we do attempt to use such a constraint, some rows might be
4471 ** repeated in the output. */
4472 break;
4473 }
4474 /* A virtual table that is constrained by an IN clause may not
4475 ** consume the ORDER BY clause because (1) the order of IN terms
4476 ** is not necessarily related to the order of output terms and
4477 ** (2) Multiple outputs from a single IN value will not merge
4478 ** together. */
4479 pIdxInfo->orderByConsumed = 0;
4480 }
4481 }
4482 }
drh4efc9292013-06-06 23:02:03 +00004483 if( i>=nConstraint ){
4484 pNew->nLTerm = mxTerm+1;
4485 assert( pNew->nLTerm<=pNew->nLSlot );
drh5346e952013-05-08 14:14:26 +00004486 pNew->u.vtab.idxNum = pIdxInfo->idxNum;
4487 pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
4488 pIdxInfo->needToFreeIdxStr = 0;
4489 pNew->u.vtab.idxStr = pIdxInfo->idxStr;
drh3b1d8082013-06-03 16:56:37 +00004490 pNew->u.vtab.isOrdered = (u8)((pIdxInfo->nOrderBy!=0)
4491 && pIdxInfo->orderByConsumed);
drhb8a8e8a2013-06-10 19:12:39 +00004492 pNew->rSetup = 0;
drhb50596d2013-10-08 20:42:41 +00004493 pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost);
dana9f58152013-11-11 19:01:33 +00004494 pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows);
drhcf8fa7a2013-05-10 20:26:22 +00004495 whereLoopInsert(pBuilder, pNew);
drh5346e952013-05-08 14:14:26 +00004496 if( pNew->u.vtab.needFree ){
4497 sqlite3_free(pNew->u.vtab.idxStr);
4498 pNew->u.vtab.needFree = 0;
4499 }
4500 }
4501 }
4502
4503whereLoopAddVtab_exit:
4504 if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
4505 sqlite3DbFree(db, pIdxInfo);
4506 return rc;
drhf1b5f5b2013-05-02 00:15:01 +00004507}
drh8636e9c2013-06-11 01:50:08 +00004508#endif /* SQLITE_OMIT_VIRTUALTABLE */
drhf1b5f5b2013-05-02 00:15:01 +00004509
4510/*
drhcf8fa7a2013-05-10 20:26:22 +00004511** Add WhereLoop entries to handle OR terms. This works for either
4512** btrees or virtual tables.
4513*/
4514static int whereLoopAddOr(WhereLoopBuilder *pBuilder, Bitmask mExtra){
drh70d18342013-06-06 19:16:33 +00004515 WhereInfo *pWInfo = pBuilder->pWInfo;
drhcf8fa7a2013-05-10 20:26:22 +00004516 WhereClause *pWC;
4517 WhereLoop *pNew;
4518 WhereTerm *pTerm, *pWCEnd;
4519 int rc = SQLITE_OK;
4520 int iCur;
4521 WhereClause tempWC;
4522 WhereLoopBuilder sSubBuild;
drhaa32e3c2013-07-16 21:31:23 +00004523 WhereOrSet sSum, sCur, sPrev;
drhcf8fa7a2013-05-10 20:26:22 +00004524 struct SrcList_item *pItem;
4525
drhcf8fa7a2013-05-10 20:26:22 +00004526 pWC = pBuilder->pWC;
drh70d18342013-06-06 19:16:33 +00004527 if( pWInfo->wctrlFlags & WHERE_AND_ONLY ) return SQLITE_OK;
drhcf8fa7a2013-05-10 20:26:22 +00004528 pWCEnd = pWC->a + pWC->nTerm;
4529 pNew = pBuilder->pNew;
drh77dfd5b2013-08-19 11:15:48 +00004530 memset(&sSum, 0, sizeof(sSum));
drh186ad8c2013-10-08 18:40:37 +00004531 pItem = pWInfo->pTabList->a + pNew->iTab;
drhd4ddae92013-11-06 12:05:57 +00004532 if( !HasRowid(pItem->pTab) ) return SQLITE_OK;
drh186ad8c2013-10-08 18:40:37 +00004533 iCur = pItem->iCursor;
drhcf8fa7a2013-05-10 20:26:22 +00004534
4535 for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
4536 if( (pTerm->eOperator & WO_OR)!=0
4537 && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
4538 ){
4539 WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
4540 WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
4541 WhereTerm *pOrTerm;
drhaa32e3c2013-07-16 21:31:23 +00004542 int once = 1;
4543 int i, j;
drh783dece2013-06-05 17:53:43 +00004544
drh783dece2013-06-05 17:53:43 +00004545 sSubBuild = *pBuilder;
4546 sSubBuild.pOrderBy = 0;
drhaa32e3c2013-07-16 21:31:23 +00004547 sSubBuild.pOrSet = &sCur;
drhcf8fa7a2013-05-10 20:26:22 +00004548
drhc7f0d222013-06-19 03:27:12 +00004549 for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
drh783dece2013-06-05 17:53:43 +00004550 if( (pOrTerm->eOperator & WO_AND)!=0 ){
drhcf8fa7a2013-05-10 20:26:22 +00004551 sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
4552 }else if( pOrTerm->leftCursor==iCur ){
drh70d18342013-06-06 19:16:33 +00004553 tempWC.pWInfo = pWC->pWInfo;
drh783dece2013-06-05 17:53:43 +00004554 tempWC.pOuter = pWC;
4555 tempWC.op = TK_AND;
drh783dece2013-06-05 17:53:43 +00004556 tempWC.nTerm = 1;
drhcf8fa7a2013-05-10 20:26:22 +00004557 tempWC.a = pOrTerm;
4558 sSubBuild.pWC = &tempWC;
4559 }else{
4560 continue;
4561 }
drhaa32e3c2013-07-16 21:31:23 +00004562 sCur.n = 0;
drh8636e9c2013-06-11 01:50:08 +00004563#ifndef SQLITE_OMIT_VIRTUALTABLE
drhcf8fa7a2013-05-10 20:26:22 +00004564 if( IsVirtual(pItem->pTab) ){
danff4b23b2013-11-12 12:17:16 +00004565 rc = whereLoopAddVirtual(&sSubBuild, mExtra);
drh8636e9c2013-06-11 01:50:08 +00004566 }else
4567#endif
4568 {
drhcf8fa7a2013-05-10 20:26:22 +00004569 rc = whereLoopAddBtree(&sSubBuild, mExtra);
4570 }
drhaa32e3c2013-07-16 21:31:23 +00004571 assert( rc==SQLITE_OK || sCur.n==0 );
4572 if( sCur.n==0 ){
4573 sSum.n = 0;
4574 break;
4575 }else if( once ){
4576 whereOrMove(&sSum, &sCur);
4577 once = 0;
4578 }else{
4579 whereOrMove(&sPrev, &sSum);
4580 sSum.n = 0;
4581 for(i=0; i<sPrev.n; i++){
4582 for(j=0; j<sCur.n; j++){
4583 whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,
drhbf539c42013-10-05 18:16:02 +00004584 sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
4585 sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
drhaa32e3c2013-07-16 21:31:23 +00004586 }
4587 }
4588 }
drhcf8fa7a2013-05-10 20:26:22 +00004589 }
drhaa32e3c2013-07-16 21:31:23 +00004590 pNew->nLTerm = 1;
4591 pNew->aLTerm[0] = pTerm;
4592 pNew->wsFlags = WHERE_MULTI_OR;
4593 pNew->rSetup = 0;
4594 pNew->iSortIdx = 0;
4595 memset(&pNew->u, 0, sizeof(pNew->u));
4596 for(i=0; rc==SQLITE_OK && i<sSum.n; i++){
drh74f91d42013-06-19 18:01:44 +00004597 /* TUNING: Multiple by 3.5 for the secondary table lookup */
drhaa32e3c2013-07-16 21:31:23 +00004598 pNew->rRun = sSum.a[i].rRun + 18;
4599 pNew->nOut = sSum.a[i].nOut;
4600 pNew->prereq = sSum.a[i].prereq;
drhfd5874d2013-06-12 14:52:39 +00004601 rc = whereLoopInsert(pBuilder, pNew);
4602 }
drhcf8fa7a2013-05-10 20:26:22 +00004603 }
4604 }
4605 return rc;
4606}
4607
4608/*
drhf1b5f5b2013-05-02 00:15:01 +00004609** Add all WhereLoop objects for all tables
4610*/
drh5346e952013-05-08 14:14:26 +00004611static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
drh70d18342013-06-06 19:16:33 +00004612 WhereInfo *pWInfo = pBuilder->pWInfo;
drhf1b5f5b2013-05-02 00:15:01 +00004613 Bitmask mExtra = 0;
4614 Bitmask mPrior = 0;
4615 int iTab;
drh70d18342013-06-06 19:16:33 +00004616 SrcList *pTabList = pWInfo->pTabList;
drhf1b5f5b2013-05-02 00:15:01 +00004617 struct SrcList_item *pItem;
drh70d18342013-06-06 19:16:33 +00004618 sqlite3 *db = pWInfo->pParse->db;
4619 int nTabList = pWInfo->nLevel;
drh5346e952013-05-08 14:14:26 +00004620 int rc = SQLITE_OK;
drhc63367e2013-06-10 20:46:50 +00004621 u8 priorJoinType = 0;
drhb8a8e8a2013-06-10 19:12:39 +00004622 WhereLoop *pNew;
drhf1b5f5b2013-05-02 00:15:01 +00004623
4624 /* Loop over the tables in the join, from left to right */
drhb8a8e8a2013-06-10 19:12:39 +00004625 pNew = pBuilder->pNew;
drha2014152013-06-07 00:29:23 +00004626 whereLoopInit(pNew);
drha18f3d22013-05-08 03:05:41 +00004627 for(iTab=0, pItem=pTabList->a; iTab<nTabList; iTab++, pItem++){
drhb2a90f02013-05-10 03:30:49 +00004628 pNew->iTab = iTab;
drh70d18342013-06-06 19:16:33 +00004629 pNew->maskSelf = getMask(&pWInfo->sMaskSet, pItem->iCursor);
drhc63367e2013-06-10 20:46:50 +00004630 if( ((pItem->jointype|priorJoinType) & (JT_LEFT|JT_CROSS))!=0 ){
drhf1b5f5b2013-05-02 00:15:01 +00004631 mExtra = mPrior;
4632 }
drhc63367e2013-06-10 20:46:50 +00004633 priorJoinType = pItem->jointype;
drhb2a90f02013-05-10 03:30:49 +00004634 if( IsVirtual(pItem->pTab) ){
danff4b23b2013-11-12 12:17:16 +00004635 rc = whereLoopAddVirtual(pBuilder, mExtra);
drhb2a90f02013-05-10 03:30:49 +00004636 }else{
4637 rc = whereLoopAddBtree(pBuilder, mExtra);
4638 }
drhb2a90f02013-05-10 03:30:49 +00004639 if( rc==SQLITE_OK ){
4640 rc = whereLoopAddOr(pBuilder, mExtra);
4641 }
drhb2a90f02013-05-10 03:30:49 +00004642 mPrior |= pNew->maskSelf;
drh5346e952013-05-08 14:14:26 +00004643 if( rc || db->mallocFailed ) break;
drhf1b5f5b2013-05-02 00:15:01 +00004644 }
drha2014152013-06-07 00:29:23 +00004645 whereLoopClear(db, pNew);
drh5346e952013-05-08 14:14:26 +00004646 return rc;
drhf1b5f5b2013-05-02 00:15:01 +00004647}
4648
drha18f3d22013-05-08 03:05:41 +00004649/*
drh7699d1c2013-06-04 12:42:29 +00004650** Examine a WherePath (with the addition of the extra WhereLoop of the 5th
drh319f6772013-05-14 15:31:07 +00004651** parameters) to see if it outputs rows in the requested ORDER BY
drh94433422013-07-01 11:05:50 +00004652** (or GROUP BY) without requiring a separate sort operation. Return:
drh319f6772013-05-14 15:31:07 +00004653**
4654** 0: ORDER BY is not satisfied. Sorting required
4655** 1: ORDER BY is satisfied. Omit sorting
4656** -1: Unknown at this time
4657**
drh94433422013-07-01 11:05:50 +00004658** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
4659** strict. With GROUP BY and DISTINCT the only requirement is that
4660** equivalent rows appear immediately adjacent to one another. GROUP BY
4661** and DISTINT do not require rows to appear in any particular order as long
4662** as equivelent rows are grouped together. Thus for GROUP BY and DISTINCT
4663** the pOrderBy terms can be matched in any order. With ORDER BY, the
4664** pOrderBy terms must be matched in strict left-to-right order.
drh6b7157b2013-05-10 02:00:35 +00004665*/
4666static int wherePathSatisfiesOrderBy(
4667 WhereInfo *pWInfo, /* The WHERE clause */
drh4f402f22013-06-11 18:59:38 +00004668 ExprList *pOrderBy, /* ORDER BY or GROUP BY or DISTINCT clause to check */
drh6b7157b2013-05-10 02:00:35 +00004669 WherePath *pPath, /* The WherePath to check */
drh4f402f22013-06-11 18:59:38 +00004670 u16 wctrlFlags, /* Might contain WHERE_GROUPBY or WHERE_DISTINCTBY */
4671 u16 nLoop, /* Number of entries in pPath->aLoop[] */
drh319f6772013-05-14 15:31:07 +00004672 WhereLoop *pLast, /* Add this WhereLoop to the end of pPath->aLoop[] */
drh4f402f22013-06-11 18:59:38 +00004673 Bitmask *pRevMask /* OUT: Mask of WhereLoops to run in reverse order */
drh6b7157b2013-05-10 02:00:35 +00004674){
drh88da6442013-05-27 17:59:37 +00004675 u8 revSet; /* True if rev is known */
4676 u8 rev; /* Composite sort order */
4677 u8 revIdx; /* Index sort order */
drhe353ee32013-06-04 23:40:53 +00004678 u8 isOrderDistinct; /* All prior WhereLoops are order-distinct */
4679 u8 distinctColumns; /* True if the loop has UNIQUE NOT NULL columns */
4680 u8 isMatch; /* iColumn matches a term of the ORDER BY clause */
drh416846a2013-11-06 12:56:04 +00004681 u16 nKeyCol; /* Number of key columns in pIndex */
4682 u16 nColumn; /* Total number of ordered columns in the index */
drh7699d1c2013-06-04 12:42:29 +00004683 u16 nOrderBy; /* Number terms in the ORDER BY clause */
4684 int iLoop; /* Index of WhereLoop in pPath being processed */
4685 int i, j; /* Loop counters */
4686 int iCur; /* Cursor number for current WhereLoop */
4687 int iColumn; /* A column number within table iCur */
drhe8ae5832013-06-19 13:32:46 +00004688 WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
drh7699d1c2013-06-04 12:42:29 +00004689 WhereTerm *pTerm; /* A single term of the WHERE clause */
4690 Expr *pOBExpr; /* An expression from the ORDER BY clause */
4691 CollSeq *pColl; /* COLLATE function from an ORDER BY clause term */
4692 Index *pIndex; /* The index associated with pLoop */
4693 sqlite3 *db = pWInfo->pParse->db; /* Database connection */
4694 Bitmask obSat = 0; /* Mask of ORDER BY terms satisfied so far */
4695 Bitmask obDone; /* Mask of all ORDER BY terms */
drhe353ee32013-06-04 23:40:53 +00004696 Bitmask orderDistinctMask; /* Mask of all well-ordered loops */
drhb8916be2013-06-14 02:51:48 +00004697 Bitmask ready; /* Mask of inner loops */
drh319f6772013-05-14 15:31:07 +00004698
4699 /*
drh7699d1c2013-06-04 12:42:29 +00004700 ** We say the WhereLoop is "one-row" if it generates no more than one
4701 ** row of output. A WhereLoop is one-row if all of the following are true:
drh319f6772013-05-14 15:31:07 +00004702 ** (a) All index columns match with WHERE_COLUMN_EQ.
4703 ** (b) The index is unique
drh7699d1c2013-06-04 12:42:29 +00004704 ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
4705 ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
drh319f6772013-05-14 15:31:07 +00004706 **
drhe353ee32013-06-04 23:40:53 +00004707 ** We say the WhereLoop is "order-distinct" if the set of columns from
4708 ** that WhereLoop that are in the ORDER BY clause are different for every
4709 ** row of the WhereLoop. Every one-row WhereLoop is automatically
4710 ** order-distinct. A WhereLoop that has no columns in the ORDER BY clause
4711 ** is not order-distinct. To be order-distinct is not quite the same as being
4712 ** UNIQUE since a UNIQUE column or index can have multiple rows that
4713 ** are NULL and NULL values are equivalent for the purpose of order-distinct.
4714 ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
4715 **
4716 ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
4717 ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
4718 ** automatically order-distinct.
drh319f6772013-05-14 15:31:07 +00004719 */
4720
4721 assert( pOrderBy!=0 );
4722
4723 /* Sortability of virtual tables is determined by the xBestIndex method
4724 ** of the virtual table itself */
4725 if( pLast->wsFlags & WHERE_VIRTUALTABLE ){
drh7699d1c2013-06-04 12:42:29 +00004726 testcase( nLoop>0 ); /* True when outer loops are one-row and match
4727 ** no ORDER BY terms */
drh319f6772013-05-14 15:31:07 +00004728 return pLast->u.vtab.isOrdered;
drh6b7157b2013-05-10 02:00:35 +00004729 }
drh7699d1c2013-06-04 12:42:29 +00004730 if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
drh319f6772013-05-14 15:31:07 +00004731
drh319f6772013-05-14 15:31:07 +00004732 nOrderBy = pOrderBy->nExpr;
drh7963b0e2013-06-17 21:37:40 +00004733 testcase( nOrderBy==BMS-1 );
drhe353ee32013-06-04 23:40:53 +00004734 if( nOrderBy>BMS-1 ) return 0; /* Cannot optimize overly large ORDER BYs */
4735 isOrderDistinct = 1;
drh7699d1c2013-06-04 12:42:29 +00004736 obDone = MASKBIT(nOrderBy)-1;
drhe353ee32013-06-04 23:40:53 +00004737 orderDistinctMask = 0;
drhb8916be2013-06-14 02:51:48 +00004738 ready = 0;
drhe353ee32013-06-04 23:40:53 +00004739 for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
drhb8916be2013-06-14 02:51:48 +00004740 if( iLoop>0 ) ready |= pLoop->maskSelf;
drh7699d1c2013-06-04 12:42:29 +00004741 pLoop = iLoop<nLoop ? pPath->aLoop[iLoop] : pLast;
drh319f6772013-05-14 15:31:07 +00004742 assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
drh319f6772013-05-14 15:31:07 +00004743 iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
drhb8916be2013-06-14 02:51:48 +00004744
4745 /* Mark off any ORDER BY term X that is a column in the table of
4746 ** the current loop for which there is term in the WHERE
4747 ** clause of the form X IS NULL or X=? that reference only outer
4748 ** loops.
4749 */
4750 for(i=0; i<nOrderBy; i++){
4751 if( MASKBIT(i) & obSat ) continue;
4752 pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
4753 if( pOBExpr->op!=TK_COLUMN ) continue;
4754 if( pOBExpr->iTable!=iCur ) continue;
4755 pTerm = findTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
4756 ~ready, WO_EQ|WO_ISNULL, 0);
4757 if( pTerm==0 ) continue;
drh7963b0e2013-06-17 21:37:40 +00004758 if( (pTerm->eOperator&WO_EQ)!=0 && pOBExpr->iColumn>=0 ){
drhb8916be2013-06-14 02:51:48 +00004759 const char *z1, *z2;
4760 pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
4761 if( !pColl ) pColl = db->pDfltColl;
4762 z1 = pColl->zName;
4763 pColl = sqlite3ExprCollSeq(pWInfo->pParse, pTerm->pExpr);
4764 if( !pColl ) pColl = db->pDfltColl;
4765 z2 = pColl->zName;
4766 if( sqlite3StrICmp(z1, z2)!=0 ) continue;
4767 }
4768 obSat |= MASKBIT(i);
4769 }
4770
drh7699d1c2013-06-04 12:42:29 +00004771 if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
4772 if( pLoop->wsFlags & WHERE_IPK ){
4773 pIndex = 0;
drhbbbdc832013-10-22 18:01:40 +00004774 nKeyCol = 0;
drh416846a2013-11-06 12:56:04 +00004775 nColumn = 1;
drh7699d1c2013-06-04 12:42:29 +00004776 }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
drh1b0f0262013-05-30 22:27:09 +00004777 return 0;
drh7699d1c2013-06-04 12:42:29 +00004778 }else{
drhbbbdc832013-10-22 18:01:40 +00004779 nKeyCol = pIndex->nKeyCol;
drh416846a2013-11-06 12:56:04 +00004780 nColumn = pIndex->nColumn;
4781 assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) );
4782 assert( pIndex->aiColumn[nColumn-1]==(-1) || !HasRowid(pIndex->pTable));
drhe353ee32013-06-04 23:40:53 +00004783 isOrderDistinct = pIndex->onError!=OE_None;
drh1b0f0262013-05-30 22:27:09 +00004784 }
drh7699d1c2013-06-04 12:42:29 +00004785
drh7699d1c2013-06-04 12:42:29 +00004786 /* Loop through all columns of the index and deal with the ones
4787 ** that are not constrained by == or IN.
4788 */
4789 rev = revSet = 0;
drhe353ee32013-06-04 23:40:53 +00004790 distinctColumns = 0;
drh416846a2013-11-06 12:56:04 +00004791 for(j=0; j<nColumn; j++){
drh7699d1c2013-06-04 12:42:29 +00004792 u8 bOnce; /* True to run the ORDER BY search loop */
4793
drhe353ee32013-06-04 23:40:53 +00004794 /* Skip over == and IS NULL terms */
drh7699d1c2013-06-04 12:42:29 +00004795 if( j<pLoop->u.btree.nEq
drhcd8629e2013-11-13 12:27:25 +00004796 && pLoop->u.btree.nSkip==0
drh4efc9292013-06-06 23:02:03 +00004797 && ((i = pLoop->aLTerm[j]->eOperator) & (WO_EQ|WO_ISNULL))!=0
drh7699d1c2013-06-04 12:42:29 +00004798 ){
drh7963b0e2013-06-17 21:37:40 +00004799 if( i & WO_ISNULL ){
4800 testcase( isOrderDistinct );
4801 isOrderDistinct = 0;
4802 }
drhe353ee32013-06-04 23:40:53 +00004803 continue;
drh7699d1c2013-06-04 12:42:29 +00004804 }
4805
drhe353ee32013-06-04 23:40:53 +00004806 /* Get the column number in the table (iColumn) and sort order
4807 ** (revIdx) for the j-th column of the index.
drh7699d1c2013-06-04 12:42:29 +00004808 */
drh416846a2013-11-06 12:56:04 +00004809 if( pIndex ){
drh7699d1c2013-06-04 12:42:29 +00004810 iColumn = pIndex->aiColumn[j];
4811 revIdx = pIndex->aSortOrder[j];
4812 if( iColumn==pIndex->pTable->iPKey ) iColumn = -1;
drhdc3cd4b2013-05-30 23:21:20 +00004813 }else{
drh7699d1c2013-06-04 12:42:29 +00004814 iColumn = -1;
4815 revIdx = 0;
drhdc3cd4b2013-05-30 23:21:20 +00004816 }
drh7699d1c2013-06-04 12:42:29 +00004817
4818 /* An unconstrained column that might be NULL means that this
drh416846a2013-11-06 12:56:04 +00004819 ** WhereLoop is not well-ordered
drh7699d1c2013-06-04 12:42:29 +00004820 */
drhe353ee32013-06-04 23:40:53 +00004821 if( isOrderDistinct
4822 && iColumn>=0
drh7699d1c2013-06-04 12:42:29 +00004823 && j>=pLoop->u.btree.nEq
4824 && pIndex->pTable->aCol[iColumn].notNull==0
4825 ){
drhe353ee32013-06-04 23:40:53 +00004826 isOrderDistinct = 0;
drh7699d1c2013-06-04 12:42:29 +00004827 }
4828
4829 /* Find the ORDER BY term that corresponds to the j-th column
4830 ** of the index and and mark that ORDER BY term off
4831 */
4832 bOnce = 1;
drhe353ee32013-06-04 23:40:53 +00004833 isMatch = 0;
drh7699d1c2013-06-04 12:42:29 +00004834 for(i=0; bOnce && i<nOrderBy; i++){
4835 if( MASKBIT(i) & obSat ) continue;
4836 pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
drh93ec45d2013-06-17 18:20:48 +00004837 testcase( wctrlFlags & WHERE_GROUPBY );
4838 testcase( wctrlFlags & WHERE_DISTINCTBY );
drh4f402f22013-06-11 18:59:38 +00004839 if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
drhe353ee32013-06-04 23:40:53 +00004840 if( pOBExpr->op!=TK_COLUMN ) continue;
drh7699d1c2013-06-04 12:42:29 +00004841 if( pOBExpr->iTable!=iCur ) continue;
4842 if( pOBExpr->iColumn!=iColumn ) continue;
4843 if( iColumn>=0 ){
4844 pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
4845 if( !pColl ) pColl = db->pDfltColl;
4846 if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
4847 }
drhe353ee32013-06-04 23:40:53 +00004848 isMatch = 1;
drh7699d1c2013-06-04 12:42:29 +00004849 break;
4850 }
drhe353ee32013-06-04 23:40:53 +00004851 if( isMatch ){
drh7963b0e2013-06-17 21:37:40 +00004852 if( iColumn<0 ){
4853 testcase( distinctColumns==0 );
4854 distinctColumns = 1;
4855 }
drh7699d1c2013-06-04 12:42:29 +00004856 obSat |= MASKBIT(i);
4857 if( (pWInfo->wctrlFlags & WHERE_GROUPBY)==0 ){
drhe353ee32013-06-04 23:40:53 +00004858 /* Make sure the sort order is compatible in an ORDER BY clause.
4859 ** Sort order is irrelevant for a GROUP BY clause. */
drh7699d1c2013-06-04 12:42:29 +00004860 if( revSet ){
4861 if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) return 0;
4862 }else{
4863 rev = revIdx ^ pOrderBy->a[i].sortOrder;
4864 if( rev ) *pRevMask |= MASKBIT(iLoop);
4865 revSet = 1;
4866 }
4867 }
4868 }else{
4869 /* No match found */
drhbbbdc832013-10-22 18:01:40 +00004870 if( j==0 || j<nKeyCol ){
drh7963b0e2013-06-17 21:37:40 +00004871 testcase( isOrderDistinct!=0 );
4872 isOrderDistinct = 0;
4873 }
drh7699d1c2013-06-04 12:42:29 +00004874 break;
4875 }
4876 } /* end Loop over all index columns */
drh81186b42013-06-18 01:52:41 +00004877 if( distinctColumns ){
4878 testcase( isOrderDistinct==0 );
4879 isOrderDistinct = 1;
4880 }
drh7699d1c2013-06-04 12:42:29 +00004881 } /* end-if not one-row */
4882
4883 /* Mark off any other ORDER BY terms that reference pLoop */
drhe353ee32013-06-04 23:40:53 +00004884 if( isOrderDistinct ){
4885 orderDistinctMask |= pLoop->maskSelf;
drh7699d1c2013-06-04 12:42:29 +00004886 for(i=0; i<nOrderBy; i++){
4887 Expr *p;
4888 if( MASKBIT(i) & obSat ) continue;
4889 p = pOrderBy->a[i].pExpr;
drh70d18342013-06-06 19:16:33 +00004890 if( (exprTableUsage(&pWInfo->sMaskSet, p)&~orderDistinctMask)==0 ){
drh7699d1c2013-06-04 12:42:29 +00004891 obSat |= MASKBIT(i);
4892 }
drh0afb4232013-05-31 13:36:32 +00004893 }
drh319f6772013-05-14 15:31:07 +00004894 }
drhb8916be2013-06-14 02:51:48 +00004895 } /* End the loop over all WhereLoops from outer-most down to inner-most */
drh7699d1c2013-06-04 12:42:29 +00004896 if( obSat==obDone ) return 1;
drhe353ee32013-06-04 23:40:53 +00004897 if( !isOrderDistinct ) return 0;
drh319f6772013-05-14 15:31:07 +00004898 return -1;
drh6b7157b2013-05-10 02:00:35 +00004899}
4900
drhd15cb172013-05-21 19:23:10 +00004901#ifdef WHERETRACE_ENABLED
4902/* For debugging use only: */
4903static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
4904 static char zName[65];
4905 int i;
4906 for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
4907 if( pLast ) zName[i++] = pLast->cId;
4908 zName[i] = 0;
4909 return zName;
4910}
4911#endif
4912
drh6b7157b2013-05-10 02:00:35 +00004913
4914/*
dan51576f42013-07-02 10:06:15 +00004915** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
drha18f3d22013-05-08 03:05:41 +00004916** attempts to find the lowest cost path that visits each WhereLoop
4917** once. This path is then loaded into the pWInfo->a[].pWLoop fields.
4918**
drhc7f0d222013-06-19 03:27:12 +00004919** Assume that the total number of output rows that will need to be sorted
4920** will be nRowEst (in the 10*log2 representation). Or, ignore sorting
4921** costs if nRowEst==0.
4922**
drha18f3d22013-05-08 03:05:41 +00004923** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
4924** error occurs.
4925*/
drhbf539c42013-10-05 18:16:02 +00004926static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
drh783dece2013-06-05 17:53:43 +00004927 int mxChoice; /* Maximum number of simultaneous paths tracked */
drha18f3d22013-05-08 03:05:41 +00004928 int nLoop; /* Number of terms in the join */
drhe1e2e9a2013-06-13 15:16:53 +00004929 Parse *pParse; /* Parsing context */
drha18f3d22013-05-08 03:05:41 +00004930 sqlite3 *db; /* The database connection */
4931 int iLoop; /* Loop counter over the terms of the join */
4932 int ii, jj; /* Loop counters */
drhfde1e6b2013-09-06 17:45:42 +00004933 int mxI = 0; /* Index of next entry to replace */
drhbf539c42013-10-05 18:16:02 +00004934 LogEst rCost; /* Cost of a path */
4935 LogEst nOut; /* Number of outputs */
4936 LogEst mxCost = 0; /* Maximum cost of a set of paths */
4937 LogEst mxOut = 0; /* Maximum nOut value on the set of paths */
4938 LogEst rSortCost; /* Cost to do a sort */
drha18f3d22013-05-08 03:05:41 +00004939 int nTo, nFrom; /* Number of valid entries in aTo[] and aFrom[] */
4940 WherePath *aFrom; /* All nFrom paths at the previous level */
4941 WherePath *aTo; /* The nTo best paths at the current level */
4942 WherePath *pFrom; /* An element of aFrom[] that we are working on */
4943 WherePath *pTo; /* An element of aTo[] that we are working on */
4944 WhereLoop *pWLoop; /* One of the WhereLoop objects */
4945 WhereLoop **pX; /* Used to divy up the pSpace memory */
4946 char *pSpace; /* Temporary memory used by this routine */
4947
drhe1e2e9a2013-06-13 15:16:53 +00004948 pParse = pWInfo->pParse;
4949 db = pParse->db;
drha18f3d22013-05-08 03:05:41 +00004950 nLoop = pWInfo->nLevel;
drhe1e2e9a2013-06-13 15:16:53 +00004951 /* TUNING: For simple queries, only the best path is tracked.
4952 ** For 2-way joins, the 5 best paths are followed.
4953 ** For joins of 3 or more tables, track the 10 best paths */
drhe9d935a2013-06-05 16:19:59 +00004954 mxChoice = (nLoop==1) ? 1 : (nLoop==2 ? 5 : 10);
drha18f3d22013-05-08 03:05:41 +00004955 assert( nLoop<=pWInfo->pTabList->nSrc );
drh3b48e8c2013-06-12 20:18:16 +00004956 WHERETRACE(0x002, ("---- begin solver\n"));
drha18f3d22013-05-08 03:05:41 +00004957
4958 /* Allocate and initialize space for aTo and aFrom */
4959 ii = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
4960 pSpace = sqlite3DbMallocRaw(db, ii);
4961 if( pSpace==0 ) return SQLITE_NOMEM;
4962 aTo = (WherePath*)pSpace;
4963 aFrom = aTo+mxChoice;
4964 memset(aFrom, 0, sizeof(aFrom[0]));
4965 pX = (WhereLoop**)(aFrom+mxChoice);
drhe9d935a2013-06-05 16:19:59 +00004966 for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
drha18f3d22013-05-08 03:05:41 +00004967 pFrom->aLoop = pX;
4968 }
4969
drhe1e2e9a2013-06-13 15:16:53 +00004970 /* Seed the search with a single WherePath containing zero WhereLoops.
4971 **
4972 ** TUNING: Do not let the number of iterations go above 25. If the cost
4973 ** of computing an automatic index is not paid back within the first 25
4974 ** rows, then do not use the automatic index. */
drhbf539c42013-10-05 18:16:02 +00004975 aFrom[0].nRow = MIN(pParse->nQueryLoop, 46); assert( 46==sqlite3LogEst(25) );
drha18f3d22013-05-08 03:05:41 +00004976 nFrom = 1;
drh6b7157b2013-05-10 02:00:35 +00004977
4978 /* Precompute the cost of sorting the final result set, if the caller
4979 ** to sqlite3WhereBegin() was concerned about sorting */
drhb8a8e8a2013-06-10 19:12:39 +00004980 rSortCost = 0;
4981 if( pWInfo->pOrderBy==0 || nRowEst==0 ){
drh6b7157b2013-05-10 02:00:35 +00004982 aFrom[0].isOrderedValid = 1;
4983 }else{
drh186ad8c2013-10-08 18:40:37 +00004984 /* TUNING: Estimated cost of sorting is 48*N*log2(N) where N is the
4985 ** number of output rows. The 48 is the expected size of a row to sort.
4986 ** FIXME: compute a better estimate of the 48 multiplier based on the
4987 ** result set expressions. */
drhb50596d2013-10-08 20:42:41 +00004988 rSortCost = nRowEst + estLog(nRowEst);
drh3b48e8c2013-06-12 20:18:16 +00004989 WHERETRACE(0x002,("---- sort cost=%-3d\n", rSortCost));
drh6b7157b2013-05-10 02:00:35 +00004990 }
4991
4992 /* Compute successively longer WherePaths using the previous generation
4993 ** of WherePaths as the basis for the next. Keep track of the mxChoice
4994 ** best paths at each generation */
drha18f3d22013-05-08 03:05:41 +00004995 for(iLoop=0; iLoop<nLoop; iLoop++){
4996 nTo = 0;
4997 for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
4998 for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
4999 Bitmask maskNew;
drh319f6772013-05-14 15:31:07 +00005000 Bitmask revMask = 0;
drh6b7157b2013-05-10 02:00:35 +00005001 u8 isOrderedValid = pFrom->isOrderedValid;
5002 u8 isOrdered = pFrom->isOrdered;
drha18f3d22013-05-08 03:05:41 +00005003 if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
5004 if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
drh6b7157b2013-05-10 02:00:35 +00005005 /* At this point, pWLoop is a candidate to be the next loop.
5006 ** Compute its cost */
drhbf539c42013-10-05 18:16:02 +00005007 rCost = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
5008 rCost = sqlite3LogEstAdd(rCost, pFrom->rCost);
drhfde1e6b2013-09-06 17:45:42 +00005009 nOut = pFrom->nRow + pWLoop->nOut;
drha18f3d22013-05-08 03:05:41 +00005010 maskNew = pFrom->maskLoop | pWLoop->maskSelf;
drh6b7157b2013-05-10 02:00:35 +00005011 if( !isOrderedValid ){
drh4f402f22013-06-11 18:59:38 +00005012 switch( wherePathSatisfiesOrderBy(pWInfo,
5013 pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
drh93ec45d2013-06-17 18:20:48 +00005014 iLoop, pWLoop, &revMask) ){
drh6b7157b2013-05-10 02:00:35 +00005015 case 1: /* Yes. pFrom+pWLoop does satisfy the ORDER BY clause */
5016 isOrdered = 1;
5017 isOrderedValid = 1;
5018 break;
5019 case 0: /* No. pFrom+pWLoop will require a separate sort */
5020 isOrdered = 0;
5021 isOrderedValid = 1;
drhbf539c42013-10-05 18:16:02 +00005022 rCost = sqlite3LogEstAdd(rCost, rSortCost);
drh6b7157b2013-05-10 02:00:35 +00005023 break;
5024 default: /* Cannot tell yet. Try again on the next iteration */
5025 break;
5026 }
drh3a5ba8b2013-06-03 15:34:48 +00005027 }else{
5028 revMask = pFrom->revLoop;
drh6b7157b2013-05-10 02:00:35 +00005029 }
5030 /* Check to see if pWLoop should be added to the mxChoice best so far */
5031 for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
drhfde1e6b2013-09-06 17:45:42 +00005032 if( pTo->maskLoop==maskNew
5033 && pTo->isOrderedValid==isOrderedValid
5034 && ((pTo->rCost<=rCost && pTo->nRow<=nOut) ||
5035 (pTo->rCost>=rCost && pTo->nRow>=nOut))
5036 ){
drh7963b0e2013-06-17 21:37:40 +00005037 testcase( jj==nTo-1 );
drh6b7157b2013-05-10 02:00:35 +00005038 break;
5039 }
5040 }
drha18f3d22013-05-08 03:05:41 +00005041 if( jj>=nTo ){
drh7d9e7d82013-09-11 17:39:09 +00005042 if( nTo>=mxChoice && rCost>=mxCost ){
drh989578e2013-10-28 14:34:35 +00005043#ifdef WHERETRACE_ENABLED /* 0x4 */
drhae70cf12013-05-31 15:18:46 +00005044 if( sqlite3WhereTrace&0x4 ){
drhfde1e6b2013-09-06 17:45:42 +00005045 sqlite3DebugPrintf("Skip %s cost=%-3d,%3d order=%c\n",
5046 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
drhd15cb172013-05-21 19:23:10 +00005047 isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
5048 }
5049#endif
5050 continue;
5051 }
5052 /* Add a new Path to the aTo[] set */
drha18f3d22013-05-08 03:05:41 +00005053 if( nTo<mxChoice ){
drhd15cb172013-05-21 19:23:10 +00005054 /* Increase the size of the aTo set by one */
drha18f3d22013-05-08 03:05:41 +00005055 jj = nTo++;
5056 }else{
drhd15cb172013-05-21 19:23:10 +00005057 /* New path replaces the prior worst to keep count below mxChoice */
drhfde1e6b2013-09-06 17:45:42 +00005058 jj = mxI;
drha18f3d22013-05-08 03:05:41 +00005059 }
5060 pTo = &aTo[jj];
drh989578e2013-10-28 14:34:35 +00005061#ifdef WHERETRACE_ENABLED /* 0x4 */
drhae70cf12013-05-31 15:18:46 +00005062 if( sqlite3WhereTrace&0x4 ){
drhfde1e6b2013-09-06 17:45:42 +00005063 sqlite3DebugPrintf("New %s cost=%-3d,%3d order=%c\n",
5064 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
drhd15cb172013-05-21 19:23:10 +00005065 isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
5066 }
5067#endif
drhf204dac2013-05-08 03:22:07 +00005068 }else{
drhfde1e6b2013-09-06 17:45:42 +00005069 if( pTo->rCost<=rCost && pTo->nRow<=nOut ){
drh989578e2013-10-28 14:34:35 +00005070#ifdef WHERETRACE_ENABLED /* 0x4 */
drhae70cf12013-05-31 15:18:46 +00005071 if( sqlite3WhereTrace&0x4 ){
drhd15cb172013-05-21 19:23:10 +00005072 sqlite3DebugPrintf(
drhfde1e6b2013-09-06 17:45:42 +00005073 "Skip %s cost=%-3d,%3d order=%c",
5074 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
drhd15cb172013-05-21 19:23:10 +00005075 isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
drhfde1e6b2013-09-06 17:45:42 +00005076 sqlite3DebugPrintf(" vs %s cost=%-3d,%d order=%c\n",
5077 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
drhd15cb172013-05-21 19:23:10 +00005078 pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?');
5079 }
5080#endif
drh7963b0e2013-06-17 21:37:40 +00005081 testcase( pTo->rCost==rCost );
drhd15cb172013-05-21 19:23:10 +00005082 continue;
5083 }
drh7963b0e2013-06-17 21:37:40 +00005084 testcase( pTo->rCost==rCost+1 );
drhd15cb172013-05-21 19:23:10 +00005085 /* A new and better score for a previously created equivalent path */
drh989578e2013-10-28 14:34:35 +00005086#ifdef WHERETRACE_ENABLED /* 0x4 */
drhae70cf12013-05-31 15:18:46 +00005087 if( sqlite3WhereTrace&0x4 ){
drhd15cb172013-05-21 19:23:10 +00005088 sqlite3DebugPrintf(
drhfde1e6b2013-09-06 17:45:42 +00005089 "Update %s cost=%-3d,%3d order=%c",
5090 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
drhd15cb172013-05-21 19:23:10 +00005091 isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
drhfde1e6b2013-09-06 17:45:42 +00005092 sqlite3DebugPrintf(" was %s cost=%-3d,%3d order=%c\n",
5093 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
drhd15cb172013-05-21 19:23:10 +00005094 pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?');
5095 }
5096#endif
drha18f3d22013-05-08 03:05:41 +00005097 }
drh6b7157b2013-05-10 02:00:35 +00005098 /* pWLoop is a winner. Add it to the set of best so far */
drha18f3d22013-05-08 03:05:41 +00005099 pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
drh319f6772013-05-14 15:31:07 +00005100 pTo->revLoop = revMask;
drhfde1e6b2013-09-06 17:45:42 +00005101 pTo->nRow = nOut;
drha18f3d22013-05-08 03:05:41 +00005102 pTo->rCost = rCost;
drh6b7157b2013-05-10 02:00:35 +00005103 pTo->isOrderedValid = isOrderedValid;
5104 pTo->isOrdered = isOrdered;
drha18f3d22013-05-08 03:05:41 +00005105 memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
5106 pTo->aLoop[iLoop] = pWLoop;
5107 if( nTo>=mxChoice ){
drhfde1e6b2013-09-06 17:45:42 +00005108 mxI = 0;
drha18f3d22013-05-08 03:05:41 +00005109 mxCost = aTo[0].rCost;
drhfde1e6b2013-09-06 17:45:42 +00005110 mxOut = aTo[0].nRow;
drha18f3d22013-05-08 03:05:41 +00005111 for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
drhfde1e6b2013-09-06 17:45:42 +00005112 if( pTo->rCost>mxCost || (pTo->rCost==mxCost && pTo->nRow>mxOut) ){
5113 mxCost = pTo->rCost;
5114 mxOut = pTo->nRow;
5115 mxI = jj;
5116 }
drha18f3d22013-05-08 03:05:41 +00005117 }
5118 }
5119 }
5120 }
5121
drh989578e2013-10-28 14:34:35 +00005122#ifdef WHERETRACE_ENABLED /* >=2 */
drhd15cb172013-05-21 19:23:10 +00005123 if( sqlite3WhereTrace>=2 ){
drha50ef112013-05-22 02:06:59 +00005124 sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
drhd15cb172013-05-21 19:23:10 +00005125 for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
drhb8a8e8a2013-06-10 19:12:39 +00005126 sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
drha50ef112013-05-22 02:06:59 +00005127 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
drhd15cb172013-05-21 19:23:10 +00005128 pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?');
drh88da6442013-05-27 17:59:37 +00005129 if( pTo->isOrderedValid && pTo->isOrdered ){
5130 sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
5131 }else{
5132 sqlite3DebugPrintf("\n");
5133 }
drhf204dac2013-05-08 03:22:07 +00005134 }
5135 }
5136#endif
5137
drh6b7157b2013-05-10 02:00:35 +00005138 /* Swap the roles of aFrom and aTo for the next generation */
drha18f3d22013-05-08 03:05:41 +00005139 pFrom = aTo;
5140 aTo = aFrom;
5141 aFrom = pFrom;
5142 nFrom = nTo;
5143 }
5144
drh75b93402013-05-31 20:43:57 +00005145 if( nFrom==0 ){
drhe1e2e9a2013-06-13 15:16:53 +00005146 sqlite3ErrorMsg(pParse, "no query solution");
drh75b93402013-05-31 20:43:57 +00005147 sqlite3DbFree(db, pSpace);
5148 return SQLITE_ERROR;
5149 }
drha18f3d22013-05-08 03:05:41 +00005150
drh6b7157b2013-05-10 02:00:35 +00005151 /* Find the lowest cost path. pFrom will be left pointing to that path */
drha18f3d22013-05-08 03:05:41 +00005152 pFrom = aFrom;
5153 for(ii=1; ii<nFrom; ii++){
5154 if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
5155 }
5156 assert( pWInfo->nLevel==nLoop );
drh6b7157b2013-05-10 02:00:35 +00005157 /* Load the lowest cost path into pWInfo */
drha18f3d22013-05-08 03:05:41 +00005158 for(iLoop=0; iLoop<nLoop; iLoop++){
drh7ba39a92013-05-30 17:43:19 +00005159 WhereLevel *pLevel = pWInfo->a + iLoop;
5160 pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
drhe217efc2013-06-12 03:48:41 +00005161 pLevel->iFrom = pWLoop->iTab;
drh7ba39a92013-05-30 17:43:19 +00005162 pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
drha18f3d22013-05-08 03:05:41 +00005163 }
drhfd636c72013-06-21 02:05:06 +00005164 if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0
5165 && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
5166 && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
drh4f402f22013-06-11 18:59:38 +00005167 && nRowEst
5168 ){
5169 Bitmask notUsed;
drh6457a352013-06-21 00:35:37 +00005170 int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom,
drh93ec45d2013-06-17 18:20:48 +00005171 WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
drh4f402f22013-06-11 18:59:38 +00005172 if( rc==1 ) pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
5173 }
drh6b7157b2013-05-10 02:00:35 +00005174 if( pFrom->isOrdered ){
drh4f402f22013-06-11 18:59:38 +00005175 if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
5176 pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
5177 }else{
5178 pWInfo->bOBSat = 1;
5179 pWInfo->revMask = pFrom->revLoop;
5180 }
drh6b7157b2013-05-10 02:00:35 +00005181 }
drha50ef112013-05-22 02:06:59 +00005182 pWInfo->nRowOut = pFrom->nRow;
drha18f3d22013-05-08 03:05:41 +00005183
5184 /* Free temporary memory and return success */
5185 sqlite3DbFree(db, pSpace);
5186 return SQLITE_OK;
5187}
drh94a11212004-09-25 13:12:14 +00005188
5189/*
drh60c96cd2013-06-09 17:21:25 +00005190** Most queries use only a single table (they are not joins) and have
5191** simple == constraints against indexed fields. This routine attempts
5192** to plan those simple cases using much less ceremony than the
5193** general-purpose query planner, and thereby yield faster sqlite3_prepare()
5194** times for the common case.
5195**
5196** Return non-zero on success, if this query can be handled by this
5197** no-frills query planner. Return zero if this query needs the
5198** general-purpose query planner.
5199*/
drhb8a8e8a2013-06-10 19:12:39 +00005200static int whereShortCut(WhereLoopBuilder *pBuilder){
drh60c96cd2013-06-09 17:21:25 +00005201 WhereInfo *pWInfo;
5202 struct SrcList_item *pItem;
5203 WhereClause *pWC;
5204 WhereTerm *pTerm;
5205 WhereLoop *pLoop;
5206 int iCur;
drh92a121f2013-06-10 12:15:47 +00005207 int j;
drh60c96cd2013-06-09 17:21:25 +00005208 Table *pTab;
5209 Index *pIdx;
5210
5211 pWInfo = pBuilder->pWInfo;
drh5822d6f2013-06-10 23:30:09 +00005212 if( pWInfo->wctrlFlags & WHERE_FORCE_TABLE ) return 0;
drh60c96cd2013-06-09 17:21:25 +00005213 assert( pWInfo->pTabList->nSrc>=1 );
5214 pItem = pWInfo->pTabList->a;
5215 pTab = pItem->pTab;
5216 if( IsVirtual(pTab) ) return 0;
5217 if( pItem->zIndex ) return 0;
5218 iCur = pItem->iCursor;
5219 pWC = &pWInfo->sWC;
5220 pLoop = pBuilder->pNew;
drh60c96cd2013-06-09 17:21:25 +00005221 pLoop->wsFlags = 0;
drhcd8629e2013-11-13 12:27:25 +00005222 pLoop->u.btree.nSkip = 0;
drh3b75ffa2013-06-10 14:56:25 +00005223 pTerm = findTerm(pWC, iCur, -1, 0, WO_EQ, 0);
drh60c96cd2013-06-09 17:21:25 +00005224 if( pTerm ){
5225 pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
5226 pLoop->aLTerm[0] = pTerm;
5227 pLoop->nLTerm = 1;
5228 pLoop->u.btree.nEq = 1;
drhe1e2e9a2013-06-13 15:16:53 +00005229 /* TUNING: Cost of a rowid lookup is 10 */
drhbf539c42013-10-05 18:16:02 +00005230 pLoop->rRun = 33; /* 33==sqlite3LogEst(10) */
drh60c96cd2013-06-09 17:21:25 +00005231 }else{
5232 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
dancd40abb2013-08-29 10:46:05 +00005233 assert( pLoop->aLTermSpace==pLoop->aLTerm );
5234 assert( ArraySize(pLoop->aLTermSpace)==4 );
5235 if( pIdx->onError==OE_None
5236 || pIdx->pPartIdxWhere!=0
drhbbbdc832013-10-22 18:01:40 +00005237 || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace)
dancd40abb2013-08-29 10:46:05 +00005238 ) continue;
drhbbbdc832013-10-22 18:01:40 +00005239 for(j=0; j<pIdx->nKeyCol; j++){
drh3b75ffa2013-06-10 14:56:25 +00005240 pTerm = findTerm(pWC, iCur, pIdx->aiColumn[j], 0, WO_EQ, pIdx);
drh60c96cd2013-06-09 17:21:25 +00005241 if( pTerm==0 ) break;
drh60c96cd2013-06-09 17:21:25 +00005242 pLoop->aLTerm[j] = pTerm;
5243 }
drhbbbdc832013-10-22 18:01:40 +00005244 if( j!=pIdx->nKeyCol ) continue;
drh92a121f2013-06-10 12:15:47 +00005245 pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
drhec95c442013-10-23 01:57:32 +00005246 if( pIdx->isCovering || (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){
drh92a121f2013-06-10 12:15:47 +00005247 pLoop->wsFlags |= WHERE_IDX_ONLY;
5248 }
drh60c96cd2013-06-09 17:21:25 +00005249 pLoop->nLTerm = j;
5250 pLoop->u.btree.nEq = j;
5251 pLoop->u.btree.pIndex = pIdx;
drhe1e2e9a2013-06-13 15:16:53 +00005252 /* TUNING: Cost of a unique index lookup is 15 */
drhbf539c42013-10-05 18:16:02 +00005253 pLoop->rRun = 39; /* 39==sqlite3LogEst(15) */
drh60c96cd2013-06-09 17:21:25 +00005254 break;
5255 }
5256 }
drh3b75ffa2013-06-10 14:56:25 +00005257 if( pLoop->wsFlags ){
drhbf539c42013-10-05 18:16:02 +00005258 pLoop->nOut = (LogEst)1;
drh3b75ffa2013-06-10 14:56:25 +00005259 pWInfo->a[0].pWLoop = pLoop;
5260 pLoop->maskSelf = getMask(&pWInfo->sMaskSet, iCur);
5261 pWInfo->a[0].iTabCur = iCur;
5262 pWInfo->nRowOut = 1;
drh4f402f22013-06-11 18:59:38 +00005263 if( pWInfo->pOrderBy ) pWInfo->bOBSat = 1;
drh6457a352013-06-21 00:35:37 +00005264 if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
5265 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
5266 }
drh3b75ffa2013-06-10 14:56:25 +00005267#ifdef SQLITE_DEBUG
5268 pLoop->cId = '0';
5269#endif
5270 return 1;
5271 }
5272 return 0;
drh60c96cd2013-06-09 17:21:25 +00005273}
5274
5275/*
drhe3184742002-06-19 14:27:05 +00005276** Generate the beginning of the loop used for WHERE clause processing.
drhacf3b982005-01-03 01:27:18 +00005277** The return value is a pointer to an opaque structure that contains
drh75897232000-05-29 14:26:00 +00005278** information needed to terminate the loop. Later, the calling routine
danielk19774adee202004-05-08 08:23:19 +00005279** should invoke sqlite3WhereEnd() with the return value of this function
drh75897232000-05-29 14:26:00 +00005280** in order to complete the WHERE clause processing.
5281**
5282** If an error occurs, this routine returns NULL.
drhc27a1ce2002-06-14 20:58:45 +00005283**
5284** The basic idea is to do a nested loop, one loop for each table in
5285** the FROM clause of a select. (INSERT and UPDATE statements are the
5286** same as a SELECT with only a single table in the FROM clause.) For
5287** example, if the SQL is this:
5288**
5289** SELECT * FROM t1, t2, t3 WHERE ...;
5290**
5291** Then the code generated is conceptually like the following:
5292**
5293** foreach row1 in t1 do \ Code generated
danielk19774adee202004-05-08 08:23:19 +00005294** foreach row2 in t2 do |-- by sqlite3WhereBegin()
drhc27a1ce2002-06-14 20:58:45 +00005295** foreach row3 in t3 do /
5296** ...
5297** end \ Code generated
danielk19774adee202004-05-08 08:23:19 +00005298** end |-- by sqlite3WhereEnd()
drhc27a1ce2002-06-14 20:58:45 +00005299** end /
5300**
drh29dda4a2005-07-21 18:23:20 +00005301** Note that the loops might not be nested in the order in which they
5302** appear in the FROM clause if a different order is better able to make
drh51147ba2005-07-23 22:59:55 +00005303** use of indices. Note also that when the IN operator appears in
5304** the WHERE clause, it might result in additional nested loops for
5305** scanning through all values on the right-hand side of the IN.
drh29dda4a2005-07-21 18:23:20 +00005306**
drhc27a1ce2002-06-14 20:58:45 +00005307** There are Btree cursors associated with each table. t1 uses cursor
drh6a3ea0e2003-05-02 14:32:12 +00005308** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
5309** And so forth. This routine generates code to open those VDBE cursors
danielk19774adee202004-05-08 08:23:19 +00005310** and sqlite3WhereEnd() generates the code to close them.
drhc27a1ce2002-06-14 20:58:45 +00005311**
drhe6f85e72004-12-25 01:03:13 +00005312** The code that sqlite3WhereBegin() generates leaves the cursors named
5313** in pTabList pointing at their appropriate entries. The [...] code
drhf0863fe2005-06-12 21:35:51 +00005314** can use OP_Column and OP_Rowid opcodes on these cursors to extract
drhe6f85e72004-12-25 01:03:13 +00005315** data from the various tables of the loop.
5316**
drhc27a1ce2002-06-14 20:58:45 +00005317** If the WHERE clause is empty, the foreach loops must each scan their
5318** entire tables. Thus a three-way join is an O(N^3) operation. But if
5319** the tables have indices and there are terms in the WHERE clause that
5320** refer to those indices, a complete table scan can be avoided and the
5321** code will run much faster. Most of the work of this routine is checking
5322** to see if there are indices that can be used to speed up the loop.
5323**
5324** Terms of the WHERE clause are also used to limit which rows actually
5325** make it to the "..." in the middle of the loop. After each "foreach",
5326** terms of the WHERE clause that use only terms in that loop and outer
5327** loops are evaluated and if false a jump is made around all subsequent
5328** inner loops (or around the "..." if the test occurs within the inner-
5329** most loop)
5330**
5331** OUTER JOINS
5332**
5333** An outer join of tables t1 and t2 is conceptally coded as follows:
5334**
5335** foreach row1 in t1 do
5336** flag = 0
5337** foreach row2 in t2 do
5338** start:
5339** ...
5340** flag = 1
5341** end
drhe3184742002-06-19 14:27:05 +00005342** if flag==0 then
5343** move the row2 cursor to a null row
5344** goto start
5345** fi
drhc27a1ce2002-06-14 20:58:45 +00005346** end
5347**
drhe3184742002-06-19 14:27:05 +00005348** ORDER BY CLAUSE PROCESSING
5349**
drh94433422013-07-01 11:05:50 +00005350** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause
5351** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement
drhe3184742002-06-19 14:27:05 +00005352** if there is one. If there is no ORDER BY clause or if this routine
drh46ec5b62012-09-24 15:30:54 +00005353** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
drhfc8d4f92013-11-08 15:19:46 +00005354**
5355** The iIdxCur parameter is the cursor number of an index. If
5356** WHERE_ONETABLE_ONLY is set, iIdxCur is the cursor number of an index
5357** to use for OR clause processing. The WHERE clause should use this
5358** specific cursor. If WHERE_ONEPASS_DESIRED is set, then iIdxCur is
5359** the first cursor in an array of cursors for all indices. iIdxCur should
5360** be used to compute the appropriate cursor depending on which index is
5361** used.
drh75897232000-05-29 14:26:00 +00005362*/
danielk19774adee202004-05-08 08:23:19 +00005363WhereInfo *sqlite3WhereBegin(
danielk1977ed326d72004-11-16 15:50:19 +00005364 Parse *pParse, /* The parser context */
drh6457a352013-06-21 00:35:37 +00005365 SrcList *pTabList, /* FROM clause: A list of all tables to be scanned */
danielk1977ed326d72004-11-16 15:50:19 +00005366 Expr *pWhere, /* The WHERE clause */
drh46ec5b62012-09-24 15:30:54 +00005367 ExprList *pOrderBy, /* An ORDER BY clause, or NULL */
drh6457a352013-06-21 00:35:37 +00005368 ExprList *pResultSet, /* Result set of the query */
dan0efb72c2012-08-24 18:44:56 +00005369 u16 wctrlFlags, /* One of the WHERE_* flags defined in sqliteInt.h */
5370 int iIdxCur /* If WHERE_ONETABLE_ONLY is set, index cursor number */
drh75897232000-05-29 14:26:00 +00005371){
danielk1977be229652009-03-20 14:18:51 +00005372 int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
drhc01a3c12009-12-16 22:10:49 +00005373 int nTabList; /* Number of elements in pTabList */
drh75897232000-05-29 14:26:00 +00005374 WhereInfo *pWInfo; /* Will become the return value of this function */
5375 Vdbe *v = pParse->pVdbe; /* The virtual database engine */
drhfe05af82005-07-21 03:14:59 +00005376 Bitmask notReady; /* Cursors that are not yet positioned */
drh1c8148f2013-05-04 20:25:23 +00005377 WhereLoopBuilder sWLB; /* The WhereLoop builder */
drh111a6a72008-12-21 03:51:16 +00005378 WhereMaskSet *pMaskSet; /* The expression mask set */
drh56f1b992012-09-25 14:29:39 +00005379 WhereLevel *pLevel; /* A single level in pWInfo->a[] */
drhfd636c72013-06-21 02:05:06 +00005380 WhereLoop *pLoop; /* Pointer to a single WhereLoop object */
drh9cd1c992012-09-25 20:43:35 +00005381 int ii; /* Loop counter */
drh17435752007-08-16 04:30:38 +00005382 sqlite3 *db; /* Database connection */
drh5346e952013-05-08 14:14:26 +00005383 int rc; /* Return code */
drh75897232000-05-29 14:26:00 +00005384
drh56f1b992012-09-25 14:29:39 +00005385
5386 /* Variable initialization */
drhfd636c72013-06-21 02:05:06 +00005387 db = pParse->db;
drh1c8148f2013-05-04 20:25:23 +00005388 memset(&sWLB, 0, sizeof(sWLB));
drh1c8148f2013-05-04 20:25:23 +00005389 sWLB.pOrderBy = pOrderBy;
drh56f1b992012-09-25 14:29:39 +00005390
drhfd636c72013-06-21 02:05:06 +00005391 /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
5392 ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
5393 if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
5394 wctrlFlags &= ~WHERE_WANT_DISTINCT;
5395 }
5396
drh29dda4a2005-07-21 18:23:20 +00005397 /* The number of tables in the FROM clause is limited by the number of
drh1398ad32005-01-19 23:24:50 +00005398 ** bits in a Bitmask
5399 */
drh67ae0cb2010-04-08 14:38:51 +00005400 testcase( pTabList->nSrc==BMS );
drh29dda4a2005-07-21 18:23:20 +00005401 if( pTabList->nSrc>BMS ){
5402 sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
drh1398ad32005-01-19 23:24:50 +00005403 return 0;
5404 }
5405
drhc01a3c12009-12-16 22:10:49 +00005406 /* This function normally generates a nested loop for all tables in
5407 ** pTabList. But if the WHERE_ONETABLE_ONLY flag is set, then we should
5408 ** only generate code for the first table in pTabList and assume that
5409 ** any cursors associated with subsequent tables are uninitialized.
5410 */
5411 nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
5412
drh75897232000-05-29 14:26:00 +00005413 /* Allocate and initialize the WhereInfo structure that will become the
danielk1977be229652009-03-20 14:18:51 +00005414 ** return value. A single allocation is used to store the WhereInfo
5415 ** struct, the contents of WhereInfo.a[], the WhereClause structure
5416 ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
5417 ** field (type Bitmask) it must be aligned on an 8-byte boundary on
5418 ** some architectures. Hence the ROUND8() below.
drh75897232000-05-29 14:26:00 +00005419 */
drhc01a3c12009-12-16 22:10:49 +00005420 nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
drh60c96cd2013-06-09 17:21:25 +00005421 pWInfo = sqlite3DbMallocZero(db, nByteWInfo + sizeof(WhereLoop));
drh17435752007-08-16 04:30:38 +00005422 if( db->mallocFailed ){
drh8b307fb2010-04-06 15:57:05 +00005423 sqlite3DbFree(db, pWInfo);
5424 pWInfo = 0;
danielk197785574e32008-10-06 05:32:18 +00005425 goto whereBeginError;
drh75897232000-05-29 14:26:00 +00005426 }
drhfc8d4f92013-11-08 15:19:46 +00005427 pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1;
drhc01a3c12009-12-16 22:10:49 +00005428 pWInfo->nLevel = nTabList;
drh75897232000-05-29 14:26:00 +00005429 pWInfo->pParse = pParse;
5430 pWInfo->pTabList = pTabList;
drh6b7157b2013-05-10 02:00:35 +00005431 pWInfo->pOrderBy = pOrderBy;
drh6457a352013-06-21 00:35:37 +00005432 pWInfo->pResultSet = pResultSet;
danielk19774adee202004-05-08 08:23:19 +00005433 pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
drh6df2acd2008-12-28 16:55:25 +00005434 pWInfo->wctrlFlags = wctrlFlags;
drh8b307fb2010-04-06 15:57:05 +00005435 pWInfo->savedNQueryLoop = pParse->nQueryLoop;
drh70d18342013-06-06 19:16:33 +00005436 pMaskSet = &pWInfo->sMaskSet;
drh1c8148f2013-05-04 20:25:23 +00005437 sWLB.pWInfo = pWInfo;
drh70d18342013-06-06 19:16:33 +00005438 sWLB.pWC = &pWInfo->sWC;
drh1ac87e12013-07-18 14:50:56 +00005439 sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);
5440 assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) );
drh60c96cd2013-06-09 17:21:25 +00005441 whereLoopInit(sWLB.pNew);
drhb8a8e8a2013-06-10 19:12:39 +00005442#ifdef SQLITE_DEBUG
5443 sWLB.pNew->cId = '*';
5444#endif
drh08192d52002-04-30 19:20:28 +00005445
drh111a6a72008-12-21 03:51:16 +00005446 /* Split the WHERE clause into separate subexpressions where each
5447 ** subexpression is separated by an AND operator.
5448 */
5449 initMaskSet(pMaskSet);
drh70d18342013-06-06 19:16:33 +00005450 whereClauseInit(&pWInfo->sWC, pWInfo);
drh39759742013-08-02 23:40:45 +00005451 whereSplit(&pWInfo->sWC, pWhere, TK_AND);
drh111a6a72008-12-21 03:51:16 +00005452
drh08192d52002-04-30 19:20:28 +00005453 /* Special case: a WHERE clause that is constant. Evaluate the
5454 ** expression and either jump over all of the code or fall thru.
5455 */
drh759e8582014-01-02 21:05:10 +00005456 for(ii=0; ii<sWLB.pWC->nTerm; ii++){
5457 if( nTabList==0 || sqlite3ExprIsConstantNotJoin(sWLB.pWC->a[ii].pExpr) ){
5458 sqlite3ExprIfFalse(pParse, sWLB.pWC->a[ii].pExpr, pWInfo->iBreak,
5459 SQLITE_JUMPIFNULL);
5460 sWLB.pWC->a[ii].wtFlags |= TERM_CODED;
5461 }
drh08192d52002-04-30 19:20:28 +00005462 }
drh75897232000-05-29 14:26:00 +00005463
drh4fe425a2013-06-12 17:08:06 +00005464 /* Special case: No FROM clause
5465 */
5466 if( nTabList==0 ){
5467 if( pOrderBy ) pWInfo->bOBSat = 1;
drh6457a352013-06-21 00:35:37 +00005468 if( wctrlFlags & WHERE_WANT_DISTINCT ){
5469 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
5470 }
drh4fe425a2013-06-12 17:08:06 +00005471 }
5472
drh42165be2008-03-26 14:56:34 +00005473 /* Assign a bit from the bitmask to every term in the FROM clause.
5474 **
5475 ** When assigning bitmask values to FROM clause cursors, it must be
5476 ** the case that if X is the bitmask for the N-th FROM clause term then
5477 ** the bitmask for all FROM clause terms to the left of the N-th term
5478 ** is (X-1). An expression from the ON clause of a LEFT JOIN can use
5479 ** its Expr.iRightJoinTable value to find the bitmask of the right table
5480 ** of the join. Subtracting one from the right table bitmask gives a
5481 ** bitmask for all tables to the left of the join. Knowing the bitmask
5482 ** for all tables to the left of a left join is important. Ticket #3015.
danielk1977e672c8e2009-05-22 15:43:26 +00005483 **
drhc01a3c12009-12-16 22:10:49 +00005484 ** Note that bitmasks are created for all pTabList->nSrc tables in
5485 ** pTabList, not just the first nTabList tables. nTabList is normally
5486 ** equal to pTabList->nSrc but might be shortened to 1 if the
5487 ** WHERE_ONETABLE_ONLY flag is set.
drh42165be2008-03-26 14:56:34 +00005488 */
drh9cd1c992012-09-25 20:43:35 +00005489 for(ii=0; ii<pTabList->nSrc; ii++){
5490 createMask(pMaskSet, pTabList->a[ii].iCursor);
drh42165be2008-03-26 14:56:34 +00005491 }
5492#ifndef NDEBUG
5493 {
5494 Bitmask toTheLeft = 0;
drh9cd1c992012-09-25 20:43:35 +00005495 for(ii=0; ii<pTabList->nSrc; ii++){
5496 Bitmask m = getMask(pMaskSet, pTabList->a[ii].iCursor);
drh42165be2008-03-26 14:56:34 +00005497 assert( (m-1)==toTheLeft );
5498 toTheLeft |= m;
5499 }
5500 }
5501#endif
5502
drh29dda4a2005-07-21 18:23:20 +00005503 /* Analyze all of the subexpressions. Note that exprAnalyze() might
5504 ** add new virtual terms onto the end of the WHERE clause. We do not
5505 ** want to analyze these virtual terms, so start analyzing at the end
drhb6fb62d2005-09-20 08:47:20 +00005506 ** and work forward so that the added virtual terms are never processed.
drh75897232000-05-29 14:26:00 +00005507 */
drh70d18342013-06-06 19:16:33 +00005508 exprAnalyzeAll(pTabList, &pWInfo->sWC);
drh17435752007-08-16 04:30:38 +00005509 if( db->mallocFailed ){
danielk197785574e32008-10-06 05:32:18 +00005510 goto whereBeginError;
drh0bbaa1b2005-08-19 19:14:12 +00005511 }
drh75897232000-05-29 14:26:00 +00005512
drh4f402f22013-06-11 18:59:38 +00005513 /* If the ORDER BY (or GROUP BY) clause contains references to general
5514 ** expressions, then we won't be able to satisfy it using indices, so
5515 ** go ahead and disable it now.
5516 */
drh6457a352013-06-21 00:35:37 +00005517 if( pOrderBy && (wctrlFlags & WHERE_WANT_DISTINCT)!=0 ){
drh4f402f22013-06-11 18:59:38 +00005518 for(ii=0; ii<pOrderBy->nExpr; ii++){
5519 Expr *pExpr = sqlite3ExprSkipCollate(pOrderBy->a[ii].pExpr);
5520 if( pExpr->op!=TK_COLUMN ){
5521 pWInfo->pOrderBy = pOrderBy = 0;
5522 break;
drhe217efc2013-06-12 03:48:41 +00005523 }else if( pExpr->iColumn<0 ){
5524 break;
drh4f402f22013-06-11 18:59:38 +00005525 }
5526 }
5527 }
5528
drh6457a352013-06-21 00:35:37 +00005529 if( wctrlFlags & WHERE_WANT_DISTINCT ){
5530 if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){
5531 /* The DISTINCT marking is pointless. Ignore it. */
drh4f402f22013-06-11 18:59:38 +00005532 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
5533 }else if( pOrderBy==0 ){
drh6457a352013-06-21 00:35:37 +00005534 /* Try to ORDER BY the result set to make distinct processing easier */
drh4f402f22013-06-11 18:59:38 +00005535 pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
drh6457a352013-06-21 00:35:37 +00005536 pWInfo->pOrderBy = pResultSet;
drh4f402f22013-06-11 18:59:38 +00005537 }
dan38cc40c2011-06-30 20:17:15 +00005538 }
5539
drhf1b5f5b2013-05-02 00:15:01 +00005540 /* Construct the WhereLoop objects */
drh3b48e8c2013-06-12 20:18:16 +00005541 WHERETRACE(0xffff,("*** Optimizer Start ***\n"));
drhf4e9cb02013-10-28 19:59:59 +00005542 /* Display all terms of the WHERE clause */
5543#if defined(WHERETRACE_ENABLED) && defined(SQLITE_ENABLE_TREE_EXPLAIN)
5544 if( sqlite3WhereTrace & 0x100 ){
5545 int i;
5546 Vdbe *v = pParse->pVdbe;
5547 sqlite3ExplainBegin(v);
5548 for(i=0; i<sWLB.pWC->nTerm; i++){
drh7afc8b02013-10-28 22:33:36 +00005549 sqlite3ExplainPrintf(v, "#%-2d ", i);
drhf4e9cb02013-10-28 19:59:59 +00005550 sqlite3ExplainPush(v);
5551 whereExplainTerm(v, &sWLB.pWC->a[i]);
5552 sqlite3ExplainPop(v);
5553 sqlite3ExplainNL(v);
5554 }
5555 sqlite3ExplainFinish(v);
5556 sqlite3DebugPrintf("%s", sqlite3VdbeExplanation(v));
5557 }
5558#endif
drhb8a8e8a2013-06-10 19:12:39 +00005559 if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
drh60c96cd2013-06-09 17:21:25 +00005560 rc = whereLoopAddAll(&sWLB);
5561 if( rc ) goto whereBeginError;
5562
5563 /* Display all of the WhereLoop objects if wheretrace is enabled */
drh989578e2013-10-28 14:34:35 +00005564#ifdef WHERETRACE_ENABLED /* !=0 */
drh60c96cd2013-06-09 17:21:25 +00005565 if( sqlite3WhereTrace ){
5566 WhereLoop *p;
drhfd636c72013-06-21 02:05:06 +00005567 int i;
drh60c96cd2013-06-09 17:21:25 +00005568 static char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
5569 "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
drhfd636c72013-06-21 02:05:06 +00005570 for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
5571 p->cId = zLabel[i%sizeof(zLabel)];
drhc1ba2e72013-10-28 19:03:21 +00005572 whereLoopPrint(p, sWLB.pWC);
drh60c96cd2013-06-09 17:21:25 +00005573 }
5574 }
5575#endif
5576
drh4f402f22013-06-11 18:59:38 +00005577 wherePathSolver(pWInfo, 0);
drh60c96cd2013-06-09 17:21:25 +00005578 if( db->mallocFailed ) goto whereBeginError;
5579 if( pWInfo->pOrderBy ){
drhc7f0d222013-06-19 03:27:12 +00005580 wherePathSolver(pWInfo, pWInfo->nRowOut+1);
drh60c96cd2013-06-09 17:21:25 +00005581 if( db->mallocFailed ) goto whereBeginError;
drha18f3d22013-05-08 03:05:41 +00005582 }
5583 }
drh60c96cd2013-06-09 17:21:25 +00005584 if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
drhd84ce352013-06-04 18:27:41 +00005585 pWInfo->revMask = (Bitmask)(-1);
drha50ef112013-05-22 02:06:59 +00005586 }
drh81186b42013-06-18 01:52:41 +00005587 if( pParse->nErr || NEVER(db->mallocFailed) ){
drh75b93402013-05-31 20:43:57 +00005588 goto whereBeginError;
5589 }
drh989578e2013-10-28 14:34:35 +00005590#ifdef WHERETRACE_ENABLED /* !=0 */
drha18f3d22013-05-08 03:05:41 +00005591 if( sqlite3WhereTrace ){
5592 int ii;
drh4f402f22013-06-11 18:59:38 +00005593 sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
5594 if( pWInfo->bOBSat ){
5595 sqlite3DebugPrintf(" ORDERBY=0x%llx", pWInfo->revMask);
drh319f6772013-05-14 15:31:07 +00005596 }
drh4f402f22013-06-11 18:59:38 +00005597 switch( pWInfo->eDistinct ){
5598 case WHERE_DISTINCT_UNIQUE: {
5599 sqlite3DebugPrintf(" DISTINCT=unique");
5600 break;
5601 }
5602 case WHERE_DISTINCT_ORDERED: {
5603 sqlite3DebugPrintf(" DISTINCT=ordered");
5604 break;
5605 }
5606 case WHERE_DISTINCT_UNORDERED: {
5607 sqlite3DebugPrintf(" DISTINCT=unordered");
5608 break;
5609 }
5610 }
5611 sqlite3DebugPrintf("\n");
drhfd636c72013-06-21 02:05:06 +00005612 for(ii=0; ii<pWInfo->nLevel; ii++){
drhc1ba2e72013-10-28 19:03:21 +00005613 whereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC);
drhf1b5f5b2013-05-02 00:15:01 +00005614 }
5615 }
5616#endif
drhfd636c72013-06-21 02:05:06 +00005617 /* Attempt to omit tables from the join that do not effect the result */
drh1031bd92013-06-22 15:44:26 +00005618 if( pWInfo->nLevel>=2
5619 && pResultSet!=0
5620 && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
5621 ){
drhfd636c72013-06-21 02:05:06 +00005622 Bitmask tabUsed = exprListTableUsage(pMaskSet, pResultSet);
drh67a5ec72013-09-03 14:03:47 +00005623 if( sWLB.pOrderBy ) tabUsed |= exprListTableUsage(pMaskSet, sWLB.pOrderBy);
drhfd636c72013-06-21 02:05:06 +00005624 while( pWInfo->nLevel>=2 ){
drh9d5a5792013-06-28 13:43:33 +00005625 WhereTerm *pTerm, *pEnd;
drhfd636c72013-06-21 02:05:06 +00005626 pLoop = pWInfo->a[pWInfo->nLevel-1].pWLoop;
drhbc71b1d2013-06-21 02:15:48 +00005627 if( (pWInfo->pTabList->a[pLoop->iTab].jointype & JT_LEFT)==0 ) break;
5628 if( (wctrlFlags & WHERE_WANT_DISTINCT)==0
5629 && (pLoop->wsFlags & WHERE_ONEROW)==0
drhfd636c72013-06-21 02:05:06 +00005630 ){
drhfd636c72013-06-21 02:05:06 +00005631 break;
5632 }
drhbc71b1d2013-06-21 02:15:48 +00005633 if( (tabUsed & pLoop->maskSelf)!=0 ) break;
drh9d5a5792013-06-28 13:43:33 +00005634 pEnd = sWLB.pWC->a + sWLB.pWC->nTerm;
5635 for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
5636 if( (pTerm->prereqAll & pLoop->maskSelf)!=0
5637 && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
5638 ){
5639 break;
5640 }
5641 }
5642 if( pTerm<pEnd ) break;
drhbc71b1d2013-06-21 02:15:48 +00005643 WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId));
5644 pWInfo->nLevel--;
5645 nTabList--;
drhfd636c72013-06-21 02:05:06 +00005646 }
5647 }
drh3b48e8c2013-06-12 20:18:16 +00005648 WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
drh8e23daf2013-06-11 13:30:04 +00005649 pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
drhf1b5f5b2013-05-02 00:15:01 +00005650
drh08c88eb2008-04-10 13:33:18 +00005651 /* If the caller is an UPDATE or DELETE statement that is requesting
5652 ** to use a one-pass algorithm, determine if this is appropriate.
drh24b7fe92013-09-30 19:33:06 +00005653 ** The one-pass algorithm only works if the WHERE clause constrains
drh08c88eb2008-04-10 13:33:18 +00005654 ** the statement to update a single row.
5655 */
drh165be382008-12-05 02:36:33 +00005656 assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
drh3b48e8c2013-06-12 20:18:16 +00005657 if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
5658 && (pWInfo->a[0].pWLoop->wsFlags & WHERE_ONEROW)!=0 ){
drh08c88eb2008-04-10 13:33:18 +00005659 pWInfo->okOnePass = 1;
drh702ba9f2013-11-07 21:25:13 +00005660 if( HasRowid(pTabList->a[0].pTab) ){
5661 pWInfo->a[0].pWLoop->wsFlags &= ~WHERE_IDX_ONLY;
5662 }
drh08c88eb2008-04-10 13:33:18 +00005663 }
drheb04de32013-05-10 15:16:30 +00005664
drh9012bcb2004-12-19 00:11:35 +00005665 /* Open all tables in the pTabList and any indices selected for
5666 ** searching those tables.
5667 */
drh8b307fb2010-04-06 15:57:05 +00005668 notReady = ~(Bitmask)0;
drh9cd1c992012-09-25 20:43:35 +00005669 for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
danielk1977da184232006-01-05 11:34:32 +00005670 Table *pTab; /* Table to open */
danielk1977da184232006-01-05 11:34:32 +00005671 int iDb; /* Index of database containing table/index */
drh56f1b992012-09-25 14:29:39 +00005672 struct SrcList_item *pTabItem;
drh9012bcb2004-12-19 00:11:35 +00005673
drh29dda4a2005-07-21 18:23:20 +00005674 pTabItem = &pTabList->a[pLevel->iFrom];
drh9012bcb2004-12-19 00:11:35 +00005675 pTab = pTabItem->pTab;
danielk1977595a5232009-07-24 17:58:53 +00005676 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
drh7ba39a92013-05-30 17:43:19 +00005677 pLoop = pLevel->pWLoop;
drh424aab82010-04-06 18:28:20 +00005678 if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
drh75bb9f52010-04-06 18:51:42 +00005679 /* Do nothing */
5680 }else
drh9eff6162006-06-12 21:59:13 +00005681#ifndef SQLITE_OMIT_VIRTUALTABLE
drh7ba39a92013-05-30 17:43:19 +00005682 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
danielk1977595a5232009-07-24 17:58:53 +00005683 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
danielk197793626f42006-06-20 13:07:27 +00005684 int iCur = pTabItem->iCursor;
danielk1977595a5232009-07-24 17:58:53 +00005685 sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
drhfc5e5462012-12-03 17:04:40 +00005686 }else if( IsVirtual(pTab) ){
5687 /* noop */
drh9eff6162006-06-12 21:59:13 +00005688 }else
5689#endif
drh7ba39a92013-05-30 17:43:19 +00005690 if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
drh9ef61f42011-10-07 14:40:59 +00005691 && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){
drhfc8d4f92013-11-08 15:19:46 +00005692 int op = OP_OpenRead;
5693 if( pWInfo->okOnePass ){
5694 op = OP_OpenWrite;
5695 pWInfo->aiCurOnePass[0] = pTabItem->iCursor;
5696 };
drh08c88eb2008-04-10 13:33:18 +00005697 sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
drhfc8d4f92013-11-08 15:19:46 +00005698 assert( pTabItem->iCursor==pLevel->iTabCur );
drh7963b0e2013-06-17 21:37:40 +00005699 testcase( !pWInfo->okOnePass && pTab->nCol==BMS-1 );
5700 testcase( !pWInfo->okOnePass && pTab->nCol==BMS );
drhdd9930e2013-10-23 23:37:02 +00005701 if( !pWInfo->okOnePass && pTab->nCol<BMS && HasRowid(pTab) ){
danielk19779792eef2006-01-13 15:58:43 +00005702 Bitmask b = pTabItem->colUsed;
5703 int n = 0;
drh74161702006-02-24 02:53:49 +00005704 for(; b; b=b>>1, n++){}
drh8cff69d2009-11-12 19:59:44 +00005705 sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
5706 SQLITE_INT_TO_PTR(n), P4_INT32);
danielk19779792eef2006-01-13 15:58:43 +00005707 assert( n<=pTab->nCol );
5708 }
danielk1977c00da102006-01-07 13:21:04 +00005709 }else{
5710 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
drh9012bcb2004-12-19 00:11:35 +00005711 }
drh7e47cb82013-05-31 17:55:27 +00005712 if( pLoop->wsFlags & WHERE_INDEXED ){
drh7ba39a92013-05-30 17:43:19 +00005713 Index *pIx = pLoop->u.btree.pIndex;
drhfc8d4f92013-11-08 15:19:46 +00005714 int iIndexCur;
5715 int op = OP_OpenRead;
drh4308e342013-11-11 16:55:52 +00005716 /* iIdxCur is always set if to a positive value if ONEPASS is possible */
5717 assert( iIdxCur!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 );
5718 if( pWInfo->okOnePass ){
drhfc8d4f92013-11-08 15:19:46 +00005719 Index *pJ = pTabItem->pTab->pIndex;
5720 iIndexCur = iIdxCur;
5721 assert( wctrlFlags & WHERE_ONEPASS_DESIRED );
5722 while( ALWAYS(pJ) && pJ!=pIx ){
5723 iIndexCur++;
5724 pJ = pJ->pNext;
5725 }
5726 op = OP_OpenWrite;
5727 pWInfo->aiCurOnePass[1] = iIndexCur;
5728 }else if( iIdxCur && (wctrlFlags & WHERE_ONETABLE_ONLY)!=0 ){
5729 iIndexCur = iIdxCur;
5730 }else{
5731 iIndexCur = pParse->nTab++;
5732 }
5733 pLevel->iIdxCur = iIndexCur;
danielk1977da184232006-01-05 11:34:32 +00005734 assert( pIx->pSchema==pTab->pSchema );
drhb0367fb2012-08-25 02:11:13 +00005735 assert( iIndexCur>=0 );
drhfc8d4f92013-11-08 15:19:46 +00005736 sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb);
drh2ec2fb22013-11-06 19:59:23 +00005737 sqlite3VdbeSetP4KeyInfo(pParse, pIx);
danielk1977207872a2008-01-03 07:54:23 +00005738 VdbeComment((v, "%s", pIx->zName));
drh9012bcb2004-12-19 00:11:35 +00005739 }
drhaceb31b2014-02-08 01:40:27 +00005740 if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb);
drh70d18342013-06-06 19:16:33 +00005741 notReady &= ~getMask(&pWInfo->sMaskSet, pTabItem->iCursor);
drh9012bcb2004-12-19 00:11:35 +00005742 }
5743 pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
drha21a64d2010-04-06 22:33:55 +00005744 if( db->mallocFailed ) goto whereBeginError;
drh9012bcb2004-12-19 00:11:35 +00005745
drh29dda4a2005-07-21 18:23:20 +00005746 /* Generate the code to do the search. Each iteration of the for
5747 ** loop below generates code for a single nested loop of the VM
5748 ** program.
drh75897232000-05-29 14:26:00 +00005749 */
drhfe05af82005-07-21 03:14:59 +00005750 notReady = ~(Bitmask)0;
drh9cd1c992012-09-25 20:43:35 +00005751 for(ii=0; ii<nTabList; ii++){
5752 pLevel = &pWInfo->a[ii];
drhcc04afd2013-08-22 02:56:28 +00005753#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
5754 if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){
5755 constructAutomaticIndex(pParse, &pWInfo->sWC,
5756 &pTabList->a[pLevel->iFrom], notReady, pLevel);
5757 if( db->mallocFailed ) goto whereBeginError;
5758 }
5759#endif
drh9cd1c992012-09-25 20:43:35 +00005760 explainOneScan(pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags);
drhcc04afd2013-08-22 02:56:28 +00005761 pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
drh70d18342013-06-06 19:16:33 +00005762 notReady = codeOneLoopStart(pWInfo, ii, notReady);
dan4a07e3d2010-11-09 14:48:59 +00005763 pWInfo->iContinue = pLevel->addrCont;
drh75897232000-05-29 14:26:00 +00005764 }
drh7ec764a2005-07-21 03:48:20 +00005765
drh6fa978d2013-05-30 19:29:19 +00005766 /* Done. */
drh6bc69a22013-11-19 12:33:23 +00005767 VdbeModuleComment((v, "Begin WHERE-core"));
drh75897232000-05-29 14:26:00 +00005768 return pWInfo;
drhe23399f2005-07-22 00:31:39 +00005769
5770 /* Jump here if malloc fails */
danielk197785574e32008-10-06 05:32:18 +00005771whereBeginError:
drh8b307fb2010-04-06 15:57:05 +00005772 if( pWInfo ){
5773 pParse->nQueryLoop = pWInfo->savedNQueryLoop;
5774 whereInfoFree(db, pWInfo);
5775 }
drhe23399f2005-07-22 00:31:39 +00005776 return 0;
drh75897232000-05-29 14:26:00 +00005777}
5778
5779/*
drhc27a1ce2002-06-14 20:58:45 +00005780** Generate the end of the WHERE loop. See comments on
danielk19774adee202004-05-08 08:23:19 +00005781** sqlite3WhereBegin() for additional information.
drh75897232000-05-29 14:26:00 +00005782*/
danielk19774adee202004-05-08 08:23:19 +00005783void sqlite3WhereEnd(WhereInfo *pWInfo){
drh633e6d52008-07-28 19:34:53 +00005784 Parse *pParse = pWInfo->pParse;
5785 Vdbe *v = pParse->pVdbe;
drh19a775c2000-06-05 18:54:46 +00005786 int i;
drh6b563442001-11-07 16:48:26 +00005787 WhereLevel *pLevel;
drh7ba39a92013-05-30 17:43:19 +00005788 WhereLoop *pLoop;
drhad3cab52002-05-24 02:04:32 +00005789 SrcList *pTabList = pWInfo->pTabList;
drh633e6d52008-07-28 19:34:53 +00005790 sqlite3 *db = pParse->db;
drh19a775c2000-06-05 18:54:46 +00005791
drh9012bcb2004-12-19 00:11:35 +00005792 /* Generate loop termination code.
5793 */
drh6bc69a22013-11-19 12:33:23 +00005794 VdbeModuleComment((v, "End WHERE-core"));
drhceea3322009-04-23 13:22:42 +00005795 sqlite3ExprCacheClear(pParse);
drhc01a3c12009-12-16 22:10:49 +00005796 for(i=pWInfo->nLevel-1; i>=0; i--){
drhcd8629e2013-11-13 12:27:25 +00005797 int addr;
drh6b563442001-11-07 16:48:26 +00005798 pLevel = &pWInfo->a[i];
drh7ba39a92013-05-30 17:43:19 +00005799 pLoop = pLevel->pWLoop;
drhb3190c12008-12-08 21:37:14 +00005800 sqlite3VdbeResolveLabel(v, pLevel->addrCont);
drh6b563442001-11-07 16:48:26 +00005801 if( pLevel->op!=OP_Noop ){
drhe39a7322014-02-03 14:04:11 +00005802 sqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3);
drhd1d38482008-10-07 23:46:38 +00005803 sqlite3VdbeChangeP5(v, pLevel->p5);
drh688852a2014-02-17 22:40:43 +00005804 VdbeCoverage(v);
drh19a775c2000-06-05 18:54:46 +00005805 }
drh7ba39a92013-05-30 17:43:19 +00005806 if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
drh72e8fa42007-03-28 14:30:06 +00005807 struct InLoop *pIn;
drhe23399f2005-07-22 00:31:39 +00005808 int j;
drhb3190c12008-12-08 21:37:14 +00005809 sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
drh111a6a72008-12-21 03:51:16 +00005810 for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
drhb3190c12008-12-08 21:37:14 +00005811 sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
drh2d96b932013-02-08 18:48:23 +00005812 sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
drh688852a2014-02-17 22:40:43 +00005813 VdbeCoverage(v);
drhb3190c12008-12-08 21:37:14 +00005814 sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
drhe23399f2005-07-22 00:31:39 +00005815 }
drh111a6a72008-12-21 03:51:16 +00005816 sqlite3DbFree(db, pLevel->u.in.aInLoop);
drhd99f7062002-06-08 23:25:08 +00005817 }
drhb3190c12008-12-08 21:37:14 +00005818 sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
drhcd8629e2013-11-13 12:27:25 +00005819 if( pLevel->addrSkip ){
drhcd8629e2013-11-13 12:27:25 +00005820 sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrSkip);
drhe084f402013-11-13 17:24:38 +00005821 VdbeComment((v, "next skip-scan on %s", pLoop->u.btree.pIndex->zName));
drh2e5ef4e2013-11-13 16:58:54 +00005822 sqlite3VdbeJumpHere(v, pLevel->addrSkip);
5823 sqlite3VdbeJumpHere(v, pLevel->addrSkip-2);
drhcd8629e2013-11-13 12:27:25 +00005824 }
drhad2d8302002-05-24 20:31:36 +00005825 if( pLevel->iLeftJoin ){
drh688852a2014-02-17 22:40:43 +00005826 addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v);
drh7ba39a92013-05-30 17:43:19 +00005827 assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
5828 || (pLoop->wsFlags & WHERE_INDEXED)!=0 );
5829 if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 ){
drh35451c62009-11-12 04:26:39 +00005830 sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
5831 }
drh76f4cfb2013-05-31 18:20:52 +00005832 if( pLoop->wsFlags & WHERE_INDEXED ){
drh3c84ddf2008-01-09 02:15:38 +00005833 sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
drh7f09b3e2002-08-13 13:15:49 +00005834 }
drh336a5302009-04-24 15:46:21 +00005835 if( pLevel->op==OP_Return ){
5836 sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
5837 }else{
5838 sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
5839 }
drhd654be82005-09-20 17:42:23 +00005840 sqlite3VdbeJumpHere(v, addr);
drhad2d8302002-05-24 20:31:36 +00005841 }
drh6bc69a22013-11-19 12:33:23 +00005842 VdbeModuleComment((v, "End WHERE-loop%d: %s", i,
drhfc8d4f92013-11-08 15:19:46 +00005843 pWInfo->pTabList->a[pLevel->iFrom].pTab->zName));
drh19a775c2000-06-05 18:54:46 +00005844 }
drh9012bcb2004-12-19 00:11:35 +00005845
5846 /* The "break" point is here, just past the end of the outer loop.
5847 ** Set it.
5848 */
danielk19774adee202004-05-08 08:23:19 +00005849 sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
drh9012bcb2004-12-19 00:11:35 +00005850
drhfd636c72013-06-21 02:05:06 +00005851 assert( pWInfo->nLevel<=pTabList->nSrc );
drhc01a3c12009-12-16 22:10:49 +00005852 for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
drh5f612292014-02-08 23:20:32 +00005853 int k, last;
5854 VdbeOp *pOp;
danbfca6a42012-08-24 10:52:35 +00005855 Index *pIdx = 0;
drh29dda4a2005-07-21 18:23:20 +00005856 struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
drh9012bcb2004-12-19 00:11:35 +00005857 Table *pTab = pTabItem->pTab;
drh5cf590c2003-04-24 01:45:04 +00005858 assert( pTab!=0 );
drh7ba39a92013-05-30 17:43:19 +00005859 pLoop = pLevel->pWLoop;
drhfc8d4f92013-11-08 15:19:46 +00005860
drh5f612292014-02-08 23:20:32 +00005861 /* For a co-routine, change all OP_Column references to the table of
5862 ** the co-routine into OP_SCopy of result contained in a register.
5863 ** OP_Rowid becomes OP_Null.
5864 */
5865 if( pTabItem->viaCoroutine ){
5866 last = sqlite3VdbeCurrentAddr(v);
5867 k = pLevel->addrBody;
5868 pOp = sqlite3VdbeGetOp(v, k);
5869 for(; k<last; k++, pOp++){
5870 if( pOp->p1!=pLevel->iTabCur ) continue;
5871 if( pOp->opcode==OP_Column ){
5872 pOp->opcode = OP_SCopy;
5873 pOp->p1 = pOp->p2 + pTabItem->regResult;
5874 pOp->p2 = pOp->p3;
5875 pOp->p3 = 0;
5876 }else if( pOp->opcode==OP_Rowid ){
5877 pOp->opcode = OP_Null;
5878 pOp->p1 = 0;
5879 pOp->p3 = 0;
5880 }
5881 }
5882 continue;
5883 }
5884
drhfc8d4f92013-11-08 15:19:46 +00005885 /* Close all of the cursors that were opened by sqlite3WhereBegin.
5886 ** Except, do not close cursors that will be reused by the OR optimization
5887 ** (WHERE_OMIT_OPEN_CLOSE). And do not close the OP_OpenWrite cursors
5888 ** created for the ONEPASS optimization.
5889 */
drh4139c992010-04-07 14:59:45 +00005890 if( (pTab->tabFlags & TF_Ephemeral)==0
5891 && pTab->pSelect==0
drh9ef61f42011-10-07 14:40:59 +00005892 && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
drh4139c992010-04-07 14:59:45 +00005893 ){
drh7ba39a92013-05-30 17:43:19 +00005894 int ws = pLoop->wsFlags;
drh8b307fb2010-04-06 15:57:05 +00005895 if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
drh6df2acd2008-12-28 16:55:25 +00005896 sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
5897 }
drhfc8d4f92013-11-08 15:19:46 +00005898 if( (ws & WHERE_INDEXED)!=0
5899 && (ws & (WHERE_IPK|WHERE_AUTO_INDEX))==0
5900 && pLevel->iIdxCur!=pWInfo->aiCurOnePass[1]
5901 ){
drh6df2acd2008-12-28 16:55:25 +00005902 sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
5903 }
drh9012bcb2004-12-19 00:11:35 +00005904 }
5905
drhf0030762013-06-14 13:27:01 +00005906 /* If this scan uses an index, make VDBE code substitutions to read data
5907 ** from the index instead of from the table where possible. In some cases
5908 ** this optimization prevents the table from ever being read, which can
5909 ** yield a significant performance boost.
drh9012bcb2004-12-19 00:11:35 +00005910 **
5911 ** Calls to the code generator in between sqlite3WhereBegin and
5912 ** sqlite3WhereEnd will have created code that references the table
5913 ** directly. This loop scans all that code looking for opcodes
5914 ** that reference the table and converts them into opcodes that
5915 ** reference the index.
5916 */
drh7ba39a92013-05-30 17:43:19 +00005917 if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
5918 pIdx = pLoop->u.btree.pIndex;
5919 }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
drhd40e2082012-08-24 23:24:15 +00005920 pIdx = pLevel->u.pCovidx;
danbfca6a42012-08-24 10:52:35 +00005921 }
drh7ba39a92013-05-30 17:43:19 +00005922 if( pIdx && !db->mallocFailed ){
drh9012bcb2004-12-19 00:11:35 +00005923 last = sqlite3VdbeCurrentAddr(v);
drhcc04afd2013-08-22 02:56:28 +00005924 k = pLevel->addrBody;
5925 pOp = sqlite3VdbeGetOp(v, k);
5926 for(; k<last; k++, pOp++){
drh9012bcb2004-12-19 00:11:35 +00005927 if( pOp->p1!=pLevel->iTabCur ) continue;
5928 if( pOp->opcode==OP_Column ){
drhee0ec8e2013-10-31 17:38:01 +00005929 int x = pOp->p2;
drh511717c2013-11-08 17:13:23 +00005930 assert( pIdx->pTable==pTab );
drhee0ec8e2013-10-31 17:38:01 +00005931 if( !HasRowid(pTab) ){
5932 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
5933 x = pPk->aiColumn[x];
5934 }
5935 x = sqlite3ColumnOfIndex(pIdx, x);
drh44156282013-10-23 22:23:03 +00005936 if( x>=0 ){
5937 pOp->p2 = x;
5938 pOp->p1 = pLevel->iIdxCur;
drh9012bcb2004-12-19 00:11:35 +00005939 }
drh44156282013-10-23 22:23:03 +00005940 assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || x>=0 );
drhf0863fe2005-06-12 21:35:51 +00005941 }else if( pOp->opcode==OP_Rowid ){
drh9012bcb2004-12-19 00:11:35 +00005942 pOp->p1 = pLevel->iIdxCur;
drhf0863fe2005-06-12 21:35:51 +00005943 pOp->opcode = OP_IdxRowid;
drh9012bcb2004-12-19 00:11:35 +00005944 }
5945 }
drh6b563442001-11-07 16:48:26 +00005946 }
drh19a775c2000-06-05 18:54:46 +00005947 }
drh9012bcb2004-12-19 00:11:35 +00005948
5949 /* Final cleanup
5950 */
drhf12cde52010-04-08 17:28:00 +00005951 pParse->nQueryLoop = pWInfo->savedNQueryLoop;
5952 whereInfoFree(db, pWInfo);
drh75897232000-05-29 14:26:00 +00005953 return;
5954}