FairCom DB Function Descriptions A-C

The FairCom DB® function definitions are presented in alphabetical order, each starting on a new page, to facilitate your search for information.

Function definitions include some or all of the following sections:

Short Name

Internal FairCom DB function name. See Function Name Cross Reference for a cross-reference.

Type

ISAM, Low-Level, Server only, Server admin, threading, or utility function

Declaration

Function and parameter declarations

Description

Detailed description

Return

Explanation of most common return values. See FairCom DB Error Codes for additional error explanations.

Example

Programming example

Limitations

Restrictions on use and/or shortcomings

See also

Related functions and information

After each FairCom DB function call, a global variable will contain the current error code, or zero if no error occurred. In the case of all types except ISAM, the error code variable is uerr_cod. Some of the FairCom DB Low-Level functions also set the global variable sysiocod to the value of errno when a C runtime function experiences an I/O error. errno is the Language C run-time error variable automatically maintained by the C run-time library. Unlike uerr_cod, sysiocod is not reset by new calls to FairCom DB. It is only set to errno if an open, create, seek, read, write, or lock function fails. The FairCom DB ISAM functions set the variable isam_err. In addition, the ISAM functions set the variable isam_fil with the data or index file number involved.

The error codes listed in each Return section of the function descriptions are not exhaustive. The only error codes included are those which have a meaningful context for the function in question.

 

Abort

Abort the current transaction in progress.

Short Name

TRANABT()

Type

Low-Level function

Declaration

COUNT Abort()

Description

Abort() aborts the current transaction. All file update actions since the last Begin() will not be committed. All known locks are released, and the transaction ends.

Return

Value Symbolic Constant Explanation
0 NO_ERROR No error occurred.
71 TNON_ERR There is no active transaction pending.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Example

COUNT     savepoint;


void domaster() {

    Begin(ctENABLE|ctTRNLOG);   /* start transaction with locks  */

    while(another()); {     /* get next record to add        */

        savepoint = SetSavePoint(); /* get save point at

                             beginning of each master record */

        if (add_master() < 0)

            Abort();        /* abort if can't add master rec */

        dodetail();         /* process detail records        */

    }

    if (Commit(ctFREE)0)

        printf("\nError %d in transaction",uerr_cod);

    return;

}


void dodetail() {

    while(moredetail()); {   /*get next detail record to add */

        if (add_detail()<0) {    /* add details, if possible */

            RestoreSavePoint(savepoint)

                             /* with error, return to savept */

            return;

        }

    }

}

See also

AbortXtd, Begin, ClearSavePoint, Commit, RestoreSavePoint, SetSavePoint, TRANRDY

 

AbortXtd

Abort the current transaction in progress (extended version).

Short Name

TRANABTX()

Type

Low-Level function

Declaration

COUNT AbortXtd(COUNT lokmod)

Description

AbortXtd() is an extended version of Abort that permits control of locks on abort. AbortXtd() accepts mode arguments similar to Commit(). lokmod values are described in the following table.

Mode Description
ctFREE Releases all locks. Identical to Abort. Clears the LockISAM() state.
ctKEEP Does not clear the LockISAM() state and keeps all the locks acquired before and during an active transaction.
ctKEEP_OUT Releases only locks obtained within the transaction and/or locks on records updated within the transaction. Does not clear the LockISAM() state.
ctKEEP_OUT_ALL Unconditionally keep all locks that were acquired before the transaction began. Free locks obtained within the transaction. Does not clear the LockISAM() state.

Return

Value Symbolic Constant Explanation
0 NO_ERROR No error occurred.
71 TNON_ERR There is no active transaction pending.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

See also

Abort, Begin, ClearSavePoint, Commit, LockISAM, RestoreSavePoint, SetSavePoint, TRANRDY

 

AddAutoSysTimeFields

Define which of the fields are automatically set by the server using the current server system time (in GMT time zone).

Type

ISAM Function

Declaration

NINT AddAutoSysTimeFields(FILNO datno, pA_STFIELDS defs)

Description

  • datno - the data file number. In V12, the file number typedef was formally changed from COUNT, a two-byte value to FILNO, a four-byte value. Refer to this link for compatibility details. Four Byte File Numbering TypeDef Change
  • defs - pointer to fields definition structure:
     

typedef struct astfields {

 COUNT version;                     /* Version of this structure   */

 COUNT entries;                     /* number of entries in fields array  */

 LONG pad;                          /* padding to ensure struct alignment */

 pA_STFIELD fields;                 /* fields array */

} A_STFIELDS, *pA_STFIELDS;

  • version - the version of the structure. must be set to A_STFIELDS_VERS_V01.
  • entries - the number of fields that needs to be automatically set with the system time. It must match the number of entries in the fields array.
  • fields - pointer to an array of field settings:
     

typedef struct astfield {

 LONG fieldno;                      /* field number */

 TEXT mode;                         /* set time  */

} A_STFIELD, *pA_STFIELD;
 

  • fieldno - the field number in the DODA for the field that is set to auto setting with system time stamp.
  • mode - in which condition the field gets populated. Possible values:

CT_AUTOSYSTIME_CREATE 0x01 - when the record gets added

CT_AUTOSYSTIME_UPDATE 0x02 - when the record gets rewritten/updated.

Return

NO_ERROR on success

 

addChangeIDfield

Add a change ID field to the specified data file.

Declaration

ctCONV NINT ctDECL addChangeIDfield (FILNO datno, NINT fieldno);

Description

[IN] datno- Data file number.

[IN] fieldno- The field number in the DODA for the change ID field.

Return Values

Value Symbolic Constant Explanation
0 CTDBRET_OK Successful operation.

See c-tree Plus Error Codes for a complete listing of valid c-tree Plus error values.

 

AddCtResource

Add a Resource to a data file.

Short Name

ADDRES()

Type

Low-Level file resource function

Declaration

COUNT AddCtResource(FILNO filno, pVOID resptr, VRLEN varlen)

Description

In V12, the file number typedef was formally changed from COUNT, a two-byte value to FILNO, a four-byte value. Refer to this link for compatibility details. Four Byte File Numbering TypeDef Change

AddCtResource() is used to add a Resource to filno. Every Resource is identified by a unique combination of a Resource Type and a Resource Number. The Resource Number can optionally be assigned by FairCom DB during the call to AddCtResource(). In addition, each Resource can be identified by a Resource Name. The Resource Name is not guaranteed to be unique.

resptr points to a resource data block. This block contains the following fields:

Byte Offset Data Type Field Name
0 - 3 unsigned long integer Resource Type
4 - 7 unsigned long integer Resource Number
8 - m null terminated character string Resource Name
m+1 - n any collection of data types desired Resource Information

The Resource Type must be a value greater than 65536. 0 through 65536 are reserved for FairCom use.

If the Resource Number is a value of 0xffffffffL, FairCom DB assigns this Resource the next available Resource Number for this Resource Type in the specified data file. AddCtResource() places assigned Resource Number in the Resource Data Block.

The Resource Name is optional. FairCom DB does not guarantee unique Resource Names. Names starting with “FC!” or “RD!”, are reserved for FairCom use.

The Resource Information is any collection of data that you wish to store as a Resource. It can be a character string, a structure, or any variable type.

Return

Value Symbolic Constant Explanation
0 NO_ERROR Successful addition of a new Resource.
37 WRITE_ERR Most likely disk or directory is full. Files are left in an indeterminate state and should be rebuilt
147 VDLFLG_ERR Attempt to re-use a data record that is still active. Apparently, the data file is corrupted in which case you should rebuild the file.
401 RNON_ERR Resources have not been enabled for this data file.
403 RZRO_ERR Empty Resource ID.
405 RDUP_ERR Resource ID already added. There must be a unique combination of Type and Number.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Example

struct {                    /* Resource Data Block structure */

 

    ULONG     resource_type;

 

    ULONG     resource_number;

 

    TEXT      variable_info[1016]; /* This holds the         */

 

} my_resource;                     /* Resource Name and Data */

 

 

my_resource.resource_type    = 0x10001L;            /* 65537 */

 

my_resource.resource_number  = 0xffffffffL;         /* FairCom DB assigns number*/

 

 

strcpy(my_resource.variable_info,"MY!resource");

 

strcpy(my_resource.variable_info+12,"Actual Resource Data");

 

 

if (AddCtResource(datno,&my_resource,

 

   (VRLEN)(8 + 12 + strlen(my_resource.variable_info+12))) == 0)

 

{

 

    printf("\nThe resource has been assigned number %ld",

 

           my_resource.resource_number);

 

    printf("\nThe resource is located at byte offset %ld.",

 

           GetCtResource(datno, "MY!resource", &my_resource,

 

                         1024L, RES_NAME));

 

} else

 

    printf("\nCould not add resource. Error #%d",uerr_cod);

See also

GetCtResource, UpdateCtResource, and DeleteCtResource. Also refer to Resources.

 

addIDfield

Assign an IDENTITY attribute to a DODA field.

Declaration

NINT addIDfield(FILENO datno, LONG8 startval, LONG delta, NINT fieldno)

Description

addIDfield() assigns an IDfield (IDENTITY) auto-numbering attribute to a numeric field in a record. The field number is determined from the DODA. This value is incremented on each record addition. This IDfield concept is similar to a SRLSEG, however, requires no implicit index, which allows it to be much better performing.

Where:

  • datno is the data file number - In V12, the file number typedef was formally changed from COUNT, a two-byte value to FILNO, a four-byte value. Refer to this link for compatibility details. Four Byte File Numbering TypeDef Change
  • startval is the next value to be assigned to the field on add.
  • delta is the value to increment each addition.
  • fieldno is the DODA field offset (starting at zero).

IDfields requires a DAR resource (Direct Access Resource) embedded in the file. The DAR is a specialized high-speed resource.

Return

Value Symbolic Constant Explanation
0 NO_ERROR Success

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Example

retval = addIDfield(fileno, nextid, 1, fldnum);

if (retval) {

printf("\tERROR: Failed to add ID field with error %d\n", retval);

}

Override IDENTITY Values

PUTHDR() using the ctIDfieldOverRide mode can turn on and off the ability to override the automatic IDfield values. The override is on a per user, per file basis. A nonzero hdrval turns on the override, and a zero hdrval restores the standard operation. When the override is on for a data file that supports an IDfield, then an add record operation does not fill-in the IDfield value. Whatever is passed in the record buffer is used for the IDfield. And a rewrite permits the IDfield value to change instead of generating the IDFL_CHG error. When the override is enabled, add record operations do not consume IDfield values.

See also

delIDfield, getIDfield, wchIDfield, resetIDfield, IDfields - Extended support

 

IDfields - Extended support

Several aspects of IDfield behavior have been improved.

An issue was corrected in which rebuild did not properly set the IDfield state variable when records were added with IDfields already set and internal support disabled.

Additional changes were made to two aspects of IDfield support: overflow detection and unsigned IDfield support. Prior to these modifications, IDfields were treated as signed fields (regardless of the associated DODA properties for the IDfield), and the issue of overflow was ignored. These modifications affect how a new file supporting IDfields behaves and how an existing file (whose IDfield was created before these enhancements) behaves.

New Files

When a new file has an IDfield added, the associated DODA entry for the IDfield determines (a) whether the IDfield is signed or unsigned, and (b) the length of the IDfield for the purposes of detecting an overflow (or underflow) condition.

Overflow and underflow are reported as error IDVR_ERR (1002).

Existing Files

An old file with an existing IDfield that is opened (for update) for the first time has its IDfield resource updated to the new version. The IDfield remains signed unless the associated DODA entry is for an unsigned field type (as noted above), and overflow detection is enabled using the DODA field length to determine the IDfield size (for the purposes of overflow detection).

If the COMPATIBILITY keyword NO_IDFIELD_OVERFLOW_CONVERSION (see below) is in use, then the behavior of the IDfield will not change.

Note: It is possible that when the old file is upgraded to the new/enhanced IDfield support that it will be in overflow/underflow status. This can occur because operations on the old file caused an overflow or underflow (which was not being checked), evidence of the problem still remains after conversion to the IDfield support, and the update detects this unless NO_IDFIELD_OVERFLOW_DETECTION is in use (see below).

 

COMPATIBILITY KEYWORDS

NO_IDFIELD_OVERFLOW_CONVERSION

Old files behave as before, no overflow/under-flow detection

NO_IDFIELD_OVERFLOW_DETECTION

All tests for overflow/under-flow are ignored

Summary of keyword behavior:

None of the keywords:

Old files that are opened for update and new files have new IDfield with signed/unsigned fields (per DODA), and overflow/under-flow detection turned on.

NO_IDFIELD_OVERFLOW_CONVERSION only:

Old files behave as before and new files have new IDfield support with signed/unsigned fields (per DODA) and overflow/under-flow detection turned on.

NO_IDFIELD_OVERFLOW_DETECTION only:

Same as "None of the keywords" except that all tests for overflow/under-flow are skipped; but tables with the new IDfield support will have overflow detection enforced if this keyword is removed.

NO_IDFIELD_OVERFLOW_CONVERSION and NO_IDFIELD_OVERFLOW_DETECTION:

Old files behave as before and new files have new IDfield support with signed/unsigned fields (per DODA) and overflow/under-flow detection turned on, but all tests for overflow/under-flow are skipped.

The new function described below can be used to modify the IDfield signed/unsigned setting and the overflow detection setting on a table.

 

xtdatrIDfield(datno,xtdatr)

The new routine xtdatrIDfield( FILENO datno, LONG xtdatr ) can be used to (a) return the current bit fields for the extended attribute (when xtdatr is passed in as -1 on the call); or (b) set the bit fields as specified in xtdatr. In the event of an error, xtdatrIDfield() returns ‑1.

The extended attribute bit fields are defined in ctport.h:


IDfield_xtdatr_unsigned    unsigned IDfield [DODA field types: CT_CHARU, CT_INT2U,
                           CT_INT4U, CT_INT8U]

IDfield_xtdatr_overflwd    IDfield overflowed

IDfield_xtdatr_versn__2    IDfield with xtdatr support

IDfield_xtdatr_versn__1    IDfield without active xtdatr support: an old IDfield
                           with an up-to-date resource, but no overflow/under-flow
                           detection

IDfield_xtdatr_noovrflw    IDfield overflow detection is disabled

IDfield_xtdatr_signed      signed IDfield [remaining DODA field types]
 

Example

Given a DODA field as the 5th field {"cm_identity",NULL,CT_INT4U}:


printf("Setting ID field\n");

   if(rc = addIDfield(custmast_ifil.tfilno, 0, 1, 4))

  printf("addIDfield failed %d\n", rc);

 

   printf("Setting xtdatrID\n");

   if (xtdatrIDfield(custmast_ifil.tfilno, IDfield_xtdatr_versn__2 | IDfield_xtdatr_noovrflw ) == -1)

  printf("xtdatrID failed with %d\n", sysiocod);

 

Using xtdatrIDfield() as part of a TRANDEP file create sequence such as:

TRANBEG

CREIFILX()

addIDfield()

xtdatrIDfield()

TRANEND

would allow changing the default behavior of the IDfield (as described in New File section above). The signed/unsigned nature of the field could be changed or overflow/under-flow detection could be disabled (by turning on IDfield_xtdatr_noovrflw).

Note: xtdatrIDfield() could be called with an xtdatr of zero which would make the file appear, on its next open, as an old file not opened with the new support. It is also possible to explicitly set either of the IDfield_xtdatr_versn__1/2 bits. Calls to xtdatrIDfield will return an error, IDXA_ERR (1003), if the new xtdatr settings are not internally consistent. For example, both "versn" bits cannot be turned on, or one cannot clear the IDfield_xtdatr_overflwd bit unless the IDfield_xtdatr_noovrflw bit is turned on.

Return

When called with a xtdatr mode of -1, xtdatrIDfield() returns the currently assigned ID field extended bit mask.

When called with a supplied xtdatr mode, xtdatrIDfield() returns either:

  • Success: - the new extended bit mask assigned, or;
  • Error: -1

If -1 is returned then uerr_cod is set as follows and sysiocod contains one of the values as shown below (found in cterrc.h)

Value uerr_cod Explanation
1003 IDXA_ERR Invalid IDfield extended attribute (xtdatr)

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

 

sysiocod validation issue
1 mutually exclusive attributes
2 specified version incompatible with other attributes
3 if version reset to 0, no other attributes allowed
4 cannot turn off overflowed indicator unless the no overflow detection attribute is turned on
5 cannot turn on the overflowed indicator unless the no overflow detection attribute is off
6 IDfield_xtdatr_versn__1 requires IDfield_xtdatr_noovrflw

Note: If xtdatrIDfield is called, and IDfield_xtdatr_versn__2 is on, then if neither IDfield_xtdatr_signed/unsigned is specified, xtdatrIDfield() will use the associated DODA to determine the signed/unsigned attribute.

 

AddKey

Add key value to index file.

Short Name

ADDKEY()

Type

Low-Level index file function

Declaration

  COUNT AddKey(FILNO keyno, pVOID target, LONG recbyt, COUNT typadd)

Description

In V12 the file number typedef was formally changed from COUNT, a two-byte value to FILNO, a four-byte value. Refer to this link for compatibility details. Four Byte File Numbering TypeDef Change

AddKey() inserts the key value pointed to by target and the associated data record position recbyt into index file number keyno. typadd determines how a full B-Tree node is split. The symbolic constants defined in ctport.h, REGADD, INCADD, and DECADD, represent the three node splitting options:

typadd Value Symbolic Constant Action
0 REGADD Split nodes in half. This is the ordinary mode for random key value insertions.
1 INCADD Uneven node split to accommodate insertions made in ascending key value order. For example, if the key values are already sorted in ascending order, using INCADD creates more compact B-Trees.
2 DECADD Uneven node split to accommodate insertions made in descending key value order.

Return

Value Symbolic Constant Explanation
0 NO_ERROR Successful key value insertion.
2 KDUP_ERR Target key value already in index. No insertion performed.
28 ZDRN_ERR recbyt is zero. No insertion performed.
39 FULL_ERR No more B-Tree nodes available. It is necessary to rebuild index.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Example

TEXT target[11];

LONG recbyt;

COUNT name_key;


if (AddKey(name_key,target,recbyt,REGADD))

    printf("\nAddKey error = %d",uerr_cod);

Limitations

AddKey() does not pad key values. If passed a key value which is not completely specified to its full length, AddKey() uses whatever “garbage” follows the key value in memory up to the key length.

Key values added to an index allowing duplicate keys, (keydup = 1 in CreateIndexFile() or CreateIndexMember()), have their last 4 bytes overwritten by the associated data record position. In this way, identical key values become distinguishable.

The recbyt parameter in this function is a 4-byte value capable of addressing at most 4 gigabytes. If your application supports HUGE files (greater than 4 gigabytes), you must use the ctSETHGH() and ctGETHGH() functions to set or get the high-order 4 bytes of the file offset. See Record Offsets Under Huge File Support.

See also

CreateIndexFile and CreateIndexMember specify the key value characteristics of length, type, and allowance for duplicate values at index file creation.

 

AddRecord

Add a new fixed-length data record and corresponding key values to ISAM files.

Short Name

ADDREC()

Type

ISAM function fixed-length record

Declaration

COUNT AddRecord(FILNO datno, pVOID recptr)

Description

In V12 the file number typedef was formally changed from COUNT, a two-byte value to FILNO, a four-byte value. Refer to this link for compatibility details. Four Byte File Numbering TypeDef Change

AddRecord(), short name ADDREC(), adds the fixed-length data record pointed to by recptr to data file number datno. It automatically adds the key values defined for the data file to their respective index files. If successful, the new data record becomes the current ISAM record for data file datno.

In multi-user applications, AddRecord() automatically causes a data record lock to be placed on the new record. Therefore, LockISAM(ctENABLE) and LockISAM(ctFREE) should be called before and after AddRecord(). However, with transaction processing locks are enabled and freed using Begin() and Commit(). LockCtData(ctFREE) can also be used if the record offset is known, to provide individual record lock control. Optionally, the SetOperationState() status_word OPS_UNLOCK_ADD automatically unlocks after each AddRecord().

As of c-tree V8.14, c-tree sets the current ISAM position after a record is added such that the next or previous record can be read without having to re-read the record just added. Prior to V8.14, the current ISAM position was not set to a newly-added record and an INOT_ERR (101) error would result if you tried to read either the next of previous record.

Return

Value Symbolic Constant Explanation
0 NO_ERROR Successful addition of a new data record.
2 KDUP_ERR Duplicate key value found in index file number isam_fil. Data record not added and no key values inserted.
31 DELFLG_ERR Attempt to re-use data record whose first byte is not set to ff (hex). Either the data file is corrupted,, in which case you should rebuild the ISAM files,, or the C255 constant defined in ctcmpl.h is not set properly.
33 DNUL_ERR recptr is null. No action taken.
37 WRITE_ERR Most likely disk or directory is full. Files are left in an indeterminate state and should be rebuilt.
48 FMOD_ERR datno is assigned to a variable record length file.
199 NSCH_ERR Key segment refers to schema, but schema not defined.
433 SSCH_ERR Segment definition inconsistent with schema.
445 SDAT_ERR Not enough data to assembly key.
446 BMOD_ERR Invalid key mode.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Example

FILNO invfil

struct invd {

   TEXT     delflg;

   LONG     part_no;

   TEXT     part_name[60];

   LONG     on_hand;

} recbuf;


scanf("%ld %59s %ld",&recbuf.part_no,recbuf.part_name, &recbuf.on_hand);

recbuf.delflg = '\0'; /* clear delete flag */

if (LockISAM(ctENABLE) || AddRecord(invfil,&recbuf) ||

      LockISAM(ctFREE))

    printf("\nAddRecord error %d in file %d",

         isam_err,isam_fil);

ADDREC DELFLG_ERR (31)

In extremely rare situations, it was possible for the delete stack to become corrupted on a data file after it went through automatic recovery. In these obscure scenarios, ADDREC could return a DELFLG_ERR error (31) following recovery. ADDREC and NEWREC failed with error 31 until the table was rebuilt. Instead of returning DELFLG_ERR, c-tree now discards its list of deleted records and retries the operation. This should prevent the error and allow the call to proceed normally. The following is logged to CTSTATUS:

WARNING: an invalid delete stack has been reset to zero for fixed length data file

This message indicates that all the space occupied by deleted records in that file at that point in time is lost and will not be re-used until the file is rebuilt or compacted.

Note: This is a Compatibility Change.

 

See also

ISAM Functions discusses how the relationship among the data files and their corresponding index files is specified. Begin, Commit, LockCtData, LockISAM, SetOperationState

 

AddVRecord

Add a new variable-length data record, and its corresponding key values, to ISAM files.

Short Name

ADDVREC()

Type

ISAM function variable-length record

Declaration

COUNT AddVRecord(FILNO datno, pVOID recptr, VRLEN varlen)

Description

In V12 the file number typedef was formally changed from COUNT, a two-byte value to FILNO, a four-byte value. Refer to this link for compatibility details. Four Byte File Numbering TypeDef Change

AddVRecord() adds the data record with length in bytes given by varlen and pointed to by recptr to data file number datno. It automatically adds the key values defined for the data file to their respective index files. If successful, the new data record becomes the current ISAM record for datno. In multi-user applications, AddVRecord() automatically causes a data record lock to be placed on the new record. Therefore, LockISAM(ctENABLE) and LockISAM(ctFREE) should be called before and after AddVRecord(). However, if you are using transaction processing, (single-user and client/server models only), you will usually enable and free locks during the Begin() and Commit() functions.

As of c-tree V8.14, c-tree sets the current ISAM position after a record is added such that the next or previous record can be read without having to re-read the record just added. Prior to V8.14, the current ISAM position was not set to a newly-added record and an INOT_ERR (101) error would result if you tried to read either the next of previous record.

Return

Value Symbolic Constant Explanation
0 NO_ERROR Successful addition of a new data record.
2 KDUP_ERR Duplicate key value found in index file number isam_fil. Data record not added and no key values inserted.
33 DNUL_ERR recptr is null. No action taken.
37 WRITE_ERR Most likely disk or directory is full. Files are left in an indeterminate state and should be rebuilt.
48 FMOD_ERR datno is assigned to a fixed record length file.
147 VDLFLG_ERR Attempt to re-use a data record that is still active. Apparently, the data file is corrupted in which case you should rebuild the ISAM files.
149 VRLN_ERR varlen is less than the minimum record length for this variable-length file.
199 NSCH_ERR key segment refers to schema, but schema not defined.
433 SSCH_ERR Segment definition inconsistent with schema.
445 SDAT_ERR Not enough data to assembly key.
446 BMOD_ERR Invalid key mode.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Example

FILNO invfil;

struct invd {

  LONG part_no;

  LONG on_hand;

  TEXT part_name[120];

} recbuf;


scanf("%ld %ld %119s",&recbuf.part_no,&recbuf.on_hand,

      recbuf.part_name);


if (LockISAM(ctENABLE) || AddVRecord(invfil,&recbuf,8 +

   strlen(recbuf.part_name)) || LockISAM(ctFREE))

     printf("\nAddVRecord error %d in file %d",isam_err, isam_fil);

See also

ISAM Functions discusses how the relationship among the data files and their corresponding index files is specified. Begin, Commit, LockCtData, LockISAM, SetOperationState, Commit, LockISAM

 

AllocateBatch

Optionally allocates buffer space for multiple batches (groups of records).

Short Name

ALCBAT()

TYPE

ISAM function

Declaration

COUNT AllocateBatch(COUNT numbat)

Description

AllocateBatch() is an optional part of the API called internally by ChangeBatch().

AllocateBatch() allocates data structures for multiple, simultaneous batches. Ordinarily the FairCom DB batch function, DoBatch(), is used for only one batch at a time. Each time ChangeBatch() is called with a previously unused numbat, a new batch structure is allocated and maintained by FairCom DB. Therefore, calling AllocateBatch() is optional, as it is automatically called by ChangeBatch().

Prior to c-tree V6.4B, the numbat parameter was a unique batch identification number. numbat is ignored by c‑tree V6.4B and after. See ChangeBatch() for more information.

Return

Value Symbolic Constant Explanation
0 NO_ERROR Successful allocation.
184 ISDP_ERR AllocateBatch() already called for this batch. Call FreeBatch() if you must recall AllocateBatch().
185 ISAL_ERR No memory available for set buffers.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Example

See the ChangeBatch example.

See also

ChangeBatch, FreeBatch, DoBatch

 

AllocateRange

Establishes a new index range for ISAM record retrieval.

Short Name

ALCRNG()

Type

ISAM function

Declaration

COUNT AllocateRange(FILNO keyno, NINT segcount, pVOID lrange, pVOID urange, pNINT operators)

Description

In V12 the file number typedef was formally changed from COUNT, a two-byte value to FILNO, a four-byte value. Refer to this link for compatibility details. Four Byte File Numbering

An index range is defined by specifying a range of values for one or more key segments.

AllocateRange() allocates buffer space and establishes a new range based on the segment values passed for the lower bound, upper bound and operators for each segment. keyno identifies the index file that should be used to establish the range. segcount indicates the number of index segment values for the range, and implicitly, the number of operators. lRange is a buffer with the lower range segment values, while uRange is a buffer with the upper range segment values. operators is an array of operators for each segment value.

The operators CTIX_EQ, CTIX_NE, CTIX_GT, CTIX_GE, CTIX_LE, CTIX_LT are open ended and use only the lRange buffer for range values. The uRange buffer is ignored and may be set to NULL for these operators.

The operators CTIX_BET, CTIX_BET_IE, CTIX_BET_EI, CTIX_BET_EE and CTIX_NOTBET use both lRange and uRange buffers to establish the lower and upper bound key values. The range is set for all index entries that are situated between the lower bound and upper bound values.

Segment values are stored in lRange and uRange buffers in the same order and type as the index segment definition.

If a previous range exists for this index, the previous range is released and the new range is established.

Return

Value Symbolic Constant Explanation
0 CTDBRET_OK Successful operation.
10 SPAC_ERR Could not allocate memory for range definition.
48 FMOD_ERR

Operation incompatible with type of file. The specifics vary by function:

  • The specified keyno is not an index file number.
  • The file is not a data file or it does not contain an IFIL resource (ctFILBLK in ctFBisam mode).
  • One or more associated file (data and index files) is not TRANDEP (using RENIFIL / RENIFILX).
614 HMAP_ERR Could not find ISAM map from specified index file to a data file. Is the specified index file opened at the ISAM level?
749 PBAD_ERR

Bad parameter value. Can be caused by any of these conditions:

a) segcount is less than or equal to zero.

b) lrange is NULL.

c) invalid operator specified.

d) between operator specified but urange is NULL.

 

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Example

  /*
  ** 3 segment example for keyno 12
  */
  NINT ops[3] = {CTIX_LT,CTIX_BET,CTIX_NE};
  TEXT lbuf[22];
  TEXT ubuf[22]; 
  COUNT rc;

  memcpy(lbuf,"TUVWXYZ   ",10);
  memcpy(lbuf + 10,"00001000",8);
  memcpy(lbuf + 18,"AX00",4);

  memset(ubuf,0,22);
  memcpy(ubuf + 10,"00001999",8);

  rc = ALCRNG(12,3,lbuf,ubuf,ops);

 

See also

EstimateRange, FreeRange, FirstInRange, FirstInVRange, LastInRange, LastInVRange, NextInRange, NextInVRange, PreviousInRange, PreviousInVRange

 

AllocateSet

Optionally allocate key buffers for multiple, simultaneous sets.

Short Name

ALCSET()

Type

ISAM function

Declaration

COUNT AllocateSet(COUNT numset)

Description

AllocateSet() is called internally by ChangeSet() and is an optional part of the API.

AllocateSet() allocates key buffers for multiple, simultaneous sets. Ordinarily, the FairCom DB sequence set functions, FirstInSet(), NextInSet(), etc., are used for only one set at a time. Each call to ChangeSet() with a unique value allocates a new set maintained by FairCom DB. Calling AllocateSet() is optional, as ChangeSet() automatically calls AllocateSet() when necessary.

Prior to c-tree V6.4B, the numset parameter was a unique set identification number. numset is ignored by c-tree V6.4B and after.

See ChangeSet() for more information

Return

Value Symbolic Constant Explanation
0 NO_ERROR Successful allocation.
184 ISDP_ERR AllocateSet() already called for this set. Call FreeSet() if you must recall AllocateSet().
185 ISAL_ERR No memory available for set buffers.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Example

See the ChangeSet example.

See also

ChangeSet, FreeSet, FirstInSet, LastInSet, PositionSet, NextInSet, PreviousInSet

 

AvailableFileNbr

Return next available FairCom DB file number.

Short Name

AVLFILNUM()

Type

Low-Level data file function

Declaration

COUNT AvailableFileNbr(COUNT numfils)

Description

AvailableFileNbr() returns a valid FairCom DB file number that is available for use (i.e., not presently assigned to a file). numfils is the number of consecutive file numbers required. If numfils consecutive file numbers are not available, AvailableFileNbr() returns -1.

This function does not consume the file number(s) returned. The file number is consumed only if you subsequently create or open a file with the returned file number. Therefore, two calls in succession to AvailableFileNbr(), without any intervening creates, opens, or closes, will return the same file number. However, the scope is local to your application. No multi-user interference is possible, since each application only references file numbers internally.

If used for a host superfile, remember to use an argument of 2.

Return

AvailableFileNbr() returns the first file number in the series requested. If the requested block of file numbers is not available, it returns -1. Check uerr_cod for the error value.

Value Symbolic Constant Explanation
46 FUSE_ERR No file number is available.
47 ISDP_ERR FairCom DB is not initialized.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Example

FILENO super_number;

COUNT  retval;


super_number = AvailableFileNbr(2);

if (super_number == -1) {

    printf("\nNot enough file numbers available");

    exit(1);

}

retval = OpenCtFile(super_number,"superfil",

         ctPERMANENT | ctEXCLUSIVE | ctSUPERFILE);

 

Begin

Mark beginning of transaction.

Short Name

TRANBEG()

Type

Low-Level data file function

Declaration

  LONG Begin(COUNT trnmod)

Description

Begin() marks the beginning of a transaction. All files opened by this user, that have been created with a file mode of either ctPREIMG or ctTRNLOG, will have file updates held until they are committed with a matching call to Commit(). For a full description of transaction processing, see the chapter on Data Integrity.

trnmod values presently supported are summarized in the following table:

trmmod value Operation
ctTRNLOG Full transaction processing functionality, including auto-recovery. Mutually exclusive to ctPREIMG.
ctPREIMG Transaction atomicity only, auto-recovery is not available. Mutually exclusive to ctTRNLOG.
ctENABLE Automatically implements LockISAM(ctENABLE) when applicable. Mutually exclusive with ctREADREC.
ctREADREC Automatically implements LockISAM(ctREADREC) when applicable. Mutually exclusive with ctENABLE.
ctLK_BLOCK Automatically implements blocking locks when OR-ed with ctREADREC or ctENABLE.
ctLK_RECR Enables recursive locking.
ctSAVENV Saves current ISAM position after each successful ISAM file update operation (i.e., ReWriteRecord(), DeleteRecord(), etc. ).
ctAUTOSAVE Automatically invokes savepoints after each successful ISAM or resource update. Disables ctSAVENV.
ctTWOFASE Enables two-phase transaction support.
ctDEFERBEG Enables a deferred transaction begin state. The TRANBEG log entry is delayed until an update is made within the transaction. This can benefit performance when no updates are made as the transaction flush can ultimately be skipped.

Either ctPREIMG or ctTRNLOG must be used to specify the transaction logging mode.

Note: Using ctPREIMG with a file created with ctTRNLOG results in a TTYP_ERR (99).

Either ctENABLE or ctREADREC may also be OR-ed in to automatically invoke LockISAM(). If either is used, ctLK_BLOCK can be OR-ed in to convert the locks to blocking locks. This sleeps the process until the lock is available instead of returning DLOK_ERR (42).

If ctSAVENV is used, or if the user profile in InitCTreeXtd() or InitISAMXtd() includes USERPRF_SAVENV, then the current ISAM position of the files updated during the transaction is saved. This allows a subsequent Abort() or RestoreSavePoint() to reset the current ISAM position of the files.

Automatic Savepoints

ctAUTOSAVE automatically follows each successful ISAM update or resource update with a special savepoint. The savepoint permits an update error to be rolled-back so that a compound transaction can continue its updates and subsequently Commit() the transaction. This automatic savepoint does NOT support the ctSAVENV profile setting. ctSAVENV is disabled if ctAUTOSAVE is on.

This approach is faster than explicit savepoints after each update since no network traffic is required between updates, and the auto savepoint is more efficient than an explicit savepoint.

If an error occurs in the middle of a set of updates within a single transaction, and if ctAUTOSAVE was in trnmod, the application simply calls RestoreSavePoint(-1) to roll-back the error, and continues update processing.

Explicit calls to SetSavePoint() should not be made when ctAUTOSAVE is effective. Error ASAV_ERR (532) will be returned by SetSavePoint() if called after updates have occurred. A typical usage pattern in pseudo-code would be:

Begin(ctTRNLOG | ctAUTOSAVE | ctENABLE)

    loop: update operation

          if error

              RestoreSavePoint(-1)

          if not done

              goto loop

Commit(...)

Deferred Begin

It is not uncommon for a higher-level API to start transactions without knowledge of whether or not any updates will occur. To reduce the overhead of unnecessary log flushes, a deferred mode is available. ctDEFERBEG results in the actual TRANBEG entry in the log to be delayed until an attempt is made to update a transaction controlled file, and if a TRANEND() or TRANABT() is called without any updates, then the transaction begin and end log entries are not flushed to disk. ctDEFERBEG has no affect for ctPREIMG transactions.

Note: When using a transaction mode of deferred begin, Begin(ctTRNLOG | ctDEFERBEG) returns a value of 1 as the actual transaction number assignment is delayed until the log write of the first file update takes place.

Two-Phase Transactions

Two-Phase transaction support allows, for example, a transaction to span multiple servers. This is useful for updating information from a master database to remote databases in an all-or-nothing approach.

To start a transaction that supports a two-phase commit, you would include the ctTWOFASE attribute in the transaction mode passed to the Begin() function. Call the TRANRDY() function to execute the first commit phase, and finally Commit() to execute the second commit phase.

Note: You may need additional caution with regard to locking and unlocking of records as your transactions become more complex in a multi-server environment to avoid performance problems.

Example

(Note that this example could also use individual threads of operation for the different c-tree Server connections, avoiding the c-tree instance calls.)

COUNT rc1,rc2,filno1,filno2,rcc1,rcc2;

TEXT databuf1[128],databuf2[128];

 

/* Create the connections and c-tree instances */

...

if (!RegisterCtree("server_1")) {

SwitchCtree("server_1");

InitISAMXtd(10, 10, 64, 10, 0, "ADMIN", "ADMIN", "FAIRCOMS1");

filno1 = OPNRFIL(0, "mydata.dat", ctSHARED);

FirstRecord(filno1, databuf1);

memcpy (databuf1, "new data", 8);


/* Prepare transaction on c-tree server 1 */

Begin(ctTRNLOG | ctTWOFASE | ctENABLE);

ReWriteRecord(filno1, databuf2);

rc1 = TRANRDY();

}

 

if (!RegisterCtree("server_2")) {

SwitchCtree("server_2");

InitISAMXtd(10, 10, 64, 10, 0, "ADMIN", "ADMIN", "FAIRCOMS2");

filno2 = OPNRFIL(0, "mydata.dat", ctSHARED);

FirstRecord(filno2, databuf2);

memcpy (databuf2, "new data", 8);


/* Prepare transaction on c-tree server 2 */

Begin(ctTRNLOG | ctTWOFASE | ctENABLE);

ReWriteRecord(filno2, databuf2);

rc2 = TRANRDY();

}

 

/* Commit the transactions */

if (!rc1 && !rc2) {

SwitchCtree("server_1");

rcc1 = Commit(ctFREE);

 

SwitchCtree("server_2");

rcc2 = Commit(ctFREE);

 

if (!rcc1 && !rcc2) {

printf("Transaction successfully committed across both servers.\n");

} else {

printf("One or more units of the second commit phase of the transaction failed: rcc1=%d rcc2=%d\n", rcc1, rcc2);


} else {

printf("One or more of the transactions failed to be prepared: rc1=%d rc2=%d\n", rc1, rc2);


printf("Pending transactions will be aborted.\n");

SwitchCtree("server_1");

Abort();

SwitchCtree("server_2");

Abort();

}

 

/* Done */

SwitchCtree("server_1");

CloseISAM();

SwitchCtree("server_2");

CloseISAM();

 

Note: Two-Phase transactions can become extremely difficult to debug should there be communications problems between servers at any time during the second commit phase. This can result in out of sync data between the servers as one server may have committed while another server failed. It is always appropriate to check the return codes of the individual Commit() functions to ensure a complete successful transaction commit across multiple servers.

Return

Begin() returns a transaction number (low word for six-byte transaction numbers) if successful, or zero on error. With six-byte transaction number support, call ctGETHGH() for the high word of the transaction number.

It an error occurs Begin() returns 0 and uerr_cod will return the appropriate c-tree error code.

Value Symbolic Constant Explanation
70 TEXS_ERR Transaction already pending - you cannot start one until the prior one is committed or aborted.
99 TTYP_ERR Transaction type / trnmod conflict.
150 SHUT_ERR Server is shutting down.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Example

COUNT     savepoint;


void domaster() {

    Begin(ctENABLE|ctTRNLOG);   /* start transaction with locks  */

    while(another()); {     /* get next record to add        */

        savepoint = SetSavePoint(); /* get save point at

                             beginning of each master record */

        if (add_master() < 0)

            Abort();        /* Begin if can't add master rec */

        dodetail();         /* process detail records        */

    }

    if (Commit(ctFREE) != 0)

        printf("\nError %d in transaction",uerr_cod);

    return;

}


void dodetail() {

    while(moredetail()); {   /*get next detail record to add */

        if (add_detail()<0) {    /* add details, if possible */

            RestoreSavePoint(savepoint) /* with error, return

                                                   to savept */

            return;

        }

    }

}

See also

Abort, AbortXtd, Commit, ClearSavePoint, ctGETHGH, ctSETHGH, DeleteRecord, InitCTreeXtd, InitISAMXtd, LockISAM, RestoreSavePoint, ReWriteRecord, SetSavePoint, SetOperationState, TRANRDY

 

BlockingISAMRead

c-tree ISAM function to support a blocking record read.

Short Name

BLKIREC()

Type

ISAM function

Declaration

COUNT BlockingISAMRead(FILNO filno,NINT opcode,LONG timeoutsec,

    pTEXT blockcond,pVOID target,pVOID recptr,pVRLEN plen)

Description

In V12 the file number typedef was formally changed from COUNT, a two-byte value to FILNO, a four-byte value. Refer to this link for compatibility details. Four Byte File Numbering

A blocking record read permits an application to attempt to read a record, and if no existing record satisfy the read request, BlockingISAMRead() blocks until such a record exists or the times out period expires.

BlockingISAMRead() supports blocking ISAM reads on fixed or variable-length records subject to an optional blocking condition that may be a logical expression or a function callback, just as in a set filter call (SETFLTR()).

  • filno is a file number of an open c-tree data or index file.
  • opcode specifies one of the following ISAM read operations:
ISAM Read Operation Explanation
ctBLKIREC_FIRST Read first record in physical or key order
ctBLKIREC_NEXT Read next record in physical or key order
ctBLKIREC_PREV Read previous record in physical or key order
ctBLKIREC_LAST Read last record in physical or key order
ctBLKIREC_GT Read record with key value greater than target key
ctBLKIREC_GTE Read record with key value greater than or equal to target key
ctBLKIREC_EQL Read record with key value equal to target key
ctBLKIREC_LTE Read record with key value less than or equal to target key
ctBLKIREC_LT Read record with key value less than target key
  • timeoutsec specifies the number of seconds the blocking read will wait before returning if no record satisfies the optional blockcond argument or no record is found. Set timeoutsec to zero to return immediately.
  • blockcond is an optional conditional expression which may be a logical expression of the same form as used for conditional index support or a function callback as in a SetDataFilter() call. Set blockcond to an empty string ("") to specify no condition.
  • target should be non-NULL only if filno specifies an index and the opcode requires a target value (for example, ctBLKIREC_GT).
  • The record is read into the buffer pointed to by recptr.
  • plen should be NULL for a fixed-length read, and should point to the length of the output buffer (recptr) for a variable-length read. *plen is updated to the actual record length upon successful return.

The function operates by performing the requested ISAM operation (FIRST(), NEXT(), etc.). If the requested ISAM operation successful, BlockingISAMRead() then sees if the optional blocking condition is satisfied. If no record was found or if the record does not satisfy the blocking condition, and timeoutsec is non-zero, then the read blocks (sleeps) for timeoutsec. The sleep is interrupted if the target file is updated, and this process repeats until a record is found that satisfies the condition, or the block times out. A time out condition is indicated by returning NTIM_ERR (156). BlockingISAMRead() requires server notification support to operate correctly.

Return

Value Symbolic Constant Explanation
0 NO_ERROR No error occurred.
156 NTIM_ERR Timeout error

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Example

struct {

    TEXT    job_name[256];

        .....

    LONG    start_time;

            .....

} JOBMAN;

TEXT    blockcond[128];

ChangeISAMContext
/*

** setting the first character to zero means no

** blocking condition

*/

blockcond[0] = '\0';


start:

    rc = BLKIREC( keyno, ctBLKIREC_FIRST, WAITTIME, blockcond,  NULL, &JOBMAN, NULL);

    if (rc == NTIM_ERR) {

        /* time out occurred. check whether to continue

         ** job management processing

         */

        if **continue** {

            blockcond[0]= '\0';

            goto start;

        } else

            goto end;

    } else if (rc) {

        /* unexpected error */

        handle possible error conditions

         [examin BLKIREC source for possible error cases]

    } else {

        /* found job record. check job start time */

        if **JOBMAN.start_time <= current_time** {

            launch job

            update record (so no longer at front of file)

            blockcond[0] = '\0';

            goto start;

        } else {

            /*

             ** job not ready to run yet. create a

             ** blocking condition so that if a job with

             ** an earlier time is added to the job file

             ** the BLKIREC will return

             */

            ctrt_sprintf(blockcond, "start_time < %ld",JOBMAN.start_time);

            goto start;

        }

    }

end:

 

 

See also

To double performance, see ChangeISAMContext.

 

BuildKey

BuildKey() assembles a key value from the supplied record buffer using the ISAM key segment definitions, then calls TransformKey().

Short Name

frmkey()

Type

ISAM-level index file function

Declaration

COUNT frmkey(FILNO keyno, pTEXT recptr, pTEXT txt, ctRECPT pntr, VRLEN datlen)

Description

In V12 the file number typedef was formally changed from COUNT, a two-byte value to FILNO, a four-byte value. Refer to this link for compatibility details. Four Byte File Numbering

BuildKey() extracts a key value for index number keyno from the data record image of datlen bytes pointed to by recptr. The key value is assembled at the location pointed to by txt. If the index supports duplicate key values, then the 4-byte value given by pntr is appended to the end of the key value in most significant to least significant byte order. BuildKey() uses the information in the Incremental ISAM structure, or ISAM parameter file, to extract the key, concatenating key segments after they have been transformed according to the segment mode parameter.

BuildKey() may be called directly from an application program in a situation where a target key value can be created according to the ISAM specifications, but TransformKey() is not convenient. Consider the following example in which the key value is made up of two segments:

  • The first 6 bytes of the name field converted to upper case with a segment mode value of 2.
  • The 4 bytes of the id field.

In an 80X86 environment, the 4-byte id field will be automatically reversed using a segment mode value of 1 (INTSEG - unsigned integer).

The value of pntr is only used when an index supports duplicate entries. CurrentFileOffset() can be used to determine the current file offset. In most cases, pass a long zero (0L) for this parameter. Use 0xffffffff for pntr before a call to GetLTERecord() for an index supporting duplicates.

Return

BuildKey() returns the length of the key value assembled or a zero if the key is composed entirely of the empty character, as defined in the parameter file. See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

A non-zero return code indicates success. Zero means either no key or an error occurred. When the function returns zero, check isam_err. If it is zero, the specified record image produced no key value (for example due to a condition on the index, or the null key check is enabled and the key consists entirely of the empty character). If it is non-zero, an error occurred.

Example

FILNO     keyno;

COUNT     i;
 

struct {

    COUNT     delflg[4];

    TEXT      name[24];

    LONG      id;

    TEXT      desc[128];

} cur_info,           /* current ISAM buffer                 */

  upd_info,           /* rewrite update buffer               */

  tar_info;           /* target key staging area             */

TEXT     target[10];  /* target key buffer                   */


printf("\n\nEnter name field ");

scanf("%24s",tar_info.name);              /* load name field */


for (i = strlen(tar_info.name); i < 24; i++)     /* pad name */

    tar_info.name[i] = PADDING;


printf("\nEnter id field ");

scanf("%ld",&tar_info.id);                        /* load id */


/* now the raw elements of the target are ready              */

frmkey(keyno, &tar_info,target,0L,sizeof(tar_info));


/* frmkey performs the necessary transformations on tar_info

     and places the result in target. Now search isam files. */

GetRecord(keyno,target,&cur_info);

Limitations

The recbyt parameter in this function is a 4-byte value capable of addressing at most 4 gigabytes. If your application supports HUGE files (greater than 4 gigabytes), you must use the ctSETHGH() and ctGETHGH() functions to set or get the high-order 4 bytes of the file offset.

See also

CurrentFileOffset, GetLTERecord, TransformKey

 

ChangeBatch

Change current batch (group of records).

Short Name

CHGBAT()

Type

ISAM function

Declaration

COUNT ChangeBatch(COUNT batchnum)

Description

ChangeBatch() is called before each use of DoBatch() when multiple batches are in use at the same time.

As a new batch area is needed, call ChangeBatch() with a unique batchnum. When ChangeBatch() perceives a previously unused batchnum value, AllocateBatch() is called to allocate the necessary batch structures for this new batchnum. These structures are not a concern of your program, but they are required for multiple, simultaneous batches.

Changing between active batches is accomplished by passing the desired batchnum value. batchnum values do not need to be consecutive and can be positive or negative values up to the maximum value of COUNT. See your compiler’s limits.h file for the maximum value of a 2-byte integer.

Return

Value Symbolic Constant Explanation
0 NO_ERROR Successful allocation.
185 ISAL_ERR No memory available for set buffers.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Example

#define namebuf 32


struct {                               /* data record format */

    TEXT name[namebuf];                     /* customer name */

    LONG num;                             /* customer number */

} parentimage;


COUNT    error;

PKEYREQ  batsample;   /* batch partial key request structure */

TEXT     recbuf[1024];          /* batch retrieval structure */

TEXT     worktarget[namebuf];

FILNO    keyno;


memset(worktarget,' ',namebuf);

cpybuf(worktarget,"John",strlen("John"));

batsample.siglen = strlen(worktarget); cpybuf(batsample.target,worktarget,strlen(worktarget));


/* bufsiz for DoBatch is namebuf+ 4(long) + 4(record offset) */


if(ChangeBat(0) ||

      DoBatch(keyno,&batsample,recbuf, 40,BAT_GET|BAT_RET_REC))

    printf("\n\tError on BATSET - isam_err = %d",isam_err);

memset(worktarget,' ',namebuf);

cpybuf(worktarget,"Fred",strlen("Fred"));

batsample.siglen = strlen(worktarget);

cpybuf(batsample.target,worktarget,strlen(worktarget));


if (ChangeBat(1) ||

      DoBatch(keyno,&batsample,recbuf, 40,BAT_GET|BAT_RET_REC))

    printf("\n\tError on BATSET - isam_err = %d",isam_err);


ChangeBat(0);

DoBatch(keyno,NULL,NULL,0L,BAT_CAN);


ChangeBat(1);

DoBatch(keyno,NULL,NULL,0L,BAT_CAN);

See also

AllocateBatch, FreeBatch, DoBatch, DoBatchXtd, and Batched Operations (Batched Operations, Batches)

 

ChangeHistory

Change current history buffer.

Short Name

CHGHST()

Type

ISAM function

Declaration

COUNT ChangeHistory(COUNT hstnum)

Description

ChangeHistory() is called before each use of TransactionHistory() when multiple history buffers are in use at the same time. As a new history area is needed, simply call ChangeHistory() with a unique hstnum.

Changing between active history buffers is accomplished by passing the desired hstnum value. hstnum values do not need to be consecutive and can be positive or negative values up to 32,767.

Return

Value Symbolic Constant Explanation
0 NO_ERROR Successful set change.
185 ISAL_ERR No memory available for history buffers.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

See also

TransactionHistory, FreeHistory

 

ChangeISAMContext

Change current ISAM context.

Short Name

CHGICON()

Type

ISAM function

Declaration

COUNT ChangeISAMContext(COUNT contextid)

Description

ChangeISAMContext() accepts the context ID returned as the result of a successful call to OpenISAMContext(). If ChangeISAMContext() is successful, the current ISAM position for the data file associated with the context ID is:

  1. Saved in the context ID active just prior to the call to ChangeISAMContext().
  2. Changed to the position stored in the selected context ID.

If the context ID passed to ChangeISAMContext() is the current context for the associated data file, ChangeISAMContext() has no effect.

Return

Value Symbolic Constant Explanation
0 NO_ERROR Successful change.
590 NCON_ERR Non-existent context ID.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Example

See the example for OpenISAMContext(). The following example uses ctSetAutoContextId() to increase performance.

 

FILNO     datno1,datno2;              /* data file numbers   */

pVOID     bufptr1,bufptr2;            /* data buffer pointer */

COUNT     contextID_1,contextID_2,contextID_3; /* context ID's     */

 

OpenFileWithResource(datno1,"data1",ctSHARED);

OpenFileWithResource(datno2,"data2",ctSHARED);

 

 

/* move to first record for datno1 using first key */

FirstRecord(datno1 + 1,bufptr1);

/* establish first context for datno1 at first record. keyno == -1 saves all key positions. */

contextID_1 = OpenISAMContext(datno1,-1,-1);

/* move to first record for datno2 using third key. */

FirstRecord(datno2 + 3,bufptr2);

/* establish first context for datno2 at first record. keyno != -1 saves only key value for third key. */

contextID_2 = OpenISAMContext(datno2, datno2 + 3,-1);

NextRecord(datno1 + 1,bufptr1);

/* position datno1 at third record by first key. */

NextRecord(datno1 + 1,bufptr1);

/* Third record by first key becomes the saved position for contextID_1 and contextID_3 becomes the active context for datno1. */

contextID_3 = OpenISAMContext(datno1,-1,-1);

/* move from third record by first key, to the next record using the second key. Call this record 4' */

NextRecord(datno1 + 2,bufptr1);

/* Save record 4' as contextID_3. Make the 3rd record the current position for datno1, and contextID_1 becomes the active context for datno1. contextID_2 is still the active context for datno2. */

ctSetAutoContextId(contextID_1);

 

 

/* move to the 4th record by key 1 for datno1.*/

NextRecord(datno1 + 1,bufptr1);

See also

CloseISAMContext, OpenISAMContext

 

ChangeSet

Change current set.

Short Name

CHGSET()

Type

ISAM function

Declaration

COUNT ChangeSet(COUNT setnum)

Description

ChangeSet() is called before each use of a set function when multiple sets are in use at the same time. As a new set area is needed, call ChangeSet() with a unique setnum.

When ChangeSet() perceives a previously unused setnum value, AllocateSet() is called to allocate the necessary set structures for this new setnum. These structures are not a concern of your program, but they are required for multiple, simultaneous sets.

Changing between active sets is accomplished by passing the desired setnum value. setnum values do not need to be consecutive and can be positive or negative values up to the maximum value of COUNT. See your compiler’s limits.h file for the maximum value of a 2-byte integer.

Return

Value Symbolic Constant Explanation
0 NO_ERROR Successful set change.
185 ISAL_ERR No memory available for set buffers.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Example

COUNT i;

FILNO keyno,keyno1;
 

struct DATAREC datrec0,datrec1;


if (ChangeSet(0))

  printf("\nCould not change set. Error = %d\n", isam_err);

if (FirstInSet(keyno0,&datrec0))

  printf("\nCould not get FirstInSet. Error = %d\n", isam_err);


if (ChangeSet(1))

  printf("\nCould not change set. Error = %d\n", isam_err);

if (LastInSet(keyno1,&datrec1))

   printf("\nCould not get LastInSet. Error = %d\n", isam_err);

See also

AllocateSet, FreeSet, FirstInSet, LastInSet, NextInSet, PreviousInSet

 

CleanIndexXtd

Clean up any leaf node exceptions and reset high-water mark.

Short Name

CLNIDXX()

Type

Utility Function

Declaration

COUNT CleanIndexXtd(pTEXT filnam, pTEXT fileword)

Description

CleanIndexXtd() function cleans any leaf nodes of exceptional transaction marks and resets the transaction high-water mark in the header to zero. This allows a high-volume transaction-controlled index file to have its high-water mark reset without rebuilding the entire index file.

Return

This routine returns an error code, but should return NO_ERROR unless filnam does not exist. See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Example

See the ctclntrn utility for an example of this function in use.

See also

ctclntrn utility

 

ClearSavePoint

Remove the last savepoint without undoing other changes.

Short Name

SAVPCLR()

Type

Low-Level function

Declaration

COUNT ClearSavePoint() 

Description

ClearSavePoint() removes a savepoint WITHOUT UNDOING the changes made since the savepoint. Calling ClearSavePoint() puts pre-image space in the same state as if the most recently called savepoint had never been called. By comparison, RestoreSavePoint() cancels changes made since the last savepoint, but does NOT remove this savepoint. ClearSavePoint() takes no arguments, and returns an error code if it fails, or zero if successful.

Return

Value Symbolic Constant Explanation
0 NO_ERROR Savepoint cleared.
71 TNON_ERR No savepoint or no transaction.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

See also

Abort, AbortXtd, Begin, Commit, RestoreSavePoint, SetSavePoint, TRANRDY

 

ClearTranError

Clear an error in an active transaction

DEPRECATED

(circa 2008) It was determined that the TRANCLR() function is unsafe to use: it simply clears the pending transaction error flag and does not do the work needed to clean up a failed operation such as restoring to a savepoint or aborting a transaction does. For this reason, TRANCLR() returns NSUP_ERR without clearing the pending transaction error flag.

Applications that use TRANCLR() should instead recover from an error in a transaction by using savepoints or aborting and restarting the transaction.

This function will be completely removed in future releases.

DEPRECATED - Consider the use of formal Savepoints instead.

Short Name

TRANCLR()

Type

Low-level function

Declaration

COUNT ClearTranError()

Description

If an update error occurs when you are in the middle of a transaction, you will not be able to commit that transaction. For example, AddRecord() could fail trying to add a duplicate key where they are not allowed. A subsequent call to Commit() fails, since an error has occurred.

The proper way to handle this situation is to either use RestoreSavePoint() to go back to a savepoint, or to abandon the entire transaction with Abort(). There is an alternative, however. ClearTranError() can clear the error flag, allowing you to continue with the transaction after correcting the previous error. Typically, you will only do this if you are working with low-level update functions and you know how to recover from the error that has occurred. We DO NOT recommend this, however, as you are now responsible for the integrity of your data.

Return

ClearTranError() always returns zero (NO_ERROR).

Example

COUNT invfil;

struct invd { TEXT delflg; LONG part_no; } recbuf;


part_no = getpartno();

recbuf.delflg = '\0'; /* clear delete flag */

if (AddRecord(invfil,&recbuf))

    ClearTranError();

See also

Abort(), AbortXtd(), Begin(), ClearSavePoint(), Commit(), RestoreSavePoint(), SetSavePoint(), TRANRDY()

 

CloseConnection

Forking a process with an active server connection causes the child and parent processes to each have a reference to the same connection. A new function, CLCONN(), was introduced to clean up one copy of this connection without breaking the other connection.

Declaration

ctCONV  COUNT ctDECL CLCONN( VOID );

Short name

CLCONN()

Description

When a process with an active c-tree connection is forked and does not call exec(), CLCONN should be called by one of the resulting processes to clean up an existing connection rather than calling CLISAM().

This function is only available in client models.

Return Values

Value Symbolic Constant Explanation
0 CTDBRET_OK Successful operation.

See c-tree Plus Error Codes for a complete listing of valid c-tree Plus error values.

 

CloseCtFile

Close index or data file.

Short Name

CLSFIL()

Type

Low-Level file function

Declaration

COUNT CloseCtFile(FILNO filno, COUNT filmod)

Description

In V12 the file number typedef was formally changed from COUNT, a two-byte value to FILNO, a four-byte value. Refer to this link for compatibility details. Four Byte File Numbering

CloseCtFile() closes file number filno.

The filmod parameter is no longer used. It has been left in this definition solely for the sake of compatibility with older versions. If you have programs that were developed with older versions of FairCom DB, you don’t have to change your CloseCtFile() function calls. For newer programs, you can leave it out, unless you are using function prototyping and receive a warning about having too few parameters. In this case either use a second parameter, which will be ignored, or change the function prototype definition in ctdecl.h.

If filno references an index file with additional index members, CloseCtFile() closes the primary index and its members.

CloseCtFile() ensures a file is properly closed so updates will be properly saved to disk. In Low-Level mode, data files are updated by NewData(), ReleaseData(), and WriteData(), and index files are updated by AddKey(), DeleteKey(), and DeleteKeyBlind().

Return

Value Symbolic Constant Explanation
0 NO_ERROR Successful file close.
22 FNUM_ERR File number out of range.
24 FCLS_ERR Could not close file number isam_fil.
26 FACS_ERR File number is not assigned to a file in use.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Example

FILNO     filno = 0;

COUNT     retval;

TEXT      filnam[15] = "sample.dat";


if (retval = InitCtree(6,7,4))

    printf("\nCould not initialize. Error %d.", retval);

else {

    if (OpenCtFile(filno, filnam, (ctSHARED | ctVIRTUAL | ctFIXED)))

        printf("\nCould not open file.");

    else if (CloseCtFile(filno, 0))

        printf("\nCould not close file.");

 

    if (CloseISAM())

        printf("\nCould not close ISAM.");

}

See also

NewData, ReleaseData, WriteData, AddKey, DeleteKey, DeleteKeyBlind, OpenCtFile, CreateDataFile, CreateIndexFile

 

CloseCtFileByName

Close a memory file, or a file held open by the FairCom Server KEEPOPEN_LIST keyword, and remove it from memory.

Short Name

ctCLSNAM()

Type

ISAM function

Declaration

NINT  CloseCtFileByName(cpTEXT filnam, cpTEXT fileword);

Description

CloseCtFileByName() closes a memory file and remove its data from memory.

Parameter filnam is the file name.

fileword is an optional file password. If fileword is null then there will be no password for this file. If a password is established, every user will need to use the password to be able to open the file.

In order to be able to remove the file from memory, all users must have the file closed. To close the file and reopen it, use CloseIFile().

Return

CloseCtFileByName() returns NO_ERROR in case of successfully closing and removing the file from memory.

Value Symbolic Constant Explanation
12 FNOP_ERR Could not open file.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Limitations

Client/Server mode only.

 

CloseIFile

Incremental ISAM close.

Short Name

CLIFIL()

Type

ISAM function

Declaration

COUNT CloseIFile(pIFIL ifilptr)

Description

CloseIFile() closes the data file, and associated indexes, referenced in the IFIL structure pointed to by ifilptr.

Return

Value Symbolic Constant Explanation
0 NO_ERROR Successful close of ISAM files.
24 FCLS_ERR Could not close file number isam_fil.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Example

extern IFIL     myfile;

       COUNT    retval;


if (retval = InitISAM(6,7,4))

    printf("\nCould not close files. Error %d.", retval);

else {

    if (OpenIFile(&myfile))

        printf("\nCould not open files.");

    else if (CloseIFile(&myfile))

        printf("\nCould not close files.");


   if (CloseISAM())

        printf("\nCould not close ISAM.");

}

See also

InitISAM, CreateIFile, OpenIFile, and CloseISAM. The ISAM Functions topic discusses the contents of the IFIL structure.

 

CloseISAM

Close all ISAM files.

Short Name

CLISAM()

Type

ISAM function

Declaration

COUNT CloseISAM()

Description

CloseISAM() closes all the files opened in the current FairCom DB session and frees all memory allocated by that session. If CloseISAM() encounters difficulty closing a file, it tries to close the remaining files. The error code returned by CloseISAM() pertains to the first file that could not be closed.

Before a second FairCom DB session is started with a call to InitCTree(), CreateISAM(), InitISAM() or OpenISAM() can be made, CloseISAM() must be called.

Return

Value Symbolic Constant Explanation
0 NO_ERROR Successful close of ISAM files.
22 FNUM_ERR File number out of range.
24 FCLS_ERR Could not close file number isam_fil.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Example

extern IFIL     myfile;

       COUNT    retval;


if (retval = InitISAM(6,7,4))

    printf("\nCould not close files. Error %d.", retval);

else {

    if (OpenIFile(&myfile))

        printf("\nCould not open files.");


    if (CloseISAM())

        printf("\nCould not close ISAM.");

}

Limitations

CloseISAM() closes all ISAM files including those opened or created with the incremental ISAM functions.

See also

OpenISAM, CreateISAM, InitISAM, OpenIFile, InitCTree, CreateIFile, CloseIFile

 

CloseISAMContext

Close current ISAM context.

Short Name

CLSICON()

Type

ISAM function

Declaration

COUNT CloseISAMContext(COUNT contextid)

Description

CloseISAMContext() removes the context for the specified contextid. It returns all the memory associated with the context.

Return

Value Symbolic Constant Explanation
0 NO_ERROR Successful close ISAM context.
590 NCON_ERR Non-existent (or previously closed) context ID.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Example

See the example for OpenISAMContext()

See also

ChangeISAMContext, OpenISAMContext

 

CloseRFile

Incremental ISAM close for files opened by Resource IFIL open.

Short Name

CLRFIL()

Type

ISAM function

Declaration

COUNT CloseRFile(FILNO filno)

Description

In V12 the file number typedef was formally changed from COUNT, a two-byte value to FILNO, a four-byte value. Refer to this link for compatibility details. Four Byte File Numbering

CloseRFile() closes the data file filno, and all associated indexes, opened by OpenFileWithResource().

Return

Value Symbolic Constant Explanation
0 NO_ERROR Successful close of ISAM files.
22 FNUM_ERR File number out of range.
24 FCLS_ERR Could not close file number isam_fil.
401 RNON_ERR Resources not enabled.
408 RNOT_ERR IFIL structure not stored in data file resource.
438 DZRO_ERR File definition block is empty.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Example

FILNO    myfile;

COUNT    retval;

if (retval = InitISAM(6,7,4))

    printf("\nCould not close files. Error %d.", retval);

else {

    if (myfile = OpenFileWithResource(-1, "sample.dat", 0))

        printf("\nCould not open files.");

    else if (CloseRFile(myfile))

        printf("\nCould not close files.");


    if (CloseISAM())

        printf("\nCould not close ISAM.");

}

See also

InitISAM, CreateIFile, OpenFileWithResource

 

cndxeval

Evaluates an expression tree produced by cndxeval().

Declaration

COUNT cndxeval( PTREE Tree, pVOID Recptr, pConvMap Schema, VRLEN fixlen, VRLEN datlen )

Description

Where:

  • Tree - parse tree generated by cndxparse()
  • Recptr - pointer to a record handle
  • Schema - record schema
  • fixlen - Fixed record length
  • datlen - total record length

Evaluating your expression involves three steps:

  1. Allocate a run-time stack for the expression analyzer (first time only).
  2. Set up a buffer containing the field data used in the expression.
  3. Evaluate the expression.

If you wish, you can repeat steps b) and c) multiple times. Sample code to perform these steps is shown below. It is assumed the Get_Buffer() routine allocates a record buffer and initializes it with data conforming to the field definitions specified in the DODA.

Return Values

Value Symbolic Constant Explanation
1 YES Expression evaluated as true
0 NO Expression evaluated as false

Example

COUNT retcidx;  /* Result of expression evaluation. */

pTEXT recbuf;   /* Record buffer. */


/* Allocate a run-time stack for the expression analyzer (first time only). */

if (!ctcidxStk)  {

    ctcidxStk = (pVOID) getcndxmem(CNDX_MAX_STACK * ctSIZE(PLEAF));

    if (!ctcidxStk)  {

        printf("Unable to allocate memory for run-time stack.\n");

        ctrt_exit(1);

    }

}


/* Set up a buffer containing the field data used in the expression. */

Get_Buffer(&recbuf);


/* Evaluate the expression. */

retcidx = cndxeval(ptree, recbuf, (pConvMap)schema);

if (retcidx < 0)

    printf("The expression cannot be evaluated for this record

           - error %d.\n", uerr_cod);

else if (retcidx)

    printf("The expression evaluates to TRUE for this record.\n");

else

    printf("The expression evaluates to FALSE for this record.\n");

See also

cndxfree, cndxparse, ctparsedoda, cndxrun, getcndxmem, putcndxmem

 

cndxfree

Frees an expression tree generated by cndxparse().

Declaration

cndxfree ( PTREE Tree );

Description

cndxfree() releases en entire PTREE structure.

Return Values

Value Symbolic Constant Explanation
0 CTDBRET_OK Successful operation.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Example

PTREE ptree;   /* Expression tree.    */

....

ptree = cndxparse(schema, names, expr, strlen(expr));

if (!ptree)

    printf("Error: Unable to parse expression.\n");

else

    printf("Successfully parsed expression.\n");

....

if ( ptree )

cndxfree (ptree);

See also

cndxeval, cndxparse, ctparsedoda, cndxrun, getcndxmem, putcndxmem

 

cndxparse

Creates an expression tree for later evaluation.

Declaration

PTREE cndxparse( pConvMap Schema, pTEXT Names, pTEXT InputText, NINT InputTextSize )

Description

You can use the FairCom DB expression parser/analyzer to evaluate expressions. For a complete sample program, see ctexpr.c in the ctree/source directory.

Where:

  • Schema - DODA
  • Names - List of names of fields
  • InputText - Text of conditional expression
  • InputTextSize - Length of text for conditional expression

Using the FairCom DB expression parser/analyzer involves two steps:

  1. Calling cndxparse() to parse your expression, producing an expression tree the expression analyzer can evaluate. This involves three steps:
    1. Define a DODA structure.
    2. Parse the DODA into a record schema and field name list.
    3. Parse your expression to produce an expression tree.
  2. Calling cndxeval() to evaluate the expression tree using data from a buffer in memory.

Return Values

Returns a PTREE parse tree on success. NULL if error.

Example

#include "ctcndx.h"  /* For PTREE type */
 

/* Define a DODA structure. */

DATOBJ doda[] = {

  {"CustomerNumber", 0,  CT_INT4U},

  {"ZipCode",        4,  CT_FSTRING,  9},

  {"State",         13,  CT_FSTRING,  2},

  {"LastName",      15,  CT_STRING,  37},

  {"FirstName",     52,  CT_STRING,  37},

  {"Address",       89,  CT_STRING,  49},

  {"City",         138,  CT_STRING,  37}

};


COUNT retval;  /* Return code.        */

pTEXT schema;  /* Record schema.      */

pTEXT names;   /* Field name list.    */

PTREE ptree;   /* Expression tree.    */

pTEXT expr;    /* Expression string.  */
 

/* Parse the DODA into a record schema and field name list. */

if ((retval = ctparsedoda(doda, 7, &schema, &names)) != 0)

    printf("Error %d parsing DODA.\n", retval);


/* Parse your expression to produce an expression tree. */

expr  = "stricmp(LastName, \"Smith\") == 0

        && CustomerNumber > 10000";

ptree = cndxparse(schema, names, expr, strlen(expr));

if (!ptree)

    printf("Error: Unable to parse expression.\n");

else

    printf("Successfully parsed expression.\n");

...

if ( ptree )

cndxfree (ptree);

See also

cndxeval, cndxfree, ctparsedoda, cndxrun, getcndxmem, putcndxmem

 

cndxrun

Executes the parse tree evaluating an expression in a parse tree. The result of the expression is left on top of the stack.

Declaration

COUNT cndxrun( PTREE Tree, pVOID Recptr, pConvMap Schema, VRLEN fixlen, VRLEN datlen );

Description

Where:

  • Tree - Parser tree generated by the expression parser
  • Recptr - pointer to a record buffer with data
  • Schema - c-tree DODA schema for the data file
  • fixlen - record fixed length size
  • datlen - total size of record

Return Values

Value Symbolic Constant Explanation
  ERY_NONE SUCCESS

 

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Example

if ( ( retcidx = cndxrun( (PTREE)expr->expr_tree, 

pRecord->recbuf,

(pConvMap)pTable->schemaptr,

(VRLEN)pRecord->fixrec_len,

(VRLEN)pRecord->recbuf_len inHan) ) == ERY_NONE && ctcidxStkPtr == 0 )

{

retval = CTDBRET_INTERNAL;

goto Exit;

}

See also

cndxeval, cndxfree, cndxparse, ctparsedoda, getcndxmem, putcndxmem

 

Commit

Commit the current transaction in progress.

Short Name

TRANEND()

Type

Low-Level data file function

Declaration

COUNT Commit(COUNT mode)

Description

Commits all file updates for files that support transactions, which means that the updates go to the data files from the preimage buffers.

The mode parameter can take on values from the following table.

Mode Description
ctFREE Clear the LockISAM() state and free all locks acquired before and during an active transaction.
ctKEEP Does not clear the LockISAM() state and keeps all the locks acquired before and during an active transaction.
ctKEEP_OUT Release only locks obtained within the transaction and/or locks on records updated within the transaction. Does not clear the LockISAM() state.
ctKEEP_OUT_ALL Unconditionally keep all locks that were acquired before the transaction began. Free locks obtained within the transaction. Does not clear the LockISAM() state.

Note: If an update error has occurred, such as an AddRecord() failing due to a duplicate key, Commit() returns a PNDG_ERR (94) error and aborts the transaction.

Return

Value Symbolic Constant Explanation
0 NO_ERROR No error occurred.
37 WRITE_ERR Most likely the disk is full. Transaction is aborted.
71 TNON_ERR There is no active transaction pending.
94 PNDG_ERR An update error occurred during one of the previous operations that has not been cleared through RestoreSavePoint().

See c-tree Plus Error Codes for a complete listing of valid c-tree Plus error values.

Example

Begin(ctENABLE | ctTRNLOG);        /* Start transaction with locks   */


while(another())                 /* Get next record to add         */

    if (add_master() < 0) {

        printf(Error adding record.\n");

        Abort();                 /* Abort if can't add master rec. */

        return(-1);

    }

    dodetail();                  /* Process detail records         */

}

if (Commit(ctFREE) > 0)

    printf("\nError %d in transaction",uerr_cod);

See also

Abort, AbortXtd, Begin, ClearSavePoint, RestoreSavePoint, SetSavePoint, TRANRDY

For a full description of transaction processing, see the Data Integrity in the c-tree Plus Programmer’s Reference Guide.

 

CompactIFile

Compresses a data file, then rebuilds to regenerate the indexes.

Short Name

CMPIFIL()

Type

ISAM function

Declaration

COUNT CompactIFile(pIFIL ifilptr)

Description

CompactIFile() removes any deleted records from the data file pointed to by ifilptr. Up to twice the data file size is needed to perform this operation. This function calls RebuildIFile to rebuild the associated indexes. CompactIFile() produces a compressed data file containing only active records and new optimized indexes. By calling this function, remote client processes can compact and rebuild files in the client/server model.

InitISAM() must be called prior to calling CompactIFile(). The file(s) pointed to by ifilptr must be closed at the time of the call to CompactIFile().

CompactIFile() also supports two features that the file rebuild function RebuildIFile() supports:

  • Purging of records having illegal duplicate keys.
  • Updating the IFIL resource in the data file with the IFIL and IIDX and ISEG structure definitions passed to CompactIFile().

These features are used in the same way they are used when calling RebuildIFile():

  • To instruct the compact operation to purge records containing illegal duplicate keys, set the purgeIFIL mode in the tfilno member of the IFIL structure passed to CompactIFile().
  • To instruct the compact operation to update the IFIL resource in the data file with the structure definitions passed to CompactIFile(), set the updateIFIL mode in the tfilno member of the IFIL structure passed to CompactIFile().
  • To specify both options, add both modes to the tfilno member of the IFIL structure. For example:

   myifil.tfilno = updateIFIL + purgeIFIL;

To enable or disable compression when calling CompactIFile(), set the chgcompressIFILoption bit in the tfilno member of the IFIL structure whose address you pass to CMPIFIL(). When this bit is set, CMPIFIL() switches the compression state of the file: compressed files become un-compressed, un-compressed files become compressed.

Serial Number Reassignment

When a serial number (SRLSEG or SCHSRL) field reaches the maximum value, FairCom DB simply increments the serial number such that it wraps around and continues with 0, 1, 2, and so on. This can cause a duplicate key error when an attempt is made to add a record. However, a record having that serial number already exists. To provide an option to recover from this situation, FairCom DB now permits the ISAM file compact functions CMPIFIL(), CMPIFILX(), and CMPIFILX8() to assign new serial numbers to the records in the compacted version of a file. Prior to this modification, the compact always copied the records with their original serial numbers to the new compacted file, so the new file used the same serial numbers as the old file.

The caller of the file compact function indicates that the serial numbers are to be reassigned by specifying a special value in the tfilno field of the IFIL structure that it passes to the compact function.

Prior to FairCom DB V9.5, several option values were defined such as updateIFIL, purgeIFIL, and badpartIFIL, that can be specified. These values are specified by adding them together. For example: myifil.tfilno = updateIFIL + purgeIFIL. A new approach simplifies checking of these options. The following option values are now specified in ctport.h:

#define updateIFILoption 0x0002

#define purgeIFILoption 0x0004

#define badpartIFILoption 0x0008

#define redosrlIFILoption 0x0010

#define chgcompressIFILoption 0x0020  - set compression on/off for new file

#define setencryptIFILoption 0x0040  - use current ctSETENCRYPT state for new file

These values can now be OR-ed together and, using the setIFILoptions() macro, assigned to the tfilno field of the IFIL structure passed to the compact or rebuild function. For example, to indicate that you want to assign new serial numbers, do the following:

myifil.tfilno = setIFILoptions(redosrlIFILoption);

CMPIFIL(&myifil);

If you want to also use more than one option when compacting or rebuilding a file, OR them in to the value. For example:

/* assign new serial numbers and update IFIL resource. */

myifil.tfilno = setIFILoptions(redosrlIFILoption | updateIFILoption);

CMPIFIL(&myifil);

While it is possible to rebuild a mirrored file in c-tree, it is not possible to compact such a file.

Updates for V11

Beginning in FairCom DB V11, several improvements were made to the API function and the compact utility. The file compact utility (ctcmpcif) and the CompactIFile() API function now better handle file encryption The following improvements were made:

  1. The compact API function and utility can optionally change encryption attributes. To use this option when calling the compact API function, use the setIFILoptions() macro to set the setencryptIFILoption bit in the tfilno field of the IFIL structure whose address you pass to the compact API function, and call ctSETENCRYPT() with the desired encryption attributes before calling the compact API function. For example:

 

NINT rc;

 

myifil.tfilno = setIFILoptions(setencryptIFILoption);

rc = ctSETENCRYPT(ctAES32, NULL, 32);

rc = CMPIFIL(&myifil);

 

  1. The ctcmpcif utility now supports an option to specify the encryption cipher for the data and index files created by the compact operation. Usage:

-encrypt=cipher - Create the compacted file using the specified cipher:

  • for AES, use aes16, aes24, or aes32
  • for Blowfish, use blf8, blf9, ..., or blf56
  • for DES, use des8, des16, or des24
  • for Twofish, use twf16, twf24, or twf32
  • for no encryption, use none
  1. Compact now always deletes and recreates index files after saving resources from the original index file. This provides the expected behavior of (possibly) reducing the size of the index file.

Online Compact - new for V13

Files can now be compacted while the file is open in ctSHARED mode. To enable this request, call CMPIFIL() (CompactIFile) using the new onlineIFILoption bit:

myifil.tfilno = setIFILoptions(onlineIFILoption);

This carries out a more limited form of file compact, referred to as defragmentation, while the file remains available to other users. Defragmentation attempts to reorganize the records within the file to minimize file size. When defragmentation is completed, the size of the file is reduced, if possible.

If the file is under ctTRNLOG control, a ctSHARED mode index rebuild will automatically follow a successful ctSHARED mode compact.

LIMITATIONS: Server Only. The calling user should have the target file initially closed with no active transactions. Other CMPIFIL options specified using setIFILoptions()are not available in combination with onlineIFILoption. Defragmentation is not supported for memory files, super files, partition host files, segmented files, or index files.

 

NOTES: Defragmentation works similar to a regular user normally updating records within the file. Due to the type and extent of changes during defragmentation, it may highlight artifacts of multiuser interference not frequently observed by applications. Applications using files without transaction control, or using physical order scans, or using more relaxed locking protocols may see increased rates of these artifacts when defragmentation is in progress. This may appear as unexpected missing or even duplicate records (which a future scan doesn't encounter).

Return

A zero (0) return indicates successful operation. A non-zero return indicates an error, check isam_err. The error returns are similar OpenCtFile() and RebuildIFile(). See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Example

extern IFIL    customer;

       COUNT   retval;


main() { 

    if (retval = InitISAM(10,10,16))

        printf("\nInitISAM error = %d",retval);


    if (!(CompactIFile(&customer)))

        printf("\nSuccessful compact");

    else

        printf("\nCompactIFile isam_err = %d",isam_err);


    CloseISAM();

}

Limitations

  • CompactIFile() does not support FairCom DB Superfiles, see Superfiles.
  • Online compact is not allowed for changing encryption or compression settings.

See also

 

CompactIFileXtd

Compresses a data file, then rebuilds to regenerate the indexes.

Short Name

CMPIFILX()

Type

Extended ISAM function

Declaration

COUNT CompactIFileXtd(pIFIL ifilptr, cpTEXT dataextn,

                      cpTEXT indxextn, LONG permmask,

                      cpTEXT groupid, cpTEXT fileword)

Description

CompactIFileXtd() is the extended version of CompactIFile() permitting the use of the FairCom Server security system.

In addition, it can be used to change the file name extension from the defaults used by CompactIFile(). The period is not assumed in the extensions. For example, to name the data file fname.dta, set dataextn to .dta, not dta.

Please read the description for CompactIFile() and RebuildIFileXtd() for additional information.

Return

A zero (0) return indicates successful operation. A non-zero return indicates an error, check isam_err. The error returns are similar OpenCtFile() and RebuildIFileXtd(). See FairCom DB Error Codes for additional error explanations.

Limitations

Same as CompactIFile().

See also

 

CompactIFileXtd8

Compresses a data file, then rebuilds to regenerate the indexes.

Short Name

CMPIFILX8()

Type

Extended ISAM function for files with extended header support

Declaration

COUNT CompactIFileXtd8(pIFIL ifilptr, cpTEXT dataextn,

                      cpTEXT indxextn, LONG permmask,

                      cpTEXT groupid, cpTEXT fileword,pXCREblk pxcreblk )

Description

CompactIFileXtd8() is the extended version of CompactIFile() permitting the use of the FairCom DB security system and adds extended header support (pxcreblk).

In addition, it can be used to change the file name extension from the defaults used by CompactIFile(). The period is not assumed in the extensions. For example, to name the data file fname.dta, set dataextn to .dta, not dta.

pxcreblk points to an array of XCREblk structures, the extended creation block, one for each physical file in ifilptr. For more information, review Huge File Support.

Note: Memory files can not have ctTRNLOG mode applied or CreateIFileXtd8() fails with error 749 (bad parameter). Be sure to adjust any IFIL definitions.

Please review CompactIFile() and RebuildIFileXtd() descriptions for additional information.

Return

A zero (0) return indicates successful operation. A non-zero return indicates an error, check isam_err. The error returns are similar to OpenCtFile() and CompactIFileXtd(). See FairCom DB Error Codes for additional error explanations.

Limitations

Same as CompactIFileXtd().

See also

 

cpybuf

Copy one buffer area to another regardless of any null characters.

Short Name

cpybuf()

Type

Utility function

Declaration

void cpybuf(pTEXT destination, pTEXT source, UINT length)

Description

cpybuf() copies length bytes from source to destination.

It does not stop when it sees a null character. You can copy strings or structures with this.

We strongly suggest using cpybuf() instead of strcpy(), for the following reasons:

  • strcpy() copies until it reaches a null character, terminating the source string. If a string is larger than the destination buffer, an overwrite of adjacent data or code occurs. This can be an extremely difficult bug to find. Using a length as the size of the destination buffer as the limit to cpybuf() avoids this problem.
  • Many constructs used in FairCom DB are not null-terminated strings. Keys and data records can both have null characters embedded in the middle. strcpy() will not copy the entire data item in this case.

Example

FILNO   keyno;

TEXT    target[24],idxval[23];

LONG    recbyt;


scanf("%23s",target);

recbyt = GetGTEKey(keyno,target,idxval);

while (recbyt) {

    printf("\nIndex entry = %23s ", idxval);

    printf("\nRecord # = %ld, recbyt);

    cpybuf(target,idxval,23);

    recbyt = GetGTKey(keyno,target,idxval);

}

Limitations

cpybuf() does not check to see if the buffer at destination is large enough to hold the data being moved.

See also

FairCom DB also includes cpybig(), which provides the same functionality as cpybuf(), and works for very large buffers, even on machines with segmented memory models. The length parameter is declared as VRLEN instead of UINT, which provides for larger buffers. Also see strcpy().

 

CreateDataFile

Create a data file.

Short Name

CREDAT()

Type

Low-Level data file function

Declaration

COUNT CreateDataFile(FILNO datno, cpTEXT filnam, UCOUNT datlen,

                     UCOUNT xtdsiz, COUNT filmod)

Description

CreateDataFile() attempts to create a new data file with the name pointed to by filnam and with a record length of datlen. Subsequent calls to other Low-Level data file functions use datno to reference this file. datno must be in the range 0 to fils - 1, where fils is the second parameter in the initialization routine InitCTree().

If a file with the name pointed to by filnam already exists, CreateDataFile() returns an error code, and the file is not opened.

filmod determines if the file contains fixed- or variable-length records, whether it is shared or used exclusively, and whether it is opened permanently or virtually. The following list shows the values that can be used for filmod. You can combine the values by OR-ing them together, such as:

(ctVIRTUAL | ctEXCLUSIVE | ctFIXED)

Some values must be used exclusively. For instance, you cannot use both ctSHARED and ctEXCLUSIVE. You cannot use more than one mode from any line in the listing below. In addition, you must use one of the modes from each of the first three groups.

ctPERMANENT ctVIRTUAL

ctEXCLUSIVE ctSHARED ctREADFIL

ctFIXED ctVLENGTH

ctCHECKLOCK

ctCHECKREAD

ctPREIMG ctTRNLOG

ctDUPCHANEL

ctWRITETHRU

ctSUPERFILE

ctDISABLERES

ctCHECKREAD and ctDUPCHANEL are available only if you are using the FairCom Server. See filmod in the index for additional information.

Note: ctCHECKLOCK and ctCHECKREAD are intended as debugging aids to help developers to identify code locations where locks are not being acquired.

ctCHECKREAD is not compatible with ctSUSPEND because ctSUSPEND will disable record lock acquisition without releasing existing locks, so any record read would then trigger the ctCHECKREAD error condition.

ctCHECKLOCK and ctCHECKREAD should not be applied to index files.

 

If the file is created with a fixed record length, then datlen must be greater than 4. If the file is created with a variable record length, then datlen is interpreted as the fixed portion of the record for the file and may be greater than or equal to zero. See Fixed versus Variable-length Records for more information.

If xtdsiz is greater than zero, then whenever it is necessary to extend the size of the data file, it will be extended by xtdsiz bytes and the directory will be updated. If xtdsiz is set too large, then disk space will be wasted. If xtdsiz is too small (but greater than zero), then the time to extend the file and force a directory update will become excessive. A value of zero for xtdsiz causes the file to grow one data record at a time without the directory being updated until the file is closed.

When a fixed record length data file is extended by xtdsiz bytes, delete flags are written into the beginning of each logical record in the newly allocated space. This may cause a noticeable delay for large values of xtdsiz.

Except for ctFIXED versus ctVLENGTH, and ctPREIMG versus ctTRNLOG, filmod is not permanently stored with the file. A file may be opened as a read only (ctREADFIL) one time, ctSHARED another and ctEXCLUSIVE yet another time.

The name referenced by filnam must conform to the operating system environment, and usually can include directory path names and/or disk drive identifiers. The file name should be null terminated.

ctSUPERFILES: Superfiles and superfile members, discussed in “Advanced FairCom DB Concepts", must be handled differently than standard files. When creating a superfile, the file mode ctSUPERFILE must be OR-ed. Set xtdsiz and datlen to 0. Superfiles consume two consecutive file numbers, datno and datno + 1. Superfile members can be a mixture of data and index files. The name of the member must be formed as follows:

<name of superfile>!<name of member>

Return

Value Symbolic Constant Explanation
0 NO_ERROR Data file successfully created.
17 DCRAT_ERR Could not create data file.
19 DOPN_ERR Data file already exists. File is not opened.
21 DREC_ERR Record length is too small. File is not created.
22 FNUM_ERR File number is out of range.
46 FUSE_ERR File number is already in use.
413 SDIR_ERR Host superfile is not open.
414 SNST_ERR Cannot nest superfiles.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Example

FILNO     datno = 0;

COUNT     retval, reclen = 64;

UCOUNT    xtdsiz = 1024;

TEXT      filnam[15] = "sample.dat";


if (retval = InitCtree(6,7,4))

    printf("\nCould not initialize. Error %d.", retval);

else {

    if (CreateDataFile(datno, filnam, reclen, xtdsiz,

       (ctSHARED | ctVIRTUAL | ctFIXED)))

          printf("\nError %d creating file %.14s", uerr_cod, filnam);

    else if (CloseCtFile(datno, 0))

        printf("\nCould not close file.");


    if (OpenCtFile(datno, filnam, (ctSHARED | ctVIRTUAL | ctFIXED)))

        printf("\nCould not open file.");

    else if (CloseCtFile(datno, 0))

        printf("\nCould not close file.");


    if (CloseISAM())

        printf("\nCould not close ISAM.");

}

Limitations

While CreateDataFile() can mark a file for shared use, it is not created in the shared mode. In order to use a data file in the shared mode, it must first be created, then closed (CloseCtFile()), then opened (OpenCtFile()) with a shared file mode.

See also

CloseCtFile, OpenCtFile, InitCTree, CreateIndexFile, CreateDataFileXtd

 

CreateDataFileXtd

Extended data file creation.

Short Name

CREDATX()

Type

Low-Level data file function

Declaration

COUNT CreateDataFileXtd(FILNO datno, cpTEXT filnam,

                  UCOUNT datlen, UCOUNT xtdsiz, COUNT filmod,

                  LONG permmask, cpTEXT groupid, cpTEXT fileword)

Description

In V12 the file number typedef was formally changed from COUNT, a two-byte value to FILNO, a four-byte value. Refer to this link for compatibility details. Four Byte File Numbering

CreateDataFileXtd() is a variation of CreateDataFile() that permits the use of the FairCom Server’s security system. This section expands on the description of CreateDataFile().

permmask is the permission mask assigned to this data file. It is formed by OR-ing the appropriate permission constants.

groupid is a pointer to a buffer that contains the group id that this file is to be assigned to. The group id must be valid for the user that is creating the file. If groupid is null, the file will be assigned to the default group for the user.

fileword is an optional file password. If fileword is null then there will be no password for this file. If a password is established, every user will need to use the password to be able to open the file.

For more information on permission masks, group IDs, and file passwords, review Security and Encryption (File Security and Encryption, /doc/ctreeplus/FileSecurityandEncryption.htm).

Return

The following error code may be seen in addition to those for CreateDataFile():

Value Symbolic Constant Explanation
455 SGRP_ERR This user does not belong to the group groupid.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

See also

InitCTree, CreateIndexFile, CreateDataFile

 

CreateDataFileXtd8

Extended 8-byte data file creation.

Short Name

CREDATX8()

Type

Low-Level 8-byte data file function

Declaration

  COUNT CreateDataFileXtd8(FILNO datno, cpTEXT filnam, UCOUNT datlen,

           UCOUNT xtdsiz, COUNT filmod, LONG permmask, cpTEXT groupid,

           cpTEXT fileword, pXCREblk pxcreblk)

Description

In V12 the file number typedef was formally changed from COUNT, a two-byte value to FILNO, a four-byte value. Refer to this link for compatibility details. Four Byte File Numbering

CreateDataFileXtd8() is a variation of CreateDataFile() that permits the use of huge file support. This section expands on the description of CreateDataFile() and CreateDataFileXtd().

pxcreblk points to a XCREblk structure, the extended creation block. For more information, review Huge File Support.

Return

CreateDataFileXtd8() returns similar error codes to those for CreateDataFile() and CreateDataFileXtd(). See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

See also

InitCTree, CreateIndexFile, CreateDataFile, CreateDataFileXtd

 

CreateIFile

Incremental ISAM create.

Short Name

CREIFIL()

Type

ISAM function

Declaration

COUNT CreateIFile(pIFIL ifilptr)

Description

CreateIFile() creates the data file and (optional) index file referenced by the IFIL structure pointed to by ifilptr. The file name pointed to by the IFIL structure, ifilptr- >pfilnam, should NOT include an extension: “.dat” and “.idx” are automatically appended to the file name for the data file and index file, respectively. The extended version of this function, CreateIFileXtd(), can change the file extensions at runtime.

If you desire the files to be created in directories that are not specified until runtime, then ifilptr- >pfilnam should not be finalized until runtime.

Consecutive file numbers are assigned to the data file and any (optional) indexes associated with the data file. The IFIL structure contains two file numbers: a permanent file number (dfilno), and a temporary file number (tfilno). If dfilno is less than zero, FairCom DB finds the first available block of sufficient consecutive file numbers. If such a block of numbers is found, then the first number in the block is assigned to the data file and to tfilno. If dfilno is greater than or equal to zero, then dfilno is assigned to the data file and to tfilno.

Unless Resources are disabled for this file, CreateIFile() automatically stores the IFIL definition in the file as a resource. This permits OpenFileWithResource() to open the entire IFIL set simply by file name.

Prevent ISAM Index Key Value Updates

Beginning with V11, it is possible to create an index that does not allow an ISAM update to change the key values. On such an index, an ISAM record add can add a new key value and an ISAM record delete can delete a key value, but an ISAM record update cannot change a key value. (Note the special case for a variable-length record: if an ISAM update causes the record to move, the key is allowed to change its record offset from the old offset to the new offset; but the key value itself is not allowed to change.)

To create an index with this feature enabled, OR KTYP_NOISMUPD into the key type (ikeytyp) field of the IIDX structure for that index file before calling CREIFIL() to create the index.

PUTIFIL() can be used to turn this bit on or off. Changes take effect immediately.

An ISAM record update that attempts to change a key value for an index with this property enabled fails with error UKEY_ERR (1001).

Return

Upon successful create, ifilptr->tfilno contains the file number assigned to the data file; and the associated indexes are assigned consecutive index numbers starting one (1) greater than the data file number.

Value Symbolic Constant Explanation
0 NO_ERROR Successful open of ISAM files.
16 KCRAT_ERR Could not create index file.
17 DCRAT_ERR Could not create data file.
18 KOPN_ERR Index file already exists. File is not opened.
19 DOPN_ERR Data file already exists. File is not opened.
20 KMIN_ERR Key length too large for node size.
21 DREC_ERR Record length is too small. File is not created.
22 FNUM_ERR File number is out of range.
45 KLEN_ERR Key length exceeds MAXLEN parameter in ctoptn.h.
46 FUSE_ERR File number is already in use.
47 FINT_ERR FairCom DB has not been initialized. Call InitISAM before the first call to CreateIFile().
107 IDRK_ERR Too many index files for one data file. Increase MAX_DAT_KEY parameter in ctoptn.h or keyword in ctsrvr.cfg.
109 IKRS_ERR Too many key segments. Increase MAX_KEY_SEG parameter in ctoptn.h.
115 ISLN_ERR Key segments do not equal key length.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Example

extern IFIL     myfile;

       COUNT    retval;


if (retval = InitISAM(6,7,4))

    printf("\nCould not close files. Error %d.", retval);

else {

    if (CreateIFile(&myfile))

        printf( "\nCould not create %s (%d,%d)\n", 

               myfile.pfilnam, isam_err, isam_fil );

    else if (CloseIFile(&myfile))

        printf("\nCould not close files.");

   

    if (OpenIFile(&myfile))

        printf("\nCould not open files.");

    else if (CloseIFile(&myfile))

        printf("\nCould not close files.");


    if (CloseISAM())

        printf("\nCould not close ISAM.");

}

Limitations

The index files will be numbered consecutively following the data file. See “File numbering” in the index for additional information.

While CreateIFile() can mark files for shared use, they is not created in the shared mode. In order to use files in the shared mode, they must first be created, then closed, then opened with a shared file mode.

See also

InitISAM, OpenIFile, CloseISAM, CreateIFileXtd, OpenFileWithResource, GetIFile and the ISAM Functions, which describes the ISAM parameters.

 

CreateIFileXtd

Extended incremental ISAM creation.

Short Name

CREIFILX()

Type

Extended ISAM function

Declaration

COUNT CreateIFileXtd(pIFIL ifilptr, cpTEXT dataextn,

                     cpTEXT indxextn, LONG permmask,

                     cpTEXT groupid, cpTEXT fileword)

Description

CreateIFileXtd() is a variation of CreateIFile() that permits the use of the FairCom Server’s security system. This section expands on the description of CreateIFile().

dataextn and indxextn point to buffers specifying the data and index file name extensions, respectively, which should include the period, ‘.’. The extensions are 8-byte ASCIIZ (NULL terminated ASCII) strings. If the pointers are NULL, the default extension will be used: “.dat” for data files and “.idx” for index files. For files with no extension, pass a pointer to a buffer that contains only blanks terminated by a NULL character.

permmask is the permission mask assigned to this data file. It is formed by OR-ing the appropriate permission constants.

groupid is a pointer to a buffer that contains the group id that this file is to be assigned to. The group id must be valid for the user that is creating the file. If groupid is null, the file will be assigned to the default group for the user.

fileword is an optional file password. If fileword is null then there will be no password for this file. If a password is established, every user will need to use the password to be able to open the file.

For more information on permission masks, group IDs, and file passwords, review Security and Encryption (File Security and Encryption, /doc/ctreeplus/FileSecurityandEncryption.htm).

Return

The following error code may be seen in addition to those for CreateIFile():

Value Symbolic Constant Explanation
455 SGRP_ERR This user does not belong to the group groupid.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

See also

CreateIFile, InitISAM, OpenIFile, CloseISAM

 

CreateIFileXtd8

Extended 8-byte incremental ISAM creation.

Short Name

CREIFILX8()

Type

Extended 8-byte ISAM function

Declaration

COUNT CreateIFileXtd8(pIFIL ifilptr, cpTEXT dataextn,

                      cpTEXT indxextn, LONG permmask,

                      cpTEXT groupid, cpTEXT fileword,

                      pXCREblk pxcreblk)

Description

CreateIFileXtd8() is a variation of CreateIFile() that permits the use of huge file support. This section expands on the description of CreateIFile() and CreateIFileXtd().

pxcreblk points to an array of XCREblk structures, the extended creation block, one structure for each physical file specified in the IFIL structure, ifilptr. For more information, review Huge File Support.

Return

CreateIFileXtd8() returns similar error codes to those for CreateIFile() and CreateIFileXtd(). See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

See also

InitISAM, CreateIFile, CreateIFileXtd, OpenIFile, CloseISAM

 

CreateIndexFile

Create an index file.

Short Name

CREIDX()

Type

Low-Level index file function

Declaration

COUNT CreateIndexFile(FILNO keyno, cpTEXT filnam, COUNT keylen,

                      COUNT keytyp, COUNT keydup, COUNT nomemb,

                      UCOUNT xtdsiz, COUNT filmod)

Description
In V12 the file number typedef was formally changed from COUNT, a two-byte value to FILNO, a four-byte value. Refer to this link for compatibility details. Four Byte File Numbering

CreateIndexFile() attempts to create a new index file with the name pointed to by filnam and with a key length of keylen bytes. If a file with the name pointed to by filnam already exists, CreateIndexFile() returns an error code, and the file is not opened.

keyno must be in the range 0 to fils - 1 where fils is the second parameter in the initialization routine InitCTree(). Subsequent calls to other Low-Level index file functions use keyno to reference this file.

keytyp determines whether keys are fixed length or use some form of compression. See Alternative Key Type for more information.

keydup of 0 indicates no duplicates allowed, and a value of 1 indicates duplicate keys are supported.

Note: Allowing duplicate records assumes the last 4 bytes of keylen is available for the record offset. Add 4 bytes to the length of the key segments making up a duplicate key.

nomemb specifies the number of additional indexes which will reside in this index file. Combining more than one index in one physical index file reduces the file descriptors used by an application. If nomemb is zero (0), no additional indexes are included. Each additional index has its own key length, key type and auto-duplication parameter. In order to set these parameters for the additional indexes, CreateIndexMember() should be called for each additional index immediately after the call to CreateIndexFile().

Once the index file and all its members have been created, a single call to OpenCtFile() activates all members of the index file. See OpenCtFile() for a more complete discussion. Each additional index is referenced by a file number equal to keyno plus the member number. For example, if keyno is three (3) and nomemb is five (5), the index created by CreateIndexFile() will be referenced by file number three (3). The first additional index will be referenced by key number four (4), the second by five (5), and so on through key number eight (8).

If xtdsiz is greater than zero, whenever it is necessary to extend the size of the index file, it will be extended by xtdsiz bytes and the directory will be updated. If xtdsiz is set too large, then disk space will be wasted. If xtdsiz is too small (but greater than zero), the time to extend the file and force a directory update will become excessive. A value of zero for xtdsiz causes the file to grow one B-Tree node at a time without the directory being updated until the file is closed.

filmod determines whether the index is shared or used exclusively, and whether it is opened permanently or virtually. The following list shows the values that can be used for filmod. You can combine the values by OR-ing them together, such as:

(ctVIRTUAL | ctEXCLUSIVE)

Some values must be used exclusively of others. For instance, you cannot use both ctSHARED and ctEXCLUSIVE. You cannot use more than one mode from any line in the listing below. In addition, you must use one of the modes from each of the first two groups.

ctPERMANENT ctVIRTUAL

ctEXCLUSIVE ctSHARED ctREADFIL

ctPREIMG ctTRNLOG

ctDUPCHANEL

ctWRITETHRU

Note: ctDUPCHANEL is available only if you are using the FairCom Server and only with limited platforms.

Except for ctPREIMG and ctTRNLOG, filmod is not permanently stored with the file. A file may be opened as a read only (ctREADFIL) one time, ctSHARED another and ctEXCLUSIVE yet another time.

The name referenced by filnam must conform to the operating system environment, and usually can include directory path names and/or disk drive identifiers. The file name should be null terminated.

Superfiles: An index file can be a member of a Superfile, as discussed in the Chapter 9 “FairCom DB Features”. The name of the member must be formed as follows:

<name of superfile>!<name of member file>

Return

Value Symbolic Constant Explanation
0 NO_ERROR Index file successfully created.
16 KCRAT_ERR Could not create index file. Possibly no disk or directory space, no more file descriptors, or an improper file name.
18 KOPN_ERR Index file already exists. File is not opened.
20 KMIN_ERR Key length too large for node size (determined by node sectors in call to InitCTree()). There must be room for at least four key values per node.
22 FNUM_ERR keyno + nomemb is out of range.
23 KMEM_ERR nomemb < 0 or nomemb > 31.
45 KLEN_ERR Key length exceeds MAXLEN parameter in ctoptn.h.
46 FUSE_ERR A file number in the range keyno to keyno + nomemb is already in use.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Example

FILNO     keyno = 0;

COUNT     retval, keylen,keytyp,keydup,nomemb;

UCOUNT    xtdsiz = 1024;

TEXT      filnam[15] = "sample.dat";


if (retval = InitCtree(6,7,4))

    printf("\nCould not initialize. Error %d.", retval);

else {

    if (CreateIndexFile(keyno, filnam, keylen, keytyp, keydup,

                        nomemb, 8192, (ctSHARED | ctVIRTUAL)))

        printf("\nError %d creating file %.14s",uerr_cod,

               filnam);

    else if (CloseCtFile(keyno, 0))

        printf("\nCould not close file.");


    if (OpenCtFile(keyno, filnam, (ctSHARED | ctVIRTUAL | ctFIXED)))

        printf("\nCould not open file.");

    else if (CloseCtFile(keyno, 0))

        printf("\nCould not close file.");


    if (CloseISAM())

        printf("\nCould not close ISAM.");

}

Limitations

While CreateIndexFile() allows a file to be marked for sharing, it does not actually create the index in the shared mode. For an index file to be shared by multiple users, it must be created, then closed (CloseCtFile()), then opened (OpenCtFile()) with a shared file mode. Most application programs use a separate module to create the files at installation time, so the main module will only open the files.

If using an alternate collating sequence, call SetAlternateSequence() immediately after creating the index file to assign an alternate collating sequence to the index file.

See also

InitCTree, CreateDataFile, CreateIndexMember, CreateIndexFileXtd, OpenCtFile and FairCom DB Keys for a discussion on how automatic support of duplicate keys is handled.

 

CreateIndexFileXtd

Extended index file creation.

Short Name

CREIDXX()

Type

Extended Low-Level index file function

Declaration

COUNT CreateIndexFileXtd(FILNO keyno, cpTEXT filnam,

        COUNT keylen, COUNT keytyp, COUNT keydup, COUNT nomemb,

        UCOUNT xtdsiz, COUNT filmod, LONG permmask,

        cpTEXT groupid, cpTEXT fileword)

Description

In V12 the file number typedef was formally changed from COUNT, a two-byte value to FILNO, a four-byte value. Refer to this link for compatibility details. Four Byte File Numbering

CreateIndexFileXtd() is a variation of CreateIndexFile() permitting use of the FairCom Server’s security system. Please read the description of CreateIndexFile() before proceeding, since only the extended features are described here.

permmask is the permission mask assigned to this data file. It is formed by OR-ing the appropriate permission constants.

groupid is a pointer to a buffer containing the group id assigned to this file. The group id must be valid for the user that is creating the file. If groupid is null, the file is assigned to the user’s default group.

fileword is an optional file password. If fileword is null, no password is stored for this file. If one is established, every user will need to use the password to be able to open the file.

For more information on permission masks, group IDs, and file passwords, refer to Security and Encryption (File Security and Encryption, /doc/ctreeplus/FileSecurityandEncryption.htm).

Return

The following error code may be seen in addition to those for CreateIndexFile():

Value Symbolic Constant Explanation
455 SGRP_ERR This user does not belong to the group groupid.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

 

CreateIndexFileXtd8

Extended 8-byte index file creation.

Short Name

CREIDXX8()

Type

Low-Level data file function

Declaration

  COUNT CreateIndexFileXtd8(FILNO keyno, cpTEXT filnam,

          COUNT keylen, COUNT keytyp, COUNT keydup,

          COUNT nomemb, UCOUNT xtdsiz, COUNT filmod,

          LONG permmask, cpTEXT groupid, cpTEXT fileword,

          pXCREblk pxcreblk)

Description

In V12 the file number typedef was formally changed from COUNT, a two-byte value to FILNO, a four-byte value. Refer to this link for compatibility details. Four Byte File Numbering

CreateIndexFileXtd8() is a variation of CreateIndexFile() that permits the use of huge file support. This section expands on the description of CreateIndexFile() and CreateIndexFileXtd().

pxcreblk points to an XCREblk structure, the extended creation block. For more information, review Huge File Support.

Return

CreateIndexFileXtd8() returns similar error codes to those for CreateIndexFile() and CreateIndexFileXtd(). See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

See also

InitCTree, CreateIndexFile, CreateDataFile, CreateIndexFileXtd

 

CreateIndexMember

Create an additional index file member.

Short Name

CREMEM()

Type

Low-Level index file function

Declaration

COUNT CreateIndexMember(FILNO keyno, COUNT keylen,

                        COUNT keytyp, COUNT keydup, COUNT membno)

Description

In V12 the file number typedef was formally changed from COUNT, a two-byte value to FILNO, a four-byte value. Refer to this link for compatibility details. Four Byte File Numbering

CreateIndexMember() attempts to add an additional index to index file number keyno, just created by CreateIndexFile(). This additional index file member has a key length of keylen bytes.

keytyp determines whether keys are fixed length or use some form of compression. See Alternative Key Types for more information.

keydup of 0 indicates no duplicates allowed, and a value of 1 indicates duplicate keys are supported.

membno must be in the range from 1 to the number of members set by the previous call to CreateIndexFile() (see the nomemb parameter of CreateIndexFile()). Subsequent calls to other Low-Level index file functions use keyno + membno to reference this file. For example, if keyno is three (3) and membno is two (2), then this additional index file member is referenced as file number five (5).

Return

Value Symbolic Constant Explanation
0 NO_ERROR Index file member successfully added.
20 KMIN_ERR Key length too large for node size (determined by node sectors in call to InitCTree()). There must be room for at least four key values per node.
23 KMEM_ERR membno < 1 or membno greater than number of additional members established for the index keyno.
45 KLEN_ERR Key length exceeds MAXLEN parameter in ctoptn.h.
46 FUSE_ERR File number keyno + nomemb is already in use.
48 FMOD_ERR keyno is not assigned to an index file.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Example

FILNO     keyno = 0;

COUNT     retval, keylen,keytyp,keydup,nomemb;

UCOUNT    xtdsiz = 1024;

TEXT      filnam[15] = "sample.dat";


if (retval = InitCtree(6,7,4))

    printf("\nCould not initialize. Error %d.", retval);

else {

    if (CreateIndexFile(keyno, filnam, keylen, keytyp,

                     keydup, nomemb, 8192, (ctSHARED | ctVIRTUAL)))

        printf("\nError %d creating file %.14s",uerr_cod,

              filnam);

    else {

        if (CreateIndexMember(keyno, keylen2, keytyp2,

                               keydup2, membno);

            printf("Error %d adding member %d.", uerr_cod,

                   membno);


        if (CloseCtFile(keyno, 0))

            printf("\nCould not close file.");


        if (OpenCtFile(keyno, filnam,

                      (ctSHARED | ctVIRTUAL | ctFIXED)))

            printf("\nCould not open file.");

        else if (CloseCtFile(keyno, 0))

            printf("\nCould not close file.");

    }


    if (CloseISAM())

        printf("\nCould not close ISAM.");

}

Limitations

See the Limitations discussion under CreateIndexFile().

See also

InitCTree, SetAlternateSequence, InitCTree, CreateIndexFile, OpenCtFile and FairCom DB Keys for a discussion on how automatic support of duplicate keys is handled.

 

CreateISAM

Create all the ISAM files.

Short Name

CREISAM()

Type

ISAM function

Declaration

COUNT CreateISAM(pTEXT filnam)

Description

CreateISAM() opens the parameter file, whose name is pointed to by filnam, and creates the data and index files specified in the parameter file. Application programs using the ISAM level functions must make a call to CreateISAM(), InitISAM(), or OpenISAM() before any other FairCom DB functions are used. If any one of these three functions has been called, then CloseISAM() must be called before anyone of them can be invoked again. In part, this implies that no more than one ISAM parameter file may be active at one time. However, the incremental ISAM functions allow for more flexibility in file manipulations.

Although it is not recommended, it is possible to use incremental ISAM file opens and creates along with a parameter file. Increase the value of the second parameter in the parameter file, (idxs), by the total number of files used by the incremental routines. For example, if the incremental routines open two additional data files, each with five indexes, then the idxs parameter in the ISAM parameter file should be increased by 12.

Return

Value Symbolic Constant Explanation
0 NO_ERROR Successful open of ISAM files.
10 SPAC_ERR Not enough space for file structures and buffers.
11 SPRM_ERR Illegal parameters in first record of parameter file.
16 KCRAT_ERR Could not create index file.
17 DCRAT_ERR Could not create data file.
18 KOPN_ERR Index file already exists. File is not opened.
19 DOPN_ERR Data file already exists. File is not opened.
20 KMIN_ERR Key length too large for node size.
21 DREC_ERR Record length is too small. File is not created.
22 FNUM_ERR File number is out of range.
45 KLEN_ERR Key length exceeds MAXLEN parameter in ctoptn.h.
102 INOD_ERR Could not open ISAM parameter file.
103 IGIN_ERR Could not read first record of ISAM parameter file.
104 IFIL_ERR Too many files specified. Increase MAXFIL in ctoptn.h and rebuild library.
106 IDRI_ERR Could not read data file description record in parameter file.
107 IDRK_ERR Too many index files for one data file. Increase MAX_DAT_KEY parameter in ctoptn.h, (and rebuild the library), or increase the ctsrvr.cfg keyword.
108 IMKY_ERR keyno for index member is out of sequence. keyno must equal the host index keyno plus the member number.
109 IKRS_ERR Too many key segments. Increase MAX_KEY_SEG parameter in ctoptn.h.
110 ISRC_ERR Could not read key segment description record in parameter file.
111 IKRI_ERR Could not read index file description record in parameter file.
115 ISLN_ERR Key segments do not equal key length.
117 IMRI_ERR Could not read index member record.
125 IINT_ERR FairCom DB already initialized. Call CloseISAM() before recalling CreateISAM().
182 IKSR_ERR No room for r-tree temporary files. Increase MAXFIL in ctoptn.h and rebuild library.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Example

TEXT         isam_par[64];


printf("\nEnter ISAM parameter file name: ");

scanf("%63s",isam_par);

if (CreateISAM(isam_par))

    printf("\n%s files could not be created. (%d  %d)",

          isam_err,isam_fil);

if (CloseISAM())

    printf("\nCould not close ISAM.");

if (OpenISAM(isam_par))

    printf("\nCould not open ISAM.");

if (CloseISAM())

    printf("\nCould not close ISAM.");

}

Limitations

It is not possible to open some of the files specified in the parameter file and create others. They must all be created by CreateISAM(). However, the incremental ISAM functions permit on the fly opening and closing of ISAM files. If you are adding a new index file to an established set of ISAM files, you should :

Update the parameter file to include the new index;

  • Use the rebuild utility to create and build the new index file (respond no when asked to force rebuild); and
  • Call OpenISAM() to actually use the files.

See also

CloseISAM, InitISAM, OpenISAM, CreateIFile, OpenIFile, CreateISAMXtd and ISAM Parameters, which describes the parameter, file contents.

 

CreateISAMXtd

Extended ISAM file creation routine.

Short Name

CREISAMX()

Type

Extended ISAM function

Declaration

COUNT CreateISAMXtd(pTEXT filnam, COUNT userprof, pTEXT userid, pTEXT userword,

                    pTEXT servname, LONG permmask, pTEXT groupid, pTEXT fileword)

Description

CreateISAMXtd() is a variation of CreateISAM() that permits the use of the FairCom Server’s security system. This section expands on the description of CreateISAM().

userprof is the user profile mask. Setting this to the value USERPRF_NTKEY disables the automatic TransformKey() feature. See the TransformKey() function description for more information. Setting this to the value USERPRF_SAVENV enables the automatic ctSAVENV feature. See the Begin() function description for more information. You can OR these values together, or leave userprof set to zero if you don’t want either.

userid is a pointer to a buffer containing the user ID. If userid is null, the user is assigned the ID of GUEST

userword is a pointer to a buffer containing the user password.

servname is a pointer to a Server name if you are going to use a Server other than the default Server.

permmask is the permission mask assigned to this data file. It is formed by OR-ing the appropriate permission constants.

groupid is a pointer to a buffer that contains the group id that this file is to be assigned to. The group id must be valid for the user that is creating the file. If groupid is null, the file will be assigned to the default group for the user.

fileword is an optional file password. If fileword is null then there will be no password for this file. If a password is established, every user will need to use the password to be able to open the file.

For more information on user IDs, user passwords, server names, permission masks, group IDs, and file passwords, review Security and Encryption (File Security and Encryption, /doc/ctreeplus/FileSecurityandEncryption.htm).

Return

The following error codes may be seen in addition to those for CreateISAM():

Value Symbolic Constant Explanation
453 NSRV_ERR Invalid Server name.
455 SGRP_ERR This user does not belong to the group groupid.
1215 AUTHENTICATION_ERR Invalid authentication information.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

See also

CreateISAM, TransformKey, Begin, InitISAM, OpenISAM, CloseISAM

 

ctAddSerialNumberField

Declaration

 ctCONV NINT ctDECL ctAddSerialNumberField(FILNO datno, UCOUNT mode, UCOUNT offset, UCOUNT length);

 

  • datno is the user file number of the data file, which must be open in exclusive mode.
  • mode is either SRLSEG or SCHSRL.
  • offset is the serial number offset, which is interpreted as follows: If mode is SCHSEG, offset is a zero-based offset in the record, otherwise offset is the zero-based field number in the DODA.
  • length is the size of the serial number in bytes, either 4 or 8.

NOTE: The data file requires an extended header in order to use this function.

Description

ctAddSerialNumberField() modifies any four- or eight-byte integer field to be automatically incremented when a record is inserted. Unlike an SRLSEG or SCHSRL field, the field is not indexed.

This function returns a c-tree error code. NO_ERROR indicates success.

NOTE: If a version of the database engine that doesn't support this feature attempts to open a data file that uses this feature, the file open fails with error 744 (FREL_ERR) and logs a message to CTSTATUS.FCS indicating which feature bit is not supported. In that case, the solution is to update the database engine to a version that supports this feature.

See Also

Serial Segments (SRLSEG)

Sequence Number Segments

Serial Number Segments

Key Segment Modes (Key Segment Modes, /doc/ctreeplus/30863.htm)

 

ctAlterSchema

Declaration

NINT ctAlterSchema(FILNO datno, pVOID precdsc); 

 

  • datno is the user file number of the data file, which must be open in exclusive mode.
  • precdsc is a pointer to a record descriptor, which indicates what changes are being made to the schema.
     

Record Descriptor

typedef struct recdsc {

LONG rdtype; /* type (version macro) of record descriptor */

LONG rdcount; /* number of entries in record descriptor */

LONG oldrln; /* old data record length */

LONG newrln; /* new data record length */

pVOID prdspec; /* record descriptor specification */

} RCDSC, *pRCDSC, **ppRCDSC;


/* record descriptor, version 2 */

typedef struct recdsc2 {

LONG rdtype; /* type of record descriptor - ctRDSCver2 */

LONG rdcount; /* number of entries in record descriptor */

LONG oldrln; /* old data record length */

LONG newrln; /* new data record length */

pTEXT dllname; /* optional field conversion DLL name */

pVOID prdspec; /* record descriptor specification */

} RCDSC2, * pRCDSC2, ** ppRCDSC2;

 

#define RCACTnochange 0 /* no changes to this field */

#define RCACTaddfield 1 /* add this field */

#define RCACTdelfield 2 /* delete this field */

#define RCACTupdfield 3 /* change attributes of this field */

Description

Alter an existing table schema. This function enables the hot alter table function. To use this feature, first create a file that uses the flexible record support attribute, ctFLEXREC, bit in the splval field of the extended create block structure for the data file. For example:
 

IFIL    myifil = { ... };

XCREBLK xcreblk[2];

NINT    rc;

 

memset(xcreblk,0,sizeof(xcreblk));

xcreblk[0].splval = ctFLEXREC;

rc = CREIFILX8(&myifil, NULL, NULL, 0, NULL, NULL, xcreblk);

Example

RCDSC recdsc = { 0 };

RCSCHD fieldlist[] = {

{RCACTaddfield, "newfield", CT_STRING, 128, "", 1},

{RCACTnochange, "custnum", CT_INT4, 4},

{RCACTdelfield, "field1", CT_STRING, 32},

{RCACTnochange, "field2", CT_STRING, 32},

{RCACTnochange, "field3", CT_STRING, 32}

};

 

recdsc.rdtype = ctRDSCver1;

recdsc.rdcount = sizeof(fieldlist)/sizeof(*fieldlist);

recdsc.prdspec = fieldlist;

recdsc.oldrln = 0;

recdsc.newrln = 0;

 

if ((rc = ctAlterSchema(datno, &recdsc))) {

qa_err_printf("Error: Failed to change file schema: %d\n",

rc);

goto err_ret;

 

Field Conversion Callback

V13 added the ability to define custom field conversions during alter table. It is now possible to include a custom shared library to be used with ctAlterSchema().

This function accepts parameters that use the record descriptor base structure of type RCDSC, and an array of record descriptor structure of type RCSCHD. To support this field conversion feature, we define a new structure, RCDSC2, that contains a field pTEXT dllname to hold the field conversion DLL name, and we defined a new structure RCSCHD2, that contains a field pTEXT fncname to hold the field conversion function name.

The data type of the precdsc pointer in ctAlterSchema() was changed to pVOID such that either a pointer to the RCDSC structure or the RCDSC2 structure can be specified.

To use version 2 of these structures, use the RCDSC2 and RCSCHD2 structures and set the RCDSC2 rdtype field to ctRDSCver2.

The function prototype for the user-defined field conversion function convertfield() is shown here. Note the use of the pRCSCHDN data type, which is a pointer to the current version of RCSCHD structure. The field conversion function should check that the version value passed to the function matches the version of the RCSCHD structure (1 or 2) that the conversion function is using.

NINT convertfield(NINT verson, pRCSCHDN pschema, ppTEXT pdp, pVRLEN premlen, ppTEXT psp, VRLEN datlen, TEXT dbyte, TEXT pbyte) 
 

[IN] verson: Version of pschema structure. 

[IN] pschema: Record descriptor for this field. 

[IN,OUT] pdp: Destination data pointer. 

[IN,OUT] premlen: Remaining length in output buffer. 

[IN,OUT] psp: Source data pointer. 

[IN] datlen: Number of bytes from source data pointer to end of record image. 

[IN] dbyte: String delimiter byte. 

[IN] pbyte: String padding byte. 

Returns a c-tree error code. NO_ERROR indicates success.

Diagnostics

We added a companion utility function, ctGetRecordConverters(), that can be used to read the record converter information that is stored in the data file by a hot alter schema operation. The ctinfo utility uses this function to read and display the record converter information.
 

NINT ctGetRecordConverters(FILNO datno, pTEXT buffer, pVRLEN pbuflen); 


[IN] datno- Data file number. 

[OUT] buffer- Output buffer. 

[IN/OUT] pbuflen- On input, holds the size of the output buffer in bytes. If the output buffer is too small to hold the output data, the function returns VBSZ_ERR and sets *pbuflen to the required buffer size in bytes. On success, holds the size of the data that was written to the output buffer. 

ctGetRecordConverters() reads the record converters from the specified data file. The record converters are written to the output buffer as a null-terminated string in JSON format.

Returns a c-tree error code. NO_ERROR(0) indicates success.

Example code for a field conversion function can be found in

ctree\source\ctrucbdll.c in the function qaflexrec015_convertfield().

Compatibility

Our implementation approach for version 2 of the hot alter feature allows existing code to operate without any changes. If a new client attempts to use the new feature with an old server, its function call fails with error FVER_ERR (43). Even if a call to ctAlterSchema() specifies version 2 of the hot alter structures, the function call data is sent to the server in version 1 format unless the new structure fields are used, and the record converter is stored in version 1 format in the data file. This makes it possible to preserve backward compatibility of a v2 client with v1 servers.

Contact FairCom if you're interested in implementing this callback capability.

Return Values

Value Symbolic Constant Explanation
0 CTDBRET_OK Successful operation.

See c-tree Plus Error Codes for a complete listing of valid c-tree Plus error values.

Example

 

 

See Also

 

ctCallback

Establish a notification callback.

Short Name

ctCallback()

Type

ISAM function.

Declaration

NINT  ctCallback(NINT opcode, NINT objhandle, ctCallbackPtr cbptr,

                 NINT contents, NINT controls)

Description

Instead of passing the notification information to a queue, a server-side SDK can make calls to ctCallback() to associate a callback function to a notification.

ctCallback() is used in the same manner as ctNotify() except that the third parameter is a pointer to a callback function instead of a queue handle.

A notification setup with ctCallback() causes the function pointed to by cbptr to be called (instead of a message written to a queue). This capability is only available with the server SDK, and ctCallback() can only be called from code compiled into the server itself (using the server SDK).

The prototype for the callback function pointer is:

typedef NINT (*ctCallbackPtr)(pVOID msg,NINT msglen,pVOID aux,NINT auxlen);

The callback function returns NO_ERROR on success and a non zero value on failure. Parameter msg and the optional parameter aux are input parameters. If both msg and aux are passed in, then they should be conceptually pasted together to form one long message.

It is important to note that as currently coded, the target file’s header semaphore is held while the callback function is executed. Therefore the callback function cannot introduce pauses or delays or attempt to lock the header of the target file.

Return

Value Symbolic Constant Explanation
0 NO_ERROR Successful close of the queue.
446 BMOD_ERR Bad mode: parameter out of range.
458 SWRT_ERR Write permission not granted.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Example

NINT MyCallBack(pVOID msg, NINT msglen, pVOID aux, NINT auxlen)

{

    /* save callback message to disk */

    fwrite(msglen, sizeof(msglen), 1, fd);

    fwrite(msg, msglen, 1, fd);

}


if (ctCallback(ctNT_ADDREC, datno, MyCallBack, 0, 0) != NO_ERROR)

    printf("ctCallback failed\n");

Limitations

Server-side SDK only.

See also

ctNotify

 

ctCloseSequence

Declaration

NINT ctCloseSequence(LONG seqhnd);

Description

Closes the sequence having the specified handle.

Return Values

Value Symbolic Constant Explanation
0 NO_ERROR Successfully created the sequence.
900 SEQDUP_ERR A sequence having the specified name already exists.
903 SEQTYP_ERR The specified sequence type contains an invalid combination of sequence type options.
904 SEQINI_ERR The initial value specified for the sequence is out of range.
905 SEQCUR_ERR The current value specified for the sequence is out of range.
906 SEQLIM_ERR The limit value specified for the sequence is out of range.
907 SEQINC_ERR The increment value specified for the sequence is out of range.
901 SEQNAM_ERR An invalid sequence name was specified: the name is NULL, empty, or too long.

See FairCom DB Error Codes for a complete listing of valid error values.

Example

ctSEQATTR seqattr;

NINT rc;

/*

** Create an incrementing sequence that starts with 1, increments by 3, and

** terminates with 100.

*/

strcpy(seqattr.seqnam, "MyFirstSequence");

seqattr.seqini = 1;

seqattr.seqinc = 3;

seqattr.seqlim = 100;

seqattr.seqtyp = ctSEQINC | ctSEQTRM | ctSEQLIM;

 

if ((rc = ctCreateSequence(&seqattr))) {

printf("Error: Failed to create the sequence: %d\n", rc);

} else {

printf("Successfully created the sequence.\n");

}

See also

ctCreateSequence, ctDeleteSequence, ctOpenSequence, ctCloseSequence, ctGetSequenceAttrs, ctSetSequenceAttrs, ctGetCurrentSequenceValue, ctSetCurrentSequenceValue, ctGetNextSequenceValue

 

ctCopyFile

Description:

Server-to-server file copy.

ctCopyFile() makes a copy of a c-tree data or index file, or a c-tree data file and its associated index files. The caller specifies the source and destination file names and options that affect the behavior of the file copy. c-tree copies the files synchronously. That is, the copy call does not return until the file copy is completed.

Prototype:

NINT  ctCopyFile(pCPYFIL pcpyfil); 

Parameters:

ctCopyFile() accepts one parameter: a pointer to a file copy option structure, CPYFIL (see definitions below).

Returns:

ctCopyFile() returns zero indicating all files were successfully copied or a non-zero value to indicate one or more files failed to copy. The caller can supply an optional error message buffer and buffer size. If an error message buffer is supplied and an error occurs, the file copy function writes an error message to the error message buffer.

Notes:

The caller can optionally specify a callback function that is periodically called for displaying user feedback progress bars. The callback function is called at the start of the file copy, for each 1% of the file that has been copied, and at the end of the file copy. The callback function must return zero to permit the file copy to continue, and it can return a non-zero error code in order to terminate the file copy operation.

To copy a file, a caller must be authorized by c-tree (including the file system) to open a file for read access. ADMIN user is always granted read permission for all files. (c-tree file permissions are only supported in the client/server model and not with standalone usage.)

c-tree attempts to open the file in exclusive mode, while still allowing other connections to open the file for read access. If the file is already open, c-tree flushes updates to disk and sets the update flag to zero to indicate that the file is in a clean, consistent state. If c-tree cannot open the file in exclusive mode, the copy operation fails.

An option provides a way to open the file in shared mode. This option indicates the server should try to open the files to copy in shared mode if the files can't be opened in exclusive mode. To use this option, OR the ctCFallowSharedOpen bit into the cpoptions field of the CPYPRM structure passed to ctCopyFile()

Note: Files with an .FCS extension (such as FAIRCOM.FCS, SYSLOGDT.FCS, L0000001.FCS, SNAPSHOT.FCS, etc.) are considered to be a c-tree internal system housekeeping files. The file copy function does not allow copying from or to c-tree internal system files. An attempt to copy such a file fails with error code 1013 (SCPY_ERR).

Copying c-tree files

When copying a c-tree file, c-tree assigns a new file ID to the copy of the file so that the file ID does not match the original file’s ID, and c-tree sets the data and index file and directory names in the data file’s IFIL resource to the names of the new copies of the files. Other than those differences, the copied file is identical to the original file: it contains the same active and deleted data records or index nodes and key values, resources, and has the same properties as the original file, including:

  • security (file owner, file group, file permission mask, file password)
  • data encryption
  • data compression
  • transaction control

The caller indicates what action to take when a file already exists with the same name as the specified destination file. By default, the file copy fails in this situation, but the caller can specify that the existing file should be deleted instead.

When copying multiple files (for example when copying a data file and its associated index files), if an error occurs c-tree stops the file copy operation and deletes all files that were successfully copied. If desired, the caller can specify an option to keep all the successfully copied files in case of an error.

Limitations

The following operations are not currently supported:

  • Copying a partition host file.
  • Copying a segmented file.
  • Copying a superfile host file.
  • Copying a non-c-tree file.

File Copy Options


ISAM or Low-Level Copy

Choose either an ISAM-level or a low-level file copy:

  • An ISAM copy specifies the name of a c-tree data file, and the data file and its associated index files are copied.
  • A low-level file copy copies only the specified file.

Use one of these options to select the desired behavior:

  • ctCFisam - Copy an ISAM data file and its index files.
  • ctCFlowlevel - Copy only the specified file.

Copy with file opened in shared mode

  • ctCFallowSharedOpen - Allow files to be opened in shared mode if possible. Available in V11.6 and later.


Copy to Directory or File Names

Choose to either copy the file(s) to a specified directory or to copy the specified file(s) to the specified new file name(s).

Copying to a specified directory requires the caller to specify the source file name and the destination directory name. In order to use this option for an ISAM file copy, the data and index files must all reside in the same directory.

Copying to the specified new file names requires the caller to specify the source file name and the destination file name. When using this option for an ISAM file copy, the caller must supply source and destination file names for the data file and all its index files.

Use one of these options to select the desired behavior:

  • ctCFtoDir - Copy files to the specified directory.
  • ctCFtoName - Copy files to the specified file names.


Destination File Exists

Choose the desired behavior when the destination file exists. By default, if the destination file exists, the file copy function leaves the destination file unchanged and returns an error. The caller can instead choose to delete the destination file by using the following option:

  • ctCFifexistDelete - Delete destination file if it exists.


Create Destination Directory

By default, if a destination directory does not exist, the file copy fails. The caller can choose to create the destination directory by using the following option:

  • ctCFcreateDirs - Create destination directories.


Keep Successfully-Copied Files if One Fails

By default, when a c-tree data file and its associated index files are being copied, if one of the files fails to be copied, all the successfully-copied files are deleted. The caller can choose to keep the successfully-copied files by using the following option value:

  • ctCFiferrorKeep - Keep all successfully-copied files if a subsequent file fails to be copied.


Remote File Copy

By default, a FairCom DB server creates the destination file on its own filesystem (a local file copy). Files can be copied to another server (a remote file copy) by specifying the following option and specifying the user ID, user password, and server name in the server parameter block or the appropriate API function to set server parameters:

  • ctCFtoServer - Copy files to a specified server.

Your remote server must have ENABLE_TRANSFER_FILE_API YES in the configuration file or you will receive error NSUP_ERR (454, Feature not supported).

You will also need a multithreaded client library in the local server (mtclient.dll for Windows or libmtclient.so for Unix/Linux) or you will receive error TR_CLIL_ERR (850, "Transactional replication: Failed to start c-tree remote client subsystem: see CTSTATUS.FCS for details").

If you are logged on as a non-ADMIN user, you also need COMPATIBILITY NONADMIN_TRANSFER_FILE specified or you receive error LADM_ERR (589, Admin logon required).

Note: SYSCFG() has been updated with state bits to check for library availability as well as if the copy feature is enabled. Refer to SYSCFG() documentation for usage.


Verify

If you wish to verify that the source and destination files are identical after the file has been successfully copied, use the following option:

  • ctCFverify - After copying a file, verify that the source and destination files are identical.

Note: This option is not yet supported for a remote file copy operation.

File Copy Function Call Structure Definitions


typedef struct cpyfil {

    LONG     versn;     /* Structure version               */

    LONG     ncpyprm;   /* Number of file copy param lists */

    LONG     errbufsiz; /* Size of optional error buffer   */

    LONG     reserved;  /* Reserved for future use         */

    pCPYPRM  pcpyprm;   /* File copy parameter lists       */

    pCPYFNC  pcpyfnc;   /* Callback function               */

    pTEXT    errbuf;    /* Optional error message buffer   */

} CPYFIL, ctMEM * pCPYFIL;

versn must be initialized to value CPYFIL_VERS_CUR.
 

File Name Structure Definition:


typedef struct ctfnam {

    TEXT     name[MAXFNAME]; /* Directory or file name.    */

} CTFNAM, *pCTFNAM;
 

File Copy Parameter Structure Definition:


typedef struct ctcpyprm {

    LONG     versn;     /* Structure version               */

    ULONG    cpoptions; /* File copy options               */

    ULONG    fboptions; /* File block options              */

    LONG     filnamcnt; /* Number of file names            */

    pTEXT    fileword;  /* File password                   */

    SRVPRM   srvprm;    /* Server parameters               */

    pCTFNAM  srcfilnam; /* Source file names               */

    pCTFNAM  dstfilnam; /* Destination dir or file names   */

} CPYPRM, ctMEM * pCPYPRM, ctMEM ** ppCPYPRM;

versn must be initialized to value CPYPRM_VERS_CUR
 

File Copy Server Parameter Definition:


typedef struct srvprm {

    NINT     versn;          /* Structure version   */

    TEXT     userid[32];     /* User id             */

    TEXT     userword[64];   /* User password       */

    TEXT     servname[256];  /* Server name         */

} SRVPRM, ctMEM * pSRVPRM;

versn must be initialized to value SRVPRM_VERS_CUR.
 

File Copy Callback Function Parameters:


typedef struct cpystt {

    pCPYFIL pcpyfil; /* options passed to file copy function */

    pTEXT   filnam;  /* name of the source file being copied */

    COUNT   val;     /* percent complete or error code       */

    TEXT    opcode;  /* operation code                       */

} CPYSTT, *pCPYSTT;
 

File Copy Callback Function Prototype:


typedef NINT (*pCPYFNC)(pCPYSTT pcpystt);
 

File Copy Callback Function Operation Codes:

  • ctCPYCBKbeginfile - Start file copy
  • ctCPYCBKprogfile - File copy progress (val contains the percent complete)
  • ctCPYCBKendfile - End file copy (val contains the error code)
  • ctCPYCBKvrfyfile - File verify progress (val contains the percent complete)

Notes:

  1. If there is only one physical index file associated with a data file and the physical index file's aidxnam is NULL (so that it has the same name as the data file), the ctCFtoName option can be used with only one set of names (old data file name and new data file name).
  2. When a file copy fails because the destination file exists, error 18 is returned if a destination index file exists and error 19 is returned if the destination data file exists.

Error Codes

New error codes introduced with the ctCopyFile() function:

Value Symbolic Constant Explanation
1013 SCPY_ERR The file copy API function does not allow copying a FairCom system file.
1014 DCPY_ERR When using the file copy API option to copy files to a new directory, the source data and index files must all reside in one directory.
1015 CBKTRM_ERR A user-defined callback function terminated the operation.
1016 GFSZ_ERR Error getting file size. Check sysiocod for system error code value.
1017 FDIF_ERR The file comparison detected differences between the two files.


Existing error codes that the ctCopyFile() function can return:

Value Symbolic Constant Explanation
43 FVER_ERR The version of the CPYFIL, CPYPRM, or SRVPRM structure passed to the file copy function is not supported.

 

See Also

 

ctCreateSequence

Declaration

NINT ctCreateSequence(pctSEQATTR pseqattr);

Description

Creates a new sequence with the specified attributes. The following ctSEQATTR structure fields must be initialized:

  • seqnam - The name of the new sequence. No sequence by that name must currently exist.
  • seqini - The initial sequence value. If the sequence enforces a limit, the initial sequence value must be less than the sequence limit for an incrementing sequence or must be greater than the sequence limit for a decrementing sequence.
  • seqcur - The current sequence value. For an incrementing sequence, the current sequence value must be greater than or equal to the initial sequence value, and if the sequence enforces a limit the current sequence value must be less than or equal to the limit value. For a decrementing sequence, the current sequence value must be less than or equal to the initial sequence value, and if the sequence enforces a limit the current sequence value must be greater than or equal to the sequence limit. If sequnk is set to a non-zero value, the seqcur value is ignored, and the current sequence value is set to the unknown value.
  • seqinc - The sequence increment/decrement amount: It must be a positive value that is less than the difference between the initial sequence value and the sequence limit
  • seqlim - The sequence limit: The sequence limit must be greater than the initial sequence value for an incrementing sequence or must be less than the initial sequence value for a decrementing sequence. The sequence limit is only enforced if the sequence type specifies the ctSEQLIM bit.
  • seqtyp - The sequence type: It must be set to one of:
    • ctSEQINC (incrementing sequence)
    • ctSEQDEC (decrementing sequence)
    • ctSEQCYC (cycling sequence)
    • ctSEQTRM (terminating sequence)
  • sequnk - Setting the sequence unknown flag causes the initial sequence value to be set to the unknown value. Otherwise, the current sequence number is set to the initial sequence number.

Return Values

Value Symbolic Constant Explanation
0 NO_ERROR Successfully created the sequence.
900 SEQDUP_ERR A sequence having the specified name already exists.
903 SEQTYP_ERR The specified sequence type contains an invalid combination of sequence type options.
904 SEQINI_ERR The initial value specified for the sequence is out of range.
905 SEQCUR_ERR The current value specified for the sequence is out of range.
906 SEQLIM_ERR The limit value specified for the sequence is out of range.
907 SEQINC_ERR The increment value specified for the sequence is out of range.
901 SEQNAM_ERR An invalid sequence name was specified: the name is NULL, empty, or too long.

See FairCom DB Error Codes for a complete listing of valid error values.

Example

ctSEQATTR seqattr;

NINT rc;

/*

** Create an incrementing sequence that starts with 1, increments by 3, and

** terminates with 100.

*/

strcpy(seqattr.seqnam, "MyFirstSequence");

seqattr.seqini = 1;

seqattr.seqinc = 3;

seqattr.seqlim = 100;

seqattr.seqtyp = ctSEQINC | ctSEQTRM | ctSEQLIM;

 

if ((rc = ctCreateSequence(&seqattr))) {

printf("Error: Failed to create the sequence: %d\n", rc);

} else {

printf("Successfully created the sequence.\n");

}

See also

ctCreateSequence, ctDeleteSequence, ctOpenSequence, ctCloseSequence, ctGetSequenceAttrs, ctSetSequenceAttrs, ctGetCurrentSequenceValue, ctSetCurrentSequenceValue, ctGetNextSequenceValue

 

ctDeferredIndexControl

Declaration

Function prototype:

NINT ctDeferredIndexControl(pDFKCTL pdfkctl);

Description

The ctDeferredIndexControl() function can be used for monitoring and controlling deferred indexing.

The function accepts one parameter, a pointer to a deferred key control structure:

 

typedef struct dfkctl {

    COUNT   version; /* version of this structure */

    COUNT   opcode; /* operation code            */

    LONG    bufsiz; /* buffer size               */

    pTEXT   bufptr; /* output buffer             */

#ifndef ct8P

    LONG    pad;

#endif

} DFKCTL, *pDFKCTL;

 

To call this function set version to DFKCTL_VERS_CUR to use the current structure version from your c-tree header files, or specify a specific structure version such as DFKCTL_VERS_V01 (version 1 of this structure, which is currently the only version supported).

Set opcode to one of the following values:

  • DFKCTLclearstats - Clear deferred indexing statistics
  • DFKCTLgetstats - Get deferred indexing statistics
  • DFKCTLgetstate - Get deferred indexing thread state
  • DFKCTLgetbilstate - Get background index load thread state
  • DFKCTLpausethrds - Pause deferred indexing threads
  • DFKCTLresumethrds - Resume deferred indexing threads

For opcodes DFKCTLgetstats and DFKCTLgetstate, set bufptr to point to a DFKSTT structure (defined below), and set bufsiz to the size of this buffer.

Statistics and thread state variables are returned in a structure of the following format:

 

/* deferred indexing statistics */

#define DFKSTTvern 1 /* DFKSTT (deferred indexing stats) version # */

typedef struct dfkstt {

    ULONG   client_ver;  /* client version of structure          */

    ULONG   server_ver;  /* server version of structure          */

    LONG8   tstamp;      /* Time stamp: seconds since 70         */

    LONG8   opnok;       /* Successful file opens                */

    LONG8   addok;       /* Successful adds                       */

    LONG8   delok;       /* Successful deletes                   */

    LONG8   rwtok;       /* Successful updates                   */

    LONG8   opnerr;      /* Failed file opens                    */

    LONG8   adderr;      /* Failed adds                          */

    LONG8   delerr;      /* Failed deletes                       */

    LONG8   rwterr;      /* Failed updates                       */

    LONG8   addskp;      /* Skipped adds                         */

    LONG8   delskp;      /* Skipped deletes                      */

    LONG8   rwtskp;      /* Skipped updates                      */

    LONG    qcnt;        /* Queue entries                        */

    LONG    lognum;      /* Log number of current scan pos       */

    LONG    logpos;      /* Offset of current scan pos           */

    DFRKOP  curopT;      /* Current operation for tran thread    */

    DFRKOP  curopN;      /* Current operation for non-tran thread*/

} DFKSTT, *pDFKSTT;

 

Return Values

Value Symbolic Constant Explanation
0 CTDBRET_OK Successful operation.

See c-tree Plus Error Codes for a complete listing of valid c-tree Plus error values.

Example

1) Read deferred indexing statistics:

 

    NINT    rc;

    DFKCTL  dfkctl;

 

    memset(&dfkctl,0,sizeof(dfkctl));

    dfkctl.verson = DFKCTL_VERS_V01;

    dfkctl.opcode = DFKCTLgetstats;

    dfkctl.bufsiz = sizeof(dfkstt);

    dfkctl.bufptr = (pTEXT) &dfkstt;

    if ((rc = ctDeferredIndexControl(&dfkctl)) != NO_ERROR) {

        printf("Error: Failed to get deferred indexing statistics: %d\n", rc);

    } else {

        /* display dfkstt structure members */

    }

 

2) Read deferred indexing thread state:

 

    NINT    rc;

    DFKCTL  dfkctl;

 

    memset(&dfkctl,0,sizeof(dfkctl));

    dfkctl.verson = DFKCTL_VERS_V01;

    dfkctl.opcode = DFKCTLgetstate;

    dfkctl.bufsiz = sizeof(dfkstt);

    dfkctl.bufptr = (pTEXT) &dfkstt;

    if ((rc = ctDeferredIndexControl(&dfkctl)) != NO_ERROR) {

        printf("Error: Failed to get deferred indexing statistics: %d\n", rc);

    } else {

        /* display dfkstt structure members */

    }

 

3) Clear deferred indexing statistics:

 

    NINT    rc;

    DFKCTL  dfkctl;

 

    dfkctl.verson = DFKCTL_VERS_V01;

    dfkctl.opcode = DFKCTLclearstats;

    if ((rc = ctDeferredIndexControl(&dfkctl))) {

        printf("Error: Failed to reset deferred indexing statistics: %d\n", rc);

    } else {

        printf("Successfully reset deferred indexing statistics.\n");

    }

 

4) Pause deferred indexing threads.

 

    NINT    rc;

    DFKCTL  dfkctl;

 

    dfkctl.verson = DFKCTL_VERS_V01;

    dfkctl.opcode = DFKCTLpausethrds;

    if ((rc = ctDeferredIndexControl(&dfkctl))) {

        printf("Error: Failed to pause deferred indexing threads: %d\n", rc);

    } else {

        printf("Successfully paused deferred indexing threads.\n");

    }

 

5) Resume deferred indexing threads.

 

    NINT    rc;

    DFKCTL  dfkctl;

 

    dfkctl.verson = DFKCTL_VERS_V01;

    dfkctl.opcode = DFKCTLresumethrds;

    if ((rc = ctDeferredIndexControl(&dfkctl))) {

        printf("Error: Failed to resume deferred indexing threads: %d\n", rc);

    } else {

        printf("Successfully resumed deferred indexing threads.\n");

    }

 

ctDeleteSequence

Declaration

NINT ctDeleteSequence(pTEXT seqnam);

Description

Deletes the sequence having the specified name from the database.

Return Values

Value Symbolic Constant Explanation
0 NO_ERROR Successfully created the sequence.
900 SEQDUP_ERR A sequence having the specified name already exists.
903 SEQTYP_ERR The specified sequence type contains an invalid combination of sequence type options.
904 SEQINI_ERR The initial value specified for the sequence is out of range.
905 SEQCUR_ERR The current value specified for the sequence is out of range.
906 SEQLIM_ERR The limit value specified for the sequence is out of range.
907 SEQINC_ERR The increment value specified for the sequence is out of range.
101 INOT_ERR No sequence exists that has the specified name.

See FairCom DB Error Codes for a complete listing of valid error values.

Example

ctSEQATTR seqattr;

NINT rc;

/*

** Create an incrementing sequence that starts with 1, increments by 3, and

** terminates with 100.

*/

strcpy(seqattr.seqnam, "MyFirstSequence");

seqattr.seqini = 1;

seqattr.seqinc = 3;

seqattr.seqlim = 100;

seqattr.seqtyp = ctSEQINC | ctSEQTRM | ctSEQLIM;

 

if ((rc = ctCreateSequence(&seqattr))) {

printf("Error: Failed to create the sequence: %d\n", rc);

} else {

printf("Successfully created the sequence.\n");

}

See also

ctCreateSequence, ctDeleteSequence, ctOpenSequence, ctCloseSequence, ctGetSequenceAttrs, ctSetSequenceAttrs, ctGetCurrentSequenceValue, ctSetCurrentSequenceValue, ctGetNextSequenceValue

 

ctfcpAddFileCopyOperation

Description:

Adds a file copy operation to the specified file copy handle.

Prototype:

NINT ctfcpAddFileCopyOperation(FCPHND fcphnd,pFCPOPR pfcpopr);

Parameters:

  • fcphnd [IN] - The file copy handle to be freed.
  • pfcpopr [OUT] - Pointer to memory in which the file copy operation handle is returned.

Returns:

  • NO_ERROR - Success.
  • PNUL_ERR - The specified file copy handle or file copy operation handle output pointer is NULL.
  • UALC_ERR - Unable to allocate memory for the file copy operation.

 

See also

 

ctfcpAllocateHandle

Description:

Allocates a file copy handle.

Prototype:

NINT ctfcpAllocateHandle(pFCPHND pfcphnd);

Parameters:

  • pfcphnd [OUT] - Pointer to memory in which the file copy handle is returned.

Returns:

  • NO_ERROR - Success.
  • PNUL_ERR - The output pointer for the file copy handle is NULL.
  • UALC_ERR - Unable to allocate memory for the file copy handle.

 

See also

 

ctfcpCopyFile

Description:

Copy files using the options that are set in the specified file copy handle.

Prototype:

NINT ctfcpCopyFile(FCPHND fcphnd);

Parameters:

  • fcphnd [IN] - The file copy handle.

Returns:

  • NO_ERROR - Success.
  • PNUL_ERR - The specified file copy handle is NULL.
  • PBAD_ERR - Invalid parameter specified. For example, the file copy parameter count is zero or negative.
  • UALC_ERR - Unable to allocate memory for the source and destination filename buffers.
  • Other errors - This function can return any error that the ctCopyFile API function returns.

 

ctfcpFreeHandle

Description:

Frees the specified file copy handle and all resources that it references.

Prototype:

NINT ctfcpFreeHandle(FCPHND fcphnd);

Parameters:

  • fcphnd [IN] - The file copy handle to be freed.

Returns:

  • NO_ERROR Success.
  • PNUL_ERR - The specified file copy handle is NULL.

 

See also

 

ctfcpGetErrorBuffer

Description:

Gets the error buffer for a file copy handle.

Prototype:

pTEXT ctfcpGetErrorBuffer(FCPHND fcphnd,pNINT perrcod);

Parameters:

  • fcphnd [IN] The file copy handle.
  • perrcod - Memory address at which the error code is stored if an error occurs. Can be NULL.

Returns:

  • Non-NULL value - Success
  • NULL value - Either the error buffer is NULL, or an error occurred. If an error occurred, *perrcod holds the error code.

 

See also

 

ctfcpRemoveFileCopyOperation

Description:

Removes a file copy operation from the specified file copy handle.

Prototype:

NINT ctfcpRemoveFileCopyOperation(FCPOPR fcpopr);

Parameters:

  • fcpopr [IN] - The handle of the file copy operation to be removed.

Returns:

  • NO_ERROR - Success.
  • PNUL_ERR - The specified file copy operation handle is NULL.

 

See also

 

ctfcpSetCallback

Description:

Sets a callback function to be called to report progress as files are being copied.

Prototype:

NINT ctfcpSetCallback (FCPHND fcphnd,pCPYFNC pcpyfnc)

Parameters:

  • fcphnd [IN] - The file copy handle.
  • pcpyfnc - The file copy callback function.

Returns:

  • NO_ERROR - Success.
  • PNUL_ERR - The specified file copy handle is NULL.

 

See also

 

ctfcpSetCopyFilenames

Description:

Sets the source and destination filenames for a file copy operation.

Prototype:

NINT ctfcpSetCopyFilenames(FCPOPR fcpopr,NINT totnames,pCTFNAM srcnames,pCTFNAM dstnames);

Parameters:

  • fcpopr [IN] - The file copy operation handle.
  • totnames [IN] - The number of names.
  • srcnames [IN] - Array of pointers to <totnames> source file names.
  • dstnames [IN] - Array of pointers to <totnames> destination file names.

Returns:

  • NO_ERROR - Success.
  • PNUL_ERR - The specified file copy operation handle, source filename pointer, or destination filename pointer is NULL.
  • UALC_ERR - Unable to allocate memory for the source and destination filename buffers.

 

See also

 

ctfcpSetCopyFilePassword

Description:

Sets the password to be used when opening the file that is being copied.

Prototype:

NINT ctfcpSetCopyFilePassword(FCPOPR fcpopr,pTEXT fileword);

Parameters:

  • fcpopr [IN] - The file copy operation handle.
  • fileword [IN] - The file password.

Returns:

  • NO_ERROR - Success.
  • PNUL_ERR - The specified file copy operation handle is NULL.

 

See also

 

ctfcpSetCopyOptions

Description:

Set the file copy options for a file copy operation.

Prototype:

NINT ctDECL ctfcpSetCopyOptions(FCPOPR fcpopr,LONG options);

Parameters:

  • fcpopr [IN] - The file copy operation handle.
  • options [IN] - The file copy options.

Returns:

  • NO_ERROR - Success.
  • PNUL_ERR - The specified file copy operation handle is NULL.

 

See also

 

ctfcpSetErrorBuffer

Description:

Set the error buffer for a file copy handle.

Prototype:

NINT ctfcpSetErrorBuffer(FCPHND fcphnd,pTEXT errbuf,LONG errbufsiz);

Parameters:

  • fcphnd [IN] - The file copy handle.
  • errbuf [IN] - The error buffer.
  • errbufsiz [IN] - The size in bytes of the error buffer.

Returns:

  • NO_ERROR - Success.
  • PNUL_ERR - The specified file copy handle is NULL.
  • NLEN_ERR - The specified error buffer size is negative.

 

See also

 

ctfcpSetServerParameters

Description:

Sets the user name, password, and server name to use if copying files to another server.

Prototype:

NINT ctfcpSetServerParameters(FCPOPR fcpopr,pTEXT userid,pTEXT userword,pTEXT servername);

Parameters:

  • fcpopr [IN] - The file copy operation handle.
  • userid [IN] - The user ID.
  • userword [IN] - The user’s password.
  • servername [IN] - The server name.

Returns:

  • NO_ERROR - Success.
  • PNUL_ERR - The specified file copy operation handle is NULL.

 

See also

 

ctExecJsonAction

ctExecJsonAction() executes the JSON Action request with the user-defined JSON string and returns the JSON string with the JSON Action response. If the provided buffer is not large enough, error VBSZ_ERR is returned, and the required buffer size is populated in the outputSize parameter.

Declaration

NINT ctExecJsonAction(const char *input, char *output, size_t *outputSize);

Description

  • input - specifies the JSON string being sent in the request.
  • output - specifies the JSON string once it has been returned in the response.
  • outputSize - specifies the size of the JSON string that was returned.

For best performance, the caller should avoid providing output buffers that are too small.

Return Values

Value Symbolic Constant Explanation
0 NO_ERROR Successful function.
153 VBSZ_ERR Output buffer too small.

See c-tree Plus Error Codes for a complete listing of valid c-tree Plus error values.

 

ctFILBLK

ctFILBLK() allows a user to block access to a file.

Declaration

The file block routine is declared as follows:

NINT  ctFILBLK(pTEXT filename,LONG action);

Description

ctFILBLK() permits a file to be blocked and unblocked by name.

  • filename is the name of the file to be blocked.
  • action is the ctFILBLK() mode desired for this file.

Note: ctFILBLK does not block access to a file if KEEPOPEN_LIST is in use. Calling CloseCtFileByName will close the file and it will remain closed until unblocked by a subsequent ctFILBLK call.

ADMIN Access

A user must have ADMIN permission to call this function. This routine permits an ADMIN group user to interrupt the file connection between users and the file. The file must also be opened by the blocking caller, and the blocking caller must have write permissions on the file. This allows, for example, an administrator to block access to a data file, open and update the file in exclusive mode, close the file, remove the file while FairCom DB continues operating, replace the file with an alternate data file, and finally unblock the file and re-establish the user file connections.

Note: The FairCom Server configuration keyword COMPATIBILITY NONADMIN_FILBLK removes the ADMIN requirement. A non-ADMIN user can set a file block if:

  1) This keyword is set.
  and
  2) They have the file opened with update permissions.

If either of these conditions is not met, a LADM_ERR (589) error will be returned.

Blocking Files

To block a file, the action parameter is comprised of a number of bit fields OR-ed together. Exactly one from each group below must be selected:

Select this option.

Action Parameter Action Taken
ctFBblock Block the file.

Select ONE of the following two options.

Action Parameter Action Taken
ctFBisam

Block data and associated index files. Can be used if you handle your files ONLY with the ISAM API.

This mode requires the file to contain the IFIL structure because it is used to determine which index files needs to be blocked.

ctFBlowl

Block only the particular file named. Can be used if all clients on the FairCom Server handle the files ONLY with the Low-Level API.

Do not use this parameter if any client on the FairCom Server handles the files with the ISAM API. ISAM access may return FMOD_ERR (48) or LISM_ERR (963).

If you have a Low-Level application blocking the file with ctFBlowl but the file is already open by an ISAM application you will get error 48, so you need to make sure that you are using ONLY the Low-Level API.

Select ONE of the following two options.

Action Parameter Action Taken
ctFBautopen Returns FBLK_ERR (798) while the block is active, and automatically reopens the file when the block is removed. The first access after the block is removed succeeds.*
ctFBappopen

Returns FBLK_ERR (798) while the block is active, and returns FBLK_RDO (799) when the file is available.

The application must issue a close and then reopen the file to continue using the file.

*ctFBautopen - The return when the file is unblocked is as if the file had not been shut down by the server. No information about the client’s file state is maintained upon reopen: no current ISAM position or sequence sets or batches or data filters or file ranges or locks are maintained. Also, if a client has a file open and has updated that file in a transaction and has not yet committed the transaction, then if an administrator blocks that file, that client's transaction is aborted.

 

Note: FairCom does not guarantee preserving the state of a transaction, locks, ISAM context when a file is blocked and then unblocked, even if using the auto open option. Because ISAM context information is lost when the file is blocked, an error 590 may be returned after the file has been blocked and unblocked using ctFBautopen or when using ctfilblkif utility, which uses this mode.

 

Note: If you must delete a data file while it is in a blocked state, the file will need to be opened in exclusive mode before a c-tree delete operation (such as DELRFIL()) will succeed. Even though a data file might be in a blocked state, the process holding the block on the file is allowed to perform an exclusive file open. 

Unblocking Files

If the original blocker quits without unblocking the file(s), then the file(s) will be unblocked by default.

Optionally, additional action parameters can be specified to modify this behavior:

  1. The original blocking user to disconnect (quit) without resulting in the block to be cleared.
  2. A different user to unblock file.
Action Parameter Action Taken
ctFBpersist Block persists after blocker quits.
ctFBdifuser Allow a different user to unblock the file if the original blocker quits.

If the original blocker quits without unblocking the file(s), then the file(s) will not be accessible to any other user until the blocked is cleared.

To unblock the file, call ctFILBLK() using the same file name and action set to ctFBunblock.

Action Parameter Action Taken
ctFBunblock Unblock a file.

In the event a file block occurs when a thread connected to the file is in the middle of a transaction that has updated the file, then the transaction is aborted before the block is placed.

Some general comments on the ctFILBLK() routine:

  • An attempt to block FAIRCOM.FCS or the SYSLOG files results in a SWRT_ERR (458).
  • An FBLK_SUP (802) error is returned on an attempt to block a SUPERFILE member. The entire SUPERFILE must be blocked, not just an individual member.
  • ADMIN may always unblock files, except if that specific ADMIN instance had the file open when it was blocked.
  • Only the original blocker may open the file while it is blocked.

Returns

ctFILBLK() returns the following return codes:

Value Symbolic Constant Explanation
2 KDUP_ERR Duplicate Key Error. The key value already exists in the index.
101 INOT_ERR

Could not satisfy and ISAM search request for index isam_fil. This error frequently indicates "End of File" reached, or "Record not Found."

The following items are the probable causes of the INOT_ERR (101).

  • Passing GetRecord() a duplicate allowed index number (keyno). GetRecord() does not support duplicate allowed indices.
  • Improper target padding. Review “Key Segment Modes” in the c-tree Plus Programmer’s Guide.
  • Not calling TransformKey() on target. Refer to “TransformKey” in the Function Reference Guide
  • Passing ctDeleteSequence() a sequence name that does not exist
  • Improper segment mode. Review “Key Segment Modes” in the c-tree Plus Programmer’s Guide.
  • ctFILBLK() is called and the file is already blocked.
48 FMOD_ERR

Operation incompatible with type of file. The specifics vary by function:

  • The specified keyno is not an index file number.
  • The file is not a data file or it does not contain an IFIL resource (ctFILBLK in ctFBisam mode).
  • One or more associated file (data and index files) is not TRANDEP (using RENIFIL / RENIFILX).
458 SWRT_ERR Write permission not granted.
798 FBLK_ERR File is blocked, retry later.
799 FBLK_RDO File block cleared: close/reopen file to gain access.
800 FBLK_PND Attempting to set file block.
802 FBLK_SUP file block not supported for file type
963 LISM_ERR

An attempt to close an ISAM data file with the low-level file close routine CLSFIL.

COMPATIBILITY CLSFIL_ISAM restores the old behavior when CLSFIL is called for an ISAM data file. For standalone applications the CLSFIL behavior can be restored by compiling the code with NO_ctBEHAV_CLSFIL_ISAM.

Please see Appendix A of the Programmer’s Reference Guide for a complete list of c-tree errors.

Example

The following pseudocode provides an example of using ctFILBLK().


#include <ctreep.h>


NINT rc = 0;

char[255] filename;

strncpy(filename, "mydata.dat", 10);


/* Initialize FairCom DB */

rc = (InitISAMXtd(16, 16, 16, 16, 0, "ADMIN", "ADMIN", "FAIRCOMS"))

if (rc)

    printf("ctree failed to initialize with error %d", rc);


/* block the data file mydata.dat and associated indexes */

/* NOTE: this example uses the ADMIN user, so the caller does not need to

** open the file before calling ctFILBLK. */

rc = ctFILBLK(filename, ctFBblock | ctFBisam | ctFBautopen);

if (rc)

    printf("ctFILBLK failed to block file %s with error %d", filename, rc);


/* Any attempts by other clients to access mydata.dat will fail with FBLK_ERR from here */


/* Swap out the file with a new version */

system("mv mydata.dat mydata.backup");

system("mv newdat.dat mydata.dat");


/* unblock mydata.dat and associated indexes */

rc = ctFILBLK(filename, ctFBunblock);

if (rc)

    printf("ctFILBLK failed to unblock file %s with error %d", filename, rc);


/* mydata.dat and associated indexes are again available */

CloseISAM();


exit(0);

See also

  • QuietCtree

 

ctFILBLKX

Immediately block access to a file upon specified conditions.

Declaration

NINT ctFILBLKX (ctFILE_BLOCK_XTD_OPTIONS *pctFileBlockXtdOptions);

Description

The file block function (ctFILBLK()) immediately blocks a file. New in V13 is file block support that gives pending transactions time to complete before the file is blocked. In order to support this feature, we introduced an extended version of the file block function that supports specifying a transaction timeout in seconds. When a non-zero transaction timeout is specified, the server optionally blocks new transactions and then waits for all active transactions to complete for those connections that have the file to be blocked open, then unblocks new transactions once the startup phase of the file block has been set up.

To set a transaction timeout, set the tranTimeoutSec field of the ctFILE_BLOCK_XTD_OPTIONS structure to a non-zero timeout value in seconds. A tranTimeoutSec value of zero indicates no transaction timeout.

To block new transactions at the start of the file block, OR in the ctFBblockNewTransactions mode bit to the action field of the ctFILE_BLOCK_XTD_OPTIONS structure.

typedef struct ctFileBlockXtdOptions_t {

     UCOUNT structVersion; /* [IN] version of this structure */

     UCOUNT tranTimeoutSec; /* [IN] optional transaction timeout in seconds */

     ULONG action; /* [IN] file block action bits */

     cpTEXT fileName; /* [IN] name of file to block or unblock */

} ctFILE_BLOCK_XTD_OPTIONS;

Tthe ctfilblkif utility was updated with options -t (trantimeoutSec) and -n to block new transactions at the start of the file block. For example, the following command will block new transactions and allow active transactions 3 seconds to complete before blocking the mark.dat file:

ctfilblkif -f mark.dat -n -t 3

Return Values

Value Symbolic Constant Explanation
0 CTDBRET_OK Successful operation.

See c-tree Plus Error Codes for a complete listing of valid c-tree Plus error values.

Example

This example shows blocking a file with a 10 second transaction timeout and blocking new transaction until the file block startup has completed:

 

NINT ret;

 

ctFILE_BLOCK_XTD_OPTIONS fileBlockXtdOptions = { 0 };

 

fileBlockXtdOptions.structVersion = ctFILE_BLOCK_XTD_OPTIONS_VERS_V01;

fileBlockXtdOptions.fileName = "myfile.dat";

fileBlockXtdOptions.action = ctFBblock | ctFBisam | ctFBblockNewTransactions;

fileBlockXtdOptions.tranTimeoutSec = 10;
 

ret = ctFILBLKX(&fileBlockXtdOptions);
 

See Also

ctfilblkif (ctfilblkif - File Block Utility, /doc/ctreeplus/64079.htm) utility

 

ctFILELIST

Manage file-specific cache features.

Short Name

ctFILELIST()

Type

Utility Function

Declaration

NINT ctFILELIST(pTEXT filnam, pLONG pvalue, pLONG pmember, pNINT pscale, 
NINT list, NINT action);

Description

ctFILELIST() manages the advanced file-specific cache capabilities (limited to standalone and bound server applications prior to V11.8) ctFILELIST() must be called prior to the creation or opening of filnam for the cache capabilities to take effect. If multi-byte file names are supported (e.g., Unicode), the configuration information (or direct call to ctFILELIST()) must have the file names in UTF‑8 form (i.e., a NULL terminated string).

pscale was added in V11.8 as an optional scaling factor. NULL sets scale to zero.

When called in client/server mode,

  1. can only be called by a member of the ADMIN group; and,
  2. limited to operate on the ctKEEPOPENlist type, with supported actions "add entry to list" and "remove entry from list". The add option returns error KDUP_ERR if an entry with the same filename already exists. The remove option only succeeds if the specified file name exactly matches a list entry.

ctclosefile (ctclosefile - Close Files on KEEPOPEN List, Close File Utility) utility was updated for easier KEEPOPEN list file references with this functionality.

The state parameter determines which cache capability is invoked, with pvalue and pmember providing supplemental information, as shown in the table below (which assumes the action ctADDfilelist):

state Description
ctSPLCACHElist Assign pvalue bytes of dedicated cache to filnam.
ctPRICACHElist Loads pvalue bytes from the beginning filnam into cache.
ctNO_CACHElist Prevents filnam from using cache.
ctPRIINDEXlist Loads pvalue bytes from the beginning of index member pmember in index file filnam into cache. A negative value for pmember indicates the entire index.
ctNO_FLUSHlist Sets filnam to not flush cache at file close.
ctKEEPOPENlist Upon file creation or physical open, (1) if the file name matches a <file spec> and (2) if the file is a data file and (3) if the data file creation/open is part of an ISAM creation or open, then the KEEPOPEN attribute is attached to the data file and its indexes. Not available with standalone models.
ctREPLICATElist Specifies which file(s) to enable transaction log information for replication. Not available with standalone models.
ctCOMPRESSlist Forces FairCom DB to create data files whose names match the specified name with data compression enabled.

The action parameter can be used to add a file to a list, check or change the values associated with a file on a list, or to remove a file from a list. Changes made to an open file have no effect until the next time the file is opened.

action Description
ctADDfilelist Add a file to the list.
ctSRCfilelist Return current values for file.
ctCHGfilelist Change values for listed file.
ctREMfilelist Remove file from list.

Return

Value Symbolic Constant Explanation
0 NO_ERROR Successful function.
101 INOT_ERR filnam is not a member of the state list.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Example

TEXT      filnam = "custmast.dat";

LONG      bytes = 4000000;

NINT      rcN = 0;

COUNT     rc2 = 0;


/* Set the file to use 4000000 bytes dedicated cache. */

if (rcN = ctFILELIST(&filnam, &bytes, NULL, ctSPLCACHElist,

                     ctADDfilelist))

    errorReturn(rcN, "Error on SPLCACHE assignment");


/* Set the file to load 4000000 bytes to cache at open. */

if (rcN = ctFILELIST(filnam, &bytes, NULL, ctPRICACHElist,

                     ctADDfilelist))

    errorReturn(rcN, "Error on SPLCACHE assignment"));


/* Open the file and load 4000000 bytes to dedicated cache  */

if (rc2 = OpenFileWithResource(-1, &filnam, ctSHARED))

    errorReturn(rc2, "Error opening file.");

Limitations

The ctFILELIST() processing, used to store and retrieve cache parameters, ignores the mirrored portion of a file name. Only the primary file is cached.

History

Declaration prior to V11.8

NINT ctFILELIST(pTEXT filnam, pLONG pvalue, pLONG pmember,

                NINT state, NINT action)

See also

 

ctFILMTX

ctFILMTX() is used to request and release a global file mutex.

Declaration

NINT ctFILMTX(pTEXT filename,NINT opcode)

Description

filename is the name of the file to establish the mutex upon.

opcode controls the access to the mutex and its particular properties. File mutexes may be recursive or non-recursive (the default), persistent (default) or non-persistent, created or deleted. The following file mutex opcode options are supported (found in ctport.h):

Opcode Value Description
ctFILMTXrequest 1 acquire mutex
ctFILMTXrelease 2 release mutex
ctFILMTXrecursive 4 recursive request/release
ctFILMTXcreate 8 create on acquisition if necessary
ctFILMTXdelete 16 delete file on release
ctFILMTXnonpersistent 32 mutex will be released when thread terminates, STPUSR(); but the file will not be deleted

Each call to ctFILMTX() must provide a file name and include either a ctFILMTXrequest or a ctFILMTXrelease option. Other opcode options are OR-ed in with these primary opcode options. If ctFILMTXcreate is included during a request, the file will be created if it does not exist. Without ctFILMTXcreate the request will fail with an error code of FNOP_ERR (12) if the file does not already exist. If the file cannot be created, then the request will return DCRAT_ERR (17). During release, the ctFILMTXdelete option causes the file mutex to be deleted if the mutex is successfully released.

Persistent File Mutexes

By default, a mutex that is acquired is persistent. Persistent means the mutex may exist independent of the thread that acquired the mutex The mutex belongs to the process, not the individual thread. If ctFILMTXnonpersistent is included when the mutex is acquired, then the mutex is assigned to the thread that acquires it, and if the thread does not release the mutex before it calls STPUSR() or CLISAM(), these calls will result in release of the mutex. Only the thread that acquired the non-persistent mutex can release it. If a different thread attempts to release a non-persistent mutex, BOWN_ERR (447) will be returned.

Recursive File Mutexes

ctFILMTXrecursive can be used with both ctFILMTXrequest and ctFILMTXrelease. A recursive mutex can be acquired multiple times by the same process. Each time it is acquired, its recursion count is incremented. Recursive releases each decrement the counter. The release attempt that causes the counter to decrement to zero cause the mutex to be released. If ctFILMTXrelease. is called without including ctFILMTXrecursive then the recursion count is ignored and the mutex is released.

If the same process attempts to acquire a non-recursive mutex that it already owns, then KDUP_ERR (2) will be returned. If a process attempts to acquire a mutex already owned by another process, error NTIM_ERR (156) is returned.

Additional Comments

Because a system lock is acquired on the file, it is generally recommended that a file mutex not contain useful data to be accessed. Instead, we suggest a dummy file. In fact, if the ctFILMTXcreate option causes the file mutex to be created, the file will be empty. The file mutex need not be a c-tree file. c-tree will not read or write to this file, but only acquire a system lock on the file.

The behavior of the file mutex is based on the underlying OS locking protocol. The c-tree logic assumes that if a process locks a local file and another process attempts to lock the same file over a network, the lock will be denied.

Within a single server, use the ctThrdMutex calls to coordinate multiple threads within an application, or use the ctSySQueue() calls to coordinate multiple applications connected to the same server.

 

ctfiltercb_rowl

Provides a callback evaluation function for system-wide filters.

Declaration

The function ctfiltercb_rowl() is located in ctclbk.c and has the following prototype:

NINT ctfiltercb_rowl(pTEXT Clbk, pVOID recptr, pConvMap Schema, VRLEN fixlen, VRLEN datlen, pTEXT username, pTEXT nodename, pVOID oldptr, VRLEN oldlen, LONG opcode pinHan);

Description

Clbk points to a nul terminated ASCII string beginning with two ctCNDXclbkCHR ('@') characters and a third character, '?' or '!', that designates a read or write filter, respectively. The string starting in the 4th position (i.e., Cblk + 3) points to a callback function designator, which is the table name.

recptr points to a record buffer image.

Schema points to a record schema. If you wish to use the record schema, then add the following local variable:

pConvBlk cp = (pConvBlk) (schema + 1);

cp now points to array of individual field descriptors.

fixlen indicates the fixed record length of the record buffer image.

datlen indicates the full length of the record buffer image. datlen may be greater than fixlen for variable length records.

oldptr points to an old record image. oldlen is the length of the old record image pointed by oldptr. Old record images are necessary for deletes so that the system filter can check whether delete permission exists based on user attributes and field values. For rewrites, the case is similar and more interesting: imagine that a user has permission to read a record and to put the contents of the new image in the record, but does not have permission to get rid of one or more of the old field values. Even though the user has permission for the new values that are replacing the old field values, they are not authorized to change the old values. Therefore a rewrite needs both the old and new images.

opcode is one of the following:

opcode Explanation
ctROWL_READ Called from a record read
ctROWL_WRITE Called from a low level record write
ctROWL_ADDREC Called from an ISAM add record
ctROWL_DELREC Called from an ISAM delete record
ctROWL_RWTREC Called from an ISAM rewrite

pinHan is a macro used internally by c-tree Plus code.

On a read, if the permanent read filter does not pass the record, then it behaves just as with the temporary, user-specific read filters: a low-level read would return error FFLT_ERR (739) and an ISAM-level read will skip the record. On a write, a record that does not pass the permanent write filter will cause the write to fail with error SWRT_ERR (458).

Function ctfiltercb_rowl() returns errors as a negative value, 0 if the record does NOT match the filter, or > 0 if the record passes the filter.

Note: To provide extended debug information with this function, define ctDBGcb_rowl when cttseg.c is compiled, and all record images passed to the call back routine will be annotated and hex-dumped into an output file, TestRowl.FCS.

Return

Value Symbolic Constant Explanation
0 NO_ERROR No error occurred.
458 SWRT_ERR Write permission not granted.
739 FFLT_ERR Record does not pass filter.

 See Appendix A for a complete listing of valid c-tree Plus error values.

ctfiltercb_rowl Callback Example

See also

ctfiltercb_init, ctfiltercb_uninit

 

ctfiltercbAddFilter

ctfiltercbAddFilter() initializes resources that are used when processing the filter. The function receives the parameters passed to the filter.

Declaration

NINT ctfiltercbAddFilter(pTEXT libname, pTEXT funcname, pTEXT params,

     pVOID libhandle, ppVOID pflthandle);

Description

  • libname - the filter callback DLL name that was passed to SetDataFilter().
  • funcname - the filter callback function name that was passed to SetDataFilter().
  • params - the function parameter string that was passed to SetDataFilter().
  • libhandle - the application-defined library handle that was set by ctfiltercbLoadLib().
  • pflthandle - a pointer to an application-defined filter handle. ctfiltercbAddFilter() can allocate memory for use by the filter callback function and can return its address in this parameter.

For example, if the parameter string is:

@#mycallback.dll#mycallback_function#my_params

then libname is “mycallback.dll”, funcname is “mycallback_function”, and params is “my_params”.

You can use c-tree API functions to open other c-tree files on that FairCom Server and you can read and write the files. All operations are done in the context of the database connection in which you called the record read operation that called the filter function.

Return Values

Value Symbolic Constant Explanation
0 CTDBRET_OK Successful operation.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Example


/* 

Example Code

*/

 

See also

EvaluateFilter, LoadFilter, ctfiltercbRemoveFilter, UnloadFilter, SetDataFilter

 

ctfiltercbRemoveFilter

Called when a data record filter is removed. This function cleans up resources that are used by that filter.

Declaration

NINT ctfiltercbRemoveFilter(pTEXT libname, pTEXT funcname, pTEXT params,

     pVOID libhandle, pVOID flthandle);

  • libname - the filter callback DLL name that was passed to SetDataFilter().
  • funcname - the filter callback function name that was passed to SetDataFilter().
  • params - the function parameter string that was passed to SetDataFilter().
  • libhandle - the application-defined library handle that was set by LoadFilter().
  • flthandle - the application-defined filter handle that was set by ctfiltercbAddFilter().

FairCom DB maintains a list of the names of the callback DLLs it has loaded. A DLL remains loaded until FairCom DB shuts down.

Description

LoadFilter() can allocate memory for use by the filter callback function and can return its address in this parameter.

Return Values

 

Example


/* 

Example Code

*/

See also

ctfiltercbAddFilter, EvaluateFilter, LoadFilter, UnloadFilter, SetDataFilter

 

ctGetAccountExpirationTime

Return remaining time until specified user account and/or user account password expires. ADMIN group members can call this function for any user account. A non-ADMIN-group member can only call this function for their own user account.

Declaration

NINT ctGetAccountExpirationTime(pTEXT userid,pctEXPTM pactexp,pctEXPTM pupwexp);

Description

  • userid [IN] - The user account whose expiration date is to be returned.
  • pactexp [OUT] - If not NULL, on success the user account expiration time is returned here.
  • pupwexp [OUT] - If not NULL, on success the user password expiration time is returned here.

ctEXPTM structure expstt field values:

#define EXPTM_NONE 0    /* account has no expiration date */

#define EXPTM_EXPIRED 1 /* account has expiration date that has passed */

#define EXPTM_FUTURE 2  /* account has future expiration date */

User account expiration time information:

typedef struct ctexptm {

 LONG expdays;     /* days until account expires */

 UTEXT exphours;   /* hours until account expires */

 UTEXT expminutes; /* minutes until account expires */

 UTEXT expseconds; /* seconds until account expires */

 UTEXT expstt;     /* expiration date status */

} ctEXPTM, *pctEXPTM;

Example
 

ctEXPTM actexp,upwexp;

NINT rc;

 

if ((rc = ctGetAccountExpirationTime("myaccount",&actexp,&upwexp))) {

 printf("Error: Failed to get account expiration time: %d\n", rc);

} else {

 printf(" Account expiration time: ");

 if (actexp.expstt == EXPTM_NONE) {

  printf("None\n");

 } else if (actexp.expstt == EXPTM_EXPIRED) {

  printf("Expired\n");

 } else {

  printf("Will expire in %3d day(s), %2d hour(s), %2d minute(s), %2d second(s)\n",

   actexp.expdays,actexp.exphours,actexp.expminutes,actexp.expseconds);

 }

 

 printf("Password expiration time: ");

 if (upwexp.expstt == EXPTM_NONE) {

  printf("None\n");

 } else if (upwexp.expstt == EXPTM_EXPIRED) {

  printf("Expired\n");

 } else {

  printf("Will expire in %3d day(s), %2d hour(s), %2d minute(s), %2d second(s)\n",

   upwexp.expdays,upwexp.exphours,upwexp.expminutes,upwexp.expseconds);

 } 

}

Return

If the specified user account does not exist, this function returns error 101.

 

ctGetConnectionInfo

Returns information for multiple connections in a single call.

Declaration

NINT ctGetConnectionInfo(NINT versn,pctCONINF pconninfo,pNINT pnconnections);

Description

When retrieving connection information for many connected c-tree clients, FairCom DB Monitor could take a very long time to return. The bulk of this time was spent in client-by-client connection returns. To reduce this expensive network traffic, a new function was added to obtain all connection information in a single API call. This function is available for all client applications.

FairCom Server now supports a function that returns information for multiple connections in a single call. Prior to the availability of this function, a function call from the client to the Server was required for obtaining information about each connection of interest. This new approach greatly reduces network traffic.

Note: The caller must be a member of the ADMIN group; otherwise the function returns error LADM_ERR (589).

Version 1 structure:

 

/* Output data format for ctGetConnectionInfo() function: */

typedef struct ctconinf {

 COUNT utaskid;     /* internal task id           */

 COUNT uactflg;     /* active request indicator   */

 LONG umemsum;      /* user memory                */

 LONG ulogtim;      /* logon time                 */

 LONG ucurtim;      /* current time               */

 LONG urqstim;      /* time of last request       */

 LONG utrntim;      /* time of last TRANBEG       */

 LONG unbrfil;      /* number of open files       */

 LONG urqstfn;      /* last request function #    */

 ULONG sipaddr;     /* client IP address          */

 ULONG sip6addr[4]; /* client IPv6 address        */

 TEXT unodnam[32];  /* node ID information        */

 TEXT uname[32];    /* user id string             */

 TEXT ucominfo[32]; /* communication info         */

 TEXT urqst[32];    /* last request function name */

 } ctCONINF, ctMEM *pctCONINF;

 

Return Values

Value Symbolic Constant Explanation
0 CTDBRET_OK Successful operation.

See c-tree Plus Error Codes for a complete listing of valid c-tree Plus error values.

Example


 NINT rc,nconnect;

 ctCONINF conninfo[32];

 

 nconnect = 32;

 if ((rc = ctGetConnectionInfo(ctCONINF_VERS_V01,conninfo,&nconnect))) {

  printf("Error: %d\n", rc);

 } else {

  printf("Current number of connections: %d\n", nconnect);

 }


 

ctGetCurrentSequenceValue

Declaration

NINT ctGetCurrentSequenceValue(LONG seqhnd, pLONG8 pcurval, pNINT punkval);

Description

Reads the current value for the specified sequence. The current value of a sequence can be one of the following:

  • The initial value specified when the sequence was created.
  • The last value set with the ctSetCurrentSequenceValue(), ctGetNextSequenceValue(), or ctSetSequenceAttrs() functions.
  • The unknown value if the sequence has exceeded its minimum or maximum and is not cycling.

Sequence values are stored in the database in which they are defined, and persist between each call to the ctSetCurrentSequenceValue() or ctGetNextSequenceValue() function.

Return Values

Value Symbolic Constant Explanation
0 NO_ERROR Successfully created the sequence.
900 SEQDUP_ERR A sequence having the specified name already exists.
903 SEQTYP_ERR The specified sequence type contains an invalid combination of sequence type options.
904 SEQINI_ERR The initial value specified for the sequence is out of range.
905 SEQCUR_ERR The current value specified for the sequence is out of range.
906 SEQLIM_ERR The limit value specified for the sequence is out of range.
907 SEQINC_ERR The increment value specified for the sequence is out of range.
901 SEQNAM_ERR An invalid sequence name was specified: the name is NULL, empty, or too long.

See FairCom DB Error Codes for a complete listing of valid error values.

Example

ctSEQATTR seqattr;

NINT rc;

/*

** Create an incrementing sequence that starts with 1, increments by 3, and

** terminates with 100.

*/

strcpy(seqattr.seqnam, "MyFirstSequence");

seqattr.seqini = 1;

seqattr.seqinc = 3;

seqattr.seqlim = 100;

seqattr.seqtyp = ctSEQINC | ctSEQTRM | ctSEQLIM;

 

if ((rc = ctCreateSequence(&seqattr))) {

printf("Error: Failed to create the sequence: %d\n", rc);

} else {

printf("Successfully created the sequence.\n");

}

See also

ctCreateSequence, ctDeleteSequence, ctOpenSequence, ctCloseSequence, ctGetSequenceAttrs, ctSetSequenceAttrs, ctGetCurrentSequenceValue, ctSetCurrentSequenceValue, ctGetNextSequenceValue

 

ctGetFailOverState

Returns current value of the background failover flag variable.

Declaration

TEXT ctGetFailOverState();

Description

ctSetCommProtocolOption() (ctSetCommProtocolOption, ctSetCommProtocolOption) enables a background thread that can toggle a background global state variable. This is useful in failover scenarios as a cluster monitor can send a "back channel" message direct to the client. However, this state variable could be used for any type of external client signaling.

See Also

ctSetClientLibraryOption (ctSetClientLibraryOption, ctSetClientLibraryOption)() ctResetFailOverState() (ctResetFailOverState, ctResetFailOverState)

Return

Zero (0) or one (1).

 

ctGetFileLocks

Declaration

NINT ctGetFileLocks(pTEXT FileName, NINT options, pctLOKINF pFileLockInfo, pLONG pNbrLocks);

Description

Returns information about all locks currently held on the specified file.

typedef struct ctwatinfo {

        NINT        loktyp;        /* lock type              */

        NINT        taskid;        /* connection number      */

        TEXT        usrnam[32];    /* user name              */

} ctWATINF, ctMEM * pctWATINF;

 

typedef struct ctlokinfo {

        LONG8       recbyt;        /* offset of lock in file */

        NINT        loktyp;        /* lock type              */

        NINT        taskid;        /* connection number      */

        NINT        waitcnt;       /* number of waiters      */

        TEXT        usrnam[32];    /* user name              */

} ctLOKINF, ctMEM * pctLOKINF;

FileName holds the name of the file whose list of locks is to be returned.

pFileLockInfo points to an array of ctLOKINF record lock information structures allocated by the caller. On input, pNbrLocks points to the size of this array. A successful call to ctGetFileLocks() sets pNbrLocks to point to the number of ctLOKINF entries that were written to the pFileLockInfo array.

Specify a value of ctLOKINFgetwaitlist for the options parameter to cause ctGetFileLocks() to return a list of lock waiters in addition to the ctLOKINF lock information for each record lock. When this option is specified, ctWATINF structures follow each ctLOKINF structure for which there are connections waiting to acquire the lock. The number of ctWATINF structures is indicated by the ctLOKINF structure's waitcnt field value. See the note below for details about the alignment of the ctWATINF and ctWATINF structures.

If you do not want to receive a list of lock waiters for each record lock, specify a value of 0 for the options parameter.

If the specified array size is too small to hold the list of all locks held on the specified file, *pNbrLocks is set to the number of array entries required, and ctGetFileLocks() returns error VBSZ_ERR (153, buffer too small).

Note: When using the ctLOKINFgetwaitlist option, the lock wait lists are written to the pFileLockInfo buffer following the list of ctLOKINF structures. If the buffer is not large enough to hold all the ctLOKINF lock information structures and ctWATINF wait list structures, ctGetFileLocks() returns error VBSZ_ERR and sets *pNbrLocks to the number of ctLOKINF structures that are needed to hold the total number of ctLOKINF and ctWATINF structures to be returned.

Note: The user name is stored in the pFileLockInfo buffer as a null-terminated string and is not padded to the full length of the usrnam field. This is true for both the ctLOKINF and ctWATINF usrnam fields. Each user name is followed by padding bytes if necessary to ensure that the next ctWATINF structure in the buffer is aligned on a four-byte boundary and that the next ctLOKINF structure in the buffer is aligned on an eight-byte boundary.

Only a user who is a member of the ADMIN group can call this function. If a user who is not a member of the ADMIN group calls this function, it returns error LADM_ERR (589, member of ADMIN group required).

Dumping large quantities of locks in a very active system could affect performance.

Return Values

Symbolic Constant   Explanation
NO_ERROR 0 No error
VBSZ_ERR 153 Buffer too small
LADM_ERR 589 Member of ADMIN group required

See FairCom DB Error Codes for a complete listing of valid error values.

Example

For code that demonstrates how to call these functions, see the functions ictadmnListOpenFiles(), ictadmnListFileUsers(), and ictadmnListFileLocks() in the c-tree source file ctree\source\ctadmn.c.

See also

ctGetOpenFiles, ctGetFileLocks

 

ctGetFileUsers

Declaration

NINT ctGetFileUsers(pTEXT FileName, pctUSRINF pFileUserInfo, pLONG pNbrUsers);

Description

Get information about all users currently held on the specified file.

typedef struct ctusrinfo {

        NINT        taskid;        /* connection number */

        NINT        ufilno;        /* user file number  */

        TEXT        usrnam[32];    /* user name         */

} ctUSRINF, ctMEM * pctUSRINF;

FileName holds the name of the file whose list of users is to be returned.

pFileUserInfo points to an array of ctUSRINF user information structures allocated by the caller. On input, pNbrUsers points to the size of this array. A successful call to ctGetFileUsers() sets pNbrUsers to point to the number of ctUSRINF entries that were written to the pFileUserInfo array.

If the specified array size is too small to hold the list of all users who have the file open, *pNbrUsers is set to the number of array entries required, and ctGetFileUsers() returns error VBSZ_ERR (153, buffer too small).

Note: The user name is stored in the pFileUserInfo buffer as a null-terminated string and is not padded to the full length of the usrnam field. Each user name is followed by padding bytes if necessary to ensure that the next ctUSRINF structure in the buffer is aligned on a four-byte boundary. For example code showing how to find the address of the next ctUSRINF structure in the output buffer, see the function ictadmnListFileUsers() in ctadmn.c.

Only a user who is a member of the ADMIN group can call this function. If a user who is not a member of the ADMIN group calls this function, it returns error LADM_ERR (589, member of ADMIN group required).

Dumping large quantities of locks in a very active system could affect performance.

Return Values

Symbolic Constant   Explanation
NO_ERROR 0 No error
VBSZ_ERR 153 Buffer too small
LADM_ERR 589 Member of ADMIN group required

See FairCom DB Error Codes for a complete listing of valid error values.

See also

ctGetOpenFiles, ctGetFileLocks

 

ctGETHGH

Retrieve the high-order 4 bytes of an 8-byte value.

Short Name

ctGETHGH()

Type

Low-Level function

Declaration

  LONG ctGETHGH()

Description

Call ctGETHGH() after a routine that returns or sets an output parameter to a record address or other 8-byte address to get the high-word portion of the address.

To minimize the effect on performance in client/Server environments, ctGETHGH() does not make a separate call to the FairCom Server. Instead, the information needed by ctGETHGH() is cached on the client side.

Return

ctGETHGH() returns the high word portion of the address.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Example

/* Assumes a key length of 14 (8 bytes for HUGE duplicate support), */


LONG      recadr_hw,recadr_lw;

TEXT      keybuf[14];


/* return lower order 4 bytes of record address              */

recadr_lw = FirstKey(

                 9, /* index file number                     */

            keybuf  /* output key buffer                     */

            );


/* return higher order 4 bytes of record address             */

recadr_hw = ctGETHGH();

Limitations

ctGETHGH() clears the internal high-word variable when used. In most cases, this is not an issue, but if used for debug purposes, follow-up with ctSETHGH() to reset the value if it is required by a following function.

The recbyt parameter in this function is a 4-byte value capable of addressing at most 4 gigabytes. If your application supports HUGE files (greater than 4 gigabytes), you must use the ctSETHGH() and ctGETHGH() functions to set or get the high-order 4 bytes of the file offset. See also Record Offsets Under Huge File Support.

See also

ctSETHGH

 

ctGetIsamErrorCode

Declaration

COUNT ctGetIsamErrorCode()

Description

Returns the last ISAM API operation return code. This is the equivalent of the isam_err global variable.

Return Values

Value Symbolic Constant Explanation
0 CTDBRET_OK Successful operation.

See c-tree Plus Error Codes for a complete listing of valid c-tree Plus error values.

Example

NINT rc = 0


rc = CreateIFile(&my_ifil);

if ( rc ) 

printf("Error %d in creating file. Check I/O code %d\n", ctGetIsamErrorCode(), ctGetSystemErrorCode() );
 

See Also

  • ctGetUserErrorCode()
  • ctGetIsamFileNbr()
  • ctGetSystemErrorCode()

 

ctGetIsamFileNbr

Declaration

COUNT ctGetIsamFileNbr()

Description

Returns the current ISAM file number involved in the last ISAM error condition. This is the equivalent of the isam_fil global variable.

Return Values

Returns a file number.

Example

NINT rc = 0


rc = CreateIFile(&my_ifil);

if ( rc ) 

printf("Error %d in creating file. File number: %d, rc, ctGetIsamFileNbr() );
 

See Also

  • ctGetUserErrorCode()
  • ctGetIsamErrorCode()
  • ctGetSystemErrorCode()

 

ctGetNextSequenceValue

Declaration

NINT ctGetNextSequenceValue(LONG seqhnd, pLONG8 pnxtval, pNINT punkval);

Description

Reads the next value for the specified sequence. The next value of a sequence can be one of the following:

  • The next value, which is computed from the current sequence value and the attributes of the sequence set in ctCreateSeqence() or ctSetSequenceAttrs().
  • The unknown value if the sequence has exceeded its minimum or maximum and is not cycling (see "Reaching the End of a Terminating Sequence" below).

Sequence values are stored in the database in which they are defined, and persist between each call to the ctSetCurrentSequenceValue() or ctGetNextSequenceValue() function.

The value of a sequence set by the ctGetNextSequenceValue() function persists in the database until the next call to ctSetCurrentSequenceValue() or ctGetNextSequenceValue() for the sequence, or until the sequence is deleted from the database.


Reaching the End of a Terminating Sequence

If the sequence is a terminating sequence, and ctGetNextSequenceValue() attempts to increment the sequence beyond its upper limit (for positive increments) or decrement the sequence beyond its lower limit (for negative increments), the function returns the unknown value and leaves the current sequence value unchanged.

Once a sequence terminates, ctGetNextSequenceValue() continues to return the unknown value for the specified sequence until it is reset to a new value with the ctSetCurrentSequenceValue() function, or its definition is changed to a cycling sequence by the ctSetSequenceAttrs() function.

After changing the sequence definition to cycle, the first use of ctGetNextSequenceValue() for the sequence sets and returns its initial value.

Return Values

Value Symbolic Constant Value Explanation
0 NO_ERROR 0 Successfully created the sequence.
900 SEQDUP_ERR 900 A sequence having the specified name already exists.
903 SEQTYP_ERR 903 The specified sequence type contains an invalid combination of sequence type options.
904 SEQINI_ERR 904 The initial value specified for the sequence is out of range.
905 SEQCUR_ERR 905 The current value specified for the sequence is out of range.
906 SEQLIM_ERR 906 The limit value specified for the sequence is out of range.
907 SEQINC_ERR 907 The increment value specified for the sequence is out of range.
901 SEQNAM_ERR 901 Invalid sequence name specified (NULL, empty, or too long).
902 SEQHND_ERR 902 Invalid sequence handle.

See FairCom DB Error Codes for a complete listing of valid error values.

Example

ctSEQATTR seqattr;

NINT rc;

/*

** Create an incrementing sequence that starts with 1, increments by 3, and

** terminates with 100.

*/

strcpy(seqattr.seqnam, "MyFirstSequence");

seqattr.seqini = 1;

seqattr.seqinc = 3;

seqattr.seqlim = 100;

seqattr.seqtyp = ctSEQINC | ctSEQTRM | ctSEQLIM;

 

if ((rc = ctCreateSequence(&seqattr))) {

printf("Error: Failed to create the sequence: %d\n", rc);

} else {

printf("Successfully created the sequence.\n");

}

See also

ctCreateSequence, ctDeleteSequence, ctOpenSequence, ctCloseSequence, ctGetSequenceAttrs, ctSetSequenceAttrs, ctGetCurrentSequenceValue, ctSetCurrentSequenceValue, ctGetNextSequenceValue

 

ctGetNullBit

Read the state of the specified bit in the specified bit array.

Declaration

ctCONV TEXT ctGetNullBit(const UTEXT* pArray, NINT BitNumber);

Description

  • pArray [IN] - the bit array to read
  • BitNumber [IN] - zero-based bit number to read

Returns

Return YES if bit is set or NO if bit is cleared. Reads the null key value for the specified index into the supplied buffer..

See Also

ctSetNullBit

 

ctGetNullKeyValue

Reads the null key value for the specified index into the supplied buffer..

Declaration

NINT ctGetNullKeyValue(FILNO keyno, pTEXT nullkey, pULONG pkeylen);

Description

  • keyno - the index file number.
  • nullkey - the buffer where the null key value is returned.
  • pkeylen -On input, holds the size of the output buffer in bytes. On output, is set to the size of the null key value in bytes.

See Also

ctSetNullKeyValue()

 

ctGetOpenFiles

Declaration

NINT ctGetOpenFiles(COUNT ConnectionNumber, pctFILINF pFileInfo, pLONG pNbrFiles);

Description

Returns the names of all open FairCom DB files or all files open by a specified connection.

typedef struct ctfilinfo {

        FILNO        filno;          /* system file number             */

        FILNO        status;         /* user count or user file number */

        TEXT         filtyp;         /* file type                      */

        TEXT         suptyp;         /* superfile type                 */

        TEXT         filnam[255];    /* file name                      */

} ctFILINF, ctMEM * pctFILINF;

To retrieve the names of all files open by the FairCom Server, set ConnectionNumber to -1. To retrieve the names of all files open by a specified connection, set ConnectionNumber to the task ID for the connection as shown in the ctadmn utility's list of active connections, which is returned by the USERLIST() and USERINFO() functions.

Set pFileInfo to point to a block of memory allocated by the caller.

Set pNbrFiles to point to the number of ctFILINF structures that can fit into the pFileInfo buffer.

A successful call to ctGetOpenFiles() sets pNbrFiles to point to the number of ctFILINF structures that were written to the pFileInfo buffer.

When retrieving the FairCom Server's list of open files, the ctFILINF structure's status field is set to the user count for the file. When retrieving a particular connection's list of open files, the status field is set to that user's user file number for the file.

Note that the user file number can contain the following special negative values if the file has been blocked by the FairCom DB file block operation:

  • -1 File is blocked by c-tree file close
  • -3 File is blocked by a ctFBsysclose file block
  • -4 File is blocked by a ctFBsysclose file block established by that connection
  • -5 File is suspended by a ctFBsysclose file block

If the specified buffer size is too small to hold the names of all open files, *pNbrFiles is set to the number of ctFILINF structures required to hold all the names of all open files, and ctGetOpenFiles() returns error VBSZ_ERR (153, buffer too small).

A successful call to ctGetOpenFiles() fills the memory block with an array of ctFILINF structures.

Note: The file name is stored in the pFileInfo buffer as a null-terminated string and is not padded to the full length of the filnam field. A filename is followed by a padding byte if necessary to ensure that the next ctFILINF structure in the buffer is aligned on a two-byte boundary.

Only a user who is a member of the ADMIN group can call this function. If a user who is not a member of the ADMIN group calls this function, it returns error LADM_ERR (589, member of ADMIN group required).

Return Values

Symbolic Constant   Explanation
NO_ERROR 0 No error
VBSZ_ERR 153 Buffer too small
LADM_ERR 589 Member of ADMIN group required

See FairCom DB Error Codes for a complete listing of valid error values.

Example

For example code showing how to find the address of a subsequent ctFILINF structure in the output buffer, see the function ictadmnListOpenFiles() in ctadmn.c.

See also

ctGetOpenFilesXtd, ctGetFileUsers, ctGetFileLocks

 

ctGetOpenFilesXtd

Declaration

NINT ctGetOpenFilesXtd(FILNO ConnectionNumber, pctFILINF pFileInfo, pLONG pNbrFiles);

Description

V12 and later: Returns the names of all open FairCom DB files or all files open by a specified connection. This function is similar to ctGetOpenFiles except that it has been extended to handle greater than 32,767 files. The information is returned in this structure (which is slightly different from the structure returned by ctGetOpenFiles):

typedef struct ctfilinfox {

        FILNO        filno;          /* system file number             */

        LONG         status;         /* user count or user file number */

        TEXT         filtyp;         /* file type                      */

        TEXT         suptyp;         /* superfile type                 */

        TEXT         filnam[255];    /* file name                      */

} ctFILINFX, ctMEM * pctFILINFX;

In V12 and later, FairCom DB supports opening more than 32,767 files. A particular database connection is still limited to a maximum of 32,767 files because we preserved the original definition of data and index file numbers as two-byte signed values, using the COUNT data type. However, internally we introduced new data types that support billions of files. Note that a compile-time limit is set to a maximum of 1,000,000 files.

Tip: If opening many files, consider the possibility of using multiple c-tree database engines to host the files, rather than having one c-tree database engine hosting all the files, since the files will compete for resources such as data and index cache, file system cache, operating system kernel memory, and transaction logs.

Return Values

Symbolic Constant   Explanation
NO_ERROR 0 No error
VBSZ_ERR 153 Buffer too small
LADM_ERR 589 Member of ADMIN group required

See c-tree Plus Error Codes for a complete listing of valid c-tree Plus error values.

Example

For example code showing how to find the address of a subsequent ctFILINF structure in the output buffer, see the function ictadmnListOpenFiles() in ctadmn.c.

See Also

 

ctGetSequenceAttrs

Declaration

NINT ctGetSequenceAttrs(LONG seqhnd, pctSEQATTR pseqattr);

Description

Retrieves the attributes for the specified sequence. seqhnd specifies the sequence handle. pseqattr points to a ctSEQATTR structure that receives the sequence attribute values.

Return Values

Value Symbolic Constant Explanation
0 NO_ERROR Successfully created the sequence.
900 SEQDUP_ERR A sequence having the specified name already exists.
903 SEQTYP_ERR The specified sequence type contains an invalid combination of sequence type options.
904 SEQINI_ERR The initial value specified for the sequence is out of range.
905 SEQCUR_ERR The current value specified for the sequence is out of range.
906 SEQLIM_ERR The limit value specified for the sequence is out of range.
907 SEQINC_ERR The increment value specified for the sequence is out of range.
901 SEQNAM_ERR An invalid sequence name was specified: the name is NULL, empty, or too long.

See FairCom DB Error Codes for a complete listing of valid error values.

Example

ctSEQATTR seqattr;

NINT rc;

/*

** Create an incrementing sequence that starts with 1, increments by 3, and

** terminates with 100.

*/

strcpy(seqattr.seqnam, "MyFirstSequence");

seqattr.seqini = 1;

seqattr.seqinc = 3;

seqattr.seqlim = 100;

seqattr.seqtyp = ctSEQINC | ctSEQTRM | ctSEQLIM;

 

if ((rc = ctCreateSequence(&seqattr))) {

printf("Error: Failed to create the sequence: %d\n", rc);

} else {

printf("Successfully created the sequence.\n");

}

See also

ctCreateSequence, ctDeleteSequence, ctOpenSequence, ctCloseSequence, ctGetSequenceAttrs, ctSetSequenceAttrs, ctGetCurrentSequenceValue, ctSetCurrentSequenceValue, ctGetNextSequenceValue

 

ctGetSystemErrorCode

Declaration

COUNT ctGetSystemErrorCode()

Description

Returns the current system I/O code. Call this function instead of directly accessing the sysiocod global c-tree variable. This value is particularly important with API calls that access filesystem I/O and errors specific to operating systems can be returned.

Return Values

The return value is an operating specific error code. Consult your OS documentation for specific values and meanings.

Example


NINT rc = 0


rc = CreateIFile(&my_ifil);

if ( rc ) 

printf("Error %d in creating file. Check I/O code %d\n", rc, ctGetSystemErrorCode() );
 

See Also

  • ctGetUserErrorCode()
  • ctGetIsamErrorCode()
  • ctGetIsamFileNbr()

 

ctGetUserErrorCode

Declaration

COUNT ctGetUserErrorCode()

Description

Returns the last API operation return code. This is the equivalent of the uerr_cod global variable.

Return Values

Value Symbolic Constant Explanation
0 CTDBRET_OK Successful operation.

See c-tree Plus Error Codes for a complete listing of valid c-tree Plus error values.

Example


NINT rc = 0


rc = CreateIFile(&my_ifil);

if ( rc ) 

printf("Error %d in creating file. Check I/O code %d\n", rc, ctGetSystemErrorCode() );
 

See Also

  • ctGetIsamErrorCode()
  • ctGetIsamFileNbr()
  • ctGetSystemErrorCode()

 

ctImpersonateTask

Used to cause a connection to impersonate another connection.

Declaration

NINT ctImpersonateTask(NINT mode, NINT taskid);

Type

ISAM function called from SQL

Description

The Thread Impersonate feature allows a connection to “impersonate” another existing connection. This is most useful for FairCom DB SQL connections that might wish to do some lower-level ISAM type of activity, such as quickly looking up a record in an uncommitted SQL transaction. The target connection must allow the ability to be impersonated.

Note: This function is not supported by the FairCom Server by default. It requires a custom build of the server available by special request.

mode is one of the following:

  • ctIMPallow - Allow the specified connection or all connections (if taskid is ctIMPall) to impersonate this connection.
  • ctIMPdisallow - Do not allow this connection to be impersonated (which is the default setting for a connection). taskid is ignored.
  • ctIMPbegin - Begin impersonation of the connection whose task ID is taskid.
  • ctIMPend - End impersonation of the connection that is currently being impersonated. taskid is ignored.

FairCom DB SQL supports a stored procedure used to easily enable impersonation of its current connection. The procedure is:

fc_set_impersonation(taskid)

Specify a taskid of zero to disable impersonation of the connection (the default). Specify a taskid of 1 to enable impersonation of the connection by any other connection. Specify a taskid greater than 1 to enable impersonation of the connection only by a connection having that specific task ID.

The ctSNAPSHOT (SnapShot, SnapShot) user snapshot report (opcode = ctPSSuser) will return the taskid for the current connection in the ctgums.slOWNR structure member. You can use other options to get the user snapshot output for other users. To get the taskid of the current user at the SQL level, call the fc_get_taskid() stored procedure.

Note: This feature is intended for calling ISAM related functions from within either another ISAM connection, or from a higher-level SQL connection. It is not a trivial task to call SQL-related features from a lower-level connection, and this usage is not recommended.

Return Values

Symbolic Constant Value Explanation
NO_ERROR 0 Successfully created the sequence
NSUP_ERR 454 Service not supported.
IMPD_ERR 863 The request to impersonate the specified connection was denied because the target connection does not allow impersonation
IMPU_ERR 864 The request to impersonate the specified connection was denied because the target connection does not allow impersonation by the specified connection.
IMPA_ERR 865 The request to impersonate the specified connection was denied because the target connection is already being impersonated.
IMPB_ERR 866 The request to impersonate the specified connection was denied because the target connection is executing a database operation or is blocked.

See FairCom DB Error Codes for a complete listing of valid error values.

Example

REGCTREE("inst1");

if ((rc = INTISAMX(6, /* index buffers */

10, /* files */

4, /* page sectors */

6, /* data file buffers */

usrprf, /* UserProfile*/

uid, /* user id */

upw, /* user password */

svn))) { /* server name */

ctrt_printf("Error: Failed to connect to c-tree Server %s instance #1: %d\n", svn, rc);

goto err_ret;

}

<< get taskid1 >>
 

REGCTREE("inst2");

if ((rc = INTISAMX(6, /* index buffers */

500, /* files */

4, /* page sectors */

6, /* data file buffers */

usrprf, /* UserProfile*/

uid, /* user id */

upw, /* user password */

svn))) { /* server name */

ctrt_printf("Error: Failed to connect to c-tree Server %s instance #2: %d\n", svn, rc);

goto err_ret;

}


<< get taskid2 >>

 

SWTCTREE("inst1");
if ((rc = ctImpersonateTask(ctIMPallow, taskid2))) {

printf("Error: Failed to enable impersonation: %d\n", rc);

goto err_ret;

}

printf("Successfully enabled impersonation.\n");


<< open file and add record >>


SWTCTREE("inst2");
if ((rc = ctImpersonateTask(ctIMPbegin, taskid1))) {

printf("Error: Failed to begin impersonation: %d\n", rc);

goto err_ret;

}

printf("Successfully impersonated first connection.\n");


<< open file and read record from taskid1 >>


if ((rc = ctImpersonateTask(ctIMPend, 0))) {

qa_printf("Error: Failed to stop impersonation: %d\n", rc);

}

 

ctLOKDYN

Alters user-wide default locking mechanisms.

Declaration

NINT ctLOKDYN( LONG action )

Description

Calls to ctLOKDYN() can alter the user-wide lock state where action is one of:

  • ctLOKDYNoptions - return ctLOKDYN state
  • ctLOKDYNdemote - turn off nodemote
  • ctLOKDYNfree - turn off nofree
  • ctLOKDYNnotranPersist - turn off tranPersist
  • ctLOKDYNnolockDefer - turn off lockDefer
  • ctLOKDYNnodemote - requesting a read lock on a write locked record that has not been modified preserves the write lock rather than demoting the write lock to a read lock
  • ctLOKDYNnofree - deny an attempt to free a lock acquired before the last savepoint (if any) — free returns NO_ERROR and sysiocod is set to SAVP_COD.
  • ctLOKDYNtranPersist - deny unlocking a record in a transaction controlled file when the caller has an active transaction even if the record has not been updated —the unlock call returns NO_ERROR and sysiocod is set to UDLK_TRN
  • ctLOKDYNlockDefer - defer the close of a transaction controlled file when the caller has an active transaction if the caller holds any locks on the file

Inside of a transaction, an unlock request on a record behaves differently depending on whether or not the record has been updated. If it has not been updated the unlock request succeeds. If it has been updated, the unlock returns a NO_ERROR, but the lock remains and the sysiocod is set to UDLK_TRN (-3).

The ctLOKDYNtranPersist mode will enable a user-wide state such that the lock persists, even if the record has not been updated. The ctLOKDYNnotranPersist will disable this state. The PUTHDR() ctTRNPERShdr mode toggles the file state. The tranPersist state (whether user-wide or file specific) only affects behavior at the time an unlock request is made. Whether it is on or off at the time the lock is granted does not affect unlock behavior.

The ctLOKDYNlockDefer mode will defer the close of a file, for the user-wide state, if there are locks pending on the file, whether or not any records are updated. ctLOKDYNnolockDefer turns off this state. The PUTHDR() ctLOCKDFRhdr mode is the equivalent file state call.

The user-wide and/or file-specific routines need only be called once. The states persist until the user logs off or the file is closed, respectively. However, they can be turned on and off as the application desires.

Return Values

Value Symbolic Constant Explanation

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

 

ctLOKTIMOUT

Sets a timeout period for a blocking lock.

Declaration

NINT ctLOKTIMOUT(FILNO datno, LONG mode, LONG timeoutSEC)

Description

In V12 the file number typedef was formally changed from COUNT, a two-byte value to FILNO, a four-byte value. Refer to this link for compatibility details. Four Byte File Numbering

ctLOKTIMOUT() specifies a type of blocking lock. These blocking locks can return a timeout error to indicate a lock request timed out. This is useful to avoid exceptionally long held locks in a system.

Timeouts, measured in seconds, can be specified for blocking lock requests made on data files. There are various ways the timeout can be specified, and in all of them, a zero timeout indicates NO timeout, not a zero timeout. If a lock request fails because of a time out, error code UTIM_OUT (827) is returned.

  • datno specifies a data file.
  • mode allows various options to be specified.
  • timeoutSEC specifies the duration of the timeout in seconds.

The long name of the function is SetBlockingLockTimeout(). If datno is -1, then the call is interpreted to apply to all data files. A zero timeoutSEC means to turn off the timeout. There are two options for mode:

Symbolic Constant Description
ctLTOdiagnostic Specifies that a message is to be sent to CTSTATUS.FCS each time a lock times out.
ctLTOallusers Specifies that the timeout applies to all users, not just the calling user; only a member of the ADMIN group can use the ctLTOallusers mode, otherwise error LADM_ERR (589) is returned.

FairCom Server Configuration

A FairCom Server configuration keyword has been defined to set a value for the blocking lock timeout on server startup. Specify the following in your ctsrvr.cfg file:

BLOCKING_LOCK_TIMEOUT_SEC <timeoutSEC>

This configuration entry is equivalent to a member of the ADMIN group making the call ctLOKTIMOUT(-1, ctLTOallusers | ctLTOdiagnostic, timeoutSEC).

Note: The effect of the configuration entry can be turned off by a call of the form ctLOKTIMOUT(-1, ctLTOallusers, 0).

If a user calls ctLOKTIMOUT() with a datno equal to -1 in order to set a timeout value on all data files for the user, the user can selectively change or turn off the timeout by making additional calls to ctLOKTIMOUT() specifying the data file number.

Lock Statistics

Locking statistics have an inconsistency when a lock request is removed from a list of waiting lock requests. When a lock request times out with this new feature, it is removed from the wait list. For instance, if a thread is waiting for a lock and it is killed by ctadmn, the lock is removed from the waiting list, however, the lock statistics do not reflect this. In fact, the count of currently blocked locks will be off (too high) by one for each lock request removed from a wait list. A new lock statistic has been added to account explicitly for lock requests that have been removed from the wait list: “killed.” It is treated in the same manner as the deadlock category.

Return Values

Value Symbolic Constant Explanation
589 LADM_ERR Member of ADMIN group required.
827 UTIM_OUT A blocking lock request timed out from a ctLOKTIMOUT() call.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Here are some ways the API can be used to specify a timeout value.

Examples


LONG my_fileno;

LONG block_timeout = 10;
 

/* A data file for the calling user  */

ctLOKTIMOUT(my_fileno, 0, block_timeout)


/* All data files for the calling user  */

ctLOKTIMOUT(-1, 0, block_timeout)


/* A data file, all users  */

ctLOKTIMOUT(my_fileno, ctLTOallusers, block_timeout)


/* All data files, all users  */

ctLOKTIMOUT(-1, ctLTOallusers, block_timeout)


In any of the above calls, ctLTOdiagnostic could be OR-ed into the mode parameter.

 

ctMBprefix

Stores a proper prefix to a Unicode filename string.

Short Name

ctMBprefix()

Type

Utility

Declaration

NINT ctMBprefix(pTEXT dp, NINT FnType)

Description

FairCom DB requires that the Unicode file name have a special 8-byte prefix that informs FairCom DB about special file name encoding. ctMBprefix() stores a proper prefix at dp of type FnType.

dp is a pTEXT because the name may be encoded as a byte stream or a wide character array and ctMBprefix() does not assume that dp is aligned when used with UTF16.

FnType may be ctFnTypeUTF8 or ctFnTypeUTF16. Both of these constants are defined in ctport.h. ctFnPrefixSIZE holds the size of the prefix in bytes.

Return

Value Symbolic Constant Explanation
0 NO_ERROR Prefix stored.
446 BMOD_ERR FnType parameter is bad.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Example

/* In the following example, getUnicodeUTF8string is assumed to be a routine 

   which will fill-in a UTF8 encoded string up to a max length.

   GetUnicodeUTF16string performs in the same manner except that it works with

   16-bit wide characters.

*/


FILNO     datno8, datno16;

WCHAR     utf16name[256];

TEXT      utf8name[512];


ctMBprefix(utf8name,ctFnTypeUTF8);

getUnicodeUTF8string(utf8name + ctFnPrefixSIZE,512 - ctFnPrefixSIZE);

datno8 = OPNRFIL(-1,utf8name,SHARED);


ctMBprefix((pTEXT) utf16name,ctFnTypeUTF16);

getUnicodeUTF16string(utf16name + ctFnPrefixSIZE / 2,

                      256 - ctFnPrefixSIZE / 2);

datno16 = OPNRFIL(-1,utf16name,SHARED);

 

ctNotify

Send notification messages to a queue.

Short Name

ctNotify()

Type

ISAM function.

Declaration

NINT  ctNotify(NINT opcode, NINT objhandle, NINT qhandle, NINT contents,

               NINT controls)

Description

Using the facilities of c-tree system queues, client applications can direct FairCom Server to monitor the use of a resource such as a data file and place notification messages on a queue. To use the notification process the user must open a queue using ctSysQueueOpen(), use ctNotify() to write the notification, ctSysQueueRead() to read the notification messages and ctSysQueueClose() to close the notification queue.

Parameters

The ctNotify opcode parameter specifies which actions on the resource should be notified. The following values are supported:

Values Explanation Level
ctNT_ADDREC Notify that a new record was added to the data file ISAM
ctNT_DELREC Notify that a record was deleted ISAM
ctNT_RWTREC Notify that a record was modified ISAM
ctNT_CLSOBJ Notify that an object was closed  
ctNT_ISMUPD Notify on any change (add, delete or rewrite) to data file. This is identical to ctNT_ADDREC | ctNT_DELREC | ctNT_RWTREC ISAM
ctNT_TOUCH Notify that the file was updated, only once per transaction. This opcode cannot be used in combination with others and the contents parameter must be 0. No details of the update are conveyed, only a “ping” that the file has been touched. ISAM and low-level
ctNT_PARTIAL Notify that a notification request was started in the middle of a transaction and not all the updates generated a notification. One of the first four opcodes in this table must also be specified when using this option. ISAM
ctNT_ISMUPP

defined as:

#define ctNT_ISMUPD (ctNT_ADDREC | ctNT_DELREC | ctNT_RWTREC)

 

The ctNotify objhandle parameter is the file number (datno) of an ISAM data file and qhandle is a server-side (system) queue handle returned by a call to ctSysQueueOpen().

The contents parameter determines what optional details are returned in the variable-length region of the notification message and may be set to the following values or any combination (by OR-ing) of them:

Values Explanation
ctNT_CON_UNQKEY Unique key
ctNT_CON_NODNAM Node name of actor
ctNT_CON_RECBUF Record buffer on add or update (not on delete)

To receive different notification contents for different actions, multiple calls to ctNotify() are required. For example, to get unique key values on a record delete notification, and full record images on either an add or rewrite notification, two ctNotify() calls are required: one call with a contents field of ctNT_CON_RECBUF to set up the add and rewrite notification, and one call with a contents field of ctNT_CON_UNQKEY for the delete.

The controls parameter is reserved for future use and must be set to zero.

ctNotify returns NO_ERROR (0) on success.

For example, to monitor ISAM updates to a data file, a call of the form below will cause each ISAM update to the data file specified by datno to generate an entry in the queue specified by qhandle.

ctNotify(ctNT_ISMUPD,datno,qhandle,0,0);

Return

Value Symbolic Constant Explanation
0 NO_ERROR Successful close of the queue.
10 SPAC_ERR INTREE() parameters require too much space.
48 FMOD_ERR Operation incompatible with type of file.
90 NQUE_ERR Could not create queue.
446 BMOD_ERR Bad mode: parameter out of range.
458 SWRT_ERR Write permission not granted.
514 CQUE_ERR Queue has already been closed.
754 QOWN_ERR Only queue creator can perform operation.
755 SQUE_ERR A system queue is required.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Example

NINT eRet;

NINT qhandle = ctSysQueueOpen("myqueue", 0);


if (qhandle < 0)

    printf("ctSysQueueOpen failed with code %d\n", -qhandle);

else

{

    eRet = ctNotify(ctNT_ADDREC, datno, qhandle, 0, 0);

    if (eRet)

        printf("ctNotify failed with code %d\n", eRet);

}

Limitations

Client/Server mode only.

See also

ctSysQueueOpen, ctSysQueueClose, ctSysQueueRead, Enabling Notification for Actions on a File

 

ctOpenSequence

Declaration

NINT ctOpenSequence(pTEXT seqnam, pLONG pseqhnd);

Description

Opens the sequence having the specified name, seqnam. pseqhnd is a pointer to memory where the sequence handle is set if the sequence is successfully opened.

Return Values

Value Symbolic Constant Explanation
0 NO_ERROR Successfully created the sequence.
900 SEQDUP_ERR A sequence having the specified name already exists.
903 SEQTYP_ERR The specified sequence type contains an invalid combination of sequence type options.
904 SEQINI_ERR The initial value specified for the sequence is out of range.
905 SEQCUR_ERR The current value specified for the sequence is out of range.
906 SEQLIM_ERR The limit value specified for the sequence is out of range.
907 SEQINC_ERR The increment value specified for the sequence is out of range.
901 SEQNAM_ERR No sequence exists that has the specified name.

See FairCom DB Error Codes for a complete listing of valid error values.

Example

ctSEQATTR seqattr;

NINT rc;

/*

** Create an incrementing sequence that starts with 1, increments by 3, and

** terminates with 100.

*/

strcpy(seqattr.seqnam, "MyFirstSequence");

seqattr.seqini = 1;

seqattr.seqinc = 3;

seqattr.seqlim = 100;

seqattr.seqtyp = ctSEQINC | ctSEQTRM | ctSEQLIM;

 

if ((rc = ctCreateSequence(&seqattr))) {

printf("Error: Failed to create the sequence: %d\n", rc);

} else {

printf("Successfully created the sequence.\n");

}

See also

ctCreateSequence, ctDeleteSequence, ctOpenSequence, ctCloseSequence, ctGetSequenceAttrs, ctSetSequenceAttrs, ctGetCurrentSequenceValue, ctSetCurrentSequenceValue, ctGetNextSequenceValue

 

ctparsedoda

Parses a DODA object into a record schema and field name list.

Declaration

COUNT ctparsedoda(pDATOBJ doda, UCOUNT numfld, ppTEXT ppschema, ppTEXT ppnames)

Description

One of the most useful features of the FairCom DB expression parser is its ability to associate symbolic names in expressions with data in a buffer in memory. To use this ability, you must define a record schema, known as a DODA (Data Object Definition Array). A DODA is an array of field specifications, each of which contains a field name, field offset, field type, and a field length. By providing the expression parser with a DODA, you may include references to DODA field names in your expressions. See the sample code shown later in this section for an example of a DODA definition.

While a DODA is conveniently defined in your application using an array of DATOBJ structures, cndxparse() does not take a DODA in DATOBJ form, but instead accepts a record schema and a list of the field names from the DODA. To simplify converting your DODA into the required record schema and field name list, FairCom has written a utility function, ctparsedoda(). This function can be found in the sample file ctexpr.c.

Return Values

Value Symbolic Constant Explanation
0 CTDBRET_OK Successful operation.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Example

#include "ctcndx.h"  /* For PTREE type */
 

/* Define a DODA structure. */
DATOBJ doda[] = {

  {"CustomerNumber", 0,  CT_INT4U},

  {"ZipCode",        4,  CT_FSTRING,  9},

  {"State",         13,  CT_FSTRING,  2},

  {"LastName",      15,  CT_STRING,  37},

  {"FirstName",     52,  CT_STRING,  37},

  {"Address",       89,  CT_STRING,  49},

  {"City",         138,  CT_STRING,  37}

};


COUNT retval;  /* Return code.        */

pTEXT schema;  /* Record schema.      */

pTEXT names;   /* Field name list.    */
 

/* Parse the DODA into a record schema and field name list. */

if ((retval = ctparsedoda(doda, 7, &schema, &names)) != 0)

    printf("Error %d parsing DODA.\n", retval);

See also

cndxeval, cndxparse, cndxfree, ctparsedoda, getcndxmem, mbfree

 

ctPlugin

Starts or stops a plug-in dynamically.

Declaration

NINT ctPlugin(ctPLUGIN_COMMAND command, pTEXT inputBuffer, pTEXT outputBuffer, pVRLEN pOutputBufferSize);

Description

  • command: currently, the options are ctPLUGIN_START or ctPLUGIN_STOP (defined by the ctPLUGIN_COMMAND enum type)
  • inputBuffer is flexible; currently, it expects only the plug-in name (loaded in the server by the PLUGIN keyword in ctsrvr.cfg)
  • outputBuffer: Starting and stopping plug-ins doesn’t have any output, so this is unused. Pass a pointer to a TEXT string.
  • pOutputBufferSize: Starting and stopping plug-ins doesn't have any output, so this is unused. Pass a pointer to a VRLEN number set to the length of the string passed to outputBuffer.

Return

Value Symbolic Constant Explanation
0 NO_ERROR No error occurred.
1167 INV_CMD_ERR Invalid plug-in command.

See c-tree Plus Error Codes for a complete listing of valid c-tree Plus error values.

Example


ctPlugin(ctPLUGIN_STOP, " cthttpd ",outBuff,&outBuffLen);
 

See Also

SetSystemConfigurationOption (SetSystemConfigurationOption, SetSystemConfigurationOption)

 

ctPlugin_describe

Defines a set of additional user callback functions contained in a server side shared library.

Declaration

int ctDECL ctPlugin_describe(char * name,size_t * size,int request) 

Description

  • CALLBACK_NUMBER - On return, "size" is set to the number of additional functions.
  • CALLBACK_TOTAL_LENGTH - On return, "size" is set to the sum of all additional function name lengths.
  • Function ordinal (from 0) - On input, "size" will hold the number of bytes in buffer "name". On return, "name" should hold the null-terminated string name of the corresponding additional function. "size" is set to the number of bytes copied to "name".

ctPlugin_describe() is called at startup and must handle several values of "request": ctPlugin_describe() defines a set of additional user callback functions contained in a server side shared library that should be loaded at server startup. It is intended for use in implementing server side PlugIns. These additional functions are not called directly, but can be invoked by existing callback functionality such as Record Update Callbacks.

Return

Return value should be zero on success or non-zero on error.

See Also

 

ctPlugin_init

Declaration

int ctDECL ctPlugin_init(void)

Description

If provided, ctPlugin_init(void) is called after ctPlugin_describe() has been used to successfully load all additional function addresses from <DLL>, and before any calls into this callback. This is intended to initialize any global state information within <DLL>, and should return zero on success, non-zero if an error occurs. An error return will prevent additional functions within <DLL> from being used as callbacks. This function should return promptly to prevent delaying database startup. Because this is executed before the database initialization is complete, c-tree API calls may have undefined behavior.

See Also

 

ctPlugin_term

Declaration

ctPlugin_term(void) 

Description

If provided, ctPlugin_term(void) is called at server shutdown before <DLL> is unloaded from the process. This is intended to cleanup any global state information within <DLL> and should return zero on success, non-zero on error. This function should return promptly to prevent delaying database shutdown. Because this is executed while database shutdown is in progress, c-tree API calls may have undefined behavior.

See Also

 

ctRecordUpdateCallbackControl

Declaration

ctRecordUpdateCallbackControl() is used to add and delete callback function definitions. Its prototype is as follows:

NINT  ctDECL ctRecordUpdateCallbackControl(pRUCBCTL prucbctl);

Description

A file can have one or more callback function definitions. Each callback function definition is identified by its name, which is a case-sensitive ASCII string. The callback functions are called in the order in which they were added.

These callbacks execute within the server process space. Programming errors will affect the entire database server process.

The synchronous callback types ( RUCBonrecupd, RUCBontrancmt ) occur in the context of the calling user. Most c-tree APIs cannot be safely called from these callbacks, as they may alter existing internal user state information. For advanced usage, information could be sent to another thread to make c-tree file calls if desired. ctThrd* APIs are useful in this regard to pass information to another thread.

The asynchronous callback types ( RUCBqueuethrd, RUCBqueueapp ) are more flexible, since they don't share the same state as the original operation. It should be safe to directly call c-tree file APIs, however, ensure you don't operate on the same file that is generating the callback.

More generally, within the server each thread has an implicit top level "connection" context that is single threaded, which we call OWNER. If you want to do something like have a pool of worker threads, you'll need to manage this using ctSetOWNER (faircom.com) or ctdbGetCtreeOWNER()/ctdbSetCtreeOWNER(). Only a single thread should be within a c-tree API call with a particular OWNER at the same time.

The RUCBCTL structure has the following definition:

 

typedef struct rucbctl {

    COUNT   version;    /* version of this structure */

    COUNT   opcode;    /* operation code  */

    LONG    bufsiz;    /* buffer size   */

    pVOID   bufptr;    /* input/output buffer  */

#ifndef ct8P

    LONG    pad;

#endif

} RUCBCTL, *pRUCBCTL;

 

The RUCBACB structure, used when adding a callback definition, has the following definition:

 

/* Input buffer format for RUCBCTLaddcallback opcode. */

typedef struct rucbacb {

    COUNT   version;    /* Version of this structure       */

    FILNO   datno;     /* Data file number        */

    LONG    calltm;    /* Time of function call       */

    LONG    nfncnames; /* Number of function names       */

    LONG    pad;       /* Padding to ensure 8-byte alignment of next field */

    pTEXT   datnam;    /* Data file name        */

    pTEXT   cbname;    /* Unique name to identify this callback     */

    pTEXT   dllname;   /* Name of callback DLL        */

    pTEXT   params;    /* Optional parameters        */

    ppTEXT  fncnames;  /* Callback function names       */

#ifndef ct8P

 LONG pad2[5];

#endif

} RUCBACB, *pRUCBACB;

 

The calltm member defines "when" a callback is executed. There are currently four possible values:

  • RUCBonrecupd - Synchronous call during record update.
  • RUCBontrancmt - Synchronous call during transaction commit.
  • RUCBqueuethrd - Asynchronous queue update to a background thread that will call the callback after the transaction commits.
  • RUCBqueueapp - Asynchronous queue update to the transaction log or memory queue. The application is responsible for reading the log/queue.

 

The RUCBDCB structure, used when deleting a callback definition, has the following definition:

 

/* Input buffer format for RUCBCTLdelcallback opcode. */

typedef struct rucbdcb {

    COUNT   version;    /* Version of this structure                    */

    FILNO   datno;     /* Data file number                             */

    LONG    pad;       /* Padding for 8-byte pointer alignment         */

    pTEXT   datnam;    /* Data file name                               */

    pTEXT   cbname;    /* Unique name to identify this callback        */

#ifndef ct8P

    LONG    pad2[2];

#endif

} RUCBDCB, *pRUCBDCB;

 

Option to Update All Existing Records

The default when adding a callback is to not call it for existing records. An option can be specified to choose a new behavior of calling the callback for all existing records. This option, RUCBcallexist, is specified by OR'ing it into the calltm field of the RUCBACB structure when calling ctRecordUpdateCallbackControl().

Additional Callback for pre-RUC Updates

 

V13 and later supports an additional callback that is called at the start of record add and update operations and allows the callback to update the record image. By comparison, the record update callbacks that existed prior to this revision are called later in the add and update routines and do not support the callback changing the record image.

To use this feature, when calling ctRecordUpdateCallbackControl() to add a record update callback function, set the calltm field of the RUCBACB structure to RUCBprerecupd.

Recall that the prototype for the user-defined record update callback function is as follows:

NINT rucbRecordUpdateCallbackFunction(pRUCBF prucbf, pRUCBO prucbo, pRUCBSTT prucbstt); 

Additional fields were added to the RUCBSTT structure. When the structure version (indicated by the verson field value) is RUCBSTT_VERSION_V02, the RUCBSTT structure includes fields that hold the record length, record image pointer, and function pointers to the server's memory allocation and free functions:

 

/* State information to pass to record update callback function: */ 

typedef struct rucbstt_t { 

LONG verson; /* structure version */ 

VRLEN reclen; /* record length in bytes */ 

LONG8 tranno; /* transaction number for the operation */ 

pTEXT recbuf; /* buffer containing record image */ 

rucbAllocFunction_t allocfn; /* memory allocation function */ 

rucbFreeFunction_t freefn; /* memory free function */ 

} RUCBSTT, *pRUCBSTT; 

To update the record image in your user-defined record update callback function, if you are increasing the record length, use the memory allocation function to reallocate the record buffer and set prucbstt->recbuf to the new buffer and prucbstt->reclen to the new record length. If you are not increasing the record length, you can modify the record image in the existing record buffer.

Note that for a fixed length data file or a ctAugmentedFxd variable length data file, the record update callback function is not allowed to change the record length. Attempting to do so causes the add or update operation to fail with error DSIZ_ERR (443).

Also, record update callbacks now receive the partition host file name and file number. The record update callback functions were receiving the file name and file number of the partition member. We have changed the behavior so that the host name and file number are passed if available. In our testing, we found that the host info might not be available when closing a partition member because the host might already be closed.

Return Values

Value Symbolic Constant Explanation
0 CTDBRET_OK Successful operation.

See c-tree Plus Error Codes for a complete listing of valid c-tree Plus error values.

Example

Follow these steps to use ctRecordUpdateCallbackControl() to add a callback function:

  1. Declare RUCBCTL and RUCBACB structures and a list of callback names:

RUCBCTL rucbctl;

RUCBACB rucbacb;

pTEXT   myCallbackFunctionNames[NbrRUCBFnc] = {

    "rucbOpenFileCallback",

    "rucbCloseFileCallback",

    "rucbRecordUpdateCallback"

};

NINT    rc;
 

  1. Initialize the RUCBCTL structure to indicate that this is an add callback operation:

memset(&rucbctl,0,sizeof(rucbctl));

rucbctl.verson = RUCBCTL_VERS_V01;

rucbctl.opcode = RUCBCTLaddcallback;

rucbctl.bufsiz = sizeof(rucbacb);

rucbctl.bufptr = &rucbacb;
 

  1. Initialize the RUCBACB structure with your callback settings:

memset(&rucbacb,0,sizeof(rucbacb));

rucbacb.verson = RUCBACB_VERS_V01;

rucbacb.opcode = RUCBCTLaddcallback;

/* datno of -1 instructs ctRecordUpdateCallbackControl() to open the file;

** otherwise it is the file number of an already-open data file. */

rucbacb.datno = -1;

rucbacb.datnam = "mydatafile.dat";

rucbacb.dllname = "ctuser.dll";

rucbacb.params = "my parameters";

rucbacb.fncnames = myCallbackFunctionNames;

rucbacb.nfncnames = NbrRUCBFnc;

rucbacb.cbname = "My First Callback";

/* This record update callback will be called on record update. */

rucbacb.calltm = RUCBonrecupd;
 

  1. Call ctRecordUpdateCallbackControl() and check the result:

if ((rc = ctRecordUpdateCallbackControl(&rucbctl)) != NO_ERROR)

    printf("Error: Failed to add record update callback function '%s': %d (%d)\n",

        rucbacb.cbname,rc,sysiocod);

else

    printf("Successfully added record update callback function '%s'.\n",

        rucbacb.cbname);
 

To use ctRecordUpdateCallbackControl() to delete a callback function:

  1. Declare RUCBCTL and istructures:

RUCBCTL rucbctl;

RUCBDCB rucbdcb;

NINT    rc;
 

  1. Initialize the RUCBCTL structure to indicate that this is a delete callback operation:

memset(&rucbctl,0,sizeof(rucbctl));

rucbctl.verson = RUCBCTL_VERS_V01;

rucbctl.opcode = RUCBCTLdelcallback;

rucbctl.bufsiz = sizeof(rucbdcb);

rucbctl.bufptr = &rucbdcb;
 

  1. Initialize the RUCBDCB structure with your callback settings:

memset(&rucbdcb,0,sizeof(rucbdcb));

rucbdcb.verson = RUCBDCB_VERS_V01;

/* datno of -1 instructs ctRecordUpdateCallbackControl() to open the file;

** otherwise it is the file number of an already-open data file. */

rucbdcb.datno = -1;

rucbdcb.datnam = "mydatafile.dat";

rucbdcb.cbname = "My First Callback";
 

  1. Call ctRecordUpdateCallbackControl() and check the result:

if ((rc = ctRecordUpdateCallbackControl(&rucbctl)) != NO_ERROR)

    printf("Error: Failed to delete record update callback function '%s': %d (%d)\n",

        rucbdcb.cbname,rc,sysiocod);

else

    printf("Successfully deleted record update callback function '%s'.\n",

        rucbdcb.cbname);

 

CtreeAsynchronous

Deals with asynchronous threads launched by an application.

Short Name

CTASYNC()

Type

Utility

Declaration

LONG CtreeAsynchronous(LONG handle, NINT mode, VRLEN bufsiz, pTEXT bufptr)

Description

CtreeAsynchronous() deals with asynchronous threads (including flush threads) launched by an application. CtreeAsynchronous() can be used to determine the status of an asynchronous thread or to cancel the thread.

  • handle is the handle value returned by a function that launches an asynchronous thread (e.g., CTFLUSHX()).
  • mode is ctASYNC_STATUS or ctASYNC_CANCEL.

The bufsiz and bufptr parameters are ignored now. They are intended for future use if it is desirable to return information stored by an asynchronous thread.

At this point, only the thread that launched the asynchronous thread can call CtreeAsynchronous().

Return

Value Symbolic Constant Description
0 ctASYNC_completed Thread completed successfully.
1 ctASYNC_cancelled Thread canceled.
2 ctASYNC_notfound handle not found.
3 ctASYNC_badmode mode is bad.
4 ctASYNC_running Thread is running.
negative negative value Negative of c-tree error code that terminated the thread.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

 

CtreeCheckPoint

Force a system checkpoint to the transaction logs.

Short Name

CTCHKPNT()

Type

Low-Level function

Declaration

  COUNT CtreeCheckPoint() 

Description

CtreeCheckPoint() forces the system to issue a checkpoint.

Note: CtreeCheckPoint() should be used sparingly to avoid an impact on system performance.

Return

Value Symbolic Constant Explanation
0 NO_ERROR No error occurred.
454 NSUP_ERR Transaction processing not supported.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

 

CtreeFlushFile

Force FairCom DB and system file buffers to disk.

Short Name

CTFLUSH()

Type

Low-Level function

Declaration

COUNT CtreeFlushFile(FILNO filno) 

Description

In V12 the file number typedef was formally changed from COUNT, a two-byte value to FILNO, a four-byte value. Refer to this link for compatibility details. Four Byte File Numbering

CtreeFlushFile() writes cache to disk. If filno is -1, the buffers for all open files are flushed. Otherwise, the buffers for the file number specified are flushed. CtreeFlushFile() attempts to flush the system’s file buffers after the FairCom DB buffers are flushed.

CtreeFlushFile() does not guarantee that the data on disk is consistent because other users could be updating the file at the time of the flush. Cache pages that are in the middle of an update, signified by an inability of CtreeFlushFile() to acquire the update semaphore for the cache, are not flushed. The contents of the cache remain valid so subsequent I/O requests do NOT need to repopulate the cache pages.

Superfiles must be flushed as a unit. Individual members cannot be flushed separately. To flush a member of a superfile, you must flush the superfile host, which flushes ALL members. A call to CtreeFlushFile() for a member of a superfile returns FMOD_ERR (48).

A call to CtreeFlushFile() for an index member, instead of the host index, returns KMEM_ERR (23). That is, if an index file is opened with file number keyno, and if the index file contains two additional members, CtreeFlushFile() should only be called with keyno as the argument. This will flush all the index members.

Return

Value Symbolic Constant Explanation
0 NO_ERROR No error occurred.
23 KMEM_ERR Attempt to flush an index member. Flush the host index.
48 FMOD_ERR Attempt to flush a superfile member. Flush the host.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Limitations

Superfiles and index host/member files must be flushed as a unit. Individual members cannot be flushed separately. Flush the host file to flush all hosted files.

 

CtreeFlushFileXtd

Flush cache for specific files and groups of files.

Short Name

CTFLUSHX()

Type

Low-Level function

Declaration

LONG CtreeFlushFileXtd(FILNO filno, NINT mode, LONG parm)

Description

In V12 the file number typedef was formally changed from COUNT, a two-byte value to FILNO, a four-byte value. Refer to this link for compatibility details. Four Byte File Numbering

CtreeFlushFileXtd() extends CtreeFlushFile() with mode and parm values to allow applications to flush cache for specific files and groups of files. Calling CtreeFlushFileXtd() with mode and parm set to zero is identical to calling CtreeFlushFile(filno).

The following mode options may be appropriately mixed and matched:

Mode Description
ctFLUSHX_ASYNC Launch flush and return immediately
ctFLUSHX_ISAM Treat filno as an ISAM data file and flush data and associated indexes (only when filno != -1)
ctFLUSHX_TRAN Only flush TRNLOG and PREIMG files (filno == -1)
ctFLUSHX_NONTRAN Only flush non-transaction files (filno == -1)
ctFLUSHX_SYSALL Flush all files opened by system (filno == -1)
ctFLUSHX_USRALL Flush all files opened by calling user (filno == -1)
ctFLUSHX_BYTES Limit flush to specified number of bytes (parm holds the limit on the number of bytes to flush)
ctFLUSHX_PERCENT Limit flush to specified percent of bytes (parm holds a percentage between 1 and 100)
ctFLUSHX_LAST This option only applies to asynchronous flushes that do not attempt to flush all system files (ctFLUSHX_SYSALL which is the default when filno is passed in as a -1). When used, the asynchronous flush will only flush the file if the caller is the last (i.e., only) client to have the file open. This permits the client to terminate without concern that a file close will take an inordinate amount of time due to the close flushing all the file’s buffers.
ctFLUSHX_NOSAVE Suppress the file system flush to improve throughput. The c-tree buffer and cache pages will still be written to the file system, but the file system buffers will not be flushed to disk.

Not all combinations of these modes make sense. CtreeFlushFileXtd() eliminates conflicting modes before attempting the flush. For example, supplying a valid filno and then specifying ctFLUSHX_TRAN, ctFLUSHX_NONTRAN, ctFLUSHX_SYSALL, and/or ctFLUSHX_USRALL is inconsistent. In this case the filno is used and the conflicting mode option is ignored.

Return

CtreeFlushFileXtd() returns the handle, a positive LONG value, associated with a successfully launched asynchronous thread (if mode contains ctFLUSHX_ASYNC), NO_ERROR if CtreeFlushFileXtd() completes successfully (no thread launched), or a negative error code in the case of a problem.

Limitations

The only option available with stand-alone applications is ctFLUSHX_ISAM.

See also

CtreeFlushFile

 

ctResetFailOverState

Resets the current value of the background client failover flag variable.

Declaration

VOID ctDECL ctResetFailOverState()

Description

ctResetFailOverStatus() always sets the value of the internal failover flag to zero (0).

Return

VOID

See Also

ctSetClientLibraryOption (ctSetClientLibraryOption, ctSetClientLibraryOption)() ctGetFailOverState() (ctGetFailOverState, ctGetFailOverState)

 

ctSetAutoContext

This function can replace two calls to the server with one, reducing traffic and boosting performance.

Declaration

NINT ctSetAutoContextId(COUNT contextId);

 

Description

 

To use ctSetAutoContextId() as a replacement for ChangeISAMContext() at the ISAM level, call ctSetAutoContextId(), passing the context ID you wish to use in the next record read call. Check for a return code of NO_ERROR to indicate success. Then call your record read function. The following functions are the record read functions that support this feature:

 

BLKIREC, EQLVREC, EQLREC, GTEVREC, GTEREC, GTVREC, GTREC, GetLTEVRecord, LTEREC, LTVREC, LTREC

 

Example

FILNO     datno1,datno2;              /* data file numbers   */

pVOID     bufptr1,bufptr2;            /* data buffer pointer */

COUNT     contextID_1,contextID_2,contextID_3; /* context ID's     */

 

OpenFileWithResource(datno1,"data1",ctSHARED);

OpenFileWithResource(datno2,"data2",ctSHARED);

 

 

/* move to first record for datno1 using first key */

FirstRecord(datno1 + 1,bufptr1);

/* establish first context for datno1 at first record. keyno == -1 saves all key positions. */

contextID_1 = OpenISAMContext(datno1,-1,-1);

/* move to first record for datno2 using third key. */

FirstRecord(datno2 + 3,bufptr2);

/* establish first context for datno2 at first record. keyno != -1 saves only key value for third key. */

contextID_2 = OpenISAMContext(datno2, datno2 + 3,-1);

NextRecord(datno1 + 1,bufptr1);

/* position datno1 at third record by first key. */

NextRecord(datno1 + 1,bufptr1);

/* Third record by first key becomes the saved position for contextID_1 and contextID_3 becomes the active context for datno1. */

contextID_3 = OpenISAMContext(datno1,-1,-1);

/* move from third record by first key, to the next record using the second key. Call this record 4' */

NextRecord(datno1 + 2,bufptr1);

/* Save record 4' as contextID_3. Make the 3rd record the current position for datno1, and contextID_1 becomes the active context for datno1. contextID_2 is still the active context for datno2. */

ctSetAutoContextId(contextID_1);

 

 

/* move to the 4th record by key 1 for datno1.*/

NextRecord(datno1 + 1,bufptr1);

 

ctSetClientLibraryOption

Enable additional c-tree client functions.

Declaration

NINT ctDECL ctSetClientLibraryOption(NINT option, pVOID value);

Description

  • option - ctCLIOPT_BROADCAST_READ
  • value - "YES" enables a background broadcast listening thread.

ctCLIOPT_BROADCAST_READ mode enables a background listening thread. This thread listens on the default TCP/IP broadcast port 5595 for a UDP packet. On reception of a validated packet, a global variable is set. In this initial support, this global variable is a failover flag indicating the client is required to reconnect to it's server.

A global variable is used to indicate the current failover state. A qualified failover event sets this flag variable to one (1).

See Also

ctResetFailOverState() (ctResetFailOverState, ctResetFailOverState) ctGetFailOverState (ctGetFailOverState, ctGetFailOverState)()

 

ctSetCommProtocolOption

Set additional communication socket options.

Declaration

NINT  ctDECL ctSetCommProtocolOption (NINT option,pVOID value)

Description

  • option - option to set - see list below
  • value - the value of the specified option

Unless otherwise noted, options must be set before making a database connection.

option is one of

  • ctCOMMOPT_SOCKET_TIMEOUT - The c-tree socket timeout limits how long a client socket will wait for a server response. It was added as a means to terminate hanging connections, for example, waiting on long-held blocking locks. While the socket timeout has been supported for many years it required modifying a c-tree global variable field structure directly. The socket timeout value, can now be set using ctSetCommProtocolOption() with the new ctCOMMOPT_SOCKET_TIMEOUT mode.
  • ctCOMMOPT_SOCKET_WAIT_INTERVAL - If a failover has occurred, the c-tree function call returns error SERVER_FAILOVER_ERR (1159). If no failover has occurred, the socket receive call waits again for the specified time interval with this option. This function can be called at any time to change the setting, but a c-tree instance must have already been initialized before calling this function. It affects the current c-tree instance.
  • ctCOMMOPT_FSSLTCP_SERVER_CERTIFICATE - By default, the ISAM and SQL client libraries use the file ctsrvr.pem in the client process' working directory when connecting. An ISAM client can change the file name of the client library with this option.
  • ctCOMMOPT_FSSLTCP_DEBUG_LOG - If an error occurs when connecting using SSL, the connection attempt returns error 1104 (SSLCONN_ERR). To get more additional detailed information enable SSL logging with this option.
  • ctCOMMOPT_FSSLTCP_CLIENT_CERTIFICATE - References a char * referencing the filename of a PEM formatted file with the full certificate chain the client will present for X.509-based authentication. This file name can be overridden by the environment variable CTSSL_CLIENT_CERTIFICATE
  • ctCOMMOPT_FSSLTCP_CLIENT_KEY - References a char * referencing the filename of a PEM formatted file containing the private key used to sign the client certificate for X.509- based authentication. This file name can be overridden by the environment variable CTSSL_CLIENT_KEY. The PEM may optionally be encrypted. Use ctCOMMOPT_FSSLTCP_CLIENT_PASSPHRASE to supply the passphrase.
  • ctCOMMOPT_FSSLTCP_CLIENT_PASSPHRASE - References a char * used to decrypt the client's private key if it is encrypted.
  • ctCOMMOPT_TCP_KEEPALIVE_INTERVAL - Provides a means of detecting broken TCP links in a configurable time interval. This sets a TCP level keepalive interval in seconds (value interpreted as a string). If the socket is idle, keepalive probes are generated at this interval. If the server does not acknowledge the probe, additional probes may be sent, and an error occurs after roughly 10 additional seconds of non-response. By default, a broken TCP link may be maintained by the OS for several hours, depending on OS defaults and activity on the socket.
  • ctCOMMOPT_SHMEM_MAX_SPIN - Sets the maximum number of spins that the client connection uses for a shared memory receive operation when the shared memory spin feature is enabled. This value can also be set by the environment variable FAIRCOM_SHMEM_MAX_SPIN. Note: if the application sets the ctCOMMOPT_SHMEM_MAX_SPIN value, the environment variable is ignored.

Example

Set the socket timeout to 10 seconds.

retval = ctSetCommProtocolOption(ctCOMMOPT_SOCKET_TIMEOUT, "10");

Return

NO_ERROR on success. c-tree error on exception.

 

Socket wait interval can be used to check server failover status

The client library now supports setting a time interval in seconds after which a socket receive call checks the server failover status. If a failover has occurred, the c-tree function call returns error SERVER_FAILOVER_ERR (1159). If no failover has occurred, the socket receive call waits again for the specified time interval. To use this feature, call this function:

NINT retval;

retval = ctSetCommProtocolOption(ctCOMMOPT_SOCKET_WAIT_INTERVAL, socketWaitInterval);

where socketWaitInterval is a string that holds the desired time interval in seconds, for example, "5" to indicate 5 seconds.

This function can be called at any time to change the setting. A c-tree instance must have already been initialized before calling this function. It affects the current c-tree instance.

Note: The socket timeout value, which has been supported for a number of years, can now be set using this function instead of having to modify a field of the c-tree global variable structure directly. For example, to set the socket timeout to 10 seconds call:

retval = ctSetCommProtocolOption(ctCOMMOPT_SOCKET_TIMEOUT, "10");

Affected Components: c-tree client library

 

ctSetCompress

Sets the data compression type and attribute to be used when creating files with data compression.

Note: To enable data compression, you need to either use the COMPRESS_FILE keyword or programmatically add ctCompressRec in the XCREblk.splval (for ISAM and Low-Level API).

Declaration

ctSETCOMPRESS( NINT comptype, NINT compvrsn, pTEXT dllname, pTEXT attrstr, VRLEN attrlen ) 

Description

  • comptype - either ctCMPRECzlib (default), ctCMPRECsRLE, ctCMPRECuser (user supplied shared library)
  • compvrsn - alternative versions for a given type
  • dllname - required when comptype==ctCMPRECuser

attrstr - NULL if no fine-tuning parameters are specified, or the following optional parameter format is:

"parm1=value; ... parmn=value;"

zlib specific parameter names are:

  • level
  • strategy
  • windowbits
  • memlevel
  • method
  • level [ 0 - 7 ]
  • strategy [ 0 ]
  • attrlen - combined length of the attrstrf strings including the null-termination bytes

Similar in operation to ctSETENCRYPT(), ctSETCOMPRESS() determines the compression specifics that will be used for all compressed data files created after the call to ctSETCOMPRESS(). To use different compression routines for different files, the application creating the files must call ctSETCOMPRESS() before each of the creates. Calling ctSETCOMPRESS() does not affect the compression used by existing files. When existing files are opened the compression resource is used to specify how the records are compressed. Such an open will fail if the resource contains a DLL name that is not available.

If no call is made to ctSETCOMPRESS(), then default, built-in zlib compression routines are used, as long as no server configuration is specified otherwise.

If no DLL is required, dllname is NULL. If no fine-tuning parameters are specified, then attrstrf is NULL and attrlen is zero. (See User Defined Compression Dynamic Shared Library for additional details.)

Notes

  • ctCompressRec is only allowed for data files. An error 944 (AREC_MOD) will be generated if it is used in the XCREblk corresponding to an index file.
  • If a data file to be compressed is fixed-length, it will be changed to a variable-length file at create time. This means there will be an additional 10 bytes of information for each record in the file for the variable-length record management (as discussed in Variable-Length Records). Therefore, be sure compression makes sense on a fixed-length file before turning it on.
  • This feature is available only for ISAM files fully maintained by ISAM updates. Low-Level FairCom DB functions will return an error when used on files with the compression attribute enabled.
  • Some files compress better than others (text data vs. binary data for instance). Initial testing revealed up to an 80:1 compression ratio in some cases.
  • Additional compression routines may become available in the future.

Server Configuration

Default FairCom DB compression can be specified with the following configuration keywords:

CMPREC_TYPE < "ZLIB" | "USER" | "RLE" >

CMPREC_VERSION <a number >= 1>

CMPREC_DLL <name of DLL>

These keywords should be entered in the configuration file in the order shown, and a DLL name is required for CMPREC_TYPE of USER.

The COMPRESS_FILE keyword can be used to enable compression in files whose names match specified file names (including wildcards).

Run Length Encoding (RLE) compression option is available in V10.3 and later. Configure the RLE compression algorithm in ctsrvr.cfg, similar to using the keywords ZLIB or USER.

In v10.3.0 and later, c-tree on Unix/Linux platforms dynamically loads zlib instead of statically linking with it.

Compressed Files in FairCom DB API - In V10 and later, the FairCom DB API file create mode, CTCREATE_COMPRESS, enables compressed record support in FairCom DB API. When CTCREATE_COMPRESS mode is used, FairCom DB API automatically creates the file as variable-length.

Return

AREC_BUF 936 Could not allocate a buffer for an augmented variable-length record. (for example, ctCMPREC).
AREC_SUP 937 Augmented variable-length records not supported for SUPERFILE host, fixed length files or index files.
AREC_DCM 938 Could not decompress the data record. sysiocod set to Z_xyz_ERROR.
AREC_ISM 939 Compressed record-length files require ISAM update; not Low-Level update.
AREC_NOP 940 Requested operation not supported for augmented records.
AREC_MOD 944

Bad augmented record file mode at create. Two conditions return this error:

  • Setting ctCompressRec in the XCREblk corresponding to an index file. It is only allowed for data files.
  • Setting ctCompressRec on a data file that is not variable-length (ctVLENGTH).

See also

User Defined Compression Dynamic Shared Library

 

User Defined Compression Dynamic Shared Library

The FairCom DB data record compression feature supports user definable compression modules. To include a custom compression module, the following information must be made available from within the shared library.

Function Arguments

pCMPRECFNC pfnc; input pointer to function pointer/DLL structure defined in ctstrc.h.

ppVOID pattrbuf; on input, a pointer to optional, fine-tuning parameter buffer. *pattrbuf==NULL implies no fine-tuning parameters specified. On output, *pattrbuf points to a parameter buffer. *pattrbuf is not guaranteed to be NULL on output if it is NULL on input, and vice versa.

pVRLEN pattrlen; on input, pointer to length of fine-tuning parameter buffer. If *pattrbuf is NULL on input, *pattrlen must be zero. On output *pattrlen contains the length of the parameter buffer.

pCMPRECRES pres; input pointer to compression resource structure defined in ctstrc.h.

pVOID context; input pointer to optional, compression/decompression support structure. If the compression (CmpActn) and/or decompression (ExpActn) routines do not use a support structure, then context will be NULL or ((pVOID) 1).

pVOID source; input pointer to byte stream to be compressed or decompressed.

VRLEN slen; input length of source buffer.

pVOID destination; output pointer to buffer that will contain the result of compression/decompression.

pVRLEN pdlen; on input, *pdlen is length of destination buffer. On output, *pdlen is the length of the byte stream result from the compression/decompression.

Function Prototypes

The module ctzlib.c has implementations of these functions for the built-in zlib support.

FncInit

NINT FncInit(pCMPRECFNC pfnc,pTEXT attrstr,VRLEN attrlen)

This routine performs a one-time setup on each physical open of a file after the DLL has been loaded. attrstr and attrlen are the same as those in ctSETCOMPRESS(). In addition to any DLL specific requirements, FncInit() should verify that the compression type and version (pfnc->comptype and pfnc->compvrsn) are compatible with the DLL, and that the fine-tuning parameters, if any, are valid. If no fine-tuning parameters are passed in, then if the routines require a parameter set, FncInit() should allocate and initialize such a parameter buffer. If it does so, then it should set pfnc->allocbuf to the address of the allocated buffer.

FncInit() returns NO_ERROR or CMPR_ERR (). In the case of CMPR_ERR FncInit() should set the sysiocod (using the routine usys(code)) as listed in cterrc.h for CMPR_ERR. FncInit() does not actually set uerr_cod.

FncExit

NINT  FncExit(pCMPRECFNC pfnc )

FncExit() is called just before a file is closed and its associated DLL is unloaded. In addition to DLL specific requirements, FncExit() should free memory allocated for a parameter buffer. FncExit() can test pfnc->allocbuf to find the allocated buffer address, if any.

FncExit() should return NO_ERROR.

CmpInit

pVOID CmpInit(pCMPRECFNC pfnc)

CmpInit() is called each time a user opens a compressed data file. CmpInit() should allocate a context buffer if the DLL requires one, and initialize the context as needed. The context buffer would typically be used to initialize and maintain the compression state. If no such context buffer is needed, then return ((pVOID) 1).

CmpInit() returns the address of the context buffer, or (pVOID) 1 if no context is used, or NULL on error. In case of error call usys(35) to indicate the CmpInit() failure.

CmpActn

NINT  CmpActn(pVOID context, pCMPRECFNC pfnc, pVOID source, VRLEN slen, pVOID destination, pVRLEN pdlen)

CmpActn() performs the actual compression of the source into the destination. *pdlen holds the length of the destination buffer on input, and is set to the length of the compressed output on return. CmpActn should be aware that an input value of ((pVOID) 1) means that no context structure has been provided.

CmpActn() returns CMPREC_OK () on success, CMPREC_BUF () if the destination buffer is too small, or CMPR_ERR for an unexpected error. In case of an unexpected error, usys(1000 + err) should be called to set sysiocod where err is the internal error code used by the compression routines. (See zlib1_CmpActn() for an example.)

CmpExit

NINT  CmpExit(pVOID context, pCMPRECFNC pfnc)

CmpExit() is called each time a user closes a compressed data file. CmpExit() should de-initialize a context buffer, if one has been allocated in CmpInit(), and free the associated memory.

CmpExit() typically returns NO_ERROR unless the DLL specific code to de-initialize the context buffer returns an error code in which case return this error code.

The following three functions behave just as their compression counterparts except that they apply to decompression. ExpActn() has the same return values as CmpExp() except that attempting to decompress corrupted data results in a return value of CMPREC_DATA and usys(2000 + err) is called where err is the DLL specific internal code signifying the corruption.

pVOID ExpInit(pCMPRECFNC pfnc)

NINT  ExpActn(pVOID context, pCMPRECFNC pfnc, pVOID source, VRLEN slen, pVOID destination, pVRLEN pdlen)

NINT  ExpExit(pVOID context, pCMPRECFNC pfnc)

 

ctSetConfigurationOptions

Pass a server configuration file into an embedded database server model ("Server DLL").

Declaration

NINT ctDECL ctSetConfigurationOptions (const char *optionString);

Description

ctSetConfigurationOptions() passes a null-terminated string in the format of the server configuration file as used by the embedded database server model ("Server .DLL"). Each configuration option is followed by a newline.

Example 1:

 

NINT rc;
 

rc = ctSetConfigurationOptions("SERVER_NAME FAIRCOMS\nCOMM_PROTOCOL FSHAREMM\n");

 

Example 2:

This is a copy of the default ctsrvr.cfg file and note each line that starts with a semicolon (;) indicates this line is a comment and will be ignored by the FairCom Server parsing routine.

 

#define MY_CONFIG_FILE_OPTIONS "\

; FairCom DB ISAM Server Configuration File - v11.5.0.46433 Build(171113)\n\

CHECK_CONFIG YES\n\

\n\

; Server Name\n\

SERVER_NAME             FAIRCOMS2\n\

;SERVER_PORT             5597\n\

\n\

; Location for data Files and Logs\n\

; LOCAL_DIRECTORY         ./data/\n\

\n\

; End of File\n"

 

 ctSetConfigurationOptions(MY_CONFIG_FILE_OPTIONS);

 

 /* FairCom MT API: Please note #01 */

 if ((err = ctThrdInit(3,(LONG) 0,  (pctINIT)&cfg))) {

Return

NO_ERROR on success. c-tree error on exception.

 

ctSetConnectionAttribute

The ctSetConnectionAttribute function sets a connection-level attribute.

Declaration

ctCONV NINT ctDECL ctSetConnectionAttribute(CTCONNECTION_ATTRIBUTE attr, cpVOID value);

 

Attribute Value
CTCONNECTION_ATTRIBUTE_SKIP_LOCKS_IN_EXCLUSIVE_MODE

A null-terminated string.

 

Specify "y" to skip locks for tables open in exclusive mode.

 

Specify "n" to acquire locks for tables open in exclusive mode.

 

 

ctSetCurrentSequenceValue

Declaration

NINT ctSetCurrentSequenceValue(LONG seqhnd, LONG8 newval);

Description

Sets the current value for the specified sequence. If newval is outside the boundary set by the initial value (at one end) and the lower limit or upper limit (at the other end) for the sequence, ctSetCurrentSequenceValue() returns an error, and the sequence value remains unchanged.

You cannot set a sequence to the unknown value.

Improvements to Sequence API and Active Transactions

In V11.5 and later, FairCom sequence support has been improved as follows:

  1. By default, sequence creates and deletes within an active transaction use Immediate Independent Commit Transactions (IICT) to commit immediately. If the sequence attribute ctSEQTRNDEP is specified when creating the sequence, the creation and deletion of the sequence is committed only when the transaction commits. This option makes it possible to rely upon a transaction abort to undo the sequence create or delete.
  2. The functions that update the sequence, ctSetSequenceAttrs(), ctSetCurrentSequenceValue(), and ctGetNextSequenceValue(), commit their changes immediately if possible. If the changes cannot be immediately committed, rather than failing with error 935 (IICT_FIL), the changes commit when the transaction commits. The case where these functions cannot immediately commit is when one of these functions is called in the same transaction that created the sequence, and the sequence is using the ctSEQTRNDEP option. In that situation, an IICT cannot be used because the file has been updated in the transaction, and so the sequence record remains locked until the transaction commits or aborts.
  3. ctSetSequenceAttrs(), ctSetCurrentSequenceValue(), and ctGetNextSequenceValue() left the sequence record locked until the transaction committed. In V11.5 and later, these functions ensure that the record is unlocked before they return (except for the case mentioned in point 2 above, where a transaction is active and IICT cannot be used).
  4. ctCreateSequence() and ctDeleteSequence() failed with error 588 (CPND_ERR) if called within an active transaction and OPS_DEFER_CLOSE was not in effect. In V11.5 and later, we temporarily enable OPS_DEFER_CLOSE in this situation to avoid the error.

 

Return Values

Value Symbolic Constant Explanation
0 NO_ERROR Successfully created the sequence.
900 SEQDUP_ERR A sequence having the specified name already exists.
903 SEQTYP_ERR The specified sequence type contains an invalid combination of sequence type options.
904 SEQINI_ERR The initial value specified for the sequence is out of range.
905 SEQCUR_ERR The current value specified for the sequence is out of range.
906 SEQLIM_ERR The limit value specified for the sequence is out of range.
907 SEQINC_ERR The increment value specified for the sequence is out of range.
901 SEQNAM_ERR Invalid sequence name specified (NULL, empty, or too long).

See FairCom DB Error Codes for a complete listing of valid error values.

Example

ctSEQATTR seqattr;

NINT rc;

/*

** Create an incrementing sequence that starts with 1, increments by 3, and

** terminates with 100.

*/

strcpy(seqattr.seqnam, "MyFirstSequence");

seqattr.seqini = 1;

seqattr.seqinc = 3;

seqattr.seqlim = 100;

seqattr.seqtyp = ctSEQINC | ctSEQTRM | ctSEQLIM;

 

if ((rc = ctCreateSequence(&seqattr))) {

printf("Error: Failed to create the sequence: %d\n", rc);

} else {

printf("Successfully created the sequence.\n");

}

See also

ctCreateSequence, ctDeleteSequence, ctOpenSequence, ctCloseSequence, ctGetSequenceAttrs, ctSetSequenceAttrs, ctGetCurrentSequenceValue, ctSetCurrentSequenceValue, ctGetNextSequenceValue

 

ctSETHGH

Set the high-order 4 bytes of an 8-byte record address.

Short Name

ctSETHGH()

Type

Low-Level function

Declaration

NINT ctSETHGH(LONG highword) 

Description

Call ctSETHGH() before a routine requiring a record address as an input parameter to set the high word value for the function.

To minimize the effect on performance in client/Server environments, ctSETHGH() does not make a separate call to the FairCom Server. Instead, the information supplied by ctSETHGH() is cached on the client side.

Return

ctSETHGH() always returns NO_ERROR (0). See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Example

/* Assumes a key length of 14 (8 bytes for HUGE duplicate support) */


LONG      recadr_hw,recadr_lw;

pTEXT     keyval;


keyval = "123456";


/* Remember, the high word counts the number of 4GB multiples contained  **

** in the composite 8 byte record address. Therefore, recadr_hw = 2 and  **

** recadr_lw = 512 means a record address of 8,589,935,104               */


recadr_hw = 2;

recadr_lw = 512;


/* set higher order 4 bytes of record address                */

ctSETHGH(recadr_hw);


if (AddKey(   /* add key value to index                      */

          9,  /* index file number                           */

     keyval,  /* pointer to key value                        */

  recadr_lw,  /* lower order 4 bytes of record address       */

     REGADD   /* regular add mode                            */

))

    printf("\nAddKey error = %d", uerr_cod);

Limitations

The recbyt parameter in this function is a 4-byte value capable of addressing at most 4 gigabytes. If your application supports HUGE files (greater than 4 gigabytes), you must use the ctSETHGH() and ctGETHGH() functions to set or get the high-order 4 bytes of the file offset.

See also Record Offsets Under Huge File Support.

See also

ctGETHGH

 

ctSetLicenseFile

Sets a server license file by name.

Declaration

NINT ctSetLicenseFile (pTEXT license);

Description

  • license - license file name

ctSetLicenseFile() is expected to be made before starting an embedded database engine; that is, before a call to ctdbStartDatabaseEngine() or ctThrdInit().

Return

NO_ERROR on success. c-tree error code on exception.

 

ctSetLicenseOptions

Passes server license file contents directly to an embedded server model ("Server DLL").

Declaration

NINT ctDECL ctSetLicenseOptions (const char *licenseString);

Description

ctSetLicenseOptions() passes a null-terminated string containing the contents of a valid c-tree Server license file for use with the embedded database engine model ("Server DLL").

Note: The license data must be entered exactly as on disk because a checksum is used to ensure that the license has not been modified. Simply including a newline at the end of the last line will cause a checksum error because the license file has no newline at the end of its last line.

Example:

 

NINT rc;

rc = ctSetLicenseOptions("<?xml version=\"1.0\" encoding=\"us-ascii\"?>\n<ctlicense version="3">\n...");

 

Note: When this option is used, the following message is logged to CTSTATUS.FCS instead of the usual message which shows the license file name:

Tue Jun 25 14:26:51 2019
 - User# 00001  LICENSE: License file in use: application-provided
 

Return

 

ctSetLocalDirectory

Sets a local working directory location for an embedded server model.

Declaration

NINT ctSetLocalDirectory (pTEXT localdir);

Description

  • localdir - directory path string to set as the working directory.

ctSetLocalDirectory() sets the server's working directory area as usually defined with a LOCAL_DIRECTORY configuration option.

LOCAL_DIRECTORY is the default location where database files will be created. Your transaction logs and other housekeeping files will also be located in this area. This API call is expected to be made before starting an embedded database engine; that is, before a call to ctdbStartDatabaseEngine() or ctThrdInit().

Return

NO_ERROR on success. c-tree error code on exception.

 

ctSetNullBit

Set or clear the specified bit in the specified bit array.

Declaration

NINT ctDECL ctSetNullKeyValue(FILNO keyno, cpTEXT nullkey, ULONG keylen);

Description

  • pArray [IN/OUT] - the bit array to update
  • BitNumber [IN] - zero-based bit number to set or clear
  • SetBit [IN] - if non-zero, set the bit; if zero, clear the bit

Returns

none

See Also

ctGetNullBit

 

ctSetNullKeyValue

Sets the null key value for the specified index.

Declaration

NINT ctDECL ctSetNullKeyValue(FILNO keyno, cpTEXT nullkey, ULONG keylen);

Description

  • keyno - the index file number.
  • nullkey - the null key value.
  • keylen - the size of the null key value in bytes, which must be less than or equal to the defined key length, including the tie-breaking bytes for an index that allows duplicates, although those bytes are not considered in the null key comparison. If the null value length is smaller than the key length, only the specified length of the key value is compared to the null key value.

Returns

zero on success or a non-zero c-tree error code on failure.

COMPATIBILITY NOTE: An index file that uses this feature, and its corresponding data file, have a feature bit that is set in their header. If this feature bit is set and the server or client or standalone library attempting to open the file does not support this feature, the file open fails with error 744.

See Also

ctGetNullKeyValue()

 

ctSetOWNER

Allows a thread to take ownership of an existing c-tree connection.

Declaration

VOID ctSetOWNER(NINT sOWNR)

Description

ctSetOWNER() allows a thread to take ownership of an existing c-tree connection. This is useful in applications where one thread needs to perform some duty in another thread of operation. For example, a controller thread taking over a worker thread for administrative tasks.

Note: This function is only available in the c-tree multi-threaded library.

Return

void

Example

A thread can use this function to take ownership of a c-tree connection as demonstrated by the following:

NINT sOWNR = 0; /* A c-tree connection handle accessible to both threads. */

Thread #1:

/* Initialize c-tree. */

INTISAM(...);


/* Get handle for this connection. */

sOWNR = ctOWNER();

Thread #2:

/* Take ownership of the connection. */

ctSetOWNER(sOWNR);

/* Call c-tree functions on the connection from Thread #1. */

Only a single thread is expected to make c-tree API calls using a particular owner. In the above case, thread #1 still has the same OWNER value. Undefined behavior occurs if multiple threads make c-tree API calls using the same connection.

 

ctSetSequenceAttrs

Declaration

NINT ctSetSequenceAttrs(LONG seqhnd, pctSEQATTR pseqattr);

Description

Sets the attributes for the specified sequence.

  • seqhnd specifies the sequence handle.
  • pseqattr points to a ctSEQATTR structure that contains the modified sequence attribute values.

The following attributes can be changed:

  • seqnam - Changing the sequence name renames the sequence.
  • seqini - If the sequence enforces a limit, the initial sequence value must be less than the sequence limit for an incrementing sequence or must be greater than the sequence limit for a decrementing sequence.
  • seqcur - For an incrementing sequence, the current sequence value must be greater than or equal to the initial sequence value, and if the sequence enforces a limit the current sequence value must be less than or equal to the limit value. For a decrementing sequence, the current sequence value must be less than or equal to the initial sequence value, and if the sequence enforces a limit the current sequence value must be greater than or equal to the sequence limit. If sequnk is set to a non-zero value, the seqcur value is ignored, and the current sequence value is set to the unknown value.
  • seqinc - The sequence increment must be a positive value that is less than the difference between the initial sequence value and the sequence limit.
  • seqlim - The sequence limit must be greater than the initial sequence value for an incrementing sequence or must be less than the initial sequence value for a decrementing sequence. The sequence limit is only enforced if the sequence type specifies the ctSEQLIM bit.
  • seqtyp - The sequence type must be set to either ctSEQINC or ctSEQDEC, and either ctSEQCYC or ctSEQTRM, and optionally includes ctSEQLIM. By changing seqtyp, a sequence can be changed from an incrementing to a decrementing sequence and/or from a cycling to a terminating sequence, and a sequence limit can be enabled or disabled. If changing a sequence from incrementing to decrementing (or vice-versa), the initial and limit values must also be changed (see notes on seqini and seqlim).
  • sequnk - Setting the sequence unknown flag causes the current sequence value to be set to the unknown value

Return Values

Value Symbolic Constant Explanation
0 NO_ERROR Successfully created the sequence.
900 SEQDUP_ERR A sequence having the specified name already exists.
903 SEQTYP_ERR The specified sequence type contains an invalid combination of sequence type options.
904 SEQINI_ERR The initial value specified for the sequence is out of range.
905 SEQCUR_ERR The current value specified for the sequence is out of range.
906 SEQLIM_ERR The limit value specified for the sequence is out of range.
907 SEQINC_ERR The increment value specified for the sequence is out of range.
901 SEQNAM_ERR An invalid sequence name was specified: the name is NULL, empty, or too long.

See FairCom DB Error Codes for a complete listing of valid error values.

Example

ctSEQATTR seqattr;

NINT rc;

/*

** Create an incrementing sequence that starts with 1, increments by 3, and

** terminates with 100.

*/

strcpy(seqattr.seqnam, "MyFirstSequence");

seqattr.seqini = 1;

seqattr.seqinc = 3;

seqattr.seqlim = 100;

seqattr.seqtyp = ctSEQINC | ctSEQTRM | ctSEQLIM;

 

if ((rc = ctCreateSequence(&seqattr))) {

printf("Error: Failed to create the sequence: %d\n", rc);

} else {

printf("Successfully created the sequence.\n");

}

See also

ctCreateSequence, ctDeleteSequence, ctOpenSequence, ctCloseSequence, ctGetSequenceAttrs, ctSetSequenceAttrs, ctGetCurrentSequenceValue, ctSetCurrentSequenceValue, ctGetNextSequenceValue

 

ctSQLImportTable

Imports a table to the FairCom data dictionaries.

Note: See the fget_input note below for an important Compatibility Change in V11.2.3 and later.

Declaration

The function prototype is as follows:

NINT ctSQLImportTable(pCTSQLIMPOPTS pctsqlimpopts);

Description

The caller passes the address of a CTSQLIMPOPTS structure, which specifies the table import options (corresponding command-line flags in parentheses). The full CTSQLIMPOPTS structure is defined in ctdbsdk.h, which is as follows in V11.2.3 and later (the remarks indicate the corresponding ctsqlimp options):

 

    pTEXT   tblnam; /* <table_name>: name of table to import                 */

    pTEXT   symnam; /* -n <symbolic_name>: symbolic table name               */

    pTEXT   prefix; /* -q <prefix>: table name prefix                        */

    pTEXT   dbsnam; /* -d <database_name>: name of FairCom DB SQL database
                          (default: ctreeSQL)                                */

    pTEXT   srvnam; /* -s <server_name>: FairCom DB SQL Server name
                          (default: FAIRCOMS)                                */

    pTEXT   usrnam; /* -u <user_name>: userid for connecting to
                          FairCom DB SQL Server                           */

    pTEXT   usrpwd; /* -a <password>: password for authentication            */

    pTEXT   tblown; /* -o <owner>: assign table owner                        */

    pTEXT   prikey; /* -m <idname>: set 'idxname' as primary key             */

    pTEXT   paddin; /* -f <s|z|sz>: force string padding to 
                          (s)paces (z)eroes or (sz)spaces zero terminated    */

    SQLCBF  clbkfn; /* callback function                                     */

    NINT    chkfld; /* -k: skip fields that don't comply with conventional
                           identifier rules                                  */

    NINT    skpidx; /* -x: skip indices                                      */

    NINT    rmlink; /* -r: unlink table from database                        */

    NINT    frctbl; /* -c: allow table names that don't comply with          */

    NINT    grntpb; /* -b: grant public access permissions                   */

    NINT    nonint; /* -i: non-interactive mode: ignore errors and continue  */

    NINT    grntro; /* -B: grant public read-only access permissions
                           (V10.3 and later)            */

    NINT    promot; /* -p: promote unsigned types to greater signed type      */

    NINT    prmver; /* -P: promote unsigned types to greater signed type and
                           set check for fitting value                        */

    NINT    strinz; /* -z: allow indices with missing string terminator in
                           key segments                                       */

    NINT    lobsiz; /* -l <size>: specify LONGVAR* field size threshold       */

    NINT    ignnam; /* -g: ignore existing index name in IFIL resource        */

    NINT    nintrl; /* -j: non-interactive relink of existing table           */

    pTEXT   script; /* -w: build script file with CREATE statements
                           (don't import table)                               */

    pTEXT   extdef; /* -e: get DODA definitions in XML format from 'xmlfile   */

    PRINTFNC print_message; /* ctSQLImportTable print message function        */

    GETINPUT fget_input; /* ctSQLImportTable interactive mode input function  */

    pVOID   usertag;    /* user tag for print_message and fget_input          */

    NINT    dropstrict; /* error out when dropping table if missing in
                           dictionaries                                       */

    CTBOOL  keepextra;  /* keep existing permissions and synonym 
                           (does not remove nor add them)                     */

    SQLCBFX clbkfnX; /* new extended callback function */

    pTEXT rowidfld; /* --rowid_fld: name of the rowid field NULL to not expose it */

    pTEXT rowididx; /* --rowid_idx: name of the rowid index NULL to not expose it */

    pTEXT tls_cert; /* --tls: TLS cert file, SQLIMP_BASE_TLS for TLS with no certificate checking */

 

(If you are using a FairCom version earlier than V11.2.3, see the CTSQLIMPOPTS structure prior to V11.2.3 page.)

ctSQLImportTable() is implemented with FairCom DB API API functions. An application using only ISAM or Low-Level functions can call ctSQLImportTable() provided the application #includes the FairCom DB API header file ctdbsdk.h and links with a c-tree client library that is built with underlying FairCom DB API C API support.

Notes:

Exclusive Open:

Prior to V12, this function call needed an exclusive open. This requirement has been relaxed starting in V12 forward.

fget_input:

Setting fget_input to SQLIMP_CBK_FNC or NULL implies that the ctSQLImportTable requests input and simply behaves as default or as specified in the callback.

Compatibility Change (V11.2.3 and later): When using this setting, the “nonint” member needs to be set to 1 (non-interactive) or the ctSQLImportTable fails because of bad setting (c-treeDB error 4004, cannot be interactive without an input function).

Setting fget_input to SQLIMP_IO_FNC indicates to use the default input function of ctsqlimp utility. This was the default ctSQLImportTable behavior before this change, with some exceptions that were ignored.

Setting fget_input to a pointer to a function with this prototype:

pTEXT GETINPUT (pTEXT Message, pTEXT Buffer, NINT MaxCount, pVOID tag);

  • Message is the prompt to "display".
  • Buffer is the output buffer where the input should be placed.
  • MaxCount in the maximum size of the buffer.
  • tag is the “usertag” specified in the CTSQLIMPOPTS used when calling the ctSQLImportTable function

clbkfn field:

The clbkfn field can be used to specify a callback function called by ctSQLImportTable() in certain situations. If no callback function address is specified, c-tree uses the default callback function SQLLinkCallback() found in ctsqlimp.c. This default callback function prompts the user for input in some situations. To avoid these prompts, developers can implement their own version of this function and can pass the address of this function to ctSQLImportTable() by setting the clbkfn field to the address of the custom callback function.

tls_cert field:

The tls_cert member can be set to:

1) NULL to not use TLS.

2) SQLIMP_BASE_TLS to use a basic TLS connection with encryption but no certificate checking.

3) A string containing the name of a certificate file to use TLS with a certificate.

 

Reuse of logon:

This API call differs from others as it directly instantiates a client connection to the server for this specific task. V11.5 introduced a mode to reuse the existing connection. The srvnam member can be set to SQLIMP_REUSE_LOGON to force the SQL Import connection to use the existing client connection when already connected to the server.

print_message:

Setting print_message to SQLIMP_CBK_FNC or NULL implies that the ctSQLImportTable does not print any message.

Setting print_message to SQLIMP_IO_FNC instructs it to use the default messaging reporting of the ctsqlimp utility (default ctSQLImportTable behavior before V11.2.3).

Setting the pointer to a function with this prototype:

VOID PRINTFNC(NINT lvl, pTEXT msg, pVOID tag)

  • msg is the message to be printed.
  • lvl is one of the following:

SQLIMP_PRINT_EMSG - error message

SQLIMP_PRINT_WMSG - warning message

SQLIMP_PRINT_MSG - generic message

  • tag is the “usertag” specified in the CTSQLIMPOPTS used when calling the ctSQLImportTable function. It may be useful to pass information like the file handle to print or a Windows handle for GUI.

Call Back Function

Prototype

CTBOOL SQLLinkCallback(CTSQLCB_MODE mode, pTEXT msg, CTBOOL def, pVOID extra)

 

CTSQLCB_MODE enum Function
CTSQLCB_ERROR 1 handle error
CTSQLCB_WARNING 2 handle warning
CTSQLCB_CONFIRM_SKIPIDX 3 confirm skipping index import
CTSQLCB_CONFIRM_PUTIFIL 4 confirm PUTIFIL update
CTSQLCB_CONFIRM_NOPUTIFIL 5 confirm continuing after skipping PUTIFIL
CTSQLCB_CONFIRM_REPLACELNK 6 confirm replacing existing table link
CTSQLCB_CONFIRM_CHANGEPAD 7 confirm changing string pad strategy
CTSQLCB_CONFIRM_SPACEPAD 8 confirm space padding or zeroes padding
CTSQLCB_CONFIRM_NULLTERM 9 confirm NULL terminator
CTSQLCB_CONFIRM_PUTPAD 10 confirm updating PAD resource
CTSQLCB_CONFIRM_NOPUTPAD 11 confirm continuing after skipping upd PAD
CTSQLCB_CONFIRM_SKPHIDFLD 12 confirm skip of FC-ODBC hidden field
CTSQLCB_CONFIRM_SKPHFLDIDX 13 confirm skip of hidden field's indexes
CTSQLCB_RETURN_SYMTBLNAME 14 return alternate symbolic table name
CTSQLCB_ELAB_IDX 15 confirm index elaboration
CTSQLCB_PROMOTE_UINT 16 promote unsigned integer to greater signed type
CTSQLCB_RETURN_PRIIDXNAME 17 return primary key index name
CTSQLCB_RETURN_TBLUID 18 return table id
CTSQLCB_STRING_PARTSEG 19 allow segments on strings missing last byte
CTSQLCB_FORCE_PADDING 20 force string padding
CTSQLCB_RETURN_MAXFLDLEN 21 return maximum length of fields
CTSQLCB_RETURN_IDXMETHOD 22 return SQL index method id
CTSQLCB_CONFIRM_NONCONVIDS 23 confirm import of non-conventional identifiers
CTSQLCB_GRANT_PUBLIC 24 grant access to public (all SQL users)
CTSQLCB_CONFIRM_PRIIDX 25 confirm if primary key (NO calls #17 YES is primary)
CTSQLCB_RETURN_TBLPREFIX 26 return prefix to table name
CTSQLCB_CONFIRM_MAXIDXENTRIES 27 confirm continuing on reaching max idx fields
CTSQLCB_PROMOTE_UINT_CHECK 28 add check constraint for promoted unsigned integer
CTSQLCB_GRANT_PUBLIC_RO 29 grant read-only access to public (all SQL users)
CTSQLCB_CONFIRM_MAXKEYSEG 30 confirm continuing when #of seg > MAX_KEY_SEG
CTSQLCB_CONFIRM_MAXIDX 31 confirm continuing when #of indices > MAX_DAT_KEY
CTSQLCB_CONFIRM_INDEXTRUNC 32 allow indexes with rightmost segment(s) on hidden field(s)
CTSQLCB_RETURN_TBLORIGIN 33 return table origin (10 chars)
CTSQLCB_CONFIRM_SKPREGFLD 34 confirm hiding of a field that would be exposed
CTSQLCB_CONFIRM_KEEPEXTRAS 35 keep information in sys*auth and sys synonyms tables during unlink/link operation
CTSQLCB_CONFIRM_NULKEY_IMP 36 confirm import of ISAM keys with NUL key support
CTSQLCB_GRANT_GROUP_RO 37 grant read-only access to the group the table belongs to. it returns group name in extras (max IDZ including terminator)
CTSQLCB_RETURN_ROWID_FLD 38 expose to SQL rowid field with given name
CTSQLCB_RETURN_ROWID_IDX 39 expose to SQL rowid index with given name

 

Example


CTBOOL myCB(CTSQLCB_MODE mode, pTEXT msg, CTBOOL def, pVOID extra) {

unsigned char input[256], *ch;

ch = &input[0];

 

switch (mode)

{

case CTSQLCB_ERROR:

printf("ERROR:  %S\n", msg);

return def;

case CTSQLCB_WARNING:

printf("WARNING  %s\n", msg);

return def;

case CTSQLCB_CONFIRM_SPACEPAD:

case CTSQLCB_CONFIRM_CHANGEPAD:

case CTSQLCB_CONFIRM_PUTIFIL:

return NO;

/* following modes that defaults to YES in non-interactive mode */

case CTSQLCB_CONFIRM_NOPUTIFIL:

case CTSQLCB_CONFIRM_NOPUTPAD:

return YES;

case CTSQLCB_CONFIRM_REPLACELNK:

return YES;

}

 

return def;

}

 

NINT main (NINT argc, pTEXT argv[])

{

   NINT rc = 0;

   CTSQLIMPOPTS impopts;

 

   ctsfill(&impopts, 0, sizeof(impopts));

   impopts.tblnam = ".\\customer.dat";

   impopts.symnam = "customer";

   impopts.dbsnam = "ctreeSQL";

   impopts.srvnam = "FAIRCOMS@localhost";

   impopts.usrnam = "ADMIN";

   impopts.usrpwd = "ADMIN";

   impopts.clbkfn = myCB;

   impopts.nintrl = 1;

   impopts.nonint = 0;

   impopts.fget_input = SQLIMP_IO_FNC;

 

   if (!(rc = ctSQLImportTable(&impopts)))

      ctrt_printf("Import ok\n");

   else

      ctrt_printf("Import failed: %d, %d\n", rc, sysiocod);

}

Returns

Value Symbolic Constant Explanation
0 CTDBRET_OK Successful operation.
12 FNOP_ERR

Could not open file. Either file does not exist, filnam points to incorrect file name, or file is locked by another process. Check sysiocod for the system-level error. For ISAM functions, check isam_fil for the specific file number.

For the client/server model only, if a file open returns FNOP_ERR, check sysiocod. If sysiocod = FCNF_COD, (-8), the file exists but there is file mode conflict preventing the file from being opened. For example, requesting an ctEXCLUSIVE open when the file is already open ctSHARED.

The failure to open the file with system error 32 could happen due to third-party backup software having the file open even if it does not lock regions of the file.

For example, if the software has the file open in exclusive mode, an attempt by c-tree to open the file in shared or exclusive mode will fail. If the software has the file open in shared mode, an attempt by c-tree to open the file in exclusive mode will fail.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Example


NINT rc;

CTSQLIMPOPTS impopts;

ctsfill(&impopts, 0, sizeof(impopts));

impopts.tblnam = ".\\qasqlimp.dat";

impopts.symnam = "inventory";

impopts.dbsnam = "ctreeSQL";

impopts.srvnam = "FAIRCOMS@localhost";

impopts.usrnam = "ADMIN";

impopts.usrpwd = "ADMIN";

impopts.clbkfn = mySQLLinkCallback;

if (!(rc = ctSQLImportTable(&impopts)))

     ctrt_printf("Import ok\n");

else

     ctrt_printf("Import failed: %d\n", rc);

 

History

V11.2.3 and later has ability to optionally retain SQL grants and synonyms on table drop such that they can be retained on subsequent table link. Refer to CTSQLIMPOPTS keepextra member.

 

CTSQLIMPOPTS structure prior to V11.2.3

If you are using a version of FairCom DB prior to V11.2.3, the CTSQLIMPOPTS structure is as follows. (If you are using the current version of FairCom DB, see the ctSQLImportTable (ctSQLImportTable, ctSQLImportTable) documentation):

 

typedef struct tagCTSQLIMPOPTS {

    pTEXT   tblnam; /* name of table to import                               */

    pTEXT   symnam; /* (-n) symbolic table name                              */

    pTEXT   prefix; /* (-q) table name prefix                                */

    pTEXT   dbsnam; /* (-d) name of c-treeSQL database (default: ctreeSQL)   */

    pTEXT   srvnam; /* (-s) FairCom DB SQL Server name (default: FAIRCOMS)    */

    pTEXT   usrnam; /* (-u) userid for connecting to FairCom DB SQL Server    */

    pTEXT   usrpwd; /* (-a) password for authentication                      */

    pTEXT   tblown; /* (-o) assign table owner                               */

    SQLCBF  clbkfn; /* callback function                                     */

    NINT    chkfld; /* (-k) skip fields that don't comply with 
                       conventional identifier rules                         */

    NINT    skpidx; /* (-x) skip indexes                                     */

    NINT    rmlink; /* (-r) unlink table from database                       */

    NINT    frctbl; /* (-c) allow table names that don't comply with         */

    NINT    grntpb; /* (-b) grant public access permissions                  */

    NINT    nonint; /* (-i) non-interactive mode: ignore errors and continue */

} CTSQLIMPOPTS, *pCTSQLIMPOPTS;

 

ctStatusLogWrite

Writes the specified message to the FairCom DB status log file, CTSTATUS.FCS.

Declaration

COUNT ctStatusLogWrite(pTEXT msg,NINT err)

Description

Where

  • msg is the message to write to the status log
  • err is the error code to include in the message.

Return

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Example

Writes a message in the following format to CTSTATUS.FCS:

ctStatusLogWrite("This is a test", 3);

 

Wed Jun 10 15:10:27 2009

 - User# 00011 This is a test: 3

Limitations

Available only in the Server DLL model (server side).

 

ctSysQueueClose

Closes an existing queue.

Short Name

ctSysQueueClose()

Type

ISAM function.

Declaration

 

NINT ctSysQueueClose(NINT qhandle)

 

Description

Closes an existing queue when the queue is no longer needed.

Parameter qhandle is a system queue handle returned by a call to the ctSysQueueOpen() function.

Return

Value Symbolic Constant Explanation
0 NO_ERROR Successful close of the queue.
90 NQUE_ERR Could not create queue.
454 NSUP_ERR Service not supported.
514 CQUE_ERR Queue has already been closed.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Example

NINT qhandle = ctSysQueueOpen("myqueue", 0);


if (qhandle > 0)

    ctSysQueueClose(qhandle);

Limitations

Client/Server mode only.

See also

ctSysQueueOpen

 

ctSysQueueCount

Return the number of messages waiting in the queue.

Short Name

ctSysQueueCount()

Type

ISAM function.

Declaration

 

NINT  ctSysQueueCount(NINT qhandle)
 

Description

ctSysQueueCount() can be used to obtain the number of messages waiting in the system queue.

Parameter qhandle is a system queue handle returned by a call to ctSysQueueOpen().

Return

ctSysQueueCount returns the number of messages in the queue, or a negative number on error.

Value Symbolic Constant Explanation
-90 NQUE_ERR Could not create queue.
-514 CQUE_ERR Queue has already been closed.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Example

/* check the number of messages on a queue */

NINT count = ctSysQueueCount(qhandle);


if (count >= 0)

    printf("There are %d messages on my queue\n", count);

else

    printf("ctSysQueueCount failed with code %d\n", -count);

Limitations

Client/Server mode only.

See also

ctSysQueueRead

 

ctSysQueueLIFOWrite

Add new data at the beginning of a queue.

Short Name

ctSysQueueLIFOWrite()

Type

ISAM function.

Declaration

 

NINT ctSysQueueLIFOWrite(NINT qhandle, pVOID message, NINT msglen)

 

Description

Data is placed at the beginning of the queue by invoking ctSysQueueLIFOWrite(). This is similar to a stack operation.

Parameter qhandle is a system queue handle returned by a call to ctSysQueueOpen(). Parameter message is a pointer to a block of memory containing arbitrary data to be placed on the queue and msglen indicates how many bytes are pointed to by message.

Return

Value Symbolic Constant Explanation
0 NO_ERROR Successful write to the queue.
90 NQUE_ERR Could not create queue.
92 QMRT_ERR Queue memory error during write.
446 BMOD_ERR Bad mode: parameter out of range.
454 NSUP_ERR Service not supported.
514 CQUE_ERR Queue has already been closed.
758 QNOT_ERR Only notifications to queue.
759 QUIN_ERR Wrong queue instance.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Example

NINT eRet = ctSysQueueLIFOWrite(qhandle, "My message", 10);


if (eRet)

    printf("ctSysQueueLIFOWrite failed with code %d\n", eRet);

Limitations

Client/Server mode only.

See also

ctSysQueueWrite

 

ctSysQueueMlen

Retrieves the length of the next available message in the queue.

Short Name

ctSysQueueMlen()

Type

ISAM function.

Declaration

NINT  ctSysQueueMlen(NINT qhandle, LONG timeout)

Description

ctSysQueueMlen() returns the length of the next available message in the specified queue.

Parameter qhandle is a system queue handle returned by a call to ctSysQueueOpen(). Parameter timeout specifies a millisecond time that ctSysQueueMlen() will block if the queue is empty. A timeout value of ctWAITDFOREVER will cause ctSysQueueMlen() to block until data is available in the queue.

Use ctSysQueueMlen() to find out the appropriate size of a buffer before calling ctSysQueueRead().

Return

ctSysQueueMlen() returns the length of the next available message, or a negative value on error.

Value Symbolic Constant Explanation
-7 TUSR_ERR Terminate user.
-90 NQUE_ERR Could not create queue.
-514 CQUE_ERR Queue has already been closed.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Example

NINT len = ctSysQueueMlen(qhandle, ctWAITFOREVER);


if (len >= 0)

    printf("The next message length is %d bytes\n", len);

else

    printf("ctSysQueueMlen failed with code %d\n", -len);

Limitations

Client/Server mode only.

See also

ctSysQueueRead

 

ctSysQueueOpen

Open or create a new queue.

Short Name

ctSysQueueOpen()

Type

ISAM function

Declaration

 

NINT  ctSysQueueOpen(pTEXT qname, NINT qmode)

 

Description

ctSysQueueOpen() opens an existing queue or creates a new queue.

Parameter qname identify the queue to be opened. If the queue specified by qname does not exist, a new queue is created. Parameter qmode is currently reserved for future use and should be set to zero.

Register a queue list

In V11.6.1 and later, we support registering a system queue in a dedicated catalog of queues. This catalog is created as a memory file. Application can then access and query registered system queues. To use this feature, OR the ctSQ_MONITOR bit into the mode ctSysQueueOpen() call mode parameter. The memory file catalog is named $sysqueuemonitor.dat.

Example

An application opens $sysqueuemonitor.dat and reads records in this file, then queries the count of system queue entries for each queue. Example output:

 

16:26:42 - Logon to server...

16:26:42 - Open table...

16:26:45 - Update records...

16:26:45 - Logon to master server...

16:26:54 - Updated 50000 records locally in 12031 msecs - 4155.00 ops/sec

16:26:54 - Master pending queue: 9274

16:26:54 - Master notification queue local2: 3738

16:26:54 - Master notification queue local: 3608

16:26:56 - Master notification queue local2: 0

16:26:56 - Master notification queue local: 0

16:26:56 - Updated 50000 records to the master in 14031 msecs - 3563.00 ops/sec

16:26:56 - Close table...

16:26:56 - Logout...

 

When the queue is no longer needed, it must be closed by calling the close function ctSysQueueClose().

Return

ctSysQueueOpen() returns a queue handle on success, or a negative value on error.

Value Symbolic Constant Explanation
-454 NSUP_ERR Service not supported.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Example

NINT qhandle = ctSysQueueOpen("myqueue", 0);


if (qhandle < 0)

    printf("ctSysQueueOpen failed with code %d\n", -qhandle);

Limitations

Client/Server mode only.

See also

ctSysQueueClose

 

ctSysQueueRead

Read data from the queue.

Short Name

ctSysQueueRead()

Type

ISAM function.

Declaration

NINT  ctSysQueueRead(NINT qhandle, pVOID buffer, NINT buflen, LONG timeout)

Description

Data is read from the queue by calling ctSysQueueRead().

Parameter qhandle is a system queue handle returned by a call to ctSysQueueOpen(), while timeout specifies a millisecond time that ctSysQueueRead() will block waiting for data. A timeout of ctWAITFOREVER will cause ctSysQueueRead() to block until data is available in the queue. Parameter buffer is a pointer to a memory block large enough to hold the next message in the queue, and buflen indicates the size in bytes of buffer.

ctSysQueueMlen() may be used to retrieve the next message length, while ctSysQueueCount() may be used to retrieve the number of messages waiting in the queue.

Return

Value Symbolic Constant Explanation
0 NO_ERROR Successful function.
90 NQUE_ERR Could not create queue.
514 CQUE_ERR Queue has already been closed.
638 TQUE_ERR Queue message truncated to fit.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Example

TEXT msg[128];

NINT eRet = ctSysQueueRead(qhandle, msg, sizeof(msg), ctWAITFOREVER);


if (eRet)

    printf("ctSysQueueRead failed with code %d\n", eRet);

Limitations

Client/Server mode only.

See also

ctSysQueueMlen, ctSysQueueCount

 

ctSysQueueWrite

Add new data at the end of a queue.

Short Name

ctSysQueueWrite()

Type

ISAM function.

Declaration

NINT ctSysQueueWrite(NINT qhandle, pVOID message, NINT msglen)

Description

Data is placed at the end of the queue by invoking ctSysQueueWrite().

Parameter qhandle is a system queue handle returned by a call to ctSysQueueOpen(). Parameter message is a pointer to a block of memory containing arbitrary data to be placed on the queue and msglen indicates how many bytes are pointed to by message.

Return

Value Symbolic Constant Explanation
0 NO_ERROR Successful write to the queue.
90 NQUE_ERR Could not create queue.
92 QMRT_ERR Queue memory error during write.
446 BMOD_ERR Bad mode: parameter out of range.
454 NSUP_ERR Service not supported.
514 CQUE_ERR Queue has already been closed.
758 QNOT_ERR Only notifications to queue.
759 QUIN_ERR Wrong queue instance.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Example

NINT eRet = ctSysQueueWrite(qhandle, "My message", 10);


if (eRet)

    printf("ctSysQueueWrite failed with error %d\n", eRet);

Limitations

Client/Server mode only.

See also

ctSysQueueLIFOWrite

 

ctThrdAttach

Make an existing thread FairCom DB compatible.

Short Name

ctThrdAttach()

Type

Threading function

Declaration

NINT ctThrdAttach(void) 

Description

ctThrdAttach() prepares a thread to be used with FairCom DB. If the calling thread is already compatible, ctThrdAttach() returns NO_ERROR and does nothing.

Return

Value Symbolic Constant Explanation
0 NO_ERROR Thread successfully attached.
82 UALC_ERR Insufficient memory.
600 CTHD_ERR Exceeded threads permitted by ctThrdInit().

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Example

See the ctThrdDetach() example.

See also

ctThrdDetach, ctThrdInit

 

ctThrdBlockCls

Close a block.

Short Name

ctThrdBlockCls()

Type

Threading function

Declaration

NINT ctThrdBlockCls(pctBLOCK block)

Description

Close the block referenced by block, making it inactive.

Return

ctThrdBlockCls() returns NO_ERROR (0). See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Limitations

Can only be used with a ctThrd library.

See also

ctThrdBlockGet, ctThrdBlockRel, ctThrdBlockWait

 

ctThrdBlockGet

Get a thread block.

Short Name

ctThrdBlockGet

Type

Threading function

Declaration

NINT ctThrdBlockGet(pctBLOCK block, LONG timeout) 

Description

  • block is the address of a synchronization object of type ctBLOCK.
  • timeout is specified in milliseconds.

A block differs from a mutex in two significant respects: it may be released by a thread other than the thread which acquired it, and you may specify a timeout value which causes a ctThrdBlockGet() to return with a NTIM_ERR (156) if the block could not be acquired within the specified timeout interval. Like a mutex, a block can be acquired by only one thread at a time.

Return

Value Symbolic Constant Explanation
0 NO_ERROR Successfully acquired block.
156 NTIM_ERR block in use by another thread. Timeout error.
636 TSYF_ERR block get failed.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Limitations

Can only be used with a ctThrd library.

See also

ctThrdBlockCls, ctThrdBlockRel, ctThrdBlockWait

 

ctThrdBlockInit

Initialize memory for a thread block.

Short Name

ctThrdBlockInit()

Type

Threading function

Declaration

NINT ctThrdBlockInit(pctBLOCK block) 

Description

ctThrdBlockInit() provides a means to initialize block. Before using a block the memory for the block must be cleared. If this space is initialized when allocated, this function is not needed.

However, if the block memory requires “zeroing out”, this function provides a convenient way to perform this task. This is most common when a block is defined on the stack within an application. In essence, this function simply initializes (memset()) the memory.

Return

ctThrdBlockInit() always returns NO_ERROR. See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Example

NINT      err;       /* ctThrdInit return code.            */

ctBLOCK   guiblk;    /* Block to wait for window creation. */

ctMUTEX   tfin_mtx;  /* Mutex for thread finished counter. */


#if (defined(USE_CURSES) || defined(USE_ANSI))

  ctMUTEX   tprt_mtx;  /* Mutex for displaying thread output.*/

#endif /* USE_CURSES || USE_ANSI */


if ((err = ctThrdInit(3,(LONG) 0,  (pctINIT)&cfg))) {

    ctrt_printf("\nctThrdInit failed. Error={%d}\n", err);

    ctrt_exit(1);

}


/* Initialize Blocks and Mutexes. */

    ctThrdBlockInit(&guiblk);

    ctThrdMutexInit(&tfin_mtx);


#if (defined(USE_CURSES) || defined(USE_ANSI))

    ctThrdMutexInit(&tprt_mtx);

#endif /* USE_CURSES || USE_ANSI */

See also

ctThrdMutexInit

 

ctThrdBlockRel

Releases a block.

Short Name

ctThrdBlockRel()

Type

Threading function

Declaration

NINT ctThrdBlockRel(pctBLOCK block) 

Description

Releases the block referenced by block. It is not necessary for the same thread that acquired the block to release it.

Return

Value Symbolic Constant Explanation
0 NO_ERROR Successful function.
637 TSYR_ERR block release failed.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Limitations

Can only be used with a ctThrd library.

See also

ctThrdBlockCls, ctThrdBlockGet, ctThrdBlockWait

 

ctThrdBlockWait

Wait for a block to clear.

Short Name

ctThrdBlockWait()

Type

Threading function

Declaration

NINT ctThrdBlockWait(pctBLOCK block, LONG timeout) 

Description

ctThrdBlockWait() behaves similarly to ctThrdBlockGet() except that it does not acquire the block. Rather, it simply waits until the block is not acquired by any thread before permitting the thread to continue. Any number of threads can attempt to wait on a block. Whether or not all waiting threads will successfully pass the block before another thread acquires the block is system dependent. To encourage this behavior, each thread successfully passing a block automatically yields to the other threads.

Return

Value Symbolic Constant Explanation
0 NO_ERROR Successfully acquired block.
156 NTIM_ERR block in use by another thread. Timeout error.
636 TSYF_ERR block get failed.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Limitations

Can only be used with a ctThrd library.

See also

ctThrdBlockCls, ctThrdBlockGet, ctThrdBlockRel

 

ctThrdCreate

Create a FairCom DB thread.

Short Name

ctThrdCreate()

Type

Threading function

Declaration

NINT ctThrdCreate(pctFUNC function, pVOID argument_list,

                  pVOID user_var, LONG mode)

Description

Create thread with entry point at function, arguments pointed to by argument_list, private thread data pointed to by user_var, and thread characteristics specified by mode, a bit-map where zero is the default. Currently, mode is ignored.

Return

Value Symbolic Constant Explanation
0 NO_ERROR Successful function.
10 SPAC_ERR Too much space required.
82 UALC_ERR Not enough memory.
95 STSK_ERR Could not start task.
600 CTHD_ERR Ran out of fixed threads or could not get new thread.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Example

See ctmtex.c and ctmtap.c for ctThrdCreate() examples.

Limitations

Can only be used with a ctThrd library.

See also

ctThrdInit, ctThrdExit

 

ctThrdData

Returns a pointer to a private data area.

Short Name

ctThrdData()

Type

Threading function

Declaration

 pVOID ctThrdData() 

Description

Returns a pointer to the private data area of the current thread, set up during ctThrdCreate(). A NULL return is possible if user_var was NULL at thread create, or if current thread does not appear to have been created within the context of the API.

For efficiency, if a function makes more than one reference to the private data area, a pointer to the area should be included on the functions stack and initialized by a call to this function.

Return

See Description.

Limitations

Can only be used with a ctThrd library.

See also

ctThrdDataSet, ctThrdCreate

 

ctThrdDataSet

Set a pointer to a private data area.

Short Name

ctThrdDataSet()

Type

Threading function

Declaration

NINT ctThrdDataSet(pVOID user_var) 

Description

Set the pointer to the private thread data area for the calling thread to user_var.

Return

Value Symbolic Constant Explanation
0 NO_ERROR Successful function.
535 REGC_ERR Not called from within a valid thread.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Limitations

Can only be used with a ctThrd library.

See also

ctThrdData

 

ctThrdDetach

Clean up the FairCom DB compatibility created with ctThrdAttach().

Short Name

ctThrdDetach()

Type

Threading function

Declaration

NINT ctThrdDetach(void) 

Description

If ctThrdDetach() is called for a thread made compatible by ctThrdAttach(), any memory allocated for control structures is returned.

If ctThrdDetach() is called for a thread that was not made compatible by ctThrdAttach(), ctThrdDetach() does nothing.

Calling ctThrdDetach() more than once for the same thread will have no affect.

Return

ctThrdDetach() always returns NO_ERROR. See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Example

 

NINT      retval4;

COUNT     retval2;


/* Assumes ctThrdInit is called in the main app thread */

NINT SampleThreadFunction( void )

{

    if (retval4 = ctThrdAttach()) {

        printf("\nError attaching thread: %d", retval4);

        return(retval4);

    }

    if (retval2 = InitISAM(3,50,32)) {

        printf("\nError initializing c-tree: %d", retval2);

        return(retval2);

    }

    dbWork();

    CloseISAM();

    ctThrdDetach();

    return(NULL);

}

See also

ctThrdInit, ctThrdAttach

 

ctThrdExit

Clean up thread.

Short Name

ctThrdExit()

Type

Threading function

Declaration

void ctThrdExit()

Description

Clean up thread.

Return

ctThrdExit() does not return.

Example

See ctmtex.c and ctmtap.c for ctThrdExit() examples.

Limitations

Can only be used with a ctThrd library.

See also

ctThrdInit, ctThrdCreate

 

ctThrdHandle

Returns a thread identifier.

Short Name

ctThrdHandle()

Type

Threading function

Declaration

NINT ctThrdHandle() 

Description

Returns a small thread identifier corresponding to the calling thread. This identifier can be reassigned to a new thread once the original thread goes away via ctThrdExit().

Return

See Description. On error, check sysiocod for the system level error return. See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Limitations

Can only be used with a ctThrd library.

See also

ctThrdInit, ctThrdExit

 

ctThrdInit

Initialize thread management.

Short Name

ctThrdInit()

Type

Threading function

Declaration

NINT ctThrdInit(NINT numthreads, LONG mode, pctINIT cfg) 

Description

ctThrdInit() initializes FairCom DB thread management. When using a multithreaded FairCom DB library, you must call ctThrdInit() before initializing FairCom DB.

mode is either zero or ctThrdFIXED_THREADS. In ctThrdFIXED_THREADS mode numthreads represents the fixed maximum number of threads available at one time. Otherwise, numthreads simply represents the number of threads allocated each time new threads are required.

cfg should be NULL for non-server applications. In the Bound Server Model, cfg points to a parameter block representing the FairCom Server configuration file options. If cfg is NULL, the bound FairCom Server, i.e., Custom Server, is initialized similarly to a standard FairCom Server.

Checking if ctThrdInit() Has Been Called

(In V11.5 and later) In the server, multi-threaded client, and multi-threaded standalone c-tree operational models, it is possible to determine if ctThrdInit() has already been called by calling ctThrdInit() as follows:

NINT rc;

rc = ctThrdInit(0,ctThrdCHECK_INIT,NULL);

When a mode of ctThrdCHECK_INIT is specified, ctThrdInit() returns a value of YES if a successful ctThrdInit() call has already been made and returns NO otherwise. In both cases it does not perform any initialization.

Failed Calls

With the c-tree database engine DLL model, a failed ctThrdInit() call due to insufficient memory resulted in exiting the process in prior releases. In this release and later, it is possible for an application to take its own actions when ctThrdInit() fails. When the database engine shutdown function is called due to an error occurring during a ctThrdInit() call, the function will return instead of exiting the process. The error code is returned to the caller.

Return

Value Symbolic Constant Explanation
0 NO_ERROR Successful thread initialization.
82 UALC_ERR Could not allocate memory.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Example

COUNT     retval2;

NINT      retval4;


if (retval4 = ctThrdInit(5, NULL, NULL)) {

    ctThrdTerm();

    return(retval4);

}

if ((retval2 = InitISAM(6, 25, 32)) {

    CloseISAM();

    return((NINT) retval2);

}

dbWork();

CloseISAM();

ctThrdTerm();

return(0)

Limitations

Required with a ctThrd library.

See also

ctThrdTerm

 

ctThrdLIFOWrite

Write a message at the beginning of a queue.

Short Name

ctThrdLIFOWrite()

Type

Threading function

Declaration

NINT ctThrdLIFOWrite(NINT qid, pVOID message, NINT msglen) 

Description

Write a message at the beginning of the queue specified by qid. It is permissible for the message to be NULL and/or the msglen to be zero.

Return

Value Symbolic Constant Explanation
0 NO_ERROR Successful function.
90 NQUE_ERR Invalid qid.
92 QMRT_ERR Queue memory error.
514 CQUE_ERR Queue could not be closed.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Limitations

Can only be used with a ctThrd library.

See also

ctThrdQueueClose, ctThrdQueueCount, ctThrdQueueOpen, ctThrdQueueMlen, ctThrdQueueRead, ctThrdQueueWrite

 

ctThrdLIFOWriteDirect

Short Name

ctThrdLIFOWriteDirect()

Type

Threading function

Declaration

NINT ctThrdLIFOWriteDirect(NINT qid, pVOID message, NINT msglen)

Description

ctThrdLIFOWriteDirect() adds the address for queue entry message of length msglen to the front of queue qid. Unlike ctThrdLIFOWrite(), which copies the contents of the entry into a buffer allocated by the queue write call, ctThrdLIFOWriteDirect() uses pointers to buffers created by the application to manage messages.

 

Note: The application is responsible for managing the buffers used in the ctThrdQueueReadDirect(), ctThrdQueueWriteDirect(), and ctThrdLIFOWriteDirect() calls. To avoid memory/buffer errors, FairCom recommends using either the original Queue read/write calls or the new direct calls, but not mixing calls from both pairs.

 

The return value is an error indicator.

Return Values

Value Symbolic Constant Explanation
0 NO_ERROR Successful queue write.
90 NQUE_ERR Invalid qid.
92 QMRT_ERR Queue memory error.
514 CQUE_ERR Queue could not be closed.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.See c-tree Plus Error Codes for a complete listing of valid c-tree Plus error values.

See Also

ctThrdQueueWriteDirect, ctThrdLIFOWrite

 

ctThrdMutexCls

Closes a mutex.

Short Name

ctThrdMutexCls()

Type

Threading function

Declaration

NINT ctThrdMutexCls(pctMUTEX mutex)

Description

Closes the mutex referenced by mutex, making it in active.

Return

ctThrdMutexCls() returns NO_ERROR. See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Example

See ctmtex.c and ctmtap.c for ctThrdMutexCls() examples.

Limitations

Can only close a mutex currently held by this thread with no other threads in contention. Can only be used with a ctThrd library.

See also

ctThrdMutexGet, ctThrdMutexTry

 

ctThrdMutexGet

Acquires a mutex.

Short Name

ctThrdMutexGet()

Type

Threading function

Declaration

NINT ctThrdMutexGet(pctMUTEX mutex) 

Description

A mutex is the most simple, efficient synchronization object supported by this API. A mutex must be released by the same thread that acquired it. ctThrdMutexGet() waits indefinitely to acquire the mutex. Only one thread can acquire a mutex at a time. The argument to ctThrdMutexGet() is the address of a mutex object of type ctMUTEX.

Return

On error, check sysiocod for the system level error return.

Value Symbolic Constant Explanation
0 NO_ERROR Successful function.
636 TSYF_ERR mutex get failed.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Example

ctMUTEX  tfin_mtx;

NINT      rc;


ctThrdMutexGet(&tfin_mtx);

rc = tfin;

ctThrdMutexRel(&tfin_mtx);

Limitations

Can only be used with a ctThrd library.

See also

ctThrdMutexTry, ctThrdMutexRel

 

ctThrdMutexInit

Initialize memory for a mutex.

Short Name

ctThrdMutexInit()

Type

Threading function

Declaration

NINT ctThrdMutexInit(pctMUTEX mutex) 

Description

ctThrdMutexInit() provides a means to initialize mutex. Before using a mutex the memory for the mutex must be cleared. If this space is initialized when allocated, this function is not needed, for example, internally within the FairCom DB code.

However, if the mutex memory requires “zeroing out”, this function provides a convenient way to perform this task. This is most common when a mutex is defined on the stack within an application. In essence, this function simply initializes (memset()) the memory.

Return

ctThrdMutexInit() always returns NO_ERROR. See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Example

NINT      err;       /* ctThrdInit return code.            */

ctBLOCK   guiblk;    /* Block to wait for window creation. */

ctMUTEX   tfin_mtx;  /* Mutex for thread finished counter. */


#if (defined(USE_CURSES) || defined(USE_ANSI))

  ctMUTEX   tprt_mtx;  /* Mutex for displaying thread output.*/

#endif /* USE_CURSES || USE_ANSI */


if ((err = ctThrdInit(3,(LONG) 0,  (pctINIT)&cfg))) {

    ctrt_printf("\nctThrdInit failed. Error={%d}\n", err);

    ctrt_exit(1);

}


/* Initialize Blocks and Mutexes. */

    ctThrdBlockInit(&guiblk);

    ctThrdMutexInit(&tfin_mtx);

#if (defined(USE_CURSES) || defined(USE_ANSI))

    ctThrdMutexInit(&tprt_mtx);

#endif /* USE_CURSES || USE_ANSI */

See also

ctThrdBlockInit

 

ctThrdMutexRel

Releases a mutex.

Short Name

ctThrdMutexRel()

Type

Threading function

Declaration

NINT ctThrdMutexRel(pctMUTEX mutex) 

Description

Releases the mutex pointed to by mutex, permitting other threads to contend for it.

Return

Value Symbolic Constant Explanation
0 NO_ERROR Successful function.
637 TSYR_ERR mutex release failed. Check sysiocod for system-level error return.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Example

pctMUTEX  tfin_mtx;

NINT      rc;


ctThrdMutexGet(&tfin_mtx);

rc = tfin;

ctThrdMutexRel(&tfin_mtx);

Limitations

Can only release a mutex currently held by this thread. Can only be used with a ctThrd library.

See also

ctThrdMutexGet, ctThrdMutexTry

 

ctThrdMutexTry

Try to acquire mutex immediately.

Short Name

ctThrdMutexTry()

Type

Threading function

Declaration

NINT ctThrdMutexTry(pctMUTEX mutex)

Description

ctThrdMutexTry() attempts to acquire the mutex immediately.

Return

If unsuccessful, ctThrdMutexTry() returns with a value of NTIM_ERR (156). If successful, ctThrdMutexTry() returns with a value of zero. On error, check sysiocod for the system level error return.

Value Symbolic Constant Explanation
0 NO_ERROR mutex not in use.
156 NTIM_ERR mutex in use by another thread. Timeout error.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Example

pctMUTEX  tfin_mtx;

NINT      rc;

COUNT     retry = 0;


while (ctThrdMutexTry(&tfin_mtx)) {

    if (retry < 1000) {

        ctThrdSleep((LONG) 50);

        retry ++;

    } else {

        return(-1);

}

rc = tfin;

ctThrdMutexRel(&tfin_mtx);

Limitations

Can only be used with a ctThrd library.

See also

ctThrdMutexGet, ctThrdMutexRel

 

ctThrdQueueClose

Close a message queue.

Short Name

ctThrdQueueClose()

Type

Threading function

Declaration

NINT ctThrdQueueClose(NINT qid) 

Description

Close the queue specified by the queue handle qid.

Return

Value Symbolic Constant Explanation
0 NO_ERROR Successful function.
90 NQUE_ERR Invalid qid.
514 CQUE_ERR Queue could not be closed.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Limitations

Can only be used with a ctThrd library.

See also

ctThrdQueueOpen, ctThrdQueueCount, ctThrdLIFOWrite, ctThrdQueueMlen, ctThrdQueueRead, ctThrdQueueWrite

 

ctThrdQueueCount

Returns the number of entries in a queue.

Short Name

ctThrdQueueCount()

Type

Threading function

Declaration

LONG ctThrdQueueCount(NINT qid) 

Description

Returns the number of entries in the queue qid. If an error occurs, ctThrdQueueCount() returns a negative value corresponding to the error code negated.

Return

See Description.

Value Symbolic Constant Explanation
0 NO_ERROR Successful function.
90 NQUE_ERR Invalid qid.
514 CQUE_ERR Queue could not be closed.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Limitations

Can only be used with a ctThrd library.

See also

ctThrdQueueClose, ctThrdQueueOpen, ctThrdLIFOWrite, ctThrdQueueMlen, ctThrdQueueRead, ctThrdQueueWrite

 

ctThrdQueueMlen

Returns the length of the message at the beginning of a queue.

Short Name

ctThrdQueueMlen()

Type

Threading function

Declaration

NINT ctThrdQueueMlen(NINT qid, LONG timeout) 

Description

Returns the length of the message at the head (beginning) of the queue, waiting up to timeout milliseconds if the queue is empty. Ordinarily, this call would be followed by a call to ctThrdQueueRead() with a zero timeout. If ctThrdLIFOWrite is used, ctThrdQueueMlen() is of little value because the head of the queue can change before the message length primitive can be OR-ed in a subsequent queue read.

Return

Value Symbolic Constant Explanation
0 NO_ERROR Successful function.
90 NQUE_ERR Invalid qid.
156 NTIM_ERR block in use by another thread. Timeout error.
514 CQUE_ERR Queue could not be closed.
636 TSYF_ERR block get failed.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Example

See ctmtap.c for ctThrdQueueMlen() examples.

Limitations

Can only be used with a ctThrd library.

See also

ctThrdQueueClose, ctThrdQueueCount, ctThrdLIFOWrite, ctThrdQueueOpen, ctThrdQueueRead, ctThrdQueueWrite

 

ctThrdQueueOnClose

Short Name

ctThrdQueueOnClose()

Type

Threading function

Declaration

NINT ctThrdQueueOpen()NINT ctThrdQueueOnClose(NINT qid,void (*onClose)(void * buffer, NINT msglen))

Description

ctThrdQueueOnClose() sets a function pointer onClose, which is called during ctThrdQueueClose() for each message that remains in the queue. This allows for processing of any final messages if the close is not otherwise synchronized with writes to the queue. For non-direct messages (such as written using ctThrdQueueWrite), the buffer passed to the registered callback is managed by ctThrdQueueClose() and should not be freed by the callback.

Note: The application is responsible for managing the buffers written by the ctThrdQueueWriteDirect(), and ctThrdLIFOWriteDirect() calls. To avoid memory/buffer errors, use either the original Queue read/write calls or the direct calls, but do not mix calls from both pairs.

Passing a function pointer replaces any previously set callback. Using a NULL function pointer removes the callback.

The returned value is an error indicator.

Return Values

Value Symbolic Constant Explanation
0 NO_ERROR Successful function.
90 NQUE_ERR Invalid qid.
514 CQUE_ERR Queue is closed.

See c-tree Plus Error Codes for a complete listing of valid c-tree Plus error values.

See Also

ctThrdQueueOpen, ctThrdQueueClose

 

ctThrdQueueOpen

Open a message queue.

Short Name

ctThrdQueueOpen()

Type

Threading function

Declaration

NINT ctThrdQueueOpen()

Description

ctThrdQueueOpen() opens a queue returning a small queue handle used as the queue identifier in the other queue calls. Any number of queues may be opened.

Return

ctThrdQueueOpen() returns the queue handle. On failure, it returns the error code as a negative value. Typically a queue open will fail only if insufficient memory exists for the queue control structures.

Value Symbolic Constant Explanation
0 NO_ERROR Successful function.
10 SPAC_ERR Too much space required.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Example

See ctmtap.c for ctThrdQueueOpen() examples.

Limitations

Can only be used with a ctThrd library.

See also

ctThrdQueueClose, ctThrdQueueCount, ctThrdLIFOWrite, ctThrdQueueMlen, ctThrdQueueRead, ctThrdQueueWrite

 

ctThrdQueueRead

Read a queue message.

Short Name

ctThrdQueueRead()

Type

Threading function

Declaration

NINT ctThrdQueueRead(NINT qid, pVOID buffer, NINT buflen, LONG timeout) 

Description

Read a queue message into buffer with maximum length buflen. If buffer is NULL and/or buflen is smaller than the actual message, the message is still removed from the queue, and as much as possible is placed into the buffer.

Return

In the case of a NULL or an insufficient buffer, ctThrdQueueRead() returns TQUE_ERR (638). If no message is available to be read within the interval specified in milliseconds by the timeout parameter, ctThrdQueueRead() returns NTIM_ERR (156). If more than one thread is reading the queue with an intermediate timeout parameter, i.e., greater than ctNOWAIT and less than ctWAITFOREVER, the length of time before a NTIM_ERR is returned is not accurate and such usage should not be attempted.

Value Symbolic Constant Explanation
0 NO_ERROR Successful function.
90 NQUE_ERR Invalid qid.
156 NTIM_ERR block in use by another thread. Timeout error.
514 CQUE_ERR Queue could not be closed.
636 TSYF_ERR block get failed.
638 TQUE_ERR Queue message truncated to fit.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Example

See ctmtap.c for ctThrdQueueRead() examples.

Limitations

Can only be used with a ctThrd library.

See also

ctThrdQueueClose, ctThrdQueueCount, ctThrdLIFOWrite, ctThrdQueueMlen, ctThrdQueueOpen, ctThrdQueueWrite

 

ctThrdQueueReadDirect

Read a queue message pointer.

Short Name

ctThrdQueueReadDirect()

Type

Threading function

Declaration

NINT ctThrdQueueReadDirect(NINT qid, pVOID msgadr,

                           pNINT pmsglen, LONG timeout)

Description

ctThrdQueueReadDirect() places the address of the next message from queue qid into msgadr, and places the length of the message in pmsglen. ctThrdQueueReadDirect() does not copy the message contents.

Note: Your application is responsible for managing the buffers used in the read and write calls. To avoid memory/buffer errors, FairCom recommends using either the original Queue read/write calls or the new direct calls, but not mixing calls from both pairs.

The return value is an error indicator.

Return

Value Symbolic Constant Explanation
0 NO_ERROR Successful convert.
90 NQUE_ERR Invalid qid.
156 NTIM_ERR Timeout error.
514 CQUE_ERR Queue could not be closed.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

See also

ctThrdQueueRead, ctThrdQueueWriteDirect

 

ctThrdQueueWrite

Write a queue message.

Short Name

ctThrdQueueWrite()

Type

Threading function

Declaration

NINT ctThrdQueueWrite(NINT qid, pVOID message, NINT msglen) 

Description

Write a queue message to the end of the queue specified by queue handle qid. It is permissible for the message to be NULL and/or the msglen to be zero.

Return

Value Symbolic Constant Explanation
0 NO_ERROR Successful function.
90 NQUE_ERR Invalid qid.
92 QMRT_ERR Queue memory error.
514 CQUE_ERR Queue could not be closed.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Example

See ctmtap.c for ctThrdQueueWrite() examples.

Limitations

Can only be used with a ctThrd library.

See also

ctThrdQueueClose, ctThrdQueueCount, ctThrdLIFOWrite, ctThrdQueueMlen, ctThrdQueueRead, ctThrdQueueOpen

 

ctThrdQueueWriteDirect

Write a queue message pointer.

Short Name

ctThrdQueueWriteDirect()

Type

Threading function

Declaration

NINT ctDECL ctThrdQueueWriteDirect(NINT qid, pVOID message, NINT msglen)

Description

ctThrdQueueWriteDirect() adds the address for queue entry message of length msglen to the queue qid. Unlike ctThrdQueueWrite(), which copies the contents of the entry into a buffer allocated by the queue write call, ctThrdQueueWriteDirect(). Uses pointers to buffers created by the application to manage messages.

Note: The application is responsible for managing the buffers used in the ctThrdQueueReadDirect() and ctThrdQueueWriteDirect() calls. To avoid memory/buffer errors, FairCom recommends using either the original Queue read/write calls or the new direct calls, but not mixing calls from both pairs.

The return value is an error indicator.

Return

Value Symbolic Constant Explanation
0 NO_ERROR Successful queue write.
90 NQUE_ERR Invalid qid.
92 QMRT_ERR Queue memory error.
514 CQUE_ERR Queue could not be closed.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

See also

ctThrdQueueWrite, ctThrdQueueReadDirect, ctThrdLIFOWrite

 

ctThrdSemapCls

Close a semaphore.

Short Name

ctThrdSemapCls()

Type

Threading function

Declaration

NINT ctThrdSemapCls(pctSEMAP semap)

Description

Close semaphore semap, making it inactive.

Return

Value Symbolic Constant Explanation
0 NO_ERROR Successful function.
90 NQUE_ERR Invalid qid.
514 CQUE_ERR Queue could not be closed.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Limitations

Can only be used with a ctThrd library.

See also

ctThrdSemapGet, ctThrdSemapInit, ctThrdSemapRel, ctThrdSemapTry

 

ctThrdSemapGet

Get one unit of a semaphore.

Short Name

ctThrdSemapGet()

Type

Threading function

Declaration

NINT ctThrdSemapGet(pctSEMAP semap) 

Description

Attempts to get one unit of the semaphore referenced by semap. The thread will block indefinitely until a unit of the semaphore is available.

Return

Value Symbolic Constant Explanation
0 NO_ERROR Successful function.
90 NQUE_ERR Invalid qid.
156 NTIM_ERR block in use by another thread. Timeout error.
514 CQUE_ERR Queue could not be closed.
636 TSYF_ERR block get failed.
638 TQUE_ERR Queue message truncated to fit.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Limitations

Can only be used with a ctThrd library.

See also

ctThrdSemapCls, ctThrdSemapInit, ctThrdSemapRel, ctThrdSemapTry

 

ctThrdSemapInit

Initialize a semaphore.

Short Name

ctThrdSemapInit()

Type

Threading function

Declaration

NINT ctThrdSemapInit(pctSEMAP semap, NINT count) 

Description

A semaphore is a synchronization object that may be acquired by more than one thread at a time, and may be released by a thread that has not acquired it. The count parameter specifies the maximum number of threads that may acquire it simultaneously. The semap parameter is the address of an object of type ctSEMAP.

Return

Value Symbolic Constant Explanation
0 NO_ERROR Successful function.
10 SPAC_ERR Too much space required.
639 TZRO_ERR count < 1.
640 TINT_ERR Semaphore already initialized.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Limitations

Can only be used with a ctThrd library.

See also

ctThrdSemapCls, ctThrdSemapGet, ctThrdSemapRel, ctThrdSemapTry

 

ctThrdSemapRel

Release one unit of a semaphore.

Short Name

ctThrdSemapRel()

Type

Threading function

Declaration

NINT ctThrdSemapRel(pctSEMAP semap) 

Description

Release one unit of semaphore semap.

Return

Value Symbolic Constant Explanation
0 NO_ERROR Successful function.
90 NQUE_ERR Invalid qid.
92 QMRT_ERR Queue memory error.
156 NTIM_ERR Timeout, no unit available for semaphore semap.
514 CQUE_ERR Queue could not be closed.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Limitations

Can only be used with a ctThrd library.

See also

ctThrdSemapCls, ctThrdSemapGet, ctThrdSemapInit, ctThrdSemapTry

 

ctThrdSemapTry

Try once to get one unit of a semaphore.

Short Name

ctThrdSemapTry()

Type

Threading function

Declaration

NINT ctThrdSemapTry(pctSEMAP semap) 

Description

Same as ctThrdSemapGet() except that if no unit of the semaphore is available, ctThrdSemapTry() returns NTIM_ERR (156).

Return

Value Symbolic Constant Explanation
0 NO_ERROR Successful function.
90 NQUE_ERR Invalid qid.
156 NTIM_ERR block in use by another thread. Timeout error.
514 CQUE_ERR Queue could not be closed.
636 TSYF_ERR block get failed.
638 TQUE_ERR Queue message truncated to fit.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Limitations

Can only be used with a ctThrd library.

See also

ctThrdSemapCls, ctThrdSemapGet, ctThrdSemapIni, ctThrdSemapRel

 

ctThrdSleep

Sleep a thread for a given time.

Short Name

ctThrdSleep()

Type

Threading function

Declaration

NINT ctThrdSleep(LONG milliseconds) 

Description

Sleep thread for specified milliseconds, 1000 milliseconds equivalent to 1 second. A sleep of zero duration acts as a yield to other threads.

Return

ctThrdSleep() returns NO_ERROR. See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Example

See ctmtex.c and ctmtap.c for ctThrdSleep() examples.

Limitations

Can only be used with a ctThrd library.

See also

ctThrdInit

 

ctThrdTerm

Terminate threading support.

Short Name

ctThrdTerm()

Type

Threading function

Declaration

NINT ctThrdTerm(void) 

Description

Terminate threading support. All open queues are closed and control variables are reset to zero.

Return

ctThrdTerm() returns NO_ERROR. See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Example

COUNT     retval2;

NINT      retval4;


if (retval4 = ctThrdInit(5, NULL, NULL)) {

    ctThrdTerm();

    return(retval4);

}

if ((retval2 = InitISAM(6, 25, 32)) {

    CloseISAM();

    return((NINT) retval2);

}

dbWork();

CloseISAM();

ctThrdTerm();

return((NINT) 0);

Limitations

Can only be used with a ctThrd library.

See also

ctThrdInit

 

ctTransferFile

Transfers a file between a FairCom DB client and server. This function works on non-c-tree files as well as c-tree files.

Declaration

LONG ctTransferFile(pctXFRFIL pxfr);

Description

The FairCom DB API function ctTransferFile() is used to transfer a file between a FairCom DB client and the FairCom DB database server.

Note:

  • The file transfer function allows the calling client process to read the contents of any c-tree or non-c-tree file that the operating system allows the c-tree Server process to open for read access.
  • The file transfer function allows the calling client to write to any c-tree or non-c-tree file that the operating system allows the c-tree Server process to open for write access.
  • pxfr is a pointer to a file transfer request structure, which is defined as follows in FairCom DB V10.3.1 and later:

typedef struct ctxfrfil {

 LONG    ver;     /* Version of this structure    */

 LONG    mode;    /* Transfer mode                */

 pTEXT   srcnam;  /* Name of source file          */

 pTEXT   dstnam;  /* Name of destination file     */

 LONG    blksiz;  /* Transfer block size          */

 LONG    ackint;  /* Acknowledgment interval      */

 pXFRFNC xfrfnc;  /* File transfer callback func  */

 pXFRINF xfrinf;  /* File transfer callback data  */

 pVOID   xfrufn;  /* File transfer user callback  */

 pVOID   xfrudt;  /* File transfer user data      */

} ctXFRFIL;

For security reasons, this feature is disabled, by default, and requires the calling user to be a member of the ADMIN group. To enable this feature, specify the following in the FairCom DB configuration file:

ENABLE_TRANSFER_FILE_API YES

A NSUP_ERR error code is returned if ENABLE_TRANSFER_FILE_API YES is not in ctsrvr.cfg.

To allow a non-ADMIN user to call ctTransferFile() specify the following configuration keyword:

COMPATIBILITY NONADMIN_TRANSFER_FILE_API

To use the file transfer function, allocate a ctXFRFIL structure and set its fields as follows:

  • ver - The version structure ctXFRFIL_VERS_CUR.

Note: Future updates to the ctTransferFile() function might change this structure. An application must set the version field of the structure to the macro ctXFRFIL_VERS_CUR, which c-tree defines to its current version of the file transfer request structure definition.

  • mode - Set to one of the following:

#define ctXFRFIL_SEND   0x00000001  /* send file to server             */

#define ctXFRFIL_RECV   0x00000002  /* receive file from server        */

 

#define ctXFRFIL_RAW    0x00000004  /* raw file transfer               */

#define ctXFRFIL_CTREE  0x00000008  /* c-tree file transfer            */

 

#define ctXFRFIL_OVRWRT 0x00000010  /* overwrite existing file         */

 

#define ctXFRFIL_MASTER 0x00000020  /* perform transfer with master    */

 

#define ctXFRFIL_CLBK   0x00000040  /* use callback function           */

#define ctXFRFIL_CREDIR 0x00000080  /* create non-existent directories */

#define ctXFRFIL_CPYFIL 0x00000100  /* used for remote file copy       */

OR in the ctXFRFIL_OVRWRT option if you wish the destination file to be overwritten if it exists.

  • srcnam - The source file name. When sending a file, this is the name of the file on the client system that the client reads and sends to the server. When receiving a file, this is the name of the file on the server system that the server reads and sends to the client.
  • dstnam - The destination file name. When sending a file, this is the name of the file on the server system that the server creates and writes with the data received from the client. When receiving a file, this is the name of the file on the client system that the client creates and writes with the data received from the server.
  • blksiz - The block size, in bytes, to be used when transferring the file. A buffer of the specified block size is allocated by both the client and server processes.
  • ackint - The acknowledgment interval. A value of 0 or 1 causes the receiving process to send an acknowledgment message to the sending process after each file transfer message it receives. A value greater than 1 causes the receiving process to send an acknowledgment only after receiving the specified number of file transfer messages from the sending process. This option is ignored for shared memory connections.

Important: The file transfer ctXFRFIL_OVRWRT mode causes the specified destination file to be overwritten, so if the destination file exists before the file transfer, its original contents are lost (replaced by the transferred data).

Return

Value Symbolic Constant Explanation
0 NO_ERROR Successful operation.
454 NSUP_ERR Operation or service not supported. Using an option unavailable to this library.
871 XFR_SOPN_ERR The file transfer operation failed because the source file could not be opened for reading. Check sysiocod for the system error code.
872 XFR_DOPN_ERR The file transfer operation failed because the destination file could not be opened for writing. Check sysiocod for the system error code.
873 XFR_READ_ERR The file transfer operation failed because the source file could not be read. Check sysiocod for the system error code.
874 XFR_WRITE_ERR The file transfer operation failed because the destination file could not be written. Check sysiocod for the system error code.
875 XFR_BCON_ERR A bound database connection called the file transfer function, but this function is supported for client connections only.
876 XFR_BSIZ_ERR The file transfer operation failed because the caller specified an invalid file transfer block size.
877 XFR_SFNM_ERR The file transfer operation failed because the caller specified a NULL or empty source file name.
878 XFR_DFNM_ERR The file transfer operation failed because the caller specified a NULL or empty destination file name.
879 XFR_VER_ERR The version of the file transfer structure supplied by the caller is not compatible with the c-tree library's structure definition. Check sysiocod for the required file transfer structure version.
880 XFR_DEXS_ERR The file transfer operation failed because the destination file exists and the caller did not specify that the destination file is to be overwritten.
881 XFR_TREP_ERR The file transfer operation between a local and master server failed because the server does not support the transactional replication feature.
882 XFR_TRLC_ERR The file transfer operation between a local and master server failed because the server is not configured as a local server. Use the REPL_MAPPINGS configuration keyword option to configure the server as a local server.
454    

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Example

pctXFRFL xferfile;

char srcnam[80];

char dstnam[80];


NINT rc = 0;


memset(srcnam, 0, 80);

memset(dstnam, 0, 80);


strcpy(srcnam, "custmast.dat");

strcpy(dstnam, "custmast.dat");


xferfile = (pctXFRFL) malloc (sizeof(ctXFRFL));

if (!xferfile)

Handle_Error("Bad malloc on xferfile", 0);


xferfile->ver = ctXFRFL_CUR;

xferfile->mode = ctXFRFIL_RECV | ctXFRFIL_OVRWRT;

xferfile->srcnam = srcnam;

xferfile->dstnam = dstnam;

xferfile->blksiz = 32768;

xferfile->ackint = 0;


rc = ctTransferFile(xferfile);

if (rc)

Handle_Error("File transfer failed.", rc);

 

ctTruncateFile

ctTruncateFile() truncates a data file, meaning a new copy of the file is created with no data records. File properties and resources are preserved.

Type

ISAM Function

Declaration

NINT ctDECL ctTruncateFile(pTEXT filename,pTEXT fileword);

Description

  • filename - name of the file.
  • fileword - (optional) file password.

Return

This function requires the caller to have write access to data file, otherwise it returns error 54 (REDF_ERR, attempt to write a read only file).

Limitations

Requires data file to have an IFIL resource; otherwise, the function call fails with error RNOT_ERR (408, resource not found).

 

ctu16TOu8

Converts a UTF16 Unicode string to a UTF8 encoded string.

Short Name

ctu16TOu8()

Type

Utility

Declaration

NINT ctu16TOu8(pWCHAR u16str, pTEXT u8str, VRLEN u8byt) 

Description

ctu16TOu8() converts a UTF16 Unicode string to a UTF8 encoded string. The input strings are assumed to be terminated by a NULL character. All output buffer sizes are specified in bytes.

Return

Value Symbolic Constant Explanation
0 NO_ERROR Successful convert.
153 VBSZ_ERR The output buffer is too small.
446 BMOD_ERR There is a problem with the input string.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

See also

ctu8TOu16

 

ctu8TOu16

Converts an ASCII or UTF8 Unicode string to a UTF16 encoded string.

Short Name

ctu8TOu16()

Type

Utility

Declaration

NINT ctu8TOu16(pTEXT u8str, pWCHAR u16str, VRLEN u16byt) 

Description

ctu8TOu16() converts an ASCII or UTF8 Unicode string to a UTF16 encoded string. The input strings are assumed to be terminated by a NULL character. All output buffer sizes are specified in bytes.

Return

Value Symbolic Constant Explanation
0 NO_ERROR Successful convert.
153 VBSZ_ERR The output buffer is too small.
446 BMOD_ERR There is a problem with the input string.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

See also

ctu16TOu8

 

ctUPDICU

ctUPDATICU() allows a user to update the Unicode version stored in the resource of their files.

Declaration

NINT ctUpdateICUversion(pTEXT filnam,pTEXT fileword)

NINT ctUPDATICU(pTEXT filnam,pTEXT fileword)

Type

ISAM function

Description

ctUPDATICU() takes the name of a data file containing IFIL resources and an optional password and attempts to open the file and associated indexes exclusively, skipping the ICU version check. If the open succeeds, then the data file and associated indexes have their UNICODE resource version changed to agree with the current ICU library version, and indexes that reference the ICU resources are marked for rebuild.

  • filenam is the name of the file to update
  • fileword is the file password assigned, NULL if not assigned

Return Values

ctUPDATICU() returns NO_ERROR (0) if the files are opened successfully, and no ICU version mismatch is found.

Value Symbolic Constant Explanation
-828 ICUV_COD One or more ICU resources had versions updated, but no index was found that used ICU segments.
-829 ICUV_REB ICU version updates, and one or more indices marked for rebuild.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Example


#include ctreep.h


NINT rc = 0;

char[255] filename;

strncpy(filename, "mydata.dat", 10);


/* Initialize FairCom DB */

rc = (InitISAMXtd(16, 16, 16, 16, 0, "ADMIN", "ADMIN", "FAIRCOMS"))

if (rc)

    printf("ctree failed to initialize with error %d", rc);


/* block the data file mydata.dat and associated indexes */

rc = ctUPDTICU(filename, NULL);

if (rc) {

    printf("ctUPDTICU returned with with condition %d", filename, rc);


    /* If ICUV_REB, then the indexes require rebuild */

    if (ICUV_REB == rc)

        printf("One or more indexes marked for rebuild.\n");

}


CloseISAM();
 

exit(0);

 

ctVerifyFile

This ISAM-level function verifies the total integrity of a FairCom DB data file and its associated index files.

Function Name

NINT ctVerifyFile(pctVFYFIL pvfyfil);

Type

ISAM-level function

Description

  • pvfyfil points to a ctVFYFIL structure (see ctport.h)

typedef struct ctvfyfil {

    LONG    verson;          /* Version of this structure.             */

    LONG    options;         /* Which operations to perform.           */

    LONG    errbufsiz;       /* Size of optional error message buffer. */

    LONG    chkkey;          /* Index files to check (0=all, 1=first

                                index in IFIL, 2=second index, etc).   */

    pTEXT   datnam;          /* Name of data file to check.            */

    pTEXT   fileword;        /* Optional data file password.           */

    pVFYMSGCBFNC fnmessage;  /* Optional message callback function.    */

    pVFYPRGCBFNC fnprogress; /* Optional progress callback function.   */

    pVFYERRCBFNC fnerror;    /* Optional progress callback function.   */

    pTEXT    errbuf;         /* Optional error message buffer.         */

} ctVFYFIL, *pctVFYFIL;
 

An optional callback can be called from the fnprogress structure member.

Supported options

ctVFopenExclusive Open the files in exclusive mode. Otherwise, the files are opened in read-only mode, allowing other connections to also open the file in read-only mode.
ctVFchkDataOnly Read the data file in physical order, not checking keys.
ctVFchkDataWithKeys Read the data file in physical order and check that each index contains the key built from the record image.
ctVFchkIndexInternals Perform more thorough index validations for unusual problems.
ctVFchkIndexOnly Read the index file in key order and don't check the key built from the record image.
ctVFchkIndexWithRecord Read the index file in key order and check that the key built from the record image matches the key in the index.
ctVFchkDeletedSpace Scan a data files delete stack or space management index verifying each deleted space entry corresponds to a deleted (not active) record.
ctVFYFILspaceStart Deleted space scan is starting. (for use with a callback)
ctVFYFILspacePct Deleted space scan in progress, with the pct parameter indicating approximate percent complete. (for use with a callback)
ctVFYFILspaceEnd Deleted space scan has completed. (for use with a callback)

Note: ctVerifyFile() requires exclusive access to the file (ctVFopenExclusive). The only exception is the ctVFchkDeletedSpace option, which does not require exclusive access.

The source code for the accompanying ctvfyfil utility provides a good example showing how to use the ctVerifyFile() function.

Note: When a user-defined ctVerifyFile() error callback function returns a non-zero error code so that it can cancel the verification operation, ctVerifyFile() returns the c-tree error code and system error code for the error that triggered that call to the error callback function.

See Also

 

ctVERIFYidx

A Low-Level FairCom Server enhanced version of the ctVERIFY() function. It can be called in either client or standalone mode.

Function Name

NINT  ctVERIFYidx(FILNO keyno, pctVFYIDXin pvfyin, pctVFYIDXout pvfyout);

Type

Low-Level file function

Description

  • keyno is the file number of an index files that the caller has opened. In V12 the file number typedef was formally changed from COUNT, a two-byte value to FILNO, a four-byte value. Refer to this link for compatibility details. Four Byte File Numbering
  • pvfyin points to an input parameter structure. (ctVFYIDXin; see ctport.h)
  • pvfyout points to an output parameter structure containing index statistics returned by the function. (ctVFYIDXout see ctport.h)

Review ctvfyidx utility source code for an example demonstrating a call to the ctVERIFYidx() function.

ctVERIFYidx() calls the progress callback function with the start bit before its first call to the message callback function.

In V10.3.1 and later, ctVERIFYidx requires the file to be open in ctEXCLUSIVE mode or in ctREADFIL (read only) mode to ensure it does not incorrectly report errors if other users make changes while the verification is running. Opening with ctSHARED will fail with LERR_ERR. A ctREADFIL open will fail with error 12 and sysiocod ‑8 if any connection has the file open for write access.

A call is made to CTFLUSH on the index prior to leaf verification to ensure all changes are on disk. In some cases, such as for SUPERFILE members, CTFLUSH can fail. An error message is logged, but the verification will continue. In this case, a VRFY_ERR could indicate the existence of updated index nodes in cache. The application should ensure that the data has been properly flushed.

Input parameters

typedef struct ctvfyidxin {

    LONG    verson;            /* version of this structure            */

    LONG    action;             /* operations to perform, see below     */

    LONG    maxnod;             /* maximum node counts in output buf    */

    TEXT    flags;              /* options to pass to server            */

    TEXT    pad[3];             /* padding                              */

    pVFYMSGCBFNC    fnmessage;  /* optional message callback function   */

    pVFYPRGCBFNC    fnprogress; /* optional progress callback func      */

} ctVFYIDXin, *pctVFYIDXin;
 

ctVFYIDXin.action is a bitmask of the following options:

#define ctVFYIDXdelstk  0x00000001  /* check delete stack       */

#define ctVFYIDXlink    0x00000002  /* check links              */

#define ctVFYIDXleaf    0x00000004  /* check leaf nodes         */

#define ctVFYIDXchkkey  0x00000008  /* check keys in leaf nodes */

#define ctVFYIDXspace   0x00000040  /* analyze space usage. physical index only - added V12 */

 

The following fields should be initialized to a macro or fixed value.

ctVFYIDXin.version = ctVFYIDX_VERS_CUR;

ctVFYIDXin.maxnod = VFYLEV;

ctVFYIDXin.flags = 0;

 

As of V12 current version is ctVFYIDX_VERS_V02.

Output parameters

 

typedef struct ctvfyidxout {

  LONG smtynod;  /* number of empty nodes                   */

  LONG sbadnod;  /* number of bad nodes                     */

  LONG sununod;  /* number of unused nodes                  */

  LONG sresnod;  /* number of resource pages                */

  LONG smisnod;  /* number of misaligned nodes              */

  LONG sbadlnk;  /* number of bad links                     */

  LONG lostnod;  /* number of lost nodes - added V12        */

  LONG snodcnt[VFYLEV]; /* node count at each level of tree */

} ctVFYIDXout, *pctVFYIDXout;

Return

ctVERIFYidx() returns NO_ERROR on success or a non-zero error code on failure. Error code VRFY_ERR (601) indicates that the verification ran to completion but it detected one or more discrepancies.

The client-side progress function can return a non-zero error code to cause the c-tree Server to terminate the index verify operation. In that case, ctVERIFYidx() returns error code VFYTRM_ERR (910, a user-defined callback function terminated the index verify operation).

When a user-defined ctVerifyFile() error callback function returns a non-zero error code so that it can cancel the verification operation, ctVerifyFile() returns the c-tree error code and system error code for the error that triggered that call to the error callback function.

VFYVER_ERR (909) is returned if a client compiled with this change calls ctVERIFYidx() against an older server while specifying ctVFYIDX_VERS_V02. It is possible to obtain backwards compatibility by having the new client specify ctVFYIDXin.version = ctVFYIDX_VERS_V01, and providing a pvfyout buffer of the older type, now available as: typedef struct ctvfyidxout_v1 ctVFYIDXoutV1. Older clients will continue working with newer servers.

See Also

ctVerifyFile (ctVerifyFile, ctVerifyFile)

 

CurrentFileOffset

Returns the byte position, (file address or offset), of the current ISAM record for the specified file.

Short Name

GETCURP()

Type

ISAM function

Declaration

LONG CurrentFileOffset(FILNO datno); 

Description

In V12 the file number typedef was formally changed from COUNT, a two-byte value to FILNO, a four-byte value. Refer to this link for compatibility details. Four Byte File Numbering

CurrentFileOffset() returns the byte position, (file address), of the current ISAM record for file datno. Use this if you need to access the current ISAM record with a Low-Level function.

This function has been optimized for the client/server model by maintaining the current record pointer information on the client side in addition to the Server side. When CurrentFileOffset() is used with the client/server model, the client is able to retrieve the necessary value from the local machine in most cases. This reduces network traffic and increases performance.

This function is typically used when switching from ISAM to Low-Level work. When switching back to ISAM level, be sure to call one of the functions in “See Also” below to reset the ISAM buffers.

Return

CurrentFileOffset() returns the byte position of the current ISAM record. Zero is returned if there is no current ISAM record for the specified datno, or if an error occurs. On a zero return, check isam_err for a non-zero value indicating the error. See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Example

FILNO     datfil;

TEXT      recbuf[320];


if (FirstRecord(datfil,recbuf) == NO_ERROR)

    printf("\nfirst Record is at %ld",

           CurrentFileOffset(datfil));

Limitations

The recbyt parameter in this function is a 4-byte value capable of addressing at most 4 gigabytes. If your application supports HUGE files (greater than 4 gigabytes), you must use the ctSETHGH() and ctGETHGH() functions to set or get the high-order 4 bytes of the file offset. For more information, see Record Offsets Under Huge File Support.

See also

SetRecord, ReadISAMData, GetRecord

 

CurrentISAMKey

Create an ISAM key from the current ISAM record.

Short Name

GETCURK()

Type

ISAM function

Declaration

pVOID CurrentISAMKey(FILNO keyno, pVOID idxval, pVRLEN plen);

Description

In V12 the file number typedef was formally changed from COUNT, a two-byte value to FILNO, a four-byte value. Refer to this link for compatibility details. Four Byte File Numbering

CurrentISAMKey() looks at the current ISAM key buffer for index file keyno and creates a well formed ISAM key. This key is placed at idxval. The length of the key is placed at plen, if plen is not NULL. The ISAM key created with CurrentISAMKey() includes the 4-byte or 8-byte suffix for duplicate keys.

Return

CurrentISAMKey() returns a pointer to the key value. A NULL signifies an error or no current key exists.

Warning: The key buffer is filled with garbage when the return value is NULL on server calls, but non-server calls do not touch the key buffer on NULL returns. Check isam_err for the following error codes on a NULL return.

Value Symbolic Constant Explanation
0 NO_ERROR Successful retrieval of current ISAM record.
22 FNUM_ERR keyno out of range.
26 FACS_ERR keyno is not active.
48 FMOD_ERR keyno does not reference an index file.

See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Example

FILNO keyfil;

TEXT  keybuf[50];

VRLEN keylen;


if (CurrentISAMKey(keyfil,&keybuf,&keylen) == NULL)

   printf("\nError %d with file %d",isam_err,isam_fil);

Limitations

No check is made to determine if idxval points to a region sufficiently large to accept a key. If the area is too small, either code or data will be clobbered. Use GetCtFileInfo() to obtain the key length.

Note, the key value returned by this function will be a properly formatted key value (i.e., HIGH_LOW order, forced to upper case, etc.). The main issue this presents is if binary key values will be displayed on a LOW_HIGH machine, it will be necessary to reverse any numeric segments.

See also

GetCtFileInfo

 

CurrentLowLevelKey

Get a key from the current Low-Level key buffer.

Short Name

GETCURKL()

Type

Low-Level function

Declaration

pVOID CurrentLowLevelKey(FILNO keyno, pVOID idxval); 

Description

In V12 the file number typedef was formally changed from COUNT, a two-byte value to FILNO, a four-byte value. Refer to this link for compatibility details. Four Byte File Numbering

CurrentLowLevelKey() copies the current Low-Level key buffer for index file keyno into the buffer pointed to by idxval.

Return

CurrentLowLevelKey() returns idxval. A NULL signifies an error - check uerr_cod. See FairCom DB Error Codes for a complete listing of valid FairCom DB error values.

Example

FILNO keyfil;

TEXT  keybuf[50];


if (CurrentLowLevelKey(keyfil,&keybuf) == NULL)

   printf("\nError %d retrieving key.", uerr_cod);

Limitations

No check is made to determine if idxval points to a region sufficiently large to accept the key. If the area is too small, either code or data will be clobbered. Use GetCtFileInfo() to obtain the key length.

See also

CurrentISAMKey, GetCtFileInfo