Select.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761
  1. //------------------------------------------------------------------------------
  2. // <copyright file="Select.cs" company="Microsoft">
  3. // Copyright (c) Microsoft Corporation. All rights reserved.
  4. // </copyright>
  5. // <owner current="true" primary="true">[....]</owner>
  6. // <owner current="true" primary="false">[....]</owner>
  7. // <owner current="false" primary="false">[....]</owner>
  8. //------------------------------------------------------------------------------
  9. namespace System.Data {
  10. using System;
  11. using System.Collections.Generic;
  12. using System.ComponentModel;
  13. using System.Data.Common;
  14. using System.Diagnostics;
  15. internal sealed class Select {
  16. private readonly DataTable table;
  17. private readonly IndexField[] IndexFields;
  18. private DataViewRowState recordStates;
  19. private DataExpression rowFilter;
  20. private ExpressionNode expression;
  21. private Index index;
  22. private int[] records;
  23. private int recordCount;
  24. private ExpressionNode linearExpression;
  25. private bool candidatesForBinarySearch;
  26. private sealed class ColumnInfo {
  27. public bool flag = false; // Misc. Use
  28. public bool equalsOperator = false; // True when the associated expr has = Operator defined
  29. public BinaryNode expr = null; // Binary Search capable expression associated
  30. }
  31. ColumnInfo[] candidateColumns;
  32. int nCandidates;
  33. int matchedCandidates;
  34. public Select(DataTable table, string filterExpression, string sort, DataViewRowState recordStates) {
  35. this.table = table;
  36. IndexFields = table.ParseSortString(sort);
  37. if (filterExpression != null && filterExpression.Length > 0) {
  38. this.rowFilter = new DataExpression(this.table, filterExpression);
  39. this.expression = this.rowFilter.ExpressionNode;
  40. }
  41. this.recordStates = recordStates;
  42. }
  43. private bool IsSupportedOperator(int op) {
  44. return ((op >= Operators.EqualTo && op <= Operators.LessOrEqual) || op == Operators.Is || op == Operators.IsNot);
  45. }
  46. // [....] : Gathers all linear expressions in to this.linearExpression and all binary expressions in to their respective candidate columns expressions
  47. private void AnalyzeExpression(BinaryNode expr) {
  48. if (this.linearExpression == this.expression)
  49. return;
  50. if (expr.op == Operators.Or) {
  51. this.linearExpression = this.expression;
  52. return;
  53. }
  54. else
  55. if (expr.op == Operators.And) {
  56. bool isLeft=false, isRight=false;
  57. if (expr.left is BinaryNode) {
  58. AnalyzeExpression((BinaryNode)expr.left);
  59. if (this.linearExpression == this.expression)
  60. return;
  61. isLeft = true;
  62. }
  63. else {
  64. UnaryNode unaryNode = expr.left as UnaryNode;
  65. if (unaryNode != null) {
  66. while (unaryNode.op == Operators.Noop && unaryNode.right is UnaryNode && ((UnaryNode)unaryNode.right).op == Operators.Noop) {
  67. unaryNode = (UnaryNode)unaryNode.right;
  68. }
  69. if (unaryNode.op == Operators.Noop && unaryNode.right is BinaryNode) {
  70. AnalyzeExpression((BinaryNode)(unaryNode.right));
  71. if (this.linearExpression == this.expression) {
  72. return;
  73. }
  74. isLeft = true;
  75. }
  76. }
  77. }
  78. if (expr.right is BinaryNode) {
  79. AnalyzeExpression((BinaryNode)expr.right);
  80. if (this.linearExpression == this.expression)
  81. return;
  82. isRight = true;
  83. }
  84. else {
  85. UnaryNode unaryNode = expr.right as UnaryNode;
  86. if (unaryNode != null) {
  87. while (unaryNode.op == Operators.Noop && unaryNode.right is UnaryNode && ((UnaryNode)unaryNode.right).op == Operators.Noop) {
  88. unaryNode = (UnaryNode)unaryNode.right;
  89. }
  90. if (unaryNode.op == Operators.Noop && unaryNode.right is BinaryNode) {
  91. AnalyzeExpression((BinaryNode)(unaryNode.right));
  92. if (this.linearExpression == this.expression) {
  93. return;
  94. }
  95. // SQLBU 497534: DataTable.Select() returns incorrect results with multiple statements depending '(' and ')'
  96. // from copy paste error fixing SQLBU 342141
  97. isRight = true;
  98. }
  99. }
  100. }
  101. if (isLeft && isRight)
  102. return;
  103. ExpressionNode e = isLeft ? expr.right : expr.left;
  104. this.linearExpression = (this.linearExpression == null ? e : new BinaryNode(table, Operators.And, e, this.linearExpression));
  105. return;
  106. }
  107. else
  108. if (IsSupportedOperator(expr.op)) {
  109. if (expr.left is NameNode && expr.right is ConstNode) {
  110. ColumnInfo canColumn = (ColumnInfo)candidateColumns[((NameNode)(expr.left)).column.Ordinal];
  111. canColumn.expr = (canColumn.expr == null ? expr : new BinaryNode(table, Operators.And, expr, canColumn.expr));
  112. if (expr.op == Operators.EqualTo) {
  113. canColumn.equalsOperator = true;
  114. }
  115. candidatesForBinarySearch = true;
  116. return;
  117. }
  118. else
  119. if (expr.right is NameNode && expr.left is ConstNode) {
  120. ExpressionNode temp = expr.left;
  121. expr.left = expr.right;
  122. expr.right = temp;
  123. switch(expr.op) {
  124. case Operators.GreaterThen: expr.op = Operators.LessThen; break;
  125. case Operators.LessThen: expr.op = Operators.GreaterThen; break;
  126. case Operators.GreaterOrEqual: expr.op = Operators.LessOrEqual; break;
  127. case Operators.LessOrEqual: expr.op = Operators.GreaterOrEqual; break;
  128. default : break;
  129. }
  130. ColumnInfo canColumn = (ColumnInfo)candidateColumns[((NameNode)(expr.left)).column.Ordinal];
  131. canColumn.expr = (canColumn.expr == null ? expr : new BinaryNode(table, Operators.And, expr, canColumn.expr));
  132. if (expr.op == Operators.EqualTo) {
  133. canColumn.equalsOperator = true;
  134. }
  135. candidatesForBinarySearch = true;
  136. return;
  137. }
  138. }
  139. this.linearExpression = (this.linearExpression == null ? expr : new BinaryNode(table, Operators.And, expr, this.linearExpression));
  140. return;
  141. }
  142. private bool CompareSortIndexDesc(IndexField[] fields) {
  143. if (fields.Length < IndexFields.Length)
  144. return false;
  145. int j=0;
  146. for (int i = 0; i < fields.Length && j < IndexFields.Length; i++) {
  147. if (fields[i] == IndexFields[j]) {
  148. j++;
  149. }
  150. else {
  151. ColumnInfo canColumn = candidateColumns[fields[i].Column.Ordinal];
  152. if (!(canColumn != null && canColumn.equalsOperator))
  153. return false;
  154. }
  155. }
  156. return j == IndexFields.Length;
  157. }
  158. private bool FindSortIndex() {
  159. index = null;
  160. this.table.indexesLock.AcquireReaderLock(-1);
  161. try{
  162. int count = this.table.indexes.Count;
  163. int rowsCount = this.table.Rows.Count;
  164. for (int i = 0; i < count; i++) {
  165. Index ndx = (Index)table.indexes[i];
  166. if (ndx.RecordStates != recordStates)
  167. continue;
  168. if(!ndx.IsSharable) {
  169. continue;
  170. }
  171. if (CompareSortIndexDesc(ndx.IndexFields)) {
  172. index = ndx;
  173. return true;
  174. }
  175. }
  176. }
  177. finally {
  178. this.table.indexesLock.ReleaseReaderLock();
  179. }
  180. return false;
  181. }
  182. // Returns no. of columns that are matched
  183. private int CompareClosestCandidateIndexDesc(IndexField[] fields) {
  184. int count = (fields.Length < nCandidates ? fields.Length : nCandidates);
  185. int i = 0;
  186. for (; i < count; i++) {
  187. ColumnInfo canColumn = candidateColumns[fields[i].Column.Ordinal];
  188. if (canColumn == null || canColumn.expr == null) {
  189. break;
  190. }
  191. else
  192. if (!canColumn.equalsOperator) {
  193. return i+1;
  194. }
  195. }
  196. return i;
  197. }
  198. // Returns whether the found index (if any) is a sort index as well
  199. private bool FindClosestCandidateIndex() {
  200. index = null;
  201. matchedCandidates = 0;
  202. bool sortPriority = true;
  203. this.table.indexesLock.AcquireReaderLock(-1);
  204. try {
  205. int count = this.table.indexes.Count;
  206. int rowsCount = this.table.Rows.Count;
  207. for (int i = 0; i < count; i++) {
  208. Index ndx = (Index)table.indexes[i];
  209. if (ndx.RecordStates != recordStates)
  210. continue;
  211. if(!ndx.IsSharable)
  212. continue;
  213. int match = CompareClosestCandidateIndexDesc(ndx.IndexFields);
  214. if (match > matchedCandidates || (match == matchedCandidates && !sortPriority)) {
  215. matchedCandidates = match;
  216. index = ndx;
  217. sortPriority = CompareSortIndexDesc(ndx.IndexFields);
  218. if (matchedCandidates == nCandidates && sortPriority) {
  219. return true;
  220. }
  221. }
  222. }
  223. }
  224. finally {
  225. this.table.indexesLock.ReleaseReaderLock();
  226. }
  227. return (index != null ? sortPriority : false);
  228. }
  229. // Initialize candidate columns to new columnInfo and leave all non candidate columns to null
  230. private void InitCandidateColumns() {
  231. nCandidates = 0;
  232. candidateColumns = new ColumnInfo[this.table.Columns.Count];
  233. if (this.rowFilter == null)
  234. return;
  235. DataColumn[] depColumns = rowFilter.GetDependency();
  236. for (int i = 0; i < depColumns.Length; i++) {
  237. if (depColumns[i].Table == this.table) {
  238. candidateColumns[depColumns[i].Ordinal] = new ColumnInfo();
  239. nCandidates++;
  240. }
  241. }
  242. }
  243. // Based on the required sorting and candidate columns settings, create a new index; Should be called only when there is no existing index to be reused
  244. private void CreateIndex() {
  245. if (index == null) {
  246. if (nCandidates == 0) {
  247. index = new Index(table, IndexFields, recordStates, null);
  248. index.AddRef();
  249. }
  250. else {
  251. int i;
  252. int lenCanColumns = candidateColumns.Length;
  253. int lenIndexDesc = IndexFields.Length;
  254. bool equalsOperator = true;
  255. for (i=0; i<lenCanColumns; i++) {
  256. if (candidateColumns[i] != null) {
  257. if (!candidateColumns[i].equalsOperator) {
  258. equalsOperator = false;
  259. break;
  260. }
  261. }
  262. }
  263. int j=0;
  264. for (i=0; i < lenIndexDesc; i++) {
  265. ColumnInfo candidateColumn = candidateColumns[IndexFields[i].Column.Ordinal];
  266. if (candidateColumn != null) {
  267. candidateColumn.flag = true;
  268. j++;
  269. }
  270. }
  271. int indexNotInCandidates = lenIndexDesc - j;
  272. int candidatesNotInIndex = nCandidates - j;
  273. IndexField[] ndxFields = new IndexField[nCandidates + indexNotInCandidates];
  274. if (equalsOperator) {
  275. j=0;
  276. for (i=0; i<lenCanColumns; i++) {
  277. if (candidateColumns[i] != null) {
  278. ndxFields[j++] = new IndexField(this.table.Columns[i], isDescending: false);
  279. candidateColumns[i].flag = false;// this means it is processed
  280. }
  281. }
  282. for (i=0; i<lenIndexDesc; i++) {
  283. ColumnInfo canColumn = candidateColumns[IndexFields[i].Column.Ordinal];
  284. if (canColumn == null || canColumn.flag) { // if sort column is not a filter col , or not processed
  285. ndxFields[j++] = IndexFields[i];
  286. if (canColumn != null) {
  287. canColumn.flag = false;
  288. }
  289. }
  290. }
  291. for(i = 0; i < candidateColumns.Length; i++) {
  292. if (candidateColumns[i] != null) {
  293. candidateColumns[i].flag = false;// same as before, it is false when it returns
  294. }
  295. }
  296. // Debug.Assert(j == candidatesNotInIndex, "Whole ndxDesc should be filled!");
  297. index = new Index(table, ndxFields, recordStates, null);
  298. if (!IsOperatorIn(this.expression)) {
  299. // if the expression contains an 'IN' operator, the index will not be shared
  300. // therefore we do not need to index.AddRef, also table would track index consuming more memory until first write
  301. index.AddRef();
  302. }
  303. matchedCandidates = nCandidates;
  304. }
  305. else {
  306. for (i=0; i<lenIndexDesc; i++) {
  307. ndxFields[i] = IndexFields[i];
  308. ColumnInfo canColumn = candidateColumns[IndexFields[i].Column.Ordinal];
  309. if (canColumn != null)
  310. canColumn.flag = true;
  311. }
  312. j=i;
  313. for (i=0; i<lenCanColumns; i++) {
  314. if (candidateColumns[i] != null) {
  315. if(!candidateColumns[i].flag) {
  316. ndxFields[j++] = new IndexField(this.table.Columns[i], isDescending: false);
  317. }
  318. else {
  319. candidateColumns[i].flag = false;
  320. }
  321. }
  322. }
  323. // Debug.Assert(j == nCandidates+indexNotInCandidates, "Whole ndxDesc should be filled!");
  324. index = new Index(table, ndxFields, recordStates, null);
  325. matchedCandidates = 0;
  326. if (this.linearExpression != this.expression) {
  327. IndexField[] fields = index.IndexFields;
  328. while (matchedCandidates < j) { // [....] : j = index.IndexDesc.Length
  329. ColumnInfo canColumn = candidateColumns[fields[matchedCandidates].Column.Ordinal];
  330. if (canColumn == null || canColumn.expr == null)
  331. break;
  332. matchedCandidates++;
  333. if (!canColumn.equalsOperator)
  334. break;
  335. }
  336. }
  337. for(i = 0; i < candidateColumns.Length; i++) {
  338. if (candidateColumns[i] != null) {
  339. candidateColumns[i].flag = false;// same as before, it is false when it returns
  340. }
  341. }
  342. }
  343. }
  344. }
  345. }
  346. private bool IsOperatorIn(ExpressionNode enode) {
  347. BinaryNode bnode = (enode as BinaryNode);
  348. if (null != bnode) {
  349. if (Operators.In == bnode.op ||
  350. IsOperatorIn(bnode.right) ||
  351. IsOperatorIn(bnode.left))
  352. {
  353. return true;
  354. }
  355. }
  356. return false;
  357. }
  358. // Based on the current index and candidate columns settings, build the linear expression; Should be called only when there is atleast something for Binary Searching
  359. private void BuildLinearExpression() {
  360. int i;
  361. IndexField[] fields = index.IndexFields;
  362. int lenId = fields.Length;
  363. Debug.Assert(matchedCandidates > 0 && matchedCandidates <= lenId, "BuildLinearExpression : Invalid Index");
  364. for (i=0; i<matchedCandidates; i++) {
  365. ColumnInfo canColumn = candidateColumns[fields[i].Column.Ordinal];
  366. Debug.Assert(canColumn != null && canColumn.expr != null, "BuildLinearExpression : Must be a matched candidate");
  367. canColumn.flag = true;
  368. }
  369. //this is invalid assert, assumption was that all equals operator exists at the begining of candidateColumns
  370. // but with QFE 1704, this assumption is not true anymore
  371. // Debug.Assert(matchedCandidates==1 || candidateColumns[matchedCandidates-1].equalsOperator, "BuildLinearExpression : Invalid matched candidates");
  372. int lenCanColumns = candidateColumns.Length;
  373. for (i=0; i<lenCanColumns; i++) {
  374. if (candidateColumns[i] != null) {
  375. if (!candidateColumns[i].flag) {
  376. if (candidateColumns[i].expr != null) {
  377. this.linearExpression = (this.linearExpression == null ? candidateColumns[i].expr : new BinaryNode(table, Operators.And, candidateColumns[i].expr, this.linearExpression));
  378. }
  379. }
  380. else {
  381. candidateColumns[i].flag = false;
  382. }
  383. }
  384. }
  385. // Debug.Assert(this.linearExpression != null, "BuildLinearExpression : How come there is nothing to search linearly"); bug 97446
  386. }
  387. public DataRow[] SelectRows() {
  388. bool needSorting = true;
  389. InitCandidateColumns();
  390. if (this.expression is BinaryNode) {
  391. AnalyzeExpression((BinaryNode)this.expression);
  392. if (!candidatesForBinarySearch) {
  393. this.linearExpression = this.expression;
  394. }
  395. if (this.linearExpression == this.expression) {
  396. for (int i=0; i<candidateColumns.Length; i++) {
  397. if (candidateColumns[i] != null) {
  398. candidateColumns[i].equalsOperator = false;
  399. candidateColumns[i].expr = null;
  400. }
  401. }
  402. }
  403. else {
  404. needSorting = !FindClosestCandidateIndex();
  405. }
  406. }
  407. else {
  408. this.linearExpression = this.expression;
  409. }
  410. if (index == null && (IndexFields.Length > 0 || this.linearExpression == this.expression)) {
  411. needSorting = !FindSortIndex();
  412. }
  413. if (index == null) {
  414. CreateIndex();
  415. needSorting = false;
  416. }
  417. if (index.RecordCount == 0)
  418. return table.NewRowArray(0);
  419. Range range;
  420. if (matchedCandidates == 0) { // [....] : Either dont have rowFilter or only linear search expression
  421. range = new Range(0, index.RecordCount-1);
  422. Debug.Assert(!needSorting, "What are we doing here if no real reuse of this index ?");
  423. this.linearExpression = this.expression;
  424. return GetLinearFilteredRows(range);
  425. }
  426. else {
  427. range = GetBinaryFilteredRecords();
  428. if (range.Count == 0)
  429. return table.NewRowArray(0);
  430. if (matchedCandidates < nCandidates) {
  431. BuildLinearExpression();
  432. }
  433. if (!needSorting) {
  434. return GetLinearFilteredRows(range);
  435. }
  436. else {
  437. this.records = GetLinearFilteredRecords(range);
  438. this.recordCount = this.records.Length;
  439. if (this.recordCount == 0)
  440. return table.NewRowArray(0);
  441. Sort(0, this.recordCount-1);
  442. return GetRows();
  443. }
  444. }
  445. }
  446. public DataRow[] GetRows() {
  447. DataRow[] newRows = table.NewRowArray(recordCount);
  448. for (int i = 0; i < newRows.Length; i++) {
  449. newRows[i] = table.recordManager[records[i]];
  450. }
  451. return newRows;
  452. }
  453. private bool AcceptRecord(int record) {
  454. DataRow row = table.recordManager[record];
  455. if (row == null)
  456. return true;
  457. //
  458. DataRowVersion version = DataRowVersion.Default;
  459. if (row.oldRecord == record) {
  460. version = DataRowVersion.Original;
  461. }
  462. else if (row.newRecord == record) {
  463. version = DataRowVersion.Current;
  464. }
  465. else if (row.tempRecord == record) {
  466. version = DataRowVersion.Proposed;
  467. }
  468. object val = this.linearExpression.Eval(row, version);
  469. bool result;
  470. try {
  471. result = DataExpression.ToBoolean(val);
  472. }
  473. catch (Exception e) {
  474. //
  475. if (!ADP.IsCatchableExceptionType(e)) {
  476. throw;
  477. }
  478. throw ExprException.FilterConvertion(this.rowFilter.Expression);
  479. }
  480. return result;
  481. }
  482. private int Eval(BinaryNode expr, DataRow row, DataRowVersion version) {
  483. if (expr.op == Operators.And) {
  484. int lResult = Eval((BinaryNode)expr.left,row,version);
  485. if (lResult != 0)
  486. return lResult;
  487. int rResult = Eval((BinaryNode)expr.right,row,version);
  488. if (rResult != 0)
  489. return rResult;
  490. return 0;
  491. }
  492. long c = 0;
  493. object vLeft = expr.left.Eval(row, version);
  494. if (expr.op != Operators.Is && expr.op != Operators.IsNot) {
  495. object vRight = expr.right.Eval(row, version);
  496. bool isLConst = (expr.left is ConstNode);
  497. bool isRConst = (expr.right is ConstNode);
  498. if ((vLeft == DBNull.Value)||(expr.left.IsSqlColumn && DataStorage.IsObjectSqlNull(vLeft)))
  499. return -1;
  500. if ((vRight == DBNull.Value)||(expr.right.IsSqlColumn && DataStorage.IsObjectSqlNull(vRight)))
  501. return 1;
  502. StorageType leftType = DataStorage.GetStorageType(vLeft.GetType());
  503. if (StorageType.Char == leftType) {
  504. if ((isRConst)||(!expr.right.IsSqlColumn))
  505. vRight = Convert.ToChar(vRight, table.FormatProvider);
  506. else
  507. vRight = SqlConvert.ChangeType2(vRight, StorageType.Char, typeof(char), table.FormatProvider);
  508. }
  509. StorageType rightType = DataStorage.GetStorageType(vRight.GetType());
  510. StorageType resultType;
  511. if (expr.left.IsSqlColumn || expr.right.IsSqlColumn) {
  512. resultType = expr.ResultSqlType(leftType, rightType, isLConst, isRConst, expr.op);
  513. }
  514. else {
  515. resultType = expr.ResultType(leftType, rightType, isLConst, isRConst, expr.op);
  516. }
  517. if (StorageType.Empty == resultType) {
  518. expr.SetTypeMismatchError(expr.op, vLeft.GetType(), vRight.GetType());
  519. }
  520. // if comparing a Guid column value against a string literal
  521. // use InvariantCulture instead of DataTable.Locale because in the Danish related cultures
  522. // sorting a Guid as a string has different results than in Invariant and English related cultures.
  523. // This fix is restricted to DataTable.Select("GuidColumn = 'string literal'") types of queries
  524. NameNode namedNode = null;
  525. System.Globalization.CompareInfo comparer =
  526. ((isLConst && !isRConst && (leftType == StorageType.String) && (rightType == StorageType.Guid) && (null != (namedNode = expr.right as NameNode)) && (namedNode.column.DataType == typeof(Guid))) ||
  527. (isRConst && !isLConst && (rightType == StorageType.String) && (leftType == StorageType.Guid) && (null != (namedNode = expr.left as NameNode)) && (namedNode.column.DataType == typeof(Guid))))
  528. ? System.Globalization.CultureInfo.InvariantCulture.CompareInfo : null;
  529. c = expr.BinaryCompare(vLeft, vRight, resultType, expr.op, comparer);
  530. }
  531. switch(expr.op) {
  532. case Operators.EqualTo: c = (c == 0 ? 0 : c < 0 ? -1 : 1); break;
  533. case Operators.GreaterThen: c = (c > 0 ? 0 : -1); break;
  534. case Operators.LessThen: c = (c < 0 ? 0 : 1); break;
  535. case Operators.GreaterOrEqual: c = (c >= 0 ? 0 : -1); break;
  536. case Operators.LessOrEqual: c = (c <= 0 ? 0 : 1); break;
  537. case Operators.Is: c = (vLeft == DBNull.Value ? 0 : -1); break;
  538. case Operators.IsNot: c = (vLeft != DBNull.Value ? 0 : 1); break;
  539. default: Debug.Assert(true, "Unsupported Binary Search Operator!"); break;
  540. }
  541. return (int)c;
  542. }
  543. private int Evaluate(int record) {
  544. DataRow row = table.recordManager[record];
  545. if (row == null)
  546. return 0;
  547. //
  548. DataRowVersion version = DataRowVersion.Default;
  549. if (row.oldRecord == record) {
  550. version = DataRowVersion.Original;
  551. }
  552. else if (row.newRecord == record) {
  553. version = DataRowVersion.Current;
  554. }
  555. else if (row.tempRecord == record) {
  556. version = DataRowVersion.Proposed;
  557. }
  558. IndexField[] fields = index.IndexFields;
  559. for (int i=0; i < matchedCandidates; i++) {
  560. int columnOrdinal = fields[i].Column.Ordinal;
  561. Debug.Assert(candidateColumns[columnOrdinal] != null, "How come this is not a candidate column");
  562. Debug.Assert(candidateColumns[columnOrdinal].expr != null, "How come there is no associated expression");
  563. int c = Eval(candidateColumns[columnOrdinal].expr, row, version);
  564. if (c != 0)
  565. return fields[i].IsDescending ? -c : c;
  566. }
  567. return 0;
  568. }
  569. private int FindFirstMatchingRecord() {
  570. int rec = -1;
  571. int lo = 0;
  572. int hi = index.RecordCount - 1;
  573. while (lo <= hi) {
  574. int i = lo + hi >> 1;
  575. int recNo = index.GetRecord(i);
  576. int c = Evaluate(recNo);
  577. if (c == 0) { rec = i; }
  578. if (c < 0) lo = i + 1;
  579. else hi = i - 1;
  580. }
  581. return rec;
  582. }
  583. private int FindLastMatchingRecord(int lo) {
  584. int rec = -1;
  585. int hi = index.RecordCount - 1;
  586. while (lo <= hi) {
  587. int i = lo + hi >> 1;
  588. int recNo = index.GetRecord(i);
  589. int c = Evaluate(recNo);
  590. if (c == 0) { rec = i; }
  591. if (c <= 0) lo = i + 1;
  592. else hi = i - 1;
  593. }
  594. return rec;
  595. }
  596. private Range GetBinaryFilteredRecords() {
  597. if (matchedCandidates == 0) {
  598. return new Range(0, index.RecordCount-1);
  599. }
  600. Debug.Assert(matchedCandidates <= index.IndexFields.Length, "GetBinaryFilteredRecords : Invalid Index");
  601. int lo = FindFirstMatchingRecord();
  602. if (lo == -1) {
  603. return new Range();
  604. }
  605. int hi = FindLastMatchingRecord(lo);
  606. Debug.Assert (lo <= hi, "GetBinaryFilteredRecords : Invalid Search Results");
  607. return new Range(lo, hi);
  608. }
  609. private int[] GetLinearFilteredRecords(Range range) {
  610. if (this.linearExpression == null) {
  611. int[] resultRecords = new int[range.Count];
  612. RBTree<int>.RBTreeEnumerator iterator = index.GetEnumerator(range.Min);
  613. for (int i = 0; i < range.Count && iterator.MoveNext(); i++) {
  614. resultRecords[i] = iterator.Current;
  615. }
  616. return resultRecords;
  617. }
  618. else {
  619. List<int> matchingRecords = new List<int>();
  620. RBTree<int>.RBTreeEnumerator iterator = index.GetEnumerator(range.Min);
  621. for (int i = 0; i < range.Count && iterator.MoveNext(); i++) {
  622. if (AcceptRecord(iterator.Current)) {
  623. matchingRecords.Add(iterator.Current);
  624. }
  625. }
  626. return matchingRecords.ToArray();
  627. }
  628. }
  629. private DataRow[] GetLinearFilteredRows(Range range) {
  630. DataRow[] resultRows;
  631. if (this.linearExpression == null) {
  632. return index.GetRows(range);
  633. }
  634. List<DataRow> matchingRows = new List<DataRow>();
  635. RBTree<int>.RBTreeEnumerator iterator = index.GetEnumerator(range.Min);
  636. for (int i = 0; i < range.Count && iterator.MoveNext(); i++) {
  637. if (AcceptRecord(iterator.Current)) {
  638. matchingRows.Add(table.recordManager[iterator.Current]);
  639. }
  640. }
  641. resultRows = table.NewRowArray(matchingRows.Count);
  642. matchingRows.CopyTo(resultRows);
  643. return resultRows;
  644. }
  645. private int CompareRecords(int record1, int record2) {
  646. int lenIndexDesc = IndexFields.Length;
  647. for (int i = 0; i < lenIndexDesc; i++) {
  648. int c = IndexFields[i].Column.Compare(record1, record2);
  649. if (c != 0) {
  650. if (IndexFields[i].IsDescending) c = -c;
  651. return c;
  652. }
  653. }
  654. long id1 = table.recordManager[record1] == null? 0: table.recordManager[record1].rowID;
  655. long id2 = table.recordManager[record2] == null ? 0 : table.recordManager[record2].rowID;
  656. int diff = (id1 < id2) ? -1 : ((id2 < id1) ? 1 : 0);
  657. // if they're two records in the same row, we need to be able to distinguish them.
  658. if (diff == 0 && record1 != record2 &&
  659. table.recordManager[record1] != null && table.recordManager[record2] != null) {
  660. id1 = (int)table.recordManager[record1].GetRecordState(record1);
  661. id2 = (int)table.recordManager[record2].GetRecordState(record2);
  662. diff = (id1 < id2) ? -1 : ((id2 < id1) ? 1 : 0);
  663. }
  664. return diff;
  665. }
  666. private void Sort(int left, int right) {
  667. int i, j;
  668. int record;
  669. do {
  670. i = left;
  671. j = right;
  672. record = records[i + j >> 1];
  673. do {
  674. while (CompareRecords(records[i], record) < 0) i++;
  675. while (CompareRecords(records[j], record) > 0) j--;
  676. if (i <= j) {
  677. int r = records[i];
  678. records[i] = records[j];
  679. records[j] = r;
  680. i++;
  681. j--;
  682. }
  683. } while (i <= j);
  684. if (left < j) Sort(left, j);
  685. left = i;
  686. } while (i < right);
  687. }
  688. }
  689. }