where.c 98 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790
  1. /*
  2. ** 2001 September 15
  3. **
  4. ** The author disclaims copyright to this source code. In place of
  5. ** a legal notice, here is a blessing:
  6. **
  7. ** 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.
  10. **
  11. *************************************************************************
  12. ** This module contains C code that generates VDBE code used to process
  13. ** the WHERE clause of SQL statements. This module is reponsible for
  14. ** 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".
  18. **
  19. ** $Id: where.c,v 1.266 2007/12/12 17:42:53 danielk1977 Exp $
  20. */
  21. #include "sqliteInt.h"
  22. /*
  23. ** The number of bits in a Bitmask. "BMS" means "BitMask Size".
  24. */
  25. #define BMS (sizeof(Bitmask)*8)
  26. /*
  27. ** Trace output macros
  28. */
  29. #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
  30. int sqlite3_where_trace = 0;
  31. # define WHERETRACE(X) if(sqlite3_where_trace) sqlite3DebugPrintf X
  32. #else
  33. # define WHERETRACE(X)
  34. #endif
  35. /* Forward reference
  36. */
  37. typedef struct WhereClause WhereClause;
  38. typedef struct ExprMaskSet ExprMaskSet;
  39. /*
  40. ** The query generator uses an array of instances of this structure to
  41. ** help it analyze the subexpressions of the WHERE clause. Each WHERE
  42. ** clause subexpression is separated from the others by an AND operator.
  43. **
  44. ** All WhereTerms are collected into a single WhereClause structure.
  45. ** The following identity holds:
  46. **
  47. ** WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
  48. **
  49. ** When a term is of the form:
  50. **
  51. ** X <op> <expr>
  52. **
  53. ** where X is a column name and <op> is one of certain operators,
  54. ** then WhereTerm.leftCursor and WhereTerm.leftColumn record the
  55. ** cursor number and column number for X. WhereTerm.operator records
  56. ** the <op> using a bitmask encoding defined by WO_xxx below. The
  57. ** use of a bitmask encoding for the operator allows us to search
  58. ** quickly for terms that match any of several different operators.
  59. **
  60. ** prereqRight and prereqAll record sets of cursor numbers,
  61. ** but they do so indirectly. A single ExprMaskSet structure translates
  62. ** cursor number into bits and the translated bit is stored in the prereq
  63. ** fields. The translation is used in order to maximize the number of
  64. ** bits that will fit in a Bitmask. The VDBE cursor numbers might be
  65. ** spread out over the non-negative integers. For example, the cursor
  66. ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45. The ExprMaskSet
  67. ** translates these sparse cursor numbers into consecutive integers
  68. ** beginning with 0 in order to make the best possible use of the available
  69. ** bits in the Bitmask. So, in the example above, the cursor numbers
  70. ** would be mapped into integers 0 through 7.
  71. */
  72. typedef struct WhereTerm WhereTerm;
  73. struct WhereTerm {
  74. Expr *pExpr; /* Pointer to the subexpression */
  75. i16 iParent; /* Disable pWC->a[iParent] when this term disabled */
  76. i16 leftCursor; /* Cursor number of X in "X <op> <expr>" */
  77. i16 leftColumn; /* Column number of X in "X <op> <expr>" */
  78. u16 eOperator; /* A WO_xx value describing <op> */
  79. u8 flags; /* Bit flags. See below */
  80. u8 nChild; /* Number of children that must disable us */
  81. WhereClause *pWC; /* The clause this term is part of */
  82. Bitmask prereqRight; /* Bitmask of tables used by pRight */
  83. Bitmask prereqAll; /* Bitmask of tables referenced by p */
  84. };
  85. /*
  86. ** Allowed values of WhereTerm.flags
  87. */
  88. #define TERM_DYNAMIC 0x01 /* Need to call sqlite3ExprDelete(pExpr) */
  89. #define TERM_VIRTUAL 0x02 /* Added by the optimizer. Do not code */
  90. #define TERM_CODED 0x04 /* This term is already coded */
  91. #define TERM_COPIED 0x08 /* Has a child */
  92. #define TERM_OR_OK 0x10 /* Used during OR-clause processing */
  93. /*
  94. ** An instance of the following structure holds all information about a
  95. ** WHERE clause. Mostly this is a container for one or more WhereTerms.
  96. */
  97. struct WhereClause {
  98. Parse *pParse; /* The parser context */
  99. ExprMaskSet *pMaskSet; /* Mapping of table indices to bitmasks */
  100. int nTerm; /* Number of terms */
  101. int nSlot; /* Number of entries in a[] */
  102. WhereTerm *a; /* Each a[] describes a term of the WHERE cluase */
  103. WhereTerm aStatic[10]; /* Initial static space for a[] */
  104. };
  105. /*
  106. ** An instance of the following structure keeps track of a mapping
  107. ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
  108. **
  109. ** The VDBE cursor numbers are small integers contained in
  110. ** SrcList_item.iCursor and Expr.iTable fields. For any given WHERE
  111. ** clause, the cursor numbers might not begin with 0 and they might
  112. ** contain gaps in the numbering sequence. But we want to make maximum
  113. ** use of the bits in our bitmasks. This structure provides a mapping
  114. ** from the sparse cursor numbers into consecutive integers beginning
  115. ** with 0.
  116. **
  117. ** If ExprMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
  118. ** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<<A.
  119. **
  120. ** For example, if the WHERE clause expression used these VDBE
  121. ** cursors: 4, 5, 8, 29, 57, 73. Then the ExprMaskSet structure
  122. ** would map those cursor numbers into bits 0 through 5.
  123. **
  124. ** Note that the mapping is not necessarily ordered. In the example
  125. ** above, the mapping might go like this: 4->3, 5->1, 8->2, 29->0,
  126. ** 57->5, 73->4. Or one of 719 other combinations might be used. It
  127. ** does not really matter. What is important is that sparse cursor
  128. ** numbers all get mapped into bit numbers that begin with 0 and contain
  129. ** no gaps.
  130. */
  131. struct ExprMaskSet {
  132. int n; /* Number of assigned cursor values */
  133. int ix[sizeof(Bitmask)*8]; /* Cursor assigned to each bit */
  134. };
  135. /*
  136. ** Bitmasks for the operators that indices are able to exploit. An
  137. ** OR-ed combination of these values can be used when searching for
  138. ** terms in the where clause.
  139. */
  140. #define WO_IN 1
  141. #define WO_EQ 2
  142. #define WO_LT (WO_EQ<<(TK_LT-TK_EQ))
  143. #define WO_LE (WO_EQ<<(TK_LE-TK_EQ))
  144. #define WO_GT (WO_EQ<<(TK_GT-TK_EQ))
  145. #define WO_GE (WO_EQ<<(TK_GE-TK_EQ))
  146. #define WO_MATCH 64
  147. #define WO_ISNULL 128
  148. /*
  149. ** Value for flags returned by bestIndex().
  150. **
  151. ** The least significant byte is reserved as a mask for WO_ values above.
  152. ** The WhereLevel.flags field is usually set to WO_IN|WO_EQ|WO_ISNULL.
  153. ** But if the table is the right table of a left join, WhereLevel.flags
  154. ** is set to WO_IN|WO_EQ. The WhereLevel.flags field can then be used as
  155. ** the "op" parameter to findTerm when we are resolving equality constraints.
  156. ** ISNULL constraints will then not be used on the right table of a left
  157. ** join. Tickets #2177 and #2189.
  158. */
  159. #define WHERE_ROWID_EQ 0x000100 /* rowid=EXPR or rowid IN (...) */
  160. #define WHERE_ROWID_RANGE 0x000200 /* rowid<EXPR and/or rowid>EXPR */
  161. #define WHERE_COLUMN_EQ 0x001000 /* x=EXPR or x IN (...) */
  162. #define WHERE_COLUMN_RANGE 0x002000 /* x<EXPR and/or x>EXPR */
  163. #define WHERE_COLUMN_IN 0x004000 /* x IN (...) */
  164. #define WHERE_TOP_LIMIT 0x010000 /* x<EXPR or x<=EXPR constraint */
  165. #define WHERE_BTM_LIMIT 0x020000 /* x>EXPR or x>=EXPR constraint */
  166. #define WHERE_IDX_ONLY 0x080000 /* Use index only - omit table */
  167. #define WHERE_ORDERBY 0x100000 /* Output will appear in correct order */
  168. #define WHERE_REVERSE 0x200000 /* Scan in reverse order */
  169. #define WHERE_UNIQUE 0x400000 /* Selects no more than one row */
  170. #define WHERE_VIRTUALTABLE 0x800000 /* Use virtual-table processing */
  171. /*
  172. ** Initialize a preallocated WhereClause structure.
  173. */
  174. static void whereClauseInit(
  175. WhereClause *pWC, /* The WhereClause to be initialized */
  176. Parse *pParse, /* The parsing context */
  177. ExprMaskSet *pMaskSet /* Mapping from table indices to bitmasks */
  178. ){
  179. pWC->pParse = pParse;
  180. pWC->pMaskSet = pMaskSet;
  181. pWC->nTerm = 0;
  182. pWC->nSlot = ArraySize(pWC->aStatic);
  183. pWC->a = pWC->aStatic;
  184. }
  185. /*
  186. ** Deallocate a WhereClause structure. The WhereClause structure
  187. ** itself is not freed. This routine is the inverse of whereClauseInit().
  188. */
  189. static void whereClauseClear(WhereClause *pWC){
  190. int i;
  191. WhereTerm *a;
  192. for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
  193. if( a->flags & TERM_DYNAMIC ){
  194. sqlite3ExprDelete(a->pExpr);
  195. }
  196. }
  197. if( pWC->a!=pWC->aStatic ){
  198. sqlite3_free(pWC->a);
  199. }
  200. }
  201. /*
  202. ** Add a new entries to the WhereClause structure. Increase the allocated
  203. ** space as necessary.
  204. **
  205. ** If the flags argument includes TERM_DYNAMIC, then responsibility
  206. ** for freeing the expression p is assumed by the WhereClause object.
  207. **
  208. ** WARNING: This routine might reallocate the space used to store
  209. ** WhereTerms. All pointers to WhereTerms should be invalided after
  210. ** calling this routine. Such pointers may be reinitialized by referencing
  211. ** the pWC->a[] array.
  212. */
  213. static int whereClauseInsert(WhereClause *pWC, Expr *p, int flags){
  214. WhereTerm *pTerm;
  215. int idx;
  216. if( pWC->nTerm>=pWC->nSlot ){
  217. WhereTerm *pOld = pWC->a;
  218. pWC->a = sqlite3_malloc( sizeof(pWC->a[0])*pWC->nSlot*2 );
  219. if( pWC->a==0 ){
  220. pWC->pParse->db->mallocFailed = 1;
  221. if( flags & TERM_DYNAMIC ){
  222. sqlite3ExprDelete(p);
  223. }
  224. pWC->a = pOld;
  225. return 0;
  226. }
  227. memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
  228. if( pOld!=pWC->aStatic ){
  229. sqlite3_free(pOld);
  230. }
  231. pWC->nSlot *= 2;
  232. }
  233. pTerm = &pWC->a[idx = pWC->nTerm];
  234. pWC->nTerm++;
  235. pTerm->pExpr = p;
  236. pTerm->flags = flags;
  237. pTerm->pWC = pWC;
  238. pTerm->iParent = -1;
  239. return idx;
  240. }
  241. /*
  242. ** This routine identifies subexpressions in the WHERE clause where
  243. ** each subexpression is separated by the AND operator or some other
  244. ** operator specified in the op parameter. The WhereClause structure
  245. ** is filled with pointers to subexpressions. For example:
  246. **
  247. ** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
  248. ** \________/ \_______________/ \________________/
  249. ** slot[0] slot[1] slot[2]
  250. **
  251. ** The original WHERE clause in pExpr is unaltered. All this routine
  252. ** does is make slot[] entries point to substructure within pExpr.
  253. **
  254. ** In the previous sentence and in the diagram, "slot[]" refers to
  255. ** the WhereClause.a[] array. This array grows as needed to contain
  256. ** all terms of the WHERE clause.
  257. */
  258. static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){
  259. if( pExpr==0 ) return;
  260. if( pExpr->op!=op ){
  261. whereClauseInsert(pWC, pExpr, 0);
  262. }else{
  263. whereSplit(pWC, pExpr->pLeft, op);
  264. whereSplit(pWC, pExpr->pRight, op);
  265. }
  266. }
  267. /*
  268. ** Initialize an expression mask set
  269. */
  270. #define initMaskSet(P) memset(P, 0, sizeof(*P))
  271. /*
  272. ** Return the bitmask for the given cursor number. Return 0 if
  273. ** iCursor is not in the set.
  274. */
  275. static Bitmask getMask(ExprMaskSet *pMaskSet, int iCursor){
  276. int i;
  277. for(i=0; i<pMaskSet->n; i++){
  278. if( pMaskSet->ix[i]==iCursor ){
  279. return ((Bitmask)1)<<i;
  280. }
  281. }
  282. return 0;
  283. }
  284. /*
  285. ** Create a new mask for cursor iCursor.
  286. **
  287. ** There is one cursor per table in the FROM clause. The number of
  288. ** tables in the FROM clause is limited by a test early in the
  289. ** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[]
  290. ** array will never overflow.
  291. */
  292. static void createMask(ExprMaskSet *pMaskSet, int iCursor){
  293. assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
  294. pMaskSet->ix[pMaskSet->n++] = iCursor;
  295. }
  296. /*
  297. ** This routine walks (recursively) an expression tree and generates
  298. ** a bitmask indicating which tables are used in that expression
  299. ** tree.
  300. **
  301. ** In order for this routine to work, the calling function must have
  302. ** previously invoked sqlite3ExprResolveNames() on the expression. See
  303. ** the header comment on that routine for additional information.
  304. ** The sqlite3ExprResolveNames() routines looks for column names and
  305. ** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
  306. ** the VDBE cursor number of the table. This routine just has to
  307. ** translate the cursor numbers into bitmask values and OR all
  308. ** the bitmasks together.
  309. */
  310. static Bitmask exprListTableUsage(ExprMaskSet*, ExprList*);
  311. static Bitmask exprSelectTableUsage(ExprMaskSet*, Select*);
  312. static Bitmask exprTableUsage(ExprMaskSet *pMaskSet, Expr *p){
  313. Bitmask mask = 0;
  314. if( p==0 ) return 0;
  315. if( p->op==TK_COLUMN ){
  316. mask = getMask(pMaskSet, p->iTable);
  317. return mask;
  318. }
  319. mask = exprTableUsage(pMaskSet, p->pRight);
  320. mask |= exprTableUsage(pMaskSet, p->pLeft);
  321. mask |= exprListTableUsage(pMaskSet, p->pList);
  322. mask |= exprSelectTableUsage(pMaskSet, p->pSelect);
  323. return mask;
  324. }
  325. static Bitmask exprListTableUsage(ExprMaskSet *pMaskSet, ExprList *pList){
  326. int i;
  327. Bitmask mask = 0;
  328. if( pList ){
  329. for(i=0; i<pList->nExpr; i++){
  330. mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
  331. }
  332. }
  333. return mask;
  334. }
  335. static Bitmask exprSelectTableUsage(ExprMaskSet *pMaskSet, Select *pS){
  336. Bitmask mask = 0;
  337. while( pS ){
  338. mask |= exprListTableUsage(pMaskSet, pS->pEList);
  339. mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
  340. mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
  341. mask |= exprTableUsage(pMaskSet, pS->pWhere);
  342. mask |= exprTableUsage(pMaskSet, pS->pHaving);
  343. pS = pS->pPrior;
  344. }
  345. return mask;
  346. }
  347. /*
  348. ** Return TRUE if the given operator is one of the operators that is
  349. ** allowed for an indexable WHERE clause term. The allowed operators are
  350. ** "=", "<", ">", "<=", ">=", and "IN".
  351. */
  352. static int allowedOp(int op){
  353. assert( TK_GT>TK_EQ && TK_GT<TK_GE );
  354. assert( TK_LT>TK_EQ && TK_LT<TK_GE );
  355. assert( TK_LE>TK_EQ && TK_LE<TK_GE );
  356. assert( TK_GE==TK_EQ+4 );
  357. return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
  358. }
  359. /*
  360. ** Swap two objects of type T.
  361. */
  362. #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
  363. /*
  364. ** Commute a comparision operator. Expressions of the form "X op Y"
  365. ** are converted into "Y op X".
  366. **
  367. ** If a collation sequence is associated with either the left or right
  368. ** side of the comparison, it remains associated with the same side after
  369. ** the commutation. So "Y collate NOCASE op X" becomes
  370. ** "X collate NOCASE op Y". This is because any collation sequence on
  371. ** the left hand side of a comparison overrides any collation sequence
  372. ** attached to the right. For the same reason the EP_ExpCollate flag
  373. ** is not commuted.
  374. */
  375. static void exprCommute(Expr *pExpr){
  376. u16 expRight = (pExpr->pRight->flags & EP_ExpCollate);
  377. u16 expLeft = (pExpr->pLeft->flags & EP_ExpCollate);
  378. assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
  379. SWAP(CollSeq*,pExpr->pRight->pColl,pExpr->pLeft->pColl);
  380. pExpr->pRight->flags = (pExpr->pRight->flags & ~EP_ExpCollate) | expLeft;
  381. pExpr->pLeft->flags = (pExpr->pLeft->flags & ~EP_ExpCollate) | expRight;
  382. SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
  383. if( pExpr->op>=TK_GT ){
  384. assert( TK_LT==TK_GT+2 );
  385. assert( TK_GE==TK_LE+2 );
  386. assert( TK_GT>TK_EQ );
  387. assert( TK_GT<TK_LE );
  388. assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
  389. pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
  390. }
  391. }
  392. /*
  393. ** Translate from TK_xx operator to WO_xx bitmask.
  394. */
  395. static int operatorMask(int op){
  396. int c;
  397. assert( allowedOp(op) );
  398. if( op==TK_IN ){
  399. c = WO_IN;
  400. }else if( op==TK_ISNULL ){
  401. c = WO_ISNULL;
  402. }else{
  403. c = WO_EQ<<(op-TK_EQ);
  404. }
  405. assert( op!=TK_ISNULL || c==WO_ISNULL );
  406. assert( op!=TK_IN || c==WO_IN );
  407. assert( op!=TK_EQ || c==WO_EQ );
  408. assert( op!=TK_LT || c==WO_LT );
  409. assert( op!=TK_LE || c==WO_LE );
  410. assert( op!=TK_GT || c==WO_GT );
  411. assert( op!=TK_GE || c==WO_GE );
  412. return c;
  413. }
  414. /*
  415. ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
  416. ** where X is a reference to the iColumn of table iCur and <op> is one of
  417. ** the WO_xx operator codes specified by the op parameter.
  418. ** Return a pointer to the term. Return 0 if not found.
  419. */
  420. static WhereTerm *findTerm(
  421. WhereClause *pWC, /* The WHERE clause to be searched */
  422. int iCur, /* Cursor number of LHS */
  423. int iColumn, /* Column number of LHS */
  424. Bitmask notReady, /* RHS must not overlap with this mask */
  425. u16 op, /* Mask of WO_xx values describing operator */
  426. Index *pIdx /* Must be compatible with this index, if not NULL */
  427. ){
  428. WhereTerm *pTerm;
  429. int k;
  430. for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
  431. if( pTerm->leftCursor==iCur
  432. && (pTerm->prereqRight & notReady)==0
  433. && pTerm->leftColumn==iColumn
  434. && (pTerm->eOperator & op)!=0
  435. ){
  436. if( iCur>=0 && pIdx && pTerm->eOperator!=WO_ISNULL ){
  437. Expr *pX = pTerm->pExpr;
  438. CollSeq *pColl;
  439. char idxaff;
  440. int j;
  441. Parse *pParse = pWC->pParse;
  442. idxaff = pIdx->pTable->aCol[iColumn].affinity;
  443. if( !sqlite3IndexAffinityOk(pX, idxaff) ) continue;
  444. /* Figure out the collation sequence required from an index for
  445. ** it to be useful for optimising expression pX. Store this
  446. ** value in variable pColl.
  447. */
  448. assert(pX->pLeft);
  449. pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
  450. if( !pColl ){
  451. pColl = pParse->db->pDfltColl;
  452. }
  453. for(j=0; j<pIdx->nColumn && pIdx->aiColumn[j]!=iColumn; j++){}
  454. assert( j<pIdx->nColumn );
  455. if( sqlite3StrICmp(pColl->zName, pIdx->azColl[j]) ) continue;
  456. }
  457. return pTerm;
  458. }
  459. }
  460. return 0;
  461. }
  462. /* Forward reference */
  463. static void exprAnalyze(SrcList*, WhereClause*, int);
  464. /*
  465. ** Call exprAnalyze on all terms in a WHERE clause.
  466. **
  467. **
  468. */
  469. static void exprAnalyzeAll(
  470. SrcList *pTabList, /* the FROM clause */
  471. WhereClause *pWC /* the WHERE clause to be analyzed */
  472. ){
  473. int i;
  474. for(i=pWC->nTerm-1; i>=0; i--){
  475. exprAnalyze(pTabList, pWC, i);
  476. }
  477. }
  478. #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
  479. /*
  480. ** Check to see if the given expression is a LIKE or GLOB operator that
  481. ** can be optimized using inequality constraints. Return TRUE if it is
  482. ** so and false if not.
  483. **
  484. ** In order for the operator to be optimizible, the RHS must be a string
  485. ** literal that does not begin with a wildcard.
  486. */
  487. static int isLikeOrGlob(
  488. sqlite3 *db, /* The database */
  489. Expr *pExpr, /* Test this expression */
  490. int *pnPattern, /* Number of non-wildcard prefix characters */
  491. int *pisComplete /* True if the only wildcard is % in the last character */
  492. ){
  493. const char *z;
  494. Expr *pRight, *pLeft;
  495. ExprList *pList;
  496. int c, cnt;
  497. int noCase;
  498. char wc[3];
  499. CollSeq *pColl;
  500. if( !sqlite3IsLikeFunction(db, pExpr, &noCase, wc) ){
  501. return 0;
  502. }
  503. pList = pExpr->pList;
  504. pRight = pList->a[0].pExpr;
  505. if( pRight->op!=TK_STRING ){
  506. return 0;
  507. }
  508. pLeft = pList->a[1].pExpr;
  509. if( pLeft->op!=TK_COLUMN ){
  510. return 0;
  511. }
  512. pColl = pLeft->pColl;
  513. if( pColl==0 ){
  514. /* TODO: Coverage testing doesn't get this case. Is it actually possible
  515. ** for an expression of type TK_COLUMN to not have an assigned collation
  516. ** sequence at this point?
  517. */
  518. pColl = db->pDfltColl;
  519. }
  520. if( (pColl->type!=SQLITE_COLL_BINARY || noCase) &&
  521. (pColl->type!=SQLITE_COLL_NOCASE || !noCase) ){
  522. return 0;
  523. }
  524. sqlite3DequoteExpr(db, pRight);
  525. z = (char *)pRight->token.z;
  526. cnt = 0;
  527. if( z ){
  528. while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){ cnt++; }
  529. }
  530. if( cnt==0 || 255==(u8)z[cnt] ){
  531. return 0;
  532. }
  533. *pisComplete = z[cnt]==wc[0] && z[cnt+1]==0;
  534. *pnPattern = cnt;
  535. return 1;
  536. }
  537. #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
  538. #ifndef SQLITE_OMIT_VIRTUALTABLE
  539. /*
  540. ** Check to see if the given expression is of the form
  541. **
  542. ** column MATCH expr
  543. **
  544. ** If it is then return TRUE. If not, return FALSE.
  545. */
  546. static int isMatchOfColumn(
  547. Expr *pExpr /* Test this expression */
  548. ){
  549. ExprList *pList;
  550. if( pExpr->op!=TK_FUNCTION ){
  551. return 0;
  552. }
  553. if( pExpr->token.n!=5 ||
  554. sqlite3StrNICmp((const char*)pExpr->token.z,"match",5)!=0 ){
  555. return 0;
  556. }
  557. pList = pExpr->pList;
  558. if( pList->nExpr!=2 ){
  559. return 0;
  560. }
  561. if( pList->a[1].pExpr->op != TK_COLUMN ){
  562. return 0;
  563. }
  564. return 1;
  565. }
  566. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  567. /*
  568. ** If the pBase expression originated in the ON or USING clause of
  569. ** a join, then transfer the appropriate markings over to derived.
  570. */
  571. static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
  572. pDerived->flags |= pBase->flags & EP_FromJoin;
  573. pDerived->iRightJoinTable = pBase->iRightJoinTable;
  574. }
  575. #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
  576. /*
  577. ** Return TRUE if the given term of an OR clause can be converted
  578. ** into an IN clause. The iCursor and iColumn define the left-hand
  579. ** side of the IN clause.
  580. **
  581. ** The context is that we have multiple OR-connected equality terms
  582. ** like this:
  583. **
  584. ** a=<expr1> OR a=<expr2> OR b=<expr3> OR ...
  585. **
  586. ** The pOrTerm input to this routine corresponds to a single term of
  587. ** this OR clause. In order for the term to be a condidate for
  588. ** conversion to an IN operator, the following must be true:
  589. **
  590. ** * The left-hand side of the term must be the column which
  591. ** is identified by iCursor and iColumn.
  592. **
  593. ** * If the right-hand side is also a column, then the affinities
  594. ** of both right and left sides must be such that no type
  595. ** conversions are required on the right. (Ticket #2249)
  596. **
  597. ** If both of these conditions are true, then return true. Otherwise
  598. ** return false.
  599. */
  600. static int orTermIsOptCandidate(WhereTerm *pOrTerm, int iCursor, int iColumn){
  601. int affLeft, affRight;
  602. assert( pOrTerm->eOperator==WO_EQ );
  603. if( pOrTerm->leftCursor!=iCursor ){
  604. return 0;
  605. }
  606. if( pOrTerm->leftColumn!=iColumn ){
  607. return 0;
  608. }
  609. affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
  610. if( affRight==0 ){
  611. return 1;
  612. }
  613. affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
  614. if( affRight!=affLeft ){
  615. return 0;
  616. }
  617. return 1;
  618. }
  619. /*
  620. ** Return true if the given term of an OR clause can be ignored during
  621. ** a check to make sure all OR terms are candidates for optimization.
  622. ** In other words, return true if a call to the orTermIsOptCandidate()
  623. ** above returned false but it is not necessary to disqualify the
  624. ** optimization.
  625. **
  626. ** Suppose the original OR phrase was this:
  627. **
  628. ** a=4 OR a=11 OR a=b
  629. **
  630. ** During analysis, the third term gets flipped around and duplicate
  631. ** so that we are left with this:
  632. **
  633. ** a=4 OR a=11 OR a=b OR b=a
  634. **
  635. ** Since the last two terms are duplicates, only one of them
  636. ** has to qualify in order for the whole phrase to qualify. When
  637. ** this routine is called, we know that pOrTerm did not qualify.
  638. ** This routine merely checks to see if pOrTerm has a duplicate that
  639. ** might qualify. If there is a duplicate that has not yet been
  640. ** disqualified, then return true. If there are no duplicates, or
  641. ** the duplicate has also been disqualifed, return false.
  642. */
  643. static int orTermHasOkDuplicate(WhereClause *pOr, WhereTerm *pOrTerm){
  644. if( pOrTerm->flags & TERM_COPIED ){
  645. /* This is the original term. The duplicate is to the left had
  646. ** has not yet been analyzed and thus has not yet been disqualified. */
  647. return 1;
  648. }
  649. if( (pOrTerm->flags & TERM_VIRTUAL)!=0
  650. && (pOr->a[pOrTerm->iParent].flags & TERM_OR_OK)!=0 ){
  651. /* This is a duplicate term. The original qualified so this one
  652. ** does not have to. */
  653. return 1;
  654. }
  655. /* This is either a singleton term or else it is a duplicate for
  656. ** which the original did not qualify. Either way we are done for. */
  657. return 0;
  658. }
  659. #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
  660. /*
  661. ** The input to this routine is an WhereTerm structure with only the
  662. ** "pExpr" field filled in. The job of this routine is to analyze the
  663. ** subexpression and populate all the other fields of the WhereTerm
  664. ** structure.
  665. **
  666. ** If the expression is of the form "<expr> <op> X" it gets commuted
  667. ** to the standard form of "X <op> <expr>". If the expression is of
  668. ** the form "X <op> Y" where both X and Y are columns, then the original
  669. ** expression is unchanged and a new virtual expression of the form
  670. ** "Y <op> X" is added to the WHERE clause and analyzed separately.
  671. */
  672. static void exprAnalyze(
  673. SrcList *pSrc, /* the FROM clause */
  674. WhereClause *pWC, /* the WHERE clause */
  675. int idxTerm /* Index of the term to be analyzed */
  676. ){
  677. WhereTerm *pTerm;
  678. ExprMaskSet *pMaskSet;
  679. Expr *pExpr;
  680. Bitmask prereqLeft;
  681. Bitmask prereqAll;
  682. int nPattern;
  683. int isComplete;
  684. int op;
  685. Parse *pParse = pWC->pParse;
  686. sqlite3 *db = pParse->db;
  687. if( db->mallocFailed ){
  688. return;
  689. }
  690. pTerm = &pWC->a[idxTerm];
  691. pMaskSet = pWC->pMaskSet;
  692. pExpr = pTerm->pExpr;
  693. prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
  694. op = pExpr->op;
  695. if( op==TK_IN ){
  696. assert( pExpr->pRight==0 );
  697. pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->pList)
  698. | exprSelectTableUsage(pMaskSet, pExpr->pSelect);
  699. }else if( op==TK_ISNULL ){
  700. pTerm->prereqRight = 0;
  701. }else{
  702. pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
  703. }
  704. prereqAll = exprTableUsage(pMaskSet, pExpr);
  705. if( ExprHasProperty(pExpr, EP_FromJoin) ){
  706. prereqAll |= getMask(pMaskSet, pExpr->iRightJoinTable);
  707. }
  708. pTerm->prereqAll = prereqAll;
  709. pTerm->leftCursor = -1;
  710. pTerm->iParent = -1;
  711. pTerm->eOperator = 0;
  712. if( allowedOp(op) && (pTerm->prereqRight & prereqLeft)==0 ){
  713. Expr *pLeft = pExpr->pLeft;
  714. Expr *pRight = pExpr->pRight;
  715. if( pLeft->op==TK_COLUMN ){
  716. pTerm->leftCursor = pLeft->iTable;
  717. pTerm->leftColumn = pLeft->iColumn;
  718. pTerm->eOperator = operatorMask(op);
  719. }
  720. if( pRight && pRight->op==TK_COLUMN ){
  721. WhereTerm *pNew;
  722. Expr *pDup;
  723. if( pTerm->leftCursor>=0 ){
  724. int idxNew;
  725. pDup = sqlite3ExprDup(db, pExpr);
  726. if( db->mallocFailed ){
  727. sqlite3ExprDelete(pDup);
  728. return;
  729. }
  730. idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
  731. if( idxNew==0 ) return;
  732. pNew = &pWC->a[idxNew];
  733. pNew->iParent = idxTerm;
  734. pTerm = &pWC->a[idxTerm];
  735. pTerm->nChild = 1;
  736. pTerm->flags |= TERM_COPIED;
  737. }else{
  738. pDup = pExpr;
  739. pNew = pTerm;
  740. }
  741. exprCommute(pDup);
  742. pLeft = pDup->pLeft;
  743. pNew->leftCursor = pLeft->iTable;
  744. pNew->leftColumn = pLeft->iColumn;
  745. pNew->prereqRight = prereqLeft;
  746. pNew->prereqAll = prereqAll;
  747. pNew->eOperator = operatorMask(pDup->op);
  748. }
  749. }
  750. #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
  751. /* If a term is the BETWEEN operator, create two new virtual terms
  752. ** that define the range that the BETWEEN implements.
  753. */
  754. else if( pExpr->op==TK_BETWEEN ){
  755. ExprList *pList = pExpr->pList;
  756. int i;
  757. static const u8 ops[] = {TK_GE, TK_LE};
  758. assert( pList!=0 );
  759. assert( pList->nExpr==2 );
  760. for(i=0; i<2; i++){
  761. Expr *pNewExpr;
  762. int idxNew;
  763. pNewExpr = sqlite3Expr(db, ops[i], sqlite3ExprDup(db, pExpr->pLeft),
  764. sqlite3ExprDup(db, pList->a[i].pExpr), 0);
  765. idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
  766. exprAnalyze(pSrc, pWC, idxNew);
  767. pTerm = &pWC->a[idxTerm];
  768. pWC->a[idxNew].iParent = idxTerm;
  769. }
  770. pTerm->nChild = 2;
  771. }
  772. #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
  773. #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
  774. /* Attempt to convert OR-connected terms into an IN operator so that
  775. ** they can make use of indices. Example:
  776. **
  777. ** x = expr1 OR expr2 = x OR x = expr3
  778. **
  779. ** is converted into
  780. **
  781. ** x IN (expr1,expr2,expr3)
  782. **
  783. ** This optimization must be omitted if OMIT_SUBQUERY is defined because
  784. ** the compiler for the the IN operator is part of sub-queries.
  785. */
  786. else if( pExpr->op==TK_OR ){
  787. int ok;
  788. int i, j;
  789. int iColumn, iCursor;
  790. WhereClause sOr;
  791. WhereTerm *pOrTerm;
  792. assert( (pTerm->flags & TERM_DYNAMIC)==0 );
  793. whereClauseInit(&sOr, pWC->pParse, pMaskSet);
  794. whereSplit(&sOr, pExpr, TK_OR);
  795. exprAnalyzeAll(pSrc, &sOr);
  796. assert( sOr.nTerm>=2 );
  797. j = 0;
  798. do{
  799. assert( j<sOr.nTerm );
  800. iColumn = sOr.a[j].leftColumn;
  801. iCursor = sOr.a[j].leftCursor;
  802. ok = iCursor>=0;
  803. for(i=sOr.nTerm-1, pOrTerm=sOr.a; i>=0 && ok; i--, pOrTerm++){
  804. if( pOrTerm->eOperator!=WO_EQ ){
  805. goto or_not_possible;
  806. }
  807. if( orTermIsOptCandidate(pOrTerm, iCursor, iColumn) ){
  808. pOrTerm->flags |= TERM_OR_OK;
  809. }else if( orTermHasOkDuplicate(&sOr, pOrTerm) ){
  810. pOrTerm->flags &= ~TERM_OR_OK;
  811. }else{
  812. ok = 0;
  813. }
  814. }
  815. }while( !ok && (sOr.a[j++].flags & TERM_COPIED)!=0 && j<2 );
  816. if( ok ){
  817. ExprList *pList = 0;
  818. Expr *pNew, *pDup;
  819. Expr *pLeft = 0;
  820. for(i=sOr.nTerm-1, pOrTerm=sOr.a; i>=0 && ok; i--, pOrTerm++){
  821. if( (pOrTerm->flags & TERM_OR_OK)==0 ) continue;
  822. pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight);
  823. pList = sqlite3ExprListAppend(pWC->pParse, pList, pDup, 0);
  824. pLeft = pOrTerm->pExpr->pLeft;
  825. }
  826. assert( pLeft!=0 );
  827. pDup = sqlite3ExprDup(db, pLeft);
  828. pNew = sqlite3Expr(db, TK_IN, pDup, 0, 0);
  829. if( pNew ){
  830. int idxNew;
  831. transferJoinMarkings(pNew, pExpr);
  832. pNew->pList = pList;
  833. idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
  834. exprAnalyze(pSrc, pWC, idxNew);
  835. pTerm = &pWC->a[idxTerm];
  836. pWC->a[idxNew].iParent = idxTerm;
  837. pTerm->nChild = 1;
  838. }else{
  839. sqlite3ExprListDelete(pList);
  840. }
  841. }
  842. or_not_possible:
  843. whereClauseClear(&sOr);
  844. }
  845. #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
  846. #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
  847. /* Add constraints to reduce the search space on a LIKE or GLOB
  848. ** operator.
  849. */
  850. if( isLikeOrGlob(db, pExpr, &nPattern, &isComplete) ){
  851. Expr *pLeft, *pRight;
  852. Expr *pStr1, *pStr2;
  853. Expr *pNewExpr1, *pNewExpr2;
  854. int idxNew1, idxNew2;
  855. pLeft = pExpr->pList->a[1].pExpr;
  856. pRight = pExpr->pList->a[0].pExpr;
  857. pStr1 = sqlite3PExpr(pParse, TK_STRING, 0, 0, 0);
  858. if( pStr1 ){
  859. sqlite3TokenCopy(db, &pStr1->token, &pRight->token);
  860. pStr1->token.n = nPattern;
  861. pStr1->flags = EP_Dequoted;
  862. }
  863. pStr2 = sqlite3ExprDup(db, pStr1);
  864. if( !db->mallocFailed ){
  865. assert( pStr2->token.dyn );
  866. ++*(u8*)&pStr2->token.z[nPattern-1];
  867. }
  868. pNewExpr1 = sqlite3PExpr(pParse, TK_GE, sqlite3ExprDup(db,pLeft), pStr1, 0);
  869. idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
  870. exprAnalyze(pSrc, pWC, idxNew1);
  871. pNewExpr2 = sqlite3PExpr(pParse, TK_LT, sqlite3ExprDup(db,pLeft), pStr2, 0);
  872. idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
  873. exprAnalyze(pSrc, pWC, idxNew2);
  874. pTerm = &pWC->a[idxTerm];
  875. if( isComplete ){
  876. pWC->a[idxNew1].iParent = idxTerm;
  877. pWC->a[idxNew2].iParent = idxTerm;
  878. pTerm->nChild = 2;
  879. }
  880. }
  881. #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
  882. #ifndef SQLITE_OMIT_VIRTUALTABLE
  883. /* Add a WO_MATCH auxiliary term to the constraint set if the
  884. ** current expression is of the form: column MATCH expr.
  885. ** This information is used by the xBestIndex methods of
  886. ** virtual tables. The native query optimizer does not attempt
  887. ** to do anything with MATCH functions.
  888. */
  889. if( isMatchOfColumn(pExpr) ){
  890. int idxNew;
  891. Expr *pRight, *pLeft;
  892. WhereTerm *pNewTerm;
  893. Bitmask prereqColumn, prereqExpr;
  894. pRight = pExpr->pList->a[0].pExpr;
  895. pLeft = pExpr->pList->a[1].pExpr;
  896. prereqExpr = exprTableUsage(pMaskSet, pRight);
  897. prereqColumn = exprTableUsage(pMaskSet, pLeft);
  898. if( (prereqExpr & prereqColumn)==0 ){
  899. Expr *pNewExpr;
  900. pNewExpr = sqlite3Expr(db, TK_MATCH, 0, sqlite3ExprDup(db, pRight), 0);
  901. idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
  902. pNewTerm = &pWC->a[idxNew];
  903. pNewTerm->prereqRight = prereqExpr;
  904. pNewTerm->leftCursor = pLeft->iTable;
  905. pNewTerm->leftColumn = pLeft->iColumn;
  906. pNewTerm->eOperator = WO_MATCH;
  907. pNewTerm->iParent = idxTerm;
  908. pTerm = &pWC->a[idxTerm];
  909. pTerm->nChild = 1;
  910. pTerm->flags |= TERM_COPIED;
  911. pNewTerm->prereqAll = pTerm->prereqAll;
  912. }
  913. }
  914. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  915. }
  916. /*
  917. ** Return TRUE if any of the expressions in pList->a[iFirst...] contain
  918. ** a reference to any table other than the iBase table.
  919. */
  920. static int referencesOtherTables(
  921. ExprList *pList, /* Search expressions in ths list */
  922. ExprMaskSet *pMaskSet, /* Mapping from tables to bitmaps */
  923. int iFirst, /* Be searching with the iFirst-th expression */
  924. int iBase /* Ignore references to this table */
  925. ){
  926. Bitmask allowed = ~getMask(pMaskSet, iBase);
  927. while( iFirst<pList->nExpr ){
  928. if( (exprTableUsage(pMaskSet, pList->a[iFirst++].pExpr)&allowed)!=0 ){
  929. return 1;
  930. }
  931. }
  932. return 0;
  933. }
  934. /*
  935. ** This routine decides if pIdx can be used to satisfy the ORDER BY
  936. ** clause. If it can, it returns 1. If pIdx cannot satisfy the
  937. ** ORDER BY clause, this routine returns 0.
  938. **
  939. ** pOrderBy is an ORDER BY clause from a SELECT statement. pTab is the
  940. ** left-most table in the FROM clause of that same SELECT statement and
  941. ** the table has a cursor number of "base". pIdx is an index on pTab.
  942. **
  943. ** nEqCol is the number of columns of pIdx that are used as equality
  944. ** constraints. Any of these columns may be missing from the ORDER BY
  945. ** clause and the match can still be a success.
  946. **
  947. ** All terms of the ORDER BY that match against the index must be either
  948. ** ASC or DESC. (Terms of the ORDER BY clause past the end of a UNIQUE
  949. ** index do not need to satisfy this constraint.) The *pbRev value is
  950. ** set to 1 if the ORDER BY clause is all DESC and it is set to 0 if
  951. ** the ORDER BY clause is all ASC.
  952. */
  953. static int isSortingIndex(
  954. Parse *pParse, /* Parsing context */
  955. ExprMaskSet *pMaskSet, /* Mapping from table indices to bitmaps */
  956. Index *pIdx, /* The index we are testing */
  957. int base, /* Cursor number for the table to be sorted */
  958. ExprList *pOrderBy, /* The ORDER BY clause */
  959. int nEqCol, /* Number of index columns with == constraints */
  960. int *pbRev /* Set to 1 if ORDER BY is DESC */
  961. ){
  962. int i, j; /* Loop counters */
  963. int sortOrder = 0; /* XOR of index and ORDER BY sort direction */
  964. int nTerm; /* Number of ORDER BY terms */
  965. struct ExprList_item *pTerm; /* A term of the ORDER BY clause */
  966. sqlite3 *db = pParse->db;
  967. assert( pOrderBy!=0 );
  968. nTerm = pOrderBy->nExpr;
  969. assert( nTerm>0 );
  970. /* Match terms of the ORDER BY clause against columns of
  971. ** the index.
  972. **
  973. ** Note that indices have pIdx->nColumn regular columns plus
  974. ** one additional column containing the rowid. The rowid column
  975. ** of the index is also allowed to match against the ORDER BY
  976. ** clause.
  977. */
  978. for(i=j=0, pTerm=pOrderBy->a; j<nTerm && i<=pIdx->nColumn; i++){
  979. Expr *pExpr; /* The expression of the ORDER BY pTerm */
  980. CollSeq *pColl; /* The collating sequence of pExpr */
  981. int termSortOrder; /* Sort order for this term */
  982. int iColumn; /* The i-th column of the index. -1 for rowid */
  983. int iSortOrder; /* 1 for DESC, 0 for ASC on the i-th index term */
  984. const char *zColl; /* Name of the collating sequence for i-th index term */
  985. pExpr = pTerm->pExpr;
  986. if( pExpr->op!=TK_COLUMN || pExpr->iTable!=base ){
  987. /* Can not use an index sort on anything that is not a column in the
  988. ** left-most table of the FROM clause */
  989. break;
  990. }
  991. pColl = sqlite3ExprCollSeq(pParse, pExpr);
  992. if( !pColl ){
  993. pColl = db->pDfltColl;
  994. }
  995. if( i<pIdx->nColumn ){
  996. iColumn = pIdx->aiColumn[i];
  997. if( iColumn==pIdx->pTable->iPKey ){
  998. iColumn = -1;
  999. }
  1000. iSortOrder = pIdx->aSortOrder[i];
  1001. zColl = pIdx->azColl[i];
  1002. }else{
  1003. iColumn = -1;
  1004. iSortOrder = 0;
  1005. zColl = pColl->zName;
  1006. }
  1007. if( pExpr->iColumn!=iColumn || sqlite3StrICmp(pColl->zName, zColl) ){
  1008. /* Term j of the ORDER BY clause does not match column i of the index */
  1009. if( i<nEqCol ){
  1010. /* If an index column that is constrained by == fails to match an
  1011. ** ORDER BY term, that is OK. Just ignore that column of the index
  1012. */
  1013. continue;
  1014. }else{
  1015. /* If an index column fails to match and is not constrained by ==
  1016. ** then the index cannot satisfy the ORDER BY constraint.
  1017. */
  1018. return 0;
  1019. }
  1020. }
  1021. assert( pIdx->aSortOrder!=0 );
  1022. assert( pTerm->sortOrder==0 || pTerm->sortOrder==1 );
  1023. assert( iSortOrder==0 || iSortOrder==1 );
  1024. termSortOrder = iSortOrder ^ pTerm->sortOrder;
  1025. if( i>nEqCol ){
  1026. if( termSortOrder!=sortOrder ){
  1027. /* Indices can only be used if all ORDER BY terms past the
  1028. ** equality constraints are all either DESC or ASC. */
  1029. return 0;
  1030. }
  1031. }else{
  1032. sortOrder = termSortOrder;
  1033. }
  1034. j++;
  1035. pTerm++;
  1036. if( iColumn<0 && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
  1037. /* If the indexed column is the primary key and everything matches
  1038. ** so far and none of the ORDER BY terms to the right reference other
  1039. ** tables in the join, then we are assured that the index can be used
  1040. ** to sort because the primary key is unique and so none of the other
  1041. ** columns will make any difference
  1042. */
  1043. j = nTerm;
  1044. }
  1045. }
  1046. *pbRev = sortOrder!=0;
  1047. if( j>=nTerm ){
  1048. /* All terms of the ORDER BY clause are covered by this index so
  1049. ** this index can be used for sorting. */
  1050. return 1;
  1051. }
  1052. if( pIdx->onError!=OE_None && i==pIdx->nColumn
  1053. && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
  1054. /* All terms of this index match some prefix of the ORDER BY clause
  1055. ** and the index is UNIQUE and no terms on the tail of the ORDER BY
  1056. ** clause reference other tables in a join. If this is all true then
  1057. ** the order by clause is superfluous. */
  1058. return 1;
  1059. }
  1060. return 0;
  1061. }
  1062. /*
  1063. ** Check table to see if the ORDER BY clause in pOrderBy can be satisfied
  1064. ** by sorting in order of ROWID. Return true if so and set *pbRev to be
  1065. ** true for reverse ROWID and false for forward ROWID order.
  1066. */
  1067. static int sortableByRowid(
  1068. int base, /* Cursor number for table to be sorted */
  1069. ExprList *pOrderBy, /* The ORDER BY clause */
  1070. ExprMaskSet *pMaskSet, /* Mapping from tables to bitmaps */
  1071. int *pbRev /* Set to 1 if ORDER BY is DESC */
  1072. ){
  1073. Expr *p;
  1074. assert( pOrderBy!=0 );
  1075. assert( pOrderBy->nExpr>0 );
  1076. p = pOrderBy->a[0].pExpr;
  1077. if( p->op==TK_COLUMN && p->iTable==base && p->iColumn==-1
  1078. && !referencesOtherTables(pOrderBy, pMaskSet, 1, base) ){
  1079. *pbRev = pOrderBy->a[0].sortOrder;
  1080. return 1;
  1081. }
  1082. return 0;
  1083. }
  1084. /*
  1085. ** Prepare a crude estimate of the logarithm of the input value.
  1086. ** The results need not be exact. This is only used for estimating
  1087. ** the total cost of performing operatings with O(logN) or O(NlogN)
  1088. ** complexity. Because N is just a guess, it is no great tragedy if
  1089. ** logN is a little off.
  1090. */
  1091. static double estLog(double N){
  1092. double logN = 1;
  1093. double x = 10;
  1094. while( N>x ){
  1095. logN += 1;
  1096. x *= 10;
  1097. }
  1098. return logN;
  1099. }
  1100. /*
  1101. ** Two routines for printing the content of an sqlite3_index_info
  1102. ** structure. Used for testing and debugging only. If neither
  1103. ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
  1104. ** are no-ops.
  1105. */
  1106. #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_DEBUG)
  1107. static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
  1108. int i;
  1109. if( !sqlite3_where_trace ) return;
  1110. for(i=0; i<p->nConstraint; i++){
  1111. sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
  1112. i,
  1113. p->aConstraint[i].iColumn,
  1114. p->aConstraint[i].iTermOffset,
  1115. p->aConstraint[i].op,
  1116. p->aConstraint[i].usable);
  1117. }
  1118. for(i=0; i<p->nOrderBy; i++){
  1119. sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n",
  1120. i,
  1121. p->aOrderBy[i].iColumn,
  1122. p->aOrderBy[i].desc);
  1123. }
  1124. }
  1125. static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
  1126. int i;
  1127. if( !sqlite3_where_trace ) return;
  1128. for(i=0; i<p->nConstraint; i++){
  1129. sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n",
  1130. i,
  1131. p->aConstraintUsage[i].argvIndex,
  1132. p->aConstraintUsage[i].omit);
  1133. }
  1134. sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum);
  1135. sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr);
  1136. sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed);
  1137. sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost);
  1138. }
  1139. #else
  1140. #define TRACE_IDX_INPUTS(A)
  1141. #define TRACE_IDX_OUTPUTS(A)
  1142. #endif
  1143. #ifndef SQLITE_OMIT_VIRTUALTABLE
  1144. /*
  1145. ** Compute the best index for a virtual table.
  1146. **
  1147. ** The best index is computed by the xBestIndex method of the virtual
  1148. ** table module. This routine is really just a wrapper that sets up
  1149. ** the sqlite3_index_info structure that is used to communicate with
  1150. ** xBestIndex.
  1151. **
  1152. ** In a join, this routine might be called multiple times for the
  1153. ** same virtual table. The sqlite3_index_info structure is created
  1154. ** and initialized on the first invocation and reused on all subsequent
  1155. ** invocations. The sqlite3_index_info structure is also used when
  1156. ** code is generated to access the virtual table. The whereInfoDelete()
  1157. ** routine takes care of freeing the sqlite3_index_info structure after
  1158. ** everybody has finished with it.
  1159. */
  1160. static double bestVirtualIndex(
  1161. Parse *pParse, /* The parsing context */
  1162. WhereClause *pWC, /* The WHERE clause */
  1163. struct SrcList_item *pSrc, /* The FROM clause term to search */
  1164. Bitmask notReady, /* Mask of cursors that are not available */
  1165. ExprList *pOrderBy, /* The order by clause */
  1166. int orderByUsable, /* True if we can potential sort */
  1167. sqlite3_index_info **ppIdxInfo /* Index information passed to xBestIndex */
  1168. ){
  1169. Table *pTab = pSrc->pTab;
  1170. sqlite3_index_info *pIdxInfo;
  1171. struct sqlite3_index_constraint *pIdxCons;
  1172. struct sqlite3_index_orderby *pIdxOrderBy;
  1173. struct sqlite3_index_constraint_usage *pUsage;
  1174. WhereTerm *pTerm;
  1175. int i, j;
  1176. int nOrderBy;
  1177. int rc;
  1178. /* If the sqlite3_index_info structure has not been previously
  1179. ** allocated and initialized for this virtual table, then allocate
  1180. ** and initialize it now
  1181. */
  1182. pIdxInfo = *ppIdxInfo;
  1183. if( pIdxInfo==0 ){
  1184. WhereTerm *pTerm;
  1185. int nTerm;
  1186. WHERETRACE(("Recomputing index info for %s...\n", pTab->zName));
  1187. /* Count the number of possible WHERE clause constraints referring
  1188. ** to this virtual table */
  1189. for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  1190. if( pTerm->leftCursor != pSrc->iCursor ) continue;
  1191. if( pTerm->eOperator==WO_IN ) continue;
  1192. if( pTerm->eOperator==WO_ISNULL ) continue;
  1193. nTerm++;
  1194. }
  1195. /* If the ORDER BY clause contains only columns in the current
  1196. ** virtual table then allocate space for the aOrderBy part of
  1197. ** the sqlite3_index_info structure.
  1198. */
  1199. nOrderBy = 0;
  1200. if( pOrderBy ){
  1201. for(i=0; i<pOrderBy->nExpr; i++){
  1202. Expr *pExpr = pOrderBy->a[i].pExpr;
  1203. if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
  1204. }
  1205. if( i==pOrderBy->nExpr ){
  1206. nOrderBy = pOrderBy->nExpr;
  1207. }
  1208. }
  1209. /* Allocate the sqlite3_index_info structure
  1210. */
  1211. pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
  1212. + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
  1213. + sizeof(*pIdxOrderBy)*nOrderBy );
  1214. if( pIdxInfo==0 ){
  1215. sqlite3ErrorMsg(pParse, "out of memory");
  1216. return 0.0;
  1217. }
  1218. *ppIdxInfo = pIdxInfo;
  1219. /* Initialize the structure. The sqlite3_index_info structure contains
  1220. ** many fields that are declared "const" to prevent xBestIndex from
  1221. ** changing them. We have to do some funky casting in order to
  1222. ** initialize those fields.
  1223. */
  1224. pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
  1225. pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
  1226. pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
  1227. *(int*)&pIdxInfo->nConstraint = nTerm;
  1228. *(int*)&pIdxInfo->nOrderBy = nOrderBy;
  1229. *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
  1230. *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
  1231. *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
  1232. pUsage;
  1233. for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  1234. if( pTerm->leftCursor != pSrc->iCursor ) continue;
  1235. if( pTerm->eOperator==WO_IN ) continue;
  1236. if( pTerm->eOperator==WO_ISNULL ) continue;
  1237. pIdxCons[j].iColumn = pTerm->leftColumn;
  1238. pIdxCons[j].iTermOffset = i;
  1239. pIdxCons[j].op = pTerm->eOperator;
  1240. /* The direct assignment in the previous line is possible only because
  1241. ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The
  1242. ** following asserts verify this fact. */
  1243. assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
  1244. assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
  1245. assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
  1246. assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
  1247. assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
  1248. assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
  1249. assert( pTerm->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
  1250. j++;
  1251. }
  1252. for(i=0; i<nOrderBy; i++){
  1253. Expr *pExpr = pOrderBy->a[i].pExpr;
  1254. pIdxOrderBy[i].iColumn = pExpr->iColumn;
  1255. pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
  1256. }
  1257. }
  1258. /* At this point, the sqlite3_index_info structure that pIdxInfo points
  1259. ** to will have been initialized, either during the current invocation or
  1260. ** during some prior invocation. Now we just have to customize the
  1261. ** details of pIdxInfo for the current invocation and pass it to
  1262. ** xBestIndex.
  1263. */
  1264. /* The module name must be defined. Also, by this point there must
  1265. ** be a pointer to an sqlite3_vtab structure. Otherwise
  1266. ** sqlite3ViewGetColumnNames() would have picked up the error.
  1267. */
  1268. assert( pTab->azModuleArg && pTab->azModuleArg[0] );
  1269. assert( pTab->pVtab );
  1270. #if 0
  1271. if( pTab->pVtab==0 ){
  1272. sqlite3ErrorMsg(pParse, "undefined module %s for table %s",
  1273. pTab->azModuleArg[0], pTab->zName);
  1274. return 0.0;
  1275. }
  1276. #endif
  1277. /* Set the aConstraint[].usable fields and initialize all
  1278. ** output variables to zero.
  1279. **
  1280. ** aConstraint[].usable is true for constraints where the right-hand
  1281. ** side contains only references to tables to the left of the current
  1282. ** table. In other words, if the constraint is of the form:
  1283. **
  1284. ** column = expr
  1285. **
  1286. ** and we are evaluating a join, then the constraint on column is
  1287. ** only valid if all tables referenced in expr occur to the left
  1288. ** of the table containing column.
  1289. **
  1290. ** The aConstraints[] array contains entries for all constraints
  1291. ** on the current table. That way we only have to compute it once
  1292. ** even though we might try to pick the best index multiple times.
  1293. ** For each attempt at picking an index, the order of tables in the
  1294. ** join might be different so we have to recompute the usable flag
  1295. ** each time.
  1296. */
  1297. pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
  1298. pUsage = pIdxInfo->aConstraintUsage;
  1299. for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
  1300. j = pIdxCons->iTermOffset;
  1301. pTerm = &pWC->a[j];
  1302. pIdxCons->usable = (pTerm->prereqRight & notReady)==0;
  1303. }
  1304. memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
  1305. if( pIdxInfo->needToFreeIdxStr ){
  1306. sqlite3_free(pIdxInfo->idxStr);
  1307. }
  1308. pIdxInfo->idxStr = 0;
  1309. pIdxInfo->idxNum = 0;
  1310. pIdxInfo->needToFreeIdxStr = 0;
  1311. pIdxInfo->orderByConsumed = 0;
  1312. pIdxInfo->estimatedCost = SQLITE_BIG_DBL / 2.0;
  1313. nOrderBy = pIdxInfo->nOrderBy;
  1314. if( pIdxInfo->nOrderBy && !orderByUsable ){
  1315. *(int*)&pIdxInfo->nOrderBy = 0;
  1316. }
  1317. sqlite3SafetyOff(pParse->db);
  1318. WHERETRACE(("xBestIndex for %s\n", pTab->zName));
  1319. TRACE_IDX_INPUTS(pIdxInfo);
  1320. rc = pTab->pVtab->pModule->xBestIndex(pTab->pVtab, pIdxInfo);
  1321. TRACE_IDX_OUTPUTS(pIdxInfo);
  1322. if( rc!=SQLITE_OK ){
  1323. if( rc==SQLITE_NOMEM ){
  1324. pParse->db->mallocFailed = 1;
  1325. }else {
  1326. sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
  1327. }
  1328. sqlite3SafetyOn(pParse->db);
  1329. }else{
  1330. rc = sqlite3SafetyOn(pParse->db);
  1331. }
  1332. *(int*)&pIdxInfo->nOrderBy = nOrderBy;
  1333. return pIdxInfo->estimatedCost;
  1334. }
  1335. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  1336. /*
  1337. ** Find the best index for accessing a particular table. Return a pointer
  1338. ** to the index, flags that describe how the index should be used, the
  1339. ** number of equality constraints, and the "cost" for this index.
  1340. **
  1341. ** The lowest cost index wins. The cost is an estimate of the amount of
  1342. ** CPU and disk I/O need to process the request using the selected index.
  1343. ** Factors that influence cost include:
  1344. **
  1345. ** * The estimated number of rows that will be retrieved. (The
  1346. ** fewer the better.)
  1347. **
  1348. ** * Whether or not sorting must occur.
  1349. **
  1350. ** * Whether or not there must be separate lookups in the
  1351. ** index and in the main table.
  1352. **
  1353. */
  1354. static double bestIndex(
  1355. Parse *pParse, /* The parsing context */
  1356. WhereClause *pWC, /* The WHERE clause */
  1357. struct SrcList_item *pSrc, /* The FROM clause term to search */
  1358. Bitmask notReady, /* Mask of cursors that are not available */
  1359. ExprList *pOrderBy, /* The order by clause */
  1360. Index **ppIndex, /* Make *ppIndex point to the best index */
  1361. int *pFlags, /* Put flags describing this choice in *pFlags */
  1362. int *pnEq /* Put the number of == or IN constraints here */
  1363. ){
  1364. WhereTerm *pTerm;
  1365. Index *bestIdx = 0; /* Index that gives the lowest cost */
  1366. double lowestCost; /* The cost of using bestIdx */
  1367. int bestFlags = 0; /* Flags associated with bestIdx */
  1368. int bestNEq = 0; /* Best value for nEq */
  1369. int iCur = pSrc->iCursor; /* The cursor of the table to be accessed */
  1370. Index *pProbe; /* An index we are evaluating */
  1371. int rev; /* True to scan in reverse order */
  1372. int flags; /* Flags associated with pProbe */
  1373. int nEq; /* Number of == or IN constraints */
  1374. int eqTermMask; /* Mask of valid equality operators */
  1375. double cost; /* Cost of using pProbe */
  1376. WHERETRACE(("bestIndex: tbl=%s notReady=%x\n", pSrc->pTab->zName, notReady));
  1377. lowestCost = SQLITE_BIG_DBL;
  1378. pProbe = pSrc->pTab->pIndex;
  1379. /* If the table has no indices and there are no terms in the where
  1380. ** clause that refer to the ROWID, then we will never be able to do
  1381. ** anything other than a full table scan on this table. We might as
  1382. ** well put it first in the join order. That way, perhaps it can be
  1383. ** referenced by other tables in the join.
  1384. */
  1385. if( pProbe==0 &&
  1386. findTerm(pWC, iCur, -1, 0, WO_EQ|WO_IN|WO_LT|WO_LE|WO_GT|WO_GE,0)==0 &&
  1387. (pOrderBy==0 || !sortableByRowid(iCur, pOrderBy, pWC->pMaskSet, &rev)) ){
  1388. *pFlags = 0;
  1389. *ppIndex = 0;
  1390. *pnEq = 0;
  1391. return 0.0;
  1392. }
  1393. /* Check for a rowid=EXPR or rowid IN (...) constraints
  1394. */
  1395. pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
  1396. if( pTerm ){
  1397. Expr *pExpr;
  1398. *ppIndex = 0;
  1399. bestFlags = WHERE_ROWID_EQ;
  1400. if( pTerm->eOperator & WO_EQ ){
  1401. /* Rowid== is always the best pick. Look no further. Because only
  1402. ** a single row is generated, output is always in sorted order */
  1403. *pFlags = WHERE_ROWID_EQ | WHERE_UNIQUE;
  1404. *pnEq = 1;
  1405. WHERETRACE(("... best is rowid\n"));
  1406. return 0.0;
  1407. }else if( (pExpr = pTerm->pExpr)->pList!=0 ){
  1408. /* Rowid IN (LIST): cost is NlogN where N is the number of list
  1409. ** elements. */
  1410. lowestCost = pExpr->pList->nExpr;
  1411. lowestCost *= estLog(lowestCost);
  1412. }else{
  1413. /* Rowid IN (SELECT): cost is NlogN where N is the number of rows
  1414. ** in the result of the inner select. We have no way to estimate
  1415. ** that value so make a wild guess. */
  1416. lowestCost = 200;
  1417. }
  1418. WHERETRACE(("... rowid IN cost: %.9g\n", lowestCost));
  1419. }
  1420. /* Estimate the cost of a table scan. If we do not know how many
  1421. ** entries are in the table, use 1 million as a guess.
  1422. */
  1423. cost = pProbe ? pProbe->aiRowEst[0] : 1000000;
  1424. WHERETRACE(("... table scan base cost: %.9g\n", cost));
  1425. flags = WHERE_ROWID_RANGE;
  1426. /* Check for constraints on a range of rowids in a table scan.
  1427. */
  1428. pTerm = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE|WO_GT|WO_GE, 0);
  1429. if( pTerm ){
  1430. if( findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0) ){
  1431. flags |= WHERE_TOP_LIMIT;
  1432. cost /= 3; /* Guess that rowid<EXPR eliminates two-thirds or rows */
  1433. }
  1434. if( findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0) ){
  1435. flags |= WHERE_BTM_LIMIT;
  1436. cost /= 3; /* Guess that rowid>EXPR eliminates two-thirds of rows */
  1437. }
  1438. WHERETRACE(("... rowid range reduces cost to %.9g\n", cost));
  1439. }else{
  1440. flags = 0;
  1441. }
  1442. /* If the table scan does not satisfy the ORDER BY clause, increase
  1443. ** the cost by NlogN to cover the expense of sorting. */
  1444. if( pOrderBy ){
  1445. if( sortableByRowid(iCur, pOrderBy, pWC->pMaskSet, &rev) ){
  1446. flags |= WHERE_ORDERBY|WHERE_ROWID_RANGE;
  1447. if( rev ){
  1448. flags |= WHERE_REVERSE;
  1449. }
  1450. }else{
  1451. cost += cost*estLog(cost);
  1452. WHERETRACE(("... sorting increases cost to %.9g\n", cost));
  1453. }
  1454. }
  1455. if( cost<lowestCost ){
  1456. lowestCost = cost;
  1457. bestFlags = flags;
  1458. }
  1459. /* If the pSrc table is the right table of a LEFT JOIN then we may not
  1460. ** use an index to satisfy IS NULL constraints on that table. This is
  1461. ** because columns might end up being NULL if the table does not match -
  1462. ** a circumstance which the index cannot help us discover. Ticket #2177.
  1463. */
  1464. if( (pSrc->jointype & JT_LEFT)!=0 ){
  1465. eqTermMask = WO_EQ|WO_IN;
  1466. }else{
  1467. eqTermMask = WO_EQ|WO_IN|WO_ISNULL;
  1468. }
  1469. /* Look at each index.
  1470. */
  1471. for(; pProbe; pProbe=pProbe->pNext){
  1472. int i; /* Loop counter */
  1473. double inMultiplier = 1;
  1474. WHERETRACE(("... index %s:\n", pProbe->zName));
  1475. /* Count the number of columns in the index that are satisfied
  1476. ** by x=EXPR constraints or x IN (...) constraints.
  1477. */
  1478. flags = 0;
  1479. for(i=0; i<pProbe->nColumn; i++){
  1480. int j = pProbe->aiColumn[i];
  1481. pTerm = findTerm(pWC, iCur, j, notReady, eqTermMask, pProbe);
  1482. if( pTerm==0 ) break;
  1483. flags |= WHERE_COLUMN_EQ;
  1484. if( pTerm->eOperator & WO_IN ){
  1485. Expr *pExpr = pTerm->pExpr;
  1486. flags |= WHERE_COLUMN_IN;
  1487. if( pExpr->pSelect!=0 ){
  1488. inMultiplier *= 25;
  1489. }else if( pExpr->pList!=0 ){
  1490. inMultiplier *= pExpr->pList->nExpr + 1;
  1491. }
  1492. }
  1493. }
  1494. cost = pProbe->aiRowEst[i] * inMultiplier * estLog(inMultiplier);
  1495. nEq = i;
  1496. if( pProbe->onError!=OE_None && (flags & WHERE_COLUMN_IN)==0
  1497. && nEq==pProbe->nColumn ){
  1498. flags |= WHERE_UNIQUE;
  1499. }
  1500. WHERETRACE(("...... nEq=%d inMult=%.9g cost=%.9g\n",nEq,inMultiplier,cost));
  1501. /* Look for range constraints
  1502. */
  1503. if( nEq<pProbe->nColumn ){
  1504. int j = pProbe->aiColumn[nEq];
  1505. pTerm = findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE|WO_GT|WO_GE, pProbe);
  1506. if( pTerm ){
  1507. flags |= WHERE_COLUMN_RANGE;
  1508. if( findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE, pProbe) ){
  1509. flags |= WHERE_TOP_LIMIT;
  1510. cost /= 3;
  1511. }
  1512. if( findTerm(pWC, iCur, j, notReady, WO_GT|WO_GE, pProbe) ){
  1513. flags |= WHERE_BTM_LIMIT;
  1514. cost /= 3;
  1515. }
  1516. WHERETRACE(("...... range reduces cost to %.9g\n", cost));
  1517. }
  1518. }
  1519. /* Add the additional cost of sorting if that is a factor.
  1520. */
  1521. if( pOrderBy ){
  1522. if( (flags & WHERE_COLUMN_IN)==0 &&
  1523. isSortingIndex(pParse,pWC->pMaskSet,pProbe,iCur,pOrderBy,nEq,&rev) ){
  1524. if( flags==0 ){
  1525. flags = WHERE_COLUMN_RANGE;
  1526. }
  1527. flags |= WHERE_ORDERBY;
  1528. if( rev ){
  1529. flags |= WHERE_REVERSE;
  1530. }
  1531. }else{
  1532. cost += cost*estLog(cost);
  1533. WHERETRACE(("...... orderby increases cost to %.9g\n", cost));
  1534. }
  1535. }
  1536. /* Check to see if we can get away with using just the index without
  1537. ** ever reading the table. If that is the case, then halve the
  1538. ** cost of this index.
  1539. */
  1540. if( flags && pSrc->colUsed < (((Bitmask)1)<<(BMS-1)) ){
  1541. Bitmask m = pSrc->colUsed;
  1542. int j;
  1543. for(j=0; j<pProbe->nColumn; j++){
  1544. int x = pProbe->aiColumn[j];
  1545. if( x<BMS-1 ){
  1546. m &= ~(((Bitmask)1)<<x);
  1547. }
  1548. }
  1549. if( m==0 ){
  1550. flags |= WHERE_IDX_ONLY;
  1551. cost /= 2;
  1552. WHERETRACE(("...... idx-only reduces cost to %.9g\n", cost));
  1553. }
  1554. }
  1555. /* If this index has achieved the lowest cost so far, then use it.
  1556. */
  1557. if( flags && cost < lowestCost ){
  1558. bestIdx = pProbe;
  1559. lowestCost = cost;
  1560. bestFlags = flags;
  1561. bestNEq = nEq;
  1562. }
  1563. }
  1564. /* Report the best result
  1565. */
  1566. *ppIndex = bestIdx;
  1567. WHERETRACE(("best index is %s, cost=%.9g, flags=%x, nEq=%d\n",
  1568. bestIdx ? bestIdx->zName : "(none)", lowestCost, bestFlags, bestNEq));
  1569. *pFlags = bestFlags | eqTermMask;
  1570. *pnEq = bestNEq;
  1571. return lowestCost;
  1572. }
  1573. /*
  1574. ** Disable a term in the WHERE clause. Except, do not disable the term
  1575. ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
  1576. ** or USING clause of that join.
  1577. **
  1578. ** Consider the term t2.z='ok' in the following queries:
  1579. **
  1580. ** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
  1581. ** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
  1582. ** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
  1583. **
  1584. ** The t2.z='ok' is disabled in the in (2) because it originates
  1585. ** in the ON clause. The term is disabled in (3) because it is not part
  1586. ** of a LEFT OUTER JOIN. In (1), the term is not disabled.
  1587. **
  1588. ** Disabling a term causes that term to not be tested in the inner loop
  1589. ** of the join. Disabling is an optimization. When terms are satisfied
  1590. ** by indices, we disable them to prevent redundant tests in the inner
  1591. ** loop. We would get the correct results if nothing were ever disabled,
  1592. ** but joins might run a little slower. The trick is to disable as much
  1593. ** as we can without disabling too much. If we disabled in (1), we'd get
  1594. ** the wrong answer. See ticket #813.
  1595. */
  1596. static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
  1597. if( pTerm
  1598. && (pTerm->flags & TERM_CODED)==0
  1599. && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
  1600. ){
  1601. pTerm->flags |= TERM_CODED;
  1602. if( pTerm->iParent>=0 ){
  1603. WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
  1604. if( (--pOther->nChild)==0 ){
  1605. disableTerm(pLevel, pOther);
  1606. }
  1607. }
  1608. }
  1609. }
  1610. /*
  1611. ** Generate code that builds a probe for an index.
  1612. **
  1613. ** There should be nColumn values on the stack. The index
  1614. ** to be probed is pIdx. Pop the values from the stack and
  1615. ** replace them all with a single record that is the index
  1616. ** problem.
  1617. */
  1618. static void buildIndexProbe(
  1619. Vdbe *v, /* Generate code into this VM */
  1620. int nColumn, /* The number of columns to check for NULL */
  1621. Index *pIdx /* Index that we will be searching */
  1622. ){
  1623. sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
  1624. sqlite3IndexAffinityStr(v, pIdx);
  1625. }
  1626. /*
  1627. ** Generate code for a single equality term of the WHERE clause. An equality
  1628. ** term can be either X=expr or X IN (...). pTerm is the term to be
  1629. ** coded.
  1630. **
  1631. ** The current value for the constraint is left on the top of the stack.
  1632. **
  1633. ** For a constraint of the form X=expr, the expression is evaluated and its
  1634. ** result is left on the stack. For constraints of the form X IN (...)
  1635. ** this routine sets up a loop that will iterate over all values of X.
  1636. */
  1637. static void codeEqualityTerm(
  1638. Parse *pParse, /* The parsing context */
  1639. WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
  1640. WhereLevel *pLevel /* When level of the FROM clause we are working on */
  1641. ){
  1642. Expr *pX = pTerm->pExpr;
  1643. Vdbe *v = pParse->pVdbe;
  1644. if( pX->op==TK_EQ ){
  1645. sqlite3ExprCode(pParse, pX->pRight);
  1646. }else if( pX->op==TK_ISNULL ){
  1647. sqlite3VdbeAddOp(v, OP_Null, 0, 0);
  1648. #ifndef SQLITE_OMIT_SUBQUERY
  1649. }else{
  1650. int eType;
  1651. int iTab;
  1652. struct InLoop *pIn;
  1653. assert( pX->op==TK_IN );
  1654. eType = sqlite3FindInIndex(pParse, pX, 1);
  1655. iTab = pX->iTable;
  1656. sqlite3VdbeAddOp(v, OP_Rewind, iTab, 0);
  1657. VdbeComment((v, "# %.*s", pX->span.n, pX->span.z));
  1658. if( pLevel->nIn==0 ){
  1659. pLevel->nxt = sqlite3VdbeMakeLabel(v);
  1660. }
  1661. pLevel->nIn++;
  1662. pLevel->aInLoop = sqlite3DbReallocOrFree(pParse->db, pLevel->aInLoop,
  1663. sizeof(pLevel->aInLoop[0])*pLevel->nIn);
  1664. pIn = pLevel->aInLoop;
  1665. if( pIn ){
  1666. int op = ((eType==IN_INDEX_ROWID)?OP_Rowid:OP_Column);
  1667. pIn += pLevel->nIn - 1;
  1668. pIn->iCur = iTab;
  1669. pIn->topAddr = sqlite3VdbeAddOp(v, op, iTab, 0);
  1670. sqlite3VdbeAddOp(v, OP_IsNull, -1, 0);
  1671. }else{
  1672. pLevel->nIn = 0;
  1673. }
  1674. #endif
  1675. }
  1676. disableTerm(pLevel, pTerm);
  1677. }
  1678. /*
  1679. ** Generate code that will evaluate all == and IN constraints for an
  1680. ** index. The values for all constraints are left on the stack.
  1681. **
  1682. ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
  1683. ** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
  1684. ** The index has as many as three equality constraints, but in this
  1685. ** example, the third "c" value is an inequality. So only two
  1686. ** constraints are coded. This routine will generate code to evaluate
  1687. ** a==5 and b IN (1,2,3). The current values for a and b will be left
  1688. ** on the stack - a is the deepest and b the shallowest.
  1689. **
  1690. ** In the example above nEq==2. But this subroutine works for any value
  1691. ** of nEq including 0. If nEq==0, this routine is nearly a no-op.
  1692. ** The only thing it does is allocate the pLevel->iMem memory cell.
  1693. **
  1694. ** This routine always allocates at least one memory cell and puts
  1695. ** the address of that memory cell in pLevel->iMem. The code that
  1696. ** calls this routine will use pLevel->iMem to store the termination
  1697. ** key value of the loop. If one or more IN operators appear, then
  1698. ** this routine allocates an additional nEq memory cells for internal
  1699. ** use.
  1700. */
  1701. static void codeAllEqualityTerms(
  1702. Parse *pParse, /* Parsing context */
  1703. WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
  1704. WhereClause *pWC, /* The WHERE clause */
  1705. Bitmask notReady /* Which parts of FROM have not yet been coded */
  1706. ){
  1707. int nEq = pLevel->nEq; /* The number of == or IN constraints to code */
  1708. int termsInMem = 0; /* If true, store value in mem[] cells */
  1709. Vdbe *v = pParse->pVdbe; /* The virtual machine under construction */
  1710. Index *pIdx = pLevel->pIdx; /* The index being used for this loop */
  1711. int iCur = pLevel->iTabCur; /* The cursor of the table */
  1712. WhereTerm *pTerm; /* A single constraint term */
  1713. int j; /* Loop counter */
  1714. /* Figure out how many memory cells we will need then allocate them.
  1715. ** We always need at least one used to store the loop terminator
  1716. ** value. If there are IN operators we'll need one for each == or
  1717. ** IN constraint.
  1718. */
  1719. pLevel->iMem = pParse->nMem++;
  1720. if( pLevel->flags & WHERE_COLUMN_IN ){
  1721. pParse->nMem += pLevel->nEq;
  1722. termsInMem = 1;
  1723. }
  1724. /* Evaluate the equality constraints
  1725. */
  1726. assert( pIdx->nColumn>=nEq );
  1727. for(j=0; j<nEq; j++){
  1728. int k = pIdx->aiColumn[j];
  1729. pTerm = findTerm(pWC, iCur, k, notReady, pLevel->flags, pIdx);
  1730. if( pTerm==0 ) break;
  1731. assert( (pTerm->flags & TERM_CODED)==0 );
  1732. codeEqualityTerm(pParse, pTerm, pLevel);
  1733. if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
  1734. sqlite3VdbeAddOp(v, OP_IsNull, termsInMem ? -1 : -(j+1), pLevel->brk);
  1735. }
  1736. if( termsInMem ){
  1737. sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem+j+1, 1);
  1738. }
  1739. }
  1740. /* Make sure all the constraint values are on the top of the stack
  1741. */
  1742. if( termsInMem ){
  1743. for(j=0; j<nEq; j++){
  1744. sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem+j+1, 0);
  1745. }
  1746. }
  1747. }
  1748. #if defined(SQLITE_TEST)
  1749. /*
  1750. ** The following variable holds a text description of query plan generated
  1751. ** by the most recent call to sqlite3WhereBegin(). Each call to WhereBegin
  1752. ** overwrites the previous. This information is used for testing and
  1753. ** analysis only.
  1754. */
  1755. char sqlite3_query_plan[BMS*2*40]; /* Text of the join */
  1756. static int nQPlan = 0; /* Next free slow in _query_plan[] */
  1757. #endif /* SQLITE_TEST */
  1758. /*
  1759. ** Free a WhereInfo structure
  1760. */
  1761. static void whereInfoFree(WhereInfo *pWInfo){
  1762. if( pWInfo ){
  1763. int i;
  1764. for(i=0; i<pWInfo->nLevel; i++){
  1765. sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo;
  1766. if( pInfo ){
  1767. if( pInfo->needToFreeIdxStr ){
  1768. /* Coverage: Don't think this can be reached. By the time this
  1769. ** function is called, the index-strings have been passed
  1770. ** to the vdbe layer for deletion.
  1771. */
  1772. sqlite3_free(pInfo->idxStr);
  1773. }
  1774. sqlite3_free(pInfo);
  1775. }
  1776. }
  1777. sqlite3_free(pWInfo);
  1778. }
  1779. }
  1780. /*
  1781. ** Generate the beginning of the loop used for WHERE clause processing.
  1782. ** The return value is a pointer to an opaque structure that contains
  1783. ** information needed to terminate the loop. Later, the calling routine
  1784. ** should invoke sqlite3WhereEnd() with the return value of this function
  1785. ** in order to complete the WHERE clause processing.
  1786. **
  1787. ** If an error occurs, this routine returns NULL.
  1788. **
  1789. ** The basic idea is to do a nested loop, one loop for each table in
  1790. ** the FROM clause of a select. (INSERT and UPDATE statements are the
  1791. ** same as a SELECT with only a single table in the FROM clause.) For
  1792. ** example, if the SQL is this:
  1793. **
  1794. ** SELECT * FROM t1, t2, t3 WHERE ...;
  1795. **
  1796. ** Then the code generated is conceptually like the following:
  1797. **
  1798. ** foreach row1 in t1 do \ Code generated
  1799. ** foreach row2 in t2 do |-- by sqlite3WhereBegin()
  1800. ** foreach row3 in t3 do /
  1801. ** ...
  1802. ** end \ Code generated
  1803. ** end |-- by sqlite3WhereEnd()
  1804. ** end /
  1805. **
  1806. ** Note that the loops might not be nested in the order in which they
  1807. ** appear in the FROM clause if a different order is better able to make
  1808. ** use of indices. Note also that when the IN operator appears in
  1809. ** the WHERE clause, it might result in additional nested loops for
  1810. ** scanning through all values on the right-hand side of the IN.
  1811. **
  1812. ** There are Btree cursors associated with each table. t1 uses cursor
  1813. ** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
  1814. ** And so forth. This routine generates code to open those VDBE cursors
  1815. ** and sqlite3WhereEnd() generates the code to close them.
  1816. **
  1817. ** The code that sqlite3WhereBegin() generates leaves the cursors named
  1818. ** in pTabList pointing at their appropriate entries. The [...] code
  1819. ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
  1820. ** data from the various tables of the loop.
  1821. **
  1822. ** If the WHERE clause is empty, the foreach loops must each scan their
  1823. ** entire tables. Thus a three-way join is an O(N^3) operation. But if
  1824. ** the tables have indices and there are terms in the WHERE clause that
  1825. ** refer to those indices, a complete table scan can be avoided and the
  1826. ** code will run much faster. Most of the work of this routine is checking
  1827. ** to see if there are indices that can be used to speed up the loop.
  1828. **
  1829. ** Terms of the WHERE clause are also used to limit which rows actually
  1830. ** make it to the "..." in the middle of the loop. After each "foreach",
  1831. ** terms of the WHERE clause that use only terms in that loop and outer
  1832. ** loops are evaluated and if false a jump is made around all subsequent
  1833. ** inner loops (or around the "..." if the test occurs within the inner-
  1834. ** most loop)
  1835. **
  1836. ** OUTER JOINS
  1837. **
  1838. ** An outer join of tables t1 and t2 is conceptally coded as follows:
  1839. **
  1840. ** foreach row1 in t1 do
  1841. ** flag = 0
  1842. ** foreach row2 in t2 do
  1843. ** start:
  1844. ** ...
  1845. ** flag = 1
  1846. ** end
  1847. ** if flag==0 then
  1848. ** move the row2 cursor to a null row
  1849. ** goto start
  1850. ** fi
  1851. ** end
  1852. **
  1853. ** ORDER BY CLAUSE PROCESSING
  1854. **
  1855. ** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
  1856. ** if there is one. If there is no ORDER BY clause or if this routine
  1857. ** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
  1858. **
  1859. ** If an index can be used so that the natural output order of the table
  1860. ** scan is correct for the ORDER BY clause, then that index is used and
  1861. ** *ppOrderBy is set to NULL. This is an optimization that prevents an
  1862. ** unnecessary sort of the result set if an index appropriate for the
  1863. ** ORDER BY clause already exists.
  1864. **
  1865. ** If the where clause loops cannot be arranged to provide the correct
  1866. ** output order, then the *ppOrderBy is unchanged.
  1867. */
  1868. WhereInfo *sqlite3WhereBegin(
  1869. Parse *pParse, /* The parser context */
  1870. SrcList *pTabList, /* A list of all tables to be scanned */
  1871. Expr *pWhere, /* The WHERE clause */
  1872. ExprList **ppOrderBy /* An ORDER BY clause, or NULL */
  1873. ){
  1874. int i; /* Loop counter */
  1875. WhereInfo *pWInfo; /* Will become the return value of this function */
  1876. Vdbe *v = pParse->pVdbe; /* The virtual database engine */
  1877. int brk, cont = 0; /* Addresses used during code generation */
  1878. Bitmask notReady; /* Cursors that are not yet positioned */
  1879. WhereTerm *pTerm; /* A single term in the WHERE clause */
  1880. ExprMaskSet maskSet; /* The expression mask set */
  1881. WhereClause wc; /* The WHERE clause is divided into these terms */
  1882. struct SrcList_item *pTabItem; /* A single entry from pTabList */
  1883. WhereLevel *pLevel; /* A single level in the pWInfo list */
  1884. int iFrom; /* First unused FROM clause element */
  1885. int andFlags; /* AND-ed combination of all wc.a[].flags */
  1886. sqlite3 *db; /* Database connection */
  1887. /* The number of tables in the FROM clause is limited by the number of
  1888. ** bits in a Bitmask
  1889. */
  1890. if( pTabList->nSrc>BMS ){
  1891. sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
  1892. return 0;
  1893. }
  1894. /* Split the WHERE clause into separate subexpressions where each
  1895. ** subexpression is separated by an AND operator.
  1896. */
  1897. initMaskSet(&maskSet);
  1898. whereClauseInit(&wc, pParse, &maskSet);
  1899. whereSplit(&wc, pWhere, TK_AND);
  1900. /* Allocate and initialize the WhereInfo structure that will become the
  1901. ** return value.
  1902. */
  1903. db = pParse->db;
  1904. pWInfo = sqlite3DbMallocZero(db,
  1905. sizeof(WhereInfo) + pTabList->nSrc*sizeof(WhereLevel));
  1906. if( db->mallocFailed ){
  1907. goto whereBeginNoMem;
  1908. }
  1909. pWInfo->nLevel = pTabList->nSrc;
  1910. pWInfo->pParse = pParse;
  1911. pWInfo->pTabList = pTabList;
  1912. pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
  1913. /* Special case: a WHERE clause that is constant. Evaluate the
  1914. ** expression and either jump over all of the code or fall thru.
  1915. */
  1916. if( pWhere && (pTabList->nSrc==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
  1917. sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, 1);
  1918. pWhere = 0;
  1919. }
  1920. /* Analyze all of the subexpressions. Note that exprAnalyze() might
  1921. ** add new virtual terms onto the end of the WHERE clause. We do not
  1922. ** want to analyze these virtual terms, so start analyzing at the end
  1923. ** and work forward so that the added virtual terms are never processed.
  1924. */
  1925. for(i=0; i<pTabList->nSrc; i++){
  1926. createMask(&maskSet, pTabList->a[i].iCursor);
  1927. }
  1928. exprAnalyzeAll(pTabList, &wc);
  1929. if( db->mallocFailed ){
  1930. goto whereBeginNoMem;
  1931. }
  1932. /* Chose the best index to use for each table in the FROM clause.
  1933. **
  1934. ** This loop fills in the following fields:
  1935. **
  1936. ** pWInfo->a[].pIdx The index to use for this level of the loop.
  1937. ** pWInfo->a[].flags WHERE_xxx flags associated with pIdx
  1938. ** pWInfo->a[].nEq The number of == and IN constraints
  1939. ** pWInfo->a[].iFrom When term of the FROM clause is being coded
  1940. ** pWInfo->a[].iTabCur The VDBE cursor for the database table
  1941. ** pWInfo->a[].iIdxCur The VDBE cursor for the index
  1942. **
  1943. ** This loop also figures out the nesting order of tables in the FROM
  1944. ** clause.
  1945. */
  1946. notReady = ~(Bitmask)0;
  1947. pTabItem = pTabList->a;
  1948. pLevel = pWInfo->a;
  1949. andFlags = ~0;
  1950. WHERETRACE(("*** Optimizer Start ***\n"));
  1951. for(i=iFrom=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
  1952. Index *pIdx; /* Index for FROM table at pTabItem */
  1953. int flags; /* Flags asssociated with pIdx */
  1954. int nEq; /* Number of == or IN constraints */
  1955. double cost; /* The cost for pIdx */
  1956. int j; /* For looping over FROM tables */
  1957. Index *pBest = 0; /* The best index seen so far */
  1958. int bestFlags = 0; /* Flags associated with pBest */
  1959. int bestNEq = 0; /* nEq associated with pBest */
  1960. double lowestCost; /* Cost of the pBest */
  1961. int bestJ = 0; /* The value of j */
  1962. Bitmask m; /* Bitmask value for j or bestJ */
  1963. int once = 0; /* True when first table is seen */
  1964. sqlite3_index_info *pIndex; /* Current virtual index */
  1965. lowestCost = SQLITE_BIG_DBL;
  1966. for(j=iFrom, pTabItem=&pTabList->a[j]; j<pTabList->nSrc; j++, pTabItem++){
  1967. int doNotReorder; /* True if this table should not be reordered */
  1968. doNotReorder = (pTabItem->jointype & (JT_LEFT|JT_CROSS))!=0;
  1969. if( once && doNotReorder ) break;
  1970. m = getMask(&maskSet, pTabItem->iCursor);
  1971. if( (m & notReady)==0 ){
  1972. if( j==iFrom ) iFrom++;
  1973. continue;
  1974. }
  1975. assert( pTabItem->pTab );
  1976. #ifndef SQLITE_OMIT_VIRTUALTABLE
  1977. if( IsVirtual(pTabItem->pTab) ){
  1978. sqlite3_index_info **ppIdxInfo = &pWInfo->a[j].pIdxInfo;
  1979. cost = bestVirtualIndex(pParse, &wc, pTabItem, notReady,
  1980. ppOrderBy ? *ppOrderBy : 0, i==0,
  1981. ppIdxInfo);
  1982. flags = WHERE_VIRTUALTABLE;
  1983. pIndex = *ppIdxInfo;
  1984. if( pIndex && pIndex->orderByConsumed ){
  1985. flags = WHERE_VIRTUALTABLE | WHERE_ORDERBY;
  1986. }
  1987. pIdx = 0;
  1988. nEq = 0;
  1989. if( (SQLITE_BIG_DBL/2.0)<cost ){
  1990. /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
  1991. ** inital value of lowestCost in this loop. If it is, then
  1992. ** the (cost<lowestCost) test below will never be true and
  1993. ** pLevel->pBestIdx never set.
  1994. */
  1995. cost = (SQLITE_BIG_DBL/2.0);
  1996. }
  1997. }else
  1998. #endif
  1999. {
  2000. cost = bestIndex(pParse, &wc, pTabItem, notReady,
  2001. (i==0 && ppOrderBy) ? *ppOrderBy : 0,
  2002. &pIdx, &flags, &nEq);
  2003. pIndex = 0;
  2004. }
  2005. if( cost<lowestCost ){
  2006. once = 1;
  2007. lowestCost = cost;
  2008. pBest = pIdx;
  2009. bestFlags = flags;
  2010. bestNEq = nEq;
  2011. bestJ = j;
  2012. pLevel->pBestIdx = pIndex;
  2013. }
  2014. if( doNotReorder ) break;
  2015. }
  2016. WHERETRACE(("*** Optimizer choose table %d for loop %d\n", bestJ,
  2017. pLevel-pWInfo->a));
  2018. if( (bestFlags & WHERE_ORDERBY)!=0 ){
  2019. *ppOrderBy = 0;
  2020. }
  2021. andFlags &= bestFlags;
  2022. pLevel->flags = bestFlags;
  2023. pLevel->pIdx = pBest;
  2024. pLevel->nEq = bestNEq;
  2025. pLevel->aInLoop = 0;
  2026. pLevel->nIn = 0;
  2027. if( pBest ){
  2028. pLevel->iIdxCur = pParse->nTab++;
  2029. }else{
  2030. pLevel->iIdxCur = -1;
  2031. }
  2032. notReady &= ~getMask(&maskSet, pTabList->a[bestJ].iCursor);
  2033. pLevel->iFrom = bestJ;
  2034. }
  2035. WHERETRACE(("*** Optimizer Finished ***\n"));
  2036. /* If the total query only selects a single row, then the ORDER BY
  2037. ** clause is irrelevant.
  2038. */
  2039. if( (andFlags & WHERE_UNIQUE)!=0 && ppOrderBy ){
  2040. *ppOrderBy = 0;
  2041. }
  2042. /* Open all tables in the pTabList and any indices selected for
  2043. ** searching those tables.
  2044. */
  2045. sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
  2046. for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
  2047. Table *pTab; /* Table to open */
  2048. Index *pIx; /* Index used to access pTab (if any) */
  2049. int iDb; /* Index of database containing table/index */
  2050. int iIdxCur = pLevel->iIdxCur;
  2051. #ifndef SQLITE_OMIT_EXPLAIN
  2052. if( pParse->explain==2 ){
  2053. char *zMsg;
  2054. struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
  2055. zMsg = sqlite3MPrintf(db, "TABLE %s", pItem->zName);
  2056. if( pItem->zAlias ){
  2057. zMsg = sqlite3MPrintf(db, "%z AS %s", zMsg, pItem->zAlias);
  2058. }
  2059. if( (pIx = pLevel->pIdx)!=0 ){
  2060. zMsg = sqlite3MPrintf(db, "%z WITH INDEX %s", zMsg, pIx->zName);
  2061. }else if( pLevel->flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
  2062. zMsg = sqlite3MPrintf(db, "%z USING PRIMARY KEY", zMsg);
  2063. }
  2064. #ifndef SQLITE_OMIT_VIRTUALTABLE
  2065. else if( pLevel->pBestIdx ){
  2066. sqlite3_index_info *pBestIdx = pLevel->pBestIdx;
  2067. zMsg = sqlite3MPrintf(db, "%z VIRTUAL TABLE INDEX %d:%s", zMsg,
  2068. pBestIdx->idxNum, pBestIdx->idxStr);
  2069. }
  2070. #endif
  2071. if( pLevel->flags & WHERE_ORDERBY ){
  2072. zMsg = sqlite3MPrintf(db, "%z ORDER BY", zMsg);
  2073. }
  2074. sqlite3VdbeOp3(v, OP_Explain, i, pLevel->iFrom, zMsg, P3_DYNAMIC);
  2075. }
  2076. #endif /* SQLITE_OMIT_EXPLAIN */
  2077. pTabItem = &pTabList->a[pLevel->iFrom];
  2078. pTab = pTabItem->pTab;
  2079. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  2080. if( pTab->isEphem || pTab->pSelect ) continue;
  2081. #ifndef SQLITE_OMIT_VIRTUALTABLE
  2082. if( pLevel->pBestIdx ){
  2083. int iCur = pTabItem->iCursor;
  2084. sqlite3VdbeOp3(v, OP_VOpen, iCur, 0, (const char*)pTab->pVtab, P3_VTAB);
  2085. }else
  2086. #endif
  2087. if( (pLevel->flags & WHERE_IDX_ONLY)==0 ){
  2088. sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, OP_OpenRead);
  2089. if( pTab->nCol<(sizeof(Bitmask)*8) ){
  2090. Bitmask b = pTabItem->colUsed;
  2091. int n = 0;
  2092. for(; b; b=b>>1, n++){}
  2093. sqlite3VdbeChangeP2(v, sqlite3VdbeCurrentAddr(v)-1, n);
  2094. assert( n<=pTab->nCol );
  2095. }
  2096. }else{
  2097. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  2098. }
  2099. pLevel->iTabCur = pTabItem->iCursor;
  2100. if( (pIx = pLevel->pIdx)!=0 ){
  2101. KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
  2102. assert( pIx->pSchema==pTab->pSchema );
  2103. sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
  2104. VdbeComment((v, "# %s", pIx->zName));
  2105. sqlite3VdbeOp3(v, OP_OpenRead, iIdxCur, pIx->tnum,
  2106. (char*)pKey, P3_KEYINFO_HANDOFF);
  2107. sqlite3VdbeAddOp(v, OP_SetNumColumns, iIdxCur, pIx->nColumn+1);
  2108. }
  2109. sqlite3CodeVerifySchema(pParse, iDb);
  2110. }
  2111. pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
  2112. /* Generate the code to do the search. Each iteration of the for
  2113. ** loop below generates code for a single nested loop of the VM
  2114. ** program.
  2115. */
  2116. notReady = ~(Bitmask)0;
  2117. for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
  2118. int j;
  2119. int iCur = pTabItem->iCursor; /* The VDBE cursor for the table */
  2120. Index *pIdx; /* The index we will be using */
  2121. int nxt; /* Where to jump to continue with the next IN case */
  2122. int iIdxCur; /* The VDBE cursor for the index */
  2123. int omitTable; /* True if we use the index only */
  2124. int bRev; /* True if we need to scan in reverse order */
  2125. pTabItem = &pTabList->a[pLevel->iFrom];
  2126. iCur = pTabItem->iCursor;
  2127. pIdx = pLevel->pIdx;
  2128. iIdxCur = pLevel->iIdxCur;
  2129. bRev = (pLevel->flags & WHERE_REVERSE)!=0;
  2130. omitTable = (pLevel->flags & WHERE_IDX_ONLY)!=0;
  2131. /* Create labels for the "break" and "continue" instructions
  2132. ** for the current loop. Jump to brk to break out of a loop.
  2133. ** Jump to cont to go immediately to the next iteration of the
  2134. ** loop.
  2135. **
  2136. ** When there is an IN operator, we also have a "nxt" label that
  2137. ** means to continue with the next IN value combination. When
  2138. ** there are no IN operators in the constraints, the "nxt" label
  2139. ** is the same as "brk".
  2140. */
  2141. brk = pLevel->brk = pLevel->nxt = sqlite3VdbeMakeLabel(v);
  2142. cont = pLevel->cont = sqlite3VdbeMakeLabel(v);
  2143. /* If this is the right table of a LEFT OUTER JOIN, allocate and
  2144. ** initialize a memory cell that records if this table matches any
  2145. ** row of the left table of the join.
  2146. */
  2147. if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
  2148. if( !pParse->nMem ) pParse->nMem++;
  2149. pLevel->iLeftJoin = pParse->nMem++;
  2150. sqlite3VdbeAddOp(v, OP_MemInt, 0, pLevel->iLeftJoin);
  2151. VdbeComment((v, "# init LEFT JOIN no-match flag"));
  2152. }
  2153. #ifndef SQLITE_OMIT_VIRTUALTABLE
  2154. if( pLevel->pBestIdx ){
  2155. /* Case 0: The table is a virtual-table. Use the VFilter and VNext
  2156. ** to access the data.
  2157. */
  2158. int j;
  2159. sqlite3_index_info *pBestIdx = pLevel->pBestIdx;
  2160. int nConstraint = pBestIdx->nConstraint;
  2161. struct sqlite3_index_constraint_usage *aUsage =
  2162. pBestIdx->aConstraintUsage;
  2163. const struct sqlite3_index_constraint *aConstraint =
  2164. pBestIdx->aConstraint;
  2165. for(j=1; j<=nConstraint; j++){
  2166. int k;
  2167. for(k=0; k<nConstraint; k++){
  2168. if( aUsage[k].argvIndex==j ){
  2169. int iTerm = aConstraint[k].iTermOffset;
  2170. sqlite3ExprCode(pParse, wc.a[iTerm].pExpr->pRight);
  2171. break;
  2172. }
  2173. }
  2174. if( k==nConstraint ) break;
  2175. }
  2176. sqlite3VdbeAddOp(v, OP_Integer, j-1, 0);
  2177. sqlite3VdbeAddOp(v, OP_Integer, pBestIdx->idxNum, 0);
  2178. sqlite3VdbeOp3(v, OP_VFilter, iCur, brk, pBestIdx->idxStr,
  2179. pBestIdx->needToFreeIdxStr ? P3_MPRINTF : P3_STATIC);
  2180. pBestIdx->needToFreeIdxStr = 0;
  2181. for(j=0; j<pBestIdx->nConstraint; j++){
  2182. if( aUsage[j].omit ){
  2183. int iTerm = aConstraint[j].iTermOffset;
  2184. disableTerm(pLevel, &wc.a[iTerm]);
  2185. }
  2186. }
  2187. pLevel->op = OP_VNext;
  2188. pLevel->p1 = iCur;
  2189. pLevel->p2 = sqlite3VdbeCurrentAddr(v);
  2190. }else
  2191. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  2192. if( pLevel->flags & WHERE_ROWID_EQ ){
  2193. /* Case 1: We can directly reference a single row using an
  2194. ** equality comparison against the ROWID field. Or
  2195. ** we reference multiple rows using a "rowid IN (...)"
  2196. ** construct.
  2197. */
  2198. pTerm = findTerm(&wc, iCur, -1, notReady, WO_EQ|WO_IN, 0);
  2199. assert( pTerm!=0 );
  2200. assert( pTerm->pExpr!=0 );
  2201. assert( pTerm->leftCursor==iCur );
  2202. assert( omitTable==0 );
  2203. codeEqualityTerm(pParse, pTerm, pLevel);
  2204. nxt = pLevel->nxt;
  2205. sqlite3VdbeAddOp(v, OP_MustBeInt, 1, nxt);
  2206. sqlite3VdbeAddOp(v, OP_NotExists, iCur, nxt);
  2207. VdbeComment((v, "pk"));
  2208. pLevel->op = OP_Noop;
  2209. }else if( pLevel->flags & WHERE_ROWID_RANGE ){
  2210. /* Case 2: We have an inequality comparison against the ROWID field.
  2211. */
  2212. int testOp = OP_Noop;
  2213. int start;
  2214. WhereTerm *pStart, *pEnd;
  2215. assert( omitTable==0 );
  2216. pStart = findTerm(&wc, iCur, -1, notReady, WO_GT|WO_GE, 0);
  2217. pEnd = findTerm(&wc, iCur, -1, notReady, WO_LT|WO_LE, 0);
  2218. if( bRev ){
  2219. pTerm = pStart;
  2220. pStart = pEnd;
  2221. pEnd = pTerm;
  2222. }
  2223. if( pStart ){
  2224. Expr *pX;
  2225. pX = pStart->pExpr;
  2226. assert( pX!=0 );
  2227. assert( pStart->leftCursor==iCur );
  2228. sqlite3ExprCode(pParse, pX->pRight);
  2229. sqlite3VdbeAddOp(v, OP_ForceInt, pX->op==TK_LE || pX->op==TK_GT, brk);
  2230. sqlite3VdbeAddOp(v, bRev ? OP_MoveLt : OP_MoveGe, iCur, brk);
  2231. VdbeComment((v, "pk"));
  2232. disableTerm(pLevel, pStart);
  2233. }else{
  2234. sqlite3VdbeAddOp(v, bRev ? OP_Last : OP_Rewind, iCur, brk);
  2235. }
  2236. if( pEnd ){
  2237. Expr *pX;
  2238. pX = pEnd->pExpr;
  2239. assert( pX!=0 );
  2240. assert( pEnd->leftCursor==iCur );
  2241. sqlite3ExprCode(pParse, pX->pRight);
  2242. pLevel->iMem = pParse->nMem++;
  2243. sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
  2244. if( pX->op==TK_LT || pX->op==TK_GT ){
  2245. testOp = bRev ? OP_Le : OP_Ge;
  2246. }else{
  2247. testOp = bRev ? OP_Lt : OP_Gt;
  2248. }
  2249. disableTerm(pLevel, pEnd);
  2250. }
  2251. start = sqlite3VdbeCurrentAddr(v);
  2252. pLevel->op = bRev ? OP_Prev : OP_Next;
  2253. pLevel->p1 = iCur;
  2254. pLevel->p2 = start;
  2255. if( testOp!=OP_Noop ){
  2256. sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0);
  2257. sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
  2258. sqlite3VdbeAddOp(v, testOp, SQLITE_AFF_NUMERIC|0x100, brk);
  2259. }
  2260. }else if( pLevel->flags & WHERE_COLUMN_RANGE ){
  2261. /* Case 3: The WHERE clause term that refers to the right-most
  2262. ** column of the index is an inequality. For example, if
  2263. ** the index is on (x,y,z) and the WHERE clause is of the
  2264. ** form "x=5 AND y<10" then this case is used. Only the
  2265. ** right-most column can be an inequality - the rest must
  2266. ** use the "==" and "IN" operators.
  2267. **
  2268. ** This case is also used when there are no WHERE clause
  2269. ** constraints but an index is selected anyway, in order
  2270. ** to force the output order to conform to an ORDER BY.
  2271. */
  2272. int start;
  2273. int nEq = pLevel->nEq;
  2274. int topEq=0; /* True if top limit uses ==. False is strictly < */
  2275. int btmEq=0; /* True if btm limit uses ==. False if strictly > */
  2276. int topOp, btmOp; /* Operators for the top and bottom search bounds */
  2277. int testOp;
  2278. int topLimit = (pLevel->flags & WHERE_TOP_LIMIT)!=0;
  2279. int btmLimit = (pLevel->flags & WHERE_BTM_LIMIT)!=0;
  2280. /* Generate code to evaluate all constraint terms using == or IN
  2281. ** and level the values of those terms on the stack.
  2282. */
  2283. codeAllEqualityTerms(pParse, pLevel, &wc, notReady);
  2284. /* Duplicate the equality term values because they will all be
  2285. ** used twice: once to make the termination key and once to make the
  2286. ** start key.
  2287. */
  2288. for(j=0; j<nEq; j++){
  2289. sqlite3VdbeAddOp(v, OP_Dup, nEq-1, 0);
  2290. }
  2291. /* Figure out what comparison operators to use for top and bottom
  2292. ** search bounds. For an ascending index, the bottom bound is a > or >=
  2293. ** operator and the top bound is a < or <= operator. For a descending
  2294. ** index the operators are reversed.
  2295. */
  2296. if( pIdx->aSortOrder[nEq]==SQLITE_SO_ASC ){
  2297. topOp = WO_LT|WO_LE;
  2298. btmOp = WO_GT|WO_GE;
  2299. }else{
  2300. topOp = WO_GT|WO_GE;
  2301. btmOp = WO_LT|WO_LE;
  2302. SWAP(int, topLimit, btmLimit);
  2303. }
  2304. /* Generate the termination key. This is the key value that
  2305. ** will end the search. There is no termination key if there
  2306. ** are no equality terms and no "X<..." term.
  2307. **
  2308. ** 2002-Dec-04: On a reverse-order scan, the so-called "termination"
  2309. ** key computed here really ends up being the start key.
  2310. */
  2311. nxt = pLevel->nxt;
  2312. if( topLimit ){
  2313. Expr *pX;
  2314. int k = pIdx->aiColumn[j];
  2315. pTerm = findTerm(&wc, iCur, k, notReady, topOp, pIdx);
  2316. assert( pTerm!=0 );
  2317. pX = pTerm->pExpr;
  2318. assert( (pTerm->flags & TERM_CODED)==0 );
  2319. sqlite3ExprCode(pParse, pX->pRight);
  2320. sqlite3VdbeAddOp(v, OP_IsNull, -(nEq*2+1), nxt);
  2321. topEq = pTerm->eOperator & (WO_LE|WO_GE);
  2322. disableTerm(pLevel, pTerm);
  2323. testOp = OP_IdxGE;
  2324. }else{
  2325. testOp = nEq>0 ? OP_IdxGE : OP_Noop;
  2326. topEq = 1;
  2327. }
  2328. if( testOp!=OP_Noop ){
  2329. int nCol = nEq + topLimit;
  2330. pLevel->iMem = pParse->nMem++;
  2331. buildIndexProbe(v, nCol, pIdx);
  2332. if( bRev ){
  2333. int op = topEq ? OP_MoveLe : OP_MoveLt;
  2334. sqlite3VdbeAddOp(v, op, iIdxCur, nxt);
  2335. }else{
  2336. sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
  2337. }
  2338. }else if( bRev ){
  2339. sqlite3VdbeAddOp(v, OP_Last, iIdxCur, brk);
  2340. }
  2341. /* Generate the start key. This is the key that defines the lower
  2342. ** bound on the search. There is no start key if there are no
  2343. ** equality terms and if there is no "X>..." term. In
  2344. ** that case, generate a "Rewind" instruction in place of the
  2345. ** start key search.
  2346. **
  2347. ** 2002-Dec-04: In the case of a reverse-order search, the so-called
  2348. ** "start" key really ends up being used as the termination key.
  2349. */
  2350. if( btmLimit ){
  2351. Expr *pX;
  2352. int k = pIdx->aiColumn[j];
  2353. pTerm = findTerm(&wc, iCur, k, notReady, btmOp, pIdx);
  2354. assert( pTerm!=0 );
  2355. pX = pTerm->pExpr;
  2356. assert( (pTerm->flags & TERM_CODED)==0 );
  2357. sqlite3ExprCode(pParse, pX->pRight);
  2358. sqlite3VdbeAddOp(v, OP_IsNull, -(nEq+1), nxt);
  2359. btmEq = pTerm->eOperator & (WO_LE|WO_GE);
  2360. disableTerm(pLevel, pTerm);
  2361. }else{
  2362. btmEq = 1;
  2363. }
  2364. if( nEq>0 || btmLimit ){
  2365. int nCol = nEq + btmLimit;
  2366. buildIndexProbe(v, nCol, pIdx);
  2367. if( bRev ){
  2368. pLevel->iMem = pParse->nMem++;
  2369. sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
  2370. testOp = OP_IdxLT;
  2371. }else{
  2372. int op = btmEq ? OP_MoveGe : OP_MoveGt;
  2373. sqlite3VdbeAddOp(v, op, iIdxCur, nxt);
  2374. }
  2375. }else if( bRev ){
  2376. testOp = OP_Noop;
  2377. }else{
  2378. sqlite3VdbeAddOp(v, OP_Rewind, iIdxCur, brk);
  2379. }
  2380. /* Generate the the top of the loop. If there is a termination
  2381. ** key we have to test for that key and abort at the top of the
  2382. ** loop.
  2383. */
  2384. start = sqlite3VdbeCurrentAddr(v);
  2385. if( testOp!=OP_Noop ){
  2386. sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
  2387. sqlite3VdbeAddOp(v, testOp, iIdxCur, nxt);
  2388. if( (topEq && !bRev) || (!btmEq && bRev) ){
  2389. sqlite3VdbeChangeP3(v, -1, "+", P3_STATIC);
  2390. }
  2391. }
  2392. if( topLimit | btmLimit ){
  2393. sqlite3VdbeAddOp(v, OP_Column, iIdxCur, nEq);
  2394. sqlite3VdbeAddOp(v, OP_IsNull, 1, cont);
  2395. }
  2396. if( !omitTable ){
  2397. sqlite3VdbeAddOp(v, OP_IdxRowid, iIdxCur, 0);
  2398. sqlite3VdbeAddOp(v, OP_MoveGe, iCur, 0);
  2399. }
  2400. /* Record the instruction used to terminate the loop.
  2401. */
  2402. pLevel->op = bRev ? OP_Prev : OP_Next;
  2403. pLevel->p1 = iIdxCur;
  2404. pLevel->p2 = start;
  2405. }else if( pLevel->flags & WHERE_COLUMN_EQ ){
  2406. /* Case 4: There is an index and all terms of the WHERE clause that
  2407. ** refer to the index using the "==" or "IN" operators.
  2408. */
  2409. int start;
  2410. int nEq = pLevel->nEq;
  2411. /* Generate code to evaluate all constraint terms using == or IN
  2412. ** and leave the values of those terms on the stack.
  2413. */
  2414. codeAllEqualityTerms(pParse, pLevel, &wc, notReady);
  2415. nxt = pLevel->nxt;
  2416. /* Generate a single key that will be used to both start and terminate
  2417. ** the search
  2418. */
  2419. buildIndexProbe(v, nEq, pIdx);
  2420. sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 0);
  2421. /* Generate code (1) to move to the first matching element of the table.
  2422. ** Then generate code (2) that jumps to "nxt" after the cursor is past
  2423. ** the last matching element of the table. The code (1) is executed
  2424. ** once to initialize the search, the code (2) is executed before each
  2425. ** iteration of the scan to see if the scan has finished. */
  2426. if( bRev ){
  2427. /* Scan in reverse order */
  2428. sqlite3VdbeAddOp(v, OP_MoveLe, iIdxCur, nxt);
  2429. start = sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
  2430. sqlite3VdbeAddOp(v, OP_IdxLT, iIdxCur, nxt);
  2431. pLevel->op = OP_Prev;
  2432. }else{
  2433. /* Scan in the forward order */
  2434. sqlite3VdbeAddOp(v, OP_MoveGe, iIdxCur, nxt);
  2435. start = sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
  2436. sqlite3VdbeOp3(v, OP_IdxGE, iIdxCur, nxt, "+", P3_STATIC);
  2437. pLevel->op = OP_Next;
  2438. }
  2439. if( !omitTable ){
  2440. sqlite3VdbeAddOp(v, OP_IdxRowid, iIdxCur, 0);
  2441. sqlite3VdbeAddOp(v, OP_MoveGe, iCur, 0);
  2442. }
  2443. pLevel->p1 = iIdxCur;
  2444. pLevel->p2 = start;
  2445. }else{
  2446. /* Case 5: There is no usable index. We must do a complete
  2447. ** scan of the entire table.
  2448. */
  2449. assert( omitTable==0 );
  2450. assert( bRev==0 );
  2451. pLevel->op = OP_Next;
  2452. pLevel->p1 = iCur;
  2453. pLevel->p2 = 1 + sqlite3VdbeAddOp(v, OP_Rewind, iCur, brk);
  2454. }
  2455. notReady &= ~getMask(&maskSet, iCur);
  2456. sqlite3VdbeAddOp(v, OP_StackDepth, -1, 0);
  2457. /* Insert code to test every subexpression that can be completely
  2458. ** computed using the current set of tables.
  2459. */
  2460. for(pTerm=wc.a, j=wc.nTerm; j>0; j--, pTerm++){
  2461. Expr *pE;
  2462. if( pTerm->flags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  2463. if( (pTerm->prereqAll & notReady)!=0 ) continue;
  2464. pE = pTerm->pExpr;
  2465. assert( pE!=0 );
  2466. if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
  2467. continue;
  2468. }
  2469. sqlite3ExprIfFalse(pParse, pE, cont, 1);
  2470. pTerm->flags |= TERM_CODED;
  2471. }
  2472. /* For a LEFT OUTER JOIN, generate code that will record the fact that
  2473. ** at least one row of the right table has matched the left table.
  2474. */
  2475. if( pLevel->iLeftJoin ){
  2476. pLevel->top = sqlite3VdbeCurrentAddr(v);
  2477. sqlite3VdbeAddOp(v, OP_MemInt, 1, pLevel->iLeftJoin);
  2478. VdbeComment((v, "# record LEFT JOIN hit"));
  2479. for(pTerm=wc.a, j=0; j<wc.nTerm; j++, pTerm++){
  2480. if( pTerm->flags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  2481. if( (pTerm->prereqAll & notReady)!=0 ) continue;
  2482. assert( pTerm->pExpr );
  2483. sqlite3ExprIfFalse(pParse, pTerm->pExpr, cont, 1);
  2484. pTerm->flags |= TERM_CODED;
  2485. }
  2486. }
  2487. }
  2488. #ifdef SQLITE_TEST /* For testing and debugging use only */
  2489. /* Record in the query plan information about the current table
  2490. ** and the index used to access it (if any). If the table itself
  2491. ** is not used, its name is just '{}'. If no index is used
  2492. ** the index is listed as "{}". If the primary key is used the
  2493. ** index name is '*'.
  2494. */
  2495. for(i=0; i<pTabList->nSrc; i++){
  2496. char *z;
  2497. int n;
  2498. pLevel = &pWInfo->a[i];
  2499. pTabItem = &pTabList->a[pLevel->iFrom];
  2500. z = pTabItem->zAlias;
  2501. if( z==0 ) z = pTabItem->pTab->zName;
  2502. n = strlen(z);
  2503. if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
  2504. if( pLevel->flags & WHERE_IDX_ONLY ){
  2505. memcpy(&sqlite3_query_plan[nQPlan], "{}", 2);
  2506. nQPlan += 2;
  2507. }else{
  2508. memcpy(&sqlite3_query_plan[nQPlan], z, n);
  2509. nQPlan += n;
  2510. }
  2511. sqlite3_query_plan[nQPlan++] = ' ';
  2512. }
  2513. if( pLevel->flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
  2514. memcpy(&sqlite3_query_plan[nQPlan], "* ", 2);
  2515. nQPlan += 2;
  2516. }else if( pLevel->pIdx==0 ){
  2517. memcpy(&sqlite3_query_plan[nQPlan], "{} ", 3);
  2518. nQPlan += 3;
  2519. }else{
  2520. n = strlen(pLevel->pIdx->zName);
  2521. if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
  2522. memcpy(&sqlite3_query_plan[nQPlan], pLevel->pIdx->zName, n);
  2523. nQPlan += n;
  2524. sqlite3_query_plan[nQPlan++] = ' ';
  2525. }
  2526. }
  2527. }
  2528. while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
  2529. sqlite3_query_plan[--nQPlan] = 0;
  2530. }
  2531. sqlite3_query_plan[nQPlan] = 0;
  2532. nQPlan = 0;
  2533. #endif /* SQLITE_TEST // Testing and debugging use only */
  2534. /* Record the continuation address in the WhereInfo structure. Then
  2535. ** clean up and return.
  2536. */
  2537. pWInfo->iContinue = cont;
  2538. whereClauseClear(&wc);
  2539. return pWInfo;
  2540. /* Jump here if malloc fails */
  2541. whereBeginNoMem:
  2542. whereClauseClear(&wc);
  2543. whereInfoFree(pWInfo);
  2544. return 0;
  2545. }
  2546. /*
  2547. ** Generate the end of the WHERE loop. See comments on
  2548. ** sqlite3WhereBegin() for additional information.
  2549. */
  2550. void sqlite3WhereEnd(WhereInfo *pWInfo){
  2551. Vdbe *v = pWInfo->pParse->pVdbe;
  2552. int i;
  2553. WhereLevel *pLevel;
  2554. SrcList *pTabList = pWInfo->pTabList;
  2555. /* Generate loop termination code.
  2556. */
  2557. for(i=pTabList->nSrc-1; i>=0; i--){
  2558. pLevel = &pWInfo->a[i];
  2559. sqlite3VdbeResolveLabel(v, pLevel->cont);
  2560. if( pLevel->op!=OP_Noop ){
  2561. sqlite3VdbeAddOp(v, pLevel->op, pLevel->p1, pLevel->p2);
  2562. }
  2563. if( pLevel->nIn ){
  2564. struct InLoop *pIn;
  2565. int j;
  2566. sqlite3VdbeResolveLabel(v, pLevel->nxt);
  2567. for(j=pLevel->nIn, pIn=&pLevel->aInLoop[j-1]; j>0; j--, pIn--){
  2568. sqlite3VdbeJumpHere(v, pIn->topAddr+1);
  2569. sqlite3VdbeAddOp(v, OP_Next, pIn->iCur, pIn->topAddr);
  2570. sqlite3VdbeJumpHere(v, pIn->topAddr-1);
  2571. }
  2572. sqlite3_free(pLevel->aInLoop);
  2573. }
  2574. sqlite3VdbeResolveLabel(v, pLevel->brk);
  2575. if( pLevel->iLeftJoin ){
  2576. int addr;
  2577. addr = sqlite3VdbeAddOp(v, OP_IfMemPos, pLevel->iLeftJoin, 0);
  2578. sqlite3VdbeAddOp(v, OP_NullRow, pTabList->a[i].iCursor, 0);
  2579. if( pLevel->iIdxCur>=0 ){
  2580. sqlite3VdbeAddOp(v, OP_NullRow, pLevel->iIdxCur, 0);
  2581. }
  2582. sqlite3VdbeAddOp(v, OP_Goto, 0, pLevel->top);
  2583. sqlite3VdbeJumpHere(v, addr);
  2584. }
  2585. }
  2586. /* The "break" point is here, just past the end of the outer loop.
  2587. ** Set it.
  2588. */
  2589. sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
  2590. /* Close all of the cursors that were opened by sqlite3WhereBegin.
  2591. */
  2592. for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
  2593. struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
  2594. Table *pTab = pTabItem->pTab;
  2595. assert( pTab!=0 );
  2596. if( pTab->isEphem || pTab->pSelect ) continue;
  2597. if( (pLevel->flags & WHERE_IDX_ONLY)==0 ){
  2598. sqlite3VdbeAddOp(v, OP_Close, pTabItem->iCursor, 0);
  2599. }
  2600. if( pLevel->pIdx!=0 ){
  2601. sqlite3VdbeAddOp(v, OP_Close, pLevel->iIdxCur, 0);
  2602. }
  2603. /* If this scan uses an index, make code substitutions to read data
  2604. ** from the index in preference to the table. Sometimes, this means
  2605. ** the table need never be read from. This is a performance boost,
  2606. ** as the vdbe level waits until the table is read before actually
  2607. ** seeking the table cursor to the record corresponding to the current
  2608. ** position in the index.
  2609. **
  2610. ** Calls to the code generator in between sqlite3WhereBegin and
  2611. ** sqlite3WhereEnd will have created code that references the table
  2612. ** directly. This loop scans all that code looking for opcodes
  2613. ** that reference the table and converts them into opcodes that
  2614. ** reference the index.
  2615. */
  2616. if( pLevel->pIdx ){
  2617. int k, j, last;
  2618. VdbeOp *pOp;
  2619. Index *pIdx = pLevel->pIdx;
  2620. int useIndexOnly = pLevel->flags & WHERE_IDX_ONLY;
  2621. assert( pIdx!=0 );
  2622. pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
  2623. last = sqlite3VdbeCurrentAddr(v);
  2624. for(k=pWInfo->iTop; k<last; k++, pOp++){
  2625. if( pOp->p1!=pLevel->iTabCur ) continue;
  2626. if( pOp->opcode==OP_Column ){
  2627. for(j=0; j<pIdx->nColumn; j++){
  2628. if( pOp->p2==pIdx->aiColumn[j] ){
  2629. pOp->p2 = j;
  2630. pOp->p1 = pLevel->iIdxCur;
  2631. break;
  2632. }
  2633. }
  2634. assert(!useIndexOnly || j<pIdx->nColumn);
  2635. }else if( pOp->opcode==OP_Rowid ){
  2636. pOp->p1 = pLevel->iIdxCur;
  2637. pOp->opcode = OP_IdxRowid;
  2638. }else if( pOp->opcode==OP_NullRow && useIndexOnly ){
  2639. pOp->opcode = OP_Noop;
  2640. }
  2641. }
  2642. }
  2643. }
  2644. /* Final cleanup
  2645. */
  2646. whereInfoFree(pWInfo);
  2647. return;
  2648. }