Index.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721
  1. //
  2. // System.Data.Common.Key.cs
  3. //
  4. // Author:
  5. // Boris Kirzner <[email protected]>
  6. // Konstantin Triger ([email protected])
  7. //
  8. /*
  9. * Copyright (c) 2002-2004 Mainsoft Corporation.
  10. *
  11. * Permission is hereby granted, free of charge, to any person obtaining a
  12. * copy of this software and associated documentation files (the "Software"),
  13. * to deal in the Software without restriction, including without limitation
  14. * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  15. * and/or sell copies of the Software, and to permit persons to whom the
  16. * Software is furnished to do so, subject to the following conditions:
  17. *
  18. * The above copyright notice and this permission notice shall be included in
  19. * all copies or substantial portions of the Software.
  20. *
  21. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  22. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  23. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  24. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  25. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  26. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  27. * DEALINGS IN THE SOFTWARE.
  28. */
  29. using System;
  30. using System.Collections;
  31. using System.Text;
  32. namespace System.Data.Common
  33. {
  34. enum IndexDuplicatesState { Unknown, True, False };
  35. /// <summary>
  36. /// Summary description for Index.
  37. /// </summary>
  38. internal class Index
  39. {
  40. #region Fields
  41. int[] _array;
  42. int _size;
  43. Key _key;
  44. int _refCount = 0;
  45. IndexDuplicatesState _hasDuplicates;
  46. #endregion // Fields
  47. #region Constructors
  48. internal Index(Key key)
  49. {
  50. _key = key;
  51. Reset();
  52. }
  53. #endregion // Constructors
  54. #region Properties
  55. internal Key Key
  56. {
  57. get {
  58. return _key;
  59. }
  60. }
  61. internal int Size
  62. {
  63. get {
  64. EnsureArray();
  65. return _size;
  66. }
  67. }
  68. internal int RefCount
  69. {
  70. get {
  71. return _refCount;
  72. }
  73. }
  74. internal int IndexToRecord(int index){
  75. return index < 0 ? index : Array[index];
  76. }
  77. private int[] Array
  78. {
  79. get {
  80. EnsureArray();
  81. return _array;
  82. }
  83. }
  84. internal bool HasDuplicates
  85. {
  86. get {
  87. if (_array == null || _hasDuplicates == IndexDuplicatesState.Unknown) {
  88. EnsureArray();
  89. if (_hasDuplicates == IndexDuplicatesState.Unknown) {
  90. // check for duplicates
  91. _hasDuplicates = IndexDuplicatesState.False;
  92. for(int i = 0; i < Size - 1; i++) {
  93. if (Key.CompareRecords(Array[i],Array[i+1]) == 0) {
  94. _hasDuplicates = IndexDuplicatesState.True;
  95. break;
  96. }
  97. }
  98. }
  99. }
  100. return (_hasDuplicates == IndexDuplicatesState.True);
  101. }
  102. }
  103. #endregion // Properties
  104. #region Methods
  105. internal int[] Duplicates {
  106. get {
  107. if (!HasDuplicates)
  108. return null;
  109. ArrayList dups = new ArrayList();
  110. bool inRange = false;
  111. for(int i = 0; i < Size - 1; i++) {
  112. if (Key.CompareRecords(Array[i],Array[i+1]) == 0){
  113. if (!inRange) {
  114. dups.Add(Array[i]);
  115. inRange = true;
  116. }
  117. dups.Add(Array[i+1]);
  118. }
  119. else
  120. inRange = false;
  121. }
  122. return (int[])dups.ToArray(typeof(int));
  123. }
  124. }
  125. private void EnsureArray()
  126. {
  127. if (_array == null) {
  128. RebuildIndex();
  129. }
  130. }
  131. internal int[] GetAll()
  132. {
  133. return Array;
  134. }
  135. internal DataRow[] GetAllRows ()
  136. {
  137. DataRow[] list = new DataRow [Size];
  138. for (int i=0; i < Size; ++i)
  139. list [i] = Key.Table.RecordCache [Array [i]];
  140. return list;
  141. }
  142. internal DataRow[] GetDistinctRows ()
  143. {
  144. ArrayList list = new ArrayList ();
  145. list.Add (Key.Table.RecordCache [Array [0]]);
  146. int currRecord = Array [0];
  147. for (int i=1; i < Size; ++i) {
  148. if (Key.CompareRecords (currRecord, Array [i]) == 0)
  149. continue;
  150. list.Add (Key.Table.RecordCache [Array [i]]);
  151. currRecord = Array [i];
  152. }
  153. return (DataRow[])list.ToArray (typeof (DataRow));
  154. }
  155. internal void Reset()
  156. {
  157. _array = null;
  158. RebuildIndex();
  159. }
  160. private void RebuildIndex()
  161. {
  162. // consider better capacity approximation
  163. _array = new int[Key.Table.RecordCache.CurrentCapacity];
  164. _size = 0;
  165. foreach(DataRow row in Key.Table.Rows) {
  166. int record = Key.GetRecord(row);
  167. if (record != -1) {
  168. _array[_size++] = record;
  169. }
  170. }
  171. _hasDuplicates = IndexDuplicatesState.False;
  172. // Note : MergeSort may update hasDuplicates to True
  173. Sort();
  174. }
  175. private void Sort()
  176. {
  177. //QuickSort(Array,0,Size-1);
  178. MergeSort(Array,Size);
  179. }
  180. /*
  181. * Returns record number of the record equal to the key values supplied
  182. * in the meaning of index key, or -1 if no equal record found.
  183. */
  184. internal int Find(object[] keys)
  185. {
  186. int index = FindIndex(keys);
  187. return IndexToRecord(index);
  188. }
  189. /*
  190. * Returns record index (location) of the record equal to the key values supplied
  191. * in the meaning of index key, or -1 if no equal record found.
  192. */
  193. internal int FindIndex(object[] keys)
  194. {
  195. if (keys == null || keys.Length != Key.Columns.Length) {
  196. throw new ArgumentException("Expecting " + Key.Columns.Length + " value(s) for the key being indexed, " +
  197. "but received " + ((keys == null) ? 0 : keys.Length) + " value(s).");
  198. }
  199. int tmp = Key.Table.RecordCache.NewRecord();
  200. try {
  201. // init key values for temporal record
  202. for(int i = 0; i < Key.Columns.Length; i++) {
  203. Key.Columns[i].DataContainer[tmp] = keys[i];
  204. }
  205. return FindIndex(tmp);
  206. }
  207. // catch(FormatException) {
  208. // return -1;
  209. // }
  210. // catch(InvalidCastException) {
  211. // return -1;
  212. // }
  213. finally {
  214. Key.Table.RecordCache.DisposeRecord(tmp);
  215. }
  216. }
  217. /*
  218. * Returns record number of the record equal to the record supplied
  219. * in the meaning of index key, or -1 if no equal record found.
  220. */
  221. internal int Find(int record)
  222. {
  223. int index = FindIndex(record);
  224. return IndexToRecord(index);
  225. }
  226. /*
  227. * Returns array of record numbers of the records equal equal to the key values supplied
  228. * in the meaning of index key, or -1 if no equal record found.
  229. */
  230. internal int[] FindAll(object[] keys)
  231. {
  232. int[] indexes = FindAllIndexes(keys);
  233. IndexesToRecords(indexes);
  234. return indexes;
  235. }
  236. /*
  237. * Returns array of indexes of the records inside the index equal equal to the key values supplied
  238. * in the meaning of index key, or -1 if no equal record found.
  239. */
  240. internal int[] FindAllIndexes(object[] keys)
  241. {
  242. if (keys == null || keys.Length != Key.Columns.Length) {
  243. throw new ArgumentException("Expecting " + Key.Columns.Length + " value(s) for the key being indexed," +
  244. "but received " + ((keys == null) ? 0 : keys.Length) + " value(s).");
  245. }
  246. int tmp = Key.Table.RecordCache.NewRecord();
  247. try {
  248. // init key values for temporal record
  249. for(int i = 0; i < Key.Columns.Length; i++) {
  250. Key.Columns[i].DataContainer[tmp] = keys[i];
  251. }
  252. return FindAllIndexes(tmp);
  253. }
  254. catch(FormatException) {
  255. return new int[0];
  256. }
  257. catch(InvalidCastException) {
  258. return new int[0];
  259. }
  260. finally {
  261. Key.Table.RecordCache.DisposeRecord(tmp);
  262. }
  263. }
  264. /*
  265. * Returns array of record numbers of the records equal to the record supplied
  266. * in the meaning of index key, or empty list if no equal records found.
  267. */
  268. internal int[] FindAll(int record)
  269. {
  270. int[] indexes = FindAllIndexes(record);
  271. IndexesToRecords(indexes);
  272. return indexes;
  273. }
  274. /*
  275. * Returns array of indexes of the records inside the index that equal to the record supplied
  276. * in the meaning of index key, or empty list if no equal records found.
  277. */
  278. internal int[] FindAllIndexes(int record)
  279. {
  280. int index = FindIndex(record);
  281. if (index == -1) {
  282. return new int[0];
  283. }
  284. int startIndex = index++;
  285. int endIndex = index;
  286. for(;startIndex >= 0 && Key.CompareRecords(Array[startIndex],record) == 0;startIndex--);
  287. for(;endIndex < Size && Key.CompareRecords(Array[endIndex],record) == 0;endIndex++);
  288. int length = endIndex - startIndex - 1;
  289. int[] indexes = new int[length];
  290. for(int i = 0; i < length; i++) {
  291. indexes[i] = ++startIndex;
  292. }
  293. return indexes;
  294. }
  295. /*
  296. * Returns index inside the array where record number of the record equal to the record supplied
  297. * in the meaning of index key is sored, or -1 if no equal record found.
  298. */
  299. private int FindIndex(int record)
  300. {
  301. if (Size == 0) {
  302. return -1;
  303. }
  304. return BinarySearch(Array,0,Size - 1,record);
  305. }
  306. /*
  307. * Finds exact location of the record specified
  308. */
  309. private int FindIndexExact(int record)
  310. {
  311. for (int i = 0, size = Size; i < size; i++)
  312. if (Array[i] == record)
  313. return i;
  314. return -1;
  315. }
  316. /*
  317. * Returns array of records from the indexes (locations) inside the index
  318. */
  319. private void IndexesToRecords(int[] indexes)
  320. {
  321. for(int i = 0; i < indexes.Length; i++) {
  322. indexes[i] = Array[indexes[i]];
  323. }
  324. }
  325. internal void Delete(DataRow row)
  326. {
  327. int oldRecord = Key.GetRecord(row);
  328. Delete(oldRecord);
  329. }
  330. internal void Delete(int oldRecord)
  331. {
  332. if (oldRecord == -1)
  333. return;
  334. int index = FindIndexExact(oldRecord);
  335. if (index != -1) {
  336. if ((_hasDuplicates == IndexDuplicatesState.True)) {
  337. int c1 = 1;
  338. int c2 = 1;
  339. if (index > 0) {
  340. c1 = Key.CompareRecords(Array[index - 1],oldRecord);
  341. }
  342. if (index < Size - 1) {
  343. c2 = Key.CompareRecords(Array[index + 1],oldRecord);
  344. }
  345. if (c1 == 0 ^ c2 == 0) {
  346. _hasDuplicates = IndexDuplicatesState.Unknown;
  347. }
  348. }
  349. Remove(index);
  350. }
  351. }
  352. private void Remove(int index)
  353. {
  354. if (Size > 1) {
  355. System.Array.Copy(Array,index+1,Array,index,Size - index - 1);
  356. }
  357. _size--;
  358. }
  359. internal void Update(DataRow row,int oldRecord, DataRowVersion oldVersion, DataRowState oldState)
  360. {
  361. bool contains = Key.ContainsVersion (oldState, oldVersion);
  362. int newRecord = Key.GetRecord(row);
  363. // the record did not appeared in the index before update
  364. if (oldRecord == -1 || Size == 0 || !contains) {
  365. if (newRecord >= 0) {
  366. if (FindIndexExact(newRecord) < 0)
  367. Add(row,newRecord);
  368. }
  369. return;
  370. }
  371. // the record will not appeare in the index after update
  372. if (newRecord < 0 || !Key.CanContain (newRecord)) {
  373. Delete (oldRecord);
  374. return;
  375. }
  376. int oldIdx = FindIndexExact(oldRecord);
  377. if( oldIdx == -1 ) {
  378. Add(row,newRecord);
  379. return;
  380. }
  381. int newIdx = -1;
  382. int compare = Key.CompareRecords(Array[oldIdx],newRecord);
  383. int start,end;
  384. int c1 = 1;
  385. int c2 = 1;
  386. if (compare == 0) {
  387. if (Array[oldIdx] == newRecord) {
  388. // we deal with the same record that didn't change
  389. // in the context of current index.
  390. // so , do nothing.
  391. return;
  392. }
  393. }
  394. else {
  395. if ((_hasDuplicates == IndexDuplicatesState.True)) {
  396. if (oldIdx > 0) {
  397. c1 = Key.CompareRecords(Array[oldIdx - 1],newRecord);
  398. }
  399. if (oldIdx < Size - 1) {
  400. c2 = Key.CompareRecords(Array[oldIdx + 1],newRecord);
  401. }
  402. if ((c1 == 0 ^ c2 == 0) && compare != 0) {
  403. _hasDuplicates = IndexDuplicatesState.Unknown;
  404. }
  405. }
  406. }
  407. if ((oldIdx == 0 && compare > 0) || (oldIdx == (Size - 1) && compare < 0) || (compare == 0)) {
  408. // no need to switch cells
  409. newIdx = oldIdx;
  410. }
  411. else {
  412. if (compare < 0) {
  413. // search after the old place
  414. start = oldIdx + 1;
  415. end = Size - 1;
  416. }
  417. else {
  418. // search before the old palce
  419. start = 0;
  420. end = oldIdx - 1;
  421. }
  422. newIdx = LazyBinarySearch(Array,start,end,newRecord);
  423. if (oldIdx < newIdx) {
  424. System.Array.Copy(Array,oldIdx + 1,Array,oldIdx,newIdx - oldIdx);
  425. if (Key.CompareRecords (Array [newIdx], newRecord) > 0)
  426. --newIdx;
  427. }
  428. else if (oldIdx > newIdx){
  429. System.Array.Copy(Array,newIdx,Array,newIdx + 1,oldIdx - newIdx);
  430. if (Key.CompareRecords (Array [newIdx], newRecord) < 0)
  431. ++newIdx;
  432. }
  433. }
  434. Array[newIdx] = newRecord;
  435. if (compare != 0) {
  436. if (!(_hasDuplicates == IndexDuplicatesState.True)) {
  437. if (newIdx > 0) {
  438. c1 = Key.CompareRecords(Array[newIdx - 1],newRecord);
  439. }
  440. if (newIdx < Size - 1) {
  441. c2 = Key.CompareRecords(Array[newIdx + 1],newRecord);
  442. }
  443. if (c1 == 0 || c2 == 0) {
  444. _hasDuplicates = IndexDuplicatesState.True;
  445. }
  446. }
  447. }
  448. }
  449. internal void Add(DataRow row) {
  450. Add(row, Key.GetRecord(row));
  451. }
  452. private void Add(DataRow row,int newRecord)
  453. {
  454. int newIdx;
  455. if (newRecord < 0 || !Key.CanContain (newRecord))
  456. return;
  457. if (Size == 0) {
  458. newIdx = 0;
  459. }
  460. else {
  461. newIdx = LazyBinarySearch(Array,0,Size - 1,newRecord);
  462. // if newl value is greater - insert afer old value
  463. // else - insert before old value
  464. if (Key.CompareRecords(Array[newIdx],newRecord) < 0) {
  465. newIdx++;
  466. }
  467. }
  468. Insert(newIdx,newRecord);
  469. int c1 = 1;
  470. int c2 = 1;
  471. if (!(_hasDuplicates == IndexDuplicatesState.True)) {
  472. if (newIdx > 0) {
  473. c1 = Key.CompareRecords(Array[newIdx - 1],newRecord);
  474. }
  475. if (newIdx < Size - 1) {
  476. c2 = Key.CompareRecords(Array[newIdx + 1],newRecord);
  477. }
  478. if (c1 == 0 || c2 == 0) {
  479. _hasDuplicates = IndexDuplicatesState.True;
  480. }
  481. }
  482. }
  483. private void Insert(int index,int r)
  484. {
  485. if (Array.Length == Size) {
  486. int[] tmp = (Size == 0) ? new int[16] : new int[Size << 1];
  487. System.Array.Copy(Array,0,tmp,0,index);
  488. tmp[index] = r;
  489. System.Array.Copy(Array,index,tmp,index + 1,Size - index);
  490. _array = tmp;
  491. }
  492. else {
  493. System.Array.Copy(Array,index,Array,index + 1,Size - index);
  494. Array[index] = r;
  495. }
  496. _size++;
  497. }
  498. private void MergeSort(int[] to, int length)
  499. {
  500. int[] from = new int[length];
  501. System.Array.Copy(to, 0, from, 0, from.Length);
  502. MergeSort(from, to, 0, from.Length);
  503. }
  504. private void MergeSort(int[] from, int[] to,int p, int r)
  505. {
  506. int q = (p + r) >> 1;
  507. if (q == p) {
  508. return;
  509. }
  510. MergeSort(to, from, p, q);
  511. MergeSort(to, from, q, r);
  512. // merge
  513. for (int middle = q, current = p;;) {
  514. int res = Key.CompareRecords(from[p],from[q]);
  515. if (res > 0) {
  516. to[current++] = from[q++];
  517. if (q == r) {
  518. while( p < middle) {
  519. to[current++] = from[p++];
  520. }
  521. break;
  522. }
  523. }
  524. else {
  525. if (res == 0) {
  526. _hasDuplicates = IndexDuplicatesState.True;
  527. }
  528. to[current++] = from[p++];
  529. if (p == middle) {
  530. while( q < r) {
  531. to[current++] = from[q++];
  532. }
  533. break;
  534. }
  535. }
  536. }
  537. }
  538. private void QuickSort(int[] a,int p,int r)
  539. {
  540. if (p < r) {
  541. int q = Partition(a,p,r);
  542. QuickSort(a,p,q);
  543. QuickSort(a,q+1,r);
  544. }
  545. }
  546. private int Partition(int[] a,int p,int r)
  547. {
  548. int x = a[p];
  549. int i = p - 1;
  550. int j = r + 1;
  551. while(true) {
  552. // decrement upper limit while values are greater then border value
  553. do {
  554. j--;
  555. }
  556. while(Key.CompareRecords(a[j],x) > 0); //while(a[j] > x);
  557. do {
  558. i++;
  559. }
  560. while(Key.CompareRecords(a[i],x) < 0); //while(a[i] < x);
  561. if (i<j) {
  562. int tmp = a[j];
  563. a[j] = a[i];
  564. a[i] = tmp;
  565. }
  566. else {
  567. return j;
  568. }
  569. }
  570. }
  571. private int BinarySearch(int[] a, int p, int r,int b)
  572. {
  573. int i = LazyBinarySearch(a,p,r,b);
  574. return (Key.CompareRecords(a[i],b) == 0) ? i : -1;
  575. }
  576. // Lazy binary search only returns the cell number the search finished in,
  577. // but does not checks that the correct value was actually found
  578. private int LazyBinarySearch(int[] a, int p, int r,int b)
  579. {
  580. if ( p == r ) {
  581. return p;
  582. }
  583. int q = (p+r) >> 1;
  584. int compare = Key.CompareRecords(a[q],b);
  585. if (compare < 0) { // if (a[q] < b) {
  586. return LazyBinarySearch(a,q+1,r,b);
  587. }
  588. else if (compare > 0) { // a[q] > b
  589. return LazyBinarySearch(a,p,q,b);
  590. }
  591. else { // a[q] == b
  592. return q;
  593. }
  594. }
  595. internal void AddRef()
  596. {
  597. _refCount++;
  598. }
  599. internal void RemoveRef()
  600. {
  601. _refCount--;
  602. }
  603. /*
  604. // Prints indexes. For debugging.
  605. internal void Print ()
  606. {
  607. for (int i=0; i < Size; i++) {
  608. Console.Write ("Index {0} record {1}: ", i, Array [i]);
  609. for (int j=0; j < Key.Table.Columns.Count; j++) {
  610. DataColumn col = Key.Table.Columns [j];
  611. if (Array [i] >= 0)
  612. Console.Write ("{0,15} ", col [Array [i]]);
  613. }
  614. Console.WriteLine ();
  615. }
  616. }
  617. */
  618. #endregion // Methods
  619. }
  620. }