-
Notifications
You must be signed in to change notification settings - Fork 0
/
osndxfio.cpp
1541 lines (1297 loc) · 57.8 KB
/
osndxfio.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Copyright (C) 2024, Kees Krijnen.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTIBILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/> for a
* copy.
*
* License: LGPL, v3, as defined and found on www.gnu.org,
* https://www.gnu.org/licenses/lgpl-3.0.html
*
* Description:
*
* The OSNDXFIO module is a set of functions and definitions to setup a low
* level database (no query language). It is similar to the VMS operating
* system indexed file I/O functionality.
*
* The OSNDXFIO package opens files without exclusive access and provides no
* locking/synchronization mechanisms for read/write. Hence, the applications
* using OSNDXFIO services for database access should use proper
* synchronization mechanisms. Otherwise, data integrity is not guaranteed.
*
* The OSNDXFIO module creates, rebuilds, opens, closes, and deletes databases.
* The OSNDXFIO module reads, writes, updates, seeks, and deletes data objects.
* The OSNDXFIO module is responsible for providing indexing mechanism and
* defines an index structure that is generic. Applications can define their
* own index structures, known as the search key in the OSNDXFIO context. There
* is a practical limit to the number of search keys applied due to performance
* and memory requirements.
*
* A key descriptor provides information to generate the search key for one
* single key. The search key could be build from several key segments.
*/
// ---- system include files ----
#include <stdlib.h>
#include <string.h>
// ---- include files ----
#include <osfio.hpp>
#include <osndxfio.hpp>
// ---- local symbol definitions ----
#define NDXFIO_VERSION 0x01000000 // major.minor.patch - major, minor = 8 bits
#define MAX_MALLOC (1 << 30) // maximum memory allocation 2**30
/** Index record status. Do not modify or erase regarding backward
compatibility! */
enum eINDEX_STATUS {
eRESERVED = -2, // Used for file storage.
eOK = -1, // Used for file storage.
eDELETED = 0 // Index id >= 0.
};
/** Index structure. The index structure is followed by the application key. */
struct sINDEX {
union {
S32 status; // Status of the index record
S32 prevDeletedIndex; // The offset is not valid when record is deleted.
}; // If >= zero this field points to the previous
// deleted record.
U32 offset; // Byte offset of index record in the file
U32 dataOffset; // Byte offset of data record in the file
U32 dataSize; // Size of the object in the file, see offset.
U32 recordRef; // Verification reference for data records.
/** KEY **/ // Start of application key
sINDEX() // Constructor.
:
status( eRESERVED ),
offset( U32( INVALID_VALUE )),
dataOffset( U32( INVALID_VALUE )),
dataSize( 0 ),
recordRef( 0 ) {
}
};
/** Data record id. Do not modify or erase regarding backward compatibility! */
enum eRECORD_ID {
eHEADER = -4,
eINDEX = -3,
eNEXT_INDEX = -2,
eDELETED_DATA = -1, // Deleted data.
eDATA = 0 // Data id >= 0.
};
/** Data record struct. Adjacent this record the data is saved. */
struct sDATA {
S32 id; // Type of data record (eRECORD_ID).
U32 recordRef; // Verification reference for data records, should
union { // match with record reference given by index record.
U32 size; // Number of bytes occupied. Could be less than space
// to offset to next record.
U32 nextIndexOffset; // Reference to next index record if record id ==
}; // NEXT_INDEX.
U32 offset; // Offset to next record.
};
/** Database header struct. */
struct sHEADER {
U32 version;
U32 recordReference; // Verification reference, increased every
// record creation.
U32 nextFreeData; // Offset to free data position.
U32 nrOfRecords; // Number of all valid records (status == eOK).
U32 nrOfIndexRecords; // Total of all index records,
// status == eOK, eDELETED, eRESERVED.
S32 lastDeletedIndex; // Offset to last deleted index record.
U32 nextFreeIndex; // Offset to free index position.
U16 reservedIndexRecords;
U16 nrOfKeys; // Number of defined search index keys.
U16 totalKeySize; // Sum of all key descriptor segment data
// search key sizes. Used for indexing.
U16 keyDescriptorSize; // Size sum of all key descriptor segments,
// key descriptor is stored adjacent to header.
sHEADER() // Constructor.
:
version( NDXFIO_VERSION ),
recordReference( 0 ), // Reference incremented every record creation.
nextFreeData( 0 ),
nrOfRecords( 0 ),
nrOfIndexRecords( 0 ),
lastDeletedIndex( INVALID_VALUE ),
nextFreeIndex( 0 ),
reservedIndexRecords( OSNDXFIO::DEFAULT_RESERVED_INDEX_RECORDS ),
nrOfKeys( 0 ),
totalKeySize( 0 ),
keyDescriptorSize( 0 ) {
}
};
/** Key index struct. */
struct sKEY_INDEX {
U32* apRecord;
U32 recordCount; // ( Record count * sizeof( *apRecord )) == memory
// allocated for apRecord.
U32 position;
U32 selectionStart;
U32 selectionEnd;
U16 keyOffset;
U16 keySize;
bool bSorted;
sKEY_INDEX() // Constructor.
:
apRecord( NULL ),
recordCount( 0 ),
position( U32( INVALID_VALUE )),
selectionStart( U32( INVALID_VALUE )),
selectionEnd( U32( INVALID_VALUE )),
keyOffset( U16( INVALID_VALUE )),
keySize( 0 ),
bSorted( false ) {
}
};
/** Database handle list */
struct OSNDXFIO::sHANDLE : sHEADER { // Inherit sHEADER
OSNDXFIO::sHANDLE* pPrevious;
OSNDXFIO::sHANDLE* pNext;
OSFIO fileHandle;
char* pDatabaseName;
bool readOnly;
// Key index part.
bool reindexRequested;
sKEY_INDEX* apKeyIndex;
BYTE* apKey; // sINDEX + totalKeySize == totalIndexSize.
sKEY_DESC* apKeyDescriptor;
U32 allocatedIndexKeys; // Required for allocating memory for
// apKey and apKeyIndex[ keys ].apRecord.
U16 totalIndexSize;
sHANDLE() // Constructor.
:
pPrevious( NULL ),
pNext( NULL ),
fileHandle(),
pDatabaseName( NULL ),
readOnly( false ),
reindexRequested( false ),
apKeyIndex( NULL ),
apKey( NULL ),
apKeyDescriptor( NULL ),
allocatedIndexKeys( 0 ),
totalIndexSize( 0 ) {
}
};
// ---- local functions prototypes ----
static bool isDatabaseNameValid( const STRING in_databaseName );
static bool isKeyDescriptorValid(
U16 in_nrOfKeys,
const OSNDXFIO::sKEY_DESC in_keyDesc[],
U16& out_keyDescSize,
U16& out_totalKeySize );
static bool initKeyIndexArray(
OSNDXFIO::sHANDLE* pHandle,
U16 key );
static bool initKeyArray( OSNDXFIO::sHANDLE* pHandle );
static bool createReservedIndexRecords(
OSFIO& handle,
U32 filePointer,
U16 reservedIndexRecords,
U16 totalKeySize );
static void shellSort(
OSNDXFIO::sHANDLE* const pHandle,
U16 const in_keyId );
static bool generateSearchKey(
const OSNDXFIO::sHANDLE* pHandle,
const OSNDXFIO::sRECORD& in_rRecord,
BYTE* out_pSearchKey );
static bool convertKeySegment(
BYTE* pKeySegment,
BYTE in_keySegmentType );
static void swap( U16* pU16 );
static void swap( U32* pU32 );
// ---- local data ----
static OSNDXFIO::sHANDLE* pDatabaseListEntry = NULL;
// ---- constructor ----
OSNDXFIO::OSNDXFIO()
:
m_handle( NULL ),
m_error( NO_ERROR ) {
}
// ---- destructor ----
OSNDXFIO::~OSNDXFIO() {
if ( NULL != m_handle ) {
close();
}
}
/*============================================================================*/
bool OSNDXFIO::open( const STRING in_databaseName,
bool in_readOnly,
U32 in_allocatedIndexKeys )
/*============================================================================*/
{
m_error = INVALID_PARAMETERS;
// Check function parameters.
bool statusOk = isDatabaseNameValid( in_databaseName );
if ( statusOk ) {
m_error = DATABASE_ALREADY_OPENED;
statusOk = ( NULL == m_handle );
}
if ( statusOk ) {
m_handle = new sHANDLE;
m_error = MEMORY_ALLOCATION_ERROR;
statusOk = ( NULL != m_handle );
}
// Check database existence.
if ( statusOk ) {
statusOk = m_handle->fileHandle.open( in_databaseName, in_readOnly );
}
sDATA data;
if ( statusOk ) {
// Read and verify header.
m_error = DATABASE_IO_ERROR;
statusOk = statusOk && m_handle->fileHandle.read( &data, sizeof( data ));
// Check record id is correct.
statusOk = statusOk && ( data.id == eHEADER );
// Read header.
statusOk = statusOk && m_handle->fileHandle.read( m_handle, sizeof( sHEADER ));
}
if ( statusOk ) {
U64 allocatedIndexKeys = m_handle->nrOfIndexRecords + in_allocatedIndexKeys;
m_error = MEMORY_ALLOCATION_ERROR;
// Initialize input parameters.
if ( allocatedIndexKeys < MAX_MALLOC ) {
m_handle->readOnly = in_readOnly;
m_handle->allocatedIndexKeys = in_readOnly ?
m_handle->nrOfIndexRecords : (U32)allocatedIndexKeys;
m_handle->pDatabaseName = (char*)::malloc( ::strlen( in_databaseName ) + 1 );
}
statusOk = ( NULL != m_handle->pDatabaseName );
}
if ( statusOk ) {
::strcpy( m_handle->pDatabaseName, in_databaseName );
m_handle->apKeyIndex = (sKEY_INDEX*) ::malloc( m_handle->nrOfKeys * sizeof( sKEY_INDEX ));
m_handle->apKeyDescriptor = (sKEY_DESC*) ::malloc( m_handle->nrOfKeys * sizeof( sKEY_DESC ));
// Check if memory allocation was successful.
statusOk = ( NULL != m_handle->apKeyIndex );
statusOk = statusOk && ( NULL != m_handle->apKeyDescriptor );
}
if ( statusOk ) {
U16 totalSegmentSize = 0;
U16 keyOffset = sizeof( sINDEX );
// Initialize memory.
::memset( m_handle->apKeyIndex, 0, ( m_handle->nrOfKeys * sizeof( sKEY_INDEX )));
::memset( m_handle->apKeyDescriptor, 0, ( m_handle->nrOfKeys * sizeof( sKEY_DESC )));
// Read all key segments and key index records.
for ( U16 i = 0; statusOk && ( i < m_handle->nrOfKeys ); i++ ) {
// Read number of segments.
statusOk = statusOk && m_handle->fileHandle.read(
&( m_handle->apKeyDescriptor[ i ].nrOfSegments ),
sizeof( m_handle->apKeyDescriptor[ 0 ].nrOfSegments ));
if ( statusOk ) {
totalSegmentSize = U16( m_handle->apKeyDescriptor[ i ].nrOfSegments *
sizeof( *(m_handle->apKeyDescriptor[ 0 ].apSegment)));
// Allocate memory for key segments.
m_handle->apKeyDescriptor[ i ].apSegment = (sKEY_SEGMENT*)
::malloc( totalSegmentSize );
}
// Check if memory allocation was successful.
statusOk = statusOk &&
( NULL != m_handle->apKeyDescriptor[ i ].apSegment );
// Read all segments per key.
statusOk = statusOk && m_handle->fileHandle.read(
m_handle->apKeyDescriptor[ i ].apSegment, totalSegmentSize );
if ( statusOk ) {
U16 keySize = 0;
for ( U16 j = 0; j < m_handle->apKeyDescriptor[ i ].nrOfSegments; j++ ) {
keySize += m_handle->apKeyDescriptor[ i ].apSegment[ j ].size;
}
m_handle->apKeyIndex[ i ].keyOffset = keyOffset;
m_handle->apKeyIndex[ i ].keySize = keySize;
keyOffset += keySize;
statusOk = initKeyIndexArray( m_handle, i );
}
}
}
if ( statusOk ) {
U16 keyDescriptorSize = 0;
U16 totalKeySize = 0;
m_error = INVALID_KEY_DESCRIPTOR;
// Check validity key descriptor.
statusOk = ( isKeyDescriptorValid( m_handle->nrOfKeys,
m_handle->apKeyDescriptor, keyDescriptorSize, totalKeySize ) &&
( keyDescriptorSize == m_handle->keyDescriptorSize ) &&
( totalKeySize == m_handle->totalKeySize ));
}
if ( statusOk ) {
m_handle->totalIndexSize = (U16)( sizeof( sINDEX ) + m_handle->totalKeySize );
m_error = MEMORY_ALLOCATION_ERROR;
statusOk = initKeyArray( m_handle );
statusOk = statusOk && m_handle->fileHandle.read( &data, sizeof( data ));
// Check INDEX has been read.
statusOk = statusOk && ( data.id == eINDEX );
// Read all index and application key records.
BYTE* pByte = (BYTE*)m_handle->apKey;
U16 reservedIndexCounter = 0;
for ( U32 k = 0; statusOk && ( k < m_handle->nrOfIndexRecords ); k++ ) {
if ( reservedIndexCounter == m_handle->reservedIndexRecords ) {
// Check record ids and read next index offset.
statusOk = statusOk && m_handle->fileHandle.read( &data, sizeof( data ));
statusOk = statusOk && ( data.id == eNEXT_INDEX );
statusOk = statusOk && m_handle->fileHandle.read( data.nextIndexOffset, &data, sizeof( data ));
statusOk = statusOk && ( data.id == eINDEX );
reservedIndexCounter = 0;
}
// Deleted records are read as well!
statusOk = statusOk && m_handle->fileHandle.read( pByte, m_handle->totalIndexSize );
pByte += m_handle->totalIndexSize;
reservedIndexCounter++;
}
}
if ( statusOk ) {
if ( NULL == pDatabaseListEntry ) {
pDatabaseListEntry = m_handle;
pDatabaseListEntry->pPrevious = NULL;
} else {
// Find last NDXFIO handle.
sHANDLE* pHandle = pDatabaseListEntry;
while ( NULL != pHandle->pNext ) {
pHandle = pHandle->pNext;
}
// Update database handle administration.
pHandle->pNext = m_handle;
m_handle->pPrevious = pHandle;
}
m_handle->pNext = NULL;
m_error = NO_ERROR;
for ( U16 keyId = 0; keyId < m_handle->nrOfKeys; keyId++ ) {
shellSort( m_handle, keyId );
}
} else {
close();
}
return statusOk;
}
/*============================================================================*/
bool OSNDXFIO::create( const STRING in_databaseName,
U16 in_nrOfKeys,
const sKEY_DESC in_keyDescriptor[],
U16 in_reservedIndexRecords )
/*============================================================================*/
{
// Check function parameters.
if ( !isDatabaseNameValid( in_databaseName ) ||
( 0 == in_nrOfKeys ) ||
( NULL == in_keyDescriptor ) ||
( in_reservedIndexRecords < 10 ) || // MINIMUM_RESERVED_INDEX_RECORDS
( in_reservedIndexRecords > MAXIMUM_RESERVED_INDEX_RECORDS )) {
m_error = INVALID_PARAMETERS;
UNSUCCESSFUL_RETURN; // Exit create().
}
if ( NULL != m_handle ) {
m_error = DATABASE_ALREADY_OPENED;
UNSUCCESSFUL_RETURN; // Exit create().
}
U16 keyDescriptorSize = 0;
U16 totalKeySize = 0;
if ( !isKeyDescriptorValid(
in_nrOfKeys, in_keyDescriptor, keyDescriptorSize, totalKeySize )) {
m_error = INVALID_KEY_DESCRIPTOR;
UNSUCCESSFUL_RETURN; // Exit create().
}
// Check database existence.
OSFIO fileHandle;
if ( fileHandle.open( in_databaseName, READ_ONLY_ACCESS )) {
m_error = DATABASE_ALREADY_EXIST;
UNSUCCESSFUL_RETURN; // Exit create().
}
// Create database.
bool statusOk = ( fileHandle.create( in_databaseName ));
if ( statusOk ) {
sDATA record;
sHEADER header;
m_error = DATABASE_IO_ERROR;
/*------------------------------------------------------------------*/
/* Data file creation. Since file contents can't be read with */
/* create call alone, file is opened explicitly with open call */
/* after closing the created file */
/*------------------------------------------------------------------*/
statusOk = fileHandle.close();
statusOk = statusOk && fileHandle.open( in_databaseName );
record.id = eHEADER;
record.size = sizeof( header ) + keyDescriptorSize;
// Data header initialization.
header.reservedIndexRecords = in_reservedIndexRecords;
header.nrOfIndexRecords = header.reservedIndexRecords;
header.nextFreeIndex = sizeof( record /* header id */ ) + record.size +
sizeof( record /* index id */ );
header.nextFreeData = header.nextFreeIndex + ( header.reservedIndexRecords *
( sizeof( sINDEX ) + totalKeySize )) +
sizeof( record ); /* next index id */
header.nrOfKeys = in_nrOfKeys;
header.totalKeySize = totalKeySize;
header.keyDescriptorSize = keyDescriptorSize;
statusOk = statusOk && fileHandle.write( &record, sizeof( record ));
statusOk = statusOk && fileHandle.write( &header, sizeof( header ));
for ( int i = 0; statusOk && ( i < in_nrOfKeys ); i++ ) {
statusOk = statusOk && fileHandle.write(
&in_keyDescriptor[ i ].nrOfSegments,
sizeof( in_keyDescriptor[ 0 ].nrOfSegments ));
statusOk = statusOk && fileHandle.write(
in_keyDescriptor[ i ].apSegment, // Pointer to array of key segments.
( in_keyDescriptor[ i ].nrOfSegments *
sizeof( *(in_keyDescriptor[ i ].apSegment))));
}
statusOk = statusOk && createReservedIndexRecords(
fileHandle,
( sizeof( record /* header id */ ) +
record.size ),
header.reservedIndexRecords,
header.totalKeySize );
}
fileHandle.close();
if ( statusOk ) {
statusOk = open( in_databaseName );
}
return statusOk;
}
/*============================================================================*/
bool OSNDXFIO::close()
/*============================================================================*/
{
if ( NULL != m_handle ) {
if ( !m_handle->fileHandle.close() ) {
m_error = NO_DATABASE;
}
// Update the database administration.
if ( NULL != m_handle->pPrevious ) {
(m_handle->pPrevious)->pNext = m_handle->pNext;
}
if ( NULL != m_handle->pNext ) {
(m_handle->pNext)->pPrevious = m_handle->pPrevious;
}
// Release all allocated memory.
::free( m_handle->apKey );
for ( int i = 0; i < m_handle->nrOfKeys; i++ ) {
::free( m_handle->apKeyDescriptor[ i ].apSegment );
::free( m_handle->apKeyIndex[ i ].apRecord );
}
::free( m_handle->apKeyDescriptor );
::free( m_handle->apKeyIndex );
::free( m_handle->pDatabaseName );
delete m_handle;
m_handle = NULL;
}
return ( m_error != NO_DATABASE );
}
/*============================================================================*/
bool OSNDXFIO::rebuild( const STRING in_databaseName,
U16 in_nrOfKeys,
const sKEY_DESC in_keyDescriptor[],
U32 in_maxDataSize )
/*============================================================================*/
{
U32 nbOfRecords = getNrOfRecords();
if ( 0 == nbOfRecords ) {
m_error = EMPTY_DATABASE;
UNSUCCESSFUL_RETURN; // Exit rebuild().
}
BYTE* pData = (BYTE*)::malloc( in_maxDataSize );
if ( NULL == pData ) {
m_error = MEMORY_ALLOCATION_ERROR;
UNSUCCESSFUL_RETURN; // Exit rebuild().
}
OSNDXFIO rebuild_db;
bool statusOk = rebuild_db.create( in_databaseName, in_nrOfKeys, in_keyDescriptor, nbOfRecords );
sRECORD record;
record.pData = pData;
U32 index;
for ( index = 0; statusOk && ( index < m_handle->nrOfIndexRecords ); index++ ) {
sINDEX* pIndex = (sINDEX*)( m_handle->apKey + ( m_handle->totalIndexSize * index ));
if ( pIndex->status == eOK ) {
U32 temp;
if ( in_maxDataSize < pIndex->dataSize ) {
in_maxDataSize = pIndex->dataSize;
record.allocatedSize = in_maxDataSize;
record.pData = (BYTE*)::realloc( pData, in_maxDataSize );
}
statusOk = getRecord( index, record );
statusOk = statusOk && rebuild_db.createRecord( record, temp );
}
}
::free( pData );
(void)rebuild_db.close();
return statusOk;
}
/*============================================================================*/
U16 OSNDXFIO::getNrOfKeys()
/*============================================================================*/
{
return m_handle->nrOfKeys;
}
/*============================================================================*/
U16 OSNDXFIO::getKeySize( U16 in_keyId )
/*============================================================================*/
{
if ( in_keyId < m_handle->nrOfKeys ) {
return m_handle->apKeyIndex[ in_keyId ].keySize;
}
return 0;
}
/*============================================================================*/
U32 OSNDXFIO::getNrOfRecords()
/*============================================================================*/
{
return m_handle->nrOfRecords;
}
/*============================================================================*/
bool OSNDXFIO::createRecord( sRECORD& in_rRecord,
U32& out_rIndex )
/*============================================================================*/
{
BYTE* pSearchKey = (BYTE*)( ::malloc( m_handle->totalKeySize ));
if ( NULL == pSearchKey ) {
m_error = MEMORY_ALLOCATION_ERROR;
UNSUCCESSFUL_RETURN; // Exit createRecord().
}
if ( !generateSearchKey( m_handle, in_rRecord, pSearchKey )) {
m_error = RECORD_TOO_SMALL;
::free( pSearchKey );
UNSUCCESSFUL_RETURN; // Exit createRecord().
}
bool deletedRecordAvailable = ( m_handle->lastDeletedIndex >= 0 );
U32 indexOffset = deletedRecordAvailable ? m_handle->lastDeletedIndex :
m_handle->nextFreeIndex;
sDATA data;
sINDEX index;
sHEADER header = *m_handle;
bool statusOk;
m_error = DATABASE_IO_ERROR;
do {
// Read index record.
statusOk = m_handle->fileHandle.read( indexOffset, &index, sizeof( index ));
if ( deletedRecordAvailable ) {
statusOk = statusOk && ( index.status >= eDELETED );
// Read data record.
statusOk = statusOk && m_handle->fileHandle.read( index.dataOffset,
&data,
sizeof( data ));
statusOk = statusOk && // Verify data record.
( data.id == eDELETED_DATA ) &&
( index.recordRef == data.recordRef );
if ( statusOk ) {
if ( in_rRecord.dataSize <= data.size ) {
// This record is not available anymore for overwriting.
deletedRecordAvailable = false;
header.lastDeletedIndex = (U32)index.prevDeletedIndex;
} else {
indexOffset = index.prevDeletedIndex;
if ( indexOffset < 0 ) { // There are no more deleted records found.
deletedRecordAvailable = false;
// Reread index record and check index record id.
statusOk = m_handle->fileHandle.read( m_handle->nextFreeIndex,
&index,
sizeof( index ));
statusOk = statusOk && ( index.status == eRESERVED );
}
}
}
} else {
statusOk = statusOk && ( index.status == eRESERVED );
}
} while ( deletedRecordAvailable );
if (( statusOk ) && ( index.status == eRESERVED )) {
// Initialize index and data record.
index.status = eOK;
index.dataOffset = m_handle->nextFreeData;
index.dataSize = in_rRecord.dataSize;
index.recordRef = m_handle->recordReference;
data.id = eDATA;
data.recordRef = index.recordRef;
data.size = in_rRecord.dataSize;
data.offset = index.dataOffset + sizeof( data ) + in_rRecord.dataSize;
}
if ( statusOk ) {
m_error = DATABASE_IO_ERROR;
// Write data id record.
statusOk = m_handle->fileHandle.write( index.dataOffset, &data, sizeof( data ));
// Write data.
statusOk = statusOk && m_handle->fileHandle.write(( in_rRecord.pData + in_rRecord.dataOffset ), in_rRecord.dataSize );
// Write index record.
statusOk = statusOk && m_handle->fileHandle.write( index.offset, &index, sizeof( index ));
// Write index key.
statusOk = statusOk && m_handle->fileHandle.write( pSearchKey, header.totalKeySize );
}
if ( statusOk ) {
// Set record counter and reference.
header.nrOfRecords++;
header.recordReference++;
// Update free data and index.
header.nextFreeData += ( sizeof( data ) + in_rRecord.dataSize );
m_error = DATABASE_IO_ERROR;
bool reservedIndexRecordsCreated = false;
// Check for available index records. Reserve index records.
if ( header.nrOfRecords == m_handle->nrOfIndexRecords ) {
// Write extra reserved index records.
statusOk = createReservedIndexRecords(
m_handle->fileHandle,
header.nextFreeData,
m_handle->reservedIndexRecords,
m_handle->totalKeySize );
if ( statusOk ) {
// Set the next free index file pointer. Temporary storage.
header.nextFreeIndex = header.nextFreeData;
// Update free data file pointer from current file pointer.
statusOk = (( header.nextFreeData = m_handle->fileHandle.position() ) != (U32)INVALID_VALUE );
// Calculate the offset for the next index record and retrieve it.
U32 nextIndexOffset = ( m_handle->nextFreeIndex + sizeof( index ) + header.totalKeySize );
statusOk = statusOk && m_handle->fileHandle.read( nextIndexOffset, &data, sizeof( data ));
statusOk = statusOk && ( data.id == eNEXT_INDEX );
// Set the next index record values.
data.nextIndexOffset = header.nextFreeIndex;
data.offset = header.nextFreeIndex;
// Correction for the eINDEX data record.
header.nextFreeIndex += sizeof( data );
// Update the next index record.
statusOk = statusOk && m_handle->fileHandle.write( nextIndexOffset, &data, sizeof( data ));
// Set total index record counter.
header.nrOfIndexRecords += m_handle->reservedIndexRecords;
reservedIndexRecordsCreated = true;
}
} else {
header.nextFreeIndex += ( sizeof( index ) + header.totalKeySize );
}
// Update file header.
statusOk = statusOk && m_handle->fileHandle.write( sizeof( data ), &header,
sizeof( header ));
// Bitwise copy to first field of sHEADER part of sHANDLE!
::memcpy(&m_handle->version, &header, sizeof( header ));
if ( statusOk && reservedIndexRecordsCreated ) {
m_error = MEMORY_ALLOCATION_ERROR;
// Reinitialize apRecord and apKey array.
for ( U16 key = 0; statusOk && ( key < m_handle->nrOfKeys ); key++ ) {
statusOk = initKeyIndexArray( m_handle, key );
}
statusOk = statusOk && initKeyArray( m_handle );
}
}
if ( statusOk ) {
U32 prevNrOfRecords = header.nrOfRecords;
U32 indexOffset = prevNrOfRecords * m_handle->totalIndexSize;
// Update apRecord index array and apKey array in memory.
::memcpy(( m_handle->apKey + indexOffset), &index, sizeof( index ));
::memcpy(( m_handle->apKey + indexOffset + sizeof( index )),
pSearchKey, m_handle->totalKeySize);
for ( U16 k = 0; k < m_handle->nrOfKeys; k++ ) {
m_handle->apKeyIndex[ k ].bSorted = false;
}
m_error = NO_ERROR;
out_rIndex = prevNrOfRecords;
}
::free( pSearchKey );
return statusOk;
}
/*============================================================================*/
bool OSNDXFIO::getRecord( sKEY& in_rKey,
sRECORD& out_rRecord )
/*============================================================================*/
{
U32 index = U32( INVALID_VALUE );
// m_error is set by existRecord() or getRecord( index, .. )
return ( existRecord( in_rKey, index ) && getRecord( index, out_rRecord ));
}
/*============================================================================*/
bool OSNDXFIO::getRecord( U32 in_index,
sRECORD& out_rRecord )
/*============================================================================*/
{
m_error = DATABASE_IO_ERROR;
sINDEX* pIndex = (sINDEX*)( m_handle->apKey + ( m_handle->totalIndexSize * in_index ));
sDATA data;
// Read data id record.
bool statusOk = ( m_handle->fileHandle.read( pIndex->dataOffset, &data, sizeof( data )));
if ( statusOk ) {
m_error = INDEX_CORRUPT;
// Verify data type and record reference.
statusOk = (( data.id >= S32( eDATA )) && ( data.recordRef == pIndex->recordRef ));
}
if ( statusOk ) {
m_error = RECORD_TOO_LARGE;
// Verify data allocated memory size.
statusOk = ( data.size <= out_rRecord.allocatedSize);
}
if ( statusOk ) {
m_error = DATABASE_IO_ERROR;
// Read data record.
statusOk = ( m_handle->fileHandle.read(( pIndex->dataOffset +
sizeof( data )), out_rRecord.pData, data.size ));
}
if ( statusOk ) {
out_rRecord.dataOffset = pIndex->dataOffset + sizeof( data );
out_rRecord.dataSize = data.size;
m_error = NO_ERROR;
}
return statusOk;
}
/*============================================================================*/
bool OSNDXFIO::getNextRecord( U16 in_keyId,
sRECORD& out_rRecord,
U32& out_rIndex )
/*============================================================================*/
{
m_error = ENTRY_NOT_FOUND;
bool statusOk = ( m_handle->apKeyIndex[ in_keyId ].position !=
m_handle->apKeyIndex[ in_keyId ].selectionEnd );
out_rIndex = INVALID_VALUE;
if ( statusOk ) {
out_rIndex = m_handle->apKeyIndex[ in_keyId ].
apRecord[ m_handle->apKeyIndex[ in_keyId ].position ];
m_handle->apKeyIndex[ in_keyId ].position++;
statusOk = getRecord( out_rIndex, out_rRecord );
}
return statusOk;
}
/*============================================================================*/
bool OSNDXFIO::deleteRecord( U32 in_index )
/*============================================================================*/
{
m_error = ENTRY_NOT_FOUND;
sINDEX* pIndex = (sINDEX*)( m_handle->apKey + ( m_handle->totalIndexSize * in_index ));
bool statusOk = ( in_index < m_handle->nrOfIndexRecords );
statusOk = statusOk && ( eOK == pIndex->status );
sDATA data;
if ( statusOk ) {
m_error = DATABASE_IO_ERROR;
// Read data id record.
statusOk = ( m_handle->fileHandle.read( pIndex->dataOffset, &data, sizeof( data )));
}
if ( statusOk ) {
m_error = INDEX_CORRUPT;
// Verify data type and record reference.
statusOk = (( data.id >= S32( eDATA )) && ( data.recordRef == pIndex->recordRef ));
}
if ( statusOk ) {
m_error = DATABASE_IO_ERROR;
data.id = eDELETED;
// Write data id record.
statusOk = m_handle->fileHandle.write( pIndex->dataOffset, &data, sizeof( data ));
// Write index record.
statusOk = statusOk && m_handle->fileHandle.write( pIndex->offset, pIndex, sizeof( sINDEX ));
}
if ( statusOk ) {
m_error = NO_ERROR;
pIndex->prevDeletedIndex = m_handle->lastDeletedIndex;
m_handle->lastDeletedIndex = in_index;
}
return statusOk;
}
/*============================================================================*/
bool OSNDXFIO::updateRecord( U32 in_index,
sRECORD& in_rRecord )
/*============================================================================*/
{
m_error = ENTRY_NOT_FOUND;
sINDEX* pIndex = (sINDEX*)( m_handle->apKey + ( m_handle->totalIndexSize * in_index ));
bool statusOk = ( in_index < m_handle->nrOfIndexRecords );
sDATA data;
if ( statusOk ) {
m_error = DATABASE_IO_ERROR;
// Read data id record.
statusOk = ( m_handle->fileHandle.read( pIndex->dataOffset, &data, sizeof( data )));
}
if ( statusOk ) {
m_error = INDEX_CORRUPT;
// Verify data type and record reference.
statusOk = (( data.id >= S32( eDATA )) && ( data.recordRef == pIndex->recordRef ));
statusOk = statusOk && ( pIndex->dataOffset == in_rRecord.dataOffset );
}
if ( statusOk ) {
m_error = RECORD_TOO_LARGE;
// Verify available data size.
statusOk = ( data.offset - ( pIndex->dataOffset + sizeof( data )) >= in_rRecord.dataSize );
}
BYTE* pSearchKey = (BYTE*)( ::malloc( m_handle->totalKeySize ));
if ( statusOk ) {
if ( NULL == pSearchKey ) {
m_error = MEMORY_ALLOCATION_ERROR;
UNSUCCESSFUL_RETURN; // Exit updateRecord().
}
if ( !generateSearchKey( m_handle, in_rRecord, pSearchKey )) {
m_error = RECORD_TOO_SMALL;
::free( pSearchKey );
UNSUCCESSFUL_RETURN; // Exit updateRecord().
}
m_error = DATABASE_IO_ERROR;
}
sHEADER header = *m_handle;
// Write data.
statusOk = statusOk && m_handle->fileHandle.write(( in_rRecord.pData + in_rRecord.dataOffset ), in_rRecord.dataSize );
// Write index key.
statusOk = statusOk && m_handle->fileHandle.write( ( pIndex->offset + sizeof( sINDEX)), pSearchKey, header.totalKeySize );
if ( statusOk ) {
U32 prevNrOfRecords = header.nrOfRecords;
U32 indexOffset = prevNrOfRecords * m_handle->totalIndexSize;
// Update apRecord index array and apKey array in memory.
::memcpy(( m_handle->apKey + indexOffset), pIndex, sizeof( sINDEX ));
::memcpy(( m_handle->apKey + indexOffset + sizeof( sINDEX )),
pSearchKey, m_handle->totalKeySize);
for ( U16 k = 0; k < m_handle->nrOfKeys; k++ ) {
m_handle->apKeyIndex[ k ].bSorted = false;
}
m_error = NO_ERROR;
}
::free( pSearchKey );
return statusOk;
}
/*============================================================================*/
bool OSNDXFIO::existRecord( sKEY& in_rKey,
U32& out_rIndex )
/*============================================================================*/
{
bool bResult = ( m_handle->nrOfRecords > 0 );