PageRenderTime 273ms CodeModel.GetById 26ms RepoModel.GetById 1ms app.codeStats 2ms

/Community.CsharpSqlite/src/where_c.cs

https://bitbucket.org/eumario/csharp-sqlite
C# | 5843 lines | 3727 code | 271 blank | 1845 comment | 1241 complexity | a17d6f46b8cab672bc870d075d46415f MD5 | raw file
  1. using System;
  2. using System.Diagnostics;
  3. using System.Text;
  4. using Bitmask = System.UInt64;
  5. using i16 = System.Int16;
  6. using u8 = System.Byte;
  7. using u16 = System.UInt16;
  8. using u32 = System.UInt32;
  9. using sqlite3_int64 = System.Int64;
  10. namespace Community.CsharpSqlite
  11. {
  12. using sqlite3_value = Sqlite3.Mem;
  13. public partial class Sqlite3
  14. {
  15. /*
  16. ** 2001 September 15
  17. **
  18. ** The author disclaims copyright to this source code. In place of
  19. ** a legal notice, here is a blessing:
  20. **
  21. ** May you do good and not evil.
  22. ** May you find forgiveness for yourself and forgive others.
  23. ** May you share freely, never taking more than you give.
  24. **
  25. *************************************************************************
  26. ** This module contains C code that generates VDBE code used to process
  27. ** the WHERE clause of SQL statements. This module is responsible for
  28. ** generating the code that loops through a table looking for applicable
  29. ** rows. Indices are selected and used to speed the search when doing
  30. ** so is applicable. Because this module is responsible for selecting
  31. ** indices, you might also think of this module as the "query optimizer".
  32. *************************************************************************
  33. ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
  34. ** C#-SQLite is an independent reimplementation of the SQLite software library
  35. **
  36. ** SQLITE_SOURCE_ID: 2011-05-19 13:26:54 ed1da510a239ea767a01dc332b667119fa3c908ecd7
  37. **
  38. *************************************************************************
  39. */
  40. //#include "sqliteInt.h"
  41. /*
  42. ** Trace output macros
  43. */
  44. #if (SQLITE_TEST) || (SQLITE_DEBUG)
  45. static bool sqlite3WhereTrace = false;
  46. #endif
  47. #if (SQLITE_TEST) && (SQLITE_DEBUG) && TRACE
  48. //# define WHERETRACE(X) if(sqlite3WhereTrace) sqlite3DebugPrintf X
  49. static void WHERETRACE( string X, params object[] ap ) { if ( sqlite3WhereTrace ) sqlite3DebugPrintf( X, ap ); }
  50. #else
  51. //# define WHERETRACE(X)
  52. static void WHERETRACE( string X, params object[] ap )
  53. {
  54. }
  55. #endif
  56. /* Forward reference
  57. */
  58. //typedef struct WhereClause WhereClause;
  59. //typedef struct WhereMaskSet WhereMaskSet;
  60. //typedef struct WhereOrInfo WhereOrInfo;
  61. //typedef struct WhereAndInfo WhereAndInfo;
  62. //typedef struct WhereCost WhereCost;
  63. /*
  64. ** The query generator uses an array of instances of this structure to
  65. ** help it analyze the subexpressions of the WHERE clause. Each WHERE
  66. ** clause subexpression is separated from the others by AND operators,
  67. ** usually, or sometimes subexpressions separated by OR.
  68. **
  69. ** All WhereTerms are collected into a single WhereClause structure.
  70. ** The following identity holds:
  71. **
  72. ** WhereTerm.pWC.a[WhereTerm.idx] == WhereTerm
  73. **
  74. ** When a term is of the form:
  75. **
  76. ** X <op> <expr>
  77. **
  78. ** where X is a column name and <op> is one of certain operators,
  79. ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
  80. ** cursor number and column number for X. WhereTerm.eOperator records
  81. ** the <op> using a bitmask encoding defined by WO_xxx below. The
  82. ** use of a bitmask encoding for the operator allows us to search
  83. ** quickly for terms that match any of several different operators.
  84. **
  85. ** A WhereTerm might also be two or more subterms connected by OR:
  86. **
  87. ** (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
  88. **
  89. ** In this second case, wtFlag as the TERM_ORINFO set and eOperator==WO_OR
  90. ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
  91. ** is collected about the
  92. **
  93. ** If a term in the WHERE clause does not match either of the two previous
  94. ** categories, then eOperator==0. The WhereTerm.pExpr field is still set
  95. ** to the original subexpression content and wtFlags is set up appropriately
  96. ** but no other fields in the WhereTerm object are meaningful.
  97. **
  98. ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
  99. ** but they do so indirectly. A single WhereMaskSet structure translates
  100. ** cursor number into bits and the translated bit is stored in the prereq
  101. ** fields. The translation is used in order to maximize the number of
  102. ** bits that will fit in a Bitmask. The VDBE cursor numbers might be
  103. ** spread out over the non-negative integers. For example, the cursor
  104. ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45. The WhereMaskSet
  105. ** translates these sparse cursor numbers into consecutive integers
  106. ** beginning with 0 in order to make the best possible use of the available
  107. ** bits in the Bitmask. So, in the example above, the cursor numbers
  108. ** would be mapped into integers 0 through 7.
  109. **
  110. ** The number of terms in a join is limited by the number of bits
  111. ** in prereqRight and prereqAll. The default is 64 bits, hence SQLite
  112. ** is only able to process joins with 64 or fewer tables.
  113. */
  114. //typedef struct WhereTerm WhereTerm;
  115. public class WhereTerm
  116. {
  117. public Expr pExpr; /* Pointer to the subexpression that is this term */
  118. public int iParent; /* Disable pWC.a[iParent] when this term disabled */
  119. public int leftCursor; /* Cursor number of X in "X <op> <expr>" */
  120. public class _u
  121. {
  122. public int leftColumn; /* Column number of X in "X <op> <expr>" */
  123. public WhereOrInfo pOrInfo; /* Extra information if eOperator==WO_OR */
  124. public WhereAndInfo pAndInfo; /* Extra information if eOperator==WO_AND */
  125. }
  126. public _u u = new _u();
  127. public u16 eOperator; /* A WO_xx value describing <op> */
  128. public u8 wtFlags; /* TERM_xxx bit flags. See below */
  129. public u8 nChild; /* Number of children that must disable us */
  130. public WhereClause pWC; /* The clause this term is part of */
  131. public Bitmask prereqRight; /* Bitmask of tables used by pExpr.pRight */
  132. public Bitmask prereqAll; /* Bitmask of tables referenced by pExpr */
  133. };
  134. /*
  135. ** Allowed values of WhereTerm.wtFlags
  136. */
  137. //#define TERM_DYNAMIC 0x01 /* Need to call sqlite3ExprDelete(db, ref pExpr) */
  138. //#define TERM_VIRTUAL 0x02 /* Added by the optimizer. Do not code */
  139. //#define TERM_CODED 0x04 /* This term is already coded */
  140. //#define TERM_COPIED 0x08 /* Has a child */
  141. //#define TERM_ORINFO 0x10 /* Need to free the WhereTerm.u.pOrInfo object */
  142. //#define TERM_ANDINFO 0x20 /* Need to free the WhereTerm.u.pAndInfo obj */
  143. //#define TERM_OR_OK 0x40 /* Used during OR-clause processing */
  144. #if SQLITE_ENABLE_STAT2
  145. //# define TERM_VNULL 0x80 /* Manufactured x>NULL or x<=NULL term */
  146. #else
  147. //# define TERM_VNULL 0x00 /* Disabled if not using stat2 */
  148. #endif
  149. const int TERM_DYNAMIC = 0x01; /* Need to call sqlite3ExprDelete(db, ref pExpr) */
  150. const int TERM_VIRTUAL = 0x02; /* Added by the optimizer. Do not code */
  151. const int TERM_CODED = 0x04; /* This term is already coded */
  152. const int TERM_COPIED = 0x08; /* Has a child */
  153. const int TERM_ORINFO = 0x10; /* Need to free the WhereTerm.u.pOrInfo object */
  154. const int TERM_ANDINFO = 0x20; /* Need to free the WhereTerm.u.pAndInfo obj */
  155. const int TERM_OR_OK = 0x40; /* Used during OR-clause processing */
  156. #if SQLITE_ENABLE_STAT2
  157. const int TERM_VNULL = 0x80; /* Manufactured x>NULL or x<=NULL term */
  158. #else
  159. const int TERM_VNULL = 0x00; /* Disabled if not using stat2 */
  160. #endif
  161. /*
  162. ** An instance of the following structure holds all information about a
  163. ** WHERE clause. Mostly this is a container for one or more WhereTerms.
  164. */
  165. public class WhereClause
  166. {
  167. public Parse pParse; /* The parser context */
  168. public WhereMaskSet pMaskSet; /* Mapping of table cursor numbers to bitmasks */
  169. public Bitmask vmask; /* Bitmask identifying virtual table cursors */
  170. public u8 op; /* Split operator. TK_AND or TK_OR */
  171. public int nTerm; /* Number of terms */
  172. public int nSlot; /* Number of entries in a[] */
  173. public WhereTerm[] a; /* Each a[] describes a term of the WHERE cluase */
  174. #if (SQLITE_SMALL_STACK)
  175. public WhereTerm[] aStatic = new WhereTerm[1]; /* Initial static space for a[] */
  176. #else
  177. public WhereTerm[] aStatic = new WhereTerm[8]; /* Initial static space for a[] */
  178. #endif
  179. public void CopyTo( WhereClause wc )
  180. {
  181. wc.pParse = this.pParse;
  182. wc.pMaskSet = new WhereMaskSet();
  183. this.pMaskSet.CopyTo( wc.pMaskSet );
  184. wc.op = this.op;
  185. wc.nTerm = this.nTerm;
  186. wc.nSlot = this.nSlot;
  187. wc.a = (WhereTerm[])this.a.Clone();
  188. wc.aStatic = (WhereTerm[])this.aStatic.Clone();
  189. }
  190. };
  191. /*
  192. ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
  193. ** a dynamically allocated instance of the following structure.
  194. */
  195. public class WhereOrInfo
  196. {
  197. public WhereClause wc = new WhereClause();/* Decomposition into subterms */
  198. public Bitmask indexable; /* Bitmask of all indexable tables in the clause */
  199. };
  200. /*
  201. ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
  202. ** a dynamically allocated instance of the following structure.
  203. */
  204. public class WhereAndInfo
  205. {
  206. public WhereClause wc = new WhereClause(); /* The subexpression broken out */
  207. };
  208. /*
  209. ** An instance of the following structure keeps track of a mapping
  210. ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
  211. **
  212. ** The VDBE cursor numbers are small integers contained in
  213. ** SrcList_item.iCursor and Expr.iTable fields. For any given WHERE
  214. ** clause, the cursor numbers might not begin with 0 and they might
  215. ** contain gaps in the numbering sequence. But we want to make maximum
  216. ** use of the bits in our bitmasks. This structure provides a mapping
  217. ** from the sparse cursor numbers into consecutive integers beginning
  218. ** with 0.
  219. **
  220. ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
  221. ** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<<A.
  222. **
  223. ** For example, if the WHERE clause expression used these VDBE
  224. ** cursors: 4, 5, 8, 29, 57, 73. Then the WhereMaskSet structure
  225. ** would map those cursor numbers into bits 0 through 5.
  226. **
  227. ** Note that the mapping is not necessarily ordered. In the example
  228. ** above, the mapping might go like this: 4.3, 5.1, 8.2, 29.0,
  229. ** 57.5, 73.4. Or one of 719 other combinations might be used. It
  230. ** does not really matter. What is important is that sparse cursor
  231. ** numbers all get mapped into bit numbers that begin with 0 and contain
  232. ** no gaps.
  233. */
  234. public class WhereMaskSet
  235. {
  236. public int n; /* Number of Debug.Assigned cursor values */
  237. public int[] ix = new int[BMS]; /* Cursor Debug.Assigned to each bit */
  238. public void CopyTo( WhereMaskSet wms )
  239. {
  240. wms.n = this.n;
  241. wms.ix = (int[])this.ix.Clone();
  242. }
  243. }
  244. /*
  245. ** A WhereCost object records a lookup strategy and the estimated
  246. ** cost of pursuing that strategy.
  247. */
  248. public class WhereCost
  249. {
  250. public WherePlan plan = new WherePlan();/* The lookup strategy */
  251. public double rCost; /* Overall cost of pursuing this search strategy */
  252. public Bitmask used; /* Bitmask of cursors used by this plan */
  253. public void Clear()
  254. {
  255. plan.Clear();
  256. rCost = 0;
  257. used = 0;
  258. }
  259. };
  260. /*
  261. ** Bitmasks for the operators that indices are able to exploit. An
  262. ** OR-ed combination of these values can be used when searching for
  263. ** terms in the where clause.
  264. */
  265. //#define WO_IN 0x001
  266. //#define WO_EQ 0x002
  267. //#define WO_LT (WO_EQ<<(TK_LT-TK_EQ))
  268. //#define WO_LE (WO_EQ<<(TK_LE-TK_EQ))
  269. //#define WO_GT (WO_EQ<<(TK_GT-TK_EQ))
  270. //#define WO_GE (WO_EQ<<(TK_GE-TK_EQ))
  271. //#define WO_MATCH 0x040
  272. //#define WO_ISNULL 0x080
  273. //#define WO_OR 0x100 /* Two or more OR-connected terms */
  274. //#define WO_AND 0x200 /* Two or more AND-connected terms */
  275. //#define WO_NOOP 0x800 /* This term does not restrict search space */
  276. //#define WO_ALL 0xfff /* Mask of all possible WO_* values */
  277. //#define WO_SINGLE 0x0ff /* Mask of all non-compound WO_* values */
  278. const int WO_IN = 0x001;
  279. const int WO_EQ = 0x002;
  280. const int WO_LT = ( WO_EQ << ( TK_LT - TK_EQ ) );
  281. const int WO_LE = ( WO_EQ << ( TK_LE - TK_EQ ) );
  282. const int WO_GT = ( WO_EQ << ( TK_GT - TK_EQ ) );
  283. const int WO_GE = ( WO_EQ << ( TK_GE - TK_EQ ) );
  284. const int WO_MATCH = 0x040;
  285. const int WO_ISNULL = 0x080;
  286. const int WO_OR = 0x100; /* Two or more OR-connected terms */
  287. const int WO_AND = 0x200; /* Two or more AND-connected terms */
  288. const int WO_NOOP = 0x800; /* This term does not restrict search space */
  289. const int WO_ALL = 0xfff; /* Mask of all possible WO_* values */
  290. const int WO_SINGLE = 0x0ff; /* Mask of all non-compound WO_* values */
  291. /*
  292. ** Value for wsFlags returned by bestIndex() and stored in
  293. ** WhereLevel.wsFlags. These flags determine which search
  294. ** strategies are appropriate.
  295. **
  296. ** The least significant 12 bits is reserved as a mask for WO_ values above.
  297. ** The WhereLevel.wsFlags field is usually set to WO_IN|WO_EQ|WO_ISNULL.
  298. ** But if the table is the right table of a left join, WhereLevel.wsFlags
  299. ** is set to WO_IN|WO_EQ. The WhereLevel.wsFlags field can then be used as
  300. ** the "op" parameter to findTerm when we are resolving equality constraints.
  301. ** ISNULL constraints will then not be used on the right table of a left
  302. ** join. Tickets #2177 and #2189.
  303. */
  304. //#define WHERE_ROWID_EQ 0x00001000 /* rowid=EXPR or rowid IN (...) */
  305. //#define WHERE_ROWID_RANGE 0x00002000 /* rowid<EXPR and/or rowid>EXPR */
  306. //#define WHERE_COLUMN_EQ 0x00010000 /* x=EXPR or x IN (...) or x IS NULL */
  307. //#define WHERE_COLUMN_RANGE 0x00020000 /* x<EXPR and/or x>EXPR */
  308. //#define WHERE_COLUMN_IN 0x00040000 /* x IN (...) */
  309. //#define WHERE_COLUMN_NULL 0x00080000 /* x IS NULL */
  310. //#define WHERE_INDEXED 0x000f0000 /* Anything that uses an index */
  311. //#define WHERE_IN_ABLE 0x000f1000 /* Able to support an IN operator */
  312. //#define WHERE_NOT_FULLSCAN 0x100f3000 /* Does not do a full table scan */
  313. //#define WHERE_TOP_LIMIT 0x00100000 /* x<EXPR or x<=EXPR constraint */
  314. //#define WHERE_BTM_LIMIT 0x00200000 /* x>EXPR or x>=EXPR constraint */
  315. //#define WHERE_BOTH_LIMIT 0x00300000 /* Both x>EXPR and x<EXPR */
  316. //#define WHERE_IDX_ONLY 0x00800000 /* Use index only - omit table */
  317. //#define WHERE_ORDERBY 0x01000000 /* Output will appear in correct order */
  318. //#define WHERE_REVERSE 0x02000000 /* Scan in reverse order */
  319. //#define WHERE_UNIQUE 0x04000000 /* Selects no more than one row */
  320. //#define WHERE_VIRTUALTABLE 0x08000000 /* Use virtual-table processing */
  321. //#define WHERE_MULTI_OR 0x10000000 /* OR using multiple indices */
  322. //#define WHERE_TEMP_INDEX 0x20000000 /* Uses an ephemeral index */
  323. const int WHERE_ROWID_EQ = 0x00001000;
  324. const int WHERE_ROWID_RANGE = 0x00002000;
  325. const int WHERE_COLUMN_EQ = 0x00010000;
  326. const int WHERE_COLUMN_RANGE = 0x00020000;
  327. const int WHERE_COLUMN_IN = 0x00040000;
  328. const int WHERE_COLUMN_NULL = 0x00080000;
  329. const int WHERE_INDEXED = 0x000f0000;
  330. const int WHERE_IN_ABLE = 0x000f1000;
  331. const int WHERE_NOT_FULLSCAN = 0x100f3000;
  332. const int WHERE_TOP_LIMIT = 0x00100000;
  333. const int WHERE_BTM_LIMIT = 0x00200000;
  334. const int WHERE_BOTH_LIMIT = 0x00300000;
  335. const int WHERE_IDX_ONLY = 0x00800000;
  336. const int WHERE_ORDERBY = 0x01000000;
  337. const int WHERE_REVERSE = 0x02000000;
  338. const int WHERE_UNIQUE = 0x04000000;
  339. const int WHERE_VIRTUALTABLE = 0x08000000;
  340. const int WHERE_MULTI_OR = 0x10000000;
  341. const int WHERE_TEMP_INDEX = 0x20000000;
  342. /*
  343. ** Initialize a preallocated WhereClause structure.
  344. */
  345. static void whereClauseInit(
  346. WhereClause pWC, /* The WhereClause to be initialized */
  347. Parse pParse, /* The parsing context */
  348. WhereMaskSet pMaskSet /* Mapping from table cursor numbers to bitmasks */
  349. )
  350. {
  351. pWC.pParse = pParse;
  352. pWC.pMaskSet = pMaskSet;
  353. pWC.nTerm = 0;
  354. pWC.nSlot = ArraySize( pWC.aStatic ) - 1;
  355. pWC.a = pWC.aStatic;
  356. pWC.vmask = 0;
  357. }
  358. /* Forward reference */
  359. //static void whereClauseClear(WhereClause);
  360. /*
  361. ** Deallocate all memory Debug.Associated with a WhereOrInfo object.
  362. */
  363. static void whereOrInfoDelete( sqlite3 db, WhereOrInfo p )
  364. {
  365. whereClauseClear( p.wc );
  366. sqlite3DbFree( db, ref p );
  367. }
  368. /*
  369. ** Deallocate all memory Debug.Associated with a WhereAndInfo object.
  370. */
  371. static void whereAndInfoDelete( sqlite3 db, WhereAndInfo p )
  372. {
  373. whereClauseClear( p.wc );
  374. sqlite3DbFree( db, ref p );
  375. }
  376. /*
  377. ** Deallocate a WhereClause structure. The WhereClause structure
  378. ** itself is not freed. This routine is the inverse of whereClauseInit().
  379. */
  380. static void whereClauseClear( WhereClause pWC )
  381. {
  382. int i;
  383. WhereTerm a;
  384. sqlite3 db = pWC.pParse.db;
  385. for ( i = pWC.nTerm - 1; i >= 0; i-- )//, a++)
  386. {
  387. a = pWC.a[i];
  388. if ( ( a.wtFlags & TERM_DYNAMIC ) != 0 )
  389. {
  390. sqlite3ExprDelete( db, ref a.pExpr );
  391. }
  392. if ( ( a.wtFlags & TERM_ORINFO ) != 0 )
  393. {
  394. whereOrInfoDelete( db, a.u.pOrInfo );
  395. }
  396. else if ( ( a.wtFlags & TERM_ANDINFO ) != 0 )
  397. {
  398. whereAndInfoDelete( db, a.u.pAndInfo );
  399. }
  400. }
  401. if ( pWC.a != pWC.aStatic )
  402. {
  403. sqlite3DbFree( db, ref pWC.a );
  404. }
  405. }
  406. /*
  407. ** Add a single new WhereTerm entry to the WhereClause object pWC.
  408. ** The new WhereTerm object is constructed from Expr p and with wtFlags.
  409. ** The index in pWC.a[] of the new WhereTerm is returned on success.
  410. ** 0 is returned if the new WhereTerm could not be added due to a memory
  411. ** allocation error. The memory allocation failure will be recorded in
  412. ** the db.mallocFailed flag so that higher-level functions can detect it.
  413. **
  414. ** This routine will increase the size of the pWC.a[] array as necessary.
  415. **
  416. ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
  417. ** for freeing the expression p is Debug.Assumed by the WhereClause object pWC.
  418. ** This is true even if this routine fails to allocate a new WhereTerm.
  419. **
  420. ** WARNING: This routine might reallocate the space used to store
  421. ** WhereTerms. All pointers to WhereTerms should be invalidated after
  422. ** calling this routine. Such pointers may be reinitialized by referencing
  423. ** the pWC.a[] array.
  424. */
  425. static int whereClauseInsert( WhereClause pWC, Expr p, u8 wtFlags )
  426. {
  427. WhereTerm pTerm;
  428. int idx;
  429. testcase( wtFlags & TERM_VIRTUAL ); /* EV: R-00211-15100 */
  430. if ( pWC.nTerm >= pWC.nSlot )
  431. {
  432. //WhereTerm pOld = pWC.a;
  433. //sqlite3 db = pWC.pParse.db;
  434. Array.Resize( ref pWC.a, pWC.nSlot * 2 );
  435. //pWC.a = sqlite3DbMallocRaw(db, sizeof(pWC.a[0])*pWC.nSlot*2 );
  436. //if( pWC.a==null ){
  437. // if( wtFlags & TERM_DYNAMIC ){
  438. // sqlite3ExprDelete(db, ref p);
  439. // }
  440. // pWC.a = pOld;
  441. // return 0;
  442. //}
  443. //memcpy(pWC.a, pOld, sizeof(pWC.a[0])*pWC.nTerm);
  444. //if( pOld!=pWC.aStatic ){
  445. // sqlite3DbFree(db, ref pOld);
  446. //}
  447. //pWC.nSlot = sqlite3DbMallocSize(db, pWC.a)/sizeof(pWC.a[0]);
  448. pWC.nSlot = pWC.a.Length - 1;
  449. }
  450. pWC.a[idx = pWC.nTerm++] = new WhereTerm();
  451. pTerm = pWC.a[idx];
  452. pTerm.pExpr = p;
  453. pTerm.wtFlags = wtFlags;
  454. pTerm.pWC = pWC;
  455. pTerm.iParent = -1;
  456. return idx;
  457. }
  458. /*
  459. ** This routine identifies subexpressions in the WHERE clause where
  460. ** each subexpression is separated by the AND operator or some other
  461. ** operator specified in the op parameter. The WhereClause structure
  462. ** is filled with pointers to subexpressions. For example:
  463. **
  464. ** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
  465. ** \________/ \_______________/ \________________/
  466. ** slot[0] slot[1] slot[2]
  467. **
  468. ** The original WHERE clause in pExpr is unaltered. All this routine
  469. ** does is make slot[] entries point to substructure within pExpr.
  470. **
  471. ** In the previous sentence and in the diagram, "slot[]" refers to
  472. ** the WhereClause.a[] array. The slot[] array grows as needed to contain
  473. ** all terms of the WHERE clause.
  474. */
  475. static void whereSplit( WhereClause pWC, Expr pExpr, int op )
  476. {
  477. pWC.op = (u8)op;
  478. if ( pExpr == null )
  479. return;
  480. if ( pExpr.op != op )
  481. {
  482. whereClauseInsert( pWC, pExpr, 0 );
  483. }
  484. else
  485. {
  486. whereSplit( pWC, pExpr.pLeft, op );
  487. whereSplit( pWC, pExpr.pRight, op );
  488. }
  489. }
  490. /*
  491. ** Initialize an expression mask set (a WhereMaskSet object)
  492. */
  493. //#define initMaskSet(P) memset(P, 0, sizeof(*P))
  494. /*
  495. ** Return the bitmask for the given cursor number. Return 0 if
  496. ** iCursor is not in the set.
  497. */
  498. static Bitmask getMask( WhereMaskSet pMaskSet, int iCursor )
  499. {
  500. int i;
  501. Debug.Assert( pMaskSet.n <= (int)sizeof( Bitmask ) * 8 );
  502. for ( i = 0; i < pMaskSet.n; i++ )
  503. {
  504. if ( pMaskSet.ix[i] == iCursor )
  505. {
  506. return ( (Bitmask)1 ) << i;
  507. }
  508. }
  509. return 0;
  510. }
  511. /*
  512. ** Create a new mask for cursor iCursor.
  513. **
  514. ** There is one cursor per table in the FROM clause. The number of
  515. ** tables in the FROM clause is limited by a test early in the
  516. ** sqlite3WhereBegin() routine. So we know that the pMaskSet.ix[]
  517. ** array will never overflow.
  518. */
  519. static void createMask( WhereMaskSet pMaskSet, int iCursor )
  520. {
  521. Debug.Assert( pMaskSet.n < ArraySize( pMaskSet.ix ) );
  522. pMaskSet.ix[pMaskSet.n++] = iCursor;
  523. }
  524. /*
  525. ** This routine walks (recursively) an expression tree and generates
  526. ** a bitmask indicating which tables are used in that expression
  527. ** tree.
  528. **
  529. ** In order for this routine to work, the calling function must have
  530. ** previously invoked sqlite3ResolveExprNames() on the expression. See
  531. ** the header comment on that routine for additional information.
  532. ** The sqlite3ResolveExprNames() routines looks for column names and
  533. ** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
  534. ** the VDBE cursor number of the table. This routine just has to
  535. ** translate the cursor numbers into bitmask values and OR all
  536. ** the bitmasks together.
  537. */
  538. //static Bitmask exprListTableUsage(WhereMaskSet*, ExprList);
  539. //static Bitmask exprSelectTableUsage(WhereMaskSet*, Select);
  540. static Bitmask exprTableUsage( WhereMaskSet pMaskSet, Expr p )
  541. {
  542. Bitmask mask = 0;
  543. if ( p == null )
  544. return 0;
  545. if ( p.op == TK_COLUMN )
  546. {
  547. mask = getMask( pMaskSet, p.iTable );
  548. return mask;
  549. }
  550. mask = exprTableUsage( pMaskSet, p.pRight );
  551. mask |= exprTableUsage( pMaskSet, p.pLeft );
  552. if ( ExprHasProperty( p, EP_xIsSelect ) )
  553. {
  554. mask |= exprSelectTableUsage( pMaskSet, p.x.pSelect );
  555. }
  556. else
  557. {
  558. mask |= exprListTableUsage( pMaskSet, p.x.pList );
  559. }
  560. return mask;
  561. }
  562. static Bitmask exprListTableUsage( WhereMaskSet pMaskSet, ExprList pList )
  563. {
  564. int i;
  565. Bitmask mask = 0;
  566. if ( pList != null )
  567. {
  568. for ( i = 0; i < pList.nExpr; i++ )
  569. {
  570. mask |= exprTableUsage( pMaskSet, pList.a[i].pExpr );
  571. }
  572. }
  573. return mask;
  574. }
  575. static Bitmask exprSelectTableUsage( WhereMaskSet pMaskSet, Select pS )
  576. {
  577. Bitmask mask = 0;
  578. while ( pS != null )
  579. {
  580. mask |= exprListTableUsage( pMaskSet, pS.pEList );
  581. mask |= exprListTableUsage( pMaskSet, pS.pGroupBy );
  582. mask |= exprListTableUsage( pMaskSet, pS.pOrderBy );
  583. mask |= exprTableUsage( pMaskSet, pS.pWhere );
  584. mask |= exprTableUsage( pMaskSet, pS.pHaving );
  585. pS = pS.pPrior;
  586. }
  587. return mask;
  588. }
  589. /*
  590. ** Return TRUE if the given operator is one of the operators that is
  591. ** allowed for an indexable WHERE clause term. The allowed operators are
  592. ** "=", "<", ">", "<=", ">=", and "IN".
  593. **
  594. ** IMPLEMENTATION-OF: R-59926-26393 To be usable by an index a term must be
  595. ** of one of the following forms: column = expression column > expression
  596. ** column >= expression column < expression column <= expression
  597. ** expression = column expression > column expression >= column
  598. ** expression < column expression <= column column IN
  599. ** (expression-list) column IN (subquery) column IS NULL
  600. */
  601. static bool allowedOp( int op )
  602. {
  603. Debug.Assert( TK_GT > TK_EQ && TK_GT < TK_GE );
  604. Debug.Assert( TK_LT > TK_EQ && TK_LT < TK_GE );
  605. Debug.Assert( TK_LE > TK_EQ && TK_LE < TK_GE );
  606. Debug.Assert( TK_GE == TK_EQ + 4 );
  607. return op == TK_IN || ( op >= TK_EQ && op <= TK_GE ) || op == TK_ISNULL;
  608. }
  609. /*
  610. ** Swap two objects of type TYPE.
  611. */
  612. //#define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
  613. /*
  614. ** Commute a comparison operator. Expressions of the form "X op Y"
  615. ** are converted into "Y op X".
  616. **
  617. ** If a collation sequence is Debug.Associated with either the left or right
  618. ** side of the comparison, it remains Debug.Associated with the same side after
  619. ** the commutation. So "Y collate NOCASE op X" becomes
  620. ** "X collate NOCASE op Y". This is because any collation sequence on
  621. ** the left hand side of a comparison overrides any collation sequence
  622. ** attached to the right. For the same reason the EP_ExpCollate flag
  623. ** is not commuted.
  624. */
  625. static void exprCommute( Parse pParse, Expr pExpr )
  626. {
  627. u16 expRight = (u16)( pExpr.pRight.flags & EP_ExpCollate );
  628. u16 expLeft = (u16)( pExpr.pLeft.flags & EP_ExpCollate );
  629. Debug.Assert( allowedOp( pExpr.op ) && pExpr.op != TK_IN );
  630. pExpr.pRight.pColl = sqlite3ExprCollSeq( pParse, pExpr.pRight );
  631. pExpr.pLeft.pColl = sqlite3ExprCollSeq( pParse, pExpr.pLeft );
  632. SWAP( ref pExpr.pRight.pColl, ref pExpr.pLeft.pColl );
  633. pExpr.pRight.flags = (u16)( ( pExpr.pRight.flags & ~EP_ExpCollate ) | expLeft );
  634. pExpr.pLeft.flags = (u16)( ( pExpr.pLeft.flags & ~EP_ExpCollate ) | expRight );
  635. SWAP( ref pExpr.pRight, ref pExpr.pLeft );
  636. if ( pExpr.op >= TK_GT )
  637. {
  638. Debug.Assert( TK_LT == TK_GT + 2 );
  639. Debug.Assert( TK_GE == TK_LE + 2 );
  640. Debug.Assert( TK_GT > TK_EQ );
  641. Debug.Assert( TK_GT < TK_LE );
  642. Debug.Assert( pExpr.op >= TK_GT && pExpr.op <= TK_GE );
  643. pExpr.op = (u8)( ( ( pExpr.op - TK_GT ) ^ 2 ) + TK_GT );
  644. }
  645. }
  646. /*
  647. ** Translate from TK_xx operator to WO_xx bitmask.
  648. */
  649. static u16 operatorMask( int op )
  650. {
  651. u16 c;
  652. Debug.Assert( allowedOp( op ) );
  653. if ( op == TK_IN )
  654. {
  655. c = WO_IN;
  656. }
  657. else if ( op == TK_ISNULL )
  658. {
  659. c = WO_ISNULL;
  660. }
  661. else
  662. {
  663. Debug.Assert( ( WO_EQ << ( op - TK_EQ ) ) < 0x7fff );
  664. c = (u16)( WO_EQ << ( op - TK_EQ ) );
  665. }
  666. Debug.Assert( op != TK_ISNULL || c == WO_ISNULL );
  667. Debug.Assert( op != TK_IN || c == WO_IN );
  668. Debug.Assert( op != TK_EQ || c == WO_EQ );
  669. Debug.Assert( op != TK_LT || c == WO_LT );
  670. Debug.Assert( op != TK_LE || c == WO_LE );
  671. Debug.Assert( op != TK_GT || c == WO_GT );
  672. Debug.Assert( op != TK_GE || c == WO_GE );
  673. return c;
  674. }
  675. /*
  676. ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
  677. ** where X is a reference to the iColumn of table iCur and <op> is one of
  678. ** the WO_xx operator codes specified by the op parameter.
  679. ** Return a pointer to the term. Return 0 if not found.
  680. */
  681. static WhereTerm findTerm(
  682. WhereClause pWC, /* The WHERE clause to be searched */
  683. int iCur, /* Cursor number of LHS */
  684. int iColumn, /* Column number of LHS */
  685. Bitmask notReady, /* RHS must not overlap with this mask */
  686. u32 op, /* Mask of WO_xx values describing operator */
  687. Index pIdx /* Must be compatible with this index, if not NULL */
  688. )
  689. {
  690. WhereTerm pTerm;
  691. int k;
  692. Debug.Assert( iCur >= 0 );
  693. op &= WO_ALL;
  694. for ( k = pWC.nTerm; k != 0; k-- )//, pTerm++)
  695. {
  696. pTerm = pWC.a[pWC.nTerm - k];
  697. if ( pTerm.leftCursor == iCur
  698. && ( pTerm.prereqRight & notReady ) == 0
  699. && pTerm.u.leftColumn == iColumn
  700. && ( pTerm.eOperator & op ) != 0
  701. )
  702. {
  703. if ( pIdx != null && pTerm.eOperator != WO_ISNULL )
  704. {
  705. Expr pX = pTerm.pExpr;
  706. CollSeq pColl;
  707. char idxaff;
  708. int j;
  709. Parse pParse = pWC.pParse;
  710. idxaff = pIdx.pTable.aCol[iColumn].affinity;
  711. if ( !sqlite3IndexAffinityOk( pX, idxaff ) )
  712. continue;
  713. /* Figure out the collation sequence required from an index for
  714. ** it to be useful for optimising expression pX. Store this
  715. ** value in variable pColl.
  716. */
  717. Debug.Assert( pX.pLeft != null );
  718. pColl = sqlite3BinaryCompareCollSeq( pParse, pX.pLeft, pX.pRight );
  719. Debug.Assert( pColl != null || pParse.nErr != 0 );
  720. for ( j = 0; pIdx.aiColumn[j] != iColumn; j++ )
  721. {
  722. if ( NEVER( j >= pIdx.nColumn ) )
  723. return null;
  724. }
  725. if ( pColl != null && !pColl.zName.Equals( pIdx.azColl[j], StringComparison.OrdinalIgnoreCase ) )
  726. continue;
  727. }
  728. return pTerm;
  729. }
  730. }
  731. return null;
  732. }
  733. /* Forward reference */
  734. //static void exprAnalyze(SrcList*, WhereClause*, int);
  735. /*
  736. ** Call exprAnalyze on all terms in a WHERE clause.
  737. **
  738. **
  739. */
  740. static void exprAnalyzeAll(
  741. SrcList pTabList, /* the FROM clause */
  742. WhereClause pWC /* the WHERE clause to be analyzed */
  743. )
  744. {
  745. int i;
  746. for ( i = pWC.nTerm - 1; i >= 0; i-- )
  747. {
  748. exprAnalyze( pTabList, pWC, i );
  749. }
  750. }
  751. #if !SQLITE_OMIT_LIKE_OPTIMIZATION
  752. /*
  753. ** Check to see if the given expression is a LIKE or GLOB operator that
  754. ** can be optimized using inequality constraints. Return TRUE if it is
  755. ** so and false if not.
  756. **
  757. ** In order for the operator to be optimizible, the RHS must be a string
  758. ** literal that does not begin with a wildcard.
  759. */
  760. static int isLikeOrGlob(
  761. Parse pParse, /* Parsing and code generating context */
  762. Expr pExpr, /* Test this expression */
  763. ref Expr ppPrefix, /* Pointer to TK_STRING expression with pattern prefix */
  764. ref bool pisComplete, /* True if the only wildcard is % in the last character */
  765. ref bool pnoCase /* True if uppercase is equivalent to lowercase */
  766. )
  767. {
  768. string z = null; /* String on RHS of LIKE operator */
  769. Expr pRight, pLeft; /* Right and left size of LIKE operator */
  770. ExprList pList; /* List of operands to the LIKE operator */
  771. int c = 0; /* One character in z[] */
  772. int cnt; /* Number of non-wildcard prefix characters */
  773. char[] wc = new char[3]; /* Wildcard characters */
  774. sqlite3 db = pParse.db; /* Data_base connection */
  775. sqlite3_value pVal = null;
  776. int op; /* Opcode of pRight */
  777. if ( !sqlite3IsLikeFunction( db, pExpr, ref pnoCase, wc ) )
  778. {
  779. return 0;
  780. }
  781. //#if SQLITE_EBCDIC
  782. //if( pnoCase ) return 0;
  783. //#endif
  784. pList = pExpr.x.pList;
  785. pLeft = pList.a[1].pExpr;
  786. if ( pLeft.op != TK_COLUMN || sqlite3ExprAffinity( pLeft ) != SQLITE_AFF_TEXT )
  787. {
  788. /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
  789. ** be the name of an indexed column with TEXT affinity. */
  790. return 0;
  791. }
  792. Debug.Assert( pLeft.iColumn != ( -1 ) ); /* Because IPK never has AFF_TEXT */
  793. pRight = pList.a[0].pExpr;
  794. op = pRight.op;
  795. if ( op == TK_REGISTER )
  796. {
  797. op = pRight.op2;
  798. }
  799. if ( op == TK_VARIABLE )
  800. {
  801. Vdbe pReprepare = pParse.pReprepare;
  802. int iCol = pRight.iColumn;
  803. pVal = sqlite3VdbeGetValue( pReprepare, iCol, (byte)SQLITE_AFF_NONE );
  804. if ( pVal != null && sqlite3_value_type( pVal ) == SQLITE_TEXT )
  805. {
  806. z = sqlite3_value_text( pVal );
  807. }
  808. sqlite3VdbeSetVarmask( pParse.pVdbe, iCol ); /* IMP: R-23257-02778 */
  809. Debug.Assert( pRight.op == TK_VARIABLE || pRight.op == TK_REGISTER );
  810. }
  811. else if ( op == TK_STRING )
  812. {
  813. z = pRight.u.zToken;
  814. }
  815. if ( !String.IsNullOrEmpty( z ) )
  816. {
  817. cnt = 0;
  818. while ( cnt < z.Length && ( c = z[cnt] ) != 0 && c != wc[0] && c != wc[1] && c != wc[2] )
  819. {
  820. cnt++;
  821. }
  822. if ( cnt != 0 && 255 != (u8)z[cnt - 1] )
  823. {
  824. Expr pPrefix;
  825. pisComplete = c == wc[0] && cnt == z.Length - 1;
  826. pPrefix = sqlite3Expr( db, TK_STRING, z );
  827. if ( pPrefix != null )
  828. pPrefix.u.zToken = pPrefix.u.zToken.Substring( 0, cnt );
  829. ppPrefix = pPrefix;
  830. if ( op == TK_VARIABLE )
  831. {
  832. Vdbe v = pParse.pVdbe;
  833. sqlite3VdbeSetVarmask( v, pRight.iColumn ); /* IMP: R-23257-02778 */
  834. if ( pisComplete && pRight.u.zToken.Length > 1 )
  835. {
  836. /* If the rhs of the LIKE expression is a variable, and the current
  837. ** value of the variable means there is no need to invoke the LIKE
  838. ** function, then no OP_Variable will be added to the program.
  839. ** This causes problems for the sqlite3_bind_parameter_name()
  840. ** API. To workaround them, add a dummy OP_Variable here.
  841. */
  842. int r1 = sqlite3GetTempReg( pParse );
  843. sqlite3ExprCodeTarget( pParse, pRight, r1 );
  844. sqlite3VdbeChangeP3( v, sqlite3VdbeCurrentAddr( v ) - 1, 0 );
  845. sqlite3ReleaseTempReg( pParse, r1 );
  846. }
  847. }
  848. }
  849. else
  850. {
  851. z = null;
  852. }
  853. }
  854. sqlite3ValueFree( ref pVal );
  855. return ( z != null ) ? 1 : 0;
  856. }
  857. #endif //* SQLITE_OMIT_LIKE_OPTIMIZATION */
  858. #if !SQLITE_OMIT_VIRTUALTABLE
  859. /*
  860. ** Check to see if the given expression is of the form
  861. **
  862. ** column MATCH expr
  863. **
  864. ** If it is then return TRUE. If not, return FALSE.
  865. */
  866. static int isMatchOfColumn(
  867. Expr pExpr /* Test this expression */
  868. ){
  869. ExprList pList;
  870. if( pExpr.op!=TK_FUNCTION ){
  871. return 0;
  872. }
  873. if( !pExpr.u.zToken.Equals("match", StringComparison.OrdinalIgnoreCase ) ){
  874. return 0;
  875. }
  876. pList = pExpr.x.pList;
  877. if( pList.nExpr!=2 ){
  878. return 0;
  879. }
  880. if( pList.a[1].pExpr.op != TK_COLUMN ){
  881. return 0;
  882. }
  883. return 1;
  884. }
  885. #endif //* SQLITE_OMIT_VIRTUALTABLE */
  886. /*
  887. ** If the pBase expression originated in the ON or USING clause of
  888. ** a join, then transfer the appropriate markings over to derived.
  889. */
  890. static void transferJoinMarkings( Expr pDerived, Expr pBase )
  891. {
  892. pDerived.flags = (u16)( pDerived.flags | pBase.flags & EP_FromJoin );
  893. pDerived.iRightJoinTable = pBase.iRightJoinTable;
  894. }
  895. #if !(SQLITE_OMIT_OR_OPTIMIZATION) && !(SQLITE_OMIT_SUBQUERY)
  896. /*
  897. ** Analyze a term that consists of two or more OR-connected
  898. ** subterms. So in:
  899. **
  900. ** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
  901. ** ^^^^^^^^^^^^^^^^^^^^
  902. **
  903. ** This routine analyzes terms such as the middle term in the above example.
  904. ** A WhereOrTerm object is computed and attached to the term under
  905. ** analysis, regardless of the outcome of the analysis. Hence:
  906. **
  907. ** WhereTerm.wtFlags |= TERM_ORINFO
  908. ** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object
  909. **
  910. ** The term being analyzed must have two or more of OR-connected subterms.
  911. ** A single subterm might be a set of AND-connected sub-subterms.
  912. ** Examples of terms under analysis:
  913. **
  914. ** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
  915. ** (B) x=expr1 OR expr2=x OR x=expr3
  916. ** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
  917. ** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
  918. ** (E) (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
  919. **
  920. ** CASE 1:
  921. **
  922. ** If all subterms are of the form T.C=expr for some single column of C
  923. ** a single table T (as shown in example B above) then create a new virtual
  924. ** term that is an equivalent IN expression. In other words, if the term
  925. ** being analyzed is:
  926. **
  927. ** x = expr1 OR expr2 = x OR x = expr3
  928. **
  929. ** then create a new virtual term like this:
  930. **
  931. ** x IN (expr1,expr2,expr3)
  932. **
  933. ** CASE 2:
  934. **
  935. ** If all subterms are indexable by a single table T, then set
  936. **
  937. ** WhereTerm.eOperator = WO_OR
  938. ** WhereTerm.u.pOrInfo.indexable |= the cursor number for table T
  939. **
  940. ** A subterm is "indexable" if it is of the form
  941. ** "T.C <op> <expr>" where C is any column of table T and
  942. ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
  943. ** A subterm is also indexable if it is an AND of two or more
  944. ** subsubterms at least one of which is indexable. Indexable AND
  945. ** subterms have their eOperator set to WO_AND and they have
  946. ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
  947. **
  948. ** From another point of view, "indexable" means that the subterm could
  949. ** potentially be used with an index if an appropriate index exists.
  950. ** This analysis does not consider whether or not the index exists; that
  951. ** is something the bestIndex() routine will determine. This analysis
  952. ** only looks at whether subterms appropriate for indexing exist.
  953. **
  954. ** All examples A through E above all satisfy case 2. But if a term
  955. ** also statisfies case 1 (such as B) we know that the optimizer will
  956. ** always prefer case 1, so in that case we pretend that case 2 is not
  957. ** satisfied.
  958. **
  959. ** It might be the case that multiple tables are indexable. For example,
  960. ** (E) above is indexable on tables P, Q, and R.
  961. **
  962. ** Terms that satisfy case 2 are candidates for lookup by using
  963. ** separate indices to find rowids for each subterm and composing
  964. ** the union of all rowids using a RowSet object. This is similar
  965. ** to "bitmap indices" in other data_base engines.
  966. **
  967. ** OTHERWISE:
  968. **
  969. ** If neither case 1 nor case 2 apply, then leave the eOperator set to
  970. ** zero. This term is not useful for search.
  971. */
  972. static void exprAnalyzeOrTerm(
  973. SrcList pSrc, /* the FROM clause */
  974. WhereClause pWC, /* the complete WHERE clause */
  975. int idxTerm /* Index of the OR-term to be analyzed */
  976. )
  977. {
  978. Parse pParse = pWC.pParse; /* Parser context */
  979. sqlite3 db = pParse.db; /* Data_base connection */
  980. WhereTerm pTerm = pWC.a[idxTerm]; /* The term to be analyzed */
  981. Expr pExpr = pTerm.pExpr; /* The expression of the term */
  982. WhereMaskSet pMaskSet = pWC.pMaskSet; /* Table use masks */
  983. int i; /* Loop counters */
  984. WhereClause pOrWc; /* Breakup of pTerm into subterms */
  985. WhereTerm pOrTerm; /* A Sub-term within the pOrWc */
  986. WhereOrInfo pOrInfo; /* Additional information Debug.Associated with pTerm */
  987. Bitmask chngToIN; /* Tables that might satisfy case 1 */
  988. Bitmask indexable; /* Tables that are indexable, satisfying case 2 */
  989. /*
  990. ** Break the OR clause into its separate subterms. The subterms are
  991. ** stored in a WhereClause structure containing within the WhereOrInfo
  992. ** object that is attached to the original OR clause term.
  993. */
  994. Debug.Assert( ( pTerm.wtFlags & ( TERM_DYNAMIC | TERM_ORINFO | TERM_ANDINFO ) ) == 0 );
  995. Debug.Assert( pExpr.op == TK_OR );
  996. pTerm.u.pOrInfo = pOrInfo = new WhereOrInfo();//sqlite3DbMallocZero(db, sizeof(*pOrInfo));
  997. if ( pOrInfo == null )
  998. return;
  999. pTerm.wtFlags |= TERM_ORINFO;
  1000. pOrWc = pOrInfo.wc;
  1001. whereClauseInit( pOrWc, pWC.pParse, pMaskSet );
  1002. whereSplit( pOrWc, pExpr, TK_OR );
  1003. exprAnalyzeAll( pSrc, pOrWc );
  1004. // if ( db.mallocFailed != 0 ) return;
  1005. Debug.Assert( pOrWc.nTerm >= 2 );
  1006. /*
  1007. ** Compute the set of tables that might satisfy cases 1 or 2.
  1008. */
  1009. indexable = ~(Bitmask)0;
  1010. chngToIN = ~( pWC.vmask );
  1011. for ( i = pOrWc.nTerm - 1; i >= 0 && indexable != 0; i-- )//, pOrTerm++ )
  1012. {
  1013. pOrTerm = pOrWc.a[i];
  1014. if ( ( pOrTerm.eOperator & WO_SINGLE ) == 0 )
  1015. {
  1016. WhereAndInfo pAndInfo;
  1017. Debug.Assert( pOrTerm.eOperator == 0 );
  1018. Debug.Assert( ( pOrTerm.wtFlags & ( TERM_ANDINFO | TERM_ORINFO ) ) == 0 );
  1019. chngToIN = 0;
  1020. pAndInfo = new WhereAndInfo();//sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
  1021. if ( pAndInfo != null )
  1022. {
  1023. WhereClause pAndWC;
  1024. WhereTerm pAndTerm;
  1025. int j;
  1026. Bitmask b = 0;
  1027. pOrTerm.u.pAndInfo = pAndInfo;
  1028. pOrTerm.wtFlags |= TERM_ANDINFO;
  1029. pOrTerm.eOperator = WO_AND;
  1030. pAndWC = pAndInfo.wc;
  1031. whereClauseInit( pAndWC, pWC.pParse, pMaskSet );
  1032. whereSplit( pAndWC, pOrTerm.pExpr, TK_AND );
  1033. exprAnalyzeAll( pSrc, pAndWC );
  1034. //testcase( db.mallocFailed );
  1035. ////if ( 0 == db.mallocFailed )
  1036. {
  1037. for ( j = 0; j < pAndWC.nTerm; j++ )//, pAndTerm++ )
  1038. {
  1039. pAndTerm = pAndWC.a[j];
  1040. Debug.Assert( pAndTerm.pExpr != null );
  1041. if ( allowedOp( pAndTerm.pExpr.op ) )
  1042. {
  1043. b |= getMask( pMaskSet, pAndTerm.leftCursor );
  1044. }
  1045. }
  1046. }
  1047. indexable &= b;
  1048. }
  1049. }
  1050. else if ( ( pOrTerm.wtFlags & TERM_COPIED ) != 0 )
  1051. {
  1052. /* Skip this term for now. We revisit it when we process the
  1053. ** corresponding TERM_VIRTUAL term */
  1054. }
  1055. else
  1056. {
  1057. Bitmask b;
  1058. b = getMask( pMaskSet, pOrTerm.leftCursor );
  1059. if ( ( pOrTerm.wtFlags & TERM_VIRTUAL ) != 0 )
  1060. {
  1061. WhereTerm pOther = pOrWc.a[pOrTerm.iParent];
  1062. b |= getMask( pMaskSet, pOther.leftCursor );
  1063. }
  1064. indexable &= b;
  1065. if ( pOrTerm.eOperator != WO_EQ )
  1066. {
  1067. chngToIN = 0;
  1068. }
  1069. else
  1070. {
  1071. chngToIN &= b;
  1072. }
  1073. }
  1074. }
  1075. /*
  1076. ** Record the set of tables that satisfy case 2. The set might be
  1077. ** empty.
  1078. */
  1079. pOrInfo.indexable = indexable;
  1080. pTerm.eOperator = (u16)( indexable == 0 ? 0 : WO_OR );
  1081. /*
  1082. ** chngToIN holds a set of tables that *might* satisfy case 1. But
  1083. ** we have to do some additional checking to see if case 1 really
  1084. ** is satisfied.
  1085. **
  1086. ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means
  1087. ** that there is no possibility of transforming the OR clause into an
  1088. ** IN operator because one or more terms in the OR clause contain
  1089. ** something other than == on a column in the single table. The 1-bit
  1090. ** case means that every term of the OR clause is of the form
  1091. ** "table.column=expr" for some single table. The one bit that is set
  1092. ** will correspond to the common table. We still need to check to make
  1093. ** sure the same column is used on all terms. The 2-bit case is when
  1094. ** the all terms are of the form "table1.column=table2.column". It
  1095. ** might be possible to form an IN operator with either table1.column
  1096. ** or table2.column as the LHS if either is common to every term of
  1097. ** the OR clause.
  1098. **
  1099. ** Note that terms of the form "table.column1=table.column2" (the
  1100. ** same table on both sizes of the ==) cannot be optimized.
  1101. */
  1102. if ( chngToIN != 0 )
  1103. {
  1104. int okToChngToIN = 0; /* True if the conversion to IN is valid */
  1105. int iColumn = -1; /* Column index on lhs of IN operator */
  1106. int iCursor = -1; /* Table cursor common to all terms */
  1107. int j = 0; /* Loop counter */
  1108. /* Search for a table and column that appears on one side or the
  1109. ** other of the == operator in every subterm. That table and column
  1110. ** will be recorded in iCursor and iColumn. There might not be any
  1111. ** such table and column. Set okToChngToIN if an appropriate table
  1112. ** and column is found but leave okToChngToIN false if not found.
  1113. */
  1114. for ( j = 0; j < 2 && 0 == okToChngToIN; j++ )
  1115. {
  1116. //pOrTerm = pOrWc.a;
  1117. for ( i = pOrWc.nTerm - 1; i >= 0; i-- )//, pOrTerm++)
  1118. {
  1119. pOrTerm = pOrWc.a[pOrWc.nTerm - 1 - i];
  1120. Debug.Assert( pOrTerm.eOperator == WO_EQ );
  1121. pOrTerm.wtFlags = (u8)( pOrTerm.wtFlags & ~TERM_OR_OK );
  1122. if ( pOrTerm.leftCursor == iCursor )
  1123. {
  1124. /* This is the 2-bit case and we are on the second iteration and
  1125. ** current term is from the first iteration. So skip this term. */
  1126. Debug.Assert( j == 1 );
  1127. continue;
  1128. }
  1129. if ( ( chngToIN & getMask( pMaskSet, pOrTerm.leftCursor ) ) == 0 )
  1130. {
  1131. /* This term must be of the form t1.a==t2.b where t2 is in the
  1132. ** chngToIN set but t1 is not. This term will be either preceeded
  1133. ** or follwed by an inverted copy (t2.b==t1.a). Skip this term
  1134. ** and use its inversion. */
  1135. testcase( pOrTerm.wtFlags & TERM_COPIED );
  1136. testcase( pOrTerm.wtFlags & TERM_VIRTUAL );
  1137. Debug.Assert( ( pOrTerm.wtFlags & ( TERM_COPIED | TERM_VIRTUAL ) ) != 0 );
  1138. continue;
  1139. }
  1140. iColumn = pOrTerm.u.leftColumn;
  1141. iCursor = pOrTerm.leftCursor;
  1142. break;
  1143. }
  1144. if ( i < 0 )
  1145. {
  1146. /* No candidate table+column was found. This can only occur
  1147. ** on the second iteration */
  1148. Debug.Assert( j == 1 );
  1149. Debug.Assert( ( chngToIN & ( chngToIN - 1 ) ) == 0 );
  1150. Debug.Assert( chngToIN == getMask( pMaskSet, iCursor ) );
  1151. break;
  1152. }
  1153. testcase( j == 1 );
  1154. /* We have found a candidate table and column. Check to see if that
  1155. ** table and column is common to every term in the OR clause */
  1156. okToChngToIN = 1;
  1157. for ( ; i >= 0 && okToChngToIN != 0; i-- )//, pOrTerm++)
  1158. {
  1159. pOrTerm = pOrWc.a[pOrWc.nTerm - 1 - i];
  1160. Debug.Assert( pOrTerm.eOperator == WO_EQ );
  1161. if ( pOrTerm.leftCursor != iCursor )
  1162. {
  1163. pOrTerm.wtFlags = (u8)( pOrTerm.wtFlags & ~TERM_OR_OK );
  1164. }
  1165. else if ( pOrTerm.u.leftColumn != iColumn )
  1166. {
  1167. okToChngToIN = 0;
  1168. }
  1169. else
  1170. {
  1171. int affLeft, affRight;
  1172. /* If the right-hand side is also a column, then the affinities
  1173. ** of both right and left sides must be such that no type
  1174. ** conversions are required on the right. (Ticket #2249)
  1175. */
  1176. affRight = sqlite3ExprAffinity( pOrTerm.pExpr.pRight );
  1177. affLeft = sqlite3ExprAffinity( pOrTerm.pExpr.pLeft );
  1178. if ( affRight != 0 && affRight != affLeft )
  1179. {
  1180. okToChngToIN = 0;
  1181. }
  1182. else
  1183. {
  1184. pOrTerm.wtFlags |= TERM_OR_OK;
  1185. }
  1186. }
  1187. }
  1188. }
  1189. /* At this point, okToChngToIN is true if original pTerm satisfies
  1190. ** case 1. In that case, construct a new virtual term that is
  1191. ** pTerm converted into an IN operator.
  1192. **
  1193. ** EV: R-00211-15100
  1194. */
  1195. if ( okToChngToIN != 0 )
  1196. {
  1197. Expr pDup; /* A transient duplicate expression */
  1198. ExprList pList = null; /* The RHS of the IN operator */
  1199. Expr pLeft = null; /* The LHS of the IN operator */
  1200. Expr pNew; /* The complete IN operator */
  1201. for ( i = pOrWc.nTerm - 1; i >= 0; i-- )//, pOrTerm++)
  1202. {
  1203. pOrTerm = pOrWc.a[pOrWc.nTerm - 1 - i];
  1204. if ( ( pOrTerm.wtFlags & TERM_OR_OK ) == 0 )
  1205. continue;
  1206. Debug.Assert( pOrTerm.eOperator == WO_EQ );
  1207. Debug.Assert( pOrTerm.leftCursor == iCursor );
  1208. Debug.Assert( pOrTerm.u.leftColumn == iColumn );
  1209. pDup = sqlite3ExprDup( db, pOrTerm.pExpr.pRight, 0 );
  1210. pList = sqlite3ExprListAppend( pWC.pParse, pList, pDup );
  1211. pLeft = pOrTerm.pExpr.pLeft;
  1212. }
  1213. Debug.Assert( pLeft != null );
  1214. pDup = sqlite3ExprDup( db, pLeft, 0 );
  1215. pNew = sqlite3PExpr( pParse, TK_IN, pDup, null, null );
  1216. if ( pNew != null )
  1217. {
  1218. int idxNew;
  1219. transferJoinMarkings( pNew, pExpr );
  1220. Debug.Assert( !ExprHasProperty( pNew, EP_xIsSelect ) );
  1221. pNew.x.pList = pList;
  1222. idxNew = whereClauseInsert( pWC, pNew, TERM_VIRTUAL | TERM_DYNAMIC );
  1223. testcase( idxNew == 0 );
  1224. exprAnalyze( pSrc, pWC, idxNew );
  1225. pTerm = pWC.a[idxTerm];
  1226. pWC.a[idxNew].iParent = idxTerm;
  1227. pTerm.nChild = 1;
  1228. }
  1229. else
  1230. {
  1231. sqlite3ExprListDelete( db, ref pList );
  1232. }
  1233. pTerm.eOperator = WO_NOOP; /* case 1 trumps case 2 */
  1234. }
  1235. }
  1236. }
  1237. #endif //* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
  1238. /*
  1239. ** The input to this routine is an WhereTerm structure with only the
  1240. ** "pExpr" field filled in. The job of this routine is to analyze the
  1241. ** subexpression and populate all the other fields of the WhereTerm
  1242. ** structure.
  1243. **
  1244. ** If the expression is of the form "<expr> <op> X" it gets commuted
  1245. ** to the standard form of "X <op> <expr>".
  1246. **
  1247. ** If the expression is of the form "X <op> Y" where both X and Y are
  1248. ** columns, then the original expression is unchanged and a new virtual
  1249. ** term of the form "Y <op> X" is added to the WHERE clause and
  1250. ** analyzed separately. The original term is marked with TERM_COPIED
  1251. ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
  1252. ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
  1253. ** is a commuted copy of a prior term.) The original term has nChild=1
  1254. ** and the copy has idxParent set to the index of the original term.
  1255. */
  1256. static void exprAnalyze(
  1257. SrcList pSrc, /* the FROM clause */
  1258. WhereClause pWC, /* the WHERE clause */
  1259. int idxTerm /* Index of the term to be analyzed */
  1260. )
  1261. {
  1262. WhereTerm pTerm; /* The term to be analyzed */
  1263. WhereMaskSet pMaskSet; /* Set of table index masks */
  1264. Expr pExpr; /* The expression to be analyzed */
  1265. Bitmask prereqLeft; /* Prerequesites of the pExpr.pLeft */
  1266. Bitmask prereqAll; /* Prerequesites of pExpr */
  1267. Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */
  1268. Expr pStr1 = null; /* RHS of LIKE/GLOB operator */
  1269. bool isComplete = false; /* RHS of LIKE/GLOB ends with wildcard */
  1270. bool noCase = false; /* LIKE/GLOB distinguishes case */
  1271. int op; /* Top-level operator. pExpr.op */
  1272. Parse pParse = pWC.pParse; /* Parsing context */
  1273. sqlite3 db = pParse.db; /* Data_base connection */
  1274. //if ( db.mallocFailed != 0 )
  1275. //{
  1276. // return;
  1277. //}
  1278. pTerm = pWC.a[idxTerm];
  1279. pMaskSet = pWC.pMaskSet;
  1280. pExpr = pTerm.pExpr;
  1281. prereqLeft = exprTableUsage( pMaskSet, pExpr.pLeft );
  1282. op = pExpr.op;
  1283. if ( op == TK_IN )
  1284. {
  1285. Debug.Assert( pExpr.pRight == null );
  1286. if ( ExprHasProperty( pExpr, EP_xIsSelect ) )
  1287. {
  1288. pTerm.prereqRight = exprSelectTableUsage( pMaskSet, pExpr.x.pSelect );
  1289. }
  1290. else
  1291. {
  1292. pTerm.prereqRight = exprListTableUsage( pMaskSet, pExpr.x.pList );
  1293. }
  1294. }
  1295. else if ( op == TK_ISNULL )
  1296. {
  1297. pTerm.prereqRight = 0;
  1298. }
  1299. else
  1300. {
  1301. pTerm.prereqRight = exprTableUsage( pMaskSet, pExpr.pRight );
  1302. }
  1303. prereqAll = exprTableUsage( pMaskSet, pExpr );
  1304. if ( ExprHasProperty( pExpr, EP_FromJoin ) )
  1305. {
  1306. Bitmask x = getMask( pMaskSet, pExpr.iRightJoinTable );
  1307. prereqAll |= x;
  1308. extraRight = x - 1; /* ON clause terms may not be used with an index
  1309. ** on left table of a LEFT JOIN. Ticket #3015 */
  1310. }
  1311. pTerm.prereqAll = prereqAll;
  1312. pTerm.leftCursor = -1;
  1313. pTerm.iParent = -1;
  1314. pTerm.eOperator = 0;
  1315. if ( allowedOp( op ) && ( pTerm.prereqRight & prereqLeft ) == 0 )
  1316. {
  1317. Expr pLeft = pExpr.pLeft;
  1318. Expr pRight = pExpr.pRight;
  1319. if ( pLeft.op == TK_COLUMN )
  1320. {
  1321. pTerm.leftCursor = pLeft.iTable;
  1322. pTerm.u.leftColumn = pLeft.iColumn;
  1323. pTerm.eOperator = operatorMask( op );
  1324. }
  1325. if ( pRight != null && pRight.op == TK_COLUMN )
  1326. {
  1327. WhereTerm pNew;
  1328. Expr pDup;
  1329. if ( pTerm.leftCursor >= 0 )
  1330. {
  1331. int idxNew;
  1332. pDup = sqlite3ExprDup( db, pExpr, 0 );
  1333. //if ( db.mallocFailed != 0 )
  1334. //{
  1335. // sqlite3ExprDelete( db, ref pDup );
  1336. // return;
  1337. //}
  1338. idxNew = whereClauseInsert( pWC, pDup, TERM_VIRTUAL | TERM_DYNAMIC );
  1339. if ( idxNew == 0 )
  1340. return;
  1341. pNew = pWC.a[idxNew];
  1342. pNew.iParent = idxTerm;
  1343. pTerm = pWC.a[idxTerm];
  1344. pTerm.nChild = 1;
  1345. pTerm.wtFlags |= TERM_COPIED;
  1346. }
  1347. else
  1348. {
  1349. pDup = pExpr;
  1350. pNew = pTerm;
  1351. }
  1352. exprCommute( pParse, pDup );
  1353. pLeft = pDup.pLeft;
  1354. pNew.leftCursor = pLeft.iTable;
  1355. pNew.u.leftColumn = pLeft.iColumn;
  1356. testcase( ( prereqLeft | extraRight ) != prereqLeft );
  1357. pNew.prereqRight = prereqLeft | extraRight;
  1358. pNew.prereqAll = prereqAll;
  1359. pNew.eOperator = operatorMask( pDup.op );
  1360. }
  1361. }
  1362. #if !SQLITE_OMIT_BETWEEN_OPTIMIZATION
  1363. /* If a term is the BETWEEN operator, create two new virtual terms
  1364. ** that define the range that the BETWEEN implements. For example:
  1365. **
  1366. ** a BETWEEN b AND c
  1367. **
  1368. ** is converted into:
  1369. **
  1370. ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
  1371. **
  1372. ** The two new terms are added onto the end of the WhereClause object.
  1373. ** The new terms are "dynamic" and are children of the original BETWEEN
  1374. ** term. That means that if the BETWEEN term is coded, the children are
  1375. ** skipped. Or, if the children are satisfied by an index, the original
  1376. ** BETWEEN term is skipped.
  1377. */
  1378. else if ( pExpr.op == TK_BETWEEN && pWC.op == TK_AND )
  1379. {
  1380. ExprList pList = pExpr.x.pList;
  1381. int i;
  1382. u8[] ops = new u8[] { TK_GE, TK_LE };
  1383. Debug.Assert( pList != null );
  1384. Debug.Assert( pList.nExpr == 2 );
  1385. for ( i = 0; i < 2; i++ )
  1386. {
  1387. Expr pNewExpr;
  1388. int idxNew;
  1389. pNewExpr = sqlite3PExpr( pParse, ops[i],
  1390. sqlite3ExprDup( db, pExpr.pLeft, 0 ),
  1391. sqlite3ExprDup( db, pList.a[i].pExpr, 0 ), null );
  1392. idxNew = whereClauseInsert( pWC, pNewExpr, TERM_VIRTUAL | TERM_DYNAMIC );
  1393. testcase( idxNew == 0 );
  1394. exprAnalyze( pSrc, pWC, idxNew );
  1395. pTerm = pWC.a[idxTerm];
  1396. pWC.a[idxNew].iParent = idxTerm;
  1397. }
  1398. pTerm.nChild = 2;
  1399. }
  1400. #endif //* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
  1401. #if !(SQLITE_OMIT_OR_OPTIMIZATION) && !(SQLITE_OMIT_SUBQUERY)
  1402. /* Analyze a term that is composed of two or more subterms connected by
  1403. ** an OR operator.
  1404. */
  1405. else if ( pExpr.op == TK_OR )
  1406. {
  1407. Debug.Assert( pWC.op == TK_AND );
  1408. exprAnalyzeOrTerm( pSrc, pWC, idxTerm );
  1409. pTerm = pWC.a[idxTerm];
  1410. }
  1411. #endif //* SQLITE_OMIT_OR_OPTIMIZATION */
  1412. #if !SQLITE_OMIT_LIKE_OPTIMIZATION
  1413. /* Add constraints to reduce the search space on a LIKE or GLOB
  1414. ** operator.
  1415. **
  1416. ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
  1417. **
  1418. ** x>='abc' AND x<'abd' AND x LIKE 'abc%'
  1419. **
  1420. ** The last character of the prefix "abc" is incremented to form the
  1421. ** termination condition "abd".
  1422. */
  1423. if ( pWC.op == TK_AND
  1424. && isLikeOrGlob( pParse, pExpr, ref pStr1, ref isComplete, ref noCase ) != 0
  1425. )
  1426. {
  1427. Expr pLeft; /* LHS of LIKE/GLOB operator */
  1428. Expr pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */
  1429. Expr pNewExpr1;
  1430. Expr pNewExpr2;
  1431. int idxNew1;
  1432. int idxNew2;
  1433. CollSeq pColl; /* Collating sequence to use */
  1434. pLeft = pExpr.x.pList.a[1].pExpr;
  1435. pStr2 = sqlite3ExprDup( db, pStr1, 0 );
  1436. ////if ( 0 == db.mallocFailed )
  1437. {
  1438. int c, pC; /* Last character before the first wildcard */
  1439. pC = pStr2.u.zToken[sqlite3Strlen30( pStr2.u.zToken ) - 1];
  1440. c = pC;
  1441. if ( noCase )
  1442. {
  1443. /* The point is to increment the last character before the first
  1444. ** wildcard. But if we increment '@', that will push it into the
  1445. ** alphabetic range where case conversions will mess up the
  1446. ** inequality. To avoid this, make sure to also run the full
  1447. ** LIKE on all candidate expressions by clearing the isComplete flag
  1448. */
  1449. if ( c == 'A' - 1 )
  1450. isComplete = false; /* EV: R-64339-08207 */
  1451. c = sqlite3UpperToLower[c];
  1452. }
  1453. pStr2.u.zToken = pStr2.u.zToken.Substring( 0, sqlite3Strlen30( pStr2.u.zToken ) - 1 ) + (char)( c + 1 );// pC = c + 1;
  1454. }
  1455. pColl = sqlite3FindCollSeq( db, SQLITE_UTF8, noCase ? "NOCASE" : "BINARY", 0 );
  1456. pNewExpr1 = sqlite3PExpr( pParse, TK_GE,
  1457. sqlite3ExprSetColl( sqlite3ExprDup( db, pLeft, 0 ), pColl ),
  1458. pStr1, 0 );
  1459. idxNew1 = whereClauseInsert( pWC, pNewExpr1, TERM_VIRTUAL | TERM_DYNAMIC );
  1460. testcase( idxNew1 == 0 );
  1461. exprAnalyze( pSrc, pWC, idxNew1 );
  1462. pNewExpr2 = sqlite3PExpr( pParse, TK_LT,
  1463. sqlite3ExprSetColl( sqlite3ExprDup( db, pLeft, 0 ), pColl ),
  1464. pStr2, null );
  1465. idxNew2 = whereClauseInsert( pWC, pNewExpr2, TERM_VIRTUAL | TERM_DYNAMIC );
  1466. testcase( idxNew2 == 0 );
  1467. exprAnalyze( pSrc, pWC, idxNew2 );
  1468. pTerm = pWC.a[idxTerm];
  1469. if ( isComplete )
  1470. {
  1471. pWC.a[idxNew1].iParent = idxTerm;
  1472. pWC.a[idxNew2].iParent = idxTerm;
  1473. pTerm.nChild = 2;
  1474. }
  1475. }
  1476. #endif //* SQLITE_OMIT_LIKE_OPTIMIZATION */
  1477. #if !SQLITE_OMIT_VIRTUALTABLE
  1478. /* Add a WO_MATCH auxiliary term to the constraint set if the
  1479. ** current expression is of the form: column MATCH expr.
  1480. ** This information is used by the xBestIndex methods of
  1481. ** virtual tables. The native query optimizer does not attempt
  1482. ** to do anything with MATCH functions.
  1483. */
  1484. if ( isMatchOfColumn( pExpr ) != 0 )
  1485. {
  1486. int idxNew;
  1487. Expr pRight, pLeft;
  1488. WhereTerm pNewTerm;
  1489. Bitmask prereqColumn, prereqExpr;
  1490. pRight = pExpr.x.pList.a[0].pExpr;
  1491. pLeft = pExpr.x.pList.a[1].pExpr;
  1492. prereqExpr = exprTableUsage( pMaskSet, pRight );
  1493. prereqColumn = exprTableUsage( pMaskSet, pLeft );
  1494. if ( ( prereqExpr & prereqColumn ) == 0 )
  1495. {
  1496. Expr pNewExpr;
  1497. pNewExpr = sqlite3PExpr( pParse, TK_MATCH,
  1498. null, sqlite3ExprDup( db, pRight, 0 ), null );
  1499. idxNew = whereClauseInsert( pWC, pNewExpr, TERM_VIRTUAL | TERM_DYNAMIC );
  1500. testcase( idxNew == 0 );
  1501. pNewTerm = pWC.a[idxNew];
  1502. pNewTerm.prereqRight = prereqExpr;
  1503. pNewTerm.leftCursor = pLeft.iTable;
  1504. pNewTerm.u.leftColumn = pLeft.iColumn;
  1505. pNewTerm.eOperator = WO_MATCH;
  1506. pNewTerm.iParent = idxTerm;
  1507. pTerm = pWC.a[idxTerm];
  1508. pTerm.nChild = 1;
  1509. pTerm.wtFlags |= TERM_COPIED;
  1510. pNewTerm.prereqAll = pTerm.prereqAll;
  1511. }
  1512. }
  1513. #endif //* SQLITE_OMIT_VIRTUALTABLE */
  1514. #if SQLITE_ENABLE_STAT2
  1515. /* When sqlite_stat2 histogram data is available an operator of the
  1516. ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
  1517. ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a
  1518. ** virtual term of that form.
  1519. **
  1520. ** Note that the virtual term must be tagged with TERM_VNULL. This
  1521. ** TERM_VNULL tag will suppress the not-null check at the beginning
  1522. ** of the loop. Without the TERM_VNULL flag, the not-null check at
  1523. ** the start of the loop will prevent any results from being returned.
  1524. */
  1525. if ( pExpr.op == TK_NOTNULL
  1526. && pExpr.pLeft.op == TK_COLUMN
  1527. && pExpr.pLeft.iColumn >= 0
  1528. )
  1529. {
  1530. Expr pNewExpr;
  1531. Expr pLeft = pExpr.pLeft;
  1532. int idxNew;
  1533. WhereTerm pNewTerm;
  1534. pNewExpr = sqlite3PExpr( pParse, TK_GT,
  1535. sqlite3ExprDup( db, pLeft, 0 ),
  1536. sqlite3PExpr( pParse, TK_NULL, 0, 0, 0 ), 0 );
  1537. idxNew = whereClauseInsert( pWC, pNewExpr,
  1538. TERM_VIRTUAL | TERM_DYNAMIC | TERM_VNULL );
  1539. if ( idxNew != 0 )
  1540. {
  1541. pNewTerm = pWC.a[idxNew];
  1542. pNewTerm.prereqRight = 0;
  1543. pNewTerm.leftCursor = pLeft.iTable;
  1544. pNewTerm.u.leftColumn = pLeft.iColumn;
  1545. pNewTerm.eOperator = WO_GT;
  1546. pNewTerm.iParent = idxTerm;
  1547. pTerm = pWC.a[idxTerm];
  1548. pTerm.nChild = 1;
  1549. pTerm.wtFlags |= TERM_COPIED;
  1550. pNewTerm.prereqAll = pTerm.prereqAll;
  1551. }
  1552. }
  1553. #endif //* SQLITE_ENABLE_STAT2 */
  1554. /* Prevent ON clause terms of a LEFT JOIN from being used to drive
  1555. ** an index for tables to the left of the join.
  1556. */
  1557. pTerm.prereqRight |= extraRight;
  1558. }
  1559. /*
  1560. ** Return TRUE if any of the expressions in pList.a[iFirst...] contain
  1561. ** a reference to any table other than the iBase table.
  1562. */
  1563. static bool referencesOtherTables(
  1564. ExprList pList, /* Search expressions in ths list */
  1565. WhereMaskSet pMaskSet, /* Mapping from tables to bitmaps */
  1566. int iFirst, /* Be searching with the iFirst-th expression */
  1567. int iBase /* Ignore references to this table */
  1568. )
  1569. {
  1570. Bitmask allowed = ~getMask( pMaskSet, iBase );
  1571. while ( iFirst < pList.nExpr )
  1572. {
  1573. if ( ( exprTableUsage( pMaskSet, pList.a[iFirst++].pExpr ) & allowed ) != 0 )
  1574. {
  1575. return true;
  1576. }
  1577. }
  1578. return false;
  1579. }
  1580. /*
  1581. ** This routine decides if pIdx can be used to satisfy the ORDER BY
  1582. ** clause. If it can, it returns 1. If pIdx cannot satisfy the
  1583. ** ORDER BY clause, this routine returns 0.
  1584. **
  1585. ** pOrderBy is an ORDER BY clause from a SELECT statement. pTab is the
  1586. ** left-most table in the FROM clause of that same SELECT statement and
  1587. ** the table has a cursor number of "_base". pIdx is an index on pTab.
  1588. **
  1589. ** nEqCol is the number of columns of pIdx that are used as equality
  1590. ** constraints. Any of these columns may be missing from the ORDER BY
  1591. ** clause and the match can still be a success.
  1592. **
  1593. ** All terms of the ORDER BY that match against the index must be either
  1594. ** ASC or DESC. (Terms of the ORDER BY clause past the end of a UNIQUE
  1595. ** index do not need to satisfy this constraint.) The pbRev value is
  1596. ** set to 1 if the ORDER BY clause is all DESC and it is set to 0 if
  1597. ** the ORDER BY clause is all ASC.
  1598. */
  1599. static bool isSortingIndex(
  1600. Parse pParse, /* Parsing context */
  1601. WhereMaskSet pMaskSet, /* Mapping from table cursor numbers to bitmaps */
  1602. Index pIdx, /* The index we are testing */
  1603. int _base, /* Cursor number for the table to be sorted */
  1604. ExprList pOrderBy, /* The ORDER BY clause */
  1605. int nEqCol, /* Number of index columns with == constraints */
  1606. int wsFlags, /* Index usages flags */
  1607. ref int pbRev /* Set to 1 if ORDER BY is DESC */
  1608. )
  1609. {
  1610. int i, j; /* Loop counters */
  1611. int sortOrder = 0; /* XOR of index and ORDER BY sort direction */
  1612. int nTerm; /* Number of ORDER BY terms */
  1613. ExprList_item pTerm; /* A term of the ORDER BY clause */
  1614. sqlite3 db = pParse.db;
  1615. Debug.Assert( pOrderBy != null );
  1616. nTerm = pOrderBy.nExpr;
  1617. Debug.Assert( nTerm > 0 );
  1618. /* Argument pIdx must either point to a 'real' named index structure,
  1619. ** or an index structure allocated on the stack by bestBtreeIndex() to
  1620. ** represent the rowid index that is part of every table. */
  1621. Debug.Assert( !String.IsNullOrEmpty( pIdx.zName ) || ( pIdx.nColumn == 1 && pIdx.aiColumn[0] == -1 ) );
  1622. /* Match terms of the ORDER BY clause against columns of
  1623. ** the index.
  1624. **
  1625. ** Note that indices have pIdx.nColumn regular columns plus
  1626. ** one additional column containing the rowid. The rowid column
  1627. ** of the index is also allowed to match against the ORDER BY
  1628. ** clause.
  1629. */
  1630. for ( i = j = 0; j < nTerm && i <= pIdx.nColumn; i++ )
  1631. {
  1632. pTerm = pOrderBy.a[j];
  1633. Expr pExpr; /* The expression of the ORDER BY pTerm */
  1634. CollSeq pColl; /* The collating sequence of pExpr */
  1635. int termSortOrder; /* Sort order for this term */
  1636. int iColumn; /* The i-th column of the index. -1 for rowid */
  1637. int iSortOrder; /* 1 for DESC, 0 for ASC on the i-th index term */
  1638. string zColl; /* Name of the collating sequence for i-th index term */
  1639. pExpr = pTerm.pExpr;
  1640. if ( pExpr.op != TK_COLUMN || pExpr.iTable != _base )
  1641. {
  1642. /* Can not use an index sort on anything that is not a column in the
  1643. ** left-most table of the FROM clause */
  1644. break;
  1645. }
  1646. pColl = sqlite3ExprCollSeq( pParse, pExpr );
  1647. if ( null == pColl )
  1648. {
  1649. pColl = db.pDfltColl;
  1650. }
  1651. if ( !String.IsNullOrEmpty( pIdx.zName ) && i < pIdx.nColumn )
  1652. {
  1653. iColumn = pIdx.aiColumn[i];
  1654. if ( iColumn == pIdx.pTable.iPKey )
  1655. {
  1656. iColumn = -1;
  1657. }
  1658. iSortOrder = pIdx.aSortOrder[i];
  1659. zColl = pIdx.azColl[i];
  1660. }
  1661. else
  1662. {
  1663. iColumn = -1;
  1664. iSortOrder = 0;
  1665. zColl = pColl.zName;
  1666. }
  1667. if ( pExpr.iColumn != iColumn || !pColl.zName.Equals( zColl, StringComparison.OrdinalIgnoreCase ) )
  1668. {
  1669. /* Term j of the ORDER BY clause does not match column i of the index */
  1670. if ( i < nEqCol )
  1671. {
  1672. /* If an index column that is constrained by == fails to match an
  1673. ** ORDER BY term, that is OK. Just ignore that column of the index
  1674. */
  1675. continue;
  1676. }
  1677. else if ( i == pIdx.nColumn )
  1678. {
  1679. /* Index column i is the rowid. All other terms match. */
  1680. break;
  1681. }
  1682. else
  1683. {
  1684. /* If an index column fails to match and is not constrained by ==
  1685. ** then the index cannot satisfy the ORDER BY constraint.
  1686. */
  1687. return false;
  1688. }
  1689. }
  1690. Debug.Assert( pIdx.aSortOrder != null || iColumn == -1 );
  1691. Debug.Assert( pTerm.sortOrder == 0 || pTerm.sortOrder == 1 );
  1692. Debug.Assert( iSortOrder == 0 || iSortOrder == 1 );
  1693. termSortOrder = iSortOrder ^ pTerm.sortOrder;
  1694. if ( i > nEqCol )
  1695. {
  1696. if ( termSortOrder != sortOrder )
  1697. {
  1698. /* Indices can only be used if all ORDER BY terms past the
  1699. ** equality constraints are all either DESC or ASC. */
  1700. return false;
  1701. }
  1702. }
  1703. else
  1704. {
  1705. sortOrder = termSortOrder;
  1706. }
  1707. j++;
  1708. //pTerm++;
  1709. if ( iColumn < 0 && !referencesOtherTables( pOrderBy, pMaskSet, j, _base ) )
  1710. {
  1711. /* If the indexed column is the primary key and everything matches
  1712. ** so far and none of the ORDER BY terms to the right reference other
  1713. ** tables in the join, then we are Debug.Assured that the index can be used
  1714. ** to sort because the primary key is unique and so none of the other
  1715. ** columns will make any difference
  1716. */
  1717. j = nTerm;
  1718. }
  1719. }
  1720. pbRev = sortOrder != 0 ? 1 : 0;
  1721. if ( j >= nTerm )
  1722. {
  1723. /* All terms of the ORDER BY clause are covered by this index so
  1724. ** this index can be used for sorting. */
  1725. return true;
  1726. }
  1727. if ( pIdx.onError != OE_None && i == pIdx.nColumn
  1728. && ( wsFlags & WHERE_COLUMN_NULL ) == 0
  1729. && !referencesOtherTables( pOrderBy, pMaskSet, j, _base ) )
  1730. {
  1731. /* All terms of this index match some prefix of the ORDER BY clause
  1732. ** and the index is UNIQUE and no terms on the tail of the ORDER BY
  1733. ** clause reference other tables in a join. If this is all true then
  1734. ** the order by clause is superfluous. Not that if the matching
  1735. ** condition is IS NULL then the result is not necessarily unique
  1736. ** even on a UNIQUE index, so disallow those cases. */
  1737. return true;
  1738. }
  1739. return false;
  1740. }
  1741. /*
  1742. ** Prepare a crude estimate of the logarithm of the input value.
  1743. ** The results need not be exact. This is only used for estimating
  1744. ** the total cost of performing operations with O(logN) or O(NlogN)
  1745. ** complexity. Because N is just a guess, it is no great tragedy if
  1746. ** logN is a little off.
  1747. */
  1748. static double estLog( double N )
  1749. {
  1750. double logN = 1;
  1751. double x = 10;
  1752. while ( N > x )
  1753. {
  1754. logN += 1;
  1755. x *= 10;
  1756. }
  1757. return logN;
  1758. }
  1759. /*
  1760. ** Two routines for printing the content of an sqlite3_index_info
  1761. ** structure. Used for testing and debugging only. If neither
  1762. ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
  1763. ** are no-ops.
  1764. */
  1765. #if !(SQLITE_OMIT_VIRTUALTABLE) && (SQLITE_DEBUG)
  1766. static void TRACE_IDX_INPUTS( sqlite3_index_info p )
  1767. {
  1768. int i;
  1769. if ( !sqlite3WhereTrace ) return;
  1770. for ( i = 0 ; i < p.nConstraint ; i++ )
  1771. {
  1772. sqlite3DebugPrintf( " constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
  1773. i,
  1774. p.aConstraint[i].iColumn,
  1775. p.aConstraint[i].iTermOffset,
  1776. p.aConstraint[i].op,
  1777. p.aConstraint[i].usable );
  1778. }
  1779. for ( i = 0 ; i < p.nOrderBy ; i++ )
  1780. {
  1781. sqlite3DebugPrintf( " orderby[%d]: col=%d desc=%d\n",
  1782. i,
  1783. p.aOrderBy[i].iColumn,
  1784. p.aOrderBy[i].desc );
  1785. }
  1786. }
  1787. static void TRACE_IDX_OUTPUTS( sqlite3_index_info p )
  1788. {
  1789. int i;
  1790. if ( !sqlite3WhereTrace ) return;
  1791. for ( i = 0 ; i < p.nConstraint ; i++ )
  1792. {
  1793. sqlite3DebugPrintf( " usage[%d]: argvIdx=%d omit=%d\n",
  1794. i,
  1795. p.aConstraintUsage[i].argvIndex,
  1796. p.aConstraintUsage[i].omit );
  1797. }
  1798. sqlite3DebugPrintf( " idxNum=%d\n", p.idxNum );
  1799. sqlite3DebugPrintf( " idxStr=%s\n", p.idxStr );
  1800. sqlite3DebugPrintf( " orderByConsumed=%d\n", p.orderByConsumed );
  1801. sqlite3DebugPrintf( " estimatedCost=%g\n", p.estimatedCost );
  1802. }
  1803. #else
  1804. //#define TRACE_IDX_INPUTS(A)
  1805. static void TRACE_IDX_INPUTS( sqlite3_index_info p ) { }
  1806. //#define TRACE_IDX_OUTPUTS(A)
  1807. static void TRACE_IDX_OUTPUTS( sqlite3_index_info p ) { }
  1808. #endif
  1809. /*
  1810. ** Required because bestIndex() is called by bestOrClauseIndex()
  1811. */
  1812. //static void bestIndex(
  1813. //Parse*, WhereClause*, struct SrcList_item*,
  1814. //Bitmask, ExprList*, WhereCost);
  1815. /*
  1816. ** This routine attempts to find an scanning strategy that can be used
  1817. ** to optimize an 'OR' expression that is part of a WHERE clause.
  1818. **
  1819. ** The table associated with FROM clause term pSrc may be either a
  1820. ** regular B-Tree table or a virtual table.
  1821. */
  1822. static void bestOrClauseIndex(
  1823. Parse pParse, /* The parsing context */
  1824. WhereClause pWC, /* The WHERE clause */
  1825. SrcList_item pSrc, /* The FROM clause term to search */
  1826. Bitmask notReady, /* Mask of cursors not available for indexing */
  1827. Bitmask notValid, /* Cursors not available for any purpose */
  1828. ExprList pOrderBy, /* The ORDER BY clause */
  1829. WhereCost pCost /* Lowest cost query plan */
  1830. )
  1831. {
  1832. #if !SQLITE_OMIT_OR_OPTIMIZATION
  1833. int iCur = pSrc.iCursor; /* The cursor of the table to be accessed */
  1834. Bitmask maskSrc = getMask( pWC.pMaskSet, iCur ); /* Bitmask for pSrc */
  1835. WhereTerm pWCEnd = pWC.a[pWC.nTerm]; /* End of pWC.a[] */
  1836. WhereTerm pTerm; /* A single term of the WHERE clause */
  1837. /* No OR-clause optimization allowed if the INDEXED BY or NOT INDEXED clauses
  1838. ** are used */
  1839. if ( pSrc.notIndexed != 0 || pSrc.pIndex != null )
  1840. {
  1841. return;
  1842. }
  1843. /* Search the WHERE clause terms for a usable WO_OR term. */
  1844. for ( int _pt = 0; _pt < pWC.nTerm; _pt++ )//<pWCEnd; pTerm++)
  1845. {
  1846. pTerm = pWC.a[_pt];
  1847. if ( pTerm.eOperator == WO_OR
  1848. && ( ( pTerm.prereqAll & ~maskSrc ) & notReady ) == 0
  1849. && ( pTerm.u.pOrInfo.indexable & maskSrc ) != 0
  1850. )
  1851. {
  1852. WhereClause pOrWC = pTerm.u.pOrInfo.wc;
  1853. WhereTerm pOrWCEnd = pOrWC.a[pOrWC.nTerm];
  1854. WhereTerm pOrTerm;
  1855. int flags = WHERE_MULTI_OR;
  1856. double rTotal = 0;
  1857. double nRow = 0;
  1858. Bitmask used = 0;
  1859. for ( int _pOrWC = 0; _pOrWC < pOrWC.nTerm; _pOrWC++ )//pOrTerm = pOrWC.a ; pOrTerm < pOrWCEnd ; pOrTerm++ )
  1860. {
  1861. pOrTerm = pOrWC.a[_pOrWC];
  1862. WhereCost sTermCost = null;
  1863. #if (SQLITE_TEST) && (SQLITE_DEBUG)
  1864. WHERETRACE( "... Multi-index OR testing for term %d of %d....\n",
  1865. _pOrWC, pOrWC.nTerm - _pOrWC//( pOrTerm - pOrWC.a ), ( pTerm - pWC.a )
  1866. );
  1867. #endif
  1868. if ( pOrTerm.eOperator == WO_AND )
  1869. {
  1870. WhereClause pAndWC = pOrTerm.u.pAndInfo.wc;
  1871. bestIndex( pParse, pAndWC, pSrc, notReady, notValid, null, ref sTermCost );
  1872. }
  1873. else if ( pOrTerm.leftCursor == iCur )
  1874. {
  1875. WhereClause tempWC = new WhereClause();
  1876. tempWC.pParse = pWC.pParse;
  1877. tempWC.pMaskSet = pWC.pMaskSet;
  1878. tempWC.op = TK_AND;
  1879. tempWC.a = new WhereTerm[2];
  1880. tempWC.a[0] = pOrTerm;
  1881. tempWC.nTerm = 1;
  1882. bestIndex( pParse, tempWC, pSrc, notReady, notValid, null, ref sTermCost );
  1883. }
  1884. else
  1885. {
  1886. continue;
  1887. }
  1888. rTotal += sTermCost.rCost;
  1889. nRow += sTermCost.plan.nRow;
  1890. used |= sTermCost.used;
  1891. if ( rTotal >= pCost.rCost )
  1892. break;
  1893. }
  1894. /* If there is an ORDER BY clause, increase the scan cost to account
  1895. ** for the cost of the sort. */
  1896. if ( pOrderBy != null )
  1897. {
  1898. #if (SQLITE_TEST) && (SQLITE_DEBUG)
  1899. WHERETRACE( "... sorting increases OR cost %.9g to %.9g\n",
  1900. rTotal, rTotal + nRow * estLog( nRow ) );
  1901. #endif
  1902. rTotal += nRow * estLog( nRow );
  1903. }
  1904. /* If the cost of scanning using this OR term for optimization is
  1905. ** less than the current cost stored in pCost, replace the contents
  1906. ** of pCost. */
  1907. #if (SQLITE_TEST) && (SQLITE_DEBUG)
  1908. WHERETRACE( "... multi-index OR cost=%.9g nrow=%.9g\n", rTotal, nRow );
  1909. #endif
  1910. if ( rTotal < pCost.rCost )
  1911. {
  1912. pCost.rCost = rTotal;
  1913. pCost.used = used;
  1914. pCost.plan.nRow = nRow;
  1915. pCost.plan.wsFlags = (uint)flags;
  1916. pCost.plan.u.pTerm = pTerm;
  1917. }
  1918. }
  1919. }
  1920. #endif //* SQLITE_OMIT_OR_OPTIMIZATION */
  1921. }
  1922. #if !SQLITE_OMIT_AUTOMATIC_INDEX
  1923. /*
  1924. ** Return TRUE if the WHERE clause term pTerm is of a form where it
  1925. ** could be used with an index to access pSrc, assuming an appropriate
  1926. ** index existed.
  1927. */
  1928. static int termCanDriveIndex(
  1929. WhereTerm pTerm, /* WHERE clause term to check */
  1930. SrcList_item pSrc, /* Table we are trying to access */
  1931. Bitmask notReady /* Tables in outer loops of the join */
  1932. )
  1933. {
  1934. char aff;
  1935. if ( pTerm.leftCursor != pSrc.iCursor )
  1936. return 0;
  1937. if ( pTerm.eOperator != WO_EQ )
  1938. return 0;
  1939. if ( ( pTerm.prereqRight & notReady ) != 0 )
  1940. return 0;
  1941. aff = pSrc.pTab.aCol[pTerm.u.leftColumn].affinity;
  1942. if ( !sqlite3IndexAffinityOk( pTerm.pExpr, aff ) )
  1943. return 0;
  1944. return 1;
  1945. }
  1946. #endif
  1947. #if !SQLITE_OMIT_AUTOMATIC_INDEX
  1948. /*
  1949. ** If the query plan for pSrc specified in pCost is a full table scan
  1950. ** and indexing is allows (if there is no NOT INDEXED clause) and it
  1951. ** possible to construct a transient index that would perform better
  1952. ** than a full table scan even when the cost of constructing the index
  1953. ** is taken into account, then alter the query plan to use the
  1954. ** transient index.
  1955. */
  1956. static void bestAutomaticIndex(
  1957. Parse pParse, /* The parsing context */
  1958. WhereClause pWC, /* The WHERE clause */
  1959. SrcList_item pSrc, /* The FROM clause term to search */
  1960. Bitmask notReady, /* Mask of cursors that are not available */
  1961. WhereCost pCost /* Lowest cost query plan */
  1962. )
  1963. {
  1964. double nTableRow; /* Rows in the input table */
  1965. double logN; /* log(nTableRow) */
  1966. double costTempIdx; /* per-query cost of the transient index */
  1967. WhereTerm pTerm; /* A single term of the WHERE clause */
  1968. WhereTerm pWCEnd; /* End of pWC.a[] */
  1969. Table pTable; /* Table that might be indexed */
  1970. if ( pParse.nQueryLoop <= (double)1 )
  1971. {
  1972. /* There is no point in building an automatic index for a single scan */
  1973. return;
  1974. }
  1975. if ( ( pParse.db.flags & SQLITE_AutoIndex ) == 0 )
  1976. {
  1977. /* Automatic indices are disabled at run-time */
  1978. return;
  1979. }
  1980. if ( ( pCost.plan.wsFlags & WHERE_NOT_FULLSCAN ) != 0 )
  1981. {
  1982. /* We already have some kind of index in use for this query. */
  1983. return;
  1984. }
  1985. if ( pSrc.notIndexed != 0 )
  1986. {
  1987. /* The NOT INDEXED clause appears in the SQL. */
  1988. return;
  1989. }
  1990. Debug.Assert( pParse.nQueryLoop >= (double)1 );
  1991. pTable = pSrc.pTab;
  1992. nTableRow = pTable.nRowEst;
  1993. logN = estLog( nTableRow );
  1994. costTempIdx = 2 * logN * ( nTableRow / pParse.nQueryLoop + 1 );
  1995. if ( costTempIdx >= pCost.rCost )
  1996. {
  1997. /* The cost of creating the transient table would be greater than
  1998. ** doing the full table scan */
  1999. return;
  2000. }
  2001. /* Search for any equality comparison term */
  2002. //pWCEnd = pWC.a[pWC.nTerm];
  2003. for ( int ipTerm = 0; ipTerm < pWC.nTerm; ipTerm++ )//; pTerm<pWCEnd; pTerm++)
  2004. {
  2005. pTerm = pWC.a[ipTerm];
  2006. if ( termCanDriveIndex( pTerm, pSrc, notReady ) != 0 )
  2007. {
  2008. #if (SQLITE_TEST) && (SQLITE_DEBUG)
  2009. WHERETRACE( "auto-index reduces cost from %.2f to %.2f\n",
  2010. pCost.rCost, costTempIdx );
  2011. #endif
  2012. pCost.rCost = costTempIdx;
  2013. pCost.plan.nRow = logN + 1;
  2014. pCost.plan.wsFlags = WHERE_TEMP_INDEX;
  2015. pCost.used = pTerm.prereqRight;
  2016. break;
  2017. }
  2018. }
  2019. }
  2020. #else
  2021. //# define bestAutomaticIndex(A,B,C,D,E) /* no-op */
  2022. static void bestAutomaticIndex(
  2023. Parse pParse, /* The parsing context */
  2024. WhereClause pWC, /* The WHERE clause */
  2025. SrcList_item pSrc, /* The FROM clause term to search */
  2026. Bitmask notReady, /* Mask of cursors that are not available */
  2027. WhereCost pCost /* Lowest cost query plan */
  2028. ){}
  2029. #endif //* SQLITE_OMIT_AUTOMATIC_INDEX */
  2030. #if !SQLITE_OMIT_AUTOMATIC_INDEX
  2031. /*
  2032. ** Generate code to construct the Index object for an automatic index
  2033. ** and to set up the WhereLevel object pLevel so that the code generator
  2034. ** makes use of the automatic index.
  2035. */
  2036. static void constructAutomaticIndex(
  2037. Parse pParse, /* The parsing context */
  2038. WhereClause pWC, /* The WHERE clause */
  2039. SrcList_item pSrc, /* The FROM clause term to get the next index */
  2040. Bitmask notReady, /* Mask of cursors that are not available */
  2041. WhereLevel pLevel /* Write new index here */
  2042. )
  2043. {
  2044. int nColumn; /* Number of columns in the constructed index */
  2045. WhereTerm pTerm; /* A single term of the WHERE clause */
  2046. WhereTerm pWCEnd; /* End of pWC.a[] */
  2047. int nByte; /* Byte of memory needed for pIdx */
  2048. Index pIdx; /* Object describing the transient index */
  2049. Vdbe v; /* Prepared statement under construction */
  2050. int regIsInit; /* Register set by initialization */
  2051. int addrInit; /* Address of the initialization bypass jump */
  2052. Table pTable; /* The table being indexed */
  2053. KeyInfo pKeyinfo; /* Key information for the index */
  2054. int addrTop; /* Top of the index fill loop */
  2055. int regRecord; /* Register holding an index record */
  2056. int n; /* Column counter */
  2057. int i; /* Loop counter */
  2058. int mxBitCol; /* Maximum column in pSrc.colUsed */
  2059. CollSeq pColl; /* Collating sequence to on a column */
  2060. Bitmask idxCols; /* Bitmap of columns used for indexing */
  2061. Bitmask extraCols; /* Bitmap of additional columns */
  2062. /* Generate code to skip over the creation and initialization of the
  2063. ** transient index on 2nd and subsequent iterations of the loop. */
  2064. v = pParse.pVdbe;
  2065. Debug.Assert( v != null );
  2066. regIsInit = ++pParse.nMem;
  2067. addrInit = sqlite3VdbeAddOp1( v, OP_If, regIsInit );
  2068. sqlite3VdbeAddOp2( v, OP_Integer, 1, regIsInit );
  2069. /* Count the number of columns that will be added to the index
  2070. ** and used to match WHERE clause constraints */
  2071. nColumn = 0;
  2072. pTable = pSrc.pTab;
  2073. //pWCEnd = pWC.a[pWC.nTerm];
  2074. idxCols = 0;
  2075. for ( int ipTerm = 0; ipTerm < pWC.nTerm; ipTerm++ )//; pTerm<pWCEnd; pTerm++)
  2076. {
  2077. pTerm = pWC.a[ipTerm];
  2078. if ( termCanDriveIndex( pTerm, pSrc, notReady ) != 0 )
  2079. {
  2080. int iCol = pTerm.u.leftColumn;
  2081. Bitmask cMask = iCol >= BMS ? ( (Bitmask)1 ) << ( BMS - 1 ) : ( (Bitmask)1 ) << iCol;
  2082. testcase( iCol == BMS );
  2083. testcase( iCol == BMS - 1 );
  2084. if ( ( idxCols & cMask ) == 0 )
  2085. {
  2086. nColumn++;
  2087. idxCols |= cMask;
  2088. }
  2089. }
  2090. }
  2091. Debug.Assert( nColumn > 0 );
  2092. pLevel.plan.nEq = (u32)nColumn;
  2093. /* Count the number of additional columns needed to create a
  2094. ** covering index. A "covering index" is an index that contains all
  2095. ** columns that are needed by the query. With a covering index, the
  2096. ** original table never needs to be accessed. Automatic indices must
  2097. ** be a covering index because the index will not be updated if the
  2098. ** original table changes and the index and table cannot both be used
  2099. ** if they go out of sync.
  2100. */
  2101. extraCols = pSrc.colUsed & ( ~idxCols | ( ( (Bitmask)1 ) << ( BMS - 1 ) ) );
  2102. mxBitCol = ( pTable.nCol >= BMS - 1 ) ? BMS - 1 : pTable.nCol;
  2103. testcase( pTable.nCol == BMS - 1 );
  2104. testcase( pTable.nCol == BMS - 2 );
  2105. for ( i = 0; i < mxBitCol; i++ )
  2106. {
  2107. if ( ( extraCols & ( ( (Bitmask)1 ) << i ) ) != 0 )
  2108. nColumn++;
  2109. }
  2110. if ( ( pSrc.colUsed & ( ( (Bitmask)1 ) << ( BMS - 1 ) ) ) != 0 )
  2111. {
  2112. nColumn += pTable.nCol - BMS + 1;
  2113. }
  2114. pLevel.plan.wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WO_EQ;
  2115. /* Construct the Index object to describe this index */
  2116. //nByte = sizeof(Index);
  2117. //nByte += nColumn*sizeof(int); /* Index.aiColumn */
  2118. //nByte += nColumn*sizeof(char); /* Index.azColl */
  2119. //nByte += nColumn; /* Index.aSortOrder */
  2120. //pIdx = sqlite3DbMallocZero(pParse.db, nByte);
  2121. //if( pIdx==null) return;
  2122. pIdx = new Index();
  2123. pLevel.plan.u.pIdx = pIdx;
  2124. pIdx.azColl = new string[nColumn + 1];// pIdx[1];
  2125. pIdx.aiColumn = new int[nColumn + 1];// pIdx.azColl[nColumn];
  2126. pIdx.aSortOrder = new u8[nColumn + 1];// pIdx.aiColumn[nColumn];
  2127. pIdx.zName = "auto-index";
  2128. pIdx.nColumn = nColumn;
  2129. pIdx.pTable = pTable;
  2130. n = 0;
  2131. idxCols = 0;
  2132. //for(pTerm=pWC.a; pTerm<pWCEnd; pTerm++){
  2133. for ( int ipTerm = 0; ipTerm < pWC.nTerm; ipTerm++ )
  2134. {
  2135. pTerm = pWC.a[ipTerm];
  2136. if ( termCanDriveIndex( pTerm, pSrc, notReady ) != 0 )
  2137. {
  2138. int iCol = pTerm.u.leftColumn;
  2139. Bitmask cMask = iCol >= BMS ? ( (Bitmask)1 ) << ( BMS - 1 ) : ( (Bitmask)1 ) << iCol;
  2140. if ( ( idxCols & cMask ) == 0 )
  2141. {
  2142. Expr pX = pTerm.pExpr;
  2143. idxCols |= cMask;
  2144. pIdx.aiColumn[n] = pTerm.u.leftColumn;
  2145. pColl = sqlite3BinaryCompareCollSeq( pParse, pX.pLeft, pX.pRight );
  2146. pIdx.azColl[n] = ALWAYS( pColl != null ) ? pColl.zName : "BINARY";
  2147. n++;
  2148. }
  2149. }
  2150. }
  2151. Debug.Assert( (u32)n == pLevel.plan.nEq );
  2152. /* Add additional columns needed to make the automatic index into
  2153. ** a covering index */
  2154. for ( i = 0; i < mxBitCol; i++ )
  2155. {
  2156. if ( ( extraCols & ( ( (Bitmask)1 ) << i ) ) != 0 )
  2157. {
  2158. pIdx.aiColumn[n] = i;
  2159. pIdx.azColl[n] = "BINARY";
  2160. n++;
  2161. }
  2162. }
  2163. if ( ( pSrc.colUsed & ( ( (Bitmask)1 ) << ( BMS - 1 ) ) ) != 0 )
  2164. {
  2165. for ( i = BMS - 1; i < pTable.nCol; i++ )
  2166. {
  2167. pIdx.aiColumn[n] = i;
  2168. pIdx.azColl[n] = "BINARY";
  2169. n++;
  2170. }
  2171. }
  2172. Debug.Assert( n == nColumn );
  2173. /* Create the automatic index */
  2174. pKeyinfo = sqlite3IndexKeyinfo( pParse, pIdx );
  2175. Debug.Assert( pLevel.iIdxCur >= 0 );
  2176. sqlite3VdbeAddOp4( v, OP_OpenAutoindex, pLevel.iIdxCur, nColumn + 1, 0,
  2177. pKeyinfo, P4_KEYINFO_HANDOFF );
  2178. VdbeComment( v, "for %s", pTable.zName );
  2179. /* Fill the automatic index with content */
  2180. addrTop = sqlite3VdbeAddOp1( v, OP_Rewind, pLevel.iTabCur );
  2181. regRecord = sqlite3GetTempReg( pParse );
  2182. sqlite3GenerateIndexKey( pParse, pIdx, pLevel.iTabCur, regRecord, true );
  2183. sqlite3VdbeAddOp2( v, OP_IdxInsert, pLevel.iIdxCur, regRecord );
  2184. sqlite3VdbeChangeP5( v, OPFLAG_USESEEKRESULT );
  2185. sqlite3VdbeAddOp2( v, OP_Next, pLevel.iTabCur, addrTop + 1 );
  2186. sqlite3VdbeChangeP5( v, SQLITE_STMTSTATUS_AUTOINDEX );
  2187. sqlite3VdbeJumpHere( v, addrTop );
  2188. sqlite3ReleaseTempReg( pParse, regRecord );
  2189. /* Jump here when skipping the initialization */
  2190. sqlite3VdbeJumpHere( v, addrInit );
  2191. }
  2192. #endif //* SQLITE_OMIT_AUTOMATIC_INDEX */
  2193. #if !SQLITE_OMIT_VIRTUALTABLE
  2194. /*
  2195. ** Allocate and populate an sqlite3_index_info structure. It is the
  2196. ** responsibility of the caller to eventually release the structure
  2197. ** by passing the pointer returned by this function to //sqlite3_free().
  2198. */
  2199. static sqlite3_index_info allocateIndexInfo(
  2200. Parse pParse,
  2201. WhereClause pWC,
  2202. SrcList_item pSrc,
  2203. ExprList pOrderBy
  2204. )
  2205. {
  2206. int i, j;
  2207. int nTerm;
  2208. sqlite3_index_constraint[] pIdxCons;
  2209. sqlite3_index_orderby[] pIdxOrderBy;
  2210. sqlite3_index_constraint_usage[] pUsage;
  2211. WhereTerm pTerm;
  2212. int nOrderBy;
  2213. sqlite3_index_info pIdxInfo;
  2214. #if (SQLITE_TEST) && (SQLITE_DEBUG)
  2215. WHERETRACE( "Recomputing index info for %s...\n", pSrc.pTab.zName );
  2216. #endif
  2217. /* Count the number of possible WHERE clause constraints referring
  2218. ** to this virtual table */
  2219. for ( i = nTerm = 0; i < pWC.nTerm; i++)//, pTerm++ )
  2220. {
  2221. pTerm = pWC.a[i];
  2222. if ( pTerm.leftCursor != pSrc.iCursor )
  2223. continue;
  2224. Debug.Assert( ( pTerm.eOperator & ( pTerm.eOperator - 1 ) ) == 0 );
  2225. testcase( pTerm.eOperator == WO_IN );
  2226. testcase( pTerm.eOperator == WO_ISNULL );
  2227. if ( ( pTerm.eOperator & ( WO_IN | WO_ISNULL ) ) != 0 )
  2228. continue;
  2229. nTerm++;
  2230. }
  2231. /* If the ORDER BY clause contains only columns in the current
  2232. ** virtual table then allocate space for the aOrderBy part of
  2233. ** the sqlite3_index_info structure.
  2234. */
  2235. nOrderBy = 0;
  2236. if ( pOrderBy != null )
  2237. {
  2238. for ( i = 0; i < pOrderBy.nExpr; i++ )
  2239. {
  2240. Expr pExpr = pOrderBy.a[i].pExpr;
  2241. if ( pExpr.op != TK_COLUMN || pExpr.iTable != pSrc.iCursor )
  2242. break;
  2243. }
  2244. if ( i == pOrderBy.nExpr )
  2245. {
  2246. nOrderBy = pOrderBy.nExpr;
  2247. }
  2248. }
  2249. /* Allocate the sqlite3_index_info structure
  2250. */
  2251. pIdxInfo = new sqlite3_index_info();
  2252. //sqlite3DbMallocZero(pParse.db, sizeof(*pIdxInfo)
  2253. //+ (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
  2254. //+ sizeof(*pIdxOrderBy)*nOrderBy );
  2255. //if ( pIdxInfo == null )
  2256. //{
  2257. // sqlite3ErrorMsg( pParse, "out of memory" );
  2258. // /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  2259. // return null;
  2260. //}
  2261. /* Initialize the structure. The sqlite3_index_info structure contains
  2262. ** many fields that are declared "const" to prevent xBestIndex from
  2263. ** changing them. We have to do some funky casting in order to
  2264. ** initialize those fields.
  2265. */
  2266. pIdxCons = new sqlite3_index_constraint[nTerm];//(sqlite3_index_constraint)pIdxInfo[1];
  2267. pIdxOrderBy = new sqlite3_index_orderby[nOrderBy];//(sqlite3_index_orderby)pIdxCons[nTerm];
  2268. pUsage = new sqlite3_index_constraint_usage[nTerm];//(sqlite3_index_constraint_usage)pIdxOrderBy[nOrderBy];
  2269. pIdxInfo.nConstraint = nTerm;
  2270. pIdxInfo.nOrderBy = nOrderBy;
  2271. pIdxInfo.aConstraint = pIdxCons;
  2272. pIdxInfo.aOrderBy = pIdxOrderBy;
  2273. pIdxInfo.aConstraintUsage =
  2274. pUsage;
  2275. for ( i = j = 0; i < pWC.nTerm; i++)//, pTerm++ )
  2276. {
  2277. pTerm = pWC.a[i];
  2278. if ( pTerm.leftCursor != pSrc.iCursor )
  2279. continue;
  2280. Debug.Assert( ( pTerm.eOperator & ( pTerm.eOperator - 1 ) ) == 0 );
  2281. testcase( pTerm.eOperator == WO_IN );
  2282. testcase( pTerm.eOperator == WO_ISNULL );
  2283. if ( ( pTerm.eOperator & ( WO_IN | WO_ISNULL ) ) != 0 )
  2284. continue;
  2285. if ( pIdxCons[j] == null )
  2286. pIdxCons[j] = new sqlite3_index_constraint();
  2287. pIdxCons[j].iColumn = pTerm.u.leftColumn;
  2288. pIdxCons[j].iTermOffset = i;
  2289. pIdxCons[j].op = (u8)pTerm.eOperator;
  2290. /* The direct Debug.Assignment in the previous line is possible only because
  2291. ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The
  2292. ** following Debug.Asserts verify this fact. */
  2293. Debug.Assert( WO_EQ == SQLITE_INDEX_CONSTRAINT_EQ );
  2294. Debug.Assert( WO_LT == SQLITE_INDEX_CONSTRAINT_LT );
  2295. Debug.Assert( WO_LE == SQLITE_INDEX_CONSTRAINT_LE );
  2296. Debug.Assert( WO_GT == SQLITE_INDEX_CONSTRAINT_GT );
  2297. Debug.Assert( WO_GE == SQLITE_INDEX_CONSTRAINT_GE );
  2298. Debug.Assert( WO_MATCH == SQLITE_INDEX_CONSTRAINT_MATCH );
  2299. Debug.Assert( ( pTerm.eOperator & ( WO_EQ | WO_LT | WO_LE | WO_GT | WO_GE | WO_MATCH ) ) != 0 );
  2300. j++;
  2301. }
  2302. for ( i = 0; i < nOrderBy; i++ )
  2303. {
  2304. Expr pExpr = pOrderBy.a[i].pExpr;
  2305. if ( pIdxOrderBy[i] == null )
  2306. pIdxOrderBy[i] = new sqlite3_index_orderby();
  2307. pIdxOrderBy[i].iColumn = pExpr.iColumn;
  2308. pIdxOrderBy[i].desc = pOrderBy.a[i].sortOrder != 0;
  2309. }
  2310. return pIdxInfo;
  2311. }
  2312. /*
  2313. ** The table object reference passed as the second argument to this function
  2314. ** must represent a virtual table. This function invokes the xBestIndex()
  2315. ** method of the virtual table with the sqlite3_index_info pointer passed
  2316. ** as the argument.
  2317. **
  2318. ** If an error occurs, pParse is populated with an error message and a
  2319. ** non-zero value is returned. Otherwise, 0 is returned and the output
  2320. ** part of the sqlite3_index_info structure is left populated.
  2321. **
  2322. ** Whether or not an error is returned, it is the responsibility of the
  2323. ** caller to eventually free p.idxStr if p.needToFreeIdxStr indicates
  2324. ** that this is required.
  2325. */
  2326. static int vtabBestIndex( Parse pParse, Table pTab, sqlite3_index_info p )
  2327. {
  2328. sqlite3_vtab pVtab = sqlite3GetVTable( pParse.db, pTab ).pVtab;
  2329. int i;
  2330. int rc;
  2331. #if (SQLITE_TEST) && (SQLITE_DEBUG)
  2332. WHERETRACE( "xBestIndex for %s\n", pTab.zName );
  2333. #endif
  2334. TRACE_IDX_INPUTS( p );
  2335. rc = pVtab.pModule.xBestIndex( pVtab, ref p );
  2336. TRACE_IDX_OUTPUTS( p );
  2337. if ( rc != SQLITE_OK )
  2338. {
  2339. //if ( rc == SQLITE_NOMEM )
  2340. //{
  2341. // pParse.db.mallocFailed = 1;
  2342. //}
  2343. // else
  2344. if ( String.IsNullOrEmpty( pVtab.zErrMsg ) )
  2345. {
  2346. sqlite3ErrorMsg( pParse, "%s", sqlite3ErrStr( rc ) );
  2347. }
  2348. else
  2349. {
  2350. sqlite3ErrorMsg( pParse, "%s", pVtab.zErrMsg );
  2351. }
  2352. }
  2353. //sqlite3_free( pVtab.zErrMsg );
  2354. pVtab.zErrMsg = null;
  2355. for ( i = 0; i < p.nConstraint; i++ )
  2356. {
  2357. if ( !p.aConstraint[i].usable && p.aConstraintUsage[i].argvIndex > 0 )
  2358. {
  2359. sqlite3ErrorMsg( pParse,
  2360. "table %s: xBestIndex returned an invalid plan", pTab.zName );
  2361. }
  2362. }
  2363. return pParse.nErr;
  2364. }
  2365. /*
  2366. ** Compute the best index for a virtual table.
  2367. **
  2368. ** The best index is computed by the xBestIndex method of the virtual
  2369. ** table module. This routine is really just a wrapper that sets up
  2370. ** the sqlite3_index_info structure that is used to communicate with
  2371. ** xBestIndex.
  2372. **
  2373. ** In a join, this routine might be called multiple times for the
  2374. ** same virtual table. The sqlite3_index_info structure is created
  2375. ** and initialized on the first invocation and reused on all subsequent
  2376. ** invocations. The sqlite3_index_info structure is also used when
  2377. ** code is generated to access the virtual table. The whereInfoDelete()
  2378. ** routine takes care of freeing the sqlite3_index_info structure after
  2379. ** everybody has finished with it.
  2380. */
  2381. static void bestVirtualIndex(
  2382. Parse pParse, /* The parsing context */
  2383. WhereClause pWC, /* The WHERE clause */
  2384. SrcList_item pSrc, /* The FROM clause term to search */
  2385. Bitmask notReady, /* Mask of cursors not available for index */
  2386. Bitmask notValid, /* Cursors not valid for any purpose */
  2387. ExprList pOrderBy, /* The order by clause */
  2388. ref WhereCost pCost, /* Lowest cost query plan */
  2389. ref sqlite3_index_info ppIdxInfo /* Index information passed to xBestIndex */
  2390. )
  2391. {
  2392. Table pTab = pSrc.pTab;
  2393. sqlite3_index_info pIdxInfo;
  2394. sqlite3_index_constraint pIdxCons;
  2395. sqlite3_index_constraint_usage[] pUsage = null;
  2396. WhereTerm pTerm;
  2397. int i, j;
  2398. int nOrderBy;
  2399. double rCost;
  2400. /* Make sure wsFlags is initialized to some sane value. Otherwise, if the
  2401. ** malloc in allocateIndexInfo() fails and this function returns leaving
  2402. ** wsFlags in an uninitialized state, the caller may behave unpredictably.
  2403. */
  2404. pCost = new WhereCost();//memset(pCost, 0, sizeof(*pCost));
  2405. pCost.plan.wsFlags = WHERE_VIRTUALTABLE;
  2406. /* If the sqlite3_index_info structure has not been previously
  2407. ** allocated and initialized, then allocate and initialize it now.
  2408. */
  2409. pIdxInfo = ppIdxInfo;
  2410. if ( pIdxInfo == null )
  2411. {
  2412. ppIdxInfo = pIdxInfo = allocateIndexInfo( pParse, pWC, pSrc, pOrderBy );
  2413. }
  2414. if ( pIdxInfo == null )
  2415. {
  2416. return;
  2417. }
  2418. /* At this point, the sqlite3_index_info structure that pIdxInfo points
  2419. ** to will have been initialized, either during the current invocation or
  2420. ** during some prior invocation. Now we just have to customize the
  2421. ** details of pIdxInfo for the current invocation and pDebug.Ass it to
  2422. ** xBestIndex.
  2423. */
  2424. /* The module name must be defined. Also, by this point there must
  2425. ** be a pointer to an sqlite3_vtab structure. Otherwise
  2426. ** sqlite3ViewGetColumnNames() would have picked up the error.
  2427. */
  2428. Debug.Assert( pTab.azModuleArg != null && pTab.azModuleArg[0] != null );
  2429. Debug.Assert( sqlite3GetVTable( pParse.db, pTab ) != null );
  2430. /* Set the aConstraint[].usable fields and initialize all
  2431. ** output variables to zero.
  2432. **
  2433. ** aConstraint[].usable is true for constraints where the right-hand
  2434. ** side contains only references to tables to the left of the current
  2435. ** table. In other words, if the constraint is of the form:
  2436. **
  2437. ** column = expr
  2438. **
  2439. ** and we are evaluating a join, then the constraint on column is
  2440. ** only valid if all tables referenced in expr occur to the left
  2441. ** of the table containing column.
  2442. **
  2443. ** The aConstraints[] array contains entries for all constraints
  2444. ** on the current table. That way we only have to compute it once
  2445. ** even though we might try to pick the best index multiple times.
  2446. ** For each attempt at picking an index, the order of tables in the
  2447. ** join might be different so we have to recompute the usable flag
  2448. ** each time.
  2449. */
  2450. //pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
  2451. //pUsage = pIdxInfo->aConstraintUsage;
  2452. for ( i = 0; i < pIdxInfo.nConstraint; i++)
  2453. {
  2454. pIdxCons = pIdxInfo.aConstraint[i];
  2455. pUsage = pIdxInfo.aConstraintUsage;
  2456. j = pIdxCons.iTermOffset;
  2457. pTerm = pWC.a[j];
  2458. pIdxCons.usable = ( pTerm.prereqRight & notReady ) == 0;
  2459. pUsage[i] = new sqlite3_index_constraint_usage();
  2460. }
  2461. // memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo.nConstraint);
  2462. if ( pIdxInfo.needToFreeIdxStr!=0 )
  2463. {
  2464. //sqlite3_free(ref pIdxInfo.idxStr);
  2465. }
  2466. pIdxInfo.idxStr = null;
  2467. pIdxInfo.idxNum = 0;
  2468. pIdxInfo.needToFreeIdxStr = 0;
  2469. pIdxInfo.orderByConsumed = false;
  2470. /* ((double)2) In case of SQLITE_OMIT_FLOATING_POINT... */
  2471. pIdxInfo.estimatedCost = SQLITE_BIG_DBL / ( (double)2 );
  2472. nOrderBy = pIdxInfo.nOrderBy;
  2473. if ( null == pOrderBy )
  2474. {
  2475. pIdxInfo.nOrderBy = 0;
  2476. }
  2477. if ( vtabBestIndex( pParse, pTab, pIdxInfo ) != 0 )
  2478. {
  2479. return;
  2480. }
  2481. //pIdxCons = (sqlite3_index_constraint)pIdxInfo.aConstraint;
  2482. for ( i = 0; i < pIdxInfo.nConstraint; i++ )
  2483. {
  2484. if ( pUsage[i].argvIndex > 0 )
  2485. {
  2486. //pCost.used |= pWC.a[pIdxCons[i].iTermOffset].prereqRight;
  2487. pCost.used |= pWC.a[pIdxInfo.aConstraint[i].iTermOffset].prereqRight;
  2488. }
  2489. }
  2490. /* If there is an ORDER BY clause, and the selected virtual table index
  2491. ** does not satisfy it, increase the cost of the scan accordingly. This
  2492. ** matches the processing for non-virtual tables in bestBtreeIndex().
  2493. */
  2494. rCost = pIdxInfo.estimatedCost;
  2495. if ( pOrderBy != null && !pIdxInfo.orderByConsumed )
  2496. {
  2497. rCost += estLog( rCost ) * rCost;
  2498. }
  2499. /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
  2500. ** inital value of lowestCost in this loop. If it is, then the
  2501. ** (cost<lowestCost) test below will never be true.
  2502. **
  2503. ** Use "(double)2" instead of "2.0" in case OMIT_FLOATING_POINT
  2504. ** is defined.
  2505. */
  2506. if ( ( SQLITE_BIG_DBL / ( (double)2 ) ) < rCost )
  2507. {
  2508. pCost.rCost = ( SQLITE_BIG_DBL / ( (double)2 ) );
  2509. }
  2510. else
  2511. {
  2512. pCost.rCost = rCost;
  2513. }
  2514. pCost.plan.u.pVtabIdx = pIdxInfo;
  2515. if ( pIdxInfo.orderByConsumed )
  2516. {
  2517. pCost.plan.wsFlags |= WHERE_ORDERBY;
  2518. }
  2519. pCost.plan.nEq = 0;
  2520. pIdxInfo.nOrderBy = nOrderBy;
  2521. /* Try to find a more efficient access pattern by using multiple indexes
  2522. ** to optimize an OR expression within the WHERE clause.
  2523. */
  2524. bestOrClauseIndex( pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost );
  2525. }
  2526. #endif //* SQLITE_OMIT_VIRTUALTABLE */
  2527. /*
  2528. ** Argument pIdx is a pointer to an index structure that has an array of
  2529. ** SQLITE_INDEX_SAMPLES evenly spaced samples of the first indexed column
  2530. ** stored in Index.aSample. These samples divide the domain of values stored
  2531. ** the index into (SQLITE_INDEX_SAMPLES+1) regions.
  2532. ** Region 0 contains all values less than the first sample value. Region
  2533. ** 1 contains values between the first and second samples. Region 2 contains
  2534. ** values between samples 2 and 3. And so on. Region SQLITE_INDEX_SAMPLES
  2535. ** contains values larger than the last sample.
  2536. **
  2537. ** If the index contains many duplicates of a single value, then it is
  2538. ** possible that two or more adjacent samples can hold the same value.
  2539. ** When that is the case, the smallest possible region code is returned
  2540. ** when roundUp is false and the largest possible region code is returned
  2541. ** when roundUp is true.
  2542. **
  2543. ** If successful, this function determines which of the regions value
  2544. ** pVal lies in, sets *piRegion to the region index (a value between 0
  2545. ** and SQLITE_INDEX_SAMPLES+1, inclusive) and returns SQLITE_OK.
  2546. ** Or, if an OOM occurs while converting text values between encodings,
  2547. ** SQLITE_NOMEM is returned and *piRegion is undefined.
  2548. */
  2549. #if SQLITE_ENABLE_STAT2
  2550. static int whereRangeRegion(
  2551. Parse pParse, /* Database connection */
  2552. Index pIdx, /* Index to consider domain of */
  2553. sqlite3_value pVal, /* Value to consider */
  2554. int roundUp, /* Return largest valid region if true */
  2555. out int piRegion /* OUT: Region of domain in which value lies */
  2556. )
  2557. {
  2558. piRegion = 0;
  2559. Debug.Assert( roundUp == 0 || roundUp == 1 );
  2560. if ( ALWAYS( pVal ) )
  2561. {
  2562. IndexSample[] aSample = pIdx.aSample;
  2563. int i = 0;
  2564. int eType = sqlite3_value_type( pVal );
  2565. if ( eType == SQLITE_INTEGER || eType == SQLITE_FLOAT )
  2566. {
  2567. double r = sqlite3_value_double( pVal );
  2568. for ( i = 0; i < SQLITE_INDEX_SAMPLES; i++ )
  2569. {
  2570. if ( aSample[i].eType == SQLITE_NULL )
  2571. continue;
  2572. if ( aSample[i].eType >= SQLITE_TEXT )
  2573. break;
  2574. if ( roundUp != 0 )
  2575. {
  2576. if ( aSample[i].u.r > r )
  2577. break;
  2578. }
  2579. else
  2580. {
  2581. if ( aSample[i].u.r >= r )
  2582. break;
  2583. }
  2584. }
  2585. }
  2586. else if ( eType == SQLITE_NULL )
  2587. {
  2588. i = 0;
  2589. if ( roundUp != 0 )
  2590. {
  2591. while ( i < SQLITE_INDEX_SAMPLES && aSample[i].eType == SQLITE_NULL )
  2592. i++;
  2593. }
  2594. }
  2595. else
  2596. {
  2597. sqlite3 db = pParse.db;
  2598. CollSeq pColl;
  2599. string z;
  2600. int n;
  2601. /* pVal comes from sqlite3ValueFromExpr() so the type cannot be NULL */
  2602. Debug.Assert( eType == SQLITE_TEXT || eType == SQLITE_BLOB );
  2603. if ( eType == SQLITE_BLOB )
  2604. {
  2605. byte[] blob = sqlite3_value_blob( pVal );
  2606. z = Encoding.UTF8.GetString( blob, 0, blob.Length );
  2607. pColl = db.pDfltColl;
  2608. Debug.Assert( pColl.enc == SQLITE_UTF8 );
  2609. }
  2610. else
  2611. {
  2612. pColl = sqlite3GetCollSeq( db, SQLITE_UTF8, null, pIdx.azColl[0] );
  2613. if ( pColl == null )
  2614. {
  2615. sqlite3ErrorMsg( pParse, "no such collation sequence: %s",
  2616. pIdx.azColl );
  2617. return SQLITE_ERROR;
  2618. }
  2619. z = sqlite3ValueText( pVal, pColl.enc );
  2620. //if( null==z ){
  2621. // return SQLITE_NOMEM;
  2622. //}
  2623. Debug.Assert( z != "" && pColl != null && pColl.xCmp != null );
  2624. }
  2625. n = sqlite3ValueBytes( pVal, pColl.enc );
  2626. for ( i = 0; i < SQLITE_INDEX_SAMPLES; i++ )
  2627. {
  2628. int c;
  2629. int eSampletype = aSample[i].eType;
  2630. if ( eSampletype == SQLITE_NULL || eSampletype < eType )
  2631. continue;
  2632. if ( ( eSampletype != eType ) )
  2633. break;
  2634. #if !SQLITE_OMIT_UTF16
  2635. if( pColl.enc!=SQLITE_UTF8 ){
  2636. int nSample;
  2637. string zSample;
  2638. zSample = sqlite3Utf8to16(
  2639. db, pColl.enc, aSample[i].u.z, aSample[i].nByte, ref nSample
  2640. );
  2641. zSample = aSample[i].u.z;
  2642. nSample = aSample[i].u.z.Length;
  2643. //if( null==zSample ){
  2644. // Debug.Assert( db.mallocFailed );
  2645. // return SQLITE_NOMEM;
  2646. //}
  2647. c = pColl.xCmp(pColl.pUser, nSample, zSample, n, z);
  2648. sqlite3DbFree(db, ref zSample);
  2649. }else
  2650. #endif
  2651. {
  2652. c = pColl.xCmp( pColl.pUser, aSample[i].nByte, aSample[i].u.z, n, z );
  2653. }
  2654. if ( c - roundUp >= 0 )
  2655. break;
  2656. }
  2657. }
  2658. Debug.Assert( i >= 0 && i <= SQLITE_INDEX_SAMPLES );
  2659. piRegion = i;
  2660. }
  2661. return SQLITE_OK;
  2662. }
  2663. #endif //* #if SQLITE_ENABLE_STAT2 */
  2664. /*
  2665. ** If expression pExpr represents a literal value, set *pp to point to
  2666. ** an sqlite3_value structure containing the same value, with affinity
  2667. ** aff applied to it, before returning. It is the responsibility of the
  2668. ** caller to eventually release this structure by passing it to
  2669. ** sqlite3ValueFree().
  2670. **
  2671. ** If the current parse is a recompile (sqlite3Reprepare()) and pExpr
  2672. ** is an SQL variable that currently has a non-NULL value bound to it,
  2673. ** create an sqlite3_value structure containing this value, again with
  2674. ** affinity aff applied to it, instead.
  2675. **
  2676. ** If neither of the above apply, set *pp to NULL.
  2677. **
  2678. ** If an error occurs, return an error code. Otherwise, SQLITE_OK.
  2679. */
  2680. #if SQLITE_ENABLE_STAT2
  2681. static int valueFromExpr(
  2682. Parse pParse,
  2683. Expr pExpr,
  2684. char aff,
  2685. ref sqlite3_value pp
  2686. )
  2687. {
  2688. if ( pExpr.op == TK_VARIABLE
  2689. || ( pExpr.op == TK_REGISTER && pExpr.op2 == TK_VARIABLE )
  2690. )
  2691. {
  2692. int iVar = pExpr.iColumn;
  2693. sqlite3VdbeSetVarmask( pParse.pVdbe, iVar ); /* IMP: R-23257-02778 */
  2694. pp = sqlite3VdbeGetValue( pParse.pReprepare, iVar, (u8)aff );
  2695. return SQLITE_OK;
  2696. }
  2697. return sqlite3ValueFromExpr( pParse.db, pExpr, SQLITE_UTF8, aff, ref pp );
  2698. }
  2699. #endif
  2700. /*
  2701. ** This function is used to estimate the number of rows that will be visited
  2702. ** by scanning an index for a range of values. The range may have an upper
  2703. ** bound, a lower bound, or both. The WHERE clause terms that set the upper
  2704. ** and lower bounds are represented by pLower and pUpper respectively. For
  2705. ** example, assuming that index p is on t1(a):
  2706. **
  2707. ** ... FROM t1 WHERE a > ? AND a < ? ...
  2708. ** |_____| |_____|
  2709. ** | |
  2710. ** pLower pUpper
  2711. **
  2712. ** If either of the upper or lower bound is not present, then NULL is passed in
  2713. ** place of the corresponding WhereTerm.
  2714. **
  2715. ** The nEq parameter is passed the index of the index column subject to the
  2716. ** range constraint. Or, equivalently, the number of equality constraints
  2717. ** optimized by the proposed index scan. For example, assuming index p is
  2718. ** on t1(a, b), and the SQL query is:
  2719. **
  2720. ** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
  2721. **
  2722. ** then nEq should be passed the value 1 (as the range restricted column,
  2723. ** b, is the second left-most column of the index). Or, if the query is:
  2724. **
  2725. ** ... FROM t1 WHERE a > ? AND a < ? ...
  2726. **
  2727. ** then nEq should be passed 0.
  2728. **
  2729. ** The returned value is an integer between 1 and 100, inclusive. A return
  2730. ** value of 1 indicates that the proposed range scan is expected to visit
  2731. ** approximately 1/100th (1%) of the rows selected by the nEq equality
  2732. ** constraints (if any). A return value of 100 indicates that it is expected
  2733. ** that the range scan will visit every row (100%) selected by the equality
  2734. ** constraints.
  2735. **
  2736. ** In the absence of sqlite_stat2 ANALYZE data, each range inequality
  2737. ** reduces the search space by 3/4ths. Hence a single constraint (x>?)
  2738. ** results in a return of 25 and a range constraint (x>? AND x<?) results
  2739. ** in a return of 6.
  2740. */
  2741. static int whereRangeScanEst(
  2742. Parse pParse, /* Parsing & code generating context */
  2743. Index p, /* The index containing the range-compared column; "x" */
  2744. int nEq, /* index into p.aCol[] of the range-compared column */
  2745. WhereTerm pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
  2746. WhereTerm pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
  2747. out int piEst /* OUT: Return value */
  2748. )
  2749. {
  2750. int rc = SQLITE_OK;
  2751. #if SQLITE_ENABLE_STAT2
  2752. if ( nEq == 0 && p.aSample != null )
  2753. {
  2754. sqlite3_value pLowerVal = null;
  2755. sqlite3_value pUpperVal = null;
  2756. int iEst;
  2757. int iLower = 0;
  2758. int iUpper = SQLITE_INDEX_SAMPLES;
  2759. int roundUpUpper = 0;
  2760. int roundUpLower = 0;
  2761. char aff = p.pTable.aCol[p.aiColumn[0]].affinity;
  2762. if ( pLower != null )
  2763. {
  2764. Expr pExpr = pLower.pExpr.pRight;
  2765. rc = valueFromExpr( pParse, pExpr, aff, ref pLowerVal );
  2766. Debug.Assert( pLower.eOperator == WO_GT || pLower.eOperator == WO_GE );
  2767. roundUpLower = ( pLower.eOperator == WO_GT ) ? 1 : 0;
  2768. }
  2769. if ( rc == SQLITE_OK && pUpper != null )
  2770. {
  2771. Expr pExpr = pUpper.pExpr.pRight;
  2772. rc = valueFromExpr( pParse, pExpr, aff, ref pUpperVal );
  2773. Debug.Assert( pUpper.eOperator == WO_LT || pUpper.eOperator == WO_LE );
  2774. roundUpUpper = ( pUpper.eOperator == WO_LE ) ? 1 : 0;
  2775. }
  2776. if ( rc != SQLITE_OK || ( pLowerVal == null && pUpperVal == null ) )
  2777. {
  2778. sqlite3ValueFree( ref pLowerVal );
  2779. sqlite3ValueFree( ref pUpperVal );
  2780. goto range_est_fallback;
  2781. }
  2782. else if ( pLowerVal == null )
  2783. {
  2784. rc = whereRangeRegion( pParse, p, pUpperVal, roundUpUpper, out iUpper );
  2785. if ( pLower != null )
  2786. iLower = iUpper / 2;
  2787. }
  2788. else if ( pUpperVal == null )
  2789. {
  2790. rc = whereRangeRegion( pParse, p, pLowerVal, roundUpLower, out iLower );
  2791. if ( pUpper != null )
  2792. iUpper = ( iLower + SQLITE_INDEX_SAMPLES + 1 ) / 2;
  2793. }
  2794. else
  2795. {
  2796. rc = whereRangeRegion( pParse, p, pUpperVal, roundUpUpper, out iUpper );
  2797. if ( rc == SQLITE_OK )
  2798. {
  2799. rc = whereRangeRegion( pParse, p, pLowerVal, roundUpLower, out iLower );
  2800. }
  2801. }
  2802. WHERETRACE( "range scan regions: %d..%d\n", iLower, iUpper );
  2803. iEst = iUpper - iLower;
  2804. testcase( iEst == SQLITE_INDEX_SAMPLES );
  2805. Debug.Assert( iEst <= SQLITE_INDEX_SAMPLES );
  2806. if ( iEst < 1 )
  2807. {
  2808. piEst = 50 / SQLITE_INDEX_SAMPLES;
  2809. }
  2810. else
  2811. {
  2812. piEst = ( iEst * 100 ) / SQLITE_INDEX_SAMPLES;
  2813. }
  2814. sqlite3ValueFree( ref pLowerVal );
  2815. sqlite3ValueFree( ref pUpperVal );
  2816. return rc;
  2817. }
  2818. range_est_fallback:
  2819. #else
  2820. UNUSED_PARAMETER(pParse);
  2821. UNUSED_PARAMETER(p);
  2822. UNUSED_PARAMETER(nEq);
  2823. #endif
  2824. Debug.Assert( pLower != null || pUpper != null );
  2825. piEst = 100;
  2826. if ( pLower != null && ( pLower.wtFlags & TERM_VNULL ) == 0 )
  2827. piEst /= 4;
  2828. if ( pUpper != null )
  2829. piEst /= 4;
  2830. return rc;
  2831. }
  2832. #if SQLITE_ENABLE_STAT2
  2833. /*
  2834. ** Estimate the number of rows that will be returned based on
  2835. ** an equality constraint x=VALUE and where that VALUE occurs in
  2836. ** the histogram data. This only works when x is the left-most
  2837. ** column of an index and sqlite_stat2 histogram data is available
  2838. ** for that index. When pExpr==NULL that means the constraint is
  2839. ** "x IS NULL" instead of "x=VALUE".
  2840. **
  2841. ** Write the estimated row count into *pnRow and return SQLITE_OK.
  2842. ** If unable to make an estimate, leave *pnRow unchanged and return
  2843. ** non-zero.
  2844. **
  2845. ** This routine can fail if it is unable to load a collating sequence
  2846. ** required for string comparison, or if unable to allocate memory
  2847. ** for a UTF conversion required for comparison. The error is stored
  2848. ** in the pParse structure.
  2849. */
  2850. static int whereEqualScanEst(
  2851. Parse pParse, /* Parsing & code generating context */
  2852. Index p, /* The index whose left-most column is pTerm */
  2853. Expr pExpr, /* Expression for VALUE in the x=VALUE constraint */
  2854. ref double pnRow /* Write the revised row estimate here */
  2855. )
  2856. {
  2857. sqlite3_value pRhs = null;/* VALUE on right-hand side of pTerm */
  2858. int iLower = 0;
  2859. int iUpper = 0; /* Range of histogram regions containing pRhs */
  2860. char aff; /* Column affinity */
  2861. int rc; /* Subfunction return code */
  2862. double nRowEst; /* New estimate of the number of rows */
  2863. Debug.Assert( p.aSample != null );
  2864. aff = p.pTable.aCol[p.aiColumn[0]].affinity;
  2865. if ( pExpr != null )
  2866. {
  2867. rc = valueFromExpr( pParse, pExpr, aff, ref pRhs );
  2868. if ( rc != 0 )
  2869. goto whereEqualScanEst_cancel;
  2870. }
  2871. else
  2872. {
  2873. pRhs = sqlite3ValueNew( pParse.db );
  2874. }
  2875. if ( pRhs == null )
  2876. return SQLITE_NOTFOUND;
  2877. rc = whereRangeRegion( pParse, p, pRhs, 0, out iLower );
  2878. if ( rc != 0 )
  2879. goto whereEqualScanEst_cancel;
  2880. rc = whereRangeRegion( pParse, p, pRhs, 1, out iUpper );
  2881. if ( rc != 0 )
  2882. goto whereEqualScanEst_cancel;
  2883. WHERETRACE( "equality scan regions: %d..%d\n", iLower, iUpper );
  2884. if ( iLower >= iUpper )
  2885. {
  2886. nRowEst = p.aiRowEst[0] / ( SQLITE_INDEX_SAMPLES * 2 );
  2887. if ( nRowEst < pnRow )
  2888. pnRow = nRowEst;
  2889. }
  2890. else
  2891. {
  2892. nRowEst = ( iUpper - iLower ) * p.aiRowEst[0] / SQLITE_INDEX_SAMPLES;
  2893. pnRow = nRowEst;
  2894. }
  2895. whereEqualScanEst_cancel:
  2896. sqlite3ValueFree( ref pRhs );
  2897. return rc;
  2898. }
  2899. #endif //* defined(SQLITE_ENABLE_STAT2) */
  2900. #if SQLITE_ENABLE_STAT2
  2901. /*
  2902. ** Estimate the number of rows that will be returned based on
  2903. ** an IN constraint where the right-hand side of the IN operator
  2904. ** is a list of values. Example:
  2905. **
  2906. ** WHERE x IN (1,2,3,4)
  2907. **
  2908. ** Write the estimated row count into *pnRow and return SQLITE_OK.
  2909. ** If unable to make an estimate, leave *pnRow unchanged and return
  2910. ** non-zero.
  2911. **
  2912. ** This routine can fail if it is unable to load a collating sequence
  2913. ** required for string comparison, or if unable to allocate memory
  2914. ** for a UTF conversion required for comparison. The error is stored
  2915. ** in the pParse structure.
  2916. */
  2917. static int whereInScanEst(
  2918. Parse pParse, /* Parsing & code generating context */
  2919. Index p, /* The index whose left-most column is pTerm */
  2920. ExprList pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
  2921. ref double pnRow /* Write the revised row estimate here */
  2922. )
  2923. {
  2924. sqlite3_value pVal = null;/* One value from list */
  2925. int iLower = 0;
  2926. int iUpper = 0; /* Range of histogram regions containing pRhs */
  2927. char aff; /* Column affinity */
  2928. int rc = SQLITE_OK; /* Subfunction return code */
  2929. double nRowEst; /* New estimate of the number of rows */
  2930. int nSpan = 0; /* Number of histogram regions spanned */
  2931. int nSingle = 0; /* Histogram regions hit by a single value */
  2932. int nNotFound = 0; /* Count of values that are not constants */
  2933. int i; /* Loop counter */
  2934. u8[] aSpan = new u8[SQLITE_INDEX_SAMPLES + 1]; /* Histogram regions that are spanned */
  2935. u8[] aSingle = new u8[SQLITE_INDEX_SAMPLES + 1]; /* Histogram regions hit once */
  2936. Debug.Assert( p.aSample != null );
  2937. aff = p.pTable.aCol[p.aiColumn[0]].affinity;
  2938. //memset(aSpan, 0, sizeof(aSpan));
  2939. //memset(aSingle, 0, sizeof(aSingle));
  2940. for ( i = 0; i < pList.nExpr; i++ )
  2941. {
  2942. sqlite3ValueFree( ref pVal );
  2943. rc = valueFromExpr( pParse, pList.a[i].pExpr, aff, ref pVal );
  2944. if ( rc != 0 )
  2945. break;
  2946. if ( pVal == null || sqlite3_value_type( pVal ) == SQLITE_NULL )
  2947. {
  2948. nNotFound++;
  2949. continue;
  2950. }
  2951. rc = whereRangeRegion( pParse, p, pVal, 0, out iLower );
  2952. if ( rc != 0 )
  2953. break;
  2954. rc = whereRangeRegion( pParse, p, pVal, 1, out iUpper );
  2955. if ( rc != 0 )
  2956. break;
  2957. if ( iLower >= iUpper )
  2958. {
  2959. aSingle[iLower] = 1;
  2960. }
  2961. else
  2962. {
  2963. Debug.Assert( iLower >= 0 && iUpper <= SQLITE_INDEX_SAMPLES );
  2964. while ( iLower < iUpper )
  2965. aSpan[iLower++] = 1;
  2966. }
  2967. }
  2968. if ( rc == SQLITE_OK )
  2969. {
  2970. for ( i = nSpan = 0; i <= SQLITE_INDEX_SAMPLES; i++ )
  2971. {
  2972. if ( aSpan[i] != 0 )
  2973. {
  2974. nSpan++;
  2975. }
  2976. else if ( aSingle[i] != 0 )
  2977. {
  2978. nSingle++;
  2979. }
  2980. }
  2981. nRowEst = ( nSpan * 2 + nSingle ) * p.aiRowEst[0] / ( 2 * SQLITE_INDEX_SAMPLES )
  2982. + nNotFound * p.aiRowEst[1];
  2983. if ( nRowEst > p.aiRowEst[0] )
  2984. nRowEst = p.aiRowEst[0];
  2985. pnRow = nRowEst;
  2986. WHERETRACE( "IN row estimate: nSpan=%d, nSingle=%d, nNotFound=%d, est=%g\n",
  2987. nSpan, nSingle, nNotFound, nRowEst );
  2988. }
  2989. sqlite3ValueFree( ref pVal );
  2990. return rc;
  2991. }
  2992. #endif //* defined(SQLITE_ENABLE_STAT2) */
  2993. /*
  2994. ** Find the best query plan for accessing a particular table. Write the
  2995. ** best query plan and its cost into the WhereCost object supplied as the
  2996. ** last parameter.
  2997. **
  2998. ** The lowest cost plan wins. The cost is an estimate of the amount of
  2999. ** CPU and disk I/O needed to process the requested result.
  3000. ** Factors that influence cost include:
  3001. **
  3002. ** * The estimated number of rows that will be retrieved. (The
  3003. ** fewer the better.)
  3004. **
  3005. ** * Whether or not sorting must occur.
  3006. **
  3007. ** * Whether or not there must be separate lookups in the
  3008. ** index and in the main table.
  3009. **
  3010. ** If there was an INDEXED BY clause (pSrc->pIndex) attached to the table in
  3011. ** the SQL statement, then this function only considers plans using the
  3012. ** named index. If no such plan is found, then the returned cost is
  3013. ** SQLITE_BIG_DBL. If a plan is found that uses the named index,
  3014. ** then the cost is calculated in the usual way.
  3015. **
  3016. ** If a NOT INDEXED clause (pSrc->notIndexed!=0) was attached to the table
  3017. ** in the SELECT statement, then no indexes are considered. However, the
  3018. ** selected plan may still take advantage of the built-in rowid primary key
  3019. ** index.
  3020. */
  3021. static void bestBtreeIndex(
  3022. Parse pParse, /* The parsing context */
  3023. WhereClause pWC, /* The WHERE clause */
  3024. SrcList_item pSrc, /* The FROM clause term to search */
  3025. Bitmask notReady, /* Mask of cursors not available for indexing */
  3026. Bitmask notValid, /* Cursors not available for any purpose */
  3027. ExprList pOrderBy, /* The ORDER BY clause */
  3028. ref WhereCost pCost /* Lowest cost query plan */
  3029. )
  3030. {
  3031. int iCur = pSrc.iCursor; /* The cursor of the table to be accessed */
  3032. Index pProbe; /* An index we are evaluating */
  3033. Index pIdx; /* Copy of pProbe, or zero for IPK index */
  3034. u32 eqTermMask; /* Current mask of valid equality operators */
  3035. u32 idxEqTermMask; /* Index mask of valid equality operators */
  3036. Index sPk; /* A fake index object for the primary key */
  3037. int[] aiRowEstPk = new int[2]; /* The aiRowEst[] value for the sPk index */
  3038. int aiColumnPk = -1; /* The aColumn[] value for the sPk index */
  3039. int wsFlagMask; /* Allowed flags in pCost.plan.wsFlag */
  3040. /* Initialize the cost to a worst-case value */
  3041. if ( pCost == null )
  3042. pCost = new WhereCost();
  3043. else
  3044. pCost.Clear(); //memset(pCost, 0, sizeof(*pCost));
  3045. pCost.rCost = SQLITE_BIG_DBL;
  3046. /* If the pSrc table is the right table of a LEFT JOIN then we may not
  3047. ** use an index to satisfy IS NULL constraints on that table. This is
  3048. ** because columns might end up being NULL if the table does not match -
  3049. ** a circumstance which the index cannot help us discover. Ticket #2177.
  3050. */
  3051. if ( ( pSrc.jointype & JT_LEFT ) != 0 )
  3052. {
  3053. idxEqTermMask = WO_EQ | WO_IN;
  3054. }
  3055. else
  3056. {
  3057. idxEqTermMask = WO_EQ | WO_IN | WO_ISNULL;
  3058. }
  3059. if ( pSrc.pIndex != null )
  3060. {
  3061. /* An INDEXED BY clause specifies a particular index to use */
  3062. pIdx = pProbe = pSrc.pIndex;
  3063. wsFlagMask = ~( WHERE_ROWID_EQ | WHERE_ROWID_RANGE );
  3064. eqTermMask = idxEqTermMask;
  3065. }
  3066. else
  3067. {
  3068. /* There is no INDEXED BY clause. Create a fake Index object in local
  3069. ** variable sPk to represent the rowid primary key index. Make this
  3070. ** fake index the first in a chain of Index objects with all of the real
  3071. ** indices to follow */
  3072. Index pFirst; /* First of real indices on the table */
  3073. sPk = new Index(); // memset( &sPk, 0, sizeof( Index ) );
  3074. sPk.aSortOrder = new byte[1];
  3075. sPk.azColl = new string[1];
  3076. sPk.azColl[0] = "";
  3077. sPk.nColumn = 1;
  3078. sPk.aiColumn = new int[1];
  3079. sPk.aiColumn[0] = aiColumnPk;
  3080. sPk.aiRowEst = aiRowEstPk;
  3081. sPk.onError = OE_Replace;
  3082. sPk.pTable = pSrc.pTab;
  3083. aiRowEstPk[0] = (int)pSrc.pTab.nRowEst;
  3084. aiRowEstPk[1] = 1;
  3085. pFirst = pSrc.pTab.pIndex;
  3086. if ( pSrc.notIndexed == 0 )
  3087. {
  3088. /* The real indices of the table are only considered if the
  3089. ** NOT INDEXED qualifier is omitted from the FROM clause */
  3090. sPk.pNext = pFirst;
  3091. }
  3092. pProbe = sPk;
  3093. wsFlagMask = ~(
  3094. WHERE_COLUMN_IN | WHERE_COLUMN_EQ | WHERE_COLUMN_NULL | WHERE_COLUMN_RANGE
  3095. );
  3096. eqTermMask = WO_EQ | WO_IN;
  3097. pIdx = null;
  3098. }
  3099. /* Loop over all indices looking for the best one to use
  3100. */
  3101. for ( ; pProbe != null; pIdx = pProbe = pProbe.pNext )
  3102. {
  3103. int[] aiRowEst = pProbe.aiRowEst;
  3104. double cost; /* Cost of using pProbe */
  3105. double nRow; /* Estimated number of rows in result set */
  3106. double log10N = 0; /* base-10 logarithm of nRow (inexact) */
  3107. int rev = 0; /* True to scan in reverse order */
  3108. int wsFlags = 0;
  3109. Bitmask used = 0;
  3110. /* The following variables are populated based on the properties of
  3111. ** index being evaluated. They are then used to determine the expected
  3112. ** cost and number of rows returned.
  3113. **
  3114. ** nEq:
  3115. ** Number of equality terms that can be implemented using the index.
  3116. ** In other words, the number of initial fields in the index that
  3117. ** are used in == or IN or NOT NULL constraints of the WHERE clause.
  3118. **
  3119. ** nInMul:
  3120. ** The "in-multiplier". This is an estimate of how many seek operations
  3121. ** SQLite must perform on the index in question. For example, if the
  3122. ** WHERE clause is:
  3123. **
  3124. ** WHERE a IN (1, 2, 3) AND b IN (4, 5, 6)
  3125. **
  3126. ** SQLite must perform 9 lookups on an index on (a, b), so nInMul is
  3127. ** set to 9. Given the same schema and either of the following WHERE
  3128. ** clauses:
  3129. **
  3130. ** WHERE a = 1
  3131. ** WHERE a >= 2
  3132. **
  3133. ** nInMul is set to 1.
  3134. **
  3135. ** If there exists a WHERE term of the form "x IN (SELECT ...)", then
  3136. ** the sub-select is assumed to return 25 rows for the purposes of
  3137. ** determining nInMul.
  3138. **
  3139. ** bInEst:
  3140. ** Set to true if there was at least one "x IN (SELECT ...)" term used
  3141. ** in determining the value of nInMul. Note that the RHS of the
  3142. ** IN operator must be a SELECT, not a value list, for this variable
  3143. ** to be true.
  3144. **
  3145. ** estBound:
  3146. ** An estimate on the amount of the table that must be searched. A
  3147. ** value of 100 means the entire table is searched. Range constraints
  3148. ** might reduce this to a value less than 100 to indicate that only
  3149. ** a fraction of the table needs searching. In the absence of
  3150. ** sqlite_stat2 ANALYZE data, a single inequality reduces the search
  3151. ** space to 1/4rd its original size. So an x>? constraint reduces
  3152. ** estBound to 25. Two constraints (x>? AND x<?) reduce estBound to 6.
  3153. **
  3154. ** bSort:
  3155. ** Boolean. True if there is an ORDER BY clause that will require an
  3156. ** external sort (i.e. scanning the index being evaluated will not
  3157. ** correctly order records).
  3158. **
  3159. ** bLookup:
  3160. ** Boolean. True if a table lookup is required for each index entry
  3161. ** visited. In other words, true if this is not a covering index.
  3162. ** This is always false for the rowid primary key index of a table.
  3163. ** For other indexes, it is true unless all the columns of the table
  3164. ** used by the SELECT statement are present in the index (such an
  3165. ** index is sometimes described as a covering index).
  3166. ** For example, given the index on (a, b), the second of the following
  3167. ** two queries requires table b-tree lookups in order to find the value
  3168. ** of column c, but the first does not because columns a and b are
  3169. ** both available in the index.
  3170. **
  3171. ** SELECT a, b FROM tbl WHERE a = 1;
  3172. ** SELECT a, b, c FROM tbl WHERE a = 1;
  3173. */
  3174. int nEq; /* Number of == or IN terms matching index */
  3175. int bInEst = 0; /* True if "x IN (SELECT...)" seen */
  3176. int nInMul = 1; /* Number of distinct equalities to lookup */
  3177. int estBound = 100; /* Estimated reduction in search space */
  3178. int nBound = 0; /* Number of range constraints seen */
  3179. int bSort = 0; /* True if external sort required */
  3180. int bLookup = 0; /* True if not a covering index */
  3181. WhereTerm pTerm; /* A single term of the WHERE clause */
  3182. #if SQLITE_ENABLE_STAT2
  3183. WhereTerm pFirstTerm = null; /* First term matching the index */
  3184. #endif
  3185. /* Determine the values of nEq and nInMul */
  3186. for ( nEq = 0; nEq < pProbe.nColumn; nEq++ )
  3187. {
  3188. int j = pProbe.aiColumn[nEq];
  3189. pTerm = findTerm( pWC, iCur, j, notReady, eqTermMask, pIdx );
  3190. if ( pTerm == null )
  3191. break;
  3192. wsFlags |= ( WHERE_COLUMN_EQ | WHERE_ROWID_EQ );
  3193. if ( ( pTerm.eOperator & WO_IN ) != 0 )
  3194. {
  3195. Expr pExpr = pTerm.pExpr;
  3196. wsFlags |= WHERE_COLUMN_IN;
  3197. if ( ExprHasProperty( pExpr, EP_xIsSelect ) )
  3198. {
  3199. /* "x IN (SELECT ...)": Assume the SELECT returns 25 rows */
  3200. nInMul *= 25;
  3201. bInEst = 1;
  3202. }
  3203. else if ( ALWAYS( pExpr.x.pList != null ) && pExpr.x.pList.nExpr != 0 )
  3204. {
  3205. /* "x IN (value, value, ...)" */
  3206. nInMul *= pExpr.x.pList.nExpr;
  3207. }
  3208. }
  3209. else if ( ( pTerm.eOperator & WO_ISNULL ) != 0 )
  3210. {
  3211. wsFlags |= WHERE_COLUMN_NULL;
  3212. }
  3213. #if SQLITE_ENABLE_STAT2
  3214. if ( nEq == 0 && pProbe.aSample != null )
  3215. pFirstTerm = pTerm;
  3216. #endif
  3217. used |= pTerm.prereqRight;
  3218. }
  3219. /* Determine the value of estBound. */
  3220. if ( nEq < pProbe.nColumn && pProbe.bUnordered == 0 )
  3221. {
  3222. int j = pProbe.aiColumn[nEq];
  3223. if ( findTerm( pWC, iCur, j, notReady, WO_LT | WO_LE | WO_GT | WO_GE, pIdx ) != null )
  3224. {
  3225. WhereTerm pTop = findTerm( pWC, iCur, j, notReady, WO_LT | WO_LE, pIdx );
  3226. WhereTerm pBtm = findTerm( pWC, iCur, j, notReady, WO_GT | WO_GE, pIdx );
  3227. whereRangeScanEst( pParse, pProbe, nEq, pBtm, pTop, out estBound );
  3228. if ( pTop != null )
  3229. {
  3230. nBound = 1;
  3231. wsFlags |= WHERE_TOP_LIMIT;
  3232. used |= pTop.prereqRight;
  3233. }
  3234. if ( pBtm != null )
  3235. {
  3236. nBound++;
  3237. wsFlags |= WHERE_BTM_LIMIT;
  3238. used |= pBtm.prereqRight;
  3239. }
  3240. wsFlags |= ( WHERE_COLUMN_RANGE | WHERE_ROWID_RANGE );
  3241. }
  3242. }
  3243. else if ( pProbe.onError != OE_None )
  3244. {
  3245. testcase( wsFlags & WHERE_COLUMN_IN );
  3246. testcase( wsFlags & WHERE_COLUMN_NULL );
  3247. if ( ( wsFlags & ( WHERE_COLUMN_IN | WHERE_COLUMN_NULL ) ) == 0 )
  3248. {
  3249. wsFlags |= WHERE_UNIQUE;
  3250. }
  3251. }
  3252. /* If there is an ORDER BY clause and the index being considered will
  3253. ** naturally scan rows in the required order, set the appropriate flags
  3254. ** in wsFlags. Otherwise, if there is an ORDER BY clause but the index
  3255. ** will scan rows in a different order, set the bSort variable. */
  3256. if ( pOrderBy != null )
  3257. {
  3258. if ( ( wsFlags & WHERE_COLUMN_IN ) == 0
  3259. && pProbe.bUnordered == 0
  3260. && isSortingIndex( pParse, pWC.pMaskSet, pProbe, iCur, pOrderBy,
  3261. nEq, wsFlags, ref rev )
  3262. )
  3263. {
  3264. wsFlags |= WHERE_ROWID_RANGE | WHERE_COLUMN_RANGE | WHERE_ORDERBY;
  3265. wsFlags |= ( rev != 0 ? WHERE_REVERSE : 0 );
  3266. }
  3267. else
  3268. {
  3269. bSort = 1;
  3270. }
  3271. }
  3272. /* If currently calculating the cost of using an index (not the IPK
  3273. ** index), determine if all required column data may be obtained without
  3274. ** using the main table (i.e. if the index is a covering
  3275. ** index for this query). If it is, set the WHERE_IDX_ONLY flag in
  3276. ** wsFlags. Otherwise, set the bLookup variable to true. */
  3277. if ( pIdx != null && wsFlags != 0 )
  3278. {
  3279. Bitmask m = pSrc.colUsed;
  3280. int j;
  3281. for ( j = 0; j < pIdx.nColumn; j++ )
  3282. {
  3283. int x = pIdx.aiColumn[j];
  3284. if ( x < BMS - 1 )
  3285. {
  3286. m &= ~( ( (Bitmask)1 ) << x );
  3287. }
  3288. }
  3289. if ( m == 0 )
  3290. {
  3291. wsFlags |= WHERE_IDX_ONLY;
  3292. }
  3293. else
  3294. {
  3295. bLookup = 1;
  3296. }
  3297. }
  3298. /*
  3299. ** Estimate the number of rows of output. For an "x IN (SELECT...)"
  3300. ** constraint, do not let the estimate exceed half the rows in the table.
  3301. */
  3302. nRow = (double)( aiRowEst[nEq] * nInMul );
  3303. if ( bInEst != 0 && nRow * 2 > aiRowEst[0] )
  3304. {
  3305. nRow = aiRowEst[0] / 2;
  3306. nInMul = (int)( nRow / aiRowEst[nEq] );
  3307. }
  3308. #if SQLITE_ENABLE_STAT2
  3309. /* If the constraint is of the form x=VALUE and histogram
  3310. ** data is available for column x, then it might be possible
  3311. ** to get a better estimate on the number of rows based on
  3312. ** VALUE and how common that value is according to the histogram.
  3313. */
  3314. if ( nRow > (double)1 && nEq == 1 && pFirstTerm != null )
  3315. {
  3316. if ( ( pFirstTerm.eOperator & ( WO_EQ | WO_ISNULL ) ) != 0 )
  3317. {
  3318. testcase( pFirstTerm.eOperator == WO_EQ );
  3319. testcase( pFirstTerm.eOperator == WO_ISNULL );
  3320. whereEqualScanEst( pParse, pProbe, pFirstTerm.pExpr.pRight, ref nRow );
  3321. }
  3322. else if ( pFirstTerm.eOperator == WO_IN && bInEst == 0 )
  3323. {
  3324. whereInScanEst( pParse, pProbe, pFirstTerm.pExpr.x.pList, ref nRow );
  3325. }
  3326. }
  3327. #endif //* SQLITE_ENABLE_STAT2 */
  3328. /* Adjust the number of output rows and downward to reflect rows
  3329. ** that are excluded by range constraints.
  3330. */
  3331. nRow = ( nRow * (double)estBound ) / (double)100;
  3332. if ( nRow < 1 )
  3333. nRow = 1;
  3334. /* Experiments run on real SQLite databases show that the time needed
  3335. ** to do a binary search to locate a row in a table or index is roughly
  3336. ** log10(N) times the time to move from one row to the next row within
  3337. ** a table or index. The actual times can vary, with the size of
  3338. ** records being an important factor. Both moves and searches are
  3339. ** slower with larger records, presumably because fewer records fit
  3340. ** on one page and hence more pages have to be fetched.
  3341. **
  3342. ** The ANALYZE command and the sqlite_stat1 and sqlite_stat2 tables do
  3343. ** not give us data on the relative sizes of table and index records.
  3344. ** So this computation assumes table records are about twice as big
  3345. ** as index records
  3346. */
  3347. if ( ( wsFlags & WHERE_NOT_FULLSCAN ) == 0 )
  3348. {
  3349. /* The cost of a full table scan is a number of move operations equal
  3350. ** to the number of rows in the table.
  3351. **
  3352. ** We add an additional 4x penalty to full table scans. This causes
  3353. ** the cost function to err on the side of choosing an index over
  3354. ** choosing a full scan. This 4x full-scan penalty is an arguable
  3355. ** decision and one which we expect to revisit in the future. But
  3356. ** it seems to be working well enough at the moment.
  3357. */
  3358. cost = aiRowEst[0] * 4;
  3359. }
  3360. else
  3361. {
  3362. log10N = estLog( aiRowEst[0] );
  3363. cost = nRow;
  3364. if ( pIdx != null )
  3365. {
  3366. if ( bLookup != 0 )
  3367. {
  3368. /* For an index lookup followed by a table lookup:
  3369. ** nInMul index searches to find the start of each index range
  3370. ** + nRow steps through the index
  3371. ** + nRow table searches to lookup the table entry using the rowid
  3372. */
  3373. cost += ( nInMul + nRow ) * log10N;
  3374. }
  3375. else
  3376. {
  3377. /* For a covering index:
  3378. ** nInMul index searches to find the initial entry
  3379. ** + nRow steps through the index
  3380. */
  3381. cost += nInMul * log10N;
  3382. }
  3383. }
  3384. else
  3385. {
  3386. /* For a rowid primary key lookup:
  3387. ** nInMult table searches to find the initial entry for each range
  3388. ** + nRow steps through the table
  3389. */
  3390. cost += nInMul * log10N;
  3391. }
  3392. }
  3393. /* Add in the estimated cost of sorting the result. Actual experimental
  3394. ** measurements of sorting performance in SQLite show that sorting time
  3395. ** adds C*N*log10(N) to the cost, where N is the number of rows to be
  3396. ** sorted and C is a factor between 1.95 and 4.3. We will split the
  3397. ** difference and select C of 3.0.
  3398. */
  3399. if ( bSort != 0 )
  3400. {
  3401. cost += nRow * estLog( nRow ) * 3;
  3402. }
  3403. /**** Cost of using this index has now been computed ****/
  3404. /* If there are additional constraints on this table that cannot
  3405. ** be used with the current index, but which might lower the number
  3406. ** of output rows, adjust the nRow value accordingly. This only
  3407. ** matters if the current index is the least costly, so do not bother
  3408. ** with this step if we already know this index will not be chosen.
  3409. ** Also, never reduce the output row count below 2 using this step.
  3410. **
  3411. ** It is critical that the notValid mask be used here instead of
  3412. ** the notReady mask. When computing an "optimal" index, the notReady
  3413. ** mask will only have one bit set - the bit for the current table.
  3414. ** The notValid mask, on the other hand, always has all bits set for
  3415. ** tables that are not in outer loops. If notReady is used here instead
  3416. ** of notValid, then a optimal index that depends on inner joins loops
  3417. ** might be selected even when there exists an optimal index that has
  3418. ** no such dependency.
  3419. */
  3420. if ( nRow > 2 && cost <= pCost.rCost )
  3421. {
  3422. //int k; /* Loop counter */
  3423. int nSkipEq = nEq; /* Number of == constraints to skip */
  3424. int nSkipRange = nBound; /* Number of < constraints to skip */
  3425. Bitmask thisTab; /* Bitmap for pSrc */
  3426. thisTab = getMask( pWC.pMaskSet, iCur );
  3427. for ( int ipTerm = 0, k = pWC.nTerm; nRow > 2 && k != 0; k--, ipTerm++ )//pTerm++)
  3428. {
  3429. pTerm = pWC.a[ipTerm];
  3430. if ( ( pTerm.wtFlags & TERM_VIRTUAL ) != 0 )
  3431. continue;
  3432. if ( ( pTerm.prereqAll & notValid ) != thisTab )
  3433. continue;
  3434. if ( ( pTerm.eOperator & ( WO_EQ | WO_IN | WO_ISNULL ) ) != 0 )
  3435. {
  3436. if ( nSkipEq != 0 )
  3437. {
  3438. /* Ignore the first nEq equality matches since the index
  3439. ** has already accounted for these */
  3440. nSkipEq--;
  3441. }
  3442. else
  3443. {
  3444. /* Assume each additional equality match reduces the result
  3445. ** set size by a factor of 10 */
  3446. nRow /= 10;
  3447. }
  3448. }
  3449. else if ( ( pTerm.eOperator & ( WO_LT | WO_LE | WO_GT | WO_GE ) ) != 0 )
  3450. {
  3451. if ( nSkipRange != 0 )
  3452. {
  3453. /* Ignore the first nSkipRange range constraints since the index
  3454. ** has already accounted for these */
  3455. nSkipRange--;
  3456. }
  3457. else
  3458. {
  3459. /* Assume each additional range constraint reduces the result
  3460. ** set size by a factor of 3. Indexed range constraints reduce
  3461. ** the search space by a larger factor: 4. We make indexed range
  3462. ** more selective intentionally because of the subjective
  3463. ** observation that indexed range constraints really are more
  3464. ** selective in practice, on average. */
  3465. nRow /= 3;
  3466. }
  3467. }
  3468. else if ( pTerm.eOperator != WO_NOOP )
  3469. {
  3470. /* Any other expression lowers the output row count by half */
  3471. nRow /= 2;
  3472. }
  3473. }
  3474. if ( nRow < 2 )
  3475. nRow = 2;
  3476. }
  3477. #if (SQLITE_TEST) && (SQLITE_DEBUG)
  3478. WHERETRACE(
  3479. "%s(%s): nEq=%d nInMul=%d estBound=%d bSort=%d bLookup=%d wsFlags=0x%x\n" +
  3480. " notReady=0x%llx log10N=%.1f nRow=%.1f cost=%.1f used=0x%llx\n",
  3481. pSrc.pTab.zName, ( pIdx != null ? pIdx.zName : "ipk" ),
  3482. nEq, nInMul, estBound, bSort, bLookup, wsFlags,
  3483. notReady, log10N, cost, used
  3484. );
  3485. #endif
  3486. /* If this index is the best we have seen so far, then record this
  3487. ** index and its cost in the pCost structure.
  3488. */
  3489. if ( ( null == pIdx || wsFlags != 0 )
  3490. && ( cost < pCost.rCost || ( cost <= pCost.rCost && nRow < pCost.plan.nRow ) )
  3491. )
  3492. {
  3493. pCost.rCost = cost;
  3494. pCost.used = used;
  3495. pCost.plan.nRow = nRow;
  3496. pCost.plan.wsFlags = (uint)( wsFlags & wsFlagMask );
  3497. pCost.plan.nEq = (uint)nEq;
  3498. pCost.plan.u.pIdx = pIdx;
  3499. }
  3500. /* If there was an INDEXED BY clause, then only that one index is
  3501. ** considered. */
  3502. if ( pSrc.pIndex != null )
  3503. break;
  3504. /* Reset masks for the next index in the loop */
  3505. wsFlagMask = ~( WHERE_ROWID_EQ | WHERE_ROWID_RANGE );
  3506. eqTermMask = idxEqTermMask;
  3507. }
  3508. /* If there is no ORDER BY clause and the SQLITE_ReverseOrder flag
  3509. ** is set, then reverse the order that the index will be scanned
  3510. ** in. This is used for application testing, to help find cases
  3511. ** where application behaviour depends on the (undefined) order that
  3512. ** SQLite outputs rows in in the absence of an ORDER BY clause. */
  3513. if ( null == pOrderBy && ( pParse.db.flags & SQLITE_ReverseOrder ) != 0 )
  3514. {
  3515. pCost.plan.wsFlags |= WHERE_REVERSE;
  3516. }
  3517. Debug.Assert( pOrderBy != null || ( pCost.plan.wsFlags & WHERE_ORDERBY ) == 0 );
  3518. Debug.Assert( pCost.plan.u.pIdx == null || ( pCost.plan.wsFlags & WHERE_ROWID_EQ ) == 0 );
  3519. Debug.Assert( pSrc.pIndex == null
  3520. || pCost.plan.u.pIdx == null
  3521. || pCost.plan.u.pIdx == pSrc.pIndex
  3522. );
  3523. #if (SQLITE_TEST) && (SQLITE_DEBUG)
  3524. WHERETRACE( "best index is: %s\n",
  3525. ( ( pCost.plan.wsFlags & WHERE_NOT_FULLSCAN ) == 0 ? "none" :
  3526. pCost.plan.u.pIdx != null ? pCost.plan.u.pIdx.zName : "ipk" )
  3527. );
  3528. #endif
  3529. bestOrClauseIndex( pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost );
  3530. bestAutomaticIndex( pParse, pWC, pSrc, notReady, pCost );
  3531. pCost.plan.wsFlags |= (u32)eqTermMask;
  3532. }
  3533. /*
  3534. ** Find the query plan for accessing table pSrc.pTab. Write the
  3535. ** best query plan and its cost into the WhereCost object supplied
  3536. ** as the last parameter. This function may calculate the cost of
  3537. ** both real and virtual table scans.
  3538. */
  3539. static void bestIndex(
  3540. Parse pParse, /* The parsing context */
  3541. WhereClause pWC, /* The WHERE clause */
  3542. SrcList_item pSrc, /* The FROM clause term to search */
  3543. Bitmask notReady, /* Mask of cursors not available for indexing */
  3544. Bitmask notValid, /* Cursors not available for any purpose */
  3545. ExprList pOrderBy, /* The ORDER BY clause */
  3546. ref WhereCost pCost /* Lowest cost query plan */
  3547. )
  3548. {
  3549. #if !SQLITE_OMIT_VIRTUALTABLE
  3550. if ( IsVirtual( pSrc.pTab ) )
  3551. {
  3552. sqlite3_index_info p = null;
  3553. bestVirtualIndex( pParse, pWC, pSrc, notReady, notValid, pOrderBy, ref pCost, ref p );
  3554. if ( p.needToFreeIdxStr != 0 )
  3555. {
  3556. //sqlite3_free(ref p.idxStr);
  3557. }
  3558. sqlite3DbFree( pParse.db, ref p );
  3559. }
  3560. else
  3561. #endif
  3562. {
  3563. bestBtreeIndex( pParse, pWC, pSrc, notReady, notValid, pOrderBy, ref pCost );
  3564. }
  3565. }
  3566. /*
  3567. ** Disable a term in the WHERE clause. Except, do not disable the term
  3568. ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
  3569. ** or USING clause of that join.
  3570. **
  3571. ** Consider the term t2.z='ok' in the following queries:
  3572. **
  3573. ** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
  3574. ** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
  3575. ** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
  3576. **
  3577. ** The t2.z='ok' is disabled in the in (2) because it originates
  3578. ** in the ON clause. The term is disabled in (3) because it is not part
  3579. ** of a LEFT OUTER JOIN. In (1), the term is not disabled.
  3580. **
  3581. ** IMPLEMENTATION-OF: R-24597-58655 No tests are done for terms that are
  3582. ** completely satisfied by indices.
  3583. **
  3584. ** Disabling a term causes that term to not be tested in the inner loop
  3585. ** of the join. Disabling is an optimization. When terms are satisfied
  3586. ** by indices, we disable them to prevent redundant tests in the inner
  3587. ** loop. We would get the correct results if nothing were ever disabled,
  3588. ** but joins might run a little slower. The trick is to disable as much
  3589. ** as we can without disabling too much. If we disabled in (1), we'd get
  3590. ** the wrong answer. See ticket #813.
  3591. */
  3592. static void disableTerm( WhereLevel pLevel, WhereTerm pTerm )
  3593. {
  3594. if ( pTerm != null
  3595. && ( pTerm.wtFlags & TERM_CODED ) == 0
  3596. && ( pLevel.iLeftJoin == 0 || ExprHasProperty( pTerm.pExpr, EP_FromJoin ) ) )
  3597. {
  3598. pTerm.wtFlags |= TERM_CODED;
  3599. if ( pTerm.iParent >= 0 )
  3600. {
  3601. WhereTerm pOther = pTerm.pWC.a[pTerm.iParent];
  3602. if ( ( --pOther.nChild ) == 0 )
  3603. {
  3604. disableTerm( pLevel, pOther );
  3605. }
  3606. }
  3607. }
  3608. }
  3609. /*
  3610. ** Code an OP_Affinity opcode to apply the column affinity string zAff
  3611. ** to the n registers starting at base.
  3612. **
  3613. ** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
  3614. ** beginning and end of zAff are ignored. If all entries in zAff are
  3615. ** SQLITE_AFF_NONE, then no code gets generated.
  3616. **
  3617. ** This routine makes its own copy of zAff so that the caller is free
  3618. ** to modify zAff after this routine returns.
  3619. */
  3620. static void codeApplyAffinity( Parse pParse, int _base, int n, string zAff )
  3621. {
  3622. Vdbe v = pParse.pVdbe;
  3623. //if (zAff == 0)
  3624. //{
  3625. // Debug.Assert(pParse.db.mallocFailed);
  3626. // return;
  3627. //}
  3628. Debug.Assert( v != null );
  3629. /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
  3630. ** and end of the affinity string.
  3631. */
  3632. while ( n > 0 && zAff[0] == SQLITE_AFF_NONE )
  3633. {
  3634. n--;
  3635. _base++;
  3636. zAff = zAff.Substring( 1 );// zAff++;
  3637. }
  3638. while ( n > 1 && zAff[n - 1] == SQLITE_AFF_NONE )
  3639. {
  3640. n--;
  3641. }
  3642. /* Code the OP_Affinity opcode if there is anything left to do. */
  3643. if ( n > 0 )
  3644. {
  3645. sqlite3VdbeAddOp2( v, OP_Affinity, _base, n );
  3646. sqlite3VdbeChangeP4( v, -1, zAff, n );
  3647. sqlite3ExprCacheAffinityChange( pParse, _base, n );
  3648. }
  3649. }
  3650. /*
  3651. ** Generate code for a single equality term of the WHERE clause. An equality
  3652. ** term can be either X=expr or X IN (...). pTerm is the term to be
  3653. ** coded.
  3654. **
  3655. ** The current value for the constraint is left in register iReg.
  3656. **
  3657. ** For a constraint of the form X=expr, the expression is evaluated and its
  3658. ** result is left on the stack. For constraints of the form X IN (...)
  3659. ** this routine sets up a loop that will iterate over all values of X.
  3660. */
  3661. static int codeEqualityTerm(
  3662. Parse pParse, /* The parsing context */
  3663. WhereTerm pTerm, /* The term of the WHERE clause to be coded */
  3664. WhereLevel pLevel, /* When level of the FROM clause we are working on */
  3665. int iTarget /* Attempt to leave results in this register */
  3666. )
  3667. {
  3668. Expr pX = pTerm.pExpr;
  3669. Vdbe v = pParse.pVdbe;
  3670. int iReg; /* Register holding results */
  3671. Debug.Assert( iTarget > 0 );
  3672. if ( pX.op == TK_EQ )
  3673. {
  3674. iReg = sqlite3ExprCodeTarget( pParse, pX.pRight, iTarget );
  3675. }
  3676. else if ( pX.op == TK_ISNULL )
  3677. {
  3678. iReg = iTarget;
  3679. sqlite3VdbeAddOp2( v, OP_Null, 0, iReg );
  3680. #if !SQLITE_OMIT_SUBQUERY
  3681. }
  3682. else
  3683. {
  3684. int eType;
  3685. int iTab;
  3686. InLoop pIn;
  3687. Debug.Assert( pX.op == TK_IN );
  3688. iReg = iTarget;
  3689. int iDummy = -1;
  3690. eType = sqlite3FindInIndex( pParse, pX, ref iDummy );
  3691. iTab = pX.iTable;
  3692. sqlite3VdbeAddOp2( v, OP_Rewind, iTab, 0 );
  3693. Debug.Assert( ( pLevel.plan.wsFlags & WHERE_IN_ABLE ) != 0 );
  3694. if ( pLevel.u._in.nIn == 0 )
  3695. {
  3696. pLevel.addrNxt = sqlite3VdbeMakeLabel( v );
  3697. }
  3698. pLevel.u._in.nIn++;
  3699. if ( pLevel.u._in.aInLoop == null )
  3700. pLevel.u._in.aInLoop = new InLoop[pLevel.u._in.nIn];
  3701. else
  3702. Array.Resize( ref pLevel.u._in.aInLoop, pLevel.u._in.nIn );
  3703. //sqlite3DbReallocOrFree(pParse.db, pLevel.u._in.aInLoop,
  3704. // sizeof(pLevel.u._in.aInLoop[0])*pLevel.u._in.nIn);
  3705. //pIn = pLevel.u._in.aInLoop;
  3706. if ( pLevel.u._in.aInLoop != null )//(pIn )
  3707. {
  3708. pLevel.u._in.aInLoop[pLevel.u._in.nIn - 1] = new InLoop();
  3709. pIn = pLevel.u._in.aInLoop[pLevel.u._in.nIn - 1];//pIn++
  3710. pIn.iCur = iTab;
  3711. if ( eType == IN_INDEX_ROWID )
  3712. {
  3713. pIn.addrInTop = sqlite3VdbeAddOp2( v, OP_Rowid, iTab, iReg );
  3714. }
  3715. else
  3716. {
  3717. pIn.addrInTop = sqlite3VdbeAddOp3( v, OP_Column, iTab, 0, iReg );
  3718. }
  3719. sqlite3VdbeAddOp1( v, OP_IsNull, iReg );
  3720. }
  3721. else
  3722. {
  3723. pLevel.u._in.nIn = 0;
  3724. }
  3725. #endif
  3726. }
  3727. disableTerm( pLevel, pTerm );
  3728. return iReg;
  3729. }
  3730. /*
  3731. ** Generate code for a single equality term of the WHERE clause. An equality
  3732. ** term can be either X=expr or X IN (...). pTerm is the term to be
  3733. ** coded.
  3734. **
  3735. ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
  3736. ** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
  3737. ** The index has as many as three equality constraints, but in this
  3738. ** example, the third "c" value is an inequality. So only two
  3739. ** constraints are coded. This routine will generate code to evaluate
  3740. ** a==5 and b IN (1,2,3). The current values for a and b will be stored
  3741. ** in consecutive registers and the index of the first register is returned.
  3742. **
  3743. ** In the example above nEq==2. But this subroutine works for any value
  3744. ** of nEq including 0. If nEq==null, this routine is nearly a no-op.
  3745. ** The only thing it does is allocate the pLevel.iMem memory cell and
  3746. ** compute the affinity string.
  3747. **
  3748. ** This routine always allocates at least one memory cell and returns
  3749. ** the index of that memory cell. The code that
  3750. ** calls this routine will use that memory cell to store the termination
  3751. ** key value of the loop. If one or more IN operators appear, then
  3752. ** this routine allocates an additional nEq memory cells for internal
  3753. ** use.
  3754. **
  3755. ** Before returning, *pzAff is set to point to a buffer containing a
  3756. ** copy of the column affinity string of the index allocated using
  3757. ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
  3758. ** with equality constraints that use NONE affinity are set to
  3759. ** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
  3760. **
  3761. ** CREATE TABLE t1(a TEXT PRIMARY KEY, b);
  3762. ** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
  3763. **
  3764. ** In the example above, the index on t1(a) has TEXT affinity. But since
  3765. ** the right hand side of the equality constraint (t2.b) has NONE affinity,
  3766. ** no conversion should be attempted before using a t2.b value as part of
  3767. ** a key to search the index. Hence the first byte in the returned affinity
  3768. ** string in this example would be set to SQLITE_AFF_NONE.
  3769. */
  3770. static int codeAllEqualityTerms(
  3771. Parse pParse, /* Parsing context */
  3772. WhereLevel pLevel, /* Which nested loop of the FROM we are coding */
  3773. WhereClause pWC, /* The WHERE clause */
  3774. Bitmask notReady, /* Which parts of FROM have not yet been coded */
  3775. int nExtraReg, /* Number of extra registers to allocate */
  3776. out StringBuilder pzAff /* OUT: Set to point to affinity string */
  3777. )
  3778. {
  3779. int nEq = (int)pLevel.plan.nEq; /* The number of == or IN constraints to code */
  3780. Vdbe v = pParse.pVdbe; /* The vm under construction */
  3781. Index pIdx; /* The index being used for this loop */
  3782. int iCur = pLevel.iTabCur; /* The cursor of the table */
  3783. WhereTerm pTerm; /* A single constraint term */
  3784. int j; /* Loop counter */
  3785. int regBase; /* Base register */
  3786. int nReg; /* Number of registers to allocate */
  3787. StringBuilder zAff; /* Affinity string to return */
  3788. /* This module is only called on query plans that use an index. */
  3789. Debug.Assert( ( pLevel.plan.wsFlags & WHERE_INDEXED ) != 0 );
  3790. pIdx = pLevel.plan.u.pIdx;
  3791. /* Figure out how many memory cells we will need then allocate them.
  3792. */
  3793. regBase = pParse.nMem + 1;
  3794. nReg = (int)( pLevel.plan.nEq + nExtraReg );
  3795. pParse.nMem += nReg;
  3796. zAff = new StringBuilder( sqlite3IndexAffinityStr( v, pIdx ) );//sqlite3DbStrDup(pParse.db, sqlite3IndexAffinityStr(v, pIdx));
  3797. //if( null==zAff ){
  3798. // pParse.db.mallocFailed = 1;
  3799. //}
  3800. /* Evaluate the equality constraints
  3801. */
  3802. Debug.Assert( pIdx.nColumn >= nEq );
  3803. for ( j = 0; j < nEq; j++ )
  3804. {
  3805. int r1;
  3806. int k = pIdx.aiColumn[j];
  3807. pTerm = findTerm( pWC, iCur, k, notReady, pLevel.plan.wsFlags, pIdx );
  3808. if ( NEVER( pTerm == null ) )
  3809. break;
  3810. /* The following true for indices with redundant columns.
  3811. ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
  3812. testcase( ( pTerm.wtFlags & TERM_CODED ) != 0 );
  3813. testcase( pTerm.wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
  3814. r1 = codeEqualityTerm( pParse, pTerm, pLevel, regBase + j );
  3815. if ( r1 != regBase + j )
  3816. {
  3817. if ( nReg == 1 )
  3818. {
  3819. sqlite3ReleaseTempReg( pParse, regBase );
  3820. regBase = r1;
  3821. }
  3822. else
  3823. {
  3824. sqlite3VdbeAddOp2( v, OP_SCopy, r1, regBase + j );
  3825. }
  3826. }
  3827. testcase( pTerm.eOperator & WO_ISNULL );
  3828. testcase( pTerm.eOperator & WO_IN );
  3829. if ( ( pTerm.eOperator & ( WO_ISNULL | WO_IN ) ) == 0 )
  3830. {
  3831. Expr pRight = pTerm.pExpr.pRight;
  3832. sqlite3ExprCodeIsNullJump( v, pRight, regBase + j, pLevel.addrBrk );
  3833. if ( zAff.Length > 0 )
  3834. {
  3835. if ( sqlite3CompareAffinity( pRight, zAff[j] ) == SQLITE_AFF_NONE )
  3836. {
  3837. zAff[j] = SQLITE_AFF_NONE;
  3838. }
  3839. if ( ( sqlite3ExprNeedsNoAffinityChange( pRight, zAff[j] ) ) != 0 )
  3840. {
  3841. zAff[j] = SQLITE_AFF_NONE;
  3842. }
  3843. }
  3844. }
  3845. }
  3846. pzAff = zAff;
  3847. return regBase;
  3848. }
  3849. #if !SQLITE_OMIT_EXPLAIN
  3850. /*
  3851. ** This routine is a helper for explainIndexRange() below
  3852. **
  3853. ** pStr holds the text of an expression that we are building up one term
  3854. ** at a time. This routine adds a new term to the end of the expression.
  3855. ** Terms are separated by AND so add the "AND" text for second and subsequent
  3856. ** terms only.
  3857. */
  3858. static void explainAppendTerm(
  3859. StrAccum pStr, /* The text expression being built */
  3860. int iTerm, /* Index of this term. First is zero */
  3861. string zColumn, /* Name of the column */
  3862. string zOp /* Name of the operator */
  3863. )
  3864. {
  3865. if ( iTerm != 0 )
  3866. sqlite3StrAccumAppend( pStr, " AND ", 5 );
  3867. sqlite3StrAccumAppend( pStr, zColumn, -1 );
  3868. sqlite3StrAccumAppend( pStr, zOp, 1 );
  3869. sqlite3StrAccumAppend( pStr, "?", 1 );
  3870. }
  3871. /*
  3872. ** Argument pLevel describes a strategy for scanning table pTab. This
  3873. ** function returns a pointer to a string buffer containing a description
  3874. ** of the subset of table rows scanned by the strategy in the form of an
  3875. ** SQL expression. Or, if all rows are scanned, NULL is returned.
  3876. **
  3877. ** For example, if the query:
  3878. **
  3879. ** SELECT * FROM t1 WHERE a=1 AND b>2;
  3880. **
  3881. ** is run and there is an index on (a, b), then this function returns a
  3882. ** string similar to:
  3883. **
  3884. ** "a=? AND b>?"
  3885. **
  3886. ** The returned pointer points to memory obtained from sqlite3DbMalloc().
  3887. ** It is the responsibility of the caller to free the buffer when it is
  3888. ** no longer required.
  3889. */
  3890. static string explainIndexRange( sqlite3 db, WhereLevel pLevel, Table pTab )
  3891. {
  3892. WherePlan pPlan = pLevel.plan;
  3893. Index pIndex = pPlan.u.pIdx;
  3894. uint nEq = pPlan.nEq;
  3895. int i, j;
  3896. Column[] aCol = pTab.aCol;
  3897. int[] aiColumn = pIndex.aiColumn;
  3898. StrAccum txt = new StrAccum( 100 );
  3899. if ( nEq == 0 && ( pPlan.wsFlags & ( WHERE_BTM_LIMIT | WHERE_TOP_LIMIT ) ) == 0 )
  3900. {
  3901. return null;
  3902. }
  3903. sqlite3StrAccumInit( txt, null, 0, SQLITE_MAX_LENGTH );
  3904. txt.db = db;
  3905. sqlite3StrAccumAppend( txt, " (", 2 );
  3906. for ( i = 0; i < nEq; i++ )
  3907. {
  3908. explainAppendTerm( txt, i, aCol[aiColumn[i]].zName, "=" );
  3909. }
  3910. j = i;
  3911. if ( ( pPlan.wsFlags & WHERE_BTM_LIMIT ) != 0 )
  3912. {
  3913. explainAppendTerm( txt, i++, aCol[aiColumn[j]].zName, ">" );
  3914. }
  3915. if ( ( pPlan.wsFlags & WHERE_TOP_LIMIT ) != 0 )
  3916. {
  3917. explainAppendTerm( txt, i, aCol[aiColumn[j]].zName, "<" );
  3918. }
  3919. sqlite3StrAccumAppend( txt, ")", 1 );
  3920. return sqlite3StrAccumFinish( txt );
  3921. }
  3922. /*
  3923. ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
  3924. ** command. If the query being compiled is an EXPLAIN QUERY PLAN, a single
  3925. ** record is added to the output to describe the table scan strategy in
  3926. ** pLevel.
  3927. */
  3928. static void explainOneScan(
  3929. Parse pParse, /* Parse context */
  3930. SrcList pTabList, /* Table list this loop refers to */
  3931. WhereLevel pLevel, /* Scan to write OP_Explain opcode for */
  3932. int iLevel, /* Value for "level" column of output */
  3933. int iFrom, /* Value for "from" column of output */
  3934. u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
  3935. )
  3936. {
  3937. if ( pParse.explain == 2 )
  3938. {
  3939. u32 flags = pLevel.plan.wsFlags;
  3940. SrcList_item pItem = pTabList.a[pLevel.iFrom];
  3941. Vdbe v = pParse.pVdbe; /* VM being constructed */
  3942. sqlite3 db = pParse.db; /* Database handle */
  3943. StringBuilder zMsg = new StringBuilder( 1000 ); /* Text to add to EQP output */
  3944. sqlite3_int64 nRow; /* Expected number of rows visited by scan */
  3945. int iId = pParse.iSelectId; /* Select id (left-most output column) */
  3946. bool isSearch; /* True for a SEARCH. False for SCAN. */
  3947. if ( ( flags & WHERE_MULTI_OR ) != 0 || ( wctrlFlags & WHERE_ONETABLE_ONLY ) != 0 )
  3948. return;
  3949. isSearch = ( pLevel.plan.nEq > 0 )
  3950. || ( flags & ( WHERE_BTM_LIMIT | WHERE_TOP_LIMIT ) ) != 0
  3951. || ( wctrlFlags & ( WHERE_ORDERBY_MIN | WHERE_ORDERBY_MAX ) ) != 0;
  3952. zMsg.Append( sqlite3MPrintf( db, "%s", isSearch ? "SEARCH" : "SCAN" ) );
  3953. if ( pItem.pSelect != null )
  3954. {
  3955. zMsg.Append( sqlite3MAppendf( db, null, " SUBQUERY %d", pItem.iSelectId ) );
  3956. }
  3957. else
  3958. {
  3959. zMsg.Append( sqlite3MAppendf( db, null, " TABLE %s", pItem.zName ) );
  3960. }
  3961. if ( pItem.zAlias != null )
  3962. {
  3963. zMsg.Append( sqlite3MAppendf( db, null, " AS %s", pItem.zAlias ) );
  3964. }
  3965. if ( ( flags & WHERE_INDEXED ) != 0 )
  3966. {
  3967. string zWhere = explainIndexRange( db, pLevel, pItem.pTab );
  3968. zMsg.Append( sqlite3MAppendf( db, null, " USING %s%sINDEX%s%s%s",
  3969. ( ( flags & WHERE_TEMP_INDEX ) != 0 ? "AUTOMATIC " : "" ),
  3970. ( ( flags & WHERE_IDX_ONLY ) != 0 ? "COVERING " : "" ),
  3971. ( ( flags & WHERE_TEMP_INDEX ) != 0 ? "" : " " ),
  3972. ( ( flags & WHERE_TEMP_INDEX ) != 0 ? "" : pLevel.plan.u.pIdx.zName ),
  3973. zWhere != null ? zWhere : ""
  3974. ) );
  3975. sqlite3DbFree( db, ref zWhere );
  3976. }
  3977. else if ( ( flags & ( WHERE_ROWID_EQ | WHERE_ROWID_RANGE ) ) != 0 )
  3978. {
  3979. zMsg.Append( " USING INTEGER PRIMARY KEY" );
  3980. if ( ( flags & WHERE_ROWID_EQ ) != 0 )
  3981. {
  3982. zMsg.Append( " (rowid=?)" );
  3983. }
  3984. else if ( ( flags & WHERE_BOTH_LIMIT ) == WHERE_BOTH_LIMIT )
  3985. {
  3986. zMsg.Append( " (rowid>? AND rowid<?)" );
  3987. }
  3988. else if ( ( flags & WHERE_BTM_LIMIT ) != 0 )
  3989. {
  3990. zMsg.Append( " (rowid>?)" );
  3991. }
  3992. else if ( ( flags & WHERE_TOP_LIMIT ) != 0 )
  3993. {
  3994. zMsg.Append( " (rowid<?)" );
  3995. }
  3996. }
  3997. #if !SQLITE_OMIT_VIRTUALTABLE
  3998. else if ( ( flags & WHERE_VIRTUALTABLE ) != 0 )
  3999. {
  4000. sqlite3_index_info pVtabIdx = pLevel.plan.u.pVtabIdx;
  4001. zMsg.Append( sqlite3MAppendf( db, null, " VIRTUAL TABLE INDEX %d:%s",
  4002. pVtabIdx.idxNum, pVtabIdx.idxStr ) );
  4003. }
  4004. #endif
  4005. if ( ( wctrlFlags & ( WHERE_ORDERBY_MIN | WHERE_ORDERBY_MAX ) ) != 0 )
  4006. {
  4007. testcase( wctrlFlags & WHERE_ORDERBY_MIN );
  4008. nRow = 1;
  4009. }
  4010. else
  4011. {
  4012. nRow = (sqlite3_int64)pLevel.plan.nRow;
  4013. }
  4014. zMsg.Append( sqlite3MAppendf( db, null, " (~%lld rows)", nRow ) );
  4015. sqlite3VdbeAddOp4( v, OP_Explain, iId, iLevel, iFrom, zMsg, P4_DYNAMIC );
  4016. }
  4017. }
  4018. #else
  4019. //# define explainOneScan(u,v,w,x,y,z)
  4020. static void explainOneScan( Parse u, SrcList v, WhereLevel w, int x, int y, u16 z){}
  4021. #endif //* SQLITE_OMIT_EXPLAIN */
  4022. /*
  4023. ** Generate code for the start of the iLevel-th loop in the WHERE clause
  4024. ** implementation described by pWInfo.
  4025. */
  4026. static Bitmask codeOneLoopStart(
  4027. WhereInfo pWInfo, /* Complete information about the WHERE clause */
  4028. int iLevel, /* Which level of pWInfo.a[] should be coded */
  4029. u16 wctrlFlags, /* One of the WHERE_* flags defined in sqliteInt.h */
  4030. Bitmask notReady /* Which tables are currently available */
  4031. )
  4032. {
  4033. int j, k; /* Loop counters */
  4034. int iCur; /* The VDBE cursor for the table */
  4035. int addrNxt; /* Where to jump to continue with the next IN case */
  4036. int omitTable; /* True if we use the index only */
  4037. int bRev; /* True if we need to scan in reverse order */
  4038. WhereLevel pLevel; /* The where level to be coded */
  4039. WhereClause pWC; /* Decomposition of the entire WHERE clause */
  4040. WhereTerm pTerm; /* A WHERE clause term */
  4041. Parse pParse; /* Parsing context */
  4042. Vdbe v; /* The prepared stmt under constructions */
  4043. SrcList_item pTabItem; /* FROM clause term being coded */
  4044. int addrBrk; /* Jump here to break out of the loop */
  4045. int addrCont; /* Jump here to continue with next cycle */
  4046. int iRowidReg = 0; /* Rowid is stored in this register, if not zero */
  4047. int iReleaseReg = 0; /* Temp register to free before returning */
  4048. pParse = pWInfo.pParse;
  4049. v = pParse.pVdbe;
  4050. pWC = pWInfo.pWC;
  4051. pLevel = pWInfo.a[iLevel];
  4052. pTabItem = pWInfo.pTabList.a[pLevel.iFrom];
  4053. iCur = pTabItem.iCursor;
  4054. bRev = ( pLevel.plan.wsFlags & WHERE_REVERSE ) != 0 ? 1 : 0;
  4055. omitTable = ( ( pLevel.plan.wsFlags & WHERE_IDX_ONLY ) != 0
  4056. && ( wctrlFlags & WHERE_FORCE_TABLE ) == 0 ) ? 1 : 0;
  4057. /* Create labels for the "break" and "continue" instructions
  4058. ** for the current loop. Jump to addrBrk to break out of a loop.
  4059. ** Jump to cont to go immediately to the next iteration of the
  4060. ** loop.
  4061. **
  4062. ** When there is an IN operator, we also have a "addrNxt" label that
  4063. ** means to continue with the next IN value combination. When
  4064. ** there are no IN operators in the constraints, the "addrNxt" label
  4065. ** is the same as "addrBrk".
  4066. */
  4067. addrBrk = pLevel.addrBrk = pLevel.addrNxt = sqlite3VdbeMakeLabel( v );
  4068. addrCont = pLevel.addrCont = sqlite3VdbeMakeLabel( v );
  4069. /* If this is the right table of a LEFT OUTER JOIN, allocate and
  4070. ** initialize a memory cell that records if this table matches any
  4071. ** row of the left table of the join.
  4072. */
  4073. if ( pLevel.iFrom > 0 && ( pTabItem.jointype & JT_LEFT ) != 0 )// Check value of pTabItem[0].jointype
  4074. {
  4075. pLevel.iLeftJoin = ++pParse.nMem;
  4076. sqlite3VdbeAddOp2( v, OP_Integer, 0, pLevel.iLeftJoin );
  4077. #if SQLITE_DEBUG
  4078. VdbeComment( v, "init LEFT JOIN no-match flag" );
  4079. #endif
  4080. }
  4081. #if !SQLITE_OMIT_VIRTUALTABLE
  4082. if ( ( pLevel.plan.wsFlags & WHERE_VIRTUALTABLE ) != 0 )
  4083. {
  4084. /* Case 0: The table is a virtual-table. Use the VFilter and VNext
  4085. ** to access the data.
  4086. */
  4087. int iReg; /* P3 Value for OP_VFilter */
  4088. sqlite3_index_info pVtabIdx = pLevel.plan.u.pVtabIdx;
  4089. int nConstraint = pVtabIdx.nConstraint;
  4090. sqlite3_index_constraint_usage[] aUsage = pVtabIdx.aConstraintUsage;
  4091. sqlite3_index_constraint[] aConstraint = pVtabIdx.aConstraint;
  4092. sqlite3ExprCachePush( pParse );
  4093. iReg = sqlite3GetTempRange( pParse, nConstraint + 2 );
  4094. for ( j = 1; j <= nConstraint; j++ )
  4095. {
  4096. for ( k = 0; k < nConstraint; k++ )
  4097. {
  4098. if ( aUsage[k].argvIndex == j )
  4099. {
  4100. int iTerm = aConstraint[k].iTermOffset;
  4101. sqlite3ExprCode( pParse, pWC.a[iTerm].pExpr.pRight, iReg + j + 1 );
  4102. break;
  4103. }
  4104. }
  4105. if ( k == nConstraint )
  4106. break;
  4107. }
  4108. sqlite3VdbeAddOp2( v, OP_Integer, pVtabIdx.idxNum, iReg );
  4109. sqlite3VdbeAddOp2( v, OP_Integer, j - 1, iReg + 1 );
  4110. sqlite3VdbeAddOp4( v, OP_VFilter, iCur, addrBrk, iReg, pVtabIdx.idxStr,
  4111. pVtabIdx.needToFreeIdxStr != 0 ? P4_MPRINTF : P4_STATIC );
  4112. pVtabIdx.needToFreeIdxStr = 0;
  4113. for ( j = 0; j < nConstraint; j++ )
  4114. {
  4115. if ( aUsage[j].omit != false )
  4116. {
  4117. int iTerm = aConstraint[j].iTermOffset;
  4118. disableTerm( pLevel, pWC.a[iTerm] );
  4119. }
  4120. }
  4121. pLevel.op = OP_VNext;
  4122. pLevel.p1 = iCur;
  4123. pLevel.p2 = sqlite3VdbeCurrentAddr( v );
  4124. sqlite3ReleaseTempRange( pParse, iReg, nConstraint + 2 );
  4125. sqlite3ExprCachePop( pParse, 1 );
  4126. }
  4127. else
  4128. #endif //* SQLITE_OMIT_VIRTUALTABLE */
  4129. if ( ( pLevel.plan.wsFlags & WHERE_ROWID_EQ ) != 0 )
  4130. {
  4131. /* Case 1: We can directly reference a single row using an
  4132. ** equality comparison against the ROWID field. Or
  4133. ** we reference multiple rows using a "rowid IN (...)"
  4134. ** construct.
  4135. */
  4136. iReleaseReg = sqlite3GetTempReg( pParse );
  4137. pTerm = findTerm( pWC, iCur, -1, notReady, WO_EQ | WO_IN, null );
  4138. Debug.Assert( pTerm != null );
  4139. Debug.Assert( pTerm.pExpr != null );
  4140. Debug.Assert( pTerm.leftCursor == iCur );
  4141. Debug.Assert( omitTable == 0 );
  4142. testcase( pTerm.wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
  4143. iRowidReg = codeEqualityTerm( pParse, pTerm, pLevel, iReleaseReg );
  4144. addrNxt = pLevel.addrNxt;
  4145. sqlite3VdbeAddOp2( v, OP_MustBeInt, iRowidReg, addrNxt );
  4146. sqlite3VdbeAddOp3( v, OP_NotExists, iCur, addrNxt, iRowidReg );
  4147. sqlite3ExprCacheStore( pParse, iCur, -1, iRowidReg );
  4148. #if SQLITE_DEBUG
  4149. VdbeComment( v, "pk" );
  4150. #endif
  4151. pLevel.op = OP_Noop;
  4152. }
  4153. else if ( ( pLevel.plan.wsFlags & WHERE_ROWID_RANGE ) != 0 )
  4154. {
  4155. /* Case 2: We have an inequality comparison against the ROWID field.
  4156. */
  4157. int testOp = OP_Noop;
  4158. int start;
  4159. int memEndValue = 0;
  4160. WhereTerm pStart, pEnd;
  4161. Debug.Assert( omitTable == 0 );
  4162. pStart = findTerm( pWC, iCur, -1, notReady, WO_GT | WO_GE, null );
  4163. pEnd = findTerm( pWC, iCur, -1, notReady, WO_LT | WO_LE, null );
  4164. if ( bRev != 0 )
  4165. {
  4166. pTerm = pStart;
  4167. pStart = pEnd;
  4168. pEnd = pTerm;
  4169. }
  4170. if ( pStart != null )
  4171. {
  4172. Expr pX; /* The expression that defines the start bound */
  4173. int r1, rTemp = 0; /* Registers for holding the start boundary */
  4174. /* The following constant maps TK_xx codes into corresponding
  4175. ** seek opcodes. It depends on a particular ordering of TK_xx
  4176. */
  4177. u8[] aMoveOp = new u8[]{
  4178. /* TK_GT */ OP_SeekGt,
  4179. /* TK_LE */ OP_SeekLe,
  4180. /* TK_LT */ OP_SeekLt,
  4181. /* TK_GE */ OP_SeekGe
  4182. };
  4183. Debug.Assert( TK_LE == TK_GT + 1 ); /* Make sure the ordering.. */
  4184. Debug.Assert( TK_LT == TK_GT + 2 ); /* ... of the TK_xx values... */
  4185. Debug.Assert( TK_GE == TK_GT + 3 ); /* ... is correcct. */
  4186. testcase( pStart.wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
  4187. pX = pStart.pExpr;
  4188. Debug.Assert( pX != null );
  4189. Debug.Assert( pStart.leftCursor == iCur );
  4190. r1 = sqlite3ExprCodeTemp( pParse, pX.pRight, ref rTemp );
  4191. sqlite3VdbeAddOp3( v, aMoveOp[pX.op - TK_GT], iCur, addrBrk, r1 );
  4192. #if SQLITE_DEBUG
  4193. VdbeComment( v, "pk" );
  4194. #endif
  4195. sqlite3ExprCacheAffinityChange( pParse, r1, 1 );
  4196. sqlite3ReleaseTempReg( pParse, rTemp );
  4197. disableTerm( pLevel, pStart );
  4198. }
  4199. else
  4200. {
  4201. sqlite3VdbeAddOp2( v, bRev != 0 ? OP_Last : OP_Rewind, iCur, addrBrk );
  4202. }
  4203. if ( pEnd != null )
  4204. {
  4205. Expr pX;
  4206. pX = pEnd.pExpr;
  4207. Debug.Assert( pX != null );
  4208. Debug.Assert( pEnd.leftCursor == iCur );
  4209. testcase( pEnd.wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
  4210. memEndValue = ++pParse.nMem;
  4211. sqlite3ExprCode( pParse, pX.pRight, memEndValue );
  4212. if ( pX.op == TK_LT || pX.op == TK_GT )
  4213. {
  4214. testOp = bRev != 0 ? OP_Le : OP_Ge;
  4215. }
  4216. else
  4217. {
  4218. testOp = bRev != 0 ? OP_Lt : OP_Gt;
  4219. }
  4220. disableTerm( pLevel, pEnd );
  4221. }
  4222. start = sqlite3VdbeCurrentAddr( v );
  4223. pLevel.op = (u8)( bRev != 0 ? OP_Prev : OP_Next );
  4224. pLevel.p1 = iCur;
  4225. pLevel.p2 = start;
  4226. if ( pStart == null && pEnd == null )
  4227. {
  4228. pLevel.p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
  4229. }
  4230. else
  4231. {
  4232. Debug.Assert( pLevel.p5 == 0 );
  4233. }
  4234. if ( testOp != OP_Noop )
  4235. {
  4236. iRowidReg = iReleaseReg = sqlite3GetTempReg( pParse );
  4237. sqlite3VdbeAddOp2( v, OP_Rowid, iCur, iRowidReg );
  4238. sqlite3ExprCacheStore( pParse, iCur, -1, iRowidReg );
  4239. sqlite3VdbeAddOp3( v, testOp, memEndValue, addrBrk, iRowidReg );
  4240. sqlite3VdbeChangeP5( v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL );
  4241. }
  4242. }
  4243. else if ( ( pLevel.plan.wsFlags & ( WHERE_COLUMN_RANGE | WHERE_COLUMN_EQ ) ) != 0 )
  4244. {
  4245. /* Case 3: A scan using an index.
  4246. **
  4247. ** The WHERE clause may contain zero or more equality
  4248. ** terms ("==" or "IN" operators) that refer to the N
  4249. ** left-most columns of the index. It may also contain
  4250. ** inequality constraints (>, <, >= or <=) on the indexed
  4251. ** column that immediately follows the N equalities. Only
  4252. ** the right-most column can be an inequality - the rest must
  4253. ** use the "==" and "IN" operators. For example, if the
  4254. ** index is on (x,y,z), then the following clauses are all
  4255. ** optimized:
  4256. **
  4257. ** x=5
  4258. ** x=5 AND y=10
  4259. ** x=5 AND y<10
  4260. ** x=5 AND y>5 AND y<10
  4261. ** x=5 AND y=5 AND z<=10
  4262. **
  4263. ** The z<10 term of the following cannot be used, only
  4264. ** the x=5 term:
  4265. **
  4266. ** x=5 AND z<10
  4267. **
  4268. ** N may be zero if there are inequality constraints.
  4269. ** If there are no inequality constraints, then N is at
  4270. ** least one.
  4271. **
  4272. ** This case is also used when there are no WHERE clause
  4273. ** constraints but an index is selected anyway, in order
  4274. ** to force the output order to conform to an ORDER BY.
  4275. */
  4276. u8[] aStartOp = new u8[] {
  4277. 0,
  4278. 0,
  4279. OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */
  4280. OP_Last, /* 3: (!start_constraints && startEq && bRev) */
  4281. OP_SeekGt, /* 4: (start_constraints && !startEq && !bRev) */
  4282. OP_SeekLt, /* 5: (start_constraints && !startEq && bRev) */
  4283. OP_SeekGe, /* 6: (start_constraints && startEq && !bRev) */
  4284. OP_SeekLe /* 7: (start_constraints && startEq && bRev) */
  4285. };
  4286. u8[] aEndOp = new u8[] {
  4287. OP_Noop, /* 0: (!end_constraints) */
  4288. OP_IdxGE, /* 1: (end_constraints && !bRev) */
  4289. OP_IdxLT /* 2: (end_constraints && bRev) */
  4290. };
  4291. int nEq = (int)pLevel.plan.nEq; /* Number of == or IN terms */
  4292. int isMinQuery = 0; /* If this is an optimized SELECT min(x).. */
  4293. int regBase; /* Base register holding constraint values */
  4294. int r1; /* Temp register */
  4295. WhereTerm pRangeStart = null; /* Inequality constraint at range start */
  4296. WhereTerm pRangeEnd = null; /* Inequality constraint at range end */
  4297. int startEq; /* True if range start uses ==, >= or <= */
  4298. int endEq; /* True if range end uses ==, >= or <= */
  4299. int start_constraints; /* Start of range is constrained */
  4300. int nConstraint; /* Number of constraint terms */
  4301. Index pIdx; /* The index we will be using */
  4302. int iIdxCur; /* The VDBE cursor for the index */
  4303. int nExtraReg = 0; /* Number of extra registers needed */
  4304. int op; /* Instruction opcode */
  4305. StringBuilder zStartAff = new StringBuilder( "" );
  4306. ;/* Affinity for start of range constraint */
  4307. StringBuilder zEndAff; /* Affinity for end of range constraint */
  4308. pIdx = pLevel.plan.u.pIdx;
  4309. iIdxCur = pLevel.iIdxCur;
  4310. k = pIdx.aiColumn[nEq]; /* Column for inequality constraints */
  4311. /* If this loop satisfies a sort order (pOrderBy) request that
  4312. ** was pDebug.Assed to this function to implement a "SELECT min(x) ..."
  4313. ** query, then the caller will only allow the loop to run for
  4314. ** a single iteration. This means that the first row returned
  4315. ** should not have a NULL value stored in 'x'. If column 'x' is
  4316. ** the first one after the nEq equality constraints in the index,
  4317. ** this requires some special handling.
  4318. */
  4319. if ( ( wctrlFlags & WHERE_ORDERBY_MIN ) != 0
  4320. && ( ( pLevel.plan.wsFlags & WHERE_ORDERBY ) != 0 )
  4321. && ( pIdx.nColumn > nEq )
  4322. )
  4323. {
  4324. /* Debug.Assert( pOrderBy.nExpr==1 ); */
  4325. /* Debug.Assert( pOrderBy.a[0].pExpr.iColumn==pIdx.aiColumn[nEq] ); */
  4326. isMinQuery = 1;
  4327. nExtraReg = 1;
  4328. }
  4329. /* Find any inequality constraint terms for the start and end
  4330. ** of the range.
  4331. */
  4332. if ( ( pLevel.plan.wsFlags & WHERE_TOP_LIMIT ) != 0 )
  4333. {
  4334. pRangeEnd = findTerm( pWC, iCur, k, notReady, ( WO_LT | WO_LE ), pIdx );
  4335. nExtraReg = 1;
  4336. }
  4337. if ( ( pLevel.plan.wsFlags & WHERE_BTM_LIMIT ) != 0 )
  4338. {
  4339. pRangeStart = findTerm( pWC, iCur, k, notReady, ( WO_GT | WO_GE ), pIdx );
  4340. nExtraReg = 1;
  4341. }
  4342. /* Generate code to evaluate all constraint terms using == or IN
  4343. ** and store the values of those terms in an array of registers
  4344. ** starting at regBase.
  4345. */
  4346. regBase = codeAllEqualityTerms(
  4347. pParse, pLevel, pWC, notReady, nExtraReg, out zStartAff
  4348. );
  4349. zEndAff = new StringBuilder( zStartAff.ToString() );//sqlite3DbStrDup(pParse.db, zStartAff);
  4350. addrNxt = pLevel.addrNxt;
  4351. /* If we are doing a reverse order scan on an ascending index, or
  4352. ** a forward order scan on a descending index, interchange the
  4353. ** start and end terms (pRangeStart and pRangeEnd).
  4354. */
  4355. if ( nEq < pIdx.nColumn && bRev == ( pIdx.aSortOrder[nEq] == SQLITE_SO_ASC ? 1 : 0 ) )
  4356. {
  4357. SWAP( ref pRangeEnd, ref pRangeStart );
  4358. }
  4359. testcase( pRangeStart != null && ( pRangeStart.eOperator & WO_LE ) != 0 );
  4360. testcase( pRangeStart != null && ( pRangeStart.eOperator & WO_GE ) != 0 );
  4361. testcase( pRangeEnd != null && ( pRangeEnd.eOperator & WO_LE ) != 0 );
  4362. testcase( pRangeEnd != null && ( pRangeEnd.eOperator & WO_GE ) != 0 );
  4363. startEq = ( null == pRangeStart || ( pRangeStart.eOperator & ( WO_LE | WO_GE ) ) != 0 ) ? 1 : 0;
  4364. endEq = ( null == pRangeEnd || ( pRangeEnd.eOperator & ( WO_LE | WO_GE ) ) != 0 ) ? 1 : 0;
  4365. start_constraints = ( pRangeStart != null || nEq > 0 ) ? 1 : 0;
  4366. /* Seek the index cursor to the start of the range. */
  4367. nConstraint = nEq;
  4368. if ( pRangeStart != null )
  4369. {
  4370. Expr pRight = pRangeStart.pExpr.pRight;
  4371. sqlite3ExprCode( pParse, pRight, regBase + nEq );
  4372. if ( ( pRangeStart.wtFlags & TERM_VNULL ) == 0 )
  4373. {
  4374. sqlite3ExprCodeIsNullJump( v, pRight, regBase + nEq, addrNxt );
  4375. }
  4376. if ( zStartAff.Length != 0 )
  4377. {
  4378. if ( sqlite3CompareAffinity( pRight, zStartAff[nEq] ) == SQLITE_AFF_NONE )
  4379. {
  4380. /* Since the comparison is to be performed with no conversions
  4381. ** applied to the operands, set the affinity to apply to pRight to
  4382. ** SQLITE_AFF_NONE. */
  4383. zStartAff[nEq] = SQLITE_AFF_NONE;
  4384. }
  4385. if ( ( sqlite3ExprNeedsNoAffinityChange( pRight, zStartAff[nEq] ) ) != 0 )
  4386. {
  4387. zStartAff[nEq] = SQLITE_AFF_NONE;
  4388. }
  4389. }
  4390. nConstraint++;
  4391. testcase( pRangeStart.wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
  4392. }
  4393. else if ( isMinQuery != 0 )
  4394. {
  4395. sqlite3VdbeAddOp2( v, OP_Null, 0, regBase + nEq );
  4396. nConstraint++;
  4397. startEq = 0;
  4398. start_constraints = 1;
  4399. }
  4400. codeApplyAffinity( pParse, regBase, nConstraint, zStartAff.ToString() );
  4401. op = aStartOp[( start_constraints << 2 ) + ( startEq << 1 ) + bRev];
  4402. Debug.Assert( op != 0 );
  4403. testcase( op == OP_Rewind );
  4404. testcase( op == OP_Last );
  4405. testcase( op == OP_SeekGt );
  4406. testcase( op == OP_SeekGe );
  4407. testcase( op == OP_SeekLe );
  4408. testcase( op == OP_SeekLt );
  4409. sqlite3VdbeAddOp4Int( v, op, iIdxCur, addrNxt, regBase, nConstraint );
  4410. /* Load the value for the inequality constraint at the end of the
  4411. ** range (if any).
  4412. */
  4413. nConstraint = nEq;
  4414. if ( pRangeEnd != null )
  4415. {
  4416. Expr pRight = pRangeEnd.pExpr.pRight;
  4417. sqlite3ExprCacheRemove( pParse, regBase + nEq, 1 );
  4418. sqlite3ExprCode( pParse, pRight, regBase + nEq );
  4419. if ( ( pRangeEnd.wtFlags & TERM_VNULL ) == 0 )
  4420. {
  4421. sqlite3ExprCodeIsNullJump( v, pRight, regBase + nEq, addrNxt );
  4422. }
  4423. if ( zEndAff.Length > 0 )
  4424. {
  4425. if ( sqlite3CompareAffinity( pRight, zEndAff[nEq] ) == SQLITE_AFF_NONE )
  4426. {
  4427. /* Since the comparison is to be performed with no conversions
  4428. ** applied to the operands, set the affinity to apply to pRight to
  4429. ** SQLITE_AFF_NONE. */
  4430. zEndAff[nEq] = SQLITE_AFF_NONE;
  4431. }
  4432. if ( ( sqlite3ExprNeedsNoAffinityChange( pRight, zEndAff[nEq] ) ) != 0 )
  4433. {
  4434. zEndAff[nEq] = SQLITE_AFF_NONE;
  4435. }
  4436. }
  4437. codeApplyAffinity( pParse, regBase, nEq + 1, zEndAff.ToString() );
  4438. nConstraint++;
  4439. testcase( pRangeEnd.wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
  4440. }
  4441. sqlite3DbFree( pParse.db, ref zStartAff );
  4442. sqlite3DbFree( pParse.db, ref zEndAff );
  4443. /* Top of the loop body */
  4444. pLevel.p2 = sqlite3VdbeCurrentAddr( v );
  4445. /* Check if the index cursor is past the end of the range. */
  4446. op = aEndOp[( ( pRangeEnd != null || nEq != 0 ) ? 1 : 0 ) * ( 1 + bRev )];
  4447. testcase( op == OP_Noop );
  4448. testcase( op == OP_IdxGE );
  4449. testcase( op == OP_IdxLT );
  4450. if ( op != OP_Noop )
  4451. {
  4452. sqlite3VdbeAddOp4Int( v, op, iIdxCur, addrNxt, regBase, nConstraint );
  4453. sqlite3VdbeChangeP5( v, (u8)( endEq != bRev ? 1 : 0 ) );
  4454. }
  4455. /* If there are inequality constraints, check that the value
  4456. ** of the table column that the inequality contrains is not NULL.
  4457. ** If it is, jump to the next iteration of the loop.
  4458. */
  4459. r1 = sqlite3GetTempReg( pParse );
  4460. testcase( pLevel.plan.wsFlags & WHERE_BTM_LIMIT );
  4461. testcase( pLevel.plan.wsFlags & WHERE_TOP_LIMIT );
  4462. if ( ( pLevel.plan.wsFlags & ( WHERE_BTM_LIMIT | WHERE_TOP_LIMIT ) ) != 0 )
  4463. {
  4464. sqlite3VdbeAddOp3( v, OP_Column, iIdxCur, nEq, r1 );
  4465. sqlite3VdbeAddOp2( v, OP_IsNull, r1, addrCont );
  4466. }
  4467. sqlite3ReleaseTempReg( pParse, r1 );
  4468. /* Seek the table cursor, if required */
  4469. disableTerm( pLevel, pRangeStart );
  4470. disableTerm( pLevel, pRangeEnd );
  4471. if ( 0 == omitTable )
  4472. {
  4473. iRowidReg = iReleaseReg = sqlite3GetTempReg( pParse );
  4474. sqlite3VdbeAddOp2( v, OP_IdxRowid, iIdxCur, iRowidReg );
  4475. sqlite3ExprCacheStore( pParse, iCur, -1, iRowidReg );
  4476. sqlite3VdbeAddOp2( v, OP_Seek, iCur, iRowidReg ); /* Deferred seek */
  4477. }
  4478. /* Record the instruction used to terminate the loop. Disable
  4479. ** WHERE clause terms made redundant by the index range scan.
  4480. */
  4481. if ( ( pLevel.plan.wsFlags & WHERE_UNIQUE ) != 0 )
  4482. {
  4483. pLevel.op = OP_Noop;
  4484. }
  4485. else if ( bRev != 0 )
  4486. {
  4487. pLevel.op = OP_Prev;
  4488. }
  4489. else
  4490. {
  4491. pLevel.op = OP_Next;
  4492. }
  4493. pLevel.p1 = iIdxCur;
  4494. }
  4495. else
  4496. #if !SQLITE_OMIT_OR_OPTIMIZATION
  4497. if ( ( pLevel.plan.wsFlags & WHERE_MULTI_OR ) != 0 )
  4498. {
  4499. /* Case 4: Two or more separately indexed terms connected by OR
  4500. **
  4501. ** Example:
  4502. **
  4503. ** CREATE TABLE t1(a,b,c,d);
  4504. ** CREATE INDEX i1 ON t1(a);
  4505. ** CREATE INDEX i2 ON t1(b);
  4506. ** CREATE INDEX i3 ON t1(c);
  4507. **
  4508. ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
  4509. **
  4510. ** In the example, there are three indexed terms connected by OR.
  4511. ** The top of the loop looks like this:
  4512. **
  4513. ** Null 1 # Zero the rowset in reg 1
  4514. **
  4515. ** Then, for each indexed term, the following. The arguments to
  4516. ** RowSetTest are such that the rowid of the current row is inserted
  4517. ** into the RowSet. If it is already present, control skips the
  4518. ** Gosub opcode and jumps straight to the code generated by WhereEnd().
  4519. **
  4520. ** sqlite3WhereBegin(<term>)
  4521. ** RowSetTest # Insert rowid into rowset
  4522. ** Gosub 2 A
  4523. ** sqlite3WhereEnd()
  4524. **
  4525. ** Following the above, code to terminate the loop. Label A, the target
  4526. ** of the Gosub above, jumps to the instruction right after the Goto.
  4527. **
  4528. ** Null 1 # Zero the rowset in reg 1
  4529. ** Goto B # The loop is finished.
  4530. **
  4531. ** A: <loop body> # Return data, whatever.
  4532. **
  4533. ** Return 2 # Jump back to the Gosub
  4534. **
  4535. ** B: <after the loop>
  4536. **
  4537. */
  4538. WhereClause pOrWc; /* The OR-clause broken out into subterms */
  4539. SrcList pOrTab; /* Shortened table list or OR-clause generation */
  4540. int regReturn = ++pParse.nMem; /* Register used with OP_Gosub */
  4541. int regRowset = 0; /* Register for RowSet object */
  4542. int regRowid = 0; /* Register holding rowid */
  4543. int iLoopBody = sqlite3VdbeMakeLabel( v );/* Start of loop body */
  4544. int iRetInit; /* Address of regReturn init */
  4545. int untestedTerms = 0; /* Some terms not completely tested */
  4546. int ii;
  4547. pTerm = pLevel.plan.u.pTerm;
  4548. Debug.Assert( pTerm != null );
  4549. Debug.Assert( pTerm.eOperator == WO_OR );
  4550. Debug.Assert( ( pTerm.wtFlags & TERM_ORINFO ) != 0 );
  4551. pOrWc = pTerm.u.pOrInfo.wc;
  4552. pLevel.op = OP_Return;
  4553. pLevel.p1 = regReturn;
  4554. /* Set up a new SrcList in pOrTab containing the table being scanned
  4555. ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
  4556. ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
  4557. */
  4558. if ( pWInfo.nLevel > 1 )
  4559. {
  4560. int nNotReady; /* The number of notReady tables */
  4561. SrcList_item[] origSrc; /* Original list of tables */
  4562. nNotReady = pWInfo.nLevel - iLevel - 1;
  4563. //sqlite3StackAllocRaw(pParse.db,
  4564. //sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab.a[0]));
  4565. pOrTab = new SrcList();
  4566. pOrTab.a = new SrcList_item[nNotReady + 1];
  4567. //if( pOrTab==0 ) return notReady;
  4568. pOrTab.nAlloc = (i16)( nNotReady + 1 );
  4569. pOrTab.nSrc = pOrTab.nAlloc;
  4570. pOrTab.a[0] = pTabItem;//memcpy(pOrTab.a, pTabItem, sizeof(*pTabItem));
  4571. origSrc = pWInfo.pTabList.a;
  4572. for ( k = 1; k <= nNotReady; k++ )
  4573. {
  4574. pOrTab.a[k] = origSrc[pWInfo.a[iLevel + k].iFrom];// memcpy(&pOrTab.a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab.a[k]));
  4575. }
  4576. }
  4577. else
  4578. {
  4579. pOrTab = pWInfo.pTabList;
  4580. }
  4581. /* Initialize the rowset register to contain NULL. An SQL NULL is
  4582. ** equivalent to an empty rowset.
  4583. **
  4584. ** Also initialize regReturn to contain the address of the instruction
  4585. ** immediately following the OP_Return at the bottom of the loop. This
  4586. ** is required in a few obscure LEFT JOIN cases where control jumps
  4587. ** over the top of the loop into the body of it. In this case the
  4588. ** correct response for the end-of-loop code (the OP_Return) is to
  4589. ** fall through to the next instruction, just as an OP_Next does if
  4590. ** called on an uninitialized cursor.
  4591. */
  4592. if ( ( wctrlFlags & WHERE_DUPLICATES_OK ) == 0 )
  4593. {
  4594. regRowset = ++pParse.nMem;
  4595. regRowid = ++pParse.nMem;
  4596. sqlite3VdbeAddOp2( v, OP_Null, 0, regRowset );
  4597. }
  4598. iRetInit = sqlite3VdbeAddOp2( v, OP_Integer, 0, regReturn );
  4599. for ( ii = 0; ii < pOrWc.nTerm; ii++ )
  4600. {
  4601. WhereTerm pOrTerm = pOrWc.a[ii];
  4602. if ( pOrTerm.leftCursor == iCur || pOrTerm.eOperator == WO_AND )
  4603. {
  4604. WhereInfo pSubWInfo; /* Info for single OR-term scan */
  4605. /* Loop through table entries that match term pOrTerm. */
  4606. ExprList elDummy = null;
  4607. pSubWInfo = sqlite3WhereBegin( pParse, pOrTab, pOrTerm.pExpr, ref elDummy,
  4608. WHERE_OMIT_OPEN | WHERE_OMIT_CLOSE |
  4609. WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY );
  4610. if ( pSubWInfo != null )
  4611. {
  4612. explainOneScan(
  4613. pParse, pOrTab, pSubWInfo.a[0], iLevel, pLevel.iFrom, 0
  4614. );
  4615. if ( ( wctrlFlags & WHERE_DUPLICATES_OK ) == 0 )
  4616. {
  4617. int iSet = ( ( ii == pOrWc.nTerm - 1 ) ? -1 : ii );
  4618. int r;
  4619. r = sqlite3ExprCodeGetColumn( pParse, pTabItem.pTab, -1, iCur,
  4620. regRowid );
  4621. sqlite3VdbeAddOp4Int( v, OP_RowSetTest, regRowset,
  4622. sqlite3VdbeCurrentAddr( v ) + 2, r, iSet );
  4623. }
  4624. sqlite3VdbeAddOp2( v, OP_Gosub, regReturn, iLoopBody );
  4625. /* The pSubWInfo.untestedTerms flag means that this OR term
  4626. ** contained one or more AND term from a notReady table. The
  4627. ** terms from the notReady table could not be tested and will
  4628. ** need to be tested later.
  4629. */
  4630. if ( pSubWInfo.untestedTerms != 0 )
  4631. untestedTerms = 1;
  4632. /* Finish the loop through table entries that match term pOrTerm. */
  4633. sqlite3WhereEnd( pSubWInfo );
  4634. }
  4635. }
  4636. }
  4637. sqlite3VdbeChangeP1( v, iRetInit, sqlite3VdbeCurrentAddr( v ) );
  4638. sqlite3VdbeAddOp2( v, OP_Goto, 0, pLevel.addrBrk );
  4639. sqlite3VdbeResolveLabel( v, iLoopBody );
  4640. if ( pWInfo.nLevel > 1 )
  4641. sqlite3DbFree( pParse.db, ref pOrTab );//sqlite3DbFree(pParse.db, pOrTab)
  4642. if ( 0 == untestedTerms )
  4643. disableTerm( pLevel, pTerm );
  4644. }
  4645. else
  4646. #endif //* SQLITE_OMIT_OR_OPTIMIZATION */
  4647. {
  4648. /* Case 5: There is no usable index. We must do a complete
  4649. ** scan of the entire table.
  4650. */
  4651. u8[] aStep = new u8[] { OP_Next, OP_Prev };
  4652. u8[] aStart = new u8[] { OP_Rewind, OP_Last };
  4653. Debug.Assert( bRev == 0 || bRev == 1 );
  4654. Debug.Assert( omitTable == 0 );
  4655. pLevel.op = aStep[bRev];
  4656. pLevel.p1 = iCur;
  4657. pLevel.p2 = 1 + sqlite3VdbeAddOp2( v, aStart[bRev], iCur, addrBrk );
  4658. pLevel.p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
  4659. }
  4660. notReady &= ~getMask( pWC.pMaskSet, iCur );
  4661. /* Insert code to test every subexpression that can be completely
  4662. ** computed using the current set of tables.
  4663. **
  4664. ** IMPLEMENTATION-OF: R-49525-50935 Terms that cannot be satisfied through
  4665. ** the use of indices become tests that are evaluated against each row of
  4666. ** the relevant input tables.
  4667. */
  4668. for ( j = pWC.nTerm; j > 0; j-- )//, pTerm++)
  4669. {
  4670. pTerm = pWC.a[pWC.nTerm - j];
  4671. Expr pE;
  4672. testcase( pTerm.wtFlags & TERM_VIRTUAL ); /* IMP: R-30575-11662 */
  4673. testcase( pTerm.wtFlags & TERM_CODED );
  4674. if ( ( pTerm.wtFlags & ( TERM_VIRTUAL | TERM_CODED ) ) != 0 )
  4675. continue;
  4676. if ( ( pTerm.prereqAll & notReady ) != 0 )
  4677. {
  4678. testcase( pWInfo.untestedTerms == 0
  4679. && ( pWInfo.wctrlFlags & WHERE_ONETABLE_ONLY ) != 0 );
  4680. pWInfo.untestedTerms = 1;
  4681. continue;
  4682. }
  4683. pE = pTerm.pExpr;
  4684. Debug.Assert( pE != null );
  4685. if ( pLevel.iLeftJoin != 0 && !( ( pE.flags & EP_FromJoin ) == EP_FromJoin ) )// !ExprHasProperty(pE, EP_FromJoin) ){
  4686. {
  4687. continue;
  4688. }
  4689. sqlite3ExprIfFalse( pParse, pE, addrCont, SQLITE_JUMPIFNULL );
  4690. pTerm.wtFlags |= TERM_CODED;
  4691. }
  4692. /* For a LEFT OUTER JOIN, generate code that will record the fact that
  4693. ** at least one row of the right table has matched the left table.
  4694. */
  4695. if ( pLevel.iLeftJoin != 0 )
  4696. {
  4697. pLevel.addrFirst = sqlite3VdbeCurrentAddr( v );
  4698. sqlite3VdbeAddOp2( v, OP_Integer, 1, pLevel.iLeftJoin );
  4699. #if SQLITE_DEBUG
  4700. VdbeComment( v, "record LEFT JOIN hit" );
  4701. #endif
  4702. sqlite3ExprCacheClear( pParse );
  4703. for ( j = 0; j < pWC.nTerm; j++ )//, pTerm++)
  4704. {
  4705. pTerm = pWC.a[j];
  4706. testcase( pTerm.wtFlags & TERM_VIRTUAL ); /* IMP: R-30575-11662 */
  4707. testcase( pTerm.wtFlags & TERM_CODED );
  4708. if ( ( pTerm.wtFlags & ( TERM_VIRTUAL | TERM_CODED ) ) != 0 )
  4709. continue;
  4710. if ( ( pTerm.prereqAll & notReady ) != 0 )
  4711. {
  4712. Debug.Assert( pWInfo.untestedTerms != 0 );
  4713. continue;
  4714. }
  4715. Debug.Assert( pTerm.pExpr != null );
  4716. sqlite3ExprIfFalse( pParse, pTerm.pExpr, addrCont, SQLITE_JUMPIFNULL );
  4717. pTerm.wtFlags |= TERM_CODED;
  4718. }
  4719. }
  4720. sqlite3ReleaseTempReg( pParse, iReleaseReg );
  4721. return notReady;
  4722. }
  4723. #if (SQLITE_TEST)
  4724. /*
  4725. ** The following variable holds a text description of query plan generated
  4726. ** by the most recent call to sqlite3WhereBegin(). Each call to WhereBegin
  4727. ** overwrites the previous. This information is used for testing and
  4728. ** analysis only.
  4729. */
  4730. #if !TCLSH
  4731. //char sqlite3_query_plan[BMS*2*40]; /* Text of the join */
  4732. static StringBuilder sqlite3_query_plan;
  4733. #else
  4734. static tcl.lang.Var.SQLITE3_GETSET sqlite3_query_plan = new tcl.lang.Var.SQLITE3_GETSET( "sqlite3_query_plan" );
  4735. #endif
  4736. static int nQPlan = 0; /* Next free slow in _query_plan[] */
  4737. #endif //* SQLITE_TEST */
  4738. /*
  4739. ** Free a WhereInfo structure
  4740. */
  4741. static void whereInfoFree( sqlite3 db, WhereInfo pWInfo )
  4742. {
  4743. if ( ALWAYS( pWInfo != null ) )
  4744. {
  4745. int i;
  4746. for ( i = 0; i < pWInfo.nLevel; i++ )
  4747. {
  4748. sqlite3_index_info pInfo = pWInfo.a[i] != null ? pWInfo.a[i].pIdxInfo : null;
  4749. if ( pInfo != null )
  4750. {
  4751. /* Debug.Assert( pInfo.needToFreeIdxStr==0 || db.mallocFailed ); */
  4752. if ( pInfo.needToFreeIdxStr != 0 )
  4753. {
  4754. //sqlite3_free( ref pInfo.idxStr );
  4755. }
  4756. sqlite3DbFree( db, ref pInfo );
  4757. }
  4758. if ( pWInfo.a[i] != null && ( pWInfo.a[i].plan.wsFlags & WHERE_TEMP_INDEX ) != 0 )
  4759. {
  4760. Index pIdx = pWInfo.a[i].plan.u.pIdx;
  4761. if ( pIdx != null )
  4762. {
  4763. sqlite3DbFree( db, ref pIdx.zColAff );
  4764. sqlite3DbFree( db, ref pIdx );
  4765. }
  4766. }
  4767. }
  4768. whereClauseClear( pWInfo.pWC );
  4769. sqlite3DbFree( db, ref pWInfo );
  4770. }
  4771. }
  4772. /*
  4773. ** Generate the beginning of the loop used for WHERE clause processing.
  4774. ** The return value is a pointer to an opaque structure that contains
  4775. ** information needed to terminate the loop. Later, the calling routine
  4776. ** should invoke sqlite3WhereEnd() with the return value of this function
  4777. ** in order to complete the WHERE clause processing.
  4778. **
  4779. ** If an error occurs, this routine returns NULL.
  4780. **
  4781. ** The basic idea is to do a nested loop, one loop for each table in
  4782. ** the FROM clause of a select. (INSERT and UPDATE statements are the
  4783. ** same as a SELECT with only a single table in the FROM clause.) For
  4784. ** example, if the SQL is this:
  4785. **
  4786. ** SELECT * FROM t1, t2, t3 WHERE ...;
  4787. **
  4788. ** Then the code generated is conceptually like the following:
  4789. **
  4790. ** foreach row1 in t1 do \ Code generated
  4791. ** foreach row2 in t2 do |-- by sqlite3WhereBegin()
  4792. ** foreach row3 in t3 do /
  4793. ** ...
  4794. ** end \ Code generated
  4795. ** end |-- by sqlite3WhereEnd()
  4796. ** end /
  4797. **
  4798. ** Note that the loops might not be nested in the order in which they
  4799. ** appear in the FROM clause if a different order is better able to make
  4800. ** use of indices. Note also that when the IN operator appears in
  4801. ** the WHERE clause, it might result in additional nested loops for
  4802. ** scanning through all values on the right-hand side of the IN.
  4803. **
  4804. ** There are Btree cursors Debug.Associated with each table. t1 uses cursor
  4805. ** number pTabList.a[0].iCursor. t2 uses the cursor pTabList.a[1].iCursor.
  4806. ** And so forth. This routine generates code to open those VDBE cursors
  4807. ** and sqlite3WhereEnd() generates the code to close them.
  4808. **
  4809. ** The code that sqlite3WhereBegin() generates leaves the cursors named
  4810. ** in pTabList pointing at their appropriate entries. The [...] code
  4811. ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
  4812. ** data from the various tables of the loop.
  4813. **
  4814. ** If the WHERE clause is empty, the foreach loops must each scan their
  4815. ** entire tables. Thus a three-way join is an O(N^3) operation. But if
  4816. ** the tables have indices and there are terms in the WHERE clause that
  4817. ** refer to those indices, a complete table scan can be avoided and the
  4818. ** code will run much faster. Most of the work of this routine is checking
  4819. ** to see if there are indices that can be used to speed up the loop.
  4820. **
  4821. ** Terms of the WHERE clause are also used to limit which rows actually
  4822. ** make it to the "..." in the middle of the loop. After each "foreach",
  4823. ** terms of the WHERE clause that use only terms in that loop and outer
  4824. ** loops are evaluated and if false a jump is made around all subsequent
  4825. ** inner loops (or around the "..." if the test occurs within the inner-
  4826. ** most loop)
  4827. **
  4828. ** OUTER JOINS
  4829. **
  4830. ** An outer join of tables t1 and t2 is conceptally coded as follows:
  4831. **
  4832. ** foreach row1 in t1 do
  4833. ** flag = 0
  4834. ** foreach row2 in t2 do
  4835. ** start:
  4836. ** ...
  4837. ** flag = 1
  4838. ** end
  4839. ** if flag==null then
  4840. ** move the row2 cursor to a null row
  4841. ** goto start
  4842. ** fi
  4843. ** end
  4844. **
  4845. ** ORDER BY CLAUSE PROCESSING
  4846. **
  4847. ** ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
  4848. ** if there is one. If there is no ORDER BY clause or if this routine
  4849. ** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
  4850. **
  4851. ** If an index can be used so that the natural output order of the table
  4852. ** scan is correct for the ORDER BY clause, then that index is used and
  4853. ** ppOrderBy is set to NULL. This is an optimization that prevents an
  4854. ** unnecessary sort of the result set if an index appropriate for the
  4855. ** ORDER BY clause already exists.
  4856. **
  4857. ** If the where clause loops cannot be arranged to provide the correct
  4858. ** output order, then the ppOrderBy is unchanged.
  4859. */
  4860. static WhereInfo sqlite3WhereBegin(
  4861. Parse pParse, /* The parser context */
  4862. SrcList pTabList, /* A list of all tables to be scanned */
  4863. Expr pWhere, /* The WHERE clause */
  4864. ref ExprList ppOrderBy, /* An ORDER BY clause, or NULL */
  4865. u16 wctrlFlags /* One of the WHERE_* flags defined in sqliteInt.h */
  4866. )
  4867. {
  4868. int i; /* Loop counter */
  4869. int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
  4870. int nTabList; /* Number of elements in pTabList */
  4871. WhereInfo pWInfo; /* Will become the return value of this function */
  4872. Vdbe v = pParse.pVdbe; /* The virtual data_base engine */
  4873. Bitmask notReady; /* Cursors that are not yet positioned */
  4874. WhereMaskSet pMaskSet; /* The expression mask set */
  4875. WhereClause pWC = new WhereClause(); /* Decomposition of the WHERE clause */
  4876. SrcList_item pTabItem; /* A single entry from pTabList */
  4877. WhereLevel pLevel; /* A single level in the pWInfo list */
  4878. int iFrom; /* First unused FROM clause element */
  4879. int andFlags; /* AND-ed combination of all pWC.a[].wtFlags */
  4880. sqlite3 db; /* Data_base connection */
  4881. /* The number of tables in the FROM clause is limited by the number of
  4882. ** bits in a Bitmask
  4883. */
  4884. testcase( pTabList.nSrc == BMS );
  4885. if ( pTabList.nSrc > BMS )
  4886. {
  4887. sqlite3ErrorMsg( pParse, "at most %d tables in a join", BMS );
  4888. return null;
  4889. }
  4890. /* This function normally generates a nested loop for all tables in
  4891. ** pTabList. But if the WHERE_ONETABLE_ONLY flag is set, then we should
  4892. ** only generate code for the first table in pTabList and assume that
  4893. ** any cursors associated with subsequent tables are uninitialized.
  4894. */
  4895. nTabList = ( ( wctrlFlags & WHERE_ONETABLE_ONLY ) != 0 ) ? 1 : (int)pTabList.nSrc;
  4896. /* Allocate and initialize the WhereInfo structure that will become the
  4897. ** return value. A single allocation is used to store the WhereInfo
  4898. ** struct, the contents of WhereInfo.a[], the WhereClause structure
  4899. ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
  4900. ** field (type Bitmask) it must be aligned on an 8-byte boundary on
  4901. ** some architectures. Hence the ROUND8() below.
  4902. */
  4903. db = pParse.db;
  4904. pWInfo = new WhereInfo();
  4905. //nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
  4906. //pWInfo = sqlite3DbMallocZero( db,
  4907. // nByteWInfo +
  4908. // sizeof( WhereClause ) +
  4909. // sizeof( WhereMaskSet )
  4910. //);
  4911. pWInfo.a = new WhereLevel[pTabList.nSrc];
  4912. for ( int ai = 0; ai < pWInfo.a.Length; ai++ )
  4913. {
  4914. pWInfo.a[ai] = new WhereLevel();
  4915. }
  4916. //if ( db.mallocFailed != 0 )
  4917. //{
  4918. //sqlite3DbFree(db, pWInfo);
  4919. //pWInfo = 0;
  4920. // goto whereBeginError;
  4921. //}
  4922. pWInfo.nLevel = nTabList;
  4923. pWInfo.pParse = pParse;
  4924. pWInfo.pTabList = pTabList;
  4925. pWInfo.iBreak = sqlite3VdbeMakeLabel( v );
  4926. pWInfo.pWC = pWC = new WhereClause();// (WhereClause )((u8 )pWInfo)[nByteWInfo];
  4927. pWInfo.wctrlFlags = wctrlFlags;
  4928. pWInfo.savedNQueryLoop = pParse.nQueryLoop;
  4929. //pMaskSet = (WhereMaskSet)pWC[1];
  4930. /* Split the WHERE clause into separate subexpressions where each
  4931. ** subexpression is separated by an AND operator.
  4932. */
  4933. pMaskSet = new WhereMaskSet();//initMaskSet(pMaskSet);
  4934. whereClauseInit( pWC, pParse, pMaskSet );
  4935. sqlite3ExprCodeConstants( pParse, pWhere );
  4936. whereSplit( pWC, pWhere, TK_AND ); /* IMP: R-15842-53296 */
  4937. /* Special case: a WHERE clause that is constant. Evaluate the
  4938. ** expression and either jump over all of the code or fall thru.
  4939. */
  4940. if ( pWhere != null && ( nTabList == 0 || sqlite3ExprIsConstantNotJoin( pWhere ) != 0 ) )
  4941. {
  4942. sqlite3ExprIfFalse( pParse, pWhere, pWInfo.iBreak, SQLITE_JUMPIFNULL );
  4943. pWhere = null;
  4944. }
  4945. /* Assign a bit from the bitmask to every term in the FROM clause.
  4946. **
  4947. ** When assigning bitmask values to FROM clause cursors, it must be
  4948. ** the case that if X is the bitmask for the N-th FROM clause term then
  4949. ** the bitmask for all FROM clause terms to the left of the N-th term
  4950. ** is (X-1). An expression from the ON clause of a LEFT JOIN can use
  4951. ** its Expr.iRightJoinTable value to find the bitmask of the right table
  4952. ** of the join. Subtracting one from the right table bitmask gives a
  4953. ** bitmask for all tables to the left of the join. Knowing the bitmask
  4954. ** for all tables to the left of a left join is important. Ticket #3015.
  4955. **
  4956. ** Configure the WhereClause.vmask variable so that bits that correspond
  4957. ** to virtual table cursors are set. This is used to selectively disable
  4958. ** the OR-to-IN transformation in exprAnalyzeOrTerm(). It is not helpful
  4959. ** with virtual tables.
  4960. **
  4961. ** Note that bitmasks are created for all pTabList.nSrc tables in
  4962. ** pTabList, not just the first nTabList tables. nTabList is normally
  4963. ** equal to pTabList.nSrc but might be shortened to 1 if the
  4964. ** WHERE_ONETABLE_ONLY flag is set.
  4965. */
  4966. Debug.Assert( pWC.vmask == 0 && pMaskSet.n == 0 );
  4967. for ( i = 0; i < pTabList.nSrc; i++ )
  4968. {
  4969. createMask( pMaskSet, pTabList.a[i].iCursor );
  4970. #if !SQLITE_OMIT_VIRTUALTABLE
  4971. if ( ALWAYS( pTabList.a[i].pTab ) && IsVirtual( pTabList.a[i].pTab ) )
  4972. {
  4973. pWC.vmask |= ( (Bitmask)1 << i );
  4974. }
  4975. #endif
  4976. }
  4977. #if !NDEBUG
  4978. {
  4979. Bitmask toTheLeft = 0;
  4980. for ( i = 0; i < pTabList.nSrc; i++ )
  4981. {
  4982. Bitmask m = getMask( pMaskSet, pTabList.a[i].iCursor );
  4983. Debug.Assert( ( m - 1 ) == toTheLeft );
  4984. toTheLeft |= m;
  4985. }
  4986. }
  4987. #endif
  4988. /* Analyze all of the subexpressions. Note that exprAnalyze() might
  4989. ** add new virtual terms onto the end of the WHERE clause. We do not
  4990. ** want to analyze these virtual terms, so start analyzing at the end
  4991. ** and work forward so that the added virtual terms are never processed.
  4992. */
  4993. exprAnalyzeAll( pTabList, pWC );
  4994. //if ( db.mallocFailed != 0 )
  4995. //{
  4996. // goto whereBeginError;
  4997. //}
  4998. /* Chose the best index to use for each table in the FROM clause.
  4999. **
  5000. ** This loop fills in the following fields:
  5001. **
  5002. ** pWInfo.a[].pIdx The index to use for this level of the loop.
  5003. ** pWInfo.a[].wsFlags WHERE_xxx flags Debug.Associated with pIdx
  5004. ** pWInfo.a[].nEq The number of == and IN constraints
  5005. ** pWInfo.a[].iFrom Which term of the FROM clause is being coded
  5006. ** pWInfo.a[].iTabCur The VDBE cursor for the data_base table
  5007. ** pWInfo.a[].iIdxCur The VDBE cursor for the index
  5008. ** pWInfo.a[].pTerm When wsFlags==WO_OR, the OR-clause term
  5009. **
  5010. ** This loop also figures out the nesting order of tables in the FROM
  5011. ** clause.
  5012. */
  5013. notReady = ~(Bitmask)0;
  5014. andFlags = ~0;
  5015. #if (SQLITE_TEST) && (SQLITE_DEBUG)
  5016. WHERETRACE( "*** Optimizer Start ***\n" );
  5017. #endif
  5018. for ( i = iFrom = 0; i < nTabList; i++ )//, pLevel++ )
  5019. {
  5020. pLevel = pWInfo.a[i];
  5021. WhereCost bestPlan; /* Most efficient plan seen so far */
  5022. Index pIdx; /* Index for FROM table at pTabItem */
  5023. int j; /* For looping over FROM tables */
  5024. int bestJ = -1; /* The value of j */
  5025. Bitmask m; /* Bitmask value for j or bestJ */
  5026. int isOptimal; /* Iterator for optimal/non-optimal search */
  5027. int nUnconstrained; /* Number tables without INDEXED BY */
  5028. Bitmask notIndexed; /* Mask of tables that cannot use an index */
  5029. bestPlan = new WhereCost();// memset( &bestPlan, 0, sizeof( bestPlan ) );
  5030. bestPlan.rCost = SQLITE_BIG_DBL;
  5031. #if (SQLITE_TEST) && (SQLITE_DEBUG)
  5032. WHERETRACE( "*** Begin search for loop %d ***\n", i );
  5033. #endif
  5034. /* Loop through the remaining entries in the FROM clause to find the
  5035. ** next nested loop. The loop tests all FROM clause entries
  5036. ** either once or twice.
  5037. **
  5038. ** The first test is always performed if there are two or more entries
  5039. ** remaining and never performed if there is only one FROM clause entry
  5040. ** to choose from. The first test looks for an "optimal" scan. In
  5041. ** this context an optimal scan is one that uses the same strategy
  5042. ** for the given FROM clause entry as would be selected if the entry
  5043. ** were used as the innermost nested loop. In other words, a table
  5044. ** is chosen such that the cost of running that table cannot be reduced
  5045. ** by waiting for other tables to run first. This "optimal" test works
  5046. ** by first assuming that the FROM clause is on the inner loop and finding
  5047. ** its query plan, then checking to see if that query plan uses any
  5048. ** other FROM clause terms that are notReady. If no notReady terms are
  5049. ** used then the "optimal" query plan works.
  5050. **
  5051. ** Note that the WhereCost.nRow parameter for an optimal scan might
  5052. ** not be as small as it would be if the table really were the innermost
  5053. ** join. The nRow value can be reduced by WHERE clause constraints
  5054. ** that do not use indices. But this nRow reduction only happens if the
  5055. ** table really is the innermost join.
  5056. **
  5057. ** The second loop iteration is only performed if no optimal scan
  5058. ** strategies were found by the first iteration. This second iteration
  5059. ** is used to search for the lowest cost scan overall.
  5060. **
  5061. ** Previous versions of SQLite performed only the second iteration -
  5062. ** the next outermost loop was always that with the lowest overall
  5063. ** cost. However, this meant that SQLite could select the wrong plan
  5064. ** for scripts such as the following:
  5065. **
  5066. ** CREATE TABLE t1(a, b);
  5067. ** CREATE TABLE t2(c, d);
  5068. ** SELECT * FROM t2, t1 WHERE t2.rowid = t1.a;
  5069. **
  5070. ** The best strategy is to iterate through table t1 first. However it
  5071. ** is not possible to determine this with a simple greedy algorithm.
  5072. ** Since the cost of a linear scan through table t2 is the same
  5073. ** as the cost of a linear scan through table t1, a simple greedy
  5074. ** algorithm may choose to use t2 for the outer loop, which is a much
  5075. ** costlier approach.
  5076. */
  5077. nUnconstrained = 0;
  5078. notIndexed = 0;
  5079. for ( isOptimal = ( iFrom < nTabList - 1 ) ? 1 : 0; isOptimal >= 0 && bestJ < 0; isOptimal-- )
  5080. {
  5081. Bitmask mask; /* Mask of tables not yet ready */
  5082. for ( j = iFrom; j < nTabList; j++ )//, pTabItem++)
  5083. {
  5084. pTabItem = pTabList.a[j];
  5085. int doNotReorder; /* True if this table should not be reordered */
  5086. WhereCost sCost = new WhereCost(); /* Cost information from best[Virtual]Index() */
  5087. ExprList pOrderBy; /* ORDER BY clause for index to optimize */
  5088. doNotReorder = ( pTabItem.jointype & ( JT_LEFT | JT_CROSS ) ) != 0 ? 1 : 0;
  5089. if ( ( j != iFrom && doNotReorder != 0 ) )
  5090. break;
  5091. m = getMask( pMaskSet, pTabItem.iCursor );
  5092. if ( ( m & notReady ) == 0 )
  5093. {
  5094. if ( j == iFrom )
  5095. iFrom++;
  5096. continue;
  5097. }
  5098. mask = ( isOptimal != 0 ? m : notReady );
  5099. pOrderBy = ( ( i == 0 && ppOrderBy != null ) ? ppOrderBy : null );
  5100. if ( pTabItem.pIndex == null )
  5101. nUnconstrained++;
  5102. #if (SQLITE_TEST) && (SQLITE_DEBUG)
  5103. WHERETRACE( "=== trying table %d with isOptimal=%d ===\n",
  5104. j, isOptimal );
  5105. #endif
  5106. Debug.Assert( pTabItem.pTab != null );
  5107. #if !SQLITE_OMIT_VIRTUALTABLE
  5108. if ( IsVirtual( pTabItem.pTab ) )
  5109. {
  5110. sqlite3_index_info pp = pWInfo.a[j].pIdxInfo;
  5111. bestVirtualIndex( pParse, pWC, pTabItem, mask, notReady, pOrderBy,
  5112. ref sCost, ref pp );
  5113. }
  5114. else
  5115. #endif
  5116. {
  5117. bestBtreeIndex( pParse, pWC, pTabItem, mask, notReady, pOrderBy,
  5118. ref sCost );
  5119. }
  5120. Debug.Assert( isOptimal != 0 || ( sCost.used & notReady ) == 0 );
  5121. /* If an INDEXED BY clause is present, then the plan must use that
  5122. ** index if it uses any index at all */
  5123. Debug.Assert( pTabItem.pIndex == null
  5124. || ( sCost.plan.wsFlags & WHERE_NOT_FULLSCAN ) == 0
  5125. || sCost.plan.u.pIdx == pTabItem.pIndex );
  5126. if ( isOptimal != 0 && ( sCost.plan.wsFlags & WHERE_NOT_FULLSCAN ) == 0 )
  5127. {
  5128. notIndexed |= m;
  5129. }
  5130. /* Conditions under which this table becomes the best so far:
  5131. **
  5132. ** (1) The table must not depend on other tables that have not
  5133. ** yet run.
  5134. **
  5135. ** (2) A full-table-scan plan cannot supercede indexed plan unless
  5136. ** the full-table-scan is an "optimal" plan as defined above.
  5137. **
  5138. ** (3) All tables have an INDEXED BY clause or this table lacks an
  5139. ** INDEXED BY clause or this table uses the specific
  5140. ** index specified by its INDEXED BY clause. This rule ensures
  5141. ** that a best-so-far is always selected even if an impossible
  5142. ** combination of INDEXED BY clauses are given. The error
  5143. ** will be detected and relayed back to the application later.
  5144. ** The NEVER() comes about because rule (2) above prevents
  5145. ** An indexable full-table-scan from reaching rule (3).
  5146. **
  5147. ** (4) The plan cost must be lower than prior plans or else the
  5148. ** cost must be the same and the number of rows must be lower.
  5149. */
  5150. if ( ( sCost.used & notReady ) == 0 /* (1) */
  5151. && ( bestJ < 0 || ( notIndexed & m ) != 0 /* (2) */
  5152. || ( bestPlan.plan.wsFlags & WHERE_NOT_FULLSCAN ) == 0
  5153. || ( sCost.plan.wsFlags & WHERE_NOT_FULLSCAN ) != 0 )
  5154. && ( nUnconstrained == 0 || pTabItem.pIndex == null /* (3) */
  5155. || NEVER( ( sCost.plan.wsFlags & WHERE_NOT_FULLSCAN ) != 0 ) )
  5156. && ( bestJ < 0 || sCost.rCost < bestPlan.rCost /* (4) */
  5157. || ( sCost.rCost <= bestPlan.rCost
  5158. && sCost.plan.nRow < bestPlan.plan.nRow ) )
  5159. )
  5160. {
  5161. #if (SQLITE_TEST) && (SQLITE_DEBUG)
  5162. WHERETRACE( "=== table %d is best so far" +
  5163. " with cost=%g and nRow=%g\n",
  5164. j, sCost.rCost, sCost.plan.nRow );
  5165. #endif
  5166. bestPlan = sCost;
  5167. bestJ = j;
  5168. }
  5169. if ( doNotReorder != 0 )
  5170. break;
  5171. }
  5172. }
  5173. Debug.Assert( bestJ >= 0 );
  5174. Debug.Assert( ( notReady & getMask( pMaskSet, pTabList.a[bestJ].iCursor ) ) != 0 );
  5175. #if (SQLITE_TEST) && (SQLITE_DEBUG)
  5176. WHERETRACE( "*** Optimizer selects table %d for loop %d" +
  5177. " with cost=%g and nRow=%g\n",
  5178. bestJ, i,//pLevel-pWInfo.a,
  5179. bestPlan.rCost, bestPlan.plan.nRow );
  5180. #endif
  5181. if ( ( bestPlan.plan.wsFlags & WHERE_ORDERBY ) != 0 )
  5182. {
  5183. ppOrderBy = null;
  5184. }
  5185. andFlags = (int)( andFlags & bestPlan.plan.wsFlags );
  5186. pLevel.plan = bestPlan.plan;
  5187. testcase( bestPlan.plan.wsFlags & WHERE_INDEXED );
  5188. testcase( bestPlan.plan.wsFlags & WHERE_TEMP_INDEX );
  5189. if ( ( bestPlan.plan.wsFlags & ( WHERE_INDEXED | WHERE_TEMP_INDEX ) ) != 0 )
  5190. {
  5191. pLevel.iIdxCur = pParse.nTab++;
  5192. }
  5193. else
  5194. {
  5195. pLevel.iIdxCur = -1;
  5196. }
  5197. notReady &= ~getMask( pMaskSet, pTabList.a[bestJ].iCursor );
  5198. pLevel.iFrom = (u8)bestJ;
  5199. if ( bestPlan.plan.nRow >= (double)1 )
  5200. {
  5201. pParse.nQueryLoop *= bestPlan.plan.nRow;
  5202. }
  5203. /* Check that if the table scanned by this loop iteration had an
  5204. ** INDEXED BY clause attached to it, that the named index is being
  5205. ** used for the scan. If not, then query compilation has failed.
  5206. ** Return an error.
  5207. */
  5208. pIdx = pTabList.a[bestJ].pIndex;
  5209. if ( pIdx != null )
  5210. {
  5211. if ( ( bestPlan.plan.wsFlags & WHERE_INDEXED ) == 0 )
  5212. {
  5213. sqlite3ErrorMsg( pParse, "cannot use index: %s", pIdx.zName );
  5214. goto whereBeginError;
  5215. }
  5216. else
  5217. {
  5218. /* If an INDEXED BY clause is used, the bestIndex() function is
  5219. ** guaranteed to find the index specified in the INDEXED BY clause
  5220. ** if it find an index at all. */
  5221. Debug.Assert( bestPlan.plan.u.pIdx == pIdx );
  5222. }
  5223. }
  5224. }
  5225. #if (SQLITE_TEST) && (SQLITE_DEBUG)
  5226. WHERETRACE( "*** Optimizer Finished ***\n" );
  5227. #endif
  5228. if ( pParse.nErr != 0 /*|| db.mallocFailed != 0 */ )
  5229. {
  5230. goto whereBeginError;
  5231. }
  5232. /* If the total query only selects a single row, then the ORDER BY
  5233. ** clause is irrelevant.
  5234. */
  5235. if ( ( andFlags & WHERE_UNIQUE ) != 0 && ppOrderBy != null )
  5236. {
  5237. ppOrderBy = null;
  5238. }
  5239. /* If the caller is an UPDATE or DELETE statement that is requesting
  5240. ** to use a one-pDebug.Ass algorithm, determine if this is appropriate.
  5241. ** The one-pass algorithm only works if the WHERE clause constraints
  5242. ** the statement to update a single row.
  5243. */
  5244. Debug.Assert( ( wctrlFlags & WHERE_ONEPASS_DESIRED ) == 0 || pWInfo.nLevel == 1 );
  5245. if ( ( wctrlFlags & WHERE_ONEPASS_DESIRED ) != 0 && ( andFlags & WHERE_UNIQUE ) != 0 )
  5246. {
  5247. pWInfo.okOnePass = 1;
  5248. pWInfo.a[0].plan.wsFlags = (u32)( pWInfo.a[0].plan.wsFlags & ~WHERE_IDX_ONLY );
  5249. }
  5250. /* Open all tables in the pTabList and any indices selected for
  5251. ** searching those tables.
  5252. */
  5253. sqlite3CodeVerifySchema( pParse, -1 ); /* Insert the cookie verifier Goto */
  5254. notReady = ~(Bitmask)0;
  5255. pWInfo.nRowOut = (double)1;
  5256. for ( i = 0; i < nTabList; i++ )//, pLevel++ )
  5257. {
  5258. pLevel = pWInfo.a[i];
  5259. Table pTab; /* Table to open */
  5260. int iDb; /* Index of data_base containing table/index */
  5261. pTabItem = pTabList.a[pLevel.iFrom];
  5262. pTab = pTabItem.pTab;
  5263. pLevel.iTabCur = pTabItem.iCursor;
  5264. pWInfo.nRowOut *= pLevel.plan.nRow;
  5265. iDb = sqlite3SchemaToIndex( db, pTab.pSchema );
  5266. if ( ( pTab.tabFlags & TF_Ephemeral ) != 0 || pTab.pSelect != null )
  5267. {
  5268. /* Do nothing */
  5269. }
  5270. else
  5271. #if !SQLITE_OMIT_VIRTUALTABLE
  5272. if ( ( pLevel.plan.wsFlags & WHERE_VIRTUALTABLE ) != 0 )
  5273. {
  5274. VTable pVTab = sqlite3GetVTable( db, pTab );
  5275. int iCur = pTabItem.iCursor;
  5276. sqlite3VdbeAddOp4( v, OP_VOpen, iCur, 0, 0,
  5277. pVTab, P4_VTAB );
  5278. }
  5279. else
  5280. #endif
  5281. if ( ( pLevel.plan.wsFlags & WHERE_IDX_ONLY ) == 0
  5282. && ( wctrlFlags & WHERE_OMIT_OPEN ) == 0 )
  5283. {
  5284. int op = pWInfo.okOnePass != 0 ? OP_OpenWrite : OP_OpenRead;
  5285. sqlite3OpenTable( pParse, pTabItem.iCursor, iDb, pTab, op );
  5286. testcase( pTab.nCol == BMS - 1 );
  5287. testcase( pTab.nCol == BMS );
  5288. if ( 0 == pWInfo.okOnePass && pTab.nCol < BMS )
  5289. {
  5290. Bitmask b = pTabItem.colUsed;
  5291. int n = 0;
  5292. for ( ; b != 0; b = b >> 1, n++ )
  5293. {
  5294. }
  5295. sqlite3VdbeChangeP4( v, sqlite3VdbeCurrentAddr( v ) - 1,
  5296. n, P4_INT32 );//SQLITE_INT_TO_PTR(n)
  5297. Debug.Assert( n <= pTab.nCol );
  5298. }
  5299. }
  5300. else
  5301. {
  5302. sqlite3TableLock( pParse, iDb, pTab.tnum, 0, pTab.zName );
  5303. }
  5304. #if !SQLITE_OMIT_AUTOMATIC_INDEX
  5305. if ( ( pLevel.plan.wsFlags & WHERE_TEMP_INDEX ) != 0 )
  5306. {
  5307. constructAutomaticIndex( pParse, pWC, pTabItem, notReady, pLevel );
  5308. }
  5309. else
  5310. #endif
  5311. if ( ( pLevel.plan.wsFlags & WHERE_INDEXED ) != 0 )
  5312. {
  5313. Index pIx = pLevel.plan.u.pIdx;
  5314. KeyInfo pKey = sqlite3IndexKeyinfo( pParse, pIx );
  5315. int iIdxCur = pLevel.iIdxCur;
  5316. Debug.Assert( pIx.pSchema == pTab.pSchema );
  5317. Debug.Assert( iIdxCur >= 0 );
  5318. sqlite3VdbeAddOp4( v, OP_OpenRead, iIdxCur, pIx.tnum, iDb,
  5319. pKey, P4_KEYINFO_HANDOFF );
  5320. #if SQLITE_DEBUG
  5321. VdbeComment( v, "%s", pIx.zName );
  5322. #endif
  5323. }
  5324. sqlite3CodeVerifySchema( pParse, iDb );
  5325. notReady &= ~getMask( pWC.pMaskSet, pTabItem.iCursor );
  5326. }
  5327. pWInfo.iTop = sqlite3VdbeCurrentAddr( v );
  5328. //if( db.mallocFailed ) goto whereBeginError;
  5329. /* Generate the code to do the search. Each iteration of the for
  5330. ** loop below generates code for a single nested loop of the VM
  5331. ** program.
  5332. */
  5333. notReady = ~(Bitmask)0;
  5334. for ( i = 0; i < nTabList; i++ )
  5335. {
  5336. pLevel = pWInfo.a[i];
  5337. explainOneScan( pParse, pTabList, pLevel, i, pLevel.iFrom, wctrlFlags );
  5338. notReady = codeOneLoopStart( pWInfo, i, wctrlFlags, notReady );
  5339. pWInfo.iContinue = pLevel.addrCont;
  5340. }
  5341. #if SQLITE_TEST //* For testing and debugging use only */
  5342. /* Record in the query plan information about the current table
  5343. ** and the index used to access it (if any). If the table itself
  5344. ** is not used, its name is just '{}'. If no index is used
  5345. ** the index is listed as "{}". If the primary key is used the
  5346. ** index name is '*'.
  5347. */
  5348. #if !TCLSH
  5349. sqlite3_query_plan.Length = 0;
  5350. #else
  5351. sqlite3_query_plan.sValue = "";
  5352. #endif
  5353. for ( i = 0; i < nTabList; i++ )
  5354. {
  5355. string z;
  5356. int n;
  5357. pLevel = pWInfo.a[i];
  5358. pTabItem = pTabList.a[pLevel.iFrom];
  5359. z = pTabItem.zAlias;
  5360. if ( z == null )
  5361. z = pTabItem.pTab.zName;
  5362. n = sqlite3Strlen30( z );
  5363. if ( true ) //n+nQPlan < sizeof(sqlite3_query_plan)-10 )
  5364. {
  5365. if ( ( pLevel.plan.wsFlags & WHERE_IDX_ONLY ) != 0 )
  5366. {
  5367. sqlite3_query_plan.Append( "{}" ); //memcpy( &sqlite3_query_plan[nQPlan], "{}", 2 );
  5368. nQPlan += 2;
  5369. }
  5370. else
  5371. {
  5372. sqlite3_query_plan.Append( z ); //memcpy( &sqlite3_query_plan[nQPlan], z, n );
  5373. nQPlan += n;
  5374. }
  5375. sqlite3_query_plan.Append( " " );
  5376. nQPlan++; //sqlite3_query_plan[nQPlan++] = ' ';
  5377. }
  5378. testcase( pLevel.plan.wsFlags & WHERE_ROWID_EQ );
  5379. testcase( pLevel.plan.wsFlags & WHERE_ROWID_RANGE );
  5380. if ( ( pLevel.plan.wsFlags & ( WHERE_ROWID_EQ | WHERE_ROWID_RANGE ) ) != 0 )
  5381. {
  5382. sqlite3_query_plan.Append( "* " ); //memcpy(&sqlite3_query_plan[nQPlan], "* ", 2);
  5383. nQPlan += 2;
  5384. }
  5385. else if ( ( pLevel.plan.wsFlags & WHERE_INDEXED ) != 0 )
  5386. {
  5387. n = sqlite3Strlen30( pLevel.plan.u.pIdx.zName );
  5388. if ( true ) //n+nQPlan < sizeof(sqlite3_query_plan)-2 )//if( n+nQPlan < sizeof(sqlite3_query_plan)-2 )
  5389. {
  5390. sqlite3_query_plan.Append( pLevel.plan.u.pIdx.zName ); //memcpy(&sqlite3_query_plan[nQPlan], pLevel.plan.u.pIdx.zName, n);
  5391. nQPlan += n;
  5392. sqlite3_query_plan.Append( " " ); //sqlite3_query_plan[nQPlan++] = ' ';
  5393. }
  5394. }
  5395. else
  5396. {
  5397. sqlite3_query_plan.Append( "{} " ); //memcpy( &sqlite3_query_plan[nQPlan], "{} ", 3 );
  5398. nQPlan += 3;
  5399. }
  5400. }
  5401. //while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
  5402. // sqlite3_query_plan[--nQPlan] = 0;
  5403. //}
  5404. //sqlite3_query_plan[nQPlan] = 0;
  5405. #if !TCLSH
  5406. sqlite3_query_plan = new StringBuilder( sqlite3_query_plan.ToString().Trim() );
  5407. #else
  5408. sqlite3_query_plan.Trim();
  5409. #endif
  5410. nQPlan = 0;
  5411. #endif //* SQLITE_TEST // Testing and debugging use only */
  5412. /* Record the continuation address in the WhereInfo structure. Then
  5413. ** clean up and return.
  5414. */
  5415. return pWInfo;
  5416. /* Jump here if malloc fails */
  5417. whereBeginError:
  5418. if ( pWInfo != null )
  5419. {
  5420. pParse.nQueryLoop = pWInfo.savedNQueryLoop;
  5421. whereInfoFree( db, pWInfo );
  5422. }
  5423. return null;
  5424. }
  5425. /*
  5426. ** Generate the end of the WHERE loop. See comments on
  5427. ** sqlite3WhereBegin() for additional information.
  5428. */
  5429. static void sqlite3WhereEnd( WhereInfo pWInfo )
  5430. {
  5431. Parse pParse = pWInfo.pParse;
  5432. Vdbe v = pParse.pVdbe;
  5433. int i;
  5434. WhereLevel pLevel;
  5435. SrcList pTabList = pWInfo.pTabList;
  5436. sqlite3 db = pParse.db;
  5437. /* Generate loop termination code.
  5438. */
  5439. sqlite3ExprCacheClear( pParse );
  5440. for ( i = pWInfo.nLevel - 1; i >= 0; i-- )
  5441. {
  5442. pLevel = pWInfo.a[i];
  5443. sqlite3VdbeResolveLabel( v, pLevel.addrCont );
  5444. if ( pLevel.op != OP_Noop )
  5445. {
  5446. sqlite3VdbeAddOp2( v, pLevel.op, pLevel.p1, pLevel.p2 );
  5447. sqlite3VdbeChangeP5( v, pLevel.p5 );
  5448. }
  5449. if ( ( pLevel.plan.wsFlags & WHERE_IN_ABLE ) != 0 && pLevel.u._in.nIn > 0 )
  5450. {
  5451. InLoop pIn;
  5452. int j;
  5453. sqlite3VdbeResolveLabel( v, pLevel.addrNxt );
  5454. for ( j = pLevel.u._in.nIn; j > 0; j-- )//, pIn--)
  5455. {
  5456. pIn = pLevel.u._in.aInLoop[j - 1];
  5457. sqlite3VdbeJumpHere( v, pIn.addrInTop + 1 );
  5458. sqlite3VdbeAddOp2( v, OP_Next, pIn.iCur, pIn.addrInTop );
  5459. sqlite3VdbeJumpHere( v, pIn.addrInTop - 1 );
  5460. }
  5461. sqlite3DbFree( db, ref pLevel.u._in.aInLoop );
  5462. }
  5463. sqlite3VdbeResolveLabel( v, pLevel.addrBrk );
  5464. if ( pLevel.iLeftJoin != 0 )
  5465. {
  5466. int addr;
  5467. addr = sqlite3VdbeAddOp1( v, OP_IfPos, pLevel.iLeftJoin );
  5468. Debug.Assert( ( pLevel.plan.wsFlags & WHERE_IDX_ONLY ) == 0
  5469. || ( pLevel.plan.wsFlags & WHERE_INDEXED ) != 0 );
  5470. if ( ( pLevel.plan.wsFlags & WHERE_IDX_ONLY ) == 0 )
  5471. {
  5472. sqlite3VdbeAddOp1( v, OP_NullRow, pTabList.a[i].iCursor );
  5473. }
  5474. if ( pLevel.iIdxCur >= 0 )
  5475. {
  5476. sqlite3VdbeAddOp1( v, OP_NullRow, pLevel.iIdxCur );
  5477. }
  5478. if ( pLevel.op == OP_Return )
  5479. {
  5480. sqlite3VdbeAddOp2( v, OP_Gosub, pLevel.p1, pLevel.addrFirst );
  5481. }
  5482. else
  5483. {
  5484. sqlite3VdbeAddOp2( v, OP_Goto, 0, pLevel.addrFirst );
  5485. }
  5486. sqlite3VdbeJumpHere( v, addr );
  5487. }
  5488. }
  5489. /* The "break" point is here, just past the end of the outer loop.
  5490. ** Set it.
  5491. */
  5492. sqlite3VdbeResolveLabel( v, pWInfo.iBreak );
  5493. /* Close all of the cursors that were opened by sqlite3WhereBegin.
  5494. */
  5495. Debug.Assert( pWInfo.nLevel == 1 || pWInfo.nLevel == pTabList.nSrc );
  5496. for ( i = 0; i < pWInfo.nLevel; i++ )// for(i=0, pLevel=pWInfo.a; i<pWInfo.nLevel; i++, pLevel++){
  5497. {
  5498. pLevel = pWInfo.a[i];
  5499. SrcList_item pTabItem = pTabList.a[pLevel.iFrom];
  5500. Table pTab = pTabItem.pTab;
  5501. Debug.Assert( pTab != null );
  5502. if ( ( pTab.tabFlags & TF_Ephemeral ) == 0
  5503. && pTab.pSelect == null
  5504. && ( pWInfo.wctrlFlags & WHERE_OMIT_CLOSE ) == 0
  5505. )
  5506. {
  5507. u32 ws = pLevel.plan.wsFlags;
  5508. if ( 0 == pWInfo.okOnePass && ( ws & WHERE_IDX_ONLY ) == 0 )
  5509. {
  5510. sqlite3VdbeAddOp1( v, OP_Close, pTabItem.iCursor );
  5511. }
  5512. if ( ( ws & WHERE_INDEXED ) != 0 && ( ws & WHERE_TEMP_INDEX ) == 0 )
  5513. {
  5514. sqlite3VdbeAddOp1( v, OP_Close, pLevel.iIdxCur );
  5515. }
  5516. }
  5517. /* If this scan uses an index, make code substitutions to read data
  5518. ** from the index in preference to the table. Sometimes, this means
  5519. ** the table need never be read from. This is a performance boost,
  5520. ** as the vdbe level waits until the table is read before actually
  5521. ** seeking the table cursor to the record corresponding to the current
  5522. ** position in the index.
  5523. **
  5524. ** Calls to the code generator in between sqlite3WhereBegin and
  5525. ** sqlite3WhereEnd will have created code that references the table
  5526. ** directly. This loop scans all that code looking for opcodes
  5527. ** that reference the table and converts them into opcodes that
  5528. ** reference the index.
  5529. */
  5530. if ( ( pLevel.plan.wsFlags & WHERE_INDEXED ) != 0 )///* && 0 == db.mallocFailed */ )
  5531. {
  5532. int k, j, last;
  5533. VdbeOp pOp;
  5534. Index pIdx = pLevel.plan.u.pIdx;
  5535. Debug.Assert( pIdx != null );
  5536. //pOp = sqlite3VdbeGetOp( v, pWInfo.iTop );
  5537. last = sqlite3VdbeCurrentAddr( v );
  5538. for ( k = pWInfo.iTop; k < last; k++ )//, pOp++ )
  5539. {
  5540. pOp = sqlite3VdbeGetOp( v, k );
  5541. if ( pOp.p1 != pLevel.iTabCur )
  5542. continue;
  5543. if ( pOp.opcode == OP_Column )
  5544. {
  5545. for ( j = 0; j < pIdx.nColumn; j++ )
  5546. {
  5547. if ( pOp.p2 == pIdx.aiColumn[j] )
  5548. {
  5549. pOp.p2 = j;
  5550. pOp.p1 = pLevel.iIdxCur;
  5551. break;
  5552. }
  5553. }
  5554. Debug.Assert( ( pLevel.plan.wsFlags & WHERE_IDX_ONLY ) == 0
  5555. || j < pIdx.nColumn );
  5556. }
  5557. else if ( pOp.opcode == OP_Rowid )
  5558. {
  5559. pOp.p1 = pLevel.iIdxCur;
  5560. pOp.opcode = OP_IdxRowid;
  5561. }
  5562. }
  5563. }
  5564. }
  5565. /* Final cleanup
  5566. */
  5567. pParse.nQueryLoop = pWInfo.savedNQueryLoop;
  5568. whereInfoFree( db, pWInfo );
  5569. return;
  5570. }
  5571. }
  5572. }