Index.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696
  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. }
  406. else if (oldIdx > newIdx){
  407. System.Array.Copy(Array,newIdx,Array,newIdx + 1,oldIdx - newIdx);
  408. }
  409. }
  410. Array[newIdx] = newRecord;
  411. if (compare != 0) {
  412. if (!(_hasDuplicates == IndexDuplicatesState.True)) {
  413. if (newIdx > 0) {
  414. c1 = Key.CompareRecords(Array[newIdx - 1],newRecord);
  415. }
  416. if (newIdx < Size - 1) {
  417. c2 = Key.CompareRecords(Array[newIdx + 1],newRecord);
  418. }
  419. if (c1 == 0 || c2 == 0) {
  420. _hasDuplicates = IndexDuplicatesState.True;
  421. }
  422. }
  423. }
  424. }
  425. internal void Add(DataRow row) {
  426. Add(row, Key.GetRecord(row));
  427. }
  428. private void Add(DataRow row,int newRecord)
  429. {
  430. int newIdx;
  431. if (newRecord < 0 || !Key.CanContain (newRecord))
  432. return;
  433. if (Size == 0) {
  434. newIdx = 0;
  435. }
  436. else {
  437. newIdx = LazyBinarySearch(Array,0,Size - 1,newRecord);
  438. // if newl value is greater - insert afer old value
  439. // else - insert before old value
  440. if (Key.CompareRecords(Array[newIdx],newRecord) < 0) {
  441. newIdx++;
  442. }
  443. }
  444. Insert(newIdx,newRecord);
  445. int c1 = 1;
  446. int c2 = 1;
  447. if (!(_hasDuplicates == IndexDuplicatesState.True)) {
  448. if (newIdx > 0) {
  449. c1 = Key.CompareRecords(Array[newIdx - 1],newRecord);
  450. }
  451. if (newIdx < Size - 1) {
  452. c2 = Key.CompareRecords(Array[newIdx + 1],newRecord);
  453. }
  454. if (c1 == 0 || c2 == 0) {
  455. _hasDuplicates = IndexDuplicatesState.True;
  456. }
  457. }
  458. }
  459. private void Insert(int index,int r)
  460. {
  461. if (Array.Length == Size) {
  462. int[] tmp = (Size == 0) ? new int[16] : new int[Size << 1];
  463. System.Array.Copy(Array,0,tmp,0,index);
  464. tmp[index] = r;
  465. System.Array.Copy(Array,index,tmp,index + 1,Size - index);
  466. _array = tmp;
  467. }
  468. else {
  469. System.Array.Copy(Array,index,Array,index + 1,Size - index);
  470. Array[index] = r;
  471. }
  472. _size++;
  473. }
  474. private void MergeSort(int[] to, int length)
  475. {
  476. int[] from = new int[length];
  477. System.Array.Copy(to, 0, from, 0, from.Length);
  478. MergeSort(from, to, 0, from.Length);
  479. }
  480. private void MergeSort(int[] from, int[] to,int p, int r)
  481. {
  482. int q = (p + r) >> 1;
  483. if (q == p) {
  484. return;
  485. }
  486. MergeSort(to, from, p, q);
  487. MergeSort(to, from, q, r);
  488. // merge
  489. for (int middle = q, current = p;;) {
  490. int res = Key.CompareRecords(from[p],from[q]);
  491. if (res > 0) {
  492. to[current++] = from[q++];
  493. if (q == r) {
  494. while( p < middle) {
  495. to[current++] = from[p++];
  496. }
  497. break;
  498. }
  499. }
  500. else {
  501. if (res == 0) {
  502. _hasDuplicates = IndexDuplicatesState.True;
  503. }
  504. to[current++] = from[p++];
  505. if (p == middle) {
  506. while( q < r) {
  507. to[current++] = from[q++];
  508. }
  509. break;
  510. }
  511. }
  512. }
  513. }
  514. private void QuickSort(int[] a,int p,int r)
  515. {
  516. if (p < r) {
  517. int q = Partition(a,p,r);
  518. QuickSort(a,p,q);
  519. QuickSort(a,q+1,r);
  520. }
  521. }
  522. private int Partition(int[] a,int p,int r)
  523. {
  524. int x = a[p];
  525. int i = p - 1;
  526. int j = r + 1;
  527. while(true) {
  528. // decrement upper limit while values are greater then border value
  529. do {
  530. j--;
  531. }
  532. while(Key.CompareRecords(a[j],x) > 0); //while(a[j] > x);
  533. do {
  534. i++;
  535. }
  536. while(Key.CompareRecords(a[i],x) < 0); //while(a[i] < x);
  537. if (i<j) {
  538. int tmp = a[j];
  539. a[j] = a[i];
  540. a[i] = tmp;
  541. }
  542. else {
  543. return j;
  544. }
  545. }
  546. }
  547. private int BinarySearch(int[] a, int p, int r,int b)
  548. {
  549. int i = LazyBinarySearch(a,p,r,b);
  550. return (Key.CompareRecords(a[i],b) == 0) ? i : -1;
  551. }
  552. // Lazy binary search only returns the cell number the search finished in,
  553. // but does not checks that the correct value was actually found
  554. private int LazyBinarySearch(int[] a, int p, int r,int b)
  555. {
  556. if ( p == r ) {
  557. return p;
  558. }
  559. int q = (p+r) >> 1;
  560. int compare = Key.CompareRecords(a[q],b);
  561. if (compare < 0) { // if (a[q] < b) {
  562. return LazyBinarySearch(a,q+1,r,b);
  563. }
  564. else if (compare > 0) { // a[q] > b
  565. return LazyBinarySearch(a,p,q,b);
  566. }
  567. else { // a[q] == b
  568. return q;
  569. }
  570. }
  571. internal void AddRef()
  572. {
  573. _refCount++;
  574. }
  575. internal void RemoveRef()
  576. {
  577. _refCount--;
  578. }
  579. /*
  580. // Prints indexes. For debugging.
  581. internal void Print ()
  582. {
  583. for (int i=0; i < Size; i++) {
  584. Console.Write ("Index {0} record {1}: ", i, Array [i]);
  585. for (int j=0; j < Key.Table.Columns.Count; j++) {
  586. DataColumn col = Key.Table.Columns [j];
  587. if (Array [i] >= 0)
  588. Console.Write ("{0,15} ", col [Array [i]]);
  589. }
  590. Console.WriteLine ();
  591. }
  592. }
  593. */
  594. #endregion // Methods
  595. }
  596. }