summaryrefslogtreecommitdiff
path: root/src/core/xbdbf3.cpp
blob: cbbff1fe57b926f8ea4dba8353599a8d37fe8273 (plain)
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
/* xbdbf3.cpp

XBase64 Software Library

Copyright (c) 1997,2003,2014,2022 Gary A Kunkel

The xb64 software library is covered under the terms of the GPL Version 3, 2007 license.

Email Contact:

    XDB-devel@lists.sourceforge.net
    XDB-users@lists.sourceforge.net

*/

#include "xbase.h"


#ifdef XB_DBF3_SUPPORT

namespace xb{


/************************************************************************/
//! @brief Constructor.

xbDbf3::xbDbf3(xbXBase * x) : xbDbf( x ) {
  #ifdef XB_MEMO_SUPPORT
  ulCreateMemoBlockSize = 512;
  #endif
  iFileVersion = 3;
};

/************************************************************************/
//! @brief Destructor.

xbDbf3::~xbDbf3() {};

/************************************************************************/
//! @brief Create Version 3 table.
/*!
    This routine creates a Dbase III Plus (tm) DBF file.

  \param sTableName DBF table name.
  \param sAlias Table alias
  \param pSchema Pointer to schema structure with field definitions.
  \param iOverlay xbTrue - Overlay.<br> xbFalse - Don't overlay.
  \param iShareMode XB_SINGLE_USER<br>XB_MULTI_USER
  \returns <a href="xbretcod_8h.html">Return Codes</a>
  
*/
xbInt16 xbDbf3::CreateTable( const xbString & sTableName, const xbString & sAlias, xbSchema *pSchema, xbInt16 iOverlay, xbInt16 iShareMode ){

  xbInt16 i, k, k2;
  xbInt16 rc = 0;
  xbInt16 iErrorStop = 0;
  iDbfStatus = XB_CLOSED;

  xbString sNfn;
  try{
    sNfn = sTableName;
    xbase->GetLogStatus();

    rc = NameSuffixMissing( sNfn, 1 );
    if( rc > 0 )
      sNfn += ".DBF";

    SetFileName( sNfn );
    this->sAlias = sAlias;

    /* check if the file already exists */
    if( FileExists( 0 )){
      if( !iOverlay ){
        iErrorStop = 10;
        rc = XB_FILE_EXISTS;
        throw rc;
      }
      #ifdef XB_NDXINF_SUPPORT
      // remove the metadata file if there is one
      xbString sMname = sNfn;
      xbUInt32 iMnameLen = sMname.Len();
      sMname.PutAt( iMnameLen-2, 'X' );
      sMname.PutAt( iMnameLen-1, 'B' );
      sMname.PutAt( iMnameLen,   'M' );
      xbFile fTemp( xbase );
      fTemp.SetFileName( sMname );
      if( fTemp.FileExists() )
        fTemp.xbRemove();
      #endif // XB_NDXINF_SUPPORT
    }

    /* check if we already have a file with this alias  */
    if(( rc = xbase->AddTblToTblList( this, GetFqFileName(), sAlias )) != XB_NO_ERROR ){
      iErrorStop = 20;
      throw rc;
    }

    rc = ValidateSchema( pSchema );
    if( rc < 0 ){
      iErrorStop = 30;
      throw rc;
    } else
      iNoOfFields = rc;

    #ifdef XB_MEMO_SUPPORT
    // if we have memo fields
    iMemoFieldCnt = 0;
    i = 0;
    while( pSchema[i].cType != 0){
      if( pSchema[i].cType == 'M' )
        iMemoFieldCnt++;         /* number of memo fields in the incoming definition */
      i++;
    }

    if( iMemoFieldCnt > 0 ){
      xbString sMfn = sNfn;        /* memo file name, same as filename except ends with a "t", not an "f" */
      xbUInt32 iMfnLen = sMfn.Len();
      sMfn.PutAt( iMfnLen, 'T' );

      // dont overlay the memo file if it exists, and Overlay switch is off
      xbFile fTemp( xbase );
      fTemp.SetFileName( sMfn );
      if( fTemp.FileExists() && !iOverlay ){
        iErrorStop = 40;
        rc = XB_FILE_EXISTS;
        throw rc;
      }

      Memo = new xbMemoDbt3( this, fTemp.GetFqFileName());

      if(( rc = Memo->CreateMemoFile()) != XB_NO_ERROR ){
         iErrorStop = 50;
         throw rc;
      }
    }
    #endif

    /* this is the dBase III version of the class */
    cVersion = 0x03;     // 0x03 for Dbase level 5
    #ifdef XB_MEMO_SUPPORT
    if( iMemoFieldCnt > 0 ){
//    cVersion = cVersion |= 0x80;   // Version III memo, compiler complaints
      cVersion |= 0x80;   // Version III memo
    }
    #endif

    if(( rc = xbFopen( "w+b", iShareMode )) != XB_NO_ERROR ){
      iErrorStop = 60;
      throw rc;
    }
    uiRecordLen++;                  /* add one byte for 0x0D    */

    if(( RecBuf = (char *) malloc( uiRecordLen )) == NULL ){
      iErrorStop = 70;
      throw rc;
    }

    if(( RecBuf2 = (char *) malloc( uiRecordLen )) == NULL ){
      iErrorStop = 80;
      rc = XB_NO_MEMORY;
      throw rc;
    }

    /* BlankRecord(); */
    memset( RecBuf, 0x20, uiRecordLen );
    memset( RecBuf2, 0x20, uiRecordLen );
    ulCurRec  = 0L;
    uiHeaderLen = 33 + iNoOfFields * 32;
    xbDate d;
    cUpdateYY = (char) (d.YearOf() - 1900);
    cUpdateMM = (char) d.MonthOf();
    cUpdateDD = (char) d.DayOf( XB_FMT_MONTH );

    /* write the header prolog */
    if(( rc = WriteHeader( 0, 0 )) != XB_NO_ERROR ){
      iErrorStop = 90;
      rc = XB_WRITE_ERROR;
      throw rc;
    }
    if((SchemaPtr = (xbSchemaRec *) malloc( (size_t) iNoOfFields * sizeof( xbSchemaRec ))) == NULL){
      iErrorStop = 100;
      rc = XB_NO_MEMORY;
      throw rc;
    }

    /* write the field information into the header */
    for( i = 0, k = 1; i < iNoOfFields; i++ ){

      memset( SchemaPtr[i].cFieldName, 0x00, 11 );
      for( int x = 0; x < 10 && pSchema[i].cFieldName[x]; x++ )
        SchemaPtr[i].cFieldName[x] = pSchema[i].cFieldName[x];

      SchemaPtr[i].cType = pSchema[i].cType;
      SchemaPtr[i].cFieldLen = (unsigned char) pSchema[i].iFieldLen;
      SchemaPtr[i].cNoOfDecs = (unsigned char) pSchema[i].iNoOfDecs;

      if( SchemaPtr[i].cNoOfDecs > SchemaPtr[i].cFieldLen ){
        iErrorStop = 110;
        rc = XB_WRITE_ERROR;
        throw rc;
      }

      k2 = k;
      k += SchemaPtr[i].cFieldLen;

      if(( xbFwrite( &SchemaPtr[i].cFieldName, 1, 11 )) != XB_NO_ERROR ) {
        iErrorStop = 110;
        rc = XB_WRITE_ERROR;
        throw rc;
      }

      if(( xbFwrite( &SchemaPtr[i].cType, 1, 1 )) != XB_NO_ERROR ) {
        iErrorStop = 120;
        rc = XB_WRITE_ERROR;
        throw rc;
      }

      for( int j = 0; j < 4; j++ )
        xbFputc( 0x00 );

      if(( xbFwrite( &SchemaPtr[i].cFieldLen, 1, 1 )) != XB_NO_ERROR ) {
        iErrorStop = 130;
        rc = XB_WRITE_ERROR;
        throw rc;
      }

      if(( xbFwrite( &SchemaPtr[i].cNoOfDecs, 1, 1 )) != XB_NO_ERROR ) {
        iErrorStop = 140;
        rc = XB_WRITE_ERROR;
        throw rc;
      }

      /* 14 bytes reserved */
      for( int j = 0; j < 14; j++ )
        xbFputc( 0x00 );

      SchemaPtr[i].pAddress  = RecBuf  + k2;
      SchemaPtr[i].pAddress2 = RecBuf2 + k2;
    }

    /* write the header terminator */
    if(( xbFputc( XB_CHARHDR )) != XB_NO_ERROR ){
      iErrorStop = 150;
      rc = XB_WRITE_ERROR;
      throw rc;
    }
  }
  catch( xbInt16 rc )
  {
    xbString sMsg;
    sMsg.Sprintf( "xbdbf3::CreateTable() Exception Caught Error Stop = %d rc = %d", iErrorStop, rc );
    xbase->WriteLogMessage( sMsg );
    xbase->WriteLogMessage( GetErrorMessage( rc ));

    sMsg.Sprintf( "Table Name = [%s]", GetFqFileName().Str());
    xbase->WriteLogMessage( sMsg );   
    sMsg.Sprintf( "Alias Name = [%s]", sAlias.Str());
    xbase->WriteLogMessage( sMsg );

    xbFclose();
    if( RecBuf ){
      free( RecBuf );
      RecBuf = NULL;
    }
    if( RecBuf2 ){
      free( RecBuf2 );
      RecBuf2 = NULL;
    }
    if( SchemaPtr ){
      free( SchemaPtr );
      SchemaPtr = NULL;
    }

    InitVars();
    if( rc != XB_FILE_EXISTS )
      xbase->RemoveTblFromTblList( sAlias );
  }

  if( rc == XB_NO_ERROR )
    iDbfStatus = XB_OPEN;

  return rc;
}

/************************************************************************/
//! @brief Get version.
/*!
   The version info can be retrieved to determine
   which class is being used for a given dbf instance.
   \returns 3
*/

xbInt16 xbDbf3::GetVersion() const {
  return 3;
}



/************************************************************************/
//! @brief Open dbf file/table.
/*!
  \param sTableName DBF table name.
  \param sAlias Table alias
  \param iOpenMode XB_READ<br>XB_READ_WRITE
  \param iShareMode XB_SINGLE_USER<br>XB_MULTI_USER
  \returns <a href="xbretcod_8h.html">Return Codes</a>
*/

xbInt16 xbDbf3::Open( const xbString & sTableName, const xbString & sAlias, 
                         xbInt16 iOpenMode, xbInt16 iShareMode ){
  xbInt16 i, j, iRc = XB_NO_ERROR;
  xbInt16 iErrorStop = 0;
  char buf[33];
  char *p;

  #ifdef XB_MEMO_SUPPORT
  iMemoFieldCnt = 0;
  #endif

  try{

    /* verify the file is not already open */
    if( iDbfStatus != XB_CLOSED ){
      iErrorStop = 10;
      iRc = XB_ALREADY_OPEN;
      throw iRc;
    }
    /* copy the file name to the class variable */
    SetFileName( sTableName );
    this->sAlias = sAlias;

    if( !FileExists()){
      iErrorStop = 20;
      iRc = XB_FILE_NOT_FOUND;
      throw iRc;
    }

    if(( iRc = xbase->AddTblToTblList( this, GetFqFileName(), sAlias )) != XB_NO_ERROR ){
      iErrorStop = 30;
      throw iRc;
    }

    /* open the file */
    if(( iRc = xbFopen( iOpenMode, iShareMode )) != XB_NO_ERROR ){
      iErrorStop = 40;
      throw iRc;
    }

    /* copy the header into memory */
    if(( iRc = ReadHeader( 1, 0 )) != XB_NO_ERROR ){
      iErrorStop = 50;
      throw iRc;
    }

    /* check the version */
    if(( cVersion & 0x07 ) != 3 ){
    // if( xFileVersion != 3 && xFileVersion != 4 ){ 
      iErrorStop = 60;
      iRc = XB_FILE_TYPE_NOT_SUPPORTED;
      throw iRc;
    }
    iFileVersion = 3;

    /* calculate the number of fields */
    if( cVersion == (char)0x30 ) {
      iNoOfFields = ( uiHeaderLen - 296 ) / 32 ;
    } else {
      iNoOfFields = ( uiHeaderLen - 33 ) / 32;
    }

    if(( RecBuf = (char *) malloc( (size_t) uiRecordLen )) == NULL ){
      iErrorStop = 70;
      iRc = XB_NO_MEMORY;
      throw iRc;
    }

    if(( RecBuf2 = (char *) malloc( uiRecordLen )) == NULL ) {
      iErrorStop = 80;
      iRc = XB_NO_MEMORY;
      throw iRc;
    }

    if((SchemaPtr=(xbSchemaRec *)malloc( (size_t) iNoOfFields * sizeof( xbSchemaRec ))) == NULL){
      iErrorStop = 90;
      iRc = XB_NO_MEMORY;
      throw iRc;
    }

    memset( SchemaPtr, 0x00, ( (size_t) iNoOfFields * sizeof(xbSchemaRec) ));
    /* copy field info into memory */
    for( i = 0, j = 1; i < iNoOfFields; i++ ){
      xbFseek( ((xbInt64)i*32+32), SEEK_SET );
      xbFread( &buf, 1, 32 );
      p = buf;
      for( int x = 0; x < 10 && buf[x]; x++ ){
        SchemaPtr[i].cFieldName[x] = buf[x];
      }
      p = buf + 11;
      SchemaPtr[i].cType = *p++;
      SchemaPtr[i].pAddress  = RecBuf + j;
      SchemaPtr[i].pAddress2 = RecBuf2 + j;
      SchemaPtr[i].cFieldLen = (unsigned char) *( p + 4 );
      SchemaPtr[i].cNoOfDecs = (unsigned char) *( p + 5 );
      j += SchemaPtr[i].cFieldLen;
      #ifdef XB_MEMO_SUPPORT
      if( (SchemaPtr[i].cType == 'M' || SchemaPtr[i].cType == 'B' || SchemaPtr[i].cType == 'O' ))
        iMemoFieldCnt++;
      #endif
    }
    ulCurRec = 0L;
    iDbfStatus = XB_OPEN;
    if(( iRc = BlankRecord()) != XB_NO_ERROR ){
      iErrorStop = 100;
      throw iRc;
    }

    #ifdef XB_MEMO_SUPPORT
    if( iMemoFieldCnt > 0 ){   /* does this table have memo fields ? */

      // build the file name
      xbString sMfn   = GetFqFileName();        /* memo file name, same as filename except ends with a "t", not an "f" */
      xbUInt32 ulMfnLen = sMfn.Len();
      if( sMfn[ulMfnLen] == 'F' )
        sMfn.PutAt( ulMfnLen,  'T' );
      else
        sMfn.PutAt( ulMfnLen, 't' );
      xbFile fTemp( xbase );
      fTemp.SetFileName( sMfn );;

      Memo = new xbMemoDbt3( this, fTemp.GetFqFileName());

      if(( iRc = Memo->OpenMemoFile()) != XB_NO_ERROR ){
        iErrorStop = 110;
        throw iRc;
      }
    }
    #endif

  }
  catch ( xbInt16 iRc )
  {
    xbString sMsg;
    sMsg.Sprintf( "xbdbf3::Open() Exception Caught Error Stop = %d iRc = %d ShareMode = %d OpenMode = %d", iErrorStop, iRc, iShareMode, iOpenMode );
    xbase->WriteLogMessage( sMsg );
    xbase->WriteLogMessage( GetErrorMessage( iRc ));
    xbFclose();
    if( RecBuf ){
      free( RecBuf );
      RecBuf = NULL;
    }
    if( RecBuf2 ){
      free( RecBuf2 );
      RecBuf2 = NULL;
    }
    if( SchemaPtr ){
      free( SchemaPtr );
      SchemaPtr = NULL;
    }
    InitVars();

#ifdef XB_MEMO_SUPPORT
    if( Memo ){
      Memo->CloseMemoFile();
      delete Memo;
      Memo = NULL;
    }
#endif
  }

  if( iRc == XB_NO_ERROR )
    iDbfStatus = XB_OPEN;

  return iRc;
}

/************************************************************************/
#ifdef XB_MEMO_SUPPORT
//! @brief Create memo block size.
/*!
   This routine sets the memo file block size. This value is used when 
   the memo file is created so you if you want to change it, this must be 
   called before creating the table.

   DBF III Plus uses a block size of 512.

  \param ulBlockSize - Block size, must be evenly divisible by 512.
  \returns XB_INVALID_BLOCK_SIZE<br>XB_NO_ERROR
*/

xbInt16 xbDbf3::SetCreateMemoBlockSize( xbUInt32 ulBlockSize ){

  if( ulBlockSize != 512 )
    return XB_INVALID_BLOCK_SIZE;
  else
    ulCreateMemoBlockSize = 512;

  return XB_NO_ERROR;
}
#endif

/************************************************************************/
//! @brief Set version.
/*!
   Sets the version to 3.  The version info can be retrieved to determine
   which class is being used for a given dbf instance.
   \returns 3
*/

xbInt16 xbDbf3::SetVersion() {
   iFileVersion = 3;
   return iFileVersion;
}


/************************************************************************/
//! @brief Validate schema
/*!
  This routine verifies the field types are valid for Dbase III Plus (tm).

  \param s Pointer to schema structure with field definitions.

  \returns Number of fields or XB_INVALID_FIELD_TYPE.
*/

xbInt16 xbDbf3::ValidateSchema( xbSchema * s ){

// This routine validates an input schema
//  Negative return value is an error
//  Positive return value is the number of fields
//   On success, the class variable uiRecordLen will be updated with the record length of the combined total of the fields

  xbInt16 iFieldCnt = 0;
  uiRecordLen = 0;

  /* count the number of fields and check paramaters */
  xbInt16 i = 0;
  while( s[i].cType != 0 ){
    iFieldCnt++;
    // Version 3 field types
    if( s[i].cType != 'C' &&
        s[i].cType != 'N' &&
        s[i].cType != 'D' &&
#ifdef XB_MEMO_SUPPORT
        s[i].cType != 'M' &&
#endif /* XB_MEMO_SUPPORT */
        s[i].cType != 'L' ){
      return XB_INVALID_FIELD_TYPE;
    }

    if(s[i].cType == 'D'){
      s[i].iFieldLen = 8;
      s[i].iNoOfDecs = 0;
    }

    else if(s[i].cType == 'C')
      s[i].iNoOfDecs = 0;

    // check for numeric fields which are too long
    else if( s[i].cType == 'N'  && s[i].iFieldLen > 19 ){
      return XB_INVALID_FIELD_LEN;
    }

#ifdef XB_MEMO_SUPPORT
    else if(s[i].cType == 'M'){
      s[i].iFieldLen = 10;
      s[i].iNoOfDecs = 0;
    }
#endif /* XB_MEMO_SUPPORT */

    uiRecordLen += s[i].iFieldLen;
    i++;
  }
  return iFieldCnt;
}

}        /* namespace        */
#endif   /* XB_DBF3_SUPPORT  */