Index.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699
  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 void Reset()
  136. {
  137. _array = null;
  138. RebuildIndex();
  139. }
  140. private void RebuildIndex()
  141. {
  142. // consider better capacity approximation
  143. _array = new int[Key.Table.RecordCache.CurrentCapacity];
  144. _size = 0;
  145. foreach(DataRow row in Key.Table.Rows) {
  146. int record = Key.GetRecord(row);
  147. if (record != -1) {
  148. _array[_size++] = record;
  149. }
  150. }
  151. _hasDuplicates = IndexDuplicatesState.False;
  152. // Note : MergeSort may update hasDuplicates to True
  153. Sort();
  154. }
  155. private void Sort()
  156. {
  157. //QuickSort(Array,0,Size-1);
  158. MergeSort(Array,Size);
  159. }
  160. /*
  161. * Returns record number of the record equal to the key values supplied
  162. * in the meaning of index key, or -1 if no equal record found.
  163. */
  164. internal int Find(object[] keys)
  165. {
  166. int index = FindIndex(keys);
  167. return IndexToRecord(index);
  168. }
  169. /*
  170. * Returns record index (location) of the record equal to the key values supplied
  171. * in the meaning of index key, or -1 if no equal record found.
  172. */
  173. internal int FindIndex(object[] keys)
  174. {
  175. if (keys == null || keys.Length != Key.Columns.Length) {
  176. throw new ArgumentException("Expecting " + Key.Columns.Length + " value(s) for the key being indexed, " +
  177. "but received " + ((keys == null) ? 0 : keys.Length) + " value(s).");
  178. }
  179. int tmp = Key.Table.RecordCache.NewRecord();
  180. try {
  181. // init key values for temporal record
  182. for(int i = 0; i < Key.Columns.Length; i++) {
  183. Key.Columns[i].DataContainer[tmp] = keys[i];
  184. }
  185. return FindIndex(tmp);
  186. }
  187. // catch(FormatException) {
  188. // return -1;
  189. // }
  190. // catch(InvalidCastException) {
  191. // return -1;
  192. // }
  193. finally {
  194. Key.Table.RecordCache.DisposeRecord(tmp);
  195. }
  196. }
  197. /*
  198. * Returns record number of the record equal to the record supplied
  199. * in the meaning of index key, or -1 if no equal record found.
  200. */
  201. internal int Find(int record)
  202. {
  203. int index = FindIndex(record);
  204. return IndexToRecord(index);
  205. }
  206. /*
  207. * Returns array of record numbers of the records equal equal to the key values supplied
  208. * in the meaning of index key, or -1 if no equal record found.
  209. */
  210. internal int[] FindAll(object[] keys)
  211. {
  212. int[] indexes = FindAllIndexes(keys);
  213. IndexesToRecords(indexes);
  214. return indexes;
  215. }
  216. /*
  217. * Returns array of indexes of the records inside the index equal equal to the key values supplied
  218. * in the meaning of index key, or -1 if no equal record found.
  219. */
  220. internal int[] FindAllIndexes(object[] keys)
  221. {
  222. if (keys == null || keys.Length != Key.Columns.Length) {
  223. throw new ArgumentException("Expecting " + Key.Columns.Length + " value(s) for the key being indexed," +
  224. "but received " + ((keys == null) ? 0 : keys.Length) + " value(s).");
  225. }
  226. int tmp = Key.Table.RecordCache.NewRecord();
  227. try {
  228. // init key values for temporal record
  229. for(int i = 0; i < Key.Columns.Length; i++) {
  230. Key.Columns[i].DataContainer[tmp] = keys[i];
  231. }
  232. return FindAllIndexes(tmp);
  233. }
  234. catch(FormatException) {
  235. return new int[0];
  236. }
  237. catch(InvalidCastException) {
  238. return new int[0];
  239. }
  240. finally {
  241. Key.Table.RecordCache.DisposeRecord(tmp);
  242. }
  243. }
  244. /*
  245. * Returns array of record numbers of the records equal to the record supplied
  246. * in the meaning of index key, or empty list if no equal records found.
  247. */
  248. internal int[] FindAll(int record)
  249. {
  250. int[] indexes = FindAllIndexes(record);
  251. IndexesToRecords(indexes);
  252. return indexes;
  253. }
  254. /*
  255. * Returns array of indexes of the records inside the index that equal to the record supplied
  256. * in the meaning of index key, or empty list if no equal records found.
  257. */
  258. internal int[] FindAllIndexes(int record)
  259. {
  260. int index = FindIndex(record);
  261. if (index == -1) {
  262. return new int[0];
  263. }
  264. int startIndex = index++;
  265. int endIndex = index;
  266. for(;startIndex >= 0 && Key.CompareRecords(Array[startIndex],record) == 0;startIndex--);
  267. for(;endIndex < Size && Key.CompareRecords(Array[endIndex],record) == 0;endIndex++);
  268. int length = endIndex - startIndex - 1;
  269. int[] indexes = new int[length];
  270. for(int i = 0; i < length; i++) {
  271. indexes[i] = ++startIndex;
  272. }
  273. return indexes;
  274. }
  275. /*
  276. * Returns index inside the array where record number of the record equal to the record supplied
  277. * in the meaning of index key is sored, or -1 if no equal record found.
  278. */
  279. private int FindIndex(int record)
  280. {
  281. if (Size == 0) {
  282. return -1;
  283. }
  284. return BinarySearch(Array,0,Size - 1,record);
  285. }
  286. /*
  287. * Finds exact location of the record specified
  288. */
  289. private int FindIndexExact(int record)
  290. {
  291. for (int i = 0, size = Size; i < size; i++)
  292. if (Array[i] == record)
  293. return i;
  294. return -1;
  295. }
  296. /*
  297. * Returns array of records from the indexes (locations) inside the index
  298. */
  299. private void IndexesToRecords(int[] indexes)
  300. {
  301. for(int i = 0; i < indexes.Length; i++) {
  302. indexes[i] = Array[indexes[i]];
  303. }
  304. }
  305. internal void Delete(DataRow row)
  306. {
  307. int oldRecord = Key.GetRecord(row);
  308. Delete(oldRecord);
  309. }
  310. internal void Delete(int oldRecord)
  311. {
  312. if (oldRecord == -1)
  313. return;
  314. int index = FindIndexExact(oldRecord);
  315. if (index != -1) {
  316. if ((_hasDuplicates == IndexDuplicatesState.True)) {
  317. int c1 = 1;
  318. int c2 = 1;
  319. if (index > 0) {
  320. c1 = Key.CompareRecords(Array[index - 1],oldRecord);
  321. }
  322. if (index < Size - 1) {
  323. c2 = Key.CompareRecords(Array[index + 1],oldRecord);
  324. }
  325. if (c1 == 0 ^ c2 == 0) {
  326. _hasDuplicates = IndexDuplicatesState.Unknown;
  327. }
  328. }
  329. Remove(index);
  330. }
  331. }
  332. private void Remove(int index)
  333. {
  334. if (Size > 1) {
  335. System.Array.Copy(Array,index+1,Array,index,Size - index - 1);
  336. }
  337. _size--;
  338. }
  339. internal void Update(DataRow row,int oldRecord, DataRowVersion oldVersion, DataRowState oldState)
  340. {
  341. bool contains = Key.ContainsVersion (oldState, oldVersion);
  342. int newRecord = Key.GetRecord(row);
  343. // the record did not appeared in the index before update
  344. if (oldRecord == -1 || Size == 0 || !contains) {
  345. if (newRecord >= 0) {
  346. if (FindIndexExact(newRecord) < 0)
  347. Add(row,newRecord);
  348. }
  349. return;
  350. }
  351. // the record will not appeare in the index after update
  352. if (newRecord < 0 || !Key.CanContain (newRecord)) {
  353. Delete (oldRecord);
  354. return;
  355. }
  356. int oldIdx = FindIndexExact(oldRecord);
  357. if( oldIdx == -1 ) {
  358. Add(row,newRecord);
  359. return;
  360. }
  361. int newIdx = -1;
  362. int compare = Key.CompareRecords(Array[oldIdx],newRecord);
  363. int start,end;
  364. int c1 = 1;
  365. int c2 = 1;
  366. if (compare == 0) {
  367. if (Array[oldIdx] == newRecord) {
  368. // we deal with the same record that didn't change
  369. // in the context of current index.
  370. // so , do nothing.
  371. return;
  372. }
  373. }
  374. else {
  375. if ((_hasDuplicates == IndexDuplicatesState.True)) {
  376. if (oldIdx > 0) {
  377. c1 = Key.CompareRecords(Array[oldIdx - 1],newRecord);
  378. }
  379. if (oldIdx < Size - 1) {
  380. c2 = Key.CompareRecords(Array[oldIdx + 1],newRecord);
  381. }
  382. if ((c1 == 0 ^ c2 == 0) && compare != 0) {
  383. _hasDuplicates = IndexDuplicatesState.Unknown;
  384. }
  385. }
  386. }
  387. if ((oldIdx == 0 && compare > 0) || (oldIdx == (Size - 1) && compare < 0) || (compare == 0)) {
  388. // no need to switch cells
  389. newIdx = oldIdx;
  390. }
  391. else {
  392. if (compare < 0) {
  393. // search after the old place
  394. start = oldIdx + 1;
  395. end = Size - 1;
  396. }
  397. else {
  398. // search before the old palce
  399. start = 0;
  400. end = oldIdx - 1;
  401. }
  402. newIdx = LazyBinarySearch(Array,start,end,newRecord);
  403. if (oldIdx < newIdx) {
  404. System.Array.Copy(Array,oldIdx + 1,Array,oldIdx,newIdx - oldIdx);
  405. if (Key.CompareRecords (Array [newIdx], newRecord) > 0)
  406. --newIdx;
  407. }
  408. else if (oldIdx > newIdx){
  409. System.Array.Copy(Array,newIdx,Array,newIdx + 1,oldIdx - newIdx);
  410. if (Key.CompareRecords (Array [newIdx], newRecord) < 0)
  411. ++newIdx;
  412. }
  413. }
  414. Array[newIdx] = newRecord;
  415. if (compare != 0) {
  416. if (!(_hasDuplicates == IndexDuplicatesState.True)) {
  417. if (newIdx > 0) {
  418. c1 = Key.CompareRecords(Array[newIdx - 1],newRecord);
  419. }
  420. if (newIdx < Size - 1) {
  421. c2 = Key.CompareRecords(Array[newIdx + 1],newRecord);
  422. }
  423. if (c1 == 0 || c2 == 0) {
  424. _hasDuplicates = IndexDuplicatesState.True;
  425. }
  426. }
  427. }
  428. }
  429. internal void Add(DataRow row) {
  430. Add(row, Key.GetRecord(row));
  431. }
  432. private void Add(DataRow row,int newRecord)
  433. {
  434. int newIdx;
  435. if (newRecord < 0 || !Key.CanContain (newRecord))
  436. return;
  437. if (Size == 0) {
  438. newIdx = 0;
  439. }
  440. else {
  441. newIdx = LazyBinarySearch(Array,0,Size - 1,newRecord);
  442. // if newl value is greater - insert afer old value
  443. // else - insert before old value
  444. if (Key.CompareRecords(Array[newIdx],newRecord) < 0) {
  445. newIdx++;
  446. }
  447. }
  448. Insert(newIdx,newRecord);
  449. int c1 = 1;
  450. int c2 = 1;
  451. if (!(_hasDuplicates == IndexDuplicatesState.True)) {
  452. if (newIdx > 0) {
  453. c1 = Key.CompareRecords(Array[newIdx - 1],newRecord);
  454. }
  455. if (newIdx < Size - 1) {
  456. c2 = Key.CompareRecords(Array[newIdx + 1],newRecord);
  457. }
  458. if (c1 == 0 || c2 == 0) {
  459. _hasDuplicates = IndexDuplicatesState.True;
  460. }
  461. }
  462. }
  463. private void Insert(int index,int r)
  464. {
  465. if (Array.Length == Size) {
  466. int[] tmp = (Size == 0) ? new int[16] : new int[Size << 1];
  467. System.Array.Copy(Array,0,tmp,0,index);
  468. tmp[index] = r;
  469. System.Array.Copy(Array,index,tmp,index + 1,Size - index);
  470. _array = tmp;
  471. }
  472. else {
  473. System.Array.Copy(Array,index,Array,index + 1,Size - index);
  474. Array[index] = r;
  475. }
  476. _size++;
  477. }
  478. private void MergeSort(int[] to, int length)
  479. {
  480. int[] from = new int[length];
  481. System.Array.Copy(to, 0, from, 0, from.Length);
  482. MergeSort(from, to, 0, from.Length);
  483. }
  484. private void MergeSort(int[] from, int[] to,int p, int r)
  485. {
  486. int q = (p + r) >> 1;
  487. if (q == p) {
  488. return;
  489. }
  490. MergeSort(to, from, p, q);
  491. MergeSort(to, from, q, r);
  492. // merge
  493. for (int middle = q, current = p;;) {
  494. int res = Key.CompareRecords(from[p],from[q]);
  495. if (res > 0) {
  496. to[current++] = from[q++];
  497. if (q == r) {
  498. while( p < middle) {
  499. to[current++] = from[p++];
  500. }
  501. break;
  502. }
  503. }
  504. else {
  505. if (res == 0) {
  506. _hasDuplicates = IndexDuplicatesState.True;
  507. }
  508. to[current++] = from[p++];
  509. if (p == middle) {
  510. while( q < r) {
  511. to[current++] = from[q++];
  512. }
  513. break;
  514. }
  515. }
  516. }
  517. }
  518. private void QuickSort(int[] a,int p,int r)
  519. {
  520. if (p < r) {
  521. int q = Partition(a,p,r);
  522. QuickSort(a,p,q);
  523. QuickSort(a,q+1,r);
  524. }
  525. }
  526. private int Partition(int[] a,int p,int r)
  527. {
  528. int x = a[p];
  529. int i = p - 1;
  530. int j = r + 1;
  531. while(true) {
  532. // decrement upper limit while values are greater then border value
  533. do {
  534. j--;
  535. }
  536. while(Key.CompareRecords(a[j],x) > 0); //while(a[j] > x);
  537. do {
  538. i++;
  539. }
  540. while(Key.CompareRecords(a[i],x) < 0); //while(a[i] < x);
  541. if (i<j) {
  542. int tmp = a[j];
  543. a[j] = a[i];
  544. a[i] = tmp;
  545. }
  546. else {
  547. return j;
  548. }
  549. }
  550. }
  551. private int BinarySearch(int[] a, int p, int r,int b)
  552. {
  553. int i = LazyBinarySearch(a,p,r,b);
  554. return (Key.CompareRecords(a[i],b) == 0) ? i : -1;
  555. }
  556. // Lazy binary search only returns the cell number the search finished in,
  557. // but does not checks that the correct value was actually found
  558. private int LazyBinarySearch(int[] a, int p, int r,int b)
  559. {
  560. if ( p == r ) {
  561. return p;
  562. }
  563. int q = (p+r) >> 1;
  564. int compare = Key.CompareRecords(a[q],b);
  565. if (compare < 0) { // if (a[q] < b) {
  566. return LazyBinarySearch(a,q+1,r,b);
  567. }
  568. else if (compare > 0) { // a[q] > b
  569. return LazyBinarySearch(a,p,q,b);
  570. }
  571. else { // a[q] == b
  572. return q;
  573. }
  574. }
  575. internal void AddRef()
  576. {
  577. _refCount++;
  578. }
  579. internal void RemoveRef()
  580. {
  581. _refCount--;
  582. }
  583. /*
  584. // Prints indexes. For debugging.
  585. internal void Print ()
  586. {
  587. for (int i=0; i < Size; i++) {
  588. Console.Write ("Index {0} record {1}: ", i, Array [i]);
  589. for (int j=0; j < Key.Table.Columns.Count; j++) {
  590. DataColumn col = Key.Table.Columns [j];
  591. if (Array [i] >= 0)
  592. Console.Write ("{0,15} ", col [Array [i]]);
  593. }
  594. Console.WriteLine ();
  595. }
  596. }
  597. */
  598. #endregion // Methods
  599. }
  600. }