~ubuntu-branches/ubuntu/precise/sqlite3/precise-updates

« back to all changes in this revision

Viewing changes to src/where.c

  • Committer: Bazaar Package Importer
  • Author(s): Laszlo Boszormenyi (GCS)
  • Date: 2009-12-11 14:34:09 UTC
  • mfrom: (9.1.7 squeeze)
  • Revision ID: james.westby@ubuntu.com-20091211143409-o29fahwmcmyd0vq1
Tags: 3.6.21-2
Run autoreconf to prevent FTBFS with new libtool (closes: #560660).

Show diffs side-by-side

added added

removed removed

Lines of Context:
15
15
** rows.  Indices are selected and used to speed the search when doing
16
16
** so is applicable.  Because this module is responsible for selecting
17
17
** indices, you might also think of this module as the "query optimizer".
18
 
**
19
 
** $Id: where.c,v 1.408 2009/06/16 14:15:22 shane Exp $
20
18
*/
21
19
#include "sqliteInt.h"
22
20
 
195
193
  WherePlan plan;    /* The lookup strategy */
196
194
  double rCost;      /* Overall cost of pursuing this search strategy */
197
195
  double nRow;       /* Estimated number of output rows */
 
196
  Bitmask used;      /* Bitmask of cursors used by this plan */
198
197
};
199
198
 
200
199
/*
624
623
static int isLikeOrGlob(
625
624
  Parse *pParse,    /* Parsing and code generating context */
626
625
  Expr *pExpr,      /* Test this expression */
627
 
  int *pnPattern,   /* Number of non-wildcard prefix characters */
 
626
  Expr **ppPrefix,  /* Pointer to TK_STRING expression with pattern prefix */
628
627
  int *pisComplete, /* True if the only wildcard is % in the last character */
629
628
  int *pnoCase      /* True if uppercase is equivalent to lowercase */
630
629
){
631
 
  const char *z;             /* String on RHS of LIKE operator */
 
630
  const char *z = 0;         /* String on RHS of LIKE operator */
632
631
  Expr *pRight, *pLeft;      /* Right and left size of LIKE operator */
633
632
  ExprList *pList;           /* List of operands to the LIKE operator */
634
633
  int c;                     /* One character in z[] */
636
635
  char wc[3];                /* Wildcard characters */
637
636
  CollSeq *pColl;            /* Collating sequence for LHS */
638
637
  sqlite3 *db = pParse->db;  /* Database connection */
 
638
  sqlite3_value *pVal = 0;
 
639
  int op;                    /* Opcode of pRight */
639
640
 
640
641
  if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
641
642
    return 0;
644
645
  if( *pnoCase ) return 0;
645
646
#endif
646
647
  pList = pExpr->x.pList;
647
 
  pRight = pList->a[0].pExpr;
648
 
  if( pRight->op!=TK_STRING ){
649
 
    return 0;
650
 
  }
651
648
  pLeft = pList->a[1].pExpr;
652
 
  if( pLeft->op!=TK_COLUMN ){
 
649
  if( pLeft->op!=TK_COLUMN || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT ){
 
650
    /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
 
651
    ** be the name of an indexed column with TEXT affinity. */
653
652
    return 0;
654
653
  }
 
654
  assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
655
655
  pColl = sqlite3ExprCollSeq(pParse, pLeft);
656
 
  assert( pColl!=0 || pLeft->iColumn==-1 );
657
 
  if( pColl==0 ) return 0;
 
656
  assert( pColl!=0 );  /* Every non-IPK column has a collating sequence */
658
657
  if( (pColl->type!=SQLITE_COLL_BINARY || *pnoCase) &&
659
658
      (pColl->type!=SQLITE_COLL_NOCASE || !*pnoCase) ){
 
659
    /* IMP: R-09003-32046 For the GLOB operator, the column must use the
 
660
    ** default BINARY collating sequence.
 
661
    ** IMP: R-41408-28306 For the LIKE operator, if case_sensitive_like mode
 
662
    ** is enabled then the column must use the default BINARY collating
 
663
    ** sequence, or if case_sensitive_like mode is disabled then the column
 
664
    ** must use the built-in NOCASE collating sequence.
 
665
    */
660
666
    return 0;
661
667
  }
662
 
  if( sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT ) return 0;
663
 
  z = pRight->u.zToken;
664
 
  if( ALWAYS(z) ){
 
668
 
 
669
  pRight = pList->a[0].pExpr;
 
670
  op = pRight->op;
 
671
  if( op==TK_REGISTER ){
 
672
    op = pRight->op2;
 
673
  }
 
674
  if( op==TK_VARIABLE ){
 
675
    Vdbe *pReprepare = pParse->pReprepare;
 
676
    pVal = sqlite3VdbeGetValue(pReprepare, pRight->iColumn, SQLITE_AFF_NONE);
 
677
    if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
 
678
      z = (char *)sqlite3_value_text(pVal);
 
679
    }
 
680
    sqlite3VdbeSetVarmask(pParse->pVdbe, pRight->iColumn);
 
681
    assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
 
682
  }else if( op==TK_STRING ){
 
683
    z = pRight->u.zToken;
 
684
  }
 
685
  if( z ){
665
686
    cnt = 0;
666
687
    while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
667
688
      cnt++;
668
689
    }
669
690
    if( cnt!=0 && c!=0 && 255!=(u8)z[cnt-1] ){
 
691
      Expr *pPrefix;
670
692
      *pisComplete = z[cnt]==wc[0] && z[cnt+1]==0;
671
 
      *pnPattern = cnt;
672
 
      return 1;
 
693
      pPrefix = sqlite3Expr(db, TK_STRING, z);
 
694
      if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
 
695
      *ppPrefix = pPrefix;
 
696
      if( op==TK_VARIABLE ){
 
697
        Vdbe *v = pParse->pVdbe;
 
698
        sqlite3VdbeSetVarmask(v, pRight->iColumn);
 
699
        if( *pisComplete && pRight->u.zToken[1] ){
 
700
          /* If the rhs of the LIKE expression is a variable, and the current
 
701
          ** value of the variable means there is no need to invoke the LIKE
 
702
          ** function, then no OP_Variable will be added to the program.
 
703
          ** This causes problems for the sqlite3_bind_parameter_name()
 
704
          ** API. To workaround them, add a dummy OP_Variable here.
 
705
          */ 
 
706
          int r1 = sqlite3GetTempReg(pParse);
 
707
          sqlite3ExprCodeTarget(pParse, pRight, r1);
 
708
          sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
 
709
          sqlite3ReleaseTempReg(pParse, r1);
 
710
        }
 
711
      }
 
712
    }else{
 
713
      z = 0;
673
714
    }
674
715
  }
675
 
  return 0;
 
716
 
 
717
  sqlite3ValueFree(pVal);
 
718
  return (z!=0);
676
719
}
677
720
#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
678
721
 
1053
1096
  Expr *pExpr;                     /* The expression to be analyzed */
1054
1097
  Bitmask prereqLeft;              /* Prerequesites of the pExpr->pLeft */
1055
1098
  Bitmask prereqAll;               /* Prerequesites of pExpr */
1056
 
  Bitmask extraRight = 0;
1057
 
  int nPattern;
1058
 
  int isComplete;
1059
 
  int noCase;
 
1099
  Bitmask extraRight = 0;          /* */
 
1100
  Expr *pStr1 = 0;                 /* RHS of LIKE/GLOB operator */
 
1101
  int isComplete = 0;              /* RHS of LIKE/GLOB ends with wildcard */
 
1102
  int noCase = 0;                  /* LIKE/GLOB distinguishes case */
1060
1103
  int op;                          /* Top-level operator.  pExpr->op */
1061
1104
  Parse *pParse = pWC->pParse;     /* Parsing context */
1062
1105
  sqlite3 *db = pParse->db;        /* Database connection */
1176
1219
  else if( pExpr->op==TK_OR ){
1177
1220
    assert( pWC->op==TK_AND );
1178
1221
    exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
 
1222
    pTerm = &pWC->a[idxTerm];
1179
1223
  }
1180
1224
#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
1181
1225
 
1190
1234
  ** The last character of the prefix "abc" is incremented to form the
1191
1235
  ** termination condition "abd".
1192
1236
  */
1193
 
  if( isLikeOrGlob(pParse, pExpr, &nPattern, &isComplete, &noCase)
1194
 
         && pWC->op==TK_AND ){
1195
 
    Expr *pLeft, *pRight;
1196
 
    Expr *pStr1, *pStr2;
1197
 
    Expr *pNewExpr1, *pNewExpr2;
1198
 
    int idxNew1, idxNew2;
 
1237
  if( pWC->op==TK_AND 
 
1238
   && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
 
1239
  ){
 
1240
    Expr *pLeft;       /* LHS of LIKE/GLOB operator */
 
1241
    Expr *pStr2;       /* Copy of pStr1 - RHS of LIKE/GLOB operator */
 
1242
    Expr *pNewExpr1;
 
1243
    Expr *pNewExpr2;
 
1244
    int idxNew1;
 
1245
    int idxNew2;
1199
1246
 
1200
1247
    pLeft = pExpr->x.pList->a[1].pExpr;
1201
 
    pRight = pExpr->x.pList->a[0].pExpr;
1202
 
    pStr1 = sqlite3Expr(db, TK_STRING, pRight->u.zToken);
1203
 
    if( pStr1 ) pStr1->u.zToken[nPattern] = 0;
1204
1248
    pStr2 = sqlite3ExprDup(db, pStr1, 0);
1205
1249
    if( !db->mallocFailed ){
1206
1250
      u8 c, *pC;       /* Last character before the first wildcard */
1207
 
      pC = (u8*)&pStr2->u.zToken[nPattern-1];
 
1251
      pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
1208
1252
      c = *pC;
1209
1253
      if( noCase ){
1210
1254
        /* The point is to increment the last character before the first
1337
1381
  nTerm = pOrderBy->nExpr;
1338
1382
  assert( nTerm>0 );
1339
1383
 
 
1384
  /* Argument pIdx must either point to a 'real' named index structure, 
 
1385
  ** or an index structure allocated on the stack by bestBtreeIndex() to
 
1386
  ** represent the rowid index that is part of every table.  */
 
1387
  assert( pIdx->zName || (pIdx->nColumn==1 && pIdx->aiColumn[0]==-1) );
 
1388
 
1340
1389
  /* Match terms of the ORDER BY clause against columns of
1341
1390
  ** the index.
1342
1391
  **
1363
1412
    if( !pColl ){
1364
1413
      pColl = db->pDfltColl;
1365
1414
    }
1366
 
    if( i<pIdx->nColumn ){
 
1415
    if( pIdx->zName && i<pIdx->nColumn ){
1367
1416
      iColumn = pIdx->aiColumn[i];
1368
1417
      if( iColumn==pIdx->pTable->iPKey ){
1369
1418
        iColumn = -1;
1392
1441
        return 0;
1393
1442
      }
1394
1443
    }
1395
 
    assert( pIdx->aSortOrder!=0 );
 
1444
    assert( pIdx->aSortOrder!=0 || iColumn==-1 );
1396
1445
    assert( pTerm->sortOrder==0 || pTerm->sortOrder==1 );
1397
1446
    assert( iSortOrder==0 || iSortOrder==1 );
1398
1447
    termSortOrder = iSortOrder ^ pTerm->sortOrder;
1436
1485
}
1437
1486
 
1438
1487
/*
1439
 
** Check table to see if the ORDER BY clause in pOrderBy can be satisfied
1440
 
** by sorting in order of ROWID.  Return true if so and set *pbRev to be
1441
 
** true for reverse ROWID and false for forward ROWID order.
1442
 
*/
1443
 
static int sortableByRowid(
1444
 
  int base,               /* Cursor number for table to be sorted */
1445
 
  ExprList *pOrderBy,     /* The ORDER BY clause */
1446
 
  WhereMaskSet *pMaskSet, /* Mapping from table cursors to bitmaps */
1447
 
  int *pbRev              /* Set to 1 if ORDER BY is DESC */
1448
 
){
1449
 
  Expr *p;
1450
 
 
1451
 
  assert( pOrderBy!=0 );
1452
 
  assert( pOrderBy->nExpr>0 );
1453
 
  p = pOrderBy->a[0].pExpr;
1454
 
  if( p->op==TK_COLUMN && p->iTable==base && p->iColumn==-1
1455
 
    && !referencesOtherTables(pOrderBy, pMaskSet, 1, base) ){
1456
 
    *pbRev = pOrderBy->a[0].sortOrder;
1457
 
    return 1;
1458
 
  }
1459
 
  return 0;
1460
 
}
1461
 
 
1462
 
/*
1463
1488
** Prepare a crude estimate of the logarithm of the input value.
1464
1489
** The results need not be exact.  This is only used for estimating
1465
1490
** the total cost of performing operations with O(logN) or O(NlogN)
1559
1584
      int flags = WHERE_MULTI_OR;
1560
1585
      double rTotal = 0;
1561
1586
      double nRow = 0;
 
1587
      Bitmask used = 0;
1562
1588
 
1563
1589
      for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
1564
1590
        WhereCost sTermCost;
1581
1607
        }
1582
1608
        rTotal += sTermCost.rCost;
1583
1609
        nRow += sTermCost.nRow;
 
1610
        used |= sTermCost.used;
1584
1611
        if( rTotal>=pCost->rCost ) break;
1585
1612
      }
1586
1613
 
1598
1625
      if( rTotal<pCost->rCost ){
1599
1626
        pCost->rCost = rTotal;
1600
1627
        pCost->nRow = nRow;
 
1628
        pCost->used = used;
1601
1629
        pCost->plan.wsFlags = flags;
1602
1630
        pCost->plan.u.pTerm = pTerm;
1603
1631
      }
1726
1754
** that this is required.
1727
1755
*/
1728
1756
static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
1729
 
  sqlite3_vtab *pVtab = pTab->pVtab;
 
1757
  sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
1730
1758
  int i;
1731
1759
  int rc;
1732
1760
 
1823
1851
  ** sqlite3ViewGetColumnNames() would have picked up the error. 
1824
1852
  */
1825
1853
  assert( pTab->azModuleArg && pTab->azModuleArg[0] );
1826
 
  assert( pTab->pVtab );
 
1854
  assert( sqlite3GetVTable(pParse->db, pTab) );
1827
1855
 
1828
1856
  /* Set the aConstraint[].usable fields and initialize all 
1829
1857
  ** output variables to zero.
1850
1878
  for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
1851
1879
    j = pIdxCons->iTermOffset;
1852
1880
    pTerm = &pWC->a[j];
1853
 
    pIdxCons->usable =  (pTerm->prereqRight & notReady)==0 ?1:0;
 
1881
    pIdxCons->usable = (pTerm->prereqRight&notReady) ? 0 : 1;
1854
1882
  }
1855
1883
  memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
1856
1884
  if( pIdxInfo->needToFreeIdxStr ){
1871
1899
    return;
1872
1900
  }
1873
1901
 
 
1902
  pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
 
1903
  for(i=0; i<pIdxInfo->nConstraint; i++){
 
1904
    if( pUsage[i].argvIndex>0 ){
 
1905
      pCost->used |= pWC->a[pIdxCons[i].iTermOffset].prereqRight;
 
1906
    }
 
1907
  }
 
1908
 
1874
1909
  /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
1875
1910
  ** inital value of lowestCost in this loop. If it is, then the
1876
1911
  ** (cost<lowestCost) test below will never be true.
1898
1933
#endif /* SQLITE_OMIT_VIRTUALTABLE */
1899
1934
 
1900
1935
/*
 
1936
** Argument pIdx is a pointer to an index structure that has an array of
 
1937
** SQLITE_INDEX_SAMPLES evenly spaced samples of the first indexed column
 
1938
** stored in Index.aSample. The domain of values stored in said column
 
1939
** may be thought of as divided into (SQLITE_INDEX_SAMPLES+1) regions.
 
1940
** Region 0 contains all values smaller than the first sample value. Region
 
1941
** 1 contains values larger than or equal to the value of the first sample,
 
1942
** but smaller than the value of the second. And so on.
 
1943
**
 
1944
** If successful, this function determines which of the regions value 
 
1945
** pVal lies in, sets *piRegion to the region index (a value between 0
 
1946
** and SQLITE_INDEX_SAMPLES+1, inclusive) and returns SQLITE_OK.
 
1947
** Or, if an OOM occurs while converting text values between encodings,
 
1948
** SQLITE_NOMEM is returned and *piRegion is undefined.
 
1949
*/
 
1950
#ifdef SQLITE_ENABLE_STAT2
 
1951
static int whereRangeRegion(
 
1952
  Parse *pParse,              /* Database connection */
 
1953
  Index *pIdx,                /* Index to consider domain of */
 
1954
  sqlite3_value *pVal,        /* Value to consider */
 
1955
  int *piRegion               /* OUT: Region of domain in which value lies */
 
1956
){
 
1957
  if( ALWAYS(pVal) ){
 
1958
    IndexSample *aSample = pIdx->aSample;
 
1959
    int i = 0;
 
1960
    int eType = sqlite3_value_type(pVal);
 
1961
 
 
1962
    if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
 
1963
      double r = sqlite3_value_double(pVal);
 
1964
      for(i=0; i<SQLITE_INDEX_SAMPLES; i++){
 
1965
        if( aSample[i].eType==SQLITE_NULL ) continue;
 
1966
        if( aSample[i].eType>=SQLITE_TEXT || aSample[i].u.r>r ) break;
 
1967
      }
 
1968
    }else{ 
 
1969
      sqlite3 *db = pParse->db;
 
1970
      CollSeq *pColl;
 
1971
      const u8 *z;
 
1972
      int n;
 
1973
 
 
1974
      /* pVal comes from sqlite3ValueFromExpr() so the type cannot be NULL */
 
1975
      assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
 
1976
 
 
1977
      if( eType==SQLITE_BLOB ){
 
1978
        z = (const u8 *)sqlite3_value_blob(pVal);
 
1979
        pColl = db->pDfltColl;
 
1980
        assert( pColl->enc==SQLITE_UTF8 );
 
1981
      }else{
 
1982
        pColl = sqlite3GetCollSeq(db, SQLITE_UTF8, 0, *pIdx->azColl);
 
1983
        if( pColl==0 ){
 
1984
          sqlite3ErrorMsg(pParse, "no such collation sequence: %s",
 
1985
                          *pIdx->azColl);
 
1986
          return SQLITE_ERROR;
 
1987
        }
 
1988
        z = (const u8 *)sqlite3ValueText(pVal, pColl->enc);
 
1989
        if( !z ){
 
1990
          return SQLITE_NOMEM;
 
1991
        }
 
1992
        assert( z && pColl && pColl->xCmp );
 
1993
      }
 
1994
      n = sqlite3ValueBytes(pVal, pColl->enc);
 
1995
 
 
1996
      for(i=0; i<SQLITE_INDEX_SAMPLES; i++){
 
1997
        int r;
 
1998
        int eSampletype = aSample[i].eType;
 
1999
        if( eSampletype==SQLITE_NULL || eSampletype<eType ) continue;
 
2000
        if( (eSampletype!=eType) ) break;
 
2001
#ifndef SQLITE_OMIT_UTF16
 
2002
        if( pColl->enc!=SQLITE_UTF8 ){
 
2003
          int nSample;
 
2004
          char *zSample = sqlite3Utf8to16(
 
2005
              db, pColl->enc, aSample[i].u.z, aSample[i].nByte, &nSample
 
2006
          );
 
2007
          if( !zSample ){
 
2008
            assert( db->mallocFailed );
 
2009
            return SQLITE_NOMEM;
 
2010
          }
 
2011
          r = pColl->xCmp(pColl->pUser, nSample, zSample, n, z);
 
2012
          sqlite3DbFree(db, zSample);
 
2013
        }else
 
2014
#endif
 
2015
        {
 
2016
          r = pColl->xCmp(pColl->pUser, aSample[i].nByte, aSample[i].u.z, n, z);
 
2017
        }
 
2018
        if( r>0 ) break;
 
2019
      }
 
2020
    }
 
2021
 
 
2022
    assert( i>=0 && i<=SQLITE_INDEX_SAMPLES );
 
2023
    *piRegion = i;
 
2024
  }
 
2025
  return SQLITE_OK;
 
2026
}
 
2027
#endif   /* #ifdef SQLITE_ENABLE_STAT2 */
 
2028
 
 
2029
/*
 
2030
** If expression pExpr represents a literal value, set *pp to point to
 
2031
** an sqlite3_value structure containing the same value, with affinity
 
2032
** aff applied to it, before returning. It is the responsibility of the 
 
2033
** caller to eventually release this structure by passing it to 
 
2034
** sqlite3ValueFree().
 
2035
**
 
2036
** If the current parse is a recompile (sqlite3Reprepare()) and pExpr
 
2037
** is an SQL variable that currently has a non-NULL value bound to it,
 
2038
** create an sqlite3_value structure containing this value, again with
 
2039
** affinity aff applied to it, instead.
 
2040
**
 
2041
** If neither of the above apply, set *pp to NULL.
 
2042
**
 
2043
** If an error occurs, return an error code. Otherwise, SQLITE_OK.
 
2044
*/
 
2045
#ifdef SQLITE_ENABLE_STAT2
 
2046
static int valueFromExpr(
 
2047
  Parse *pParse, 
 
2048
  Expr *pExpr, 
 
2049
  u8 aff, 
 
2050
  sqlite3_value **pp
 
2051
){
 
2052
  /* The evalConstExpr() function will have already converted any TK_VARIABLE
 
2053
  ** expression involved in an comparison into a TK_REGISTER. */
 
2054
  assert( pExpr->op!=TK_VARIABLE );
 
2055
  if( pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE ){
 
2056
    int iVar = pExpr->iColumn;
 
2057
    sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);
 
2058
    *pp = sqlite3VdbeGetValue(pParse->pReprepare, iVar, aff);
 
2059
    return SQLITE_OK;
 
2060
  }
 
2061
  return sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, aff, pp);
 
2062
}
 
2063
#endif
 
2064
 
 
2065
/*
 
2066
** This function is used to estimate the number of rows that will be visited
 
2067
** by scanning an index for a range of values. The range may have an upper
 
2068
** bound, a lower bound, or both. The WHERE clause terms that set the upper
 
2069
** and lower bounds are represented by pLower and pUpper respectively. For
 
2070
** example, assuming that index p is on t1(a):
 
2071
**
 
2072
**   ... FROM t1 WHERE a > ? AND a < ? ...
 
2073
**                    |_____|   |_____|
 
2074
**                       |         |
 
2075
**                     pLower    pUpper
 
2076
**
 
2077
** If either of the upper or lower bound is not present, then NULL is passed in
 
2078
** place of the corresponding WhereTerm.
 
2079
**
 
2080
** The nEq parameter is passed the index of the index column subject to the
 
2081
** range constraint. Or, equivalently, the number of equality constraints
 
2082
** optimized by the proposed index scan. For example, assuming index p is
 
2083
** on t1(a, b), and the SQL query is:
 
2084
**
 
2085
**   ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
 
2086
**
 
2087
** then nEq should be passed the value 1 (as the range restricted column,
 
2088
** b, is the second left-most column of the index). Or, if the query is:
 
2089
**
 
2090
**   ... FROM t1 WHERE a > ? AND a < ? ...
 
2091
**
 
2092
** then nEq should be passed 0.
 
2093
**
 
2094
** The returned value is an integer between 1 and 100, inclusive. A return
 
2095
** value of 1 indicates that the proposed range scan is expected to visit
 
2096
** approximately 1/100th (1%) of the rows selected by the nEq equality
 
2097
** constraints (if any). A return value of 100 indicates that it is expected
 
2098
** that the range scan will visit every row (100%) selected by the equality
 
2099
** constraints.
 
2100
**
 
2101
** In the absence of sqlite_stat2 ANALYZE data, each range inequality
 
2102
** reduces the search space by 2/3rds.  Hence a single constraint (x>?)
 
2103
** results in a return of 33 and a range constraint (x>? AND x<?) results
 
2104
** in a return of 11.
 
2105
*/
 
2106
static int whereRangeScanEst(
 
2107
  Parse *pParse,       /* Parsing & code generating context */
 
2108
  Index *p,            /* The index containing the range-compared column; "x" */
 
2109
  int nEq,             /* index into p->aCol[] of the range-compared column */
 
2110
  WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
 
2111
  WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
 
2112
  int *piEst           /* OUT: Return value */
 
2113
){
 
2114
  int rc = SQLITE_OK;
 
2115
 
 
2116
#ifdef SQLITE_ENABLE_STAT2
 
2117
 
 
2118
  if( nEq==0 && p->aSample ){
 
2119
    sqlite3_value *pLowerVal = 0;
 
2120
    sqlite3_value *pUpperVal = 0;
 
2121
    int iEst;
 
2122
    int iLower = 0;
 
2123
    int iUpper = SQLITE_INDEX_SAMPLES;
 
2124
    u8 aff = p->pTable->aCol[p->aiColumn[0]].affinity;
 
2125
 
 
2126
    if( pLower ){
 
2127
      Expr *pExpr = pLower->pExpr->pRight;
 
2128
      rc = valueFromExpr(pParse, pExpr, aff, &pLowerVal);
 
2129
    }
 
2130
    if( rc==SQLITE_OK && pUpper ){
 
2131
      Expr *pExpr = pUpper->pExpr->pRight;
 
2132
      rc = valueFromExpr(pParse, pExpr, aff, &pUpperVal);
 
2133
    }
 
2134
 
 
2135
    if( rc!=SQLITE_OK || (pLowerVal==0 && pUpperVal==0) ){
 
2136
      sqlite3ValueFree(pLowerVal);
 
2137
      sqlite3ValueFree(pUpperVal);
 
2138
      goto range_est_fallback;
 
2139
    }else if( pLowerVal==0 ){
 
2140
      rc = whereRangeRegion(pParse, p, pUpperVal, &iUpper);
 
2141
      if( pLower ) iLower = iUpper/2;
 
2142
    }else if( pUpperVal==0 ){
 
2143
      rc = whereRangeRegion(pParse, p, pLowerVal, &iLower);
 
2144
      if( pUpper ) iUpper = (iLower + SQLITE_INDEX_SAMPLES + 1)/2;
 
2145
    }else{
 
2146
      rc = whereRangeRegion(pParse, p, pUpperVal, &iUpper);
 
2147
      if( rc==SQLITE_OK ){
 
2148
        rc = whereRangeRegion(pParse, p, pLowerVal, &iLower);
 
2149
      }
 
2150
    }
 
2151
 
 
2152
    iEst = iUpper - iLower;
 
2153
    testcase( iEst==SQLITE_INDEX_SAMPLES );
 
2154
    assert( iEst<=SQLITE_INDEX_SAMPLES );
 
2155
    if( iEst<1 ){
 
2156
      iEst = 1;
 
2157
    }
 
2158
 
 
2159
    sqlite3ValueFree(pLowerVal);
 
2160
    sqlite3ValueFree(pUpperVal);
 
2161
    *piEst = (iEst * 100)/SQLITE_INDEX_SAMPLES;
 
2162
    return rc;
 
2163
  }
 
2164
range_est_fallback:
 
2165
#else
 
2166
  UNUSED_PARAMETER(pParse);
 
2167
  UNUSED_PARAMETER(p);
 
2168
  UNUSED_PARAMETER(nEq);
 
2169
#endif
 
2170
  assert( pLower || pUpper );
 
2171
  if( pLower && pUpper ){
 
2172
    *piEst = 11;
 
2173
  }else{
 
2174
    *piEst = 33;
 
2175
  }
 
2176
  return rc;
 
2177
}
 
2178
 
 
2179
 
 
2180
/*
1901
2181
** Find the query plan for accessing a particular table.  Write the
1902
2182
** best query plan and its cost into the WhereCost object supplied as the
1903
2183
** last parameter.
1933
2213
  ExprList *pOrderBy,         /* The ORDER BY clause */
1934
2214
  WhereCost *pCost            /* Lowest cost query plan */
1935
2215
){
1936
 
  WhereTerm *pTerm;           /* A single term of the WHERE clause */
1937
2216
  int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
1938
2217
  Index *pProbe;              /* An index we are evaluating */
1939
 
  int rev;                    /* True to scan in reverse order */
1940
 
  int wsFlags;                /* Flags associated with pProbe */
1941
 
  int nEq;                    /* Number of == or IN constraints */
1942
 
  int eqTermMask;             /* Mask of valid equality operators */
1943
 
  double cost;                /* Cost of using pProbe */
1944
 
  double nRow;                /* Estimated number of rows in result set */
1945
 
  int i;                      /* Loop counter */
1946
 
 
1947
 
  WHERETRACE(("bestIndex: tbl=%s notReady=%llx\n", pSrc->pTab->zName,notReady));
1948
 
  pProbe = pSrc->pTab->pIndex;
1949
 
  if( pSrc->notIndexed ){
1950
 
    pProbe = 0;
1951
 
  }
1952
 
 
1953
 
  /* If the table has no indices and there are no terms in the where
1954
 
  ** clause that refer to the ROWID, then we will never be able to do
1955
 
  ** anything other than a full table scan on this table.  We might as
1956
 
  ** well put it first in the join order.  That way, perhaps it can be
1957
 
  ** referenced by other tables in the join.
1958
 
  */
 
2218
  Index *pIdx;                /* Copy of pProbe, or zero for IPK index */
 
2219
  int eqTermMask;             /* Current mask of valid equality operators */
 
2220
  int idxEqTermMask;          /* Index mask of valid equality operators */
 
2221
  Index sPk;                  /* A fake index object for the primary key */
 
2222
  unsigned int aiRowEstPk[2]; /* The aiRowEst[] value for the sPk index */
 
2223
  int aiColumnPk = -1;        /* The aColumn[] value for the sPk index */
 
2224
  int wsFlagMask;             /* Allowed flags in pCost->plan.wsFlag */
 
2225
 
 
2226
  /* Initialize the cost to a worst-case value */
1959
2227
  memset(pCost, 0, sizeof(*pCost));
1960
 
  if( pProbe==0 &&
1961
 
     findTerm(pWC, iCur, -1, 0, WO_EQ|WO_IN|WO_LT|WO_LE|WO_GT|WO_GE,0)==0 &&
1962
 
     (pOrderBy==0 || !sortableByRowid(iCur, pOrderBy, pWC->pMaskSet, &rev)) ){
1963
 
     if( pParse->db->flags & SQLITE_ReverseOrder ){
1964
 
      /* For application testing, randomly reverse the output order for
1965
 
      ** SELECT statements that omit the ORDER BY clause.  This will help
1966
 
      ** to find cases where
1967
 
      */
1968
 
      pCost->plan.wsFlags |= WHERE_REVERSE;
1969
 
    }
1970
 
    return;
1971
 
  }
1972
2228
  pCost->rCost = SQLITE_BIG_DBL;
1973
2229
 
1974
 
  /* Check for a rowid=EXPR or rowid IN (...) constraints. If there was
1975
 
  ** an INDEXED BY clause attached to this table, skip this step.
1976
 
  */
1977
 
  if( !pSrc->pIndex ){
1978
 
    pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
1979
 
    if( pTerm ){
1980
 
      Expr *pExpr;
1981
 
      pCost->plan.wsFlags = WHERE_ROWID_EQ;
1982
 
      if( pTerm->eOperator & WO_EQ ){
1983
 
        /* Rowid== is always the best pick.  Look no further.  Because only
1984
 
        ** a single row is generated, output is always in sorted order */
1985
 
        pCost->plan.wsFlags = WHERE_ROWID_EQ | WHERE_UNIQUE;
1986
 
        pCost->plan.nEq = 1;
1987
 
        WHERETRACE(("... best is rowid\n"));
1988
 
        pCost->rCost = 0;
1989
 
        pCost->nRow = 1;
1990
 
        return;
1991
 
      }else if( !ExprHasProperty((pExpr = pTerm->pExpr), EP_xIsSelect) 
1992
 
             && pExpr->x.pList 
1993
 
      ){
1994
 
        /* Rowid IN (LIST): cost is NlogN where N is the number of list
1995
 
        ** elements.  */
1996
 
        pCost->rCost = pCost->nRow = pExpr->x.pList->nExpr;
1997
 
        pCost->rCost *= estLog(pCost->rCost);
1998
 
      }else{
1999
 
        /* Rowid IN (SELECT): cost is NlogN where N is the number of rows
2000
 
        ** in the result of the inner select.  We have no way to estimate
2001
 
        ** that value so make a wild guess. */
2002
 
        pCost->nRow = 100;
2003
 
        pCost->rCost = 200;
2004
 
      }
2005
 
      WHERETRACE(("... rowid IN cost: %.9g\n", pCost->rCost));
2006
 
    }
2007
 
  
2008
 
    /* Estimate the cost of a table scan.  If we do not know how many
2009
 
    ** entries are in the table, use 1 million as a guess.
2010
 
    */
2011
 
    cost = pProbe ? pProbe->aiRowEst[0] : 1000000;
2012
 
    WHERETRACE(("... table scan base cost: %.9g\n", cost));
2013
 
    wsFlags = WHERE_ROWID_RANGE;
2014
 
  
2015
 
    /* Check for constraints on a range of rowids in a table scan.
2016
 
    */
2017
 
    pTerm = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE|WO_GT|WO_GE, 0);
2018
 
    if( pTerm ){
2019
 
      if( findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0) ){
2020
 
        wsFlags |= WHERE_TOP_LIMIT;
2021
 
        cost /= 3;  /* Guess that rowid<EXPR eliminates two-thirds of rows */
2022
 
      }
2023
 
      if( findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0) ){
2024
 
        wsFlags |= WHERE_BTM_LIMIT;
2025
 
        cost /= 3;  /* Guess that rowid>EXPR eliminates two-thirds of rows */
2026
 
      }
2027
 
      WHERETRACE(("... rowid range reduces cost to %.9g\n", cost));
2028
 
    }else{
2029
 
      wsFlags = 0;
2030
 
    }
2031
 
    nRow = cost;
2032
 
  
2033
 
    /* If the table scan does not satisfy the ORDER BY clause, increase
2034
 
    ** the cost by NlogN to cover the expense of sorting. */
2035
 
    if( pOrderBy ){
2036
 
      if( sortableByRowid(iCur, pOrderBy, pWC->pMaskSet, &rev) ){
2037
 
        wsFlags |= WHERE_ORDERBY|WHERE_ROWID_RANGE;
2038
 
        if( rev ){
2039
 
          wsFlags |= WHERE_REVERSE;
2040
 
        }
2041
 
      }else{
2042
 
        cost += cost*estLog(cost);
2043
 
        WHERETRACE(("... sorting increases cost to %.9g\n", cost));
2044
 
      }
2045
 
    }else if( pParse->db->flags & SQLITE_ReverseOrder ){
2046
 
      /* For application testing, randomly reverse the output order for
2047
 
      ** SELECT statements that omit the ORDER BY clause.  This will help
2048
 
      ** to find cases where
2049
 
      */
2050
 
      wsFlags |= WHERE_REVERSE;
2051
 
    }
2052
 
 
2053
 
    /* Remember this case if it is the best so far */
2054
 
    if( cost<pCost->rCost ){
2055
 
      pCost->rCost = cost;
2056
 
      pCost->nRow = nRow;
2057
 
      pCost->plan.wsFlags = wsFlags;
2058
 
    }
2059
 
  }
2060
 
 
2061
 
  bestOrClauseIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost);
2062
 
 
2063
2230
  /* If the pSrc table is the right table of a LEFT JOIN then we may not
2064
2231
  ** use an index to satisfy IS NULL constraints on that table.  This is
2065
2232
  ** because columns might end up being NULL if the table does not match -
2066
2233
  ** a circumstance which the index cannot help us discover.  Ticket #2177.
2067
2234
  */
2068
 
  if( (pSrc->jointype & JT_LEFT)!=0 ){
 
2235
  if( pSrc->jointype & JT_LEFT ){
 
2236
    idxEqTermMask = WO_EQ|WO_IN;
 
2237
  }else{
 
2238
    idxEqTermMask = WO_EQ|WO_IN|WO_ISNULL;
 
2239
  }
 
2240
 
 
2241
  if( pSrc->pIndex ){
 
2242
    /* An INDEXED BY clause specifies a particular index to use */
 
2243
    pIdx = pProbe = pSrc->pIndex;
 
2244
    wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
 
2245
    eqTermMask = idxEqTermMask;
 
2246
  }else{
 
2247
    /* There is no INDEXED BY clause.  Create a fake Index object to
 
2248
    ** represent the primary key */
 
2249
    Index *pFirst;                /* Any other index on the table */
 
2250
    memset(&sPk, 0, sizeof(Index));
 
2251
    sPk.nColumn = 1;
 
2252
    sPk.aiColumn = &aiColumnPk;
 
2253
    sPk.aiRowEst = aiRowEstPk;
 
2254
    aiRowEstPk[1] = 1;
 
2255
    sPk.onError = OE_Replace;
 
2256
    sPk.pTable = pSrc->pTab;
 
2257
    pFirst = pSrc->pTab->pIndex;
 
2258
    if( pSrc->notIndexed==0 ){
 
2259
      sPk.pNext = pFirst;
 
2260
    }
 
2261
    /* The aiRowEstPk[0] is an estimate of the total number of rows in the
 
2262
    ** table.  Get this information from the ANALYZE information if it is
 
2263
    ** available.  If not available, assume the table 1 million rows in size.
 
2264
    */
 
2265
    if( pFirst ){
 
2266
      assert( pFirst->aiRowEst!=0 ); /* Allocated together with pFirst */
 
2267
      aiRowEstPk[0] = pFirst->aiRowEst[0];
 
2268
    }else{
 
2269
      aiRowEstPk[0] = 1000000;
 
2270
    }
 
2271
    pProbe = &sPk;
 
2272
    wsFlagMask = ~(
 
2273
        WHERE_COLUMN_IN|WHERE_COLUMN_EQ|WHERE_COLUMN_NULL|WHERE_COLUMN_RANGE
 
2274
    );
2069
2275
    eqTermMask = WO_EQ|WO_IN;
2070
 
  }else{
2071
 
    eqTermMask = WO_EQ|WO_IN|WO_ISNULL;
 
2276
    pIdx = 0;
2072
2277
  }
2073
2278
 
2074
 
  /* Look at each index.
 
2279
  /* Loop over all indices looking for the best one to use
2075
2280
  */
2076
 
  if( pSrc->pIndex ){
2077
 
    pProbe = pSrc->pIndex;
2078
 
  }
2079
 
  for(; pProbe; pProbe=(pSrc->pIndex ? 0 : pProbe->pNext)){
2080
 
    double inMultiplier = 1;  /* Number of equality look-ups needed */
2081
 
    int inMultIsEst = 0;      /* True if inMultiplier is an estimate */
2082
 
 
2083
 
    WHERETRACE(("... index %s:\n", pProbe->zName));
2084
 
 
2085
 
    /* Count the number of columns in the index that are satisfied
2086
 
    ** by x=EXPR or x IS NULL constraints or x IN (...) constraints.
2087
 
    ** For a term of the form x=EXPR or x IS NULL we only have to do 
2088
 
    ** a single binary search.  But for x IN (...) we have to do a
2089
 
    ** number of binary searched
2090
 
    ** equal to the number of entries on the RHS of the IN operator.
2091
 
    ** The inMultipler variable with try to estimate the number of
2092
 
    ** binary searches needed.
 
2281
  for(; pProbe; pIdx=pProbe=pProbe->pNext){
 
2282
    const unsigned int * const aiRowEst = pProbe->aiRowEst;
 
2283
    double cost;                /* Cost of using pProbe */
 
2284
    double nRow;                /* Estimated number of rows in result set */
 
2285
    int rev;                    /* True to scan in reverse order */
 
2286
    int wsFlags = 0;
 
2287
    Bitmask used = 0;
 
2288
 
 
2289
    /* The following variables are populated based on the properties of
 
2290
    ** scan being evaluated. They are then used to determine the expected
 
2291
    ** cost and number of rows returned.
 
2292
    **
 
2293
    **  nEq: 
 
2294
    **    Number of equality terms that can be implemented using the index.
 
2295
    **
 
2296
    **  nInMul:  
 
2297
    **    The "in-multiplier". This is an estimate of how many seek operations 
 
2298
    **    SQLite must perform on the index in question. For example, if the 
 
2299
    **    WHERE clause is:
 
2300
    **
 
2301
    **      WHERE a IN (1, 2, 3) AND b IN (4, 5, 6)
 
2302
    **
 
2303
    **    SQLite must perform 9 lookups on an index on (a, b), so nInMul is 
 
2304
    **    set to 9. Given the same schema and either of the following WHERE 
 
2305
    **    clauses:
 
2306
    **
 
2307
    **      WHERE a =  1
 
2308
    **      WHERE a >= 2
 
2309
    **
 
2310
    **    nInMul is set to 1.
 
2311
    **
 
2312
    **    If there exists a WHERE term of the form "x IN (SELECT ...)", then 
 
2313
    **    the sub-select is assumed to return 25 rows for the purposes of 
 
2314
    **    determining nInMul.
 
2315
    **
 
2316
    **  bInEst:  
 
2317
    **    Set to true if there was at least one "x IN (SELECT ...)" term used 
 
2318
    **    in determining the value of nInMul.
 
2319
    **
 
2320
    **  nBound:
 
2321
    **    An estimate on the amount of the table that must be searched.  A
 
2322
    **    value of 100 means the entire table is searched.  Range constraints
 
2323
    **    might reduce this to a value less than 100 to indicate that only
 
2324
    **    a fraction of the table needs searching.  In the absence of
 
2325
    **    sqlite_stat2 ANALYZE data, a single inequality reduces the search
 
2326
    **    space to 1/3rd its original size.  So an x>? constraint reduces
 
2327
    **    nBound to 33.  Two constraints (x>? AND x<?) reduce nBound to 11.
 
2328
    **
 
2329
    **  bSort:   
 
2330
    **    Boolean. True if there is an ORDER BY clause that will require an 
 
2331
    **    external sort (i.e. scanning the index being evaluated will not 
 
2332
    **    correctly order records).
 
2333
    **
 
2334
    **  bLookup: 
 
2335
    **    Boolean. True if for each index entry visited a lookup on the 
 
2336
    **    corresponding table b-tree is required. This is always false 
 
2337
    **    for the rowid index. For other indexes, it is true unless all the 
 
2338
    **    columns of the table used by the SELECT statement are present in 
 
2339
    **    the index (such an index is sometimes described as a covering index).
 
2340
    **    For example, given the index on (a, b), the second of the following 
 
2341
    **    two queries requires table b-tree lookups, but the first does not.
 
2342
    **
 
2343
    **             SELECT a, b    FROM tbl WHERE a = 1;
 
2344
    **             SELECT a, b, c FROM tbl WHERE a = 1;
2093
2345
    */
2094
 
    wsFlags = 0;
2095
 
    for(i=0; i<pProbe->nColumn; i++){
2096
 
      int j = pProbe->aiColumn[i];
2097
 
      pTerm = findTerm(pWC, iCur, j, notReady, eqTermMask, pProbe);
 
2346
    int nEq;
 
2347
    int bInEst = 0;
 
2348
    int nInMul = 1;
 
2349
    int nBound = 100;
 
2350
    int bSort = 0;
 
2351
    int bLookup = 0;
 
2352
 
 
2353
    /* Determine the values of nEq and nInMul */
 
2354
    for(nEq=0; nEq<pProbe->nColumn; nEq++){
 
2355
      WhereTerm *pTerm;           /* A single term of the WHERE clause */
 
2356
      int j = pProbe->aiColumn[nEq];
 
2357
      pTerm = findTerm(pWC, iCur, j, notReady, eqTermMask, pIdx);
2098
2358
      if( pTerm==0 ) break;
2099
 
      wsFlags |= WHERE_COLUMN_EQ;
 
2359
      wsFlags |= (WHERE_COLUMN_EQ|WHERE_ROWID_EQ);
2100
2360
      if( pTerm->eOperator & WO_IN ){
2101
2361
        Expr *pExpr = pTerm->pExpr;
2102
2362
        wsFlags |= WHERE_COLUMN_IN;
2103
2363
        if( ExprHasProperty(pExpr, EP_xIsSelect) ){
2104
 
          inMultiplier *= 25;
2105
 
          inMultIsEst = 1;
 
2364
          nInMul *= 25;
 
2365
          bInEst = 1;
2106
2366
        }else if( pExpr->x.pList ){
2107
 
          inMultiplier *= pExpr->x.pList->nExpr + 1;
 
2367
          nInMul *= pExpr->x.pList->nExpr + 1;
2108
2368
        }
2109
2369
      }else if( pTerm->eOperator & WO_ISNULL ){
2110
2370
        wsFlags |= WHERE_COLUMN_NULL;
2111
2371
      }
2112
 
    }
2113
 
    nRow = pProbe->aiRowEst[i] * inMultiplier;
2114
 
    /* If inMultiplier is an estimate and that estimate results in an
2115
 
    ** nRow it that is more than half number of rows in the table,
2116
 
    ** then reduce inMultipler */
2117
 
    if( inMultIsEst && nRow*2 > pProbe->aiRowEst[0] ){
2118
 
      nRow = pProbe->aiRowEst[0]/2;
2119
 
      inMultiplier = nRow/pProbe->aiRowEst[i];
2120
 
    }
2121
 
    cost = nRow + inMultiplier*estLog(pProbe->aiRowEst[0]);
2122
 
    nEq = i;
2123
 
    if( pProbe->onError!=OE_None && nEq==pProbe->nColumn ){
 
2372
      used |= pTerm->prereqRight;
 
2373
    }
 
2374
 
 
2375
    /* Determine the value of nBound. */
 
2376
    if( nEq<pProbe->nColumn ){
 
2377
      int j = pProbe->aiColumn[nEq];
 
2378
      if( findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE|WO_GT|WO_GE, pIdx) ){
 
2379
        WhereTerm *pTop = findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE, pIdx);
 
2380
        WhereTerm *pBtm = findTerm(pWC, iCur, j, notReady, WO_GT|WO_GE, pIdx);
 
2381
        whereRangeScanEst(pParse, pProbe, nEq, pBtm, pTop, &nBound);
 
2382
        if( pTop ){
 
2383
          wsFlags |= WHERE_TOP_LIMIT;
 
2384
          used |= pTop->prereqRight;
 
2385
        }
 
2386
        if( pBtm ){
 
2387
          wsFlags |= WHERE_BTM_LIMIT;
 
2388
          used |= pBtm->prereqRight;
 
2389
        }
 
2390
        wsFlags |= (WHERE_COLUMN_RANGE|WHERE_ROWID_RANGE);
 
2391
      }
 
2392
    }else if( pProbe->onError!=OE_None ){
2124
2393
      testcase( wsFlags & WHERE_COLUMN_IN );
2125
2394
      testcase( wsFlags & WHERE_COLUMN_NULL );
2126
2395
      if( (wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0 ){
2127
2396
        wsFlags |= WHERE_UNIQUE;
2128
2397
      }
2129
2398
    }
2130
 
    WHERETRACE(("...... nEq=%d inMult=%.9g nRow=%.9g cost=%.9g\n",
2131
 
                nEq, inMultiplier, nRow, cost));
2132
 
 
2133
 
    /* Look for range constraints.  Assume that each range constraint
2134
 
    ** makes the search space 1/3rd smaller.
2135
 
    */
2136
 
    if( nEq<pProbe->nColumn ){
2137
 
      int j = pProbe->aiColumn[nEq];
2138
 
      pTerm = findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE|WO_GT|WO_GE, pProbe);
2139
 
      if( pTerm ){
2140
 
        wsFlags |= WHERE_COLUMN_RANGE;
2141
 
        if( findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE, pProbe) ){
2142
 
          wsFlags |= WHERE_TOP_LIMIT;
2143
 
          cost /= 3;
2144
 
          nRow /= 3;
2145
 
        }
2146
 
        if( findTerm(pWC, iCur, j, notReady, WO_GT|WO_GE, pProbe) ){
2147
 
          wsFlags |= WHERE_BTM_LIMIT;
2148
 
          cost /= 3;
2149
 
          nRow /= 3;
2150
 
        }
2151
 
        WHERETRACE(("...... range reduces nRow to %.9g and cost to %.9g\n",
2152
 
                    nRow, cost));
2153
 
      }
2154
 
    }
2155
 
 
2156
 
    /* Add the additional cost of sorting if that is a factor.
2157
 
    */
 
2399
 
 
2400
    /* If there is an ORDER BY clause and the index being considered will
 
2401
    ** naturally scan rows in the required order, set the appropriate flags
 
2402
    ** in wsFlags. Otherwise, if there is an ORDER BY clause but the index
 
2403
    ** will scan rows in a different order, set the bSort variable.  */
2158
2404
    if( pOrderBy ){
2159
2405
      if( (wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0
2160
 
       && isSortingIndex(pParse,pWC->pMaskSet,pProbe,iCur,pOrderBy,nEq,&rev)
 
2406
        && isSortingIndex(pParse,pWC->pMaskSet,pProbe,iCur,pOrderBy,nEq,&rev)
2161
2407
      ){
2162
 
        if( wsFlags==0 ){
2163
 
          wsFlags = WHERE_COLUMN_RANGE;
2164
 
        }
2165
 
        wsFlags |= WHERE_ORDERBY;
2166
 
        if( rev ){
2167
 
          wsFlags |= WHERE_REVERSE;
2168
 
        }
 
2408
        wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE|WHERE_ORDERBY;
 
2409
        wsFlags |= (rev ? WHERE_REVERSE : 0);
2169
2410
      }else{
2170
 
        cost += cost*estLog(cost);
2171
 
        WHERETRACE(("...... orderby increases cost to %.9g\n", cost));
 
2411
        bSort = 1;
2172
2412
      }
2173
 
    }else if( wsFlags!=0 && (pParse->db->flags & SQLITE_ReverseOrder)!=0 ){
2174
 
      /* For application testing, randomly reverse the output order for
2175
 
      ** SELECT statements that omit the ORDER BY clause.  This will help
2176
 
      ** to find cases where
2177
 
      */
2178
 
      wsFlags |= WHERE_REVERSE;
2179
2413
    }
2180
2414
 
2181
 
    /* Check to see if we can get away with using just the index without
2182
 
    ** ever reading the table.  If that is the case, then halve the
2183
 
    ** cost of this index.
2184
 
    */
2185
 
    if( wsFlags && pSrc->colUsed < (((Bitmask)1)<<(BMS-1)) ){
 
2415
    /* If currently calculating the cost of using an index (not the IPK
 
2416
    ** index), determine if all required column data may be obtained without 
 
2417
    ** seeking to entries in the main table (i.e. if the index is a covering
 
2418
    ** index for this query). If it is, set the WHERE_IDX_ONLY flag in
 
2419
    ** wsFlags. Otherwise, set the bLookup variable to true.  */
 
2420
    if( pIdx && wsFlags ){
2186
2421
      Bitmask m = pSrc->colUsed;
2187
2422
      int j;
2188
 
      for(j=0; j<pProbe->nColumn; j++){
2189
 
        int x = pProbe->aiColumn[j];
 
2423
      for(j=0; j<pIdx->nColumn; j++){
 
2424
        int x = pIdx->aiColumn[j];
2190
2425
        if( x<BMS-1 ){
2191
2426
          m &= ~(((Bitmask)1)<<x);
2192
2427
        }
2193
2428
      }
2194
2429
      if( m==0 ){
2195
2430
        wsFlags |= WHERE_IDX_ONLY;
2196
 
        cost /= 2;
2197
 
        WHERETRACE(("...... idx-only reduces cost to %.9g\n", cost));
 
2431
      }else{
 
2432
        bLookup = 1;
2198
2433
      }
2199
2434
    }
2200
2435
 
2201
 
    /* If this index has achieved the lowest cost so far, then use it.
2202
 
    */
2203
 
    if( wsFlags!=0 && cost < pCost->rCost ){
 
2436
    /**** Begin adding up the cost of using this index (Needs improvements)
 
2437
    **
 
2438
    ** Estimate the number of rows of output.  For an IN operator,
 
2439
    ** do not let the estimate exceed half the rows in the table.
 
2440
    */
 
2441
    nRow = (double)(aiRowEst[nEq] * nInMul);
 
2442
    if( bInEst && nRow*2>aiRowEst[0] ){
 
2443
      nRow = aiRowEst[0]/2;
 
2444
      nInMul = (int)(nRow / aiRowEst[nEq]);
 
2445
    }
 
2446
 
 
2447
    /* Assume constant cost to access a row and logarithmic cost to
 
2448
    ** do a binary search.  Hence, the initial cost is the number of output
 
2449
    ** rows plus log2(table-size) times the number of binary searches.
 
2450
    */
 
2451
    cost = nRow + nInMul*estLog(aiRowEst[0]);
 
2452
 
 
2453
    /* Adjust the number of rows and the cost downward to reflect rows
 
2454
    ** that are excluded by range constraints.
 
2455
    */
 
2456
    nRow = (nRow * (double)nBound) / (double)100;
 
2457
    cost = (cost * (double)nBound) / (double)100;
 
2458
 
 
2459
    /* Add in the estimated cost of sorting the result
 
2460
    */
 
2461
    if( bSort ){
 
2462
      cost += cost*estLog(cost);
 
2463
    }
 
2464
 
 
2465
    /* If all information can be taken directly from the index, we avoid
 
2466
    ** doing table lookups.  This reduces the cost by half.  (Not really -
 
2467
    ** this needs to be fixed.)
 
2468
    */
 
2469
    if( pIdx && bLookup==0 ){
 
2470
      cost /= (double)2;
 
2471
    }
 
2472
    /**** Cost of using this index has now been computed ****/
 
2473
 
 
2474
    WHERETRACE((
 
2475
      "tbl=%s idx=%s nEq=%d nInMul=%d nBound=%d bSort=%d bLookup=%d"
 
2476
      " wsFlags=%d   (nRow=%.2f cost=%.2f)\n",
 
2477
      pSrc->pTab->zName, (pIdx ? pIdx->zName : "ipk"), 
 
2478
      nEq, nInMul, nBound, bSort, bLookup, wsFlags, nRow, cost
 
2479
    ));
 
2480
 
 
2481
    /* If this index is the best we have seen so far, then record this
 
2482
    ** index and its cost in the pCost structure.
 
2483
    */
 
2484
    if( (!pIdx || wsFlags) && cost<pCost->rCost ){
2204
2485
      pCost->rCost = cost;
2205
2486
      pCost->nRow = nRow;
2206
 
      pCost->plan.wsFlags = wsFlags;
 
2487
      pCost->used = used;
 
2488
      pCost->plan.wsFlags = (wsFlags&wsFlagMask);
2207
2489
      pCost->plan.nEq = nEq;
2208
 
      assert( pCost->plan.wsFlags & WHERE_INDEXED );
2209
 
      pCost->plan.u.pIdx = pProbe;
 
2490
      pCost->plan.u.pIdx = pIdx;
2210
2491
    }
2211
 
  }
2212
 
 
2213
 
  /* Report the best result
2214
 
  */
 
2492
 
 
2493
    /* If there was an INDEXED BY clause, then only that one index is
 
2494
    ** considered. */
 
2495
    if( pSrc->pIndex ) break;
 
2496
 
 
2497
    /* Reset masks for the next index in the loop */
 
2498
    wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
 
2499
    eqTermMask = idxEqTermMask;
 
2500
  }
 
2501
 
 
2502
  /* If there is no ORDER BY clause and the SQLITE_ReverseOrder flag
 
2503
  ** is set, then reverse the order that the index will be scanned
 
2504
  ** in. This is used for application testing, to help find cases
 
2505
  ** where application behaviour depends on the (undefined) order that
 
2506
  ** SQLite outputs rows in in the absence of an ORDER BY clause.  */
 
2507
  if( !pOrderBy && pParse->db->flags & SQLITE_ReverseOrder ){
 
2508
    pCost->plan.wsFlags |= WHERE_REVERSE;
 
2509
  }
 
2510
 
 
2511
  assert( pOrderBy || (pCost->plan.wsFlags&WHERE_ORDERBY)==0 );
 
2512
  assert( pCost->plan.u.pIdx==0 || (pCost->plan.wsFlags&WHERE_ROWID_EQ)==0 );
 
2513
  assert( pSrc->pIndex==0 
 
2514
       || pCost->plan.u.pIdx==0 
 
2515
       || pCost->plan.u.pIdx==pSrc->pIndex 
 
2516
  );
 
2517
 
 
2518
  WHERETRACE(("best index is: %s\n", 
 
2519
    (pCost->plan.u.pIdx ? pCost->plan.u.pIdx->zName : "ipk")
 
2520
  ));
 
2521
  
 
2522
  bestOrClauseIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost);
2215
2523
  pCost->plan.wsFlags |= eqTermMask;
2216
 
  WHERETRACE(("best index is %s, cost=%.9g, nrow=%.9g, wsFlags=%x, nEq=%d\n",
2217
 
        (pCost->plan.wsFlags & WHERE_INDEXED)!=0 ?
2218
 
             pCost->plan.u.pIdx->zName : "(none)", pCost->nRow,
2219
 
        pCost->rCost, pCost->plan.wsFlags, pCost->plan.nEq));
2220
2524
}
2221
2525
 
2222
2526
/*
2287
2591
}
2288
2592
 
2289
2593
/*
2290
 
** Apply the affinities associated with the first n columns of index
2291
 
** pIdx to the values in the n registers starting at base.
 
2594
** Code an OP_Affinity opcode to apply the column affinity string zAff
 
2595
** to the n registers starting at base. 
 
2596
**
 
2597
** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
 
2598
** beginning and end of zAff are ignored.  If all entries in zAff are
 
2599
** SQLITE_AFF_NONE, then no code gets generated.
 
2600
**
 
2601
** This routine makes its own copy of zAff so that the caller is free
 
2602
** to modify zAff after this routine returns.
2292
2603
*/
2293
 
static void codeApplyAffinity(Parse *pParse, int base, int n, Index *pIdx){
 
2604
static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
 
2605
  Vdbe *v = pParse->pVdbe;
 
2606
  if( zAff==0 ){
 
2607
    assert( pParse->db->mallocFailed );
 
2608
    return;
 
2609
  }
 
2610
  assert( v!=0 );
 
2611
 
 
2612
  /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
 
2613
  ** and end of the affinity string.
 
2614
  */
 
2615
  while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
 
2616
    n--;
 
2617
    base++;
 
2618
    zAff++;
 
2619
  }
 
2620
  while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
 
2621
    n--;
 
2622
  }
 
2623
 
 
2624
  /* Code the OP_Affinity opcode if there is anything left to do. */
2294
2625
  if( n>0 ){
2295
 
    Vdbe *v = pParse->pVdbe;
2296
 
    assert( v!=0 );
2297
2626
    sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
2298
 
    sqlite3IndexAffinityStr(v, pIdx);
 
2627
    sqlite3VdbeChangeP4(v, -1, zAff, n);
2299
2628
    sqlite3ExprCacheAffinityChange(pParse, base, n);
2300
2629
  }
2301
2630
}
2368
2697
 
2369
2698
/*
2370
2699
** Generate code that will evaluate all == and IN constraints for an
2371
 
** index.  The values for all constraints are left on the stack.
 
2700
** index.
2372
2701
**
2373
2702
** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
2374
2703
** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
2380
2709
**
2381
2710
** In the example above nEq==2.  But this subroutine works for any value
2382
2711
** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
2383
 
** The only thing it does is allocate the pLevel->iMem memory cell.
 
2712
** The only thing it does is allocate the pLevel->iMem memory cell and
 
2713
** compute the affinity string.
2384
2714
**
2385
2715
** This routine always allocates at least one memory cell and returns
2386
2716
** the index of that memory cell. The code that
2388
2718
** key value of the loop.  If one or more IN operators appear, then
2389
2719
** this routine allocates an additional nEq memory cells for internal
2390
2720
** use.
 
2721
**
 
2722
** Before returning, *pzAff is set to point to a buffer containing a
 
2723
** copy of the column affinity string of the index allocated using
 
2724
** sqlite3DbMalloc(). Except, entries in the copy of the string associated
 
2725
** with equality constraints that use NONE affinity are set to
 
2726
** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
 
2727
**
 
2728
**   CREATE TABLE t1(a TEXT PRIMARY KEY, b);
 
2729
**   SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
 
2730
**
 
2731
** In the example above, the index on t1(a) has TEXT affinity. But since
 
2732
** the right hand side of the equality constraint (t2.b) has NONE affinity,
 
2733
** no conversion should be attempted before using a t2.b value as part of
 
2734
** a key to search the index. Hence the first byte in the returned affinity
 
2735
** string in this example would be set to SQLITE_AFF_NONE.
2391
2736
*/
2392
2737
static int codeAllEqualityTerms(
2393
2738
  Parse *pParse,        /* Parsing context */
2394
2739
  WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
2395
2740
  WhereClause *pWC,     /* The WHERE clause */
2396
2741
  Bitmask notReady,     /* Which parts of FROM have not yet been coded */
2397
 
  int nExtraReg         /* Number of extra registers to allocate */
 
2742
  int nExtraReg,        /* Number of extra registers to allocate */
 
2743
  char **pzAff          /* OUT: Set to point to affinity string */
2398
2744
){
2399
2745
  int nEq = pLevel->plan.nEq;   /* The number of == or IN constraints to code */
2400
2746
  Vdbe *v = pParse->pVdbe;      /* The vm under construction */
2404
2750
  int j;                        /* Loop counter */
2405
2751
  int regBase;                  /* Base register */
2406
2752
  int nReg;                     /* Number of registers to allocate */
 
2753
  char *zAff;                   /* Affinity string to return */
2407
2754
 
2408
2755
  /* This module is only called on query plans that use an index. */
2409
2756
  assert( pLevel->plan.wsFlags & WHERE_INDEXED );
2415
2762
  nReg = pLevel->plan.nEq + nExtraReg;
2416
2763
  pParse->nMem += nReg;
2417
2764
 
 
2765
  zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
 
2766
  if( !zAff ){
 
2767
    pParse->db->mallocFailed = 1;
 
2768
  }
 
2769
 
2418
2770
  /* Evaluate the equality constraints
2419
2771
  */
2420
2772
  assert( pIdx->nColumn>=nEq );
2436
2788
    testcase( pTerm->eOperator & WO_ISNULL );
2437
2789
    testcase( pTerm->eOperator & WO_IN );
2438
2790
    if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
2439
 
      sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk);
 
2791
      Expr *pRight = pTerm->pExpr->pRight;
 
2792
      sqlite3ExprCodeIsNullJump(v, pRight, regBase+j, pLevel->addrBrk);
 
2793
      if( zAff ){
 
2794
        if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
 
2795
          zAff[j] = SQLITE_AFF_NONE;
 
2796
        }
 
2797
        if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
 
2798
          zAff[j] = SQLITE_AFF_NONE;
 
2799
        }
 
2800
      }
2440
2801
    }
2441
2802
  }
 
2803
  *pzAff = zAff;
2442
2804
  return regBase;
2443
2805
}
2444
2806
 
2514
2876
    const struct sqlite3_index_constraint *aConstraint =
2515
2877
                                                pVtabIdx->aConstraint;
2516
2878
 
 
2879
    sqlite3ExprCachePush(pParse);
2517
2880
    iReg = sqlite3GetTempRange(pParse, nConstraint+2);
2518
2881
    for(j=1; j<=nConstraint; j++){
2519
2882
      for(k=0; k<nConstraint; k++){
2540
2903
    pLevel->p1 = iCur;
2541
2904
    pLevel->p2 = sqlite3VdbeCurrentAddr(v);
2542
2905
    sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
 
2906
    sqlite3ExprCachePop(pParse, 1);
2543
2907
  }else
2544
2908
#endif /* SQLITE_OMIT_VIRTUALTABLE */
2545
2909
 
2694
3058
    int iIdxCur;         /* The VDBE cursor for the index */
2695
3059
    int nExtraReg = 0;   /* Number of extra registers needed */
2696
3060
    int op;              /* Instruction opcode */
 
3061
    char *zAff;
2697
3062
 
2698
3063
    pIdx = pLevel->plan.u.pIdx;
2699
3064
    iIdxCur = pLevel->iIdxCur;
2733
3098
    ** and store the values of those terms in an array of registers
2734
3099
    ** starting at regBase.
2735
3100
    */
2736
 
    regBase = codeAllEqualityTerms(pParse, pLevel, pWC, notReady, nExtraReg);
 
3101
    regBase = codeAllEqualityTerms(
 
3102
        pParse, pLevel, pWC, notReady, nExtraReg, &zAff
 
3103
    );
2737
3104
    addrNxt = pLevel->addrNxt;
2738
3105
 
2739
 
 
2740
3106
    /* If we are doing a reverse order scan on an ascending index, or
2741
3107
    ** a forward order scan on a descending index, interchange the 
2742
3108
    ** start and end terms (pRangeStart and pRangeEnd).
2756
3122
    /* Seek the index cursor to the start of the range. */
2757
3123
    nConstraint = nEq;
2758
3124
    if( pRangeStart ){
2759
 
      sqlite3ExprCode(pParse, pRangeStart->pExpr->pRight, regBase+nEq);
2760
 
      sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
 
3125
      Expr *pRight = pRangeStart->pExpr->pRight;
 
3126
      sqlite3ExprCode(pParse, pRight, regBase+nEq);
 
3127
      sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
 
3128
      if( zAff ){
 
3129
        if( sqlite3CompareAffinity(pRight, zAff[nConstraint])==SQLITE_AFF_NONE){
 
3130
          /* Since the comparison is to be performed with no conversions
 
3131
          ** applied to the operands, set the affinity to apply to pRight to 
 
3132
          ** SQLITE_AFF_NONE.  */
 
3133
          zAff[nConstraint] = SQLITE_AFF_NONE;
 
3134
        }
 
3135
        if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[nConstraint]) ){
 
3136
          zAff[nConstraint] = SQLITE_AFF_NONE;
 
3137
        }
 
3138
      }  
2761
3139
      nConstraint++;
2762
3140
    }else if( isMinQuery ){
2763
3141
      sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
2765
3143
      startEq = 0;
2766
3144
      start_constraints = 1;
2767
3145
    }
2768
 
    codeApplyAffinity(pParse, regBase, nConstraint, pIdx);
 
3146
    codeApplyAffinity(pParse, regBase, nConstraint, zAff);
2769
3147
    op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
2770
3148
    assert( op!=0 );
2771
3149
    testcase( op==OP_Rewind );
2774
3152
    testcase( op==OP_SeekGe );
2775
3153
    testcase( op==OP_SeekLe );
2776
3154
    testcase( op==OP_SeekLt );
2777
 
    sqlite3VdbeAddOp4(v, op, iIdxCur, addrNxt, regBase, 
2778
 
                      SQLITE_INT_TO_PTR(nConstraint), P4_INT32);
 
3155
    sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
2779
3156
 
2780
3157
    /* Load the value for the inequality constraint at the end of the
2781
3158
    ** range (if any).
2782
3159
    */
2783
3160
    nConstraint = nEq;
2784
3161
    if( pRangeEnd ){
 
3162
      Expr *pRight = pRangeEnd->pExpr->pRight;
2785
3163
      sqlite3ExprCacheRemove(pParse, regBase+nEq);
2786
 
      sqlite3ExprCode(pParse, pRangeEnd->pExpr->pRight, regBase+nEq);
2787
 
      sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
2788
 
      codeApplyAffinity(pParse, regBase, nEq+1, pIdx);
 
3164
      sqlite3ExprCode(pParse, pRight, regBase+nEq);
 
3165
      sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
 
3166
      if( zAff ){
 
3167
        if( sqlite3CompareAffinity(pRight, zAff[nConstraint])==SQLITE_AFF_NONE){
 
3168
          /* Since the comparison is to be performed with no conversions
 
3169
          ** applied to the operands, set the affinity to apply to pRight to 
 
3170
          ** SQLITE_AFF_NONE.  */
 
3171
          zAff[nConstraint] = SQLITE_AFF_NONE;
 
3172
        }
 
3173
        if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[nConstraint]) ){
 
3174
          zAff[nConstraint] = SQLITE_AFF_NONE;
 
3175
        }
 
3176
      }  
 
3177
      codeApplyAffinity(pParse, regBase, nEq+1, zAff);
2789
3178
      nConstraint++;
2790
3179
    }
 
3180
    sqlite3DbFree(pParse->db, zAff);
2791
3181
 
2792
3182
    /* Top of the loop body */
2793
3183
    pLevel->p2 = sqlite3VdbeCurrentAddr(v);
2798
3188
    testcase( op==OP_IdxGE );
2799
3189
    testcase( op==OP_IdxLT );
2800
3190
    if( op!=OP_Noop ){
2801
 
      sqlite3VdbeAddOp4(v, op, iIdxCur, addrNxt, regBase,
2802
 
                        SQLITE_INT_TO_PTR(nConstraint), P4_INT32);
 
3191
      sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
2803
3192
      sqlite3VdbeChangeP5(v, endEq!=bRev ?1:0);
2804
3193
    }
2805
3194
 
2928
3317
            int r;
2929
3318
            r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur, 
2930
3319
                                         regRowid, 0);
2931
 
            sqlite3VdbeAddOp4(v, OP_RowSetTest, regRowset,
2932
 
                              sqlite3VdbeCurrentAddr(v)+2,
2933
 
                              r, SQLITE_INT_TO_PTR(iSet), P4_INT32);
 
3320
            sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset,
 
3321
                                 sqlite3VdbeCurrentAddr(v)+2, r, iSet);
2934
3322
          }
2935
3323
          sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
2936
3324
 
3270
3658
    WhereCost bestPlan;         /* Most efficient plan seen so far */
3271
3659
    Index *pIdx;                /* Index for FROM table at pTabItem */
3272
3660
    int j;                      /* For looping over FROM tables */
3273
 
    int bestJ = 0;              /* The value of j */
 
3661
    int bestJ = -1;             /* The value of j */
3274
3662
    Bitmask m;                  /* Bitmask value for j or bestJ */
3275
 
    int once = 0;               /* True when first table is seen */
 
3663
    int isOptimal;              /* Iterator for optimal/non-optimal search */
3276
3664
 
3277
3665
    memset(&bestPlan, 0, sizeof(bestPlan));
3278
3666
    bestPlan.rCost = SQLITE_BIG_DBL;
3279
 
    for(j=iFrom, pTabItem=&pTabList->a[j]; j<pTabList->nSrc; j++, pTabItem++){
3280
 
      int doNotReorder;    /* True if this table should not be reordered */
3281
 
      WhereCost sCost;     /* Cost information from best[Virtual]Index() */
3282
 
      ExprList *pOrderBy;  /* ORDER BY clause for index to optimize */
3283
 
 
3284
 
      doNotReorder =  (pTabItem->jointype & (JT_LEFT|JT_CROSS))!=0;
3285
 
      if( once && doNotReorder ) break;
3286
 
      m = getMask(pMaskSet, pTabItem->iCursor);
3287
 
      if( (m & notReady)==0 ){
3288
 
        if( j==iFrom ) iFrom++;
3289
 
        continue;
3290
 
      }
3291
 
      pOrderBy = ((i==0 && ppOrderBy )?*ppOrderBy:0);
3292
 
 
3293
 
      assert( pTabItem->pTab );
 
3667
 
 
3668
    /* Loop through the remaining entries in the FROM clause to find the
 
3669
    ** next nested loop. The FROM clause entries may be iterated through
 
3670
    ** either once or twice. 
 
3671
    **
 
3672
    ** The first iteration, which is always performed, searches for the
 
3673
    ** FROM clause entry that permits the lowest-cost, "optimal" scan. In
 
3674
    ** this context an optimal scan is one that uses the same strategy
 
3675
    ** for the given FROM clause entry as would be selected if the entry
 
3676
    ** were used as the innermost nested loop.  In other words, a table
 
3677
    ** is chosen such that the cost of running that table cannot be reduced
 
3678
    ** by waiting for other tables to run first.
 
3679
    **
 
3680
    ** The second iteration is only performed if no optimal scan strategies
 
3681
    ** were found by the first. This iteration is used to search for the
 
3682
    ** lowest cost scan overall.
 
3683
    **
 
3684
    ** Previous versions of SQLite performed only the second iteration -
 
3685
    ** the next outermost loop was always that with the lowest overall
 
3686
    ** cost. However, this meant that SQLite could select the wrong plan
 
3687
    ** for scripts such as the following:
 
3688
    **   
 
3689
    **   CREATE TABLE t1(a, b); 
 
3690
    **   CREATE TABLE t2(c, d);
 
3691
    **   SELECT * FROM t2, t1 WHERE t2.rowid = t1.a;
 
3692
    **
 
3693
    ** The best strategy is to iterate through table t1 first. However it
 
3694
    ** is not possible to determine this with a simple greedy algorithm.
 
3695
    ** However, since the cost of a linear scan through table t2 is the same 
 
3696
    ** as the cost of a linear scan through table t1, a simple greedy 
 
3697
    ** algorithm may choose to use t2 for the outer loop, which is a much
 
3698
    ** costlier approach.
 
3699
    */
 
3700
    for(isOptimal=1; isOptimal>=0 && bestJ<0; isOptimal--){
 
3701
      Bitmask mask = (isOptimal ? 0 : notReady);
 
3702
      assert( (pTabList->nSrc-iFrom)>1 || isOptimal );
 
3703
      for(j=iFrom, pTabItem=&pTabList->a[j]; j<pTabList->nSrc; j++, pTabItem++){
 
3704
        int doNotReorder;    /* True if this table should not be reordered */
 
3705
        WhereCost sCost;     /* Cost information from best[Virtual]Index() */
 
3706
        ExprList *pOrderBy;  /* ORDER BY clause for index to optimize */
 
3707
  
 
3708
        doNotReorder =  (pTabItem->jointype & (JT_LEFT|JT_CROSS))!=0;
 
3709
        if( j!=iFrom && doNotReorder ) break;
 
3710
        m = getMask(pMaskSet, pTabItem->iCursor);
 
3711
        if( (m & notReady)==0 ){
 
3712
          if( j==iFrom ) iFrom++;
 
3713
          continue;
 
3714
        }
 
3715
        pOrderBy = ((i==0 && ppOrderBy )?*ppOrderBy:0);
 
3716
  
 
3717
        assert( pTabItem->pTab );
3294
3718
#ifndef SQLITE_OMIT_VIRTUALTABLE
3295
 
      if( IsVirtual(pTabItem->pTab) ){
3296
 
        sqlite3_index_info **pp = &pWInfo->a[j].pIdxInfo;
3297
 
        bestVirtualIndex(pParse, pWC, pTabItem, notReady, pOrderBy, &sCost, pp);
3298
 
      }else 
 
3719
        if( IsVirtual(pTabItem->pTab) ){
 
3720
          sqlite3_index_info **pp = &pWInfo->a[j].pIdxInfo;
 
3721
          bestVirtualIndex(pParse, pWC, pTabItem, mask, pOrderBy, &sCost, pp);
 
3722
        }else 
3299
3723
#endif
3300
 
      {
3301
 
        bestBtreeIndex(pParse, pWC, pTabItem, notReady, pOrderBy, &sCost);
3302
 
      }
3303
 
      if( once==0 || sCost.rCost<bestPlan.rCost ){
3304
 
        once = 1;
3305
 
        bestPlan = sCost;
3306
 
        bestJ = j;
3307
 
      }
3308
 
      if( doNotReorder ) break;
 
3724
        {
 
3725
          bestBtreeIndex(pParse, pWC, pTabItem, mask, pOrderBy, &sCost);
 
3726
        }
 
3727
        assert( isOptimal || (sCost.used&notReady)==0 );
 
3728
 
 
3729
        if( (sCost.used&notReady)==0
 
3730
         && (j==iFrom || sCost.rCost<bestPlan.rCost) 
 
3731
        ){
 
3732
          bestPlan = sCost;
 
3733
          bestJ = j;
 
3734
        }
 
3735
        if( doNotReorder ) break;
 
3736
      }
3309
3737
    }
3310
 
    assert( once );
 
3738
    assert( bestJ>=0 );
3311
3739
    assert( notReady & getMask(pMaskSet, pTabList->a[bestJ].iCursor) );
3312
3740
    WHERETRACE(("*** Optimizer selects table %d for loop %d\n", bestJ,
3313
3741
           pLevel-pWInfo->a));
3404
3832
#endif /* SQLITE_OMIT_EXPLAIN */
3405
3833
    pTabItem = &pTabList->a[pLevel->iFrom];
3406
3834
    pTab = pTabItem->pTab;
3407
 
    iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
 
3835
    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
3408
3836
    if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ) continue;
3409
3837
#ifndef SQLITE_OMIT_VIRTUALTABLE
3410
3838
    if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
 
3839
      const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
3411
3840
      int iCur = pTabItem->iCursor;
3412
 
      sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0,
3413
 
                        (const char*)pTab->pVtab, P4_VTAB);
 
3841
      sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
3414
3842
    }else
3415
3843
#endif
3416
3844
    if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
3421
3849
        Bitmask b = pTabItem->colUsed;
3422
3850
        int n = 0;
3423
3851
        for(; b; b=b>>1, n++){}
3424
 
        sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1, SQLITE_INT_TO_PTR(n), P4_INT32);
 
3852
        sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1, 
 
3853
                            SQLITE_INT_TO_PTR(n), P4_INT32);
3425
3854
        assert( n<=pTab->nCol );
3426
3855
      }
3427
3856
    }else{
3549
3978
    if( pLevel->iLeftJoin ){
3550
3979
      int addr;
3551
3980
      addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
3552
 
      sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
 
3981
      assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
 
3982
           || (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 );
 
3983
      if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0 ){
 
3984
        sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
 
3985
      }
3553
3986
      if( pLevel->iIdxCur>=0 ){
3554
3987
        sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
3555
3988
      }
3600
4033
      int k, j, last;
3601
4034
      VdbeOp *pOp;
3602
4035
      Index *pIdx = pLevel->plan.u.pIdx;
3603
 
      int useIndexOnly = pLevel->plan.wsFlags & WHERE_IDX_ONLY;
3604
4036
 
3605
4037
      assert( pIdx!=0 );
3606
4038
      pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
3615
4047
              break;
3616
4048
            }
3617
4049
          }
3618
 
          assert(!useIndexOnly || j<pIdx->nColumn);
 
4050
          assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
 
4051
               || j<pIdx->nColumn );
3619
4052
        }else if( pOp->opcode==OP_Rowid ){
3620
4053
          pOp->p1 = pLevel->iIdxCur;
3621
4054
          pOp->opcode = OP_IdxRowid;
3622
 
        }else if( pOp->opcode==OP_NullRow && useIndexOnly ){
3623
 
          pOp->opcode = OP_Noop;
3624
4055
        }
3625
4056
      }
3626
4057
    }