Ctreedb
Ctreedb
V9
c-treeDB
C API Developer's Guide
c-treeDB
C API Developer's Guide
Copyright 1992-2008 FairCom Corporation All rights reserved. No part of this publication may be stored in a retrieval system, or transmitted in any form or by any means, electronic, mechanical, photocopying, recording or otherwise without the prior written permission of FairCom Corporation. Printed in the United States of America. Information in this document is subject to change without notice.
Trademarks
c-tree, c-tree Plus, r-tree, the circular disk logo, and FairCom are registered trademarks of the FairCom Corporation. c-treeACE SQL, c-treeACE SQL ODBC, c-treeACE SQL ODBC SDK, c-treeVCL/CLX, c-tree ODBC Driver, c-tree Crystal Reports Driver, c-treeDBX, and c-treePHP are trademarks of FairCom Corporation. The following are third-party trademarks: AMD and AMD Opteron are trademarks of Advanced Micro Devices, Inc. Macintosh, Mac OS, and Xcode are trademarks of Apple Inc., registered in the U.S. and other countries. Borland, the Borland Logo, Delphi, C#Builder, C++Builder, Kylix, and CLX are trademarks or registered trademarks of Borland Software Corporation in the United States and other countries. Business Objects, the Business Objects logo, Crystal Reports, and Crystal Enterprise are trademarks or registered trademarks of Business Objects SA or its affiliated companies in the United States and other countries. DBstore is a trademark of Dharma Systems, Inc. HP and HP-UX are registered trademarks of the Hewlett-Packard Company. AIX, IBM, OS/2, OS/2 WARP, and POWER5 are trademarks or registered trademarks of International Business Machines Corporation in the United States, other countries, or both. Intel, Itanium, Pentium and Xeon are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States and other countries. LynuxWorks, LynxOS and BlueCat are registered trademarks of LynuxWorks, Inc. Microsoft, the .NET logo, MS-DOS, Visual Studio, Windows, Windows Mobile, Windows server and Windows NT are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries. Novell and NetWare are registered trademarks of Novell, Inc., in the United States and other countries. QNX and Neutrino are registered trademarks of QNX Software Systems Ltd. in certain jurisdictions. Red Hat and the Shadow Man logo are registered trademarks of Red Hat, Inc. in the United States and other countries, used with permission. SCO and SCO Open Server, are trademarks or registered trademarks of The SCO Group, Inc. in the U.S.A. and other countries. SGI and IRIX are registered trademarks of Silicon Graphics, Inc., in the United States and/or other countries worldwide. Sun, Sun Microsystems, the Sun Logo, Solaris, SunOS, JDBC, Java and all Java-based trademarks are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries. UNIX and UnixWare are registered trademarks of The Open Group in the United States and other countries. Linux is a trademark of Linus Torvalds in the United States, other countries, or both. All other trademarks, trade names, company names, product names, and registered trademarks are the property of their respective holders. FairCom welcomes your comments on this document and the software it describes. Send comments to: Documentation Comments FairCom Corporation 6300 W. Sugar Creek Drive Columbia, MO 65203 Portions 1987-2008 Dharma Systems, Inc. All rights reserved. This software or web site utilizes or contains material that is 1994-2007 DUNDAS DATA VISUALIZATION, INC. and its licensors, all rights reserved. 6/25/2008
CONTENTS
Introduction .............................................................................................................................................................. 1 1.1 Layout of this Manual.................................................................................................................................... 2 Quick Tour ................................................................................................................................................................ 3 2.1 Introductory Tutorial ...................................................................................................................................... 4 Init ................................................................................................................................................................. 5 Define............................................................................................................................................................ 6 Manage ......................................................................................................................................................... 8 Done............................................................................................................................................................ 11 Additional Resources .................................................................................................................................. 12 2.2 Relationships............................................................................................................................................... 13 Init ............................................................................................................................................................... 15 Define.......................................................................................................................................................... 16 Manage ....................................................................................................................................................... 21 Done............................................................................................................................................................ 28 Additional Resources .................................................................................................................................. 29 2.3 Record/Row Locking................................................................................................................................... 30 Init ............................................................................................................................................................... 32 Define.......................................................................................................................................................... 33 Manage ....................................................................................................................................................... 36 Done............................................................................................................................................................ 40 Additional Resources .................................................................................................................................. 41 2.4 Transaction Processing .............................................................................................................................. 42 Init ............................................................................................................................................................... 43 Define.......................................................................................................................................................... 44 Manage ....................................................................................................................................................... 49 Done............................................................................................................................................................ 56 Additional Resources .................................................................................................................................. 57 Programmers Reference ...................................................................................................................................... 59 3.1 Working with Sessions................................................................................................................................ 60 Allocating a Session Handle ....................................................................................................................... 60 Creating a new session dictionary .............................................................................................................. 61 Session logon and logout............................................................................................................................ 62 Session properties ...................................................................................................................................... 63 Managing Databases .................................................................................................................................. 64 Session wide functions ............................................................................................................................... 68 Working with Sessions without Dictionary Support .................................................................................... 71 Attach and Detach Existing Sessions ......................................................................................................... 71 Session Dictionary ...................................................................................................................................... 72 3.2 Working with Databases ............................................................................................................................. 73 Allocating a Database handle ..................................................................................................................... 73 Connecting to a database ........................................................................................................................... 73 Database properties.................................................................................................................................... 74 Managing Tables ........................................................................................................................................ 75 Database Dictionary.................................................................................................................................... 79 3.3 Working with Tables.................................................................................................................................... 80 Allocating a table handle............................................................................................................................. 81 Creating a new table ................................................................................................................................... 82 Opening a table........................................................................................................................................... 93 Altering a table ............................................................................................................................................ 95 Attach and Detach Open Tables............................................................................................................... 100
www.faircom.com
All Rights Reserved
iii
Table of Contents
Table Properties........................................................................................................................................ 101 Working with Records ............................................................................................................................... 104 Allocating a record handle ........................................................................................................................ 104 User managed record buffers ................................................................................................................... 105 The default index ...................................................................................................................................... 106 Navigating records .................................................................................................................................... 107 Finding records ......................................................................................................................................... 108 Record sets ............................................................................................................................................... 110 Record Filters............................................................................................................................................ 111 Record Batches ........................................................................................................................................ 114 Reading and writing field data to a record buffer ...................................................................................... 123 Clearing the record buffer ......................................................................................................................... 127 Adding new records .................................................................................................................................. 127 Updating existing records ......................................................................................................................... 128 Deleting records ........................................................................................................................................ 129 Record properties ..................................................................................................................................... 129 Record Locking ......................................................................................................................................... 130 3.5 Data Types................................................................................................................................................ 131 Scalar Types ............................................................................................................................................. 131 Date Types................................................................................................................................................ 132 Time Types ............................................................................................................................................... 133 Date/Time (Timestamp) Types ................................................................................................................. 134 Numeric Types .......................................................................................................................................... 134 3.6 Data Integrity............................................................................................................................................. 138 Transactions.............................................................................................................................................. 138 Locking...................................................................................................................................................... 140 3.7 Working with Resources ........................................................................................................................... 142 Types of Resources .................................................................................................................................. 142 c-treeDB C API - Working with Resources ............................................................................................... 143 3.8 Working with Callbacks............................................................................................................................. 151 Callback Function Type ............................................................................................................................ 151 Callback Return Codes ............................................................................................................................. 152 Callback Handle Parameters .................................................................................................................... 152 Callback Types ......................................................................................................................................... 153 Working with Callbacks............................................................................................................................. 170 3.9 Working with Unicode ............................................................................................................................... 171 UNICODE UTF-16 .................................................................................................................................... 171 UNICODE UTF-8 ...................................................................................................................................... 171 c-treeDB C/C++ API UTF-8 Compliance .................................................................................................. 172 Activating c-treeDB UNICODE support .................................................................................................... 172 ICU - International Components for UNICODE ........................................................................................ 173 UNICODE Support .................................................................................................................................... 173 Extended Key Segment Definition ............................................................................................................ 180 3.10 Compatibility.............................................................................................................................................. 183 Compatibility with c-tree Plus ISAM and Low-level Data Files ................................................................. 183 Compatibility with c-treeSQL..................................................................................................................... 183 3.11 c-treeDB, ISAM and Low-Level Integration .............................................................................................. 184 Overview ................................................................................................................................................... 184 Switching c-tree instances ........................................................................................................................ 185 Switching ISAM contexts .......................................................................................................................... 186 Obtaining table data and file number........................................................................................................ 186 Obtaining data file number........................................................................................................................ 186 Obtaining index file number ...................................................................................................................... 187 3.4 c-treeDB C API Function Reference................................................................................................................... 189
FairCom Corporation
iv
4.1
4.2
4.3
c-treeDB definitions................................................................................................................................... 190 Field types................................................................................................................................................. 190 Find Modes ............................................................................................................................................... 192 Index Key Types ....................................................................................................................................... 192 Record Lock Modes .................................................................................................................................. 193 Session Wide Lock Modes........................................................................................................................ 193 Segment Modes ........................................................................................................................................ 194 Table Create Modes ................................................................................................................................. 195 Table Open Modes ................................................................................................................................... 197 Table Permissions .................................................................................................................................... 198 c-treeDB C API Summary ......................................................................................................................... 199 Initialization ............................................................................................................................................... 199 Transaction Processing ............................................................................................................................ 199 Data Definition .......................................................................................................................................... 199 Data Manipulation ..................................................................................................................................... 200 Data Types................................................................................................................................................ 200 Data Structures ......................................................................................................................................... 202 Utility ......................................................................................................................................................... 204 Function Descriptions ............................................................................................................................... 204 c-tree Plus Error Code Reference ........................................................................................ 715 c-treeDB Error and Return Values........................................................................................ 739
Appendix A. Appendix B.
Index...................................................................................................................................................................... 743
www.faircom.com
All Rights Reserved
Formatting convention
Type of Information Used to emphasize a point or for variable expressions such as parameters. Names of keys on the keyboard. For example, SHIFT, CTRL, or ALT+F4. FairCom technology term. c-tree Function name. c-tree Function Parameter. Code example or Command line usage. c-tree executable or utility. c-tree file or path name. c-treeACE Configuration Keyword. c-tree Error Code.
Bold
CAPITALS
utility filename
CONFIGURATION KEYWORDS
BIG_ERR
www.faircom.com
All Rights Reserved
vi
Chapter 1
Introduction
FairCom is pleased to present the c-tree database API (c-treeDB). c-treeDB gives application developers a simple interface into the powerful core of c-tree Plus, yet includes the advanced functionality that distinguishes c-tree Plus from other database solutions. c-treeDB offers a method of database creation and maintenance that is easier to use than the traditional c-tree Plus ISAM and low-level APIs. c-tree database utilizes the simplified concepts of sessions, databases, and tables in addition to the standard concepts of records, fields, indices, and segments. This database API allows for effortless and productive management of database systems. The c-treeDB C API provides libraries that, once installed and correctly referenced, allow C programs to access the c-tree database core via function calls. The c-tree database API gives application developers a simple interface into the powerful core of c-tree, yet includes the advanced functionality that distinguishes c-tree from other database solutions. c-treeDB offers a method of database creation and maintenance that is easier to use than the traditional c-treeISAM and c-treeLowLevel APIs.
www.faircom.com
All Rights Reserved
Chapter 1 Introduction
c-treeDB utilizes the simplified concepts of sessions, databases, and tables in addition to the standard concepts of records, fields, indices, and segments. This database layer allows for effortless and productive management of database systems.
c-treeDB Relationships Session Database Table Record Field Index Segment
c-treeDB consists of two separate APIs. The C++ API provides the classes and methods that comprise the database functionality. The C API provides the function calls without object-oriented schema. Aside from the schematic differences, there are few distinctions between these c-treeDB C++ and C APIs.
FairCom Corporation
Chapter 2
Quick Tour
This chapter will introduce four quick tutorials showing the major components of our core technology: How to init, define and manage data How to handle index files How to use locks in a multi-user environment How to use transaction processing
www.faircom.com
All Rights Reserved
Manage() - Adds a few rows/records; Reads the rows/records back from the database; displays the column/field content; and then deletes the rows/records. Done() - Disconnects from c-treeACE Database Engine. Note our simple mainline:
/* * main() * * The main() function implements the concept of "init, define, manage * and you're done..." */ #ifdef PROTOTYPE NINT main (COUNT argc, pTEXT argv[]) #else NINT main (argc, argv) COUNT argc; TEXT argv[]; #endif { Initialize(); Define(); Manage(); Done(); printf("\nPress <ENTER> key to exit . . .\n"); #ifndef ctPortWINCE getchar(); #endif return(0); }
Init
First we need to open a connection to a database by providing the c-treeACE Database Engine with a user name, password and the database name. Below is the code for Initialize():
/* * Initialize() * * Perform the minimum requirement of logging onto the c-tree Server */ #ifdef PROTOTYPE VOID Initialize(VOID) #else VOID Initialize() #endif { printf("INIT\n"); /* allocate session handle */ if ((hSession = ctdbAllocSession(CTSESSION_CTREE)) == NULL) Handle_Error("Initialize(): ctdbAllocSession()"); hDatabase = hSession; /* database not used in this tutorial */ /* connect to server */ printf("\tLogon to server...\n"); if (ctdbLogon(hSession, "FAIRCOMS", "", "")) Handle_Error("Initialize(): ctdbLogon()"); }
www.faircom.com
All Rights Reserved
Define
The Define() step is where specific data definitions are established by your application and/or process. This involves defining columns/fields and creating the tables/files with optional indices.
FairCom Corporation
Check_Table_Mode(hTable); }
/* * Check_Table_Mode() * * Check if existing table has transaction processing flag enabled. * If a table is under transaction processing control, modify the * table mode to disable transaction processing */ #ifdef PROTOTYPE VOID Check_Table_Mode(CTHANDLE hTable) #else VOID Check_Table_Mode(hTable) CTHANDLE hTable; #endif { CTCREATE_MODE mode; /* get table create mode */ mode = ctdbGetTableCreateMode(hTable); /* check if table is under transaction processing control */ if ((mode & CTCREATE_TRNLOG)) { /* change file mode to disable transaction processing */ mode ^= CTCREATE_TRNLOG; if (ctdbUpdateCreateMode(hTable, mode) != CTDBRET_OK) Handle_Error("Check_Table_Mode(); ctdbUpdateCreateMode"); } }
www.faircom.com
All Rights Reserved
Manage
The manage step provides data management functionality for your application and/or process.
/* * Delete_Records() * * This function deletes all the records in the table */ #ifdef PROTOTYPE VOID Delete_Records(CTHANDLE hRecord) #else VOID Delete_Records(hRecord) CTHANDLE hRecord; #endif { CTDBRET retval; CTBOOL empty; printf("\tDelete records...\n");
FairCom Corporation
empty = NO; retval = ctdbFirstRecord(hRecord); if (retval != CTDBRET_OK) { if (retval == END_OF_FILE) empty = YES; else Handle_Error("Delete_Records(): ctdbFirstRecord()"); } while (empty == NO) /* while table is not empty */ { /* delete record */ if (ctdbDeleteRecord(hRecord)) Handle_Error("Delete_Records(): ctdbDeleteRecord()"); /* read next record */ retval = ctdbNextRecord(hRecord); if (retval != CTDBRET_OK) { if (retval == END_OF_FILE) empty = YES; else Handle_Error("Delete_Records(): ctdbNextRecord()"); } } }
/* * Add_Records() * * This function adds records to a table in the database from an * array of strings */ typedef struct { CTSTRING number, zipcode, state, rating, name, address, city; } CUSTOMER_DATA; CUSTOMER_DATA data[] = { "1000", "92867", "CA", "1001", "61434", "CT", "1002", "73677", "GA", "1003", "10034", "MO", };
#ifdef PROTOTYPE VOID Add_Records(VOID) #else VOID Add_Records() #endif { CTDBRET retval; CTSIGNED i; CTSIGNED nRecords = sizeof(data) / sizeof(CUSTOMER_DATA); printf("\tAdd records...\n"); /* add data to table */ for (i = 0; i < nRecords; i++) { /* clear record buffer */ ctdbClearRecord(hRecord); retval = 0; /* populate record buffer with data */ retval |= ctdbSetFieldAsString(hRecord, 0, data[i].number); retval |= ctdbSetFieldAsString(hRecord, 1, data[i].zipcode); retval |= ctdbSetFieldAsString(hRecord, 2, data[i].state);
www.faircom.com
All Rights Reserved
|= |= |= |=
3, 4, 5, 6,
/* * Display_Records() * * This function displays the contents of a table. ctdbFirstRecord() and * ctdbNextRecord() fetch the record. Then each field is parsed and displayed */ #ifdef PROTOTYPE VOID Display_Records(VOID) #else VOID Display_Records() #endif { CTDBRET retval; TEXT custnumb[4+1]; TEXT custname[47+1]; printf("\tDisplay records..."); /* read first record */ retval = ctdbFirstRecord(hRecord); if (retval != CTDBRET_OK) Handle_Error("Display_Records(): ctdbFirstRecord()"); while (retval != END_OF_FILE) { retval = 0; retval |= ctdbGetFieldAsString(hRecord, 0, custnumb, sizeof(custnumb)); retval |= ctdbGetFieldAsString(hRecord, 4, custname, sizeof(custname)); if (retval) Handle_Error("Display_Records(): ctdbGetFieldAsString()"); printf("\n\t\t%-8s%10s\n",custnumb, custname); /* read next record */ retval = ctdbNextRecord(hRecord); if (retval == END_OF_FILE) break; /* reached end of file */ if (retval != CTDBRET_OK) Handle_Error("Display_Records(): ctdbNextRecord()"); } }
FairCom Corporation
10
Done
When an application and/or process has completed operations with the database, it must release resources by disconnecting from the database engine. Below is the code for Done():
/* * Done() * * This function handles the housekeeping of closing tables and * freeing of associated memory */ #ifdef PROTOTYPE VOID Done(VOID) #else VOID Done() #endif { printf("DONE\n"); /* close table */ printf("\tClose table...\n"); if (ctdbCloseTable(hTable)) Handle_Error("Done(): ctdbCloseTable()"); /* logout */ printf("\tLogout...\n"); if (ctdbLogout(hSession)) Handle_Error("Done(): ctdbLogout()"); /* free handles */ ctdbFreeRecord(hRecord); ctdbFreeTable(hTable); ctdbFreeSession(hSession); }
www.faircom.com
All Rights Reserved
11
Additional Resources
We encourage you to explore the additional resources listed here: Complete source code for this tutorial can be found in ctdb_tutorial1.c in your installation directory, within the 'sdk\ctree.ctdb\tutorials' directory for your platform. Example for the Windows platform: C:\FairCom\V9.0.0\win32\sdk\ctree.ctdb\tutorials\ctdb_tutorial1.c. Additional documentation may be found on the FairCom Web site at: www.faircom.com
FairCom Corporation
12
2.2 Relationships
..\sdk\ctree.ctdb\tutorials\ctdb_tutorial2.c Now we will build some table/file relationships using the c-treeACE C Database API. This tutorial will advance the concepts introduced in the first tutorial by expanding the number of tables. We will define key columns/fields and create specific indices for each table to form a relational model database. Like all other examples in the c-tree tutorial series, this tutorial simplifies the creation and use of a database into four simple steps: Initialize(), Define(), Manage(), and Youre Done() ! Tutorial #2: Relational Model and Indexing Here we add a bit more complexity, introducing multiple tables, with related indices in order to form a simple "relational" database simulating an Order Entry system. Here is an overview of what will be created:
Initialize()
Define() - Defines and creates the "custmast", "custordr", "ordritem" and the "itemmast" tables/files with related indices. Manage() Done() - Adds some related rows/records to all tables/files. Then queries the database. - Disconnects from c-treeACE Database Engine.
13
Initialize(); Define(); Manage(); Done(); printf("\nPress <ENTER> key to exit . . .\n"); getchar(); return(0); }
FairCom Corporation
14
Init
First we need to open a connection to a database by providing the c-treeACE Database Engine with a user name, password and the database name.
www.faircom.com
All Rights Reserved
15
Define
The Define() step is where specific data definitions are established by your application and/or process. This involves defining columns/fields and creating the tables/files with optional indices.
/* * Create_CustomerMaster_Table() * * Open table CustomerMaster, if it exists. Otherwise create it * along with its indices and open it */ #ifdef PROTOTYPE VOID Create_CustomerMaster_Table(VOID) #else VOID Create_CustomerMaster_Table() #endif { CTHANDLE pField1, pField2, pField3, pField4; CTHANDLE pField5, pField6, pField7; CTHANDLE pIndex; CTHANDLE pIseg; /* define table CustomerMaster */ printf("\ttable CustomerMaster\n"); /* allocate a table handle */ if ((hTableCustMast = ctdbAllocTable(hDatabase)) == NULL) Handle_Error("Create_CustomerMaster_Table(): ctdbAllocTable()"); /* open table */
FairCom Corporation
16
if (ctdbOpenTable(hTableCustMast, "custmast", CTOPEN_NORMAL)) { /* define table fields */ pField1 = ctdbAddField(hTableCustMast, "cm_custnumb", CT_FSTRING, 4); pField2 = ctdbAddField(hTableCustMast, "cm_custzipc", CT_FSTRING, 9); pField3 = ctdbAddField(hTableCustMast, "cm_custstat", CT_FSTRING, 2); pField4 = ctdbAddField(hTableCustMast, "cm_custratg", CT_FSTRING, 1); pField5 = ctdbAddField(hTableCustMast, "cm_custname", CT_STRING, 47); pField6 = ctdbAddField(hTableCustMast, "cm_custaddr", CT_STRING, 47); pField7 = ctdbAddField(hTableCustMast, "cm_custcity", CT_STRING, 47); if (!pField1 || !pField2 || !pField3 || !pField4 || !pField5 || !pField6|| !pField7) Handle_Error("Create_CustomerMaster_Table(): ctdbAddField()"); /* define index */ pIndex = ctdbAddIndex(hTableCustMast, "cm_custnumb_idx", CTINDEX_FIXED, NO, NO); pIseg = ctdbAddSegment(pIndex, pField1, CTSEG_SCHSEG); if (!pIndex || !pIseg) Handle_Error("Create_CustomerMaster_Table(): ctdbAddIndex()|ctdbAddSegment()"); /* create table */ if (ctdbCreateTable(hTableCustMast, "custmast", CTCREATE_NORMAL)) Handle_Error("Create_CustomerMaster_Table(): ctdbCreateTable()"); /* open table */ if (ctdbOpenTable(hTableCustMast, "custmast", CTOPEN_NORMAL)) Handle_Error("Create_CustomerMaster_Table(): ctdbOpenTable()"); } else { Check_Table_Mode(hTableCustMast); /* confirm the index exists, if not then add the index * * this scenario arises out of the fact that this table was created in tutorial 1 * without indexes. The index is now created by the call to ctdbAlterTable */ if (ctdbGetIndexByName(hTableCustMast, "cm_custnumb_idx") == NULL) { pField1 = ctdbGetFieldByName(hTableCustMast, "cm_custnumb"); pIndex = ctdbAddIndex(hTableCustMast, "cm_custnumb_idx", CTINDEX_FIXED, NO, NO); pIseg = ctdbAddSegment(pIndex, pField1, CTSEG_SCHSEG); if (!pIndex || !pIseg) Handle_Error("Create_CustomerMaster_Table(): ctdbAddIndex()|ctdbAddSegment()"); if (ctdbAlterTable(hTableCustMast, CTDB_ALTER_NORMAL) != CTDBRET_OK) Handle_Error("Create_CustomerMaster_Table(): ctdbAlterTable()"); } } }
/* * Create_CustomerOrders_Table() * * Open table CustomerOrders, if it exists. Otherwise create it * along with its indices and open it */ #ifdef PROTOTYPE VOID Create_CustomerOrders_Table(VOID) #else VOID Create_CustomerOrders_Table() #endif { CTHANDLE pField1, pField2, pField3, pField4; CTHANDLE pIndex1, pIndex2; CTHANDLE pIseg1, pIseg2;
www.faircom.com
All Rights Reserved
17
/* define table CustomerOrders */ printf("\ttable CustomerOrders\n"); /* allocate a table handle */ if ((hTableCustOrdr = ctdbAllocTable(hDatabase)) == NULL) Handle_Error("Create_CustomerOrders_Table(): ctdbAllocTable()"); /* open table */ if (ctdbOpenTable(hTableCustOrdr, "custordr", CTOPEN_NORMAL)) { /* define table fields */ pField1 = ctdbAddField(hTableCustOrdr, "co_ordrdate", CT_DATE, 4); pField2 = ctdbAddField(hTableCustOrdr, "co_promdate", CT_DATE, 4); pField3 = ctdbAddField(hTableCustOrdr, "co_ordrnumb", CT_FSTRING, 6); pField4 = ctdbAddField(hTableCustOrdr, "co_custnumb", CT_FSTRING, 4); if (!pField1 || !pField2 || !pField3 || !pField4) Handle_Error("Define(): ctdbAddField()"); /* define indices */ pIndex1 = ctdbAddIndex(hTableCustOrdr, "co_ordrnumb_idx", CTINDEX_LEADING, NO, NO); pIseg1 = ctdbAddSegment(pIndex1, pField3, CTSEG_SCHSEG); pIndex2 = ctdbAddIndex(hTableCustOrdr, "co_custnumb_idx", CTINDEX_LEADING, YES, NO); pIseg2 = ctdbAddSegment(pIndex2, pField4, CTSEG_SCHSEG); if (!pIndex1 || !pIseg1 || !pIndex2 || !pIseg2) Handle_Error("Create_CustomerOrders_Table(): ctdbAddIndex()|ctdbAddSegment()"); /* create table */ if (ctdbCreateTable(hTableCustOrdr, "custordr", CTCREATE_NORMAL)) Handle_Error("Create_CustomerOrders_Table(): ctdbCreateTable()"); /* open table */ if (ctdbOpenTable(hTableCustOrdr, "custordr", CTOPEN_NORMAL)) Handle_Error("Create_CustomerOrders_Table(): ctdbOpenTable()"); } else Check_Table_Mode(hTableCustOrdr); }
/* * Create_OrderItems_Table() * * Open table OrderItems, if it exists. Otherwise create it * along with its indices and open it */ #ifdef PROTOTYPE VOID Create_OrderItems_Table(VOID) #else VOID Create_OrderItems_Table() #endif { CTHANDLE pField1, pField2, pField3, pField4; CTHANDLE pIndex1, pIndex2; CTHANDLE pIseg1, pIseg2, pIseg3; /* define table OrderItems */ printf("\ttable OrderItems\n"); /* allocate a table handle */ if ((hTableOrdrItem = ctdbAllocTable(hDatabase)) == NULL) Handle_Error("Create_OrderItems_Table(): ctdbAllocTable()"); if (ctdbOpenTable(hTableOrdrItem, "ordritem", CTOPEN_NORMAL)) { /* define table fields */ pField1 = ctdbAddField(hTableOrdrItem,"oi_sequnumb", CT_INT2, 2); pField2 = ctdbAddField(hTableOrdrItem,"oi_quantity", CT_INT2, 2); pField3 = ctdbAddField(hTableOrdrItem,"oi_ordrnumb", CT_FSTRING, 6); pField4 = ctdbAddField(hTableOrdrItem,"oi_itemnumb", CT_FSTRING, 5);
FairCom Corporation
18
if (!pField1 || !pField2 || !pField3 || !pField4) Handle_Error("Create_OrderItems_Table(): ctdbAddField()"); /* define indices */ pIndex1 = ctdbAddIndex(hTableOrdrItem, "oi_ordrnumb_idx" ,CTINDEX_LEADING, NO, NO); pIseg1 = ctdbAddSegment(pIndex1, pField3, CTSEG_SCHSEG); pIseg2 = ctdbAddSegment(pIndex1, pField1, CTSEG_SCHSEG); pIndex2 = ctdbAddIndex(hTableOrdrItem, "oi_itemnumb_idx" ,CTINDEX_LEADING, YES, NO); pIseg3 = ctdbAddSegment(pIndex2, pField4, CTSEG_SCHSEG); if (!pIndex1 || !pIseg1 || !pIseg2 || !pIndex2 || !pIseg3) Handle_Error("Create_OrderItems_Table(): ctdbAddIndex()|ctdbAddSegment()"); /* create table */ if (ctdbCreateTable(hTableOrdrItem, "ordritem", CTCREATE_NORMAL)) Handle_Error("Create_OrderItems_Table(): ctdbCreateTable()"); /* open table */ if (ctdbOpenTable(hTableOrdrItem, "ordritem", CTOPEN_NORMAL)) Handle_Error("Create_OrderItems_Table(): ctdbOpenTable()"); } else Check_Table_Mode(hTableOrdrItem); }
/* * Create_ItemMaster_Table() * * Open table ItemMaster, if it exists. Otherwise create it * along with its indices and open it */ #ifdef PROTOTYPE VOID Create_ItemMaster_Table(VOID) #else VOID Create_ItemMaster_Table() #endif { CTHANDLE pField1, pField2, pField3, pField4; CTHANDLE pIndex; CTHANDLE pIseg; /* define table ItemMaster */ printf("\ttable ItemMaster\n"); /* allocate a table handle */ if ((hTableItemMast = ctdbAllocTable(hDatabase)) == NULL) Handle_Error("Create_ItemMaster_Table(): ctdbAllocTable()"); /* open table */ if (ctdbOpenTable(hTableItemMast, "itemmast", CTOPEN_NORMAL)) { /* define table fields */ pField1 = ctdbAddField(hTableItemMast, "im_itemwght", CT_INT4, 4); pField2 = ctdbAddField(hTableItemMast, "im_itempric", CT_MONEY, 4); pField3 = ctdbAddField(hTableItemMast, "im_itemnumb", CT_FSTRING, 5); pField4 = ctdbAddField(hTableItemMast, "im_itemdesc", CT_STRING, 47); if (!pField1 || !pField2 || !pField3 || !pField4) Handle_Error("Create_ItemMaster_Table(): ctdbAddField()"); /* define index */ pIndex = ctdbAddIndex(hTableItemMast, "im_itemnumb_idx", CTINDEX_FIXED, NO, NO); pIseg = ctdbAddSegment(pIndex, pField3, CTSEG_SCHSEG); if (!pIndex || !pIseg) Handle_Error("Create_ItemMaster_Table(): ctdbAddIndex()|ctdbAddSegment()"); /* create table */ if (ctdbCreateTable(hTableItemMast, "itemmast", CTCREATE_NORMAL)) Handle_Error("Create_ItemMaster_Table(); ctdbCreateTable()"); /* open table */
www.faircom.com
All Rights Reserved
19
/* * Check_Table_Mode() * * Check if existing table has transaction processing flag enabled. * If a table is under transaction processing control, modify the * table mode to disable transaction processing */ #ifdef PROTOTYPE VOID Check_Table_Mode(CTHANDLE hTable) #else VOID Check_Table_Mode(hTable) CTHANDLE hTable; #endif { CTCREATE_MODE mode; /* get table create mode */ mode = ctdbGetTableCreateMode(hTable); /* check if table is under transaction processing control */ if ((mode & CTCREATE_TRNLOG)) { /* change file mode to disable transaction processing */ mode ^= CTCREATE_TRNLOG; if (ctdbUpdateCreateMode(hTable, mode) != CTDBRET_OK) Handle_Error("Check_Table_Mode(); ctdbUpdateCreateMode"); } }
FairCom Corporation
20
Manage
The manage step provides data management functionality for your application and/or process.
for each order in the CustomerOrders table fetch order number fetch customer number fetch name from CustomerMaster table based on customer number for each order item in OrderItems table fetch item quantity fetch item number fetch item price from ItemMaster table based on item number next next */ printf("\n\tQuery Results\n"); /* get the first order */ if (ctdbFirstRecord(hRecordCustOrdr))
www.faircom.com
All Rights Reserved
21
Handle_Error("Manage(): ctdbFirstRecord()"); isOrderFound = YES; while (isOrderFound) /* for each order in the CustomerOrders table */ { /* fetch order number */ retval = ctdbGetFieldAsString(hRecordCustOrdr, 2, ordrnumb, sizeof(ordrnumb)); /* fetch customer number */ retval |= ctdbGetFieldAsString(hRecordCustOrdr, 3, custnumb, sizeof(custnumb)); if (retval) Handle_Error("Manage(): ctdbGetFieldAsString()"); /* fetch name from CustomerMaster table based on customer number */ if (ctdbClearRecord(hRecordCustMast)) Handle_Error("Manage(): ctdbClearRecord()"); if (ctdbSetFieldAsString(hRecordCustMast, 0, custnumb)) Handle_Error("Manage(): ctdbSetFieldAsString()"); if (ctdbFindRecord(hRecordCustMast, CTFIND_EQ)) Handle_Error("Manage(): ctdbFindRecord()"); if (ctdbGetFieldAsString(hRecordCustMast, 4, custname, sizeof(custname))) Handle_Error("Manage(): ctdbGetFieldAsString()"); /* fetch item price from OrderItems table */ if (ctdbClearRecord(hRecordOrdrItem)) Handle_Error("Manage(): ctdbClearRecord()"); if (ctdbSetFieldAsString(hRecordOrdrItem, 2, ordrnumb)) Handle_Error("Manage(): ctdbSetFieldAsString()"); /* define a recordset to scan only items applicable to this order */ if (ctdbRecordSetOn(hRecordOrdrItem, 6)) Handle_Error("Manage(): ctdbRecordSetOn()"); if (ctdbFirstRecord(hRecordOrdrItem)) Handle_Error("Manage(): ctdbFirstRecord()"); isItemFound = YES; total while { /* if = 0; (isItemFound)
fetch item quantity */ (ctdbGetFieldAsSigned(hRecordOrdrItem, 1, &quantity)) Handle_Error("Manage(): ctdbGetFieldAsSigned()"); /* fetch item number */ if (ctdbGetFieldAsString(hRecordOrdrItem, 3, itemnumb, sizeof(itemnumb))) Handle_Error("Manage(): ctdbGetFieldAsString()"); /* fetch item price from ItemMaster table based on item number */ if (ctdbClearRecord(hRecordItemMast)) Handle_Error("Manage(): ctdbClearRecord()"); if (ctdbSetFieldAsString(hRecordItemMast, 2, itemnumb)) Handle_Error("Manage(): ctdbSetFieldAsString()"); if (ctdbFindRecord(hRecordItemMast, CTFIND_EQ)) Handle_Error("Manage(): ctdbFindRecord()"); if (ctdbGetFieldAsFloat(hRecordItemMast, 1, &price)) Handle_Error("Manage(): ctdbGetFieldAsFloat()"); /* calculate order total */ total += (price * quantity); /* read next record */ retval = ctdbNextRecord(hRecordOrdrItem); if (retval != CTDBRET_OK) { if (retval == END_OF_FILE) isItemFound = NO; else Handle_Error("Manage(): ctdbNextRecord()"); }
22
printf("\t\t%-20s %.2f\n", custname, total); /* read next order */ retval = ctdbNextRecord(hRecordCustOrdr); if (retval != CTDBRET_OK) { if (retval == END_OF_FILE) isOrderFound = NO; else Handle_Error("Manage(): ctdbNextRecord()"); } } }
/* * Add_CustomerMaster_Records() * * This function adds records to table CustomerMaster from an * array of strings */ typedef struct { CTSTRING number, zipcode, state, rating, name, address, city; } CUSTOMER_DATA; CUSTOMER_DATA data4[] = { "1000", "92867", "CA", "1001", "61434", "CT", "1002", "73677", "GA", "1003", "10034", "MO", };
#ifdef PROTOTYPE VOID Add_CustomerMaster_Records(VOID) #else VOID Add_CustomerMaster_Records() #endif { CTDBRET retval; CTSIGNED i; CTSIGNED nRecords = sizeof(data4) / sizeof(CUSTOMER_DATA); if ((hRecordCustMast = ctdbAllocRecord(hTableCustMast)) == NULL) Handle_Error("Add_Customer_Records(): ctdbAllocRecord()"); Delete_Records(hRecordCustMast); printf("\tAdd records in table CustomerMaster...\n"); /* add records to table */ for (i = 0; i < nRecords; i++) { /* clear record buffer */ ctdbClearRecord(hRecordCustMast); retval = 0; /* populate record buffer with data */ retval |= ctdbSetFieldAsString(hRecordCustMast, retval |= ctdbSetFieldAsString(hRecordCustMast, retval |= ctdbSetFieldAsString(hRecordCustMast, retval |= ctdbSetFieldAsString(hRecordCustMast, retval |= ctdbSetFieldAsString(hRecordCustMast, retval |= ctdbSetFieldAsString(hRecordCustMast, retval |= ctdbSetFieldAsString(hRecordCustMast,
0, 1, 2, 3, 4, 5, 6,
23
Handle_Error("Add_Customer_Records(): ctdbWriteRecord()"); } }
/* * Add_CustomerOrders_Records() * * This function adds records to table CustomerOrders from an * array of strings */ typedef struct { CTSTRING orderdate, promisedate, ordernum, customernum; } ORDER_DATA; ORDER_DATA data1[] = { {"09/01/2002", "09/05/2002", {"09/02/2002", "09/06/2002", };
"1", "2",
"1001"}, "1002"}
#ifdef PROTOTYPE VOID Add_CustomerOrders_Records(VOID) #else VOID Add_CustomerOrders_Records() #endif { CTDBRET retval; CTSIGNED i; CTSIGNED nRecords = sizeof(data1) / sizeof(ORDER_DATA); CTDATE orderdate; CTDATE promisedate;
if ((hRecordCustOrdr = ctdbAllocRecord(hTableCustOrdr)) == NULL) Handle_Error("Add_CustomerOrders_Records(): ctdbAllocRecord()"); Delete_Records(hRecordCustOrdr); printf("\tAdd records in table CustomerOrders...\n"); /* add records to table */ for (i = 0; i < nRecords; i++) { /* clear record buffer */ ctdbClearRecord(hRecordCustOrdr); retval = 0; retval |= ctdbStringToDate(data1[i].orderdate, CTDATE_MDCY ,&orderdate); retval |= ctdbStringToDate(data1[i].promisedate, CTDATE_MDCY, &promisedate); /* populate record buffer with data */ retval |= ctdbSetFieldAsDate(hRecordCustOrdr, 0, orderdate); retval |= ctdbSetFieldAsDate(hRecordCustOrdr, 1, promisedate); retval |= ctdbSetFieldAsString(hRecordCustOrdr, 2, data1[i].ordernum); retval |= ctdbSetFieldAsString(hRecordCustOrdr, 3, data1[i].customernum); if (retval) Handle_Error("Add_CustomerOrders_Records(): ctdbSetFieldAsString()|ctdbSetFieldAsDate()"); /* add record */ if (ctdbWriteRecord(hRecordCustOrdr)) Handle_Error("Add_CustomerOrders_Records(): ctdbWriteRecord()"); } }
/* * Add_OrderItems_Records() * * This function adds records to table OrderItems from an * array of strings
FairCom Corporation
24
*/ typedef struct { COUNT sequencenum, quantity; CTSTRING ordernum, itemnum; } ORDERITEM_DATA; ORDERITEM_DATA data2[] = { {1, 2, "1", "1"}, {2, 1, "1", "2"}, {3, 1, "1", "3"}, {1, 3, "2", "3"} }; #ifdef PROTOTYPE VOID Add_OrderItems_Records(VOID) #else VOID Add_OrderItems_Records() #endif { CTDBRET retval; CTSIGNED i; CTSIGNED nRecords = sizeof(data2) / sizeof(ORDERITEM_DATA); if ((hRecordOrdrItem = ctdbAllocRecord(hTableOrdrItem)) == NULL) Handle_Error("Add_OrderItems_Records(): ctdbAllocRecord()"); Delete_Records(hRecordOrdrItem); printf("\tAdd records in table OrderItems...\n"); /* add records to table */ for (i = 0; i < nRecords; i++) { /* clear record buffer */ ctdbClearRecord(hRecordOrdrItem); retval = 0; /* populate record buffer with data */ retval |= ctdbSetFieldAsSigned(hRecordOrdrItem, retval |= ctdbSetFieldAsSigned(hRecordOrdrItem, retval |= ctdbSetFieldAsString(hRecordOrdrItem, retval |= ctdbSetFieldAsString(hRecordOrdrItem,
0, 1, 2, 3,
/* * Add_ItemMaster_Records() * * This function adds records to table ItemMaster from an * array of strings */ typedef struct { CTSIGNED weight; CTMONEY price; CTSTRING itemnum, description; } ITEM_DATA; ITEM_DATA data3[] = { {10, 1995, "1", "Hammer"}, {3, 999, "2", "Wrench"}, {4, 1659, "3", "Saw"}, {1, 398, "4", "Pliers"} };
www.faircom.com
All Rights Reserved
25
#ifdef PROTOTYPE VOID Add_ItemMaster_Records(VOID) #else VOID Add_ItemMaster_Records() #endif { CTDBRET retval; CTSIGNED i; CTSIGNED nRecords = sizeof(data3) / sizeof(ITEM_DATA); if ((hRecordItemMast = ctdbAllocRecord(hTableItemMast)) == NULL) Handle_Error("Add_ItemMaster_Records(): ctdbAllocRecord()"); Delete_Records(hRecordItemMast); printf("\tAdd records in table ItemMaster...\n"); /* add records to table */ for (i = 0; i < nRecords; i++) { /* clear record buffer */ ctdbClearRecord(hRecordItemMast); retval = 0; /* populate record buffer with data */ retval |= ctdbSetFieldAsSigned(hRecordItemMast, 0, data3[i].weight); retval |= ctdbSetFieldAsMoney(hRecordItemMast, 1, data3[i].price); retval |= ctdbSetFieldAsString(hRecordItemMast, 2, data3[i].itemnum); retval |= ctdbSetFieldAsString(hRecordItemMast, 3, data3[i].description); if(retval) Handle_Error("Add_ItemMaster_Records(): ctdbSetFieldAsString()|ctdbSetFieldAsSigned()"); /* add record */ if (ctdbWriteRecord(hRecordItemMast)) Handle_Error("Add_ItemMaster_Records(): ctdbWriteRecord()"); } }
/* * Delete_Records() * * This function deletes all the records in the table based * on the input parameter */ #ifdef PROTOTYPE VOID Delete_Records(CTHANDLE hRecord) #else VOID Delete_Records(hRecord) CTHANDLE hRecord; #endif { CTDBRET retval; CTBOOL empty; printf("\tDelete records...\n"); if (ctdbClearRecord(hRecord)) Handle_Error("Delete_Records(): ctdbClearRecord()");
empty = NO; retval = ctdbFirstRecord(hRecord); if (retval != CTDBRET_OK) { if (retval == END_OF_FILE) empty = YES; else
FairCom Corporation
26
Handle_Error("Delete_Records(): ctdbFirstRecord()"); } while (empty == NO) /* while table is not empty */ { /* delete record */ if (ctdbDeleteRecord(hRecord)) Handle_Error("Delete_Records(): ctdbDeleteRecord()"); /* read next record */ retval = ctdbNextRecord(hRecord); if (retval != CTDBRET_OK) { if (retval == END_OF_FILE) empty = YES; else Handle_Error("Delete_Records(): ctdbNextRecord()"); } } }
www.faircom.com
All Rights Reserved
27
Done
When an application and/or process has completed operations with the database, it must release resources by disconnecting from the database engine. Below is the code for Done():
/* * Done() * * This function handles the housekeeping of closing tables and * freeing of associated memory */ #ifdef PROTOTYPE VOID Done(VOID) #else VOID Done() #endif { printf("DONE\n"); /* close tables */ printf("\tClose tables...\n"); if (ctdbCloseTable(hTableCustMast)) Handle_Error("Done(): ctdbCloseTable()"); if (ctdbCloseTable(hTableOrdrItem)) Handle_Error("Done(): ctdbCloseTable()"); if (ctdbCloseTable(hTableCustOrdr)) Handle_Error("Done(): ctdbCloseTable()"); if (ctdbCloseTable(hTableItemMast)) Handle_Error("Done(): ctdbCloseTable()"); /* logout */ printf("\tLogout...\n"); if (ctdbLogout(hSession)) Handle_Error("Done(): ctdbLogout()"); /* free handles */ ctdbFreeRecord(hRecordCustMast); ctdbFreeRecord(hRecordItemMast); ctdbFreeRecord(hRecordOrdrItem); ctdbFreeRecord(hRecordCustOrdr); ctdbFreeTable(hTableCustMast); ctdbFreeTable(hTableItemMast); ctdbFreeTable(hTableOrdrItem); ctdbFreeTable(hTableCustOrdr); ctdbFreeSession(hSession); }
FairCom Corporation
28
Additional Resources
We encourage you to explore the additional resources listed here: Complete source code for this tutorial can be found in ctdb_tutorial2.c in your installation directory, within the 'sdk\ctree.ctdb\tutorials' directory for your platform. Example for the Windows platform: C:\FairCom\V9.0.0\win32\sdk\ctree.ctdb\tutorials\ctdb_tutorial2.c. Additional documentation may be found on the FairCom Web site at: www.faircom.com
www.faircom.com
All Rights Reserved
29
Manage() - Adds a few rows/records; Reads the rows/records back from the database; displays the column/field content. Then demonstrates an update operation under locking control, and a scenario that shows a locking conflict. Done() - Disconnects from c-treeACE Database Engine. Note our simple mainline:
/* * main() * * The main() function implements the concept of "init, define, manage * and you're done..." */ NINT main (COUNT argc, pTEXT argv[]) { Initialize(); Define(); Manage(); Done(); printf("\nPress <ENTER> key to exit . . .\n"); getchar(); return(0); }
FairCom Corporation
30
www.faircom.com
All Rights Reserved
31
Init
First we need to open a connection to a database by providing the c-treeACE Database Engine with a user name, password and the database name.
FairCom Corporation
32
Define
The Define() step is where specific data definitions are established by your application and/or process. This involves defining columns/fields and creating the tables/files with optional indices.
/* * Create_CustomerMaster_Table() * * Open table CustomerMaster, if it exists. Otherwise create it * along with its indices and open it */ #ifdef PROTOTYPE VOID Create_CustomerMaster_Table(VOID) #else VOID Create_CustomerMaster_Table() #endif { CTHANDLE pField1, pField2, pField3, pField4; CTHANDLE pField5, pField6, pField7; CTHANDLE pIndex; CTHANDLE pIseg; /* define table CustomerMaster */ printf("\ttable CustomerMaster\n"); /* allocate a table handle */ if ((hTable = ctdbAllocTable(hDatabase)) == NULL) Handle_Error("Create_CustomerMaster_Table(): ctdbAllocTable()"); /* open table */ if (ctdbOpenTable(hTable, "custmast", CTOPEN_NORMAL)) { /* define table fields */ pField1 = ctdbAddField(hTable, "cm_custnumb", CT_FSTRING, 4); pField2 = ctdbAddField(hTable, "cm_custzipc", CT_FSTRING, 9);
www.faircom.com
All Rights Reserved
33
= = = = =
CT_FSTRING, 2); CT_FSTRING, 1); CT_STRING, 47); CT_STRING, 47); CT_STRING, 47);
if (!pField1 || !pField2 || !pField3 || !pField4 || !pField5 || !pField6|| !pField7) Handle_Error("Create_CustomerMaster_Table(): ctdbAddField()"); /* define index */ pIndex = ctdbAddIndex(hTable, "cm_custnumb_idx", CTINDEX_FIXED, NO, NO); pIseg = ctdbAddSegment(pIndex, pField1, CTSEG_SCHSEG); if (!pIndex || !pIseg) Handle_Error("Create_CustomerMaster_Table(): ctdbAddIndex()|ctdbAddSegment()"); /* create table */ if (ctdbCreateTable(hTable, "custmast", CTCREATE_NORMAL)) Handle_Error("Create_CustomerMaster_Table(): ctdbCreateTable()"); /* open table */ if (ctdbOpenTable(hTable, "custmast", CTOPEN_NORMAL)) Handle_Error("Create_CustomerMaster_Table(): ctdbOpenTable()"); } else { Check_Table_Mode(hTable); /* confirm the index exists, if not then add the index * * this scenario arises out of the fact that this table was created in tutorial 1 * without indexes. The index is now created by the call to ctdbAlterTable */ if (ctdbGetIndexByName(hTable, "cm_custnumb_idx") == NULL) { pField1 = ctdbGetFieldByName(hTable, "cm_custnumb"); pIndex = ctdbAddIndex(hTable, "cm_custnumb_idx", CTINDEX_FIXED, NO, NO); pIseg = ctdbAddSegment(pIndex, pField1, CTSEG_SCHSEG); if (!pIndex || !pIseg) Handle_Error("Create_CustomerMaster_Table(): ctdbAddIndex()|ctdbAddSegment()"); if (ctdbAlterTable(hTable, CTDB_ALTER_NORMAL) != CTDBRET_OK) Handle_Error("Create_CustomerMaster_Table(): ctdbAlterTable()"); } } }
/* * Check_Table_Mode() * * Check if existing table has transaction processing flag enabled. * If a table is under transaction processing control, modify the * table mode to disable transaction processing */ #ifdef PROTOTYPE VOID Check_Table_Mode(CTHANDLE hTable) #else VOID Check_Table_Mode(hTable) CTHANDLE hTable; #endif { CTCREATE_MODE mode; /* get table create mode */ mode = ctdbGetTableCreateMode(hTable); /* check if table is under transaction processing control */ if ((mode & CTCREATE_TRNLOG)) {
FairCom Corporation
34
/* change file mode to disable transaction processing */ mode ^= CTCREATE_TRNLOG; if (ctdbUpdateCreateMode(hTable, mode) != CTDBRET_OK) Handle_Error("Check_Table_Mode(); ctdbUpdateCreateMode"); } }
www.faircom.com
All Rights Reserved
35
Manage
The manage step provides data management functionality for your application and/or process.
/* * Delete_Records() * * This function deletes all the records in the table */ #ifdef PROTOTYPE VOID Delete_Records(CTHANDLE hRecord) #else VOID Delete_Records(hRecord) CTHANDLE hRecord; #endif {
FairCom Corporation
36
CTDBRET CTBOOL
retval; empty;
printf("\tDelete records...\n"); /* enable session-wide lock flag */ if (ctdbLock(hSession, CTLOCK_WRITE_BLOCK)) Handle_Error("Delete_Records(): ctdbLock()"); empty = NO; retval = ctdbFirstRecord(hRecord); if (retval != CTDBRET_OK) { if (retval == END_OF_FILE) empty = YES; else Handle_Error("Delete_Records(): ctdbFirstRecord()"); } while (empty == NO) /* while table is not empty */ { /* delete record */ if (ctdbDeleteRecord(hRecord)) Handle_Error("Delete_Records(): ctdbDeleteRecord()"); /* read next record */ retval = ctdbNextRecord(hRecord); if (retval != CTDBRET_OK) { if (retval == END_OF_FILE) empty = YES; else Handle_Error("Delete_Records(): ctdbNextRecord()"); } } if (ctdbUnlock(hSession)) Handle_Error("Delete_Records(): ctdbUnlock()"); }
/* * Add_CustomerMaster_Records() * * This function adds records to table CustomerMaster from an * array of strings */ typedef struct { CTSTRING number, zipcode, state, rating, name, address, city; } CUSTOMER_DATA; CUSTOMER_DATA data[] = { "1000", "92867", "CA", "1001", "61434", "CT", "1002", "73677", "GA", "1003", "10034", "MO", };
#ifdef PROTOTYPE VOID Add_CustomerMaster_Records(VOID) #else VOID Add_CustomerMaster_Records() #endif { CTDBRET retval; CTSIGNED i; CTSIGNED nRecords = sizeof(data) / sizeof(CUSTOMER_DATA); printf("\tAdd records...\n"); /* add data to table */ for (i = 0; i < nRecords; i++)
www.faircom.com
All Rights Reserved
37
{ /* clear record buffer */ ctdbClearRecord(hRecord); retval = 0; /* populate record buffer with data */ retval |= ctdbSetFieldAsString(hRecord, retval |= ctdbSetFieldAsString(hRecord, retval |= ctdbSetFieldAsString(hRecord, retval |= ctdbSetFieldAsString(hRecord, retval |= ctdbSetFieldAsString(hRecord, retval |= ctdbSetFieldAsString(hRecord, retval |= ctdbSetFieldAsString(hRecord,
0, 1, 2, 3, 4, 5, 6,
/* * Display_Records() * * This function displays the contents of a table. ctdbFirstRecord() and * ctdbNextRecord() fetch the record. Then each field is parsed and displayed */ #ifdef PROTOTYPE VOID Display_Records(VOID) #else VOID Display_Records() #endif { CTDBRET retval; TEXT custnumb[4+1]; TEXT custname[47+1]; printf("\tDisplay records..."); /* read first record */ retval = ctdbFirstRecord(hRecord); if (retval == END_OF_FILE) return; while (retval == CTDBRET_OK) { retval = 0; retval |= ctdbGetFieldAsString(hRecord, 0, custnumb, sizeof(custnumb)); retval |= ctdbGetFieldAsString(hRecord, 4, custname, sizeof(custname)); if (retval) Handle_Error("Display_Records(): ctdbGetFieldAsString()"); printf("\n\t\t%-8s%10s\n",custnumb, custname); /* read next record */ retval = ctdbNextRecord(hRecord); if (retval == END_OF_FILE) break; /* reached end of file */ if (retval != CTDBRET_OK) Handle_Error("Display_Records(): ctdbNextRecord()"); } }
/* * Update_CustomerMaster_Records() *
FairCom Corporation
38
* Update one record under locking control to demonstrate the effects * of locking */ #ifdef PROTOTYPE VOID Update_CustomerMaster_Record(VOID) #else VOID Update_CustomerMaster_Record() #endif { printf("\tUpdate record...\n"); /* enable session-wide lock flag */ if (ctdbLock(hSession, CTLOCK_WRITE_BLOCK)) Handle_Error("Update_CustomerMaster_Record(): ctdbLock()"); /* find record by customer number */ if (ctdbClearRecord(hRecord)) Handle_Error("Update_CustomerMaster_Record(): ctdbClearRecord()"); if (ctdbSetFieldAsString(hRecord, 0, "1003")) Handle_Error("Update_CustomerMaster_Record(): ctdbSetFieldAsString()"); if (ctdbFindRecord(hRecord, CTFIND_EQ)) Handle_Error("Update_CustomerMaster_Record(): ctdbFindRecord()"); if (ctdbSetFieldAsString(hRecord, 4, "KEYON DOOLING")) Handle_Error("Update_CustomerMaster_Record(): ctdbSetFieldAsString()"); /* rewrite record */ if (ctdbWriteRecord(hRecord)) Handle_Error("Update_CustomerMaster_Record(): ctdbWriteRecord()"); else { printf("\tPress <ENTER> key to unlock\n"); getchar(); } if (ctdbUnlock(hSession)) Handle_Error("Update_CustomerMaster_Record(): ctdbUnlock()"); }
www.faircom.com
All Rights Reserved
39
Done
When an application and/or process has completed operations with the database, it must release resources by disconnecting from the database engine. Below is the code for Done():
/* * Done() * * This function handles the housekeeping of closing tables and * freeing of associated memory */ #ifdef PROTOTYPE VOID Done(VOID) #else VOID Done() #endif { printf("DONE\n"); /* close table */ printf("\tClose table\n"); if (ctdbCloseTable(hTable)) Handle_Error("Done(): ctdbCloseTable()"); /* logout */ printf("\tLogout...\n"); if (ctdbLogout(hSession)) Handle_Error("Done(): ctdbLogout()"); /* free handles */ ctdbFreeRecord(hRecord); ctdbFreeTable(hTable); ctdbFreeSession(hSession); }
FairCom Corporation
40
Additional Resources
We encourage you to explore the additional resources listed here: Complete source code for this tutorial can be found in ctdb_tutorial3.c in your installation directory, within the 'sdk\ctree.ctdb\tutorials' directory for your platform. Example for the Windows platform: C:\FairCom\V9.0.0\win32\sdk\ctree.ctdb\tutorials\ctdb_tutorial3.c. Additional documentation may be found on the FairCom Web site at: www.faircom.com
www.faircom.com
All Rights Reserved
41
FairCom Corporation
42
Init
First we need to open a connection to a database by providing the c-treeACE Database Engine with a user name, password and the database name.
www.faircom.com
All Rights Reserved
43
Define
The Define() step is where specific data definitions are established by your application and/or process. This involves defining columns/fields and creating the tables/files with optional indices.
/* * Create_CustomerMaster_Table() * * Open table CustomerMaster, if it exists. Otherwise create it * along with its indices and open it */ #ifdef PROTOTYPE VOID Create_CustomerMaster_Table(VOID) #else VOID Create_CustomerMaster_Table() #endif { CTHANDLE pField1, pField2, pField3, pField4; CTHANDLE pField5, pField6, pField7; CTHANDLE pIndex; CTHANDLE pIseg; /* define table CustomerMaster */ printf("\ttable CustomerMaster\n"); /* allocate a table handle */ if ((hTableCustMast = ctdbAllocTable(hDatabase)) == NULL) Handle_Error("Create_CustomerMaster_Table(): ctdbAllocTable()"); /* open table */ if (ctdbOpenTable(hTableCustMast, "custmast", CTOPEN_NORMAL)) {
FairCom Corporation
44
CT_FSTRING, 4); CT_FSTRING, 9); CT_FSTRING, 2); CT_FSTRING, 1); CT_STRING, 47); CT_STRING, 47); CT_STRING, 47);
if (!pField1 || !pField2 || !pField3 || !pField4 || !pField5 || !pField6|| !pField7) Handle_Error("Create_CustomerMaster_Table(): ctdbAddField()"); /* define index */ pIndex = ctdbAddIndex(hTableCustMast, "cm_custnumb_idx", CTINDEX_FIXED, NO, NO); pIseg = ctdbAddSegment(pIndex, pField1, CTSEG_SCHSEG); if (!pIndex || !pIseg) Handle_Error("Create_CustomerMaster_Table(): ctdbAddIndex()|ctdbAddSegment()"); /* create table */ if (ctdbCreateTable(hTableCustMast, "custmast", CTCREATE_TRNLOG)) Handle_Error("Create_CustomerMaster_Table(): ctdbCreateTable()"); /* open table */ if (ctdbOpenTable(hTableCustMast, "custmast", CTOPEN_NORMAL)) Handle_Error("Create_CustomerMaster_Table(): ctdbOpenTable()"); } else { Check_Table_Mode(hTableCustMast); /* confirm the index exists, if not then add the index * * this scenario arises out of the fact that this table was created in tutorial 1 * without indexes. The index is now created by the call to ctdbAlterTable */ if (ctdbGetIndexByName(hTableCustMast, "cm_custnumb_idx") == NULL) { pField1 = ctdbGetFieldByName(hTableCustMast, "cm_custnumb"); pIndex = ctdbAddIndex(hTableCustMast, "cm_custnumb_idx", CTINDEX_FIXED, NO, NO); pIseg = ctdbAddSegment(pIndex, pField1, CTSEG_SCHSEG); if (!pIndex || !pIseg) Handle_Error("Create_CustomerMaster_Table(): ctdbAddIndex()|ctdbAddSegment()"); if (ctdbAlterTable(hTableCustMast, CTDB_ALTER_NORMAL) != CTDBRET_OK) Handle_Error("Create_CustomerMaster_Table(): ctdbAlterTable()"); } } }
/* * Create_CustomerOrders_Table() * * Open table CustomerOrders, if it exists. Otherwise create it * along with its indices and open it */ #ifdef PROTOTYPE VOID Create_CustomerOrders_Table(VOID) #else VOID Create_CustomerOrders_Table() #endif { CTHANDLE pField1, pField2, pField3, pField4; CTHANDLE pIndex1, pIndex2; CTHANDLE pIseg1, pIseg2; /* define table CustomerOrders */ printf("\ttable CustomerOrders\n");
www.faircom.com
All Rights Reserved
45
/* allocate a table handle */ if ((hTableCustOrdr = ctdbAllocTable(hDatabase)) == NULL) Handle_Error("Create_CustomerOrders_Table(): ctdbAllocTable()"); /* open table */ if (ctdbOpenTable(hTableCustOrdr, "custordr", CTOPEN_NORMAL)) { /* define table fields */ pField1 = ctdbAddField(hTableCustOrdr, "co_ordrdate", CT_DATE, 4); pField2 = ctdbAddField(hTableCustOrdr, "co_promdate", CT_DATE, 4); pField3 = ctdbAddField(hTableCustOrdr, "co_ordrnumb", CT_FSTRING, 6); pField4 = ctdbAddField(hTableCustOrdr, "co_custnumb", CT_FSTRING, 4); if (!pField1 || !pField2 || !pField3 || !pField4) Handle_Error("Define(): ctdbAddField()"); /* define indices */ pIndex1 = ctdbAddIndex(hTableCustOrdr, "co_ordrnumb_idx", CTINDEX_LEADING, NO, NO); pIseg1 = ctdbAddSegment(pIndex1, pField3, CTSEG_SCHSEG); pIndex2 = ctdbAddIndex(hTableCustOrdr, "co_custnumb_idx", CTINDEX_LEADING, YES, NO); pIseg2 = ctdbAddSegment(pIndex2, pField4, CTSEG_SCHSEG); if (!pIndex1 || !pIseg1 || !pIndex2 || !pIseg2) Handle_Error("Create_CustomerOrders_Table(): ctdbAddIndex()|ctdbAddSegment()"); /* create table */ if (ctdbCreateTable(hTableCustOrdr, "custordr", CTCREATE_TRNLOG)) Handle_Error("Create_CustomerOrders_Table(): ctdbCreateTable()"); /* open table */ if (ctdbOpenTable(hTableCustOrdr, "custordr", CTOPEN_NORMAL)) Handle_Error("Create_CustomerOrders_Table(): ctdbOpenTable()"); } else Check_Table_Mode(hTableCustOrdr); }
/* * Create_OrderItems_Table() * * Open table OrderItems, if it exists. Otherwise create it * along with its indices and open it */ #ifdef PROTOTYPE VOID Create_OrderItems_Table(VOID) #else VOID Create_OrderItems_Table() #endif { CTHANDLE pField1, pField2, pField3, pField4; CTHANDLE pIndex1, pIndex2; CTHANDLE pIseg1, pIseg2, pIseg3; /* define table OrderItems */ printf("\ttable OrderItems\n"); /* allocate a table handle */ if ((hTableOrdrItem = ctdbAllocTable(hDatabase)) == NULL) Handle_Error("Create_OrderItems_Table(): ctdbAllocTable()"); if (ctdbOpenTable(hTableOrdrItem, "ordritem", CTOPEN_NORMAL)) { /* define table fields */ pField1 = ctdbAddField(hTableOrdrItem,"oi_sequnumb", CT_INT2, 2); pField2 = ctdbAddField(hTableOrdrItem,"oi_quantity", CT_INT2, 2); pField3 = ctdbAddField(hTableOrdrItem,"oi_ordrnumb", CT_FSTRING, 6); pField4 = ctdbAddField(hTableOrdrItem,"oi_itemnumb", CT_FSTRING, 5); if (!pField1 || !pField2 || !pField3 || !pField4) Handle_Error("Create_OrderItems_Table(): ctdbAddField()"); /* define indices */
FairCom Corporation
46
pIndex1 = ctdbAddIndex(hTableOrdrItem, "oi_ordrnumb_idx" ,CTINDEX_LEADING, NO, NO); pIseg1 = ctdbAddSegment(pIndex1, pField3, CTSEG_SCHSEG); pIseg2 = ctdbAddSegment(pIndex1, pField1, CTSEG_SCHSEG); pIndex2 = ctdbAddIndex(hTableOrdrItem, "oi_itemnumb_idx" ,CTINDEX_LEADING, YES, NO); pIseg3 = ctdbAddSegment(pIndex2, pField4, CTSEG_SCHSEG); if (!pIndex1 || !pIseg1 || !pIseg2 || !pIndex2 || !pIseg3) Handle_Error("Create_OrderItems_Table(): ctdbAddIndex()|ctdbAddSegment()"); /* create table */ if (ctdbCreateTable(hTableOrdrItem, "ordritem", CTCREATE_TRNLOG)) Handle_Error("Create_OrderItems_Table(): ctdbCreateTable()"); /* open table */ if (ctdbOpenTable(hTableOrdrItem, "ordritem", CTOPEN_NORMAL)) Handle_Error("Create_OrderItems_Table(): ctdbOpenTable()"); } else Check_Table_Mode(hTableOrdrItem); }
/* * Create_ItemMaster_Table() * * Open table ItemMaster, if it exists. Otherwise create it * along with its indices and open it */ #ifdef PROTOTYPE VOID Create_ItemMaster_Table(VOID) #else VOID Create_ItemMaster_Table() #endif { CTHANDLE pField1, pField2, pField3, pField4; CTHANDLE pIndex; CTHANDLE pIseg; /* define table ItemMaster */ printf("\ttable ItemMaster\n"); /* allocate a table handle */ if ((hTableItemMast = ctdbAllocTable(hDatabase)) == NULL) Handle_Error("Create_ItemMaster_Table(): ctdbAllocTable()"); /* open table */ if (ctdbOpenTable(hTableItemMast, "itemmast", CTOPEN_NORMAL)) { /* define table fields */ pField1 = ctdbAddField(hTableItemMast, "im_itemwght", CT_INT4, 4); pField2 = ctdbAddField(hTableItemMast, "im_itempric", CT_MONEY, 4); pField3 = ctdbAddField(hTableItemMast, "im_itemnumb", CT_FSTRING, 5); pField4 = ctdbAddField(hTableItemMast, "im_itemdesc", CT_STRING, 47); if (!pField1 || !pField2 || !pField3 || !pField4) Handle_Error("Create_ItemMaster_Table(): ctdbAddField()"); /* define index */ pIndex = ctdbAddIndex(hTableItemMast, "im_itemnumb_idx", CTINDEX_FIXED, NO, NO); pIseg = ctdbAddSegment(pIndex, pField3, CTSEG_SCHSEG); if (!pIndex || !pIseg) Handle_Error("Create_ItemMaster_Table(): ctdbAddIndex()|ctdbAddSegment()"); /* create table */ if (ctdbCreateTable(hTableItemMast, "itemmast", CTCREATE_TRNLOG)) Handle_Error("Create_ItemMaster_Table(); ctdbCreateTable()"); /* open table */ if (ctdbOpenTable(hTableItemMast, "itemmast", CTOPEN_NORMAL)) Handle_Error("Create_ItemMaster_Table(): ctdbOpenTable()"); } else Check_Table_Mode(hTableItemMast);
www.faircom.com
All Rights Reserved
47
/* * Check_Table_Mode() * * Check if existing table has transaction processing flag enabled. * If a table is not ready for transaction, modify the table mode to * enable transaction processing */ #ifdef PROTOTYPE VOID Check_Table_Mode(CTHANDLE hTable) #else VOID Check_Table_Mode(hTable) CTHANDLE hTable; #endif { CTCREATE_MODE mode; /* get table create mode */ mode = ctdbGetTableCreateMode(hTable); /* check if table is not under transaction processing control */ if (!(mode & CTCREATE_TRNLOG)) { /* change file mode to enable transaction processing */ mode |= CTCREATE_TRNLOG; if (ctdbUpdateCreateMode(hTable, mode) != CTDBRET_OK) Handle_Error("Check_Table_Mode(); ctdbUpdateCreateMode"); } }
FairCom Corporation
48
Manage
The manage step provides data management functionality for your application and/or process.
www.faircom.com
All Rights Reserved
49
Display_OrderItems(); }
/* * Add_CustomerMaster_Records() * * This function adds records to table CustomerMaster from an * array of strings */ typedef struct { CTSTRING number, zipcode, state, rating, name, address, city; } CUSTOMER_DATA; CUSTOMER_DATA data4[] = { "1000", "92867", "CA", "1001", "61434", "CT", "1002", "73677", "GA", "1003", "10034", "MO", };
#ifdef PROTOTYPE VOID Add_CustomerMaster_Records(VOID) #else VOID Add_CustomerMaster_Records() #endif { CTDBRET retval; CTSIGNED i; CTSIGNED nRecords = sizeof(data4) / sizeof(CUSTOMER_DATA); Delete_Records(hRecordCustMast); printf("\tAdd records in table CustomerMaster...\n"); /* add records to table */ for (i = 0; i < nRecords; i++) { /* clear record buffer */ ctdbClearRecord(hRecordCustMast); retval = 0; /* populate record buffer with data */ retval |= ctdbSetFieldAsString(hRecordCustMast, retval |= ctdbSetFieldAsString(hRecordCustMast, retval |= ctdbSetFieldAsString(hRecordCustMast, retval |= ctdbSetFieldAsString(hRecordCustMast, retval |= ctdbSetFieldAsString(hRecordCustMast, retval |= ctdbSetFieldAsString(hRecordCustMast, retval |= ctdbSetFieldAsString(hRecordCustMast,
0, 1, 2, 3, 4, 5, 6,
/* * Add_ItemMaster_Records() * * This function adds records to table ItemMaster from an * array of strings */ typedef struct { CTSIGNED weight; CTMONEY price;
FairCom Corporation
50
CTSTRING itemnum, description; } ITEM_DATA; ITEM_DATA data3[] = { {10, 1995, "1", "Hammer"}, {3, 999, "2", "Wrench"}, {4, 1659, "3", "Saw"}, {1, 398, "4", "Pliers"} }; #ifdef PROTOTYPE VOID Add_ItemMaster_Records(VOID) #else VOID Add_ItemMaster_Records() #endif { CTDBRET retval; CTSIGNED i; CTSIGNED nRecords = sizeof(data3) / sizeof(ITEM_DATA); Delete_Records(hRecordItemMast); printf("\tAdd records in table ItemMaster...\n"); /* add records to table */ for (i = 0; i < nRecords; i++) { /* clear record buffer */ ctdbClearRecord(hRecordItemMast); retval = 0; /* populate record buffer with data */ retval |= ctdbSetFieldAsSigned(hRecordItemMast, 0, data3[i].weight); retval |= ctdbSetFieldAsMoney(hRecordItemMast, 1, data3[i].price); retval |= ctdbSetFieldAsString(hRecordItemMast, 2, data3[i].itemnum); retval |= ctdbSetFieldAsString(hRecordItemMast, 3, data3[i].description); if(retval) Handle_Error("Add_ItemMaster_Records(): ctdbSetFieldAsString()|ctdbSetFieldAsSigned()"); /* add record */ if (ctdbWriteRecord(hRecordItemMast)) Handle_Error("Add_ItemMaster_Records(): ctdbWriteRecord()"); } }
/* * Delete_Records() * * This function deletes all the records in the table based * on the input parameter */ #ifdef PROTOTYPE VOID Delete_Records(CTHANDLE hRecord) #else VOID Delete_Records(hRecord) CTHANDLE hRecord; #endif { CTDBRET retval; CTBOOL empty; printf("\tDelete records...\n"); if (ctdbClearRecord(hRecord)) Handle_Error("Delete_Records(): ctdbClearRecord()");
empty = NO;
www.faircom.com
All Rights Reserved
51
retval = ctdbFirstRecord(hRecord); if (retval != CTDBRET_OK) { if (retval == END_OF_FILE) empty = YES; else Handle_Error("Delete_Records(): ctdbFirstRecord()"); } while (empty == NO) /* while table is not empty */ { /* delete record */ if (ctdbDeleteRecord(hRecord)) Handle_Error("Delete_Records(): ctdbDeleteRecord()"); /* read next record */ retval = ctdbNextRecord(hRecord); if (retval != CTDBRET_OK) { if (retval == END_OF_FILE) empty = YES; else Handle_Error("Delete_Records(): ctdbNextRecord()"); } } }
/* * Add_Transactions() * * Add an Order and associated Items "as a transaction" to their * respective tables. A transaction is committed or aborted if the * customer number on the order is confirmed valid. Likewise each * item in the order is verified to be a valid item. SavePoints are * established as an order is processed, allowing a transaction to * rollback to the previously verified item */ typedef struct { CTSTRING orderdate, promdate, ordernum, custnum; } ORDER_DATA; typedef struct { CTSTRING ordernum; CTSIGNED sequnumb; CTSIGNED quantity; CTSTRING itemnumb; } ORDERITEM_DATA; ORDER_DATA orders[] = { {"09/01/2002", "09/05/2002", "1", "1001"}, {"09/02/2002", "09/06/2002", "2", "9999"}, {"09/22/2002", "09/26/2002", "3", "1003"} }; ORDERITEM_DATA {"1", 1, 2, {"1", 2, 1, {"2", 1, 1, {"2", 2, 3, {"3", 1, 2, {"3", 2, 2, }; items[] = { "1"}, "2"}, "3"}, "4"}, "3"}, "99"} /* bad item number */
#ifdef PROTOTYPE VOID Add_Transactions(VOID) #else VOID Add_Transactions() #endif { CTDBRET retval;
FairCom Corporation
52
/* write lock required for transaction updates */ if (ctdbLock(hSession, CTLOCK_WRITE)) Handle_Error("Add_Transactions(): ctdbLock()"); /* start a transaction */ if (ctdbBegin(hSession)) Handle_Error("Add_Transactions(): ctdbBegin()"); Delete_Records(hRecordCustOrdr); Delete_Records(hRecordOrdrItem); /* commit transaction */ if (ctdbCommit(hSession)) Handle_Error("Add_Transactions(): ctdbCommit()"); /* free locks */ if (ctdbUnlock(hSession)) Handle_Error("Add_Transactions(): ctdbUnlock()"); printf("\tAdd transaction records... \n"); /* process orders */ for(i = 0; i < nOrders; i++) { /* start a transaction */ if (ctdbBegin(hSession)) Handle_Error("Add_Transactions(): ctdbBegin()"); ctdbClearRecord(hRecordCustOrdr); retval = 0; /* populate record buffer with order data */ retval |= ctdbStringToDate(orders[i].orderdate, CTDATE_MDCY, &orderdate); retval |= ctdbStringToDate(orders[i].promdate, CTDATE_MDCY, &promdate); retval |= ctdbSetFieldAsDate(hRecordCustOrdr, 0, orderdate); retval |= ctdbSetFieldAsDate(hRecordCustOrdr, 1, promdate); retval |= ctdbSetFieldAsString(hRecordCustOrdr, 2, orders[i].ordernum); retval |= ctdbSetFieldAsString(hRecordCustOrdr, 3, orders[i].custnum); if(retval) Handle_Error("Add_Transactions(): ctdbSetFieldAsString()"); /* add order record */ if (ctdbWriteRecord(hRecordCustOrdr)) Handle_Error("Add_Transactions(): ctdbWriteRecord()"); /* set transaction savepoint */ savepoint = ctdbSetSavePoint(hSession); /* process order items */ while (!(strcmp(items[j].ordernum, orders[i].ordernum))) { ctdbClearRecord(hRecordOrdrItem); retval = 0; /* populate record buffer with order item data */ retval |= ctdbSetFieldAsSigned(hRecordOrdrItem, 0, retval |= ctdbSetFieldAsSigned(hRecordOrdrItem, 1, retval |= ctdbSetFieldAsString(hRecordOrdrItem, 2, retval |= ctdbSetFieldAsString(hRecordOrdrItem, 3,
53
if (ctdbWriteRecord(hRecordOrdrItem)) Handle_Error("Add_Transactions(): ctdbWriteRecord()"); /* check that item exists in ItemMaster table */ if (ctdbClearRecord(hRecordItemMast)) Handle_Error("Add_Transactions(): ctdbClearRecord()"); if (ctdbSetFieldAsString(hRecordItemMast, 2, items[j].itemnumb)) Handle_Error("Add_Transactions(): ctdbSetFieldAsString()"); if (ctdbFindRecord(hRecordItemMast, CTFIND_EQ)) /* if not found, restore back to previous savepoint */ ctdbRestoreSavePoint(hSession, savepoint); else /* set transaction savepoint */ savepoint = ctdbSetSavePoint(hSession); /* bump to next item */ j++; /* exit the while loop on last item */ if (j >= nItems) break; } /* check that customer exists in CustomerMaster table */ if ((retval = ctdbClearRecord(hRecordCustMast)) != CTDBRET_OK) Handle_Error("Add_Transactions(): ctdbClearRecord()"); if (ctdbSetFieldAsString(hRecordCustMast, 0, orders[i].custnum)) Handle_Error("Add_Transactions(): ctdbSetFieldAsString()"); /* commit or abort the transaction */ if (ctdbFindRecord(hRecordCustMast, CTFIND_EQ)) { if (ctdbAbort(hSession)) Handle_Error("Add_Transactions(): ctdbAbort()"); } else { if (ctdbCommit(hSession)) Handle_Error("Add_Transactions(): ctdbCommit()"); } } }
/* * Display_CustomerOrders() * * This function displays the contents of a table. ctdbFirstRecord() and * ctdbNextRecord() fetch the record. Then each field is parsed and displayed */ #ifdef PROTOTYPE VOID Display_CustomerOrders(VOID) #else VOID Display_CustomerOrders() #endif { CTDBRET retval; TEXT custnumb[4+1]; TEXT ordrnumb[6+1]; printf("\n\tCustomerOrder table...\n"); /* read first record */ retval = ctdbFirstRecord(hRecordCustOrdr); if (retval != CTDBRET_OK) Handle_Error("Display_CustomerOrders(): ctdbFirstRecord()"); while (retval != END_OF_FILE) { retval = 0; retval |= ctdbGetFieldAsString(hRecordCustOrdr, 2, ordrnumb, sizeof(ordrnumb));
FairCom Corporation
54
retval |= ctdbGetFieldAsString(hRecordCustOrdr, 3, custnumb, sizeof(custnumb)); if (retval) Handle_Error("Display_CustomerOrders(): ctdbGetFieldAsString()"); printf("\t %s %s\n", ordrnumb, custnumb);
/* read next record */ retval = ctdbNextRecord(hRecordCustOrdr); if (retval == END_OF_FILE) break; /* reached end of file */ if (retval != CTDBRET_OK) Handle_Error("Display_CustomerOrders(): ctdbNextRecord()"); } }
/* * Display_OrderItems() * * This function displays the contents of a table. ctdbFirstRecord() and * ctdbNextRecord() fetch the record. Then each field is parsed and displayed */ #ifdef PROTOTYPE VOID Display_OrderItems(VOID) #else VOID Display_OrderItems() #endif { CTDBRET retval; TEXT itemnumb[5+1]; TEXT ordrnumb[6+1]; printf("\n\tOrderItems Table...\n"); /* read first record */ retval = ctdbFirstRecord(hRecordOrdrItem); if (retval != CTDBRET_OK) Handle_Error("Display_OrderItems(): ctdbFirstRecord()"); while (retval != END_OF_FILE) { retval = 0; retval |= ctdbGetFieldAsString(hRecordOrdrItem, 2, ordrnumb, sizeof(ordrnumb)); retval |= ctdbGetFieldAsString(hRecordOrdrItem, 3, itemnumb, sizeof(itemnumb)); if (retval) Handle_Error("Display_OrderItems(): ctdbGetFieldAsString()"); printf("\t %s %s\n", ordrnumb, itemnumb);
/* read next record */ retval = ctdbNextRecord(hRecordOrdrItem); if (retval == END_OF_FILE) break; /* reached end of file */ if (retval != CTDBRET_OK) Handle_Error("Display_OrderItems(): ctdbNextRecord()"); } }
www.faircom.com
All Rights Reserved
55
Done
When an application and/or process has completed operations with the database, it must release resources by disconnecting from the database engine. Below is the code for Done():
/* * Done() * * This function handles the housekeeping of closing tables and * freeing of associated memory */ #ifdef PROTOTYPE VOID Done(VOID) #else VOID Done() #endif { printf("DONE\n"); /* close tables */ printf("\tClose tables...\n"); if (ctdbCloseTable(hTableCustMast)) Handle_Error("Done(): ctdbCloseTable()"); if (ctdbCloseTable(hTableOrdrItem)) Handle_Error("Done(): ctdbCloseTable()"); if (ctdbCloseTable(hTableCustOrdr)) Handle_Error("Done(): ctdbCloseTable()"); if (ctdbCloseTable(hTableItemMast)) Handle_Error("Done(): ctdbCloseTable()"); /* logout */ printf("\tLogout...\n"); if (ctdbLogout(hSession)) Handle_Error("Done(): ctdbLogout()"); /* free handles */ ctdbFreeRecord(hRecordCustMast); ctdbFreeRecord(hRecordItemMast); ctdbFreeRecord(hRecordOrdrItem); ctdbFreeRecord(hRecordCustOrdr); ctdbFreeTable(hTableCustMast); ctdbFreeTable(hTableItemMast); ctdbFreeTable(hTableOrdrItem); ctdbFreeTable(hTableCustOrdr); ctdbFreeSession(hSession); }
FairCom Corporation
56
Additional Resources
We encourage you to explore the additional resources listed here: Complete source code for this tutorial can be found in ctdb_tutorial4.c in your installation directory, within the 'sdk\ctree.ctdb\tutorials' directory for your platform. Example for the Windows platform: C:\FairCom\V9.0.0\win32\sdk\ctree.ctdb\tutorials\ctdb_tutorial4.c. Additional documentation may be found on the FairCom Web site at: www.faircom.com
www.faircom.com
All Rights Reserved
57
Chapter 3
Programmers Reference
c-treeDB, short for c-tree DataBase, represents a new, higher-level, easier to use API on top of the two popular FairCom APIs: ISAM and Low-level. c-treeDB is intended as the new standard for c-tree Plus programming. FairCom tried to make the developer's life easier without removing the flexibility and performance of the original APIs. The c-treeDB general architecture is presented in the figure below, organized into seven different levels: session, database, table, field, index, segment, and record. These levels or layers will be used to present a group of common functionality. It is important to note that c-tree data and index files can be manipulated directly with or without session or database dictionary support. Please refer to the "Working with Sessions without Dictionary Support" and "Allocating a table handle without database support" for more information.
c-treeDB Relationships Session Database Table Record Field Index Segment
A session represents a connection between a client and a c-tree Server; no work can be performed before a session becomes active. The session handle indicates the c-treeDB session, the server name and location, the directory where the databases are located, the user name and password. A database can be considered as a collection of tables, and each database has its own database dictionary that stores information about each table that belongs to that database such as the table name, password and path, the active (open) tables, and the number of tables linked to the database. The database handle indicates a database in the session and each session can have multiple databases. A table is essentially a c-tree Plus data, and optionally, index files. There can be, and typically are, more than one table in a database, and a given table may belong to multiple databases. A Table may have zero or more records.
www.faircom.com
All Rights Reserved
59
A field is the basic element of a table, and a collection of fields forms a data record. Often a table will have zero or more indices, which enhances the retrieval of records from that table. Indices typically have one or more segments describing the index key structure. The index handle indicates an index associated with a particular table, while the segment links the index with the fields. A record is essentially an entry row in a table. A record handle indicates a record instance on a particular table. A table may have one or more record handles associated with it. Each record handle may be an independent cursor into the table, or several record handles may share the same cursor into the table.
When allocating a session handle, specify the session handle type. There are three different session handle types: CTSESSION_CTREE Allocate a new session for logon only. No session or database dictionary files will be used. No database functions can be used with this session mode. Allocate table handles using the session handle. CTSESSION_CTDB Allocate a new session making full usage of c-treeDB session and database dictionaries. With this session mode, a Session dictionary file must exist to perform a session logon and you must connect to a database before attempting to perform operation on tables. CTSESSION_SQL Allocate a new session for c-treeSQL processing. This mode allows changes made at the c-treeDB level to be reflected at the c-treeSQL level without requiring an additional table import step; your tables are immediately available with the c-treeSQL interface. While this session type is available, limitations still exist. Support for alter table operations are not supported; c-treeDB AlterTable() activities are NOT reflected in the c-treeSQL system tables.
FairCom Corporation
60
CTSESSION_SQL Limitations
CTSESSION_SQL mode is still experimental at this time. The following limitations exist: 1. Problems with table structures will prevent update of c-treeSQL system tables. 2. Support of alter table is currently not implemented (i.e., tables altered at the c-treeDB level are not reflected in the c-treeSQL system table). 3. No check is performed to verify that there is a c-treeSQL Server available.
Note: The above code, as most of the pseudocode presented in this manual, does not make use of error checking. While not an appropriate programming style, it is used in this manual for clarity of the functional code presented. These lines represent all three steps required to create the session. First, a session handle is declared. c-treeDB uses Opaque handles, and the best approach is to use the declaration as done above with CTHANDLE, which is a pointer to void. All c-treeDB handles should be defined this way. The next call, ctdbAllocSession(), makes the physical handle allocation. All c-treeDB C functions are described in detail in " c-treeDB C API Function Reference". After allocating a session handle, it is possible to log on to a session if the session dictionary already exists in the working directory. If not, a new session dictionary must be created using ctdbCreateSession(). In the above example, the session is created using ctdbCreateSession(), which requires four parameters: session handle, server name, user name, and user password. For the three last parameters, in this first example, the default values are being used. The full network address may be required in the Server name: FAIRCOMS@10.0.0.1 or FAIRCOMS@my_machine.com. For non-server applications, the parameter is ignored and may be set to NULL. A valid user name is required to access the c-tree Server. When the server is first installed, only the default user is permitted server access. This user name, ADMIN, is intended for the database administrator. ADMIN is also the default user name for c-treeDB sessions. For non-server applications, the user name may be NULL. For server applications, see the c-tree Server Administrators Guide on how to create users and groups.
www.faircom.com
All Rights Reserved
61
A valid user password is also required to access the c-tree Server. When the server is first installed, the default user ADMIN is associated with the default password, also ADMIN. For non-server applications, the user password may be NULL. ctdbCreateSession() will return error DPON_ERR (19, data file already exists) if one tries to create a new session dictionary in the same directory where a session dictionary already exists.
The parameters for the ctdbLogon() function are the same as for the ctdbCreateSession(). If the session dictionary doesn't exist and the session type is CTSESSION_CTDB or CTSESSION_SQL, ctdbLogon() function will fail returning error FNOP_ERR (12), indicating that c-treeDB could not locate the session dictionary file. Tip: A useful sequence in code is to try to log on to the session, and if it fails with error FNOP_ERR (12), create the session dictionary and then log on again.
CTSESSION hSession; hSession = ctdbAllocSession(CTSESSION_CTDB); if (!hSession) FatalError(Session handle allocation failed\n); if (ctdbLogon(hSession, FAIRCOMS, ADMIN, ADMIN) == FNOP_ERR) { if (ctdbCreateSession(hSession, FAIRCOMS, ADMIN, ADMIN)!= CTDBRET_OK) FatalError(Error creating session dictionary file\n); if (ctdbLogon(hSession, FAIRCOMS, ADMIN, ADMIN) != CTDBRET_OK) FatalError(Session logon failed\n); }
When operations with the session are no longer needed, it is necessary to logout from the session by calling ctdbLogout().
CTHANDLE hSession; hSession = ctdbAllocSession(CTSESSION_CTDB); if (!hSession) FatalError(Session handle allocation failed\n); if (ctdbLogon(hSession, "FAIRCOMS", "ADMIN", "ADMIN") != CTDBRET_OK) FatalError(Session logon failed\n); /* perform some other operations on databases and tables */ if (ctdbLogout(hSession) != CTDBRET_OK) FatalError(Session logout failed\n); ctdbFreeSession(hSession);
FairCom Corporation
62
Session properties
The default session properties are suitable for most c-treeDB applications. Advanced developers may need to tune c-treeDB to meet application requirements. Use ctdbSetSessionParams() to set the following properties:
Property Description Index file buffers File structure blocks Node sectors Data file buffers User profile mask Default 10 32 32 10 513
The default USERPROF value of 513 tells single-user, transaction-control applications, to remove the auxiliary log files S*.FCS and L*.FCS upon successful termination of the application, and also removes the automatic key transformation. The table below presents all possible values for the USERPROF parameter.
Keyword Value 1 2 32 64 128 256 512 Explanation Do not perform auto tfrmkey Savenv mode for transactions Do not perform auto data - UNIFRMAT conversion Use a local library: not server Add tmpname to input path, otherwise use system tmpname Auto language conversion Clear transaction logs
Example
/* setting different user profile before logging on to session */ ctdbSetSessionParam(hSession, USERPROF, (USERPRF_NTKEY | USERPROF_CLRCHK)); if (ctdbLogon(hSession, FAIRCOMS, ADMIN, ADMIN) != CTDBRET_OK) FatalError(Session logon failed\n);
www.faircom.com
All Rights Reserved
63
Active property
A session is active if the user has logged on to a valid session dictionary using ctdbLogon(). To render a session inactive, log off using ctdbLogout(). To verify the status of the session, use ctdbIsActiveSession().
Example
/* if session is active, retrieve the server name, user logon name and user password */ if (ctdbIsActiveSession(hSession)) { printf(Server name: %s\n, ctdbGetServerName(hSession)); printf(User name : %s\n, ctdbGetUserLogonName(hSession)); printf(Password : %s\n, ctdbGetUserPassword(hSession)); }
Path property
The default path for client/server applications is the server directory, while the default path for non-server applications is the application directory. If, for any reason, there is the need to modify the location of the session dictionary, the function ctdbSetSessionPath() may be used, before creating and/or logging on to the session. ctdbGetSessionPath() may be used to retrieve the path for an active session. Using this property, it is even possible to have multiple session dictionaries, in separate directories. This is not required, since the concepts of restricting access to different users to diverse tables or databases may be implemented inside a unique session dictionary. The example below shows how to use the ctdbSetSessionPath() function to create a session dictionary file in a user specified directory, instead of the default directory
Example
CTHANDLE hSession; hSession = ctdbAllocSession(CTSESSION_CTDB); if (!hSession) FatalError(Session handle allocation failed\n); ctdbSetSessionPath(hSession, \new\session\dictionary); if (ctdbCreateSession(hSession, "FAIRCOMS", "ADMIN", "ADMIN") != CTDBRET_OK) FatalError(Error creating session dictionary file\n);
Managing Databases
Once the user performs a successful Session Logon, the session handle can be used to operate on databases. Every time a new database is created, or an existing database is added to a session, the database properties such as database name and path are placed in an entry of the database dictionary file. Every time a user activates a database by connecting using ctdbConnect(), the handle of that database is placed in a list of active (connected) databases within the session handle. When a database is deactivated or disconnected by ctdbDisconnect(), the database handle is removed from the list of active databases. A user may query the active database list by locating the first active database, the next active database, or finding a specific active database.
FairCom Corporation
64
ctdbCreateDatabase() creates a new database dictionary file with the database name and extension .FDD (FairCom Database Dictionary). Using the example above, the database dictionary file created is MyDatabase.fdd.
Dropping a Database
When you drop a database from a session, the database information is removed from the session dictionary, but the database dictionary file is left untouched. The drop database operation can be reversed with an add database operation. Drop a database from a session by calling ctdbDropDatabase().
/* drop MyDatabase from current session */ if (ctdbDropDatabase(hSession, MyDatabase) != CTDBRET_OK) { printf(Drop database failed\n); }
Deleting a Database
When you delete a database from a session, the database information is removed from the session dictionary and the database dictionary file is deleted. The delete database operation cannot be reversed and the database dictionary data will be lost. Delete a database from a session by calling ctdbDeleteDatabase().
/* delete MyDatabase from current session */ if (ctdbDeleteDatabase(hSession, MyDatabase) != CTDBRET_OK) { printf(Delete database failed\n); }
First Database
ctdbFirstDatabase() retrieves the name and path of the first database in a session. If the session has no databases, ctdbFirstDatabase() returns an INOT_ERR (101) code.
www.faircom.com
All Rights Reserved
65
Next Database
ctdbNextDatabase() retrieves the name and path of the next database in a session. ctdbNextDatabase() returns INOT_ERR (101) when no more databases exist for the current session.
/* display all databases in a session */ CTDBRET DisplayDatabases(CTHANDLE hSession) { CTDBRET Retval; TEXT dbName[MAX_NAME]; TEXT dbPath[MAX_NAME]; if ((Retval = ctdbFirstDatabase(hSession, dbName, sizeof(dbName), dbPath, sizeof(dbPath)) == CTDBRET_OK) do { printf(Database: %s Path:%s\n, dbName, dbPath); Retval = ctdbNextDatabase(hSession, dbName, sizeof(dbName), dbPath, sizeof(dbPath)); } while (Retval = CTDBRET_OK); if (Retval == INOT_ERR) Retval = CTDBRET_OK; return Retval; }
Find Database
ctdbFindDatabase() locates a specific database given the database name and, if the database exists, retrieve the database path. If a database cannot be found, ctdbFindDatabase() returns INOT_ERR (101).
/* return YES if database exist or NO if database does not exit */ CTBOOL DatabaseExist(CTHANDLE hSession, pTEXT dbName) { TEXT dbPath[MAX_NAME]; return (ctdbFindDatabase(hSession, dbName, dbPath, sizeof(dbPath)) == CTDBRET_OK) ? YES : NO; }
FairCom Corporation
66
The function above is shown for example only. The c-treeDB API function ctdbIsActiveDatabase() provides a more efficient way to check if a database is active.
www.faircom.com
All Rights Reserved
67
Error Handling
Most c-treeDB API functions return an error status to indicate if a particular function operation succeeded or not. Most c-treeDB API functions will also keep the last error status, if the function operation failed. The last error status can be manipulated with the following functions: ctdbGetError() retrieves the last error status. If a function succeeds, the success status is not kept by the c-treeDB API. ctdbSetError() sets the last error status, overwriting any previous error status kept by the c-treeDB API. ctdbClearError() clears the last error status.
/* clear error if error is INOT_ERR */ if (ctdbGetError(AnyHandle) == INOT_ERR) { ctdbClearError(AnyHandle); }
Transaction Processing
The c-treeDB API implementation of transaction processing functions closely follows the existing c-tree Plus API definition. The basic difference between the c-treeDB and c-tree Plus ISAM transaction processing API is the separation of locking mechanisms from transaction processing. While the c-tree Plus begin transaction API allows for locking modes to be specified, the c-treeDB API separates the locking functions from transaction functions. The code fragment below shows an example using the c-tree Plus ISAM call to process a transaction with locking:
/* start transaction enabling write locks */ TRANBEG(TRNLOG | ENABLE | LK_BLOCK); ... perform some data operations ... /* commit the transaction and release locks */ TRANEND(FREE);
The c-tree Plus code fragment above starts a transaction by invoking TRANBEG(). The mode ENABLE indicates that every c-tree Plus read record operation will lock the record for writing. The mode LK_BLOCK indicates that the thread will block until the lock is acquired. When using the c-treeDB API, the transaction processing API will not start the record locking mechanism. The code fragment below shows the equivalent example using c-treeDB API:
/* start a transaction */ ctdbBegin(AnyHandle); /* enable write locks */ ctdbLock(AnyHandle, CTLOCK_WRITE_BLOCK); ... perform some data operations ... /* release locks */ ctdbUnlock(AnyHandle); /* commit the transaction */ ctdbCommit(AnyHandle);
FairCom Corporation
68
ctdbBegin() starts a new transaction. ctdbCommit() terminates a transaction by committing any changes. ctdbAbort() terminates a transaction and aborts any changes done during the transaction. ctdbSetSavePoint() and ctdbSetSingleSavePoint() set a savepoint in the current transaction. Once a save point is set within the current transaction, ctdbRestoreSavePoint() will reverse only changes done in between the set save point and restore the save point, without terminating the transaction. Please refer to "Data Integrity" for detailed description of c-treeDB API for transaction processing and locking.
CTDATE_MDY
CTDATE_DMCY
www.faircom.com
All Rights Reserved
69
CTDATE_DMY
Date format is DD/MM/YY where DD represents a two-digit day, MM represents a two-digit month, and YY represents a two-digit year. The date separator may be one of the following characters: '/', '-', or '.'. Example: 01/12/02. Date format is CCYYMMDD where CC is a two-digit century, YY is a two-digit date, MM is a two-digit month, and DD is a two-digit day of the month. This date format has no separators. Example: 20021201.
CTDATE_CYMD
CTDATE_YMD
The date format is YYMMDD where YY represents a two-digit year, MM represents a two-digit month, and DD represents a two-digit day of the month. This date format has no separators. Example: 021201
ctdbSetDefTimeFormat() sets a new default time format. ctdbGetDefTimeFormat() retrieve the current default time format. The following time formats are supported: CTTIME_HMSP
Time format is HH:MM:SS AP where HH represents the hour with values between 1 and 12, MM represents a two-digit minute value between 00 and 59, SS represents a two-digit second value between 00 and 59 and AP is either AM or PM. The time separator may be ':' or '.'. Example: 1:35:45 AM. Time format is HH:MM AP where HH represents the hour with values between 1 and 12, MM represents a two-digit minute value between 00 and 59 and AP is either AM or PM. The time separator may be either ':' or '.'. Example: 1:35 AM. Time format is HH:MM:SS where HH represents an hour value between 0 and 23, MM represents a two-digit minute value between 00 and 59, and SS represents a two-digit second value between 00 and 59. The time separator may be either ':' or '.'. Example: 1:35:45
CTTIME_HMP
CTTIME_HMS
CTTIME_HM
Time format is HH:MM where HH represents an hour value between 0 and 23, MM represents a two-digit minute value between 00 and 59. The time separator may be either ':' or '.'. Example: 1:35.
CTTIME_MIL
Time format is HHMM (military format). HH represents a two-digit hour value between 00 and 23 and MM represents a two-digit minute value between 00 and 59. This time format has no separator. Example: 0135.
When converting floating point type fields, such as CT_SFLOAT, CT_DFLOAT and CT_EFLOAT to and from strings, c-treeDB uses the same float conversion format used by the C standard library functions printf() and scanf(). By default the float conversion format is set to %f. Use ctdbSetDefFloatFormat() to set a new default float conversion format. Use ctdbGetDefFloatFormat() to retrieve the current default float conversion format.
FairCom Corporation
70
Use ctdbGetUserTag() to retrieve the current user tag value associated with a handle. Use ctdbSetUserTag() to set the current user tag value associated with a handle. Both ctdbGetUserTag() and ctdbSetUserTag() accept any handle allocated by the ctdbAllocXXX() functions of the c-treeDB API. When a c-treeDB handle is released by calling one of the ctdbFree ...() functions, the user tag value is not automatically released. The user is responsible for releasing any dynamic memory controlled by pointers stored in the handle user tag space.
The ctdbLogon() call above performs a c-tree logon but it will not attempt to open a session dictionary file. The same result is obtained by allocating a CTSESSION_CTDB or CTSESSION_SQL session but calling ctdbSetLogonOnly() before ctdbLogon().
CTSESSION hSession; hSession = ctdbAllocSession(CTSESSION_CTDB); if (!hSession) FatalError(Session handle allocation failed\n); ctdbSetLogonOnly(hSession, YES); if (ctdbLogon(hSession, FAIRCOMS, ADMIN, ADMIN) != CTDBRET_OK) FatalError(Session logon failed\n);
ctdbDetachSession() detaches a c-treeDB session handle. The c-tree ISAM or low-level un-initialization is not called, but the session handle control structures are released and re-initialized.
www.faircom.com
All Rights Reserved
71
Example
/* logon to c-tree using ISAM function */ INTISAMX(10, 32, 32, 10, (USERPRF_NTKEY | USERPRF_CLRCHK)); /* attach session to server handle */ if (ctdbAttachSession(hSession, NO) != CTDBRET_OK) printf("ctdbAttachSession failed\n"); /* ... do something useful ... */ /* detach from session */ if (ctdbDetachSession(hSession) != CTDBRET_OK) printf("ctdbDetachSession failed\n"); /* perform an ISAM logout */ CLISAM();
Session Dictionary
The session dictionary is a collection of databases, and each record of the session dictionary file contains the information of a particular database. In general, just one session dictionary file exists, ctdbdict.fsd, located by default in the server directory (client/server development) or in the application directory (stand-alone application). The table below represents the general layout of a session dictionary file: Session Dictionary Layout
Field TYPE STATUS NAME LINK LINKNBR PATH SUPEXT DATEXT IDXEXT VERSION COUNTER UID OWNER Type Length 4 4 128 128 4 256 16 16 16 4 4 4 128 Description Record type: 1-database 2-table 3-index Record status: 0-status ok 1-reserved Name of database or table or index Name of table if record type is 3-index Table UID if record type is 3-index Path of database dictionary, data or index Super file extension (if super file is used) Data file extension (usually .DAT) Index file extension (usually .IDX) Record version: 0x00010000 (version 1.0) Deprecated. UID for database or table or index Name of owner - used by the c-treeSQL server
CT_INT4 CT_INT4 CT_FSTRING CT_FSTRING CT_INT4 CT_FSTRING CT_FSTRING CT_FSTRING CT_FSTRING CT_INT4 CT_INT4 CT_INT4 CT_FSTRING
FairCom Corporation
72
Type
Description Name of mirrored file. Path of mirrored file. Reserved for future use
This information is included for general information on the session dictionary structure. c-treeDB has appropriate functions to retrieve any needed information from the session dictionary, such as the database UID or path. A session dictionary file has several different record types: Database records (the field Type set to 1) holds information about databases. A special type four record which maintained the COUNTER field has been been deprecated as of c-tree Plus V9.0.
When the database handle is no longer needed, release it with ctdbFreeDatabase(). A database handle must be allocated or released by ctdbAllocDatabase() and ctdbFreeDatabase(). If you release an active database handle, ctdbFreeDatabase() automatically closes all tables associated with the database and disconnect the database from the session before releasing any database handle resources.
Connecting to a database
Before performing any operations with a database, except creating a new database, the database handle must be connected to the session by ctdbConnect(). The database should already have been
www.faircom.com
All Rights Reserved
73
created or added to the session. After a successful database connection to a session, the database is considered active.
CTHANDLE pMyDatabase; pMyDatabase = ctdbAllocDatabase(pMySession); ctdbConnect(pMyDatabase, MyFirstDatabase);
The first line above declares the Database handle, which is not required for the database creation. The allocation of the handle links the database to the session. Use ctdbConnect() to connect to the database using the database handle and name. If the database doesn't exist, or exists but was dropped from the session, this call returns INOT_ERR (101). As suggested in the session creation/logon, the best approach to avoid errors is to attempt to connect to the database, and if it doesn't exist, create it, as shown in the Tutorial and Sample programs. The database path is not required to connect, since this information is stored inside the Session Dictionary. When finished working with a database, disconnect it using ctdbDisconnect() or disconnect all databases at once with ctdbDisconnectAll(). If the database handle is not needed, free the allocated memory using ctdbFreeDatabase(). These steps are shown below, along with logging out from the session and freeing the session handle.
ctdbDisconnect(pMyDatabase); ctdbLogout(pMySession); ctdbFreeDatabase(pMyDatabase); ctdbFreeSession(pMySession);
Database properties
The default database properties are suitable for most c-treeDB applications. Advanced developers may need to tune c-treeDB to meet application requirements.
Database name
Once the database handle is connected, the database name can be retrieved by calling ctdbGetDatabaseName(). ctdbGetDatabaseName() returns NULL if the database handle is not connected or the database handle is invalid.
/* display the database name */ printf(Database: %s\n, ctdbGetDatabaseName(hDatabase));
Table count
ctdbGetTableCount() retrieves the number of tables associated with a database, or returns -1 if the database is not connected or if the database handle is invalid.
/* display the number of tables in database */ printf(Number of tables: %d\n, ctdbGetTableCount(hDatabase));
Database path
The database path, by default, is the server directory for client/server applications, or the application directory for non-server applications. To set a different database path, when the database is being created, just insert the appropriate path as the third parameter in ctdbCreateDatabase(). With this information stored in the Session dictionary, the user doesn't need to know where it is located, since it will be automatically retrieved given the database name (ctdbConnect()). Once the database is successfully connect to a session, the database path can be obtained by calling ctdbGetDatabasePath().
/* display database properties */ void DisplayDatabaseProperties(CTHANDLE hDatabase) { printf(Database: %s\n, ctdbGetDatabaseName(hDatabase)); printf( Path: %s\n, ctdbGetDatabasePath(hDatabase));
FairCom Corporation
74
Managing Tables
Once the user performs a successful database connect, the database handle can be used to operate on tables. Every time a new table is created, or an existing table is added to a database, some of the table properties such as table name, path, data file extension, index file extension, etc, are placed in an entry of the database dictionary file. Every time a user activates a table by opening it with ctdbOpenTable(), the handle of that table is placed in a list of active (connected) tables within the database handle. When a table is deactivated, or closed by calling ctdbCloseTable(), the table handle is removed from the list of active tables in the database handle. A user may query the active table list by locating the first active table, the next active table, or a specific active table.
75
/* add a field ctdbAddField(hTable, Field1, CT_INTEGER, 4); /* add another field */ ctdbAddField(hTable, Field1, CT_CHAR, 30); /* create the table */ ctdbCreateTable(hTable, MyTable, CTCREATE_NORMAL); /* commit the transaction */ ctdbCommit(hTable);
Dropping a table
When you drop a table from a database, the table information is removed from the database dictionary, but the table data and index files are left untouched. The drop table operation can be reversed with an add table operation. Drop a table from a database by calling ctdbDropTable().
/* drop MyTable from current database */ if (ctdbDropTable(hDatabase, MyTable) != CTDBRET_OK) printf(Drop table failed\n);
76
ctdbBegin(hDatabase); /* drop MyTable from current database */ if (ctdbDropTable(hDatabase, MyTable) != CTDBRET_OK) { printf(Drop table failed\n); ctdbAbort(hDatabase); } else { printf(Drop table\n); ctdbCommit(hDatabase); }
Deleting a table
When you delete a table from a database, the table information is removed from the database dictionary and the table data and index files are deleted from disk. The delete table operation can be reversed only when used under transaction control. Without transaction control, a delete table operation will delete the data and index files and the table data will be lost. Delete a table from a database by calling ctdbDeleteTable().
/* delete MyTable from current database */ if (ctdbDeleteTable(hDatabase, MyTable, NULL) != CTDBRET_OK) printf(Delete table failed\n);
ctdbDeleteTable() takes as parameters a database handle, the table name, and the table password. Set the password parameter to NULL if a table was created without a password.
First Table
ctdbFirstTable() retrieves the name and path of the first table in a database. If the database has no tables, ctdbFirstTable() returns INOT_ERR (101). See the example in "Next Table".
Next Table
ctdbNextTable() retrieves the name and path of the next table in a database or returns INOT_ERR(101) when no more tables exist for the current database.
/* Display all tables in a database */ CTDBRET DisplayTables(CTHANDLE hDatabase) { CTDBRET Retval; TEXT Name[MAX_NAME];
www.faircom.com
All Rights Reserved
77
TEXT Path[MAX_PATH]; if ((Retval = ctdbFirstTable(hDatabase,Name,sizeof(Name), Path,sizeof(Path)) == CTDBRET_OK) { do { printf(Table: %s Database: %s\n, Name, Path); Retval = ctdbNextTable(hDatabase, Name, sizeof(Name), Path, sizeof(Path); while (Retval == CTDBRET_OK); if (Retval == INOT_ERR) { Retval = CTDBRET_OK; } return Retval; }
Find Table
ctdbFindTable() locates a specific table given the table name and, if the table exists, retrieves the table path. If a table cannot be found, ctdbFindTable() returns INOT_ERR (101).
/* return YES if table exist or NO if table does not exit */ CTBOOL TableExist(CTHANDLE hDatabase, pTEXT tblName) { TEXT tblPath[MAX_NAME]; return(ctdbFindTable(hDatabase,TblName,tblPath,sizeof(tblPath)) == CTDBRET_OK) ? YES : NO; }
FairCom Corporation
78
The function above is shown for example purposes only. ctdbIsActiveTable() provides a more efficient way to check if a table is active.
The code fragment above is provided as example only. ctdbOpenTableByUID() will open a table using the table UID.
Database Dictionary
A database must have a database dictionary; this file has the database name with extension .fdd. It is created with ctdbCreateDatabase(), and must exist for the user to connect to the database. Each database dictionary maintains information about the tables associated with the database. When a database is connected to the session, it is considered active. Database Dictionary Layout
Field TYPE STATUS NAME Type Length 4 4 128 Description Record type: 1-database 2-table 3-index Record status: 0-status ok 1-reserved Name of database or table or index
www.faircom.com
All Rights Reserved
79
Field LINK LINKNBR PATH SUPEXT DATEXT IDXEXT VERSION COUNTER UID OWNER MIRROR_NAME MIRROR_PATH RESERVED
Type
Description Name of table if record type is 3-index Table UID if record type is 3-index Path of database dictionary, data or index Super file extension (if super file is used) Data file extension (usually .DAT) Index file extension (usually .IDX) Record version: 0x00010000 (version 1.0) Deprecated. UID for database or table or index Name of owner - used by the c-treeSQL server Name of mirrored file. Path of mirrored file. Reserved for future use
CT_FSTRING CT_INT4 CT_FSTRING CT_FSTRING CT_FSTRING CT_FSTRING CT_INT4 CT_INT4 CT_INT4 CT_FSTRING CT_FSTRING CT_FSTRING CT_ARRAY
This information is included for general information on the database dictionary structure. c-treeDB has appropriate functions to retrieve any needed information from the database dictionary, such as the table UID or path. A database dictionary file has several different record types: Table records (the field Type set to 2) holds information about a data file (table). Index records (the field Type set to 3) holds information about an index file. A special type four record which maintained the COUNTER field has been been deprecated as of c-tree Plus V9.0.
80
Open the table Operate on records With c-treeDB, it is possible to modify an existing table. The general process to modify a table after it has been created is as follows: Open the table Make changes to: Fields and/or Indices and/or Segments Call the alter table function: ctdbAlterTable(). More details on this process are described in "Altering a table". In general, the table creation is done once in the application; the table is opened and the data is added in a separate routine. During table creation, besides the table layer itself, three c-treeDB APIs will be directly involved: the fields, indices and segments. These APIs are only directly involved when the table is being created, or in the event the table structure is modified. When records are being added to or searched in the table, these APIs are not relevant, but the record layer is crucial. With this in mind, this section on Tables discusses these layers in the appropriate order: Table creation using fields, indices, and segments. Table parameters and properties. Opening and manipulating tables.
When the table handle is no longer needed it should be released by calling ctdbFreeTable(). A table handle must be allocated and released by ctdbAllocTable() and ctdbFreeTable(). If you release an active table handle, ctdbFreeTable() automatically closes the table and resets all record buffers associated with the table.
www.faircom.com
All Rights Reserved
81
hSession = ctdbAllocSession(CTSESSION_CTREE); /* Logon to session */ ctdbLogon(hSession, FAIRCOMS, ADMIN, ADMIN); /* Allocate a new table handle, note the use of a session handle, not a database handle */ hTable = ctdbAllocTable(hSession); /* Without database support, it is necessary to specify the path were the table is located */ ctdbSetTablePath(hTable, c:\\MyDocuments); /* Open the table */ ctdbOpenTable(hTable, mytable, CTOPEN_NORMAL);
Please note from the code above the need to specify the path where the table is located. If no path is specified, c-treeDB will try to open the table from the current directory. The same principle applies when creating a table without database support:
CTHANDLE hSession; CTHANDLE hTable; /* Allocate a new session handle without session dictionary support*/ hSession = ctdbAllocSession(CTSESSION_CTREE); /* Logon to session */ ctdbLogon(hSession, FAIRCOMS, ADMIN, ADMIN); /* Allocate a new table handle, note the use of a session handle, not a database handle */ hTable = ctdbAllocTable(hSession); /* add fields to table */ ctdbAddField(hTable, Field1, CT_INT2, 2); ctdbAddField(hTable, Field2, CT_FSTRING, 30); /* Without database support, it is necessary to specify the path were the table is located */ ctdbSetTablePath(hTable, c:\\MyDocuments); /* Create the table */ ctdbCreateTable(hTable, mytable, CTCREATE_NORMAL);
FairCom Corporation
82
Fields are added to the record definition in the order they are declared. The c-treeDB API also include a set of functions that will allow a field to be inserted at a certain place in the records definition and fields can also be deleted from the record definition. ctdbAddField() adds a new field to the end of the record definition.
/* allocate a new table handle */ CTHANDLE hTable = ctdbAllocTable(hDatabase); /* add two fields to the table record definition */ ctdbAddField(hTable, Field1, CT_INTEGER, 4); ctdbAddField(hTable, Field2, CT_CHAR, 30); /* create the table */ ctdbCreateTable(hTable, MyTable, CTCREATE_NORMAL);
ctdbInsField() and ctdbInsFieldByName() each insert a new field before a previously defined field. Use ctdbInsField() to specify the field index by its position in the record definition. The first field is number 0, the second field is number 1 and so on. Use ctdbInsFieldByName() to specify the field index by its name.
/* allocate a new table handle */ CTHANDLE hTable = ctdbAllocTable(hDatabase); /* add two fields to the table record definition */ ctdbAddField(hTable, Field1, CT_INTEGER, 4); ctdbAddField(hTable, Field2, CT_CHAR, 30); ctdbInsFieldByName(hTable, Field2, Field3, CT_BOOL, 1); /* create the table */ ctdbCreateTable(hTable, MyTable, CTCREATE_NORMAL);
ctdbDelField() and ctdbDelFieldByName() delete a field from the record definition. Use ctdbDelField() to delete a field specifying the field number. The first field is number 0, the second field is number 1, and so on. Use ctdbDelFieldByName() to delete a field specifying the field name.
/* allocate a new table handle */ CTHANDLE hTable = ctdbAllocTable(hDatabase); /* add two fields to the table record definition */ ctdbAddField(hTable, Field1, CT_INTEGER, 4); ctdbAddField(hTable, Field2, CT_CHAR, 30); ctdbDelFieldByName(hTable, Field2); /* create the table */ ctdbCreateTable(hTable, MyTable, CTCREATE_NORMAL);
Field types
c-treeDB, c-tree Plus for .NET, and c-treeVCL support all original c-tree Plus field types and includes redefinition for new field types. For compatibility reasons, the original c-tree Plus field types can be used, but FairCom suggests its users work with the new field types. Note that these do not represent new field types, however, substitute a new name of existing c-tree Plus field types. The new naming convention is used within the c-treeSQL product line, and offers a better description of the fields. There is absolutely no difference in using any of the definitions, however, for future compatibility and better program reading, the new field types offer an improved path.
c-treeDB Field Type c-tree Plus Field Type Equivalent Data Type Implementation One byte Boolean Signed one byte integer. Unsigned one byte integer. Signed two-byte integer. Unsigned two-byte integer.
www.faircom.com
All Rights Reserved
83
Implementation Signed four-byte integer. Unsigned four-byte integer. Signed four-byte integer interpreted as number of pennies (two fixed decimal places) Unsigned four-byte integer interpreted as date. Unsigned four-byte integer interpreted as time. Four-byte floating point. Eight-byte floating point. Time stamp. Extended precision floating point (not supported as a key segment). Arbitrary fixed length data. Fixed length binary data Fixed length delimited data. Fixed length string data Fixed length data with 1-byte length count Fixed length data with 2-byte length count Fixed length data with 4-byte length count Eight-byte signed integer Scaled BCD number Eight-byte signed integer interpreted as currency value with four fixed decimal digits. Varying length field data with 1-byte length count. Varying length field data with 2-byte length count. Variable length binary data of up to 65535 bytes. Varying length field data with 4-byte length count. Variable length binary data of up to 4294967295 bytes. Varying length field delimited data. Variable length string data.
CT_DATE CT_TIME CT_FLOAT CT_DOUBLE CT_TIMESTAMP CT_EFLOAT CT_BINARY CT_CHARS CT_FPSTRING CT_F2STRING CT_F4STRING CT_BIGINT CT_NUMBER CT_CURRENCY
CT_DATE CT_TIME CT_SFLOAT CT_DFLOAT CT_TIMES CT_EFLOAT CT_ARRAY CT_FSTRING CT_FPSTRING CT_F2STRING CT_F4STRING CT_BIGINT CT_NUMBER CT_CURRENCY
CTDATE CTTIME CTFLOAT CTFLOAT CTDATETIME CTFLOAT pTEXT, pUTEXT pTEXT pTEXT pTEXT pTEXT CTBIGINT CTNUMBER CTCURRENCY
CT_PSTRING CT_VARBINARY
CT_PSTRING CT_2STRING
pTEXT pTEXT
CT_LVB
CT_4STRING
pTEXT
CT_VARCHAR or CT_LVC
CT_STRING
pTEXT
FairCom Corporation
84
All the c-tree Plus for .NET field types are defined using the FIELD_TYPE enum.
c-tree Plus for .NET Field Type
BOOL TINYINT UTINYINT SMALLINT USMALLINT INTEGER UINTEGER MONEY DATE TIME FLOAT DOUBLE TIMESTAMP EFLOAT BINARY CHARS FPSTRING F2STRING F4STRING BIGINT NUMBER CURRENCY PSTRING VARBINARY LVB VARCHAR/LVC
www.faircom.com
All Rights Reserved
85
c-treeDB also automatically calculates the size of the fixed portion of a record by adding the size of the fixed length fields, taking into consideration the field alignment in the record buffer, until the first variable length field is encountered. The variable length fields are listed below, with the matching c-tree Plus data type in parentheses:
CT_PSTRING (CT_PSTRING) CT_VARBINARY (CT_2STRING) CT_LVB (CT_4STRING) CT_VARCHAR or CT_LVC (CT_STRING)
Any type of field can be placed anywhere in the record buffer and also be used as an index segment. c-treeDB makes full use of this feature by providing the user with an advanced dynamic record buffer management.
Hidden fields
There are three special fields that are automatically included by c-treeDB in the table record definition. c-treeSQL makes extensive use of the null flag and rowid fields: The delete flag ($DELFLD$) The null flag ($NULFLD$) The rowid fields ($ROWID$) These fields are transparently and automatically handled by the c-treeDB API and can't be handled directly by the field handling functions of the c-treeDB API. There are specific functions that will, in some cases, retrieve data and status information kept by the hidden fields. These fields are also optional and c-treeDB will operate correctly with tables that do not possess them. There are also table creation modes allowing developers to create c-treeDB tables without any, or all, of the hidden fields. The delete flag field is for internal deletion purposes and should not be modified. $DELFLD$ is a CT_ARRAY field of four bytes. The only purpose of this field is to keep a place at the beginning of the record to hold a c-tree delete flag byte when the record is deleted. Four bytes are used instead of just one byte due to alignment requirements. This is an internal c-treeDB requirement, and should not be modified or touched by the user. $NULFLD$ is a CT_ARRAY field with the size based on the number of user defined fields for the table. For each user defined field, one bit is reserved in $NULFLD$. The $NULFLD$ field keeps the NULL flag information for each user defined field. If a user field is null, the corresponding bit in $NULFLD$ will be set. When data is written to the field, the corresponding bit is cleared. The user should never modify or verify this field directly, but should use the appropriate API functions: ctdbGetFieldNullFlag() or ctdbIsNullField() verify if a field contains null data. Use ctdbSetFieldNullFlag() to set the null flag for a particular field. ctdbClearField() and ctdbClearRecord() also clear the null flag. $ROWID$ is a CT_INT8 (64-bit integer) field holding the auto increment value generated by c-tree every time a new record is added to the table. This field is a read-only field that acts as a unique record identifier. Retrieve the rowid using ctdbGetRowid(), or retrieve the record handle given its rowid using ctdbFindRowid(). To know if a table has support for rowid, use ctdbHasRowid(). $ROWID$ is used by c-treeSQL as a unique record identifier. For ISAM files or c-treeDB tables created with CTCREATE_NOWROWID flag, the $ROWID$ field will not exist. In this case the RECBYT offset will be used instead. Note: Record offsets may change for a given variable-length record when a record is updated to a larger record size than the original record. Therefore, the recbyt index cannot be used as a unique record identifier.
FairCom Corporation
86
By default, c-treeDB creates the three hidden fields. Tables created with the c-tree Plus ISAM and Low-level APIs will not include these fields by default. c-treeDB does not require the fields to operate, but they allow more advanced capabilities. When creating a new table, disable the inclusion of the hidden fields using the create modes CTCREATE_NONULFLD, CTCREATE_NODELFLD, and CTCREATE_NOROWID. The default table layout is presented below. Note: The first field added by the user is always field 0.
$DELFLD$ $NULFLD$ $ROWID$ user field 0 user field 1 user field n
ctdbAddIndex() takes a table handle, index name, index type, and two Boolean flags indicating if the index accepts duplicate keys and if the index should process null keys. The valid index types are:
c-treeDB Index Type c-tree Plus for .NET Index Type
Description Fixed length key Fixed length keys that are likely to have leading character duplication among the key values Variable length keys for which not much leading character duplication is expected. Variable length keys for which much leading character duplication is expected.
www.faircom.com
All Rights Reserved
87
CTINDEX_ERROR
ERROR_INDEX
Note: c-tree Plus for .NET Index Key Types are defined in the KEY_TYPE enum.The add and insert segment functions require a segment mode as the last parameter. Please refer to "Segment Modes", which describes the valid segment modes. An index can be deleted from the table index definition by calling ctdbDelIndex().
/* allocate a new table handle */ CTHANDLE hTable = ctdbAllocTable(hDatabase); /* add two fields to the table record definition */ ctdbAddField(hTable, Field1, CT_INTEGER, 4); ctdbAddField(hTable, Field2, CT_CHAR, 30); ctdbDelFieldByName(hTable, Field2); /* add index 0 - the first index */ ctdbAddIndex(hTable, MyIndex1, CTINDEX_FIXED, YES, NO); /* add index 0 segments */ ctdbAddIndexByName(hTable, 0, Field1, CTSEG_SCHSEG); /* add index 1 - the second index */ ctdbAddIndex(hTable, MyIndex2, CTINDEX_FIXED, NO, NO); /* add index 1 segments */ ctdbAddSegmentByName(hTable, 1, Field2, CTSEG_SCHSEG); ctdbAddSegmentByName(hTable, 1, Field1, CTSEG_SCHSEG); /* delete index 1 */ ctdbDelIndex(hTable, 1); /* create the table */ ctdbCreateTable(hTable, MyTable, CTCREATE_NORMAL);
Segment Modes
The segment modes based on absolute field number, also known as schema fields, are the preferred modes to use in the segment definition. The preferred segment modes are: CTSEG_SCHSEG CTSEG_USCHSEG CTSEG_VSCHSEG CTSEG_UVSCHSEG CTSEG_SCHSRL You may OR in the mode CTSEG_DESCENDING to the segment mode to specify the descending sort order for a segment. You can also or in the segment mode CTSEG_ALTSEG to specify an alternate collating sequence for the segment. Using the preferred segment modes makes c-treeDB based tables fully compatible with ISAM/Low Level applications and/or c-treeSQL applications.
c-treeDB Segment Modes c-tree Plus for .NET Segment Modes SCHSEG_SEG
Explanation Absolute field number Absolute field number - uppercase Absolute field number - pad strings Absolute field number - pad strings upper Absolute field number - auto increment Descending segment mode Alternative collating sequence
FairCom Corporation
88
CTSEG_ENDSEG
ENDSEG_SEG
The other segment modes are kept for compatibility with existing c-tree Plus applications. Advanced c-treeDB functions like ctdbAlterTable() may not work properly if the segment mode is not one of the preferred segment modes. You may specify these segment modes with ctdbAddSegmentEx(), which expects an absolute record offset where the segment is to start instead of a field indicator, the length in bytes of the segment, and the segment mode.
c-treeDB Segment Modes c-tree Plus for .NET Segment Modes
Explanation Absolute byte offset - No transformation Absolute byte offset - unsigned int/long Absolute byte offset - uppercase Absolute byte offset - auto increment Relative field number Relative field number - uppercase Absolute byte offset - signed int/long Absolute byte offset - float/double Absolute byte offset - not yet implemented Absolute byte offset - not yet implemented Descending segment mode Alternative collating sequence
CTSEG_REGSEG CTSEG_INTSEG CTSEG_UREGSEG CTSEG_SRLSEG CTSEG_VARSEG CTSEG_UVARSEG CTSEG_SGNSEG CTSEG_FLTSEG CTSEG_DECSEG CTSEG_BCDSEG CTSEG_DESCENDING CTSEG_ALTSEG
REGSEG_SEG INTSEG_SEG UREGSEG_SEG SRLSEG_SEG VARSEG_SEG UVARSEG_SEG SGNSEG_SEG FLTSEG_SEG DECSEG_SEG BCDSEG_SEG DESCENDING_SEG ALTSEG_SEG
c-tree Plus for .NET Segment Modes are defined in the SET_MODE enum.
ROWID index
Two indices are created by default during the table creation: the ROWID and RECBYT indices. The ROWID index holds the auto increment value generated automatically by c-tree every time a new record is added to the table. When a table is created with rowid support, a ROWID index is automatically created for the table. The operation of the ROWID index is transparent to the c-treeDB user. c-treeDB will automatically update the index entries. The ROWID index will not appear in the list of indexes for a table. The user cannot alter or delete the components of the ROWID index. Functions that deal with the ROWID index are: ctdbHasRowid() - to determine if the table has ROWID support; ctdbGetRowid() - to retrieve the ROWID for a given record; ctdbFindRowid() - to retrieve the record, given the ROWID.
www.faircom.com
All Rights Reserved
89
By default, all c-treeDB tables are created with support for the ROWID index. To create a table without ROWID support, the CTCREATE_NOROWID should be OR-d into the create mode parameter to the ctdbCreateTable() function.
RECBYT index
RECBYT indices were introduced in the c-tree Plus ISAM API to provide improved space management for variable length records in a table and to permit backward physical traversal of data files that contain resources and variable length records. A RECBYT index is an index based on the byte offset (recbyt) of the record being indexed. RECBYT indices are optional and the user can disable their creation by specifying the CTCREATE_NORECBYT when the table is created. When a table is created with RECBYT index support, a RECBYT index is automatically created for the table. The operations on the RECBYT indexes are transparent to the user. c-treeDB will automatically update the index entries. The RECBYT index will not appear in the list of indices for a table. The user cannot alter or delete the components of the RECBYT index. The use of RECBYT index has no impact on the fields in the record buffer of a table. There is no field associated with this index.
90
ctdbAddIndex(hTable, MyIndex1, CTINDEX_FIXED, YES, NO); /* add index 0 segments */ ctdbAddIndexByName(hTable, 0, Field1, CTSEG_SCHSEG); /* add index 1 - the second index */ ctdbAddIndex(hTable, MyIndex2, CTINDEX_FIXED, NO, NO); /* add index 1 segments */ ctdbAddSegmentByName(hTable, 1, Field2, CTSEG_SCHSEG); ctdbAddSegmentByName(hTable, 1, Field1, CTSEG_SCHSEG); /* create the table */ ctdbCreateTable(hTable, MyTable, CTCREATE_NORMAL);
The table create modes are a combination of the following valid modes. You can specify more than one create mode by OR'ing the following constants:
c-treeDB Table Create Mode c-tree Plus for .NET Table Create Mode
Value 0 1
Explanation Normal table creation. Use this mode when no other create mode apply. This mode implements transaction processing for a table but does not support automatic file recovery. Files with CTCREATE_PREIMG mode do not take any space in the system transaction logs. With this mode you will get the full benefit of transaction processing, including both atomicity and automatic recovery. If you are not sure of what mode to use, and you do want to use transaction processing, then use this mode. This mode forces the operating system to flush all disk cache buffers when a data write occurs. Setting this mode can slow performance of the file handler. On the other hand, it is an important feature to use if you want to ensure that all data writes are put to the disk immediately. It is particularly important if you are in an operating environment where the system crashes a lot, and you are not using transactions. However, this mode does not guarantee that operating system buffers will be flushed as expected. Tables created with this mode requires a record lock before a record can be updated. If a lock is not obtained, the error code DADV_ERR is returned.
CTCREATE_NORMAL CTCREATE_PREIMG
NORMAL_CREATE PREIMG_CREATE
CTCREATE_TRNLOG
TRNLOG_CREATE
CTCREATE _WRITETHRU
WRITETHRU _CREATE
CTCREATE _CHECKLOCK
CHECKLOCK _CREATE
16
32 Create the table without the RECBYT index.
www.faircom.com
All Rights Reserved
91
Value 64 128
Explanation Create the table without the ROWID index. Tables create with this mode requires a record lock as records are read. Obtain at least a read lock on a record before it can be read, otherwise the function will return error code DADV_ERR. Create the table with huge file support. With this mode on, tables will support 8 byte addresses for file offsets. This mode indicate that the create is to be created without the $DELFLD$ field support. This mode indicate that the table is to be created without the $NULFLD$ field support.
256
512
1024
Note: If you open a table that was created inside the current transaction (i.e., the transaction has not yet been committed or aborted), you must open the table in exclusive mode by specifying the CTOPEN_EXCLUSIVE mode to ctdbOpenTable().
FairCom Corporation
92
Opening a table
A table must be opened before any data operations within it can take place. Use ctdbOpenTable() to open a table.
/* open a table */ if (ctdbOpenTable(hTable, MyTable, CTOPEN_NORMAL) != CTDBRET_OK) printf(Open table failed\n);
After opening the table, usual operations like add, update, delete, and search for records can be done. Record operations are described in detail in "Working with Tables" . ctdbOpenTable() takes as parameters a newly allocated table handle, the table name, and the table open mode.
c-treeDB File Open Mode c-tree Plus for .NET File Open Mode
Explanation Use this mode if no other open modes apply. Open only the data table. Used to rebuild a table that may or may not be missing indices. This mode opens the table as exclusive. If this mode is used, only one user can open a table. If an application already has the file open in any mode, no other application can open the table as CTOPEN_EXCLUSIVE. Once an application opens a table as CTOPEN_EXCLUSIVE, no other application can open it. Reads and writes are cached for index files opened with this file mode since there are no integrity issues with only one process in the file. Many operating systems and/or C compiler run-time libraries limit the number of files that can be opened at one time. A permanent file open causes the file to be opened and stay open until the program executes a file close. A non-permanent file open causes the table data and index files to be opened, but allows them to be transparently closed and reopened to allow other data and index files to be used. When it is necessary for a data and index file to be temporarily closed, c-tree Plus selects the least recently used file. This file remains closed until it is used, at which time it will be automatically reopened. This strategy causes c-tree Plus to use all available file descriptors.
CTOPEN_NORMAL CTOPEN_DATAONLY
NORMAL_OPEN DATAONLY_OPEN
CTOPEN_EXCLUSIVE
EXCLUSIVE_OPEN
CTOPEN_PERMANENT
PERMANENT_OPEN
www.faircom.com
All Rights Reserved
93
Explanation This mode opens tables with corrupted indexes or in certain cases, tables with corrupted data. With c-treeDB this mode is usually used in conjunction with ctdbAlterTable() mode to perform a rebuild if the indexes became corrupted: open table with CTOPEN_CORRUPT mode, then call ctdbAlterTable() with CTDB_ALTER_INDEX mode to force the rebuild of all indices of the table. You can also specify ctdbAlterTable() mode (CTDB_ALTER_INDEX | CTDB_ALTER_PURGEDUP) to purge any duplicate records that may cause the index rebuild to fail. If a table table becames corrupt, the table may be open with CTOPEN_CORRUPT mode and then ctdbAlterTable() with CTDB_ALL_FULL is invoked to try to recover the table. Tables opened with this mode requires a record lock before a record can be updated. If a lock is not obtained, the error code DADV_ERR is returned. Tables opened with this mode requires a record lock as records are read. Obtain at least a read lock on a record before it can be read, otherwise the function will return error code DADV_ERR. Opens the table in READONLY mode and does not allow any modifications to the table structure or data records.
CTOPEN_CORRUPT
CORRUPT_OPEN
CTOPEN_CHECKLOCK
CHECKLOCK_OPEN
CTOPEN_CHECKREAD
CHECKREAD_OPEN
CTOPEN_READONLY
READONLY_OPEN
Note: c-tree Plus for .NET users can find the open modes listed in the OPEN_MODE enum.
FairCom Corporation
94
Closing a table
After a successful open table, and the table handle is no longer needed, the table should be closed, to allow all c-treeDB, c-tree Plus and operating systems buffers to be flushed to disk. It is very good programming practice to always close every open table before the process or thread is terminated.
/* close the table */ if (ctdbCloseTable(hTable) != CTDBRET_OK) printf(Close table failed\n);
Altering a table
The c-treeDB alter table function was designed and implemented to allow the modification of table, field and index properties after a table was created, and possibly already populated with data. The usual steps to perform an alter table are: Add, insert, delete or edit fields Add, edit or delete indices Alter the table by calling ctdbAlterTable()
95
deleted or the index properties changed, only that index is rebuilt. If more than one index changed, or more than one index was added or deleted, then it may be necessary to rebuild all indices of the table. If fields were added, deleted, inserted, or the changes in the field property were not compatible with each other, then Alter needs to perform a full rebuild of the table. A table is rebuilt by creating a temporary table with the correct current properties taking into consideration all changes. All records are read from the original table and written into the temporary table. Once all data records have been moved, the original table is deleted and the temporary table is renamed with the name of the original table.
/* add one field to the table and rebuild it */ CTHANDLE hTable = ctdbAllocTable(hDatabase); /* open the table */ ctdbOpenTable(hTable, MyTable, CTOPEN_NORMAL); /* add one field to the table */ ctdbAddField(hTable, Wages, CT_CURRENCY, 8); /* alter the table */ if (ctdbAlterTable(hTable, CTDB_ALTER_NORMAL) != CTDBRET_OK) printf(Alter table failed\n);
ctdbAlterTable() takes as parameters an active table handle and an alter table action:
Action Value 0 1 Explanation Check for table changes before altering the table and perform only the changes required. Force rebuild of all indexes, regardless of table changes.
Default Values
c-treeDBs alter table function can be used to alter the schema of an existing table by adding new fields or modifying existing fields of the specified table. During an alter table operation, when a new field is added to the table, or when an existing field type is changed, an optional default field value can be specified for these fields. The default value of a field is used during an alter table operation when a full table rebuild is performed. During a full alter table rebuild, and after the old record buffer data is moved to the new record buffer, the new record buffer is scanned and, if a NULL field is found and that NULL field has a default value, the default value is copied to the field buffer. Typically the default field value is applied for new fields added to the table and to existing fields that have their types changed and the field value is NULL. The field default value is kept as a string representation of the data. It is recommended that numeric data should be converted to string using one of the rich set of c-treeDB data conversion functions. Binary data can also be used by passing the pointer to data and the appropriate length. The default value is set by calling the ctdbSetFieldDefaultValue() function.
Example
/* set the default value for country - field #5 */ hField = ctdbGetField(hTable, 5); if (hField) if (ctdbSetFieldDefaultValue(hField, "USA", 3) != CTDBRET_OK) printf("ctdbSetFieldDefaultValue failed\n");
96
Example
/* check if default field value is 'USA' */ hField = ctdbGetField(hTable, 5); if (hField) { VRLEN len; pTEXT value = ctdbGetFieldDefaultValue(hField, &len); if (value) { if (strcmp(value, "USA") == 0) printf("Default value is 'USA'\n"); else printf("Default value is not 'USA'\n"); } else printf("No default value set\n"); }
You can check if a default value is set by calling the ctdbIsFieldDefaultValueSet() function.
Example
/* check if default field value is set */ hField = ctdbGetField(hTable, 5); if (ctdbIsFieldDefaultValueSet(hField)) printf("Default field value is set\n"); else printf("No default field value\n");
Once set, a default field value will remain in place until the table handle is closed. The ctdbClearFieldDefaultValue() function clears the default value associated with a field. The default date and time types are also reset to their default values of CTDATE_MDCY and CTTIME_HMS respectively.
Example
/* clear the default field value */ hField = ctdbGetField(hTable, 5); if (hField) if (ctdbClearField(hField) != CTDBRET_OK) printf("ctdbClearField failed\n");
You can clear the default values for all fields in a table by calling the ctdbClearAllFieldDefaultValue() function.
Example
/* clear all default field values *. if (ctdbClearAllFieldDefaultValue(hTable) != CTDBRET_OK) printf("ctdbClearAllFieldDefaultValue failed\n");
The default date and time types used for conversions to and from strings can be changed by calling the ctdbSetFieldDefaultDateTimeType() function. When setting the default field values with date, time or timestamp data, the data must be first converted to string. By default the date type is CTDATE_MDCY while the default time type is CTTIME_HMS. The possible date formats for string conversion are:
www.faircom.com
All Rights Reserved
97
Description Date is mm/dd/ccyy Date is mm/dd/yy Date is dd/mm/ccyy Date is dd/mm/yy Date is ccyymmdd Date is yymmdd
Value Time Types can be one of the following string time formats:
c-treeDB Symbolic Constant c-tree Plus for .NET Symbolic Constant
Description Time is hh:mm:ss am|pm Time is hh:mm am|pm Time is hh:mm:ss (24 hour) Time is hh:mm (24 hour) Time is hhmm (military)
Example
/* set the field default date and time types */ hField = ctdbGetField(hTable, 5); if (hField) if (ctdbSetFieldDefaultDateTimeType(hField, CTDATE_DMY, CTIME_HMP)) printf("ctdbSetFieldDefaultDateTimeType failed\n");
The default date type value can be retrieved by calling the ctdbGetFieldDefaultDateType() function.
Example
/* check the default date type */ hField = ctdbGetField(hTable, 5); if (ctdbGetFieldDefaultDateType(hField) != CTDATE_MDCY) printf("Default date type is not OK\n");
The default time type value can be retrieved by calling the ctdbGetFieldDefaultTimeType() function.
Example
/* check the default time type */ hField = ctdbGetField(hTable, 5); if (ctdbGetFieldDefaultTimeType(hField) != CTDBRET_OK) printf("Default time type is not OK\n");
FairCom Corporation
98
www.faircom.com
All Rights Reserved
99
Example
CTHANDLE hSession = ctdbAllocSession(CTSESSION_CTREE); CTHANDLE hTable = ctdbAllocTable(hSession); CTHANDLE hRecord = ctdbAllocRecord(hTable); NINT datno, count = 0; /* logon to c-tree */ ctdbLogon(hSession, SERVER, USER, PASSWD); /* open the file using c-tree ISAM */ datno = (NINT)OPNRFILX((COUNT) -1, "test309.dat", (COUNT)0, NULL); /* attach to table */ ctdbAttachTable(hTable, datno); /* read the records */ if (ctdbFirstRecord(hRecord) == CTDBRET_OK) do { count++; } while (ctdbNextRecord(hRecord) == CTDBRET_OK);
FairCom Corporation
100
Table Properties
Table name
The table name is a read-only property that can't be changed once the table is created. Use ctdbGetTableName() to retrieve the table name.
Table Path
The table path property is set to NULL by default. If this property is not changed prior to calling ctdbCreateTable(), the table is created in the same directory as the database. Call ctdbSetTablePath() to change the table path property. ctdbGetTablePath() retrieves the current table path.
Table password
By default tables do not have a password (i.e.. the password property is set to NULL). If a table is to be created with a password, change this property before creating the table with a call to ctdbCreateTable(). Use ctdbSetTablePassword() to set the password and ctdbGetTablePassword() to retrieve it.
www.faircom.com
All Rights Reserved
101
Table group ID
The group ID can be used to manage table permissions for multiple users. By default, no group ID settings are specified for c-treeDB tables (i.e., the default group ID value is NULL). If a table is to be created with a group ID, set the value of this property before creating the table with a call to ctdbCreateTable(). To set a group ID, use ctdbSetTableGroupid() and ctdbGetTableGroupid() to retrieve it.
Explanation owner read permission owner write/update permission owner file definition permission owner file deletion permission owner granted all permissions owner grants read only without password group access denied group read permission group write/update permission group file definition permission group file deletion permission group read only access without password world access denied world read permission world write/update permission world file definition permission world file deletion permission world read only access without password
OPF_READ OPF_WRITE OPF_DEF OPF_DELETE OPF_ALL OPF_NOPASS GPF_NONE GPF_READ GPF_WRITE GPF_DEF GPF_DELETE GPF_NOPASS WPF_NONE WPF_READ WPF_WRITE WPF_DEF WPF_DELETE WPF_NOPASS
O_READ O_WRITE O_DEF O_DELETE O_ALL O_NOPASS G_NONE G_READ G_WRITE G_DEF G_DELETE G_NOPASS W_NONE W_READ W_WRITE W_DEF W_DELETE W_NOPASS
FairCom Corporation
102
Number of fields
The number of fields property indicates the total number of fields defined for a table. The value takes into consideration only user defined fields and does not include any hidden fields that exist for the table. Use ctdbGetFieldCount() to retrieve the number of fields associated with a table.
Number of indices
The number of indices property indicates the total number of indices defined for a table. The value takes into consideration only user defined indices and does not include the RECBYT or ROWID indices. Use ctdbGetIndexCount() to retrieve the number of indices associated with a table.
Field padding
By default the c-treeDB API pads fixed length string fields CT_CHARS (CT_FSTRING), CT_FPSTRING, CT_F2STRING, and CT_F4STRING with NULL ('\0') bytes. The field padding property sets the table pad and field delimiter characters to allow proper target key formation. This property allows the c-treeDB API to operate on files created using the c-tree Plus ISAM and Low-Level APIs using a fixed string padding strategy that is different from the c-treeDB API default. Use ctdbSetPadChar() to set the pad and field delimiter characters and ctdbGetPadChar() to retrieve the current pad and field delimiter characters.
/* set the table pad and delimiter characters to spaces */ if (ctdbSetPadChar(hTable, ' ', ' ') != CTDBRET_OK) printf('Set pad characters failed\n);
The most common strategies for padding fixed string fields are: Pad with NULLs: pad character is '\0' and field delimiter is '\0' Pad with spaces: pad character is ' ' and field delimiter is ' ' Pad with spaces and terminate with NULL: pad character is ' ' and field delimiter is '\0'
ctdbUpdateCreateMode() changes critical file mode attributes such as the level of transaction control. No check is made to determine if the mode change will damage data. No check is made if the new mode is valid. Use this function with caution as data may be lost. For instance, changing a data file from transaction processing to no transaction processing makes automatic recovery unavailable. The mode parameter passed to ctdbUpdateCreateMode() represents the new table create mode. It must be perfectly formed, as it will replace the current table create mode. Use ctdbGetTableCreateMode() to retrieve the current create mode and apply the changes on a fully qualified create mode. Update only the following create table modes: CTCREATE_PREIMG CTCREATE_TRNLOG CTCREATE_WRITETHRU CTCREATE_CHECKLOCK CTCREATE_CHECKREAD
www.faircom.com
All Rights Reserved
103
CTCREATE_HUGEFILE
The user fields are stored in the table record in the same order in which they were added.. To initiate the operation on the records, a record handle must be declared and instantiated. Once the table associated
FairCom Corporation
104
with the record handle is opened, the record can be used to store the information that come from or go to the fields in the table.
Resetting a record
A record handle may be reset to its initial state, i.e. to the same state it had just after being allocated, by calling ctdbResetRecord(), which performs the following actions on a record handle: The context associated with the record is released Record sets are turned off Memory allocated for record buffer is released Record properties are reinitialized.
/* reset a record */ if (ctdbResetRecord(hRecord) != CTDBRET_OK) printf(Reset record failed\n);
All records associated with a table can be reset in one ctdbResetAll() call.
/* reset all records */ if (ctdbResetAll(hTable) != CTDBRET_OK) printf(Reset all records failed\n);
When a table is closed, all records associated with that table are automatically reset by ctdbCloseTable().
ctdbSetRecordBuffer() takes as parameters the record handle, a user-supplied record buffer address, the size of the buffer, and the record buffer mode. The valid record buffer modes are:
www.faircom.com
All Rights Reserved
105
Mode
Explanation This is the default record buffer management mode. When a record handle is allocated by calling ctdbAllocRecord(), the record buffer management mode is set to CTRECBUF_AUTO. This mode implies that the c-treeDB will perform the data record buffer management dynamically. When this mode is set, the data record buffer is set to pBuffer and the user is responsible to supply a buffer that is large enough to perform all record operations for the table. OR with CTRECBUF_STATIC to indicate the record manager is not allowed to update the internal control structures of the record buffer for variable length records.
CTRECBUF_AUTO
CTRECBUF_STATIC
CTRECBUF_RAW
To reset the record buffer management back to CTRECBUF_AUTO, after it has been changed to CTRECBUF_STATIC, call ctdbSetRecordBuffer() passing the record handle, NULL buffer, with length of zero and CTRECBUF_AUTO mode.
/* reset the record buffer to automatic */ if (ctdbSetRecordBuffer(hRecord, NULL, 0, CTRECBUF_AUTO) != CTDBRET_OK) printf(Reset record buffer failed\n);
Use ctdbGetDefaultIndex ()to retrieve the current index or ctdbGetDefaultIndexName() to retrieve the name of the current default index.
/* make sure the default index is set to MyIndex */ if (strcmp(ctdbGetDefaultIndexName(hRecord), MyIndex) != 0) if (ctdbSetDefaultIndexByName(hRecord, MyIndex) != CTDBRET_OK) printf(Set default index failed\n);
The default index is set initially to the first user defined index. Once an index is chosen as the default index, all subsequent searches will be done using this index until a new default index is selected. The default index dictates the order in which records are retrieved by using ctdbFirstRecord(), ctdbLastRecord(), ctdbNextRecord(), and ctdbPrevRecord(). Perform a chronological search in the records in a table using ctdbFirstRecord() and ctdbNextRecord(), given the ROWID index as the default index:
ctdbSetDefaultIndex(hRecord, CTDB_ROWID_IDXNO);
FairCom Corporation
106
Navigating records
c-treeDB provides features that allow navigation among records of a particular table. You can position the current record at the first record, last record, next record, previous record, or seek to a specific record if you know the record offset. Setting a different default index for the record may change the order of the record navigation. The record navigation function not only updates the current position of a record, but the record data is read from disk and placed in the record buffer inside the record handle. As the record is read from disk, the new record flag is set to false to indicate that the data in the record buffer originated from an existing record in the table.
First record
Call ctdbFirstRecord() to position the current record at the first record of a table. If the table is empty (i.e., the table contains no records), ctdbFirstRecord() returns INOT_ERR (101).
/* get the first record of the table */ if (ctdbFirstRecord(hRecord) != CTDBRET_OK) printf(First record failed\n);
Last record
Call ctdbLastRecord() to position the current record at the last record of a table. If the table is empty (i.e., the table contains no records), ctdbLastRecord() returns INOT_ERR (101).
/* get the last record of the table */ if (ctdbLastRecord(hRecord) != CTDBRET_OK) printf(Last record failed\n);
Next record
ctdbNextRecord() positions the current record at the next record of a table. If the current record was the last record of a table, ctdbNextRecord() returns INOT_ERR (101).
/* get the next record */ if (ctdbNextRecord(hRecord) != CTDBRET_OK) printf(Next record failed\n);
A current record must exist before ctdbNextRecord() is called or an ICUR_ERR (100) error is returned indicating that there can be no next record if the current record does not exist. Establish a current record by calling ctdbFirstRecord(), ctdbLastRecord(), ctdbFindRecord(), or ctdbSeekRecord().
Previous record
ctdbPrevRecord() positions the current record at the previous record of a table. If the current record was the first record of a table, ctdbPrevRecord() returns INOT_ERR (101).
/* get the previous record */ if (ctdbPrevRecord(hRecord) != CTDBRET_OK)
www.faircom.com
All Rights Reserved
107
A current record must exist before ctdbPrevRecord() is called or an ICUR_ERR (100) error is returned indicating that there can be no previous record if the current record does not exist. You can establish a current record by calling ctdbFirstRecord(), ctdbLastRecord(), ctdbFindRecord(), or ctdbSeekRecord().
Seek to record
If you know in advance what is the offset of a given record, ctdbSeekRecord() can be used to make it the current record. You can use ctdbGetRecordPos() and ctdbSeekRecord() to implement a bookmark system for your records. Retrieve the record offset with ctdbGetRecordPos(), that is the bookmark value, and later on you can quickly come back to the record by calling ctdbSeekRecord().
/* get record bookmark */ CTOFFSET GetBookMark(CTHANDLE hRecord) { CTOFFSET Retval; ctdbGetRecordPos(hRecord, &Retval); return Retval; } /* goto record bookmark CTDBRET GotoBookmark(CTHANDLE hRecord, CTOFFSET bookmark) { return ctdbSeekRecord(hRecord, bookmark); }
Finding records
You can search for records in a table using one of the ctdbFindRecord(), ctdbFindTarget() and ctdbFindRowid() functions. c-treeDB performs the find operations against the table indices, when an index entry is found, the record data is loaded into the record buffer. Before you can call ctdbFindRecord(), you need to prepare the data you want to find: 1. Clear a record buffer 2. Set the default index with the appropriate value 3. Populate the fields that makeup the index segment 4. Call ctdbFindRecord() with the appropriate find mode
/* find record which product code is DISKETTE */ CTHANDLE hRecord = ctdbAllocRecord(hTable); /* clear the record buffer */ ctdbClearRecord(hRecord); /* set the default index to index 0 */ ctdbSetDefaultIndex(hRecord, 0); /* populate the 'product' field (field 1)*/ ctdbSetFieldAsString(hRecord, 1, DISKETTE); /* find the record */ if (ctdbFindRecord(hRecord, CTFIND_EQ) != CTDBRET_OK) printf(Record not found\n);
ctdbFindRecord(), ctdbFindTarget() and ctdbFindRowid() returns CTDBRET_OK if a record is found or INOT_ERR (101) if no record is found. Any other return value indicates an error condition.
FairCom Corporation
108
Find Modes
Use the following find modes with the record find methods:
c-treeDB Find mode c-tree Plus for .NET Find Mode Explanation Find a record equal to the target Find a record less than target Find a record less or equal than target Find a record greater than target Find a record greater or equal than target
EQ LT LE GT GE
Note: The Find Mode CTFIND_EQ requires that the target contains values for all segments that compose the index and the index cannot allow duplicates. Note: c-tree Plus for .NET defines this mode with the FIND_MODE enum.
www.faircom.com
All Rights Reserved
109
Record sets
An alternative and more efficient way to retrieve records is the use of Record Sets. A record set contains part of a table, representing a group of records that have keys that match a certain target. For example, an index contains the following keys:
CASE DISKCASE DISKDRIVE DISKETTE KEY KEYBOARD KEYCAP
When scanning through the index looking for records, record navigation functions work on the entire index file. Navigating to the first record obtains the first key in the index, CASE, and moving to the next record obtains each of the following keys in turn, on through KEYCAP. When creating a record set using ctdbRecordSetOn(), with a target of DISK and a target length of 4, c-treeDB returns only the records in which the first 4 bytes of the key start with DISK. The record navigation functions will operate only on the records that match the set until the record set operation is terminated with a call to ctdbRecordSetOff(). To work with multiple record sets at once, use more than one record handle. Record sets allow a faster search for records, in particular in the client/server mode since fewer records may be retrieved and less traffic on the network will be generated. When worked in conjunction with filters (see below), record sets allow for simple queries. To use record sets, follow the steps below: 1. Clear the record buffer 2. Set the index you want to use 3. Populate the index segments you would like to participate in the set 4. Establish the Set
Once the record set is created, ctdbFirstRecord(), ctdbNextRecord(), ctdbLastRecord() and ctdbPrevRecord() will return only the records that match the record set criteria.
110
/* terminate the record set */ if (ctdbRecordSetOff(hRecord) != CTDBRET_OK) printf(Terminating record set failed\n);
Once the record set is terminated, ctdbFirstRecord(), ctdbNextRecord(), ctdbLastRecord() and ctdbPrevRecord() will operate again will all records of a table.
Record Filters
c-treeDB allows the user to define filters on the record using ctdbFilterRecord(). When a filter is set, all records retrieved from the table will be filtered against the given expression, and just those records that match the filter criteria will be returned.
/* set the filter */ if (ctdbFilterRecord(hRecord, ZIPCODE == 12345) != CTDBRET_OK) printf(Start filter failed\n);
Only the user who sets the filter will have its records filtered. The filter is turned off when the table is closed, or when ctdbFilterRecord() is called with a NULL or an empty string as the filter expression. Just one filter may be active per table per user at once, so if a new filter is set to a table with an existing filter for the specific table, the old filter will be overridden.
/* terminate the filter */ if (ctdbFilterRecord(hRecord, NULL) != CTDBRET_OK) printf(Terminate filter failed\n);
Use ctdbGetFilter() to retrieve the current filter expression. If no filters are active, ctdbGetFilter() return NULL. Use ctdbIsFilteredRecord() to test if filters are active for a table. When used in the client/server model, this feature has the potential to increase the performance since just the records matching the criteria will be returned, reducing the network traffic. Record filters, when used in conjunction with sets (ctdbRecordSetOn()), provide the c-treeDB API with simple query capabilities.
Constants The expression parser uses the constants below internally as a 32-bit signed or unsigned integer: Character constants: any valid char enclosed in single quotes, e.g., a Signed Integer constants: values from - 2,147,438,647 to 2,147,438,647 Unsigned Integer constants: values from 0 to 4,294,967,295 Hexadecimal constants: values from 0x00000000 to 0xffffffff. Any combination of lowercase or upper case letters are accepted, e.g., 0Xbc4f or 0xF5C56d Any integer larger than the maximum size allowed for integers, or any number with decimal points, or any numbers in scientific notation are interpreted as a floating point constant by the expression parser .
www.faircom.com
All Rights Reserved
111
String constants are similar to C string constants and represent any text enclosed by double quotes, e.g., This is a string. The maximum size of a string constant defaults to 255 characters. The filter expression parser allows the following escape characters in string constants or character constants:
Escape char \a or \A \b or \B \f or \F \n or \N \r or \R \t or \T \v or \V \\ \any Any character not listed above Value ASCII 7 ASCII 8 ASCII 12 ASCII 10 ASCII 13 ASCII 9 ASCII 11 Explanation bell backspace Form Feed Linefeed Carriage Return tab vertical tab
Variables A filter expression variable is actually the name of the fields defined for the table. There is a limit of 128 characters for the name of variables and the names are case sensitive. When a user specifies a variable name, the filter parser searches the table definition for a field of that name. The parser uses the type of the field and converts it to the types used internally by the expression evaluator. The conversion of field types is as follows:
Field Type Data Type int int unsigned int unsigned int unsigned unsigned unsigned int Field Type Data Type double double char* char* char* char* char* char* char* char*
CT_BOOL CT_CHAR CT_CHARU CT_INT2 CT_INT2U CT_INT4 CT_INT4U CT_DATE CT_TIME CT_MONEY
CT_SFLOAT CT_DFLOAT CT_FSTRING CT_FPSTRING CT_F2STRING CT_F4STRING CT_STRING CT_PSTRING CT_2STRING CT_4STRING
Please note that int is a LONG, unsigned is a ULONG and char* is a pTEXT.
FairCom Corporation
112
Parentheses Use parentheses exactly like they are used in C expressions. There are no limits on the number of parentheses you may use in an expression, as long as each open parenthesis has a closing parenthesis. Parentheses are also used to enclose the arguments of built-in functions. Predefined Functions The conditional expression parser has a number of built-in functions to make the use of expressions easier. The built-in functions closely follow the C library functions:
Function int atoi( char* String ) int atol( char* String ) double atof( char* String ) int cabs( into Value ) int labs( into Value ) double fabs( double Value ) double ceil( double Value ) double floor( double Value ) double fmod( double r, double t ) int strlen( char* String ) int strcmp( char* s, char* t ) int stricmp( char* s, char* t ) int strncmp( char* s, char* t, int len) int strnicmp( char* s, char *t, int len ) int memcmp(char* s, char *d, int len) Explanation convert string to integer convert string to long convert string to double return the absolute value of a complex number. return the absolute value of a long integer. return the absolute value of a double return the ceiling of a value return the floor of a value return the remainder of r by t as a double return the length of a string compare two strings compare strings without regard to case compare characters of two strings compare characters of two strings without regard to case compare bytes of two memory locations
Type Casting The filter expression parser allows you to use explicit type casts in expressions. This is very useful if you are comparing fields of different types and want to control the result of an expression. For example, suppose Salary is a CT_MONEY field and Average is a CT_DFLOAT field; type casts can be used as illustrated in the following expression: (Salary - (int)Average) > 500 The following type casts may be used in conditional expressions: (int) or (long): Convert the result of expression to integer (32 bit). (unsigned [int | long]): Convert the result of expression to unsigned integer (32 bit). (double): Convert the result of expression to double. You cannot type cast a string expression.
www.faircom.com
All Rights Reserved
113
Automatic Type Promotion When mixing different types in an expression without explicit type casting, the conditional expression parser automatically promotes the types using the following rule: signed and unsigned integers: promoted to unsigned integer signed integer and double: promoted to double unsigned integer and double: promoted to double In the great majority of cases, mixing strings with numeric values returns a parsing error. Operators The following operators are allowed in conditional expressions: Mathematical operators + Adds two operands - Subtracts two operands or negates an operand (e.g., -5) * Multiplication / Division % Modulus == Equal to != Not equal to < Less than <= Less or equal to > Greater than >= Greater than or equal to && And || Or ! Not & And | Or ~ Not ^ Xor
Relational operators
Logical operators
Binary operators
Record Batches
There are situations where a record fetch, a record insert or a record delete operation has to be applied to a group of related records. For example, if an invoice record is being displayed, it may be necessary to retrieve all invoice items for that invoice as well. The following code fragment shows a typical c-treeDB C function to extract all items of an invoice, given the invoice number.
FairCom Corporation
114
NINT count = 0; TEXT target[32]; VRLEN len = sizeof(target); /* find the first record that match the Invoice */ ctdbClearRecord(hRecord); ctdbSetFieldAsSigned(hRecord, 0, Invoice); if (ctdbFindRecord(hRecord, CTFIND_GE) == CTDBRET_OK) { LONG val; /* make sure all record invoice numbers match */ ctdbGetFieldAsSigned(hRecord, 0, &val); while (val == (LONG)Invoice) { val = -1; count++; if (ctdbNextRecord(hRecord) == CTDBRET)OK) ctdbGetFieldAsSigned(hRecord, 0, &val); } } printf("%d records found\n", count); }
The code fragment above shows how easy it is to use c-treeDB functionality to retrieve a number of related records from a table. A close inspection of the code reveals that while it is simple to implement, it does have a hidden issue that may affect the overall performance of the system, specially when running in client/server mode: for every record that is fetched, the client must place a request to the server, which must travel the network, the c-tree Server must interpret the client request, perform the record retrieval operation and return the record to the client, again traveling across the network. It is obvious the operation described above would be more efficient if we could, in just one call, request the c-tree Server to perform a given operation on a group of related records, and return all the resulting records, or as many records as possible, in one client request. The ability of perform record retrievals, insert or delete operations on a group of related records is implemented under c-treeDB as record batch operations. The same code fragment above implemented with c-treeDB C API batch record facility would look as follows:
The code fragment above is even simpler than the initial example, and it also performs far fewer c-tree Server calls to perform the operations. c-treeDB batch record functionality is implemented on top of c-tree Plus ISAM batch operations.
www.faircom.com
All Rights Reserved
115
Batch Modes
You must specify one of the following Mandatory modes when calling the ctdbSetBatch() function or the CTRecord:SetBatch() method:
MODE Description Retrieve a group of related records by partial key Retrieve a group of related records based on an index range expression Retrieve records from a table in physical order. The starting record for the batch retrieval may be specified. Delete a group of related records by partial key Insert a group of records
The following modes are optional and can be OR-ed to the mandatory mode to specify other details on how the batch operation is to be performed.
FairCom Corporation
116
Mode
Description Process records with a greater than or equal key match with the target key. When this mode is specified, the number of matched records is not readily available. ctdbBatchLocked() and CTRecord::BatchLocked returns a value one greater than ctdbBatchLoaded() to indicate there may be more records to process.This mode is applicable only with CTBATCH_GET and CTBATCH_DEL modes and can not be used with CTBATCH_LKEY. Process records that have a less than or equal key match with the target key.This mode is applicable only with CTBATCH_GET and CTBATCH_DEL modes and can not be used with CTBATCH_GKEY. Verify that the keys in the index match the values in the key fields of the record. Keep all records locked after ...EndBatch() is called. Without this mode, all records locks are released when ...EndBatch() is called. This option is only in effect when used with CTBATCH_LOCK_READ or CTBATCH_LOCK_WRITE. Place a read lock on each record that matches the partial key. Place a write lock on each record that matches the partial key. Convert a CTBATCH_LOCK_READ or CTBATCH_LOCK_WRITE to blocking read and blocking write locks, respectively. Implement an alternative locking strategy: only locks the record during the record read; original locking strategy keeps locks on during entire batch processing.
CTBATCH_GKEY
CTBATCH_LKEY
CTBATCH_VERIFY CTBATCH_LOCK_KEEP
CTBATCH_COMPLETE
...SetBatch() returns a success code only if all matching records are successfully locked. You must specify either CTBATCH_LOCK_READ or CTBATCH_LOCK_WRITE.
117
1. Clear a record buffer by calling ctdbClearRecord(). 2. Use ctdbSetFieldAs() to set the fields that form the partial target key that will be used to select a group of records. 3. Call the ctdbSetBatch() function with CTBATCH_GET mode, to start a new record retrieval batch operation. 4. If the ctdbSetBatch() function returns with no errors, continue to call the ctdbNextBatch() function repeatedly until all related records are retrieved. ctdbNextBatch() returns BTMT_ERR (428) to indicate no more records are available. 5. When you are done with the batch records, call the ctdbEndBatch() function to terminate the batch operation. Please note that another batch operation can only start after the current batch operation is terminated. To start a new batch operation to retrieve records, you must first establish the partial target key that will identify the group of related records. This is accomplished by clearing a record buffer and setting the fields that form the partial target key. For example, if an invoice item table has one index with segments based on invoice number and item number fields, the following partial code will create a partial target key that will select all invoice item records associated with a particular invoice number:
Example
/* set the partial target key */ ctdbClearRecord(hRecord); ctdbSetFieldAsSigned(hRecord, 0, Invoice);
After preparing the partial target key, a new batch operation is started by calling the function ctdbSetBatch(). Continuing from the example above, a new batch operation is started by performing the following call:
Example
/* set the batch operation */ if (ctdbSetBatch(hRecord, CTBATCH_GET, sizeof(Invoice), 0) != CTDBRET_OK) printf("ctdbSetBatch failed with error %d\n", ctdbGetError(hRecord)); /* retrieve and display all records */ while (ctdbNextBatch(hRecord) == CTDBRET_OK) PrintRecord(hRecord); /* terminate batch operations */ ctdbEndBatch(hRecord);
ctdbSetBatch() takes as first argument a valid record handle. The second argument is the batch mode that will direct how the batch operation will be performed. The chapters below describe the available batch modes in detail. You must provide the length of the ctdbSetBatch()s target key in bytes. The length of the target key will indicate how many bytes of the target key should be used to create the partial target key. The last parameter is the size of the buffer used internally by c-treeDB to handle batch operations. A zero value for the last parameter is an indication that the default value size should be used. The default buffer size is calculated as the size of the fixed portion of the record multiplied by 128. Retrieving records by index range All records that match an index range expression are loaded into a buffer region maintained internally by c-treeDB. If the selected records do not fit in the buffer, those that fit are loaded, and subsequent calls will retrieve the remaining records. The following steps must be taken to perform an index range batch retrieval of records: 1. Establish an index range by calling the ctdbRecordRangeOn() function.
FairCom Corporation
118
2. Call the ctdbSetBatch() function with the CTBATCH_RANGE mode to start a new record retrieval batch operation. 3. If the ctdbSetBatch() function returns with no errors, continue to call the ctdbNextBatch() function repeatedly until all related records are retrieved. ctdbNextBatch() returns BTMT_ERR (428) to indicate no more records are available. 4. When you are done with the batch records, call the ctdbEndBatch() function to terminate the batch operation. 5. Call the ctdbRecordRangeOff() function to terminate index range operations. To start a new batch operation to retrieve records, you must first establish the index range operation that will identify the group of related records.
Example:
/* build target key to be used in index range */ TEXT lRange[32]; VRLEN len = (VRLEN)sizeof(lRange); NINT op = CTIX_EQ; if (ctdbClearRecord(hRecord); ctdbSetFieldAsSigned(hRecord, 0, Invoice); if (ctdbBuildTargetKey(hRecord, CTFIND_EQ, (pVOID)lRange, &len) != CTDBRET_OK) printf("ctdbBuildTargetKey failed with error %d\n", ctdbGetError(hRecord)); /* set the index range based on the target key */ if (ctdbRecordRangeOn(hRecord, 1, (pVOID)lRange, NULL, CTIX_EQ&op) != CTDBRET_OK) printf("ctdbRecordRangeOn failed with error %d\n", ctdbGetError(hRecord));
After setting the index range operation, you may start a new batch operation by calling the ctdbSetBatch() function.
Example:
/* set the batch operation */ if (ctdbSetBatch(hRecord, CTBATCH_RANGE, 0, 0) != CTDBRET_OK) printf("ctdbSetBatch failed with error %d\n", ctdbGetError(hRecord)); /* retrieve and display all records */ while (ctdbNextBatch(hRecord) == CTDBRET_OK) PrintRecord(hRecord); /* terminate batch operations */ ctdbEndBatch(hRecord); /* terminate the index range */ ctdbRecordRangeOff(hRecord);
Notice when retrieving records by index range ctdbSetBatch()s targetLen parameter is set to zero. The last parameter is the size of the buffer used internally by c-treeDB to handle batch operations. A zero value for the last parameter is an indication that the default value size should be used. The default buffer size is calculated as the size of the fixed portion of the record multiplied by 128. Retrieving records by physical order All records of a table are loaded by physical order into a buffer region maintained internally by c-treeDB. If the selected records do not fit in the buffer, those that fit are loaded, and subsequent calls will retrieve the remaining records. The following steps must be taken to perform a physical order batch retrieval of records: 1. Call the ctdbSetBatch() function with the CTBATCH_PHYS mode to start a new record retrieval batch operation.
www.faircom.com
All Rights Reserved
119
2. If the ctdbSetBatch() function returns with no errors, call ctdbNextBatch() repeatedly until all related records are retrieved. ctdbNextBatch() returns BTMT_ERR (428) to indicate no more records are available. 3. When you are done with the batch records, call the ctdbEndBatch() function to terminate the batch operation.
Example
/* set the batch operation */ if (ctdbSetBatch(hRecord, CTBATCH_PHYS, 0, 0) != CTDBRET_OK) printf("ctdbSetBatch failed with error %d\n", ctdbGetError(hRecord)); /* retrieve and display all records */ while (ctdbNextBatch(hRecord) == CTDBRET_OK) PrintRecord(hRecord); /* terminate batch operations */ ctdbEndBatch(hRecord);
Notice when retrieving records by index range ctdbSetBatch()s targetLen parameter is set to zero since no partial key is need for this operation. The last parameter is the size of the buffer used internally by c-treeDB code to handle batch operations. A zero value for this parameter is an indication that the default value size should be used. The default buffer size is calculated as the size of the fixed portion of the record multiplied by 128. Deleting a group of records If the intended batch operation is to delete a group of selected records, you need to initially set the partial target key to select the group of related records and then start the batch operation to delete the selected records. Even if no records are retrieved with the delete operation, ctdbEndBatch() must be called to terminate the current batch operation. The following steps must be taken to perform a batch delete record operation: 1. Clear a record buffer by calling the ctdbClearRecord() function. 2. Use the ctdbSetFieldAsxxx() functions to set the fields that form the partial target key that will be used to select a group of records. 3. Call the ctdbSetBatch() function with the CTBATCH_DEL mode to delete a group of related records. 4. Call the ctdbEndBatch() function to terminate the delete record batch operation.
Example
/* set the partial target key */ ctdbClearRecord(hRecord); ctdbSetFieldAsSigned(hRecord, 0, Invoice); /* set the batch operation */ if (ctdbSetBatch(hRecord, CTBATCH_DEL, sizeof(Invoice), 0) != CTDBRET_OK) printf("ctdbSetBatch failed with error %d\n", ctdbGetError(hRecord)); /* end the batch operation */ if (ctdbEndBatch(hRecord) != CTDBRET_OK) printf("ctdbEndBatch failed with error %d\n", ctdbGetError(hRecord));
You must provide the length of ctdbSetBatch()s Target key in bytes. The length of the target key indicates how many bytes of the target key should be used to create the partial target key. The last parameter is the size of the buffer used internally by c-treeDB to handle batch operations. A zero value
FairCom Corporation
120
for the last parameter indicates the default value size should be used. The default buffer size is calculated as the size of the fixed portion of the record multiplied by 128. Inserting a group of records A group of new records are loaded into a buffer region maintained internally by c-treeDB and this group of records are inserted into a table. When the batch buffer fills up, the group of records stored in the batch buffer are inserted into the table. If ctdbEndBatch() is called and the batch buffer still contains records, a new insert record operation is performed for the remaining records before the batch operation is terminated. For transaction controlled files, the batch insertion operation is treated as one all or nothing operation. If no explicit transaction is started, each insertion of records with will start and end its own transaction. Even if an explicit transaction is started, each insertion operation is treated independently through safe points. Currently, all records insertion operations do not perform any conversion of record images, key values and record position for heterogeneous client/server implementations. The following steps must be taken to perform a batch insert record operation: 1. Call the ctdbSetBatch() function with the CTBATCH_INS mode, to insert a group of records. 2. For each record to be inserted perform the following operations: a) Call the ctdbClearRecord() functionto clear a record buffer. b) For each field in the record call one of the ctdbSetFieldAs...() functions to set the field data. c) Call the ctdbInsertBatch() to insert the record into the batch buffer. 3. Call the ctdbEndBatch() function to indicate no more records will be inserted.
Example
/* set the batch operation */ if (ctdbSetBatch(hRecord, CTBATCH_INS, 0, 0) != CTDBRET_OK) printf("ctdbSetBatch failed with error %d\n", ctdbGetError(hRecord)); /* prepare the first record */ ctdbClearRecord(hRecord); ctdbSetFieldAsSigned(hRecord, 0, Invoice); /* invoice number */ ctdbSetFieldAsSigned(hRecord, 1, 0); /* invoice item number */ ctdbSetFieldAsSigned(hRecord, 2, 100); /* item quantity */ ctdbSetFieldAsSigned(hRecord, 3, 1001); /* item code */ if (ctdbInsertBatch(hRecord) != CTDBRET_OK) /* insert record in batch */ printf("ctdbInsertBatch failed with error %d\n", ctdbGetError(hRecord)); /* prepare the second record */ ctdbClearRecord(hRecord); ctdbSetFieldAsSigned(hRecord, 0, Invoice); /* invoice number */ ctdbSetFieldAsSigned(hRecord, 1, 1); /* invoice item number */ ctdbSetFieldAsSigned(hRecord, 2, 200); /* item quantity */ ctdbSetFieldAsSigned(hRecord, 3, 1002); /* item code */ if (ctdbInsertBatch(hRecord) != CTDBRET_OK) /* insert record in batch */ printf("ctdbInsertBatch failed with error %d\n", ctdbGetError(hRecord)); /* terminate the batch operation */ if (ctdbEndBatch(hRecord) != CTDBRET_OK) printf("ctdbEndBatch failed with error %d\n", ctdbGetError(hRecord));
Notice when inserting a group of records ctdbSetBatch()s targetLen parameter is set to zero as no partial key is needed for this operation. The last parameter is the size of the buffer used internally by c-treeDB to handle batch operations. A zero value for this parameter indicates the default value size
www.faircom.com
All Rights Reserved
121
should be used. The default buffer size is calculated as the size of the fixed portion of the record multiplied by 128.
Retrieving records
If the mode of the batch operation is one of CTBATCH_GET, CTBATCH_RANGE or CTBATCH_PHYS then it may be necessary to retrieve all records that match the batch criteria. The records are retrieved by calling the ctdbNextBatch() function. ctdbNextBatch() retrieves record data from the batch buffer maintained by c-treeDBs record handle. After a successful call to ctdbNextBatch() the field data can be retrieved by calling the appropriate ctdbGetFieldAsxxx() functions.
Example
/* retrieve records */ while (ctdbNextBatch(hRecord) == CTDBRET_OK) { TEXT invoice[32], item[32]; ctdbGetFieldAsString(hRecord, 0, invoice, sizeof(invoice)); ctdbGetFieldAsString(hRecord, 1, item, sizeof(item)); printf("%-11s %s\n", invoice, item); }
Example
/* set the partial target key */ ctdbClearRecord(hRecord); ctdbSetFieldAsSigned(hRecord, 0, Invoice); /* set the batch operation */ if (ctdbSetBatch(hRecord, CTBATCH_DEL, sizeof(Invoice), 0) != CTDBRET_OK) printf("ctdbSetBatch failed with error %d\n", ctdbGetError(hRecord)); /* end the batch operation */ if (ctdbEndBatch(hRecord) != CTDBRET_OK) printf("ctdbEndBatch failed with error %d\n", ctdbGetError(hRecord));
When performing batch retrieval operations, you may cancel the batch operation before retrieving all the records by calling ctdbEndBatch(). If the batch operation is a CTBATCH_RANGE then you must also call the ctdbRecordRangeOff() function to terminate the index range used for the batch operation.
FairCom Corporation
122
Batch Properties Returned Retrieves the number of records locked by a batch operation. Retrieves the number of records loaded in a batch buffer maintained by c-treeDB record handle. Retrieves the batch mode set by ctdbSetBatch() function. Returns YES if a batch operation is active.
ctdbBatchMode ctdbIsBatchActive
ctdbGetFieldAsBool ctdbGetFieldAsSigned ctdbGetFieldAsUnsigned ctdbGetFieldAsDate ctdbGetFieldAsTime ctdbGetFieldAsMoney ctdbGetFieldAsFloat ctdbGetFieldAsDateTime ctdbGetFieldAsString ctdbGetFieldAsBinary ctdbGetFieldAsBlob ctdbGetFieldAsBigint ctdbGetFieldAsCurrency ctdbGetFieldAsNumber
/* display all field data on screen */ void DisplayData(CTHANDLE hRecord) { NINT count = ctdbGetTableFieldCount(hRecord); NINT i; TEXT str[256]; for (i = 0; i < count; i++) { ctdbGetFieldAsString(hRecord, i, str, sizeof(str)); printf(Field %d: %s\n, i, str); } }
www.faircom.com
All Rights Reserved
123
The following functions should be used to write fields into the data record buffer:
Function name Explanation update field data as Boolean value update field data as signed integer value update field data as unsigned integer value update field data as date value update field data as time value update field data as money value update field data as double value update field data as time stamp value update field data as string value update field data as binary data update field data as blob update field data as signed 64-bit integer update field data as currency value update field data as number (BCD) value
ctdbSetFieldAsBool ctdbSetFieldAsSigned ctdbSetFieldAsUnsigned ctdbSetFieldAsDate ctdbSetFieldAsTime ctdbSetFieldAsMoney ctdbSetFieldAsFloat ctdbSetFieldAsDateTime ctdbSetFieldAsString ctdbSetFieldAsBinary ctdbSetFieldAsBlob ctdbSetFieldAsBigint ctdbSetFieldAsCurrency ctdbSetFieldAsNumber
/* add new record */ void AddRecord(CTHANDLE hRecord, pTEXT name, pTEXT address, pTEXT phone) { ctdbClearRecord(hRecord); ctdbSetFieldAsString(hRecord, 0, name); ctdbSetFieldAsString(hRecord, 1, address); ctdbSetFieldAsString(hRecord, 2, phone); if (ctdbWriteRecord(hRecord) != CTDBRET_OK) { printf(Add record failed\n); } }
The ctdbSetFieldAs() functions will also clear the null bit flag for the updated field. When you invoke one of the ctdbGetFieldAs() or ctdbSetFieldAs() functions, you pass the record handle, the field number and the data you want to read from or write to the data record buffer. The ctdbGetFieldAs() or ctdbSetFieldAs() function names specify the type of the data you are trying to read or write not the underlying field type. If the type of the field you are trying to read from, or write to, is different than the type of the data specified by the ctdbGetFieldAs() or ctdbSetFieldAs() functions, the record manager will automatically convert the field data type to match the data type of the parameter of passed by one of the ctdbGetFieldAs() or ctdbSetFieldAs() function. For example, if you are writing a report generator application that displays the fields of a record on screen, you can read all fields in the record buffer with ctdbGetFieldAsString() and the record manager will convert the different field types to string. Boolean field type is converted as True or False, numeric values are converted to string and dates and times use the session wide default date and time formats.
FairCom Corporation
124
Si g ne d CT_BOOL CT_TINYINT CT_UTINYINT CT_SMALLINT CT_USMALLINT CT_INTEGER CT_UINTEGER CT_MONEY CT_DATE CT_TIME CT_FLOAT CT_DOUBLE CT_TIMESTAMP CT_EFLOAT CT_BINARY CT_CHARS CT_FPSTRING CT_F2STRING CT_F4STRING CT_BIGINT CT_NUMBER CT_CURRENCY CT_PSTRING CT_VARBINARY CT_LVB
X X X X X X X X X X X X X X X X X X X X X X X X X
U ns ig ne
X X X X X X X X X X X X X X X X X X X X X X X X X
Bi gi nt
X X X X X X X X X X X X X X X X X X X X X X X X X
N u m be
X X
Fl oa t
M o ne y
C ur re nc
X X
D at e
Ti m e
D a t e
St ri n g
*2 X X
B i n a
X X X X X X X X X X X X X X X X X X X X X X X X X
B o o l
X X X X X X X X X X X X X X
B l o b
X X X X X X X X X X X X X X X X X X X
X X
X X X
X X
X X X
X X X
X X X X X X X X X X X X X X X
X X X X X X X X X X X X X X X
X X X X X X X X X X X X X X X
X X X X X X X X X X X X X X X
X X X X X X X X X X X X X X X
X X X X X X X X X X X X X X X
X X X X
X X X X X
X X
X X X X
X X X X X X
X X X X X X
X X X X X X
X X X X X X
www.faircom.com
All Rights Reserved
125
CT_VARCHAR or CT_LVC
*1 - these are the c-treeDB field types. The old c-tree Plus field types are also valid and may be used. For new projects, the best approach would be to use the new field type convention, presented in this table, since this is the naming convention for the c-treeSQL field types. *2 - the value being set must be equal to either TRUE or FALSE, case insensitive - otherwise, the function will fail with CTDBRET_CANTCONVERT (4042). For every row in the table above, there is a highlighted column. This column represents the natural function that should be used to update that particular field. As discussed, though, any other function (column) marked with an X can be used, and the appropriate conversions will be performed.
FairCom Corporation
126
Clearing a field
A field can be cleared, and its null field flag is set, by calling ctdbClearField(). Call ctdbIsNullField() to check if a field null flag is set.
/* if a field 0 is not null, clear the field */ if (ctdbIsNullField(hRecord, 0) ctdbClearField(hRecord, 0);
127
/* populate the record buffer */ ctdbSetFieldAsSigned(hRecord, 0, 1000); ctdbSetFieldAsString(hRecord, 1, Joe Smith); /* write the record */ if (ctdbWriteRecord(hRecord) != CTDBRET_OK) printf(Add record failed\n);
A record is added to a table if the new record flag and edited flag are both set. ctdbClearRecord() sets the new record flag, while one of the ctdbSetFieldAs() functions will set the edited record flag. If you clear a record without populating the record buffer with data, ctdbWriteRecord() returns no error code. However, no data record is written to disk, since the new record flag is set but the edited record flag is cleared. If you wish to write a cleared or blank record to disk, you must clear the record buffer, set the edited record flag by calling ctdbSetEditedRecord() and then write the record by calling ctdbWriteRecord().
/* add a blank record to disk */ ctdbClearRecord(hRecord); /* set the edited record flag */ ctdbSetEditedRecord(hRecord, YES); /* write the record */ if (ctdbWriteRecord(hRecord) != CTDBRET_OK) printf(Add record failed\n);
c-treeDB utilizes two flags to track the edited state of a record: new record and edited. When a record is newly created, the new record flag is set and the edited flag is cleared. The edited flag is set whenever data is moved into the record with any ctdbSetField() operations. When CTDB prepares to write the record, it examines these flags. If this record has been edited, it checks the new record flag to either update an existing record, or add a new record. When you read an existing record with ctdbFirstRecord() or ctdbNextRecord(), etc, the new record flag is cleared and the edited flag is cleared. Again, the edited flag is only set if data is moved into the record with ctdbSetField() operations. If you request c-treeDB to write the record and the edited flag is not set, no data is written. To force a record update to disk you should call ctdbSetEditedRecord() to set the edited flag directly.
/* update the first record */ ctdbFirstRecord(hRecord); /* set the edited flag */ ctdbSetEditedRecord(hRecord, YES); /* write the record */
FairCom Corporation
128
Duplicate a record by: reading it from disk, setting the edited record flag with ctdbSetEditedRecord(), setting the new record flag with ctdbSetNewRecord(), and calling ctdbWriteRecord() to write it to disk. Please note that a record can only be duplicated if the table has no indices with unique keys.
/* duplicate the first record */ ctdbFirstRecord(hRecord); /* set the edited flag */ ctdbSetEditedRecord(hRecord, YES); /* set the new record flag */ ctdbSetNewRecord(hRecord, YES); /* write the record */ if (ctdbWriteRecord(hRecord) != CTDBRET_OK) printf(Duplicate record failed\n);
Deleting records
To delete a record, you need to perform the following actions: 1. Read the record from disk by calling one of the ctdbFirstRecord(), ctdbLastRecord(), ctdbNextRecord(), ctdbPrevRecord(), ctdbSeekRecord(), ctdbFindRecord(), or ctdbFindTarget() functions. 2. Lock the record with ctdbLock(), or ctdbLockRecord(). 3. Delete the record by calling ctdbDeleteRecord().
/* delete the first record */ ctdbFirstRecord(hRecord); ctdbLockRecord (hRecord, CTLOCK_WRITE); /* delete the record */ if (ctdbDeleteRecord(hRecord) != CTDBRET_OK) printf(Delete record failed\n);
Record properties
New record flag
The new record flag indicates if a record has been cleared and not written to disk yet. The record manager uses this flag to decide if a record should be added or updated. The new record flag is set when the record handle is allocated or when the record is cleared by ctdbClearRecord(). The new record flag is cleared when a record is read from disk by calling ctdbFirstRecord(), ctdbLastRecord(), ctdbNextRecord(), ctdbPrevRecord(), ctdbSeekRecord(), ctdbFindRecord(), or ctdbFindTarget() functions.
Record offset
This property holds the current record offset of a record. If a record is cleared, the record offset property is zero. All records in a table, even the first record, will have a record offset value greater than zero.
www.faircom.com
All Rights Reserved
129
You can retrieve the record offset value by calling ctdbGetRecordPos(). You can set the record offset property, and load the record data at the offset, by calling ctdbSeekRecord().
Record count
Use ctdbGetRecordCount() to retrieve the total number of records in a table. This is a read only property.
/* check if table is empty */ CTUINT64 count; ctdbGetRecordCount(hRecord, &count); if (count > 0) then printf(Table is not empty\n);
Record ROWID
Use ctdbGetRowid() to retrieve the ROWID value for the current record. This is a read only property.
/* retrieve the first record rowid */ CTROWID rowid; ctdbFirstRecord(hRecord); if (ctdbGetRowid(hRecord, &rowid) != CTDBRET_OK) printf(Table has no ROWID index\n);
Record Locking
A record lock can be acquired by performing the following actions: 1. Read a record from disk by calling ctdbFirstRecord(), ctdbLastRecord(), ctdbNextRecord(), ctdbPrevRecord(), ctdbSeekRecord(), ctdbFindRecord(), or ctdbFindTarget() functions. 2. Lock the record by calling ctdbLockRecord() Session wide locks are better suited to implement data integrity as the records are locked as they are read from disk. Since a record lock can only be applied after the record is read, there is a window of opportunity for the record to be modified or deleted by another thread before the record lock is acquired. Release a record lock by calling ctdbUnlockRecord() or by calling ctdbLockRecord() with CTLOCK_FREE mode.
FairCom Corporation
130
c-treeDB also exposes the following data types, based on c-tree scalar types. These c-treeDB types also provide a one to one relationship with c-treeDB field types: CTBOOL CTSIGNED
Declared as an integer, this type holds Boolean values using the predefined Boolean constants YES for true and NO for false. Declared as a signed long (32-bit signed integer), this type holds any scalar value: 8-bit signed integer (TEXT), 16-bit signed integer (COUNT), integers (NINT), and 32-bit signed integers (LONG). Declared as an unsigned long (32-bit unsigned integer), this type holds any scalar value: 8-bit unsigned char (UTEXT), 16-bit unsigned integer (UCOUNT), unsigned integers (UINT), and 32-bit unsigned integers (ULONG). Declared as C type double. Declared as C type double.
CTUNSIGNED
DOUBLE CTFLOAT
All the types in this category can be manipulated using the normal operators defined for the C and C++ language.
www.faircom.com
All Rights Reserved
131
Date Types
CTDATE is declared as an unsigned 32-bit integer. The date is stored as the number of days since March 1st 1700. The CTDATE type was implemented to be compatible with FairCom's r-tree and ODBC products. Hence, if a CTDATE type has a value of 1, it means that the date is March 1st 1700, while a value of 2 means March 2nd 1700 and so on. Since CTDATE is a 32 bit unsigned integer, numerical operations with dates can be done using standard C operators. For example, to add 10 days to a date use the normal C operation date + 10 (assuming that date is a CTDATE type). To get the difference in days of 2 dates, just subtract one date from another. c-treeDB provides methods and functions to allow the user to manipulate the CTDATE type in their applications.
Function Operation Returns CTDBRET_OK if it is a valid date. Month must be a value between 1 and 12 and day must be a value between 1 and 31. This function checks for dates such as February 29th for leap years and for months that have 30 and 31 days. Packs a date as year, month and day and store the result in pDate. The date is checked and ctdbDatePack() returns CTDBRET_OK if the date was packed correctly. Update a CTDATE value into year, month and day. Convert a packed CTDATE value into string. DateType() gives the format of the date in string form. Convert a date in string format to a packed CTDATE value. DateType gives the format of the date in string form. Retrieve the day component of a packed date type. Retrieve the month component of a packed date type. Retrieve the year component of a packed date type. Indicate if the year component of the packed date type is a leap year. Retrieve the day of the week for a given packed date type. Sunday is 0, Monday is 1, Tuesday is 2, and so on. Retrieve the default date format type for this session. The record manager uses the session default date format type when converting date fields into string values and vice-versa. Set the default date format type for this session. When a session handle is allocated, the default date format type is set to CTDATE_MDCY: month followed by day and year Retrieve the current system date and store it in CTDATE packed format.
ctdbDateCheck
ctdbDatePack
ctdbSetDefDateType
ctdbCurrentDate
CTDATE_MDCY
MDCY_DATE
FairCom Corporation
132
Date is mm/dd/yy Date is dd/mm/ccyy Date is dd/mm/yy Date is ccyymmdd Date is yymmdd
Time Types
CTTIME is declared as a 32 bit unsigned integer, stored as the number of seconds since midnight. The CTTIME type was implemented to be compatible with FairCom's r-tree and ODBC products. c-treeDB provides functions and methods to allow the user to manipulate the CTTIME type in their applications.
Function Operation Check an unpacked time in hour, minute and second and return CTDBRET_OK if the time is valid. Hour must be a value between 0 and 23, minute and second must be a value between 0 and 59. Pack a time in the form hour, minute and second into a CTTIME form. Unpack a CTTIME time into hour, minute and second. Convert a packed time value into string format. Convert a time in string form into a packed time. TimeType() gives the string form of the time value. Retrieve the hour component of a packed time. The hour return is a 24-hour value (e.g. 11 pm is returned as 23). Retrieve the minute component of a packed time. Retrieve the second component of a packed time. Retrieve the default time format kept by the session. The record manager uses the default time format to convert time fields into string fields and vice-versa. Set the default time format for the session. The record manager uses the default time format to convert packed time fields into string values, and vice-versa. When a session handle is allocated, the default time format is set to CTTIME_HMP (HH:MM am/pm) Retrieve the current system time.
ctdbTimeCheck
ctdbSetDefTimeType
ctdbCurrentTime
Value Time Types can be one of the following string time formats:
c-treeDB Symbolic Constant c-tree Plus for .NET Symbolic Constant
Description Time is hh:mm:ss am|pm Time is hh:mm am|pm Time is hh:mm:ss (24 hour)
133
CTTIME_HM CTTIME_MIL
HM_TIME MIL_TIME
Numeric Types
Numeric types are used to manipulate numeric values that are too large for the scalar types or numeric values representing currency values. c-treeDB implements the following numeric types:
CTBIGINT
CTBIGINT is a 64-bit signed integer type. Today most C compilers are capable of dealing with 64-bit integers. In the Windows operating system, Borland, Microsoft and Watcom use a __int64 type to represent native 64-bit integers, while in other operating systems such as Unix and Linux, 64-bit integers are represented as long long types. The following set of functions converts of CTBIGINT into other c-treeDB types.
Function Operation Convert a CTBIGINT value to a long (32 bit signed integer). If the CTBIGINT value is too large for the conversion, ctdbBigIntToLong() return either CTDBRET_OVERFLOW or CTDBRET_UNDERFLOW errors. Convert a long value to CTBIGINT. Convert a CTBIGINT value to CTFLOAT. Convert a CTFLOAT value to CTBIGINT.
ctdbBigIntToLong
FairCom Corporation
134
Function
ctdbBigIntToString ctdbStringToBigInt
CTMONEY
CTMONEY represents a currency value in a 32-bit signed integer. The last two decimal digits of the value are used as the decimal part of the value. For example, a currency value of 123.45 is represented with CTMONEY as 12345. A currency value of 1 is represented in CTMONEY as 100. Since all the operations performed on CTMONEY values are integer operations, this type offers exact currency value capabilities that do not need large values or large precision at excellent performance that is very close to 32-bit integer performance. c-treeDB provides the following set of functions to manipulate CTMONEY values, including functions for performing the basic arithmetic operations on CTMONEY values. These set of basic arithmetic operations are especially important in multiplication and division of CTMONEY values. Take for example the multiplication of two values such as 123.45 and 67.89. These values are represented in a CTMONEY type as 12345 and 6789 respectively. An integer multiplication on the values above, would give the result 83810205, which is 838102.05 in CTMONEY representation. This result is clearly wrong since the expected result would be 8381.02. The same principle applies to division operation. By using the CTMONEY API provided by c-treeDB, the user will be able to operate correctly with CTMONEY values.
Function Operation Convert a CTMONEY value to LONG. Only the integer portion of the CTMONEY value is converted to LONG, as the decimal portion of the CTMONEY value is ignored for the conversion. Convert LONG to CTMONEY. Convert CTMONEY value to CTFLOAT. Convert CTFLOAT value to CTMONEY. Convert CTMONEY value to string. Convert string to CTMONEY value. Add two CTMONEY values left and right and store the result in pResult. The mathematical equivalent of this function would be pResult = left + right. Subtract two CTMONEY values left and right and store the result in pResult. The mathematical equivalent of this function would be pResult = left - right. Multiply two CTMONEY values and store the result in pResult. The mathematical equivalent of this function would be pResult = left * right. Divide two CTMONEY values and store the result in pResult. The mathematical equivalent of this function would be pResult = left / right. If the value of right is zero, ctdbMoneyDiv returns CTDBRET_DIVBYZERO. Compare two CTMONEY values left and right and return zero value if left is equal to right. Return negative value if left is less than right and return a positive value if left is greater than right. Return the absolute value of a CTMONEY value.
ctdbMoneyToLong
ctdbMoneyCmp
ctdbMoneyAbs
www.faircom.com
All Rights Reserved
135
CTCURRENCY
CTCURRENCY represents a currency value in a 64-bit signed integer. The last four decimal digits of the value are used as the decimal part of the value. Example: a currency value of 123.45 is represented with CTCURRENCY type as 1234500. A currency value of 1 is represented in CTCURRENCY as 10000. Since all the operations performed on CTCURRENCY values are integer operations, this type offers exact currency value capabilities with large value capabilities and good precision at excellent performance that is very close to 64-bit integer performance. c-treeDB provides the following set of functions to manipulate CTCURRENCY values, including functions for performing the basic arithmetic operations on CTCURRENCY values. This set of basic arithmetic operations are especially important in multiplication and division of CTCURRENCY values. Take for example the multiplication of two values such as 123.45 and 67.89. These values are represented in a CTCURRENCY type as 1234500 and 678900 respectively. An integer multiplication on the values above would yield 838102050000, which is 83810205.0000 in CTCURRENCY representation. This result is clearly wrong since the expected result would be 8381.02. The same principle applies to division operation. By using the CTCURRENCY API provided by c-treeDB, the user will be able to operate correctly with CTCURRENCY values.
c-treeDB Function Operation Convert a CTMONEY value to CTCURRENCY value. Convert a CTCURRENCY value to CTMONEY value. Convert a CTCURRENCY value to a LONG value. Convert a LONG value to CTCURRENCY value. Convert a CTCURRENCY value to CTBIGINT value. Convert a CTBIGINT value to CTCURRENCY value. Convert a CTCURRENCY value to a CTFLOAT value. Convert a CTFLOAT value to CTCURRENCY value. Convert a CTCURRENCY value to a string. Convert a string to a CTCURRENCY value. Add two CTCURRENCY values left and right and store the result in pResult. The mathematical equivalent of this function would be pResult = left + right. Subtract two CTCURRENCY values left and right, and store the result in pResult. The mathematical equivalent of this function would be pResult = left - right. Multiply two CTCURRENCY values left and right and store the result in pResult. The mathematical equivalent of this function would be pResult = left * right. Divide two CTCURRENCY values left, and right and store the result in pResult. The mathematical equivalent of this function would be pResult = left / right. If the value of right is zero, ctdbCurrencyDiv() returns CTDBRET_DIVBYZERO.
ctdbMoneyToCurrency ctdbCurrencyToMoney ctdbCurrencyToLong ctdbLongToCurrency ctdbCurrencyToBigInt ctdbBigIntToCurrency ctdbCurrencyToFloat ctdbFloatToCurrency ctdbCurrencyToString ctdbStringToCurrency ctdbCurrencyAdd
ctdbCurrencySub
ctdbCurrencyMul
ctdbCurrencyDiv
FairCom Corporation
136
c-treeDB Function
Operation Compare two CTCURRENCY values. If the value of left and right are equal, ctdbCurrencyCmp() return zero. If left is greater than right return a positive value. If the value of left is less than right return a negative value. Return the absolute value of CTCURRENCY value. Round the CTCURRENCY value to the number of decimal places specified by scale.
ctdbCurrencyCmp
ctdbCurrencyAbs ctdbCurrencyRound
CTNUMBER
CTNUMBER corresponds to a number with a given precision (maximum number of digits) and scale (the number of digits to the right of the decimal point). Numeric values can have maximum values of 32 digits precision and scale of 0 (this is 99999999999999999999999999999999), which can represent very large exact values. c-treeDB provides the following set of functions to manipulate this very powerful number representation.
Function Operation Convert CTMONEY to CTNUMBER. Convert CTNUMBER to CTMONEY. Convert CTNUMBER to LONG. Convert LONG to CTNUMBER. Convert CTNUMBER to CTBIGINT. Convert CTBIGINT to CTNUMBER. Convert CTNUMBER to CTCURRENCY. Convert CTCURRENCY to CTNUMBER. Convert CTNUMBER to CTFLOAT. Convert CTFLOAT to CTNUMBER. Convert CTNUMBER to string. Convert String to CTNUMBER. Add two CTNUMBER values left and right and store the result in pResult. The mathematical equivalent of this function would be pResult = left + right. Subtract two CTNUMBER values left and right and store the result in pResult. The mathematical equivalent of this function would be pResult = left - right. Multiply two CTNUMBER values left and right and store the result in pResult. The mathematical equivalent of this function would be pResult = left * right.
ctdbMoneyToNumber ctdbNumberToMoney ctdbNumberToLong ctdbLongToNumber ctdbNumberToBigInt ctdbBigIntToNumber ctdbNumberToCurrency ctdbCurrencyToNumber ctdbNumberToFloat ctdbFloatToNumber ctdbNumberToString ctdbStringToNumber ctdbNumberAdd ctdbNumberSub
ctdbNumberMul
www.faircom.com
All Rights Reserved
137
Function
Operation Divide two CTNUMBER values left and right and store the result in pResult. The mathematical equivalent of this function would be pResult = left / right. If the value of right is zero, ctdbNumberDiv() return CTDBRET_DIVBYZERO. Set the value pointed by pNumber to zero. Return YES if the value pointed by pNumber is zero. Compare two CTNUMBERs and return zero if both numbers are equal. Return a negative value if pLeft is less than pRight. Return a positive value if pLeft is greater than pRight. Return the absolute value of the number pointed to by pResult. Invert the sign of the value pointed to by pSource and place the result in pResult. The mathematical equivalent of this function would be pResult = -pSource. Copy the value of the number pointed to by pSource into pDest. In other words, assign the value of pSource into pDest. Round the value pointed to by num to the number of decimal digits (digits to the right of the decimal point) indicated by scale. Given the CTNUMBER data, ctdbNumberGetDecimal() retrieves the number of digits to the left of the decimal point and store it in digit_before and retrieves the number of digits to the right of decimal point and stores it in digit_after.
ctdbNumberDiv
ctdbNumberAbs ctdbNumberNegate
Atomicity
Often, when updating a table, you perform several functions in a group. For instance, when creating an invoice, you update several tables: the account balance in the customer file, the invoice file, an invoice detail file, inventory records, and others. It is important that all of these actions take place to keep the files synchronized. If some of the actions take place, but not all, your files may be out of sync, and it can be difficult to correct the problem later. If one action cannot take place, it would be best to not let any take place. We call this atomicity. The c-treeDB API provides functions that provide this feature. You can mark a set of operations so that none will take place unless they can all take place. The API goes beyond this, allowing you to create savepoints where you can partially back out a group of operations, and roll back transactions to a given point, so that you can restore your data back to a state that it was in sometime in the past.
FairCom Corporation
138
Automatic Recovery
Once you establish full transaction processing by creating tables using the CTCREATE_TRNLOG mode, you can take advantage of the automatic recovery feature. Atomicity will generally prevent problems of files being partially updated. However, there are still situations where a system crash can cause data to be lost. Once you have signaled the end of a transaction, there is still a window of vulnerability while the application is actually committing the transaction updates to disk. In addition, for speed considerations some systems buffer the data files and indices, so that updates may not be flushed to disk immediately. If the system crashes, and one of these problems exists, the recovery logic detects it. If you set up the system for automatic file recovery, the recovery logic automatically resets the table back to the last, most complete, state that it can. If any transaction sets have not been completed, or committed, they will not affect the table.
Starting a transaction
Using our example from above, you dont want to have the transaction group involve more than one invoice. You also dont want it to involve less than a whole invoice. Record locks are held on updated records for the duration of the transaction, so you dont want to make the transaction group too large or it will consume the system resources. On the other hand, you may not want to make the transaction group too small or the effect of grouping actions is lost. ctdbBegin() starts a new transaction. You will need to decide on logical groups of file updates that can be delimited as transactions.
/* start a new transaction */ if (ctdbBegin(hAnyHandle) != CTDBRET_OK) { printf(Begin transaction failed\n); }
Terminating a transaction
When all update operations have been completed, terminate a transaction by calling ctdbCommit() to commit all changes.
/* commit transaction */ if (ctdbCommit(hAnyHandle) != CTDBRET_OK) { printf(Commit transaction failed\n); }
Call ctdbAbort() to terminate the transaction and abort all changes done since the start of the transaction.
/* abort transaction */ if (ctdbAbort(hAnyHandle) != CTDBRET_OK) { printf(Abort transaction failed\n); }
www.faircom.com
All Rights Reserved
139
Save Points
There are times when you want to abort only a portion of a transaction. You may be processing several optional paths of a program, going down one branch, then backing out and trying another branch. It may be possible that you don't want any of the updates to occur until you are completely finished, but you want the flexibility to back out part of the updates. Another possibility would be if you have run into some form of update error, such as an add record failing due to a duplicate key. You would want to back up to a prior point, correct the problem, and continue. The FairCom Server lets you implement this by using savepoints. A savepoint is a temporary spot in the transaction that you may want to rollback to without having to abort the entire transaction. During a transaction, when you want to put a place mark in the process, issue a ctdbSetSavePoint() call. This does not commit any of the updates. The function returns a savepoint number, which you should keep track of. You can make as many ctdbSetSavePoint() calls as you wish during a transaction, and each time you will be given a unique savepoint number. When you decide that you want to rollback to a savepoint previously saved by a call to ctdbSetSavePoint(), issue a ctdbRestoreSavePoint() call. You should pass to ctdbRestoreSavePoint() the savepoint number that you saved. This returns your data to the state it was at the point you issued the specified ctdbSetSavePoint() call, without aborting the entire transaction.
Locking
The most significant difference between coding applications for single-user environments and multi-user environments (including local area networks) has to do with performing record updates (rewrites) and record deletions. The basic problem is that to perform a record update or delete in a multi-user system, you must own a record lock on the record of interest. Locks should be acquired when the user reads the record in preparation for updates, and should not relinquish the lock until the update is completed. However, one must be careful to help ensure that locks are held for the shortest time possible or the performance of the application will be adversely affected.
Starting locks
Calling ctdbLock() passing the appropriate lock mode initiates locking.
/* start locking */ if (ctdbLock(hAnyHandle, CTLOCK_WRITE_BLOCK) != CTDBRET_OK) printf(Lock failed\n);
After a successful call to ctdbLock(), all records read by the c-treeDB API will be locked using the lock mode passed to ctdbLock(). The locking of records can be suspended temporarily by calling ctdbLock() with the mode CTLOCK_SUSPEND. Suspending locks does not cause any locks to be released, but while locks are suspended, no record reads are automatically locked.
/* suspend locking */ if (ctdbLock(hAnyHandle, CTLOCK_SUSPEND) != CTDBRET_OK) printf(Suspend lock failed\n);
Suspended locks can be resumed by calling ctdbLock() with one of the resume lock modes CTLOCK_RESUME_READ, CTLOCK_RESUME_LOCK_BLOCK, CTLOCK_RESUME_WRITE, and CTLOCK_RESUME_WRITE_BLOCK.
/* resume locking */ if (ctdbLock(hAnyHandle, CTLOCK_RESUME_WRITE_BLOCK) != CTDBRET_OK) printf(Resume lock failed\n);
FairCom Corporation
140
Lock modes
Use the following lock modes when calling ctdbLock():
c-treeDB Lock Modes c-tree Plus for .NET Lock Modes
Explanation Free all locks. Free the data record lock. Non-blocking read locks. If the lock cannot be acquired an error is returned. Blocking read lock. The thread will block until the lock can be acquired. Non-blocking write lock. If the lock cannot be acquired an error is returned. Blocking write lock. The thread will block until the lock can be acquired. equivalent to calling Lock with
CTLOCK_FREE followed by Lock() with CTLOCK_WRITE. CTLOCK_SUSPEND CTLOCK_RESTORE _READ CTLOCK_RESTORE _READ_BLOCK SUSPEND_LOCK RESTORE_READ_LOC K RESTORE_READ _BLOCK_LOCK RESTORE_WRITE_LO CK RESTORE_WRITE _BLOCK_LOCK
Temporarily suspend locking. To be used after a call to Lock with the
CTLOCK_SUSPEND mode. This lock mode restores the lock mode as READ.
To be used after a call to Lock with the
CTLOCK_SUSPEND mode. This lock mode restores the lock mode as WRITE.
To be used after a call to Lock with the
CTLOCK_RESTORE _PREVIOUS
c-tree Plus for .NET Lock Modes are defined in the LOCK_MODE enum.
Freeing locks
Locks are freed by calling ctdbUnlock() or by calling ctdbLock() with mode CTLOCK_FREE. If freeing locks inside an active transaction, the locks of updated records will only be actually freed when the transaction terminates.
/* free locks */ if (ctdbUnlock(hAnyHandle) != CTDBRET_OK) printf(Free lock failed\n);
www.faircom.com
All Rights Reserved
141
If freeing locks associated with a table inside an active transaction, the locks of updated records will only be actually freed when the transaction terminates.
Types of Resources
There are three general types of resources that can be attached to a file. User defined resources Information that you wish to store in the table, such as a version number, or an infrequently accessed counter. Use resources to store information associated with a table that varies from the type of information stored repetitively in the data records. FairCom defined resources There is a variety of information that, under certain circumstances, FairCom wishes to store in the table. This can be information relating to IFIL structures, alternate collating sequences, special characters for key padding, and so forth. Usually you do not access this information directly. It is available to a variety of c-treeDB functions that use it. Third party resources As other developers create utilities integrating with c-tree Plus, FairCom assigns resource identifiers when necessary.
FairCom Corporation
142
Resource Identification
Within a given data file, a Resource is identified by three elements.
Resource Element Data Type unsigned long integer unsigned long integer null terminated string
Within each file, you can identify a Resource by its unique combination of Type and Number, or by its Name. Note: The Resource Name is not guaranteed to be unique.
Resource Type Resource Type gathers Resources into related groups. Resource Types in the range of 1 to 127 are reserved for use by FairCom. These are special Resources used by the c-tree Server the d-tree application builder, c-treeDB, and c-treeSQL. Resource Types in the range of 128 to 65536 are also reserved and are explicitly assigned to third party developers by FairCom. Resource Types numbered 65537 and above are available to any developer and can be assigned as desired. Resource Number There are no restrictions on assigning Resource Numbers. They separate various Resources within a given Resource Type. When adding a Resource to a file, c-tree Plus can assign the next available value for this Resource Type in the referenced table. Resource Name You can use the Resource Name as a way to access Resources in a file instead of using the Type and Number. This can make application code more readable if you use a symbolic name rather than a pair of numbers. If you are adding a number of Resources to a data file over a period of time you may not know what Resource Number has been used, particularly since c-tree Plus can automatically assign the next available Resource Number. Access via Resource Name is simpler than keeping track of what Resource Number has been assigned. However, use caution when assigning Resource Names. c-tree Plus cannot guarantee that each Resource Name is unique within a table. It is possible to add a duplicated Resource name to a table. Resource Names are optional. They are not required for a Resource. The Resource Name is a null terminated character string of any length. FairCom recommends you do not make them too long. Resource Names starting with the character sequence FC! are reserved for use by FairCom. Resource Names starting with with the character sequence RD! are reserved for Resources assigned to third party developers by FairCom.
www.faircom.com
All Rights Reserved
143
3. Once a resource handle is no longer required, call ctdbFreeResource() to free any resource locks and release the memory allocated for the resource handle.
Handle is a c-treeDB table handle. type is the resource type. number is the resource number. name is the resource name. If you do not know these values in advance, you can set the type and number parameters to zero and name to a NULL pointer or empty string (). If the resource handle is allocated correctly, ctdbAllocResource() returns a pointer to the new resource handle. If an error occurs while allocating the resource handle, ctdbAllocResource() returns NULL and you should call ctdbGetError(Handle) to retrieve the error code of the error. Once the resource handle is no longer needed, you must call ctdbFreeResource() to release all system resources used by c-treeDB Resource processing. To release a resource handle you should invoke the following c-treeDB function:
CTDBRET ctdbDECL ctdbFreeResource(CTHANDLE resource);
resource is a resource handle allocated by ctdbAllocResource(). ctdbFreeResource() returns CTDBRET_OK on success or a CTDBRET_NOTRESOURCE error if the handle passed to ctdbFreeResource() was not allocated by ctdbAllocResource() or is invalid. Once a resource handle is released by ctdbFreeResource(), the resource handle is invalid should not be used again.
FairCom Corporation
144
else printf(", name: NULL"\n"); } while ((eRet = ctdbNextResource(hRes, false)) != CTDBRET_OK); ctdbFreeResource(hRes); return eRet; }
resource is a resource handle allocated by ctdbAllocResource(). data is any collection of data you wish to store as a Resource. This can be a character string, a structure, or any variable type. size indicates the number of bytes occupied by the data parameter value. 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 CTDB_ASSIGN_RESOURCE_NUMBER (0xffffffff), c-tree Plus assigns to this Resource the next available Resource Number for this Resource Type in the specified data file. The assigned number can be retrieved by calling ctdbGetResourceNumber() before the resource handle is released. The Resource Name is optional. c-tree Plus does not guarantee unique Resource Names. Names starting with the character sequences FC! or RD!, are reserved for FairCom use.
www.faircom.com
All Rights Reserved
145
ctdbFreeResource(hRes); return eRet; } /* retrieve the assigned resource number */ number = ctdbGetResourceNumber(hRes); /* release the resource handle */ ctdbFreeResource(hRes); return number; }
Deleting Resources
A resource can be deleted from a table by calling the following c-treeDB C API function:
CTDBRET ctdbDECL ctdbDeleteResource(CTHANDLE resource);
Before the resource can be deleted, the table must be opened with exclusive mode CTOPEN_EXCLUSIVE. resource is a resource handle allocated by ctdbAllocResource(), and the resource type and resource number that identify this resource must be passed to ctdbAllocResource(). After the resource is deleted, its name, number and name are reset.
You must call ctdbAllocResource() with specific resource type and number that will uniquely identify the resource being updated. resource is a resource handle allocated by ctdbAllocResource(). data 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. size indicates the number of bytes occupied by data parameter value. ctdbUpdateResource() returns CTDBRET_OK on success.
FairCom Corporation
146
Reading Resources
Essentially, there are four different methods to read resources from a c-tree Plus table. Read all table resources, read all resources starting past a resource type and number, read a specific resource by specifying the Resource Type and Resource Number, or read a resource by specifying a Resource Name. Described below are examples of each method. Read all c-tree Plus Resources from a Table Read all resource starting with the first resource by calling ctdbFirstResource() and then read the remaining resources by calling ctdbNextResource(). To read the first resource in a table, call the following function:
CTDBRET ctdbDECL ctdbFirstResource(CTHANDLE resource, CTBOOL lock);
ctdbFirstResource() retrieves the first resource stored in a table. resource is a handle allocated with a call to ctdbAllocHandle(). lock indicates if the resource should be locked, if it is found. ctdbFirstResource() returns CTDBRET_OK on success. If no resource is found, ctdbFirstResource() returns RNOT_ERR (408). To read all other resources of a table call the following function:
CTDBRET ctdbDECL ctdbNextResource(CTHANDLE resource, CTBOOL lock);
ctdbNextResource() retrieves the next resource stored in a table, after a successful call to ctdbFirstResource() is made. resource is a handle allocated with a call to ctdbAllocHandle(). lock indicates if the resource should be locked, if it is found. ctdbNextResource() returns CTDBRET_OK on success. If no resource is found, ctdbFirstResource() returns RNOT_ERR (408).
Example
CTDBRET DisplayAllResources(CTHANDLE hTable) { CTDBRET eRet; CTHANDLE hRes = ctdbAllocResource(hTable, 0, 0, NULL); /* check if resource was allocated */
www.faircom.com
All Rights Reserved
147
if (!hRes) return ctdbGetError(hTable); /* get the first resource */ /* note that no resource locks are acquired since we are not changing the resources */ if ((eRet = ctdbFirstResource(hRes, false)) != CTDBRET_OK) { ctdbFreeResource(hRes); return eRet; } /* get the other resources */ do { /* display resource type, number and name */ printf("Resource type: %u, number: %u", ctdbGetResourceType(hRes), ctdbGetResourceNumber(hRes)); if (ctdbGetResourceName(hRes) != NULL) printf(", name: \"\"\n", ctdbGetResourceName(hRes)); else printf(", name: NULL"\n"); } while ((eRet = ctdbNextResource(hRes, false)) != CTDBRET_OK); ctdbFreeResource(hRes); return eRet; }
Read all c-tree Plus Resources Given a Starting Point from a Table Read all resources starting from a given resource type and number by calling ctdbNextResource(). Start by allocating a resource handle, set the resource type and a resource number and then call ctdbNextResource(). In this case a resource is found if its type is greater or equal to the specified type and its number is greater than the specified number.
Example
/* read resources with type >= type and number > 0 */ CTDBRET DisplayResources(CTHANDLE hTable, ULONG type) { CTDBRET eRet; CTHANDLE hRes = ctdbAllocResource(hTable, type, 0, NULL); /* check if resource was allocated */ if (!hRes) return ctdbGetError(hTable); /* note that no resource locks are acquired since we are not changing the resources */ while ((eRet = ctdbNextResource(hRes)) == CTDBRET_OK) { /* display resource type, number and name */ printf("Resource type: %u, number: %u", ctdbGetResourceType(hRes), ctdbGetResourceNumber(hRes)); if (ctdbGetResourceName(hRes) != NULL) printf(", name: \"\"\n", ctdbGetResourceName(hRes)); else printf(", name: NULL"\n"); } ctdbFreeResource(hRes); return eRet; }
Read a Specific Plus Resources from a Table Read a specific resource by providing the exact resource type and number by calling ctdbFindResource():
CTDBRET ctdbDECL ctdbFindResource(CTHANDLE resource, ULONG type, ULONG number, CTBOOL lock);
FairCom Corporation
148
ctdbFindResource() locates and retrieves a resource from a table based on the Resource Type and Resource Number. resource is a resource handle allocated by ctdbAllocResource(). type is a value of the resource type. number is the value of the resource number to be located. lock indicates if the resource should be locked, if it is found. ctdbFindRecord() returns CTDBRET_OK on success. If there are no resources for the table, ctdbFirstResource() returns RNOT_ERR (408).
Example
/* display a particular resource */ CTDBRET DisplayResource(CTHANDLE hTable, ULONG type, ULONG number) { CTDBRET eRet; CTHANDLE hRes = ctdbAllocResource(hTable, 0, 0, NULL); /* check if resource was allocated */ if (!hRes) return ctdbGetError(hTable); /* note that no resource locks are acquired since we are not changing the resources */ if ((eRet = ctdbFindResource(hRes, type, number, NO)) == CTDBRET_OK) { printf("Resource type: %u, number: %u", ctdbGetResourceType(hRes), ctdbGetResourceNumber(hRes)); if (ctdbGetResourceName(hRes) != NULL) printf(", name: \"\"\n", ctdbGetResourceName(hRes)); else printf(", name: NULL"\n"); } ctdbFreeResource(hRes); return eRet; }
Read a c-tree Plus Resources by Name from a Table Read a resource by providing its name with the ctdbFindResourceByName() c-treeDB C API call.
CTDBRET ctdbDECL ctdbFindResourceByName(CTHANDLE resource, pTEXT name, CTBOOL lock);
ctdbFindResourceByName() locates and retrieves a resource by name. c-tree Plus cannot guarantee unique resource names. resource is a handle allocated with ctdbAllocHandle(). name is the resource name being located. lock indicates if the resource should locked, if it is found. ctdbFindResourceByName() returns CTDBRET_OK on success. If there are no resources for the table, ctdbFirstResource() returns RNOT_ERR (408).
Example
/* display a particular resource */ CTDBRET DisplayResource(CTHANDLE hTable, pTEXT name) { CTDBRET eRet; CTHANDLE hRes = ctdbAllocResource(hTable, 0, 0, NULL); /* check if resource was allocated */ if (!hRes) return ctdbGetError(hTable);
www.faircom.com
All Rights Reserved
149
/* note that no resource locks are acquired since we are not changing the resources */ if ((eRet = ctdbFindResourceByName(hRes, name, NO)) == CTDBRET_OK) { printf("Resource type: %u, number: %u", ctdbGetResourceType(hRes), ctdbGetResourceNumber(hRes)); if (ctdbGetResourceName(hRes) != NULL) printf(", name: \"\"\n", ctdbGetResourceName(hRes)); else printf(", name: NULL"\n"); } ctdbFreeResource(hRes); return eRet; }
Resource Locks
It is expected that you process resource updates without permitting user interactions to occur during the actual update. It is important for performance considerations and c-treeDB assumes that resource entries will be locked only for very short intervals. Do not lock a resource and then request user input. Be careful not to include resource updates, (additions, deletions or updates), in long held transactions when the table is under transaction processing control. Locks cannot be released until a transaction either commits or aborts. c-treeDB resource handling automatically unlocks resources when necessary, however, a resource can be manually unlocked by the user. Use the following function to check if a resource is locked or not:
CTBOOL ctdbDECL ctdbIsResourceLocked(CTHANDLE resource);
ctdbIsResourceLocked() returns YES if the resource referenced by the resource handle is locked, otherwise it returns NO. The following function should be used to unlock resources whose locks are no longer necessary:
CTDBRET ctdbDECL ctdbUnlockResource(CTHANDLE resource);
ctdbUnlockResource() releases a lock placed on a resource by one of the following read resource functions: ctdbFirstResource(), ctdbNextResource(), ctdbFindResource() or ctdbFindResourceByName(). resource is a resource handle allocated by ctdbAllocHandle(). ctdbUnlockResource() returns CTDBRET_OK on success. If a resource is not locked, ctdbUnlockRecord() performs no operation and returns CTDBRET_OK.
FairCom Corporation
150
When implementing callbacks you need to create your callbacks functions with the same type of ctdbCallbackFunc. Below is an example of a c-treeDB session logon callback.
Please refer to the Callback Types section below for more information on each available callback type.
www.faircom.com
All Rights Reserved
151
Sessions
For these types the handle parameter is a session handle. You can safely typecast the handle parameter to a pCTDBSESSION structure pointer. Please refer to the ctdbsdk.h header file for the declaration of CTDBSESSION structure. CTDB_ON_SESSION_LOGON CTDB_ON_SESSION_LOGOUT
Databases
For these types the handle parameter is a database handle. You can safely typecast the handle parameter to a pCTDBDATABASE structure pointer. Please refer to the ctdbsdk.h header file for the declaration of CTDBDATABASE structure. CTDB_DATABASE_CONNECT CTDB_DATABASE_DISCONNECT
Tables
For these types the handle parameter is a table handle. You can safely typecast the handle parameter to a pCTDBTABLE structure pointer. Please refer to the ctdbsdk.h header file for the declaration of CTDBTABLE structure. CTDB_ON_TABLE_OPEN CTDB_ON_TABLE_CLOSE CTDB_ON_TABLE_GET_DODA CTDB_ON_TABLE_GET_SCHEMA CTDB_ON_TABLE_GET_EXT_INFO CTDB_ON_TABLE_GET_RECLEN CTDB_ON_TABLE_ALTER CTDB_ON_TABLE_REBUILD
Records
For these types the handle parameter is a record handle. You can safely typecast the handle parameter to a pCTDBRECORD structure pointer. Please refer to the ctdbsdk.h header file for the declaration of CTDBRECORD structure. CTDB_ON_RECORD_INIT
FairCom Corporation
152
Callback Types
When a callback is registered with a c-treeDB handle, you need to specify which callback is being intercepted. The sections below describe each of the callback types that can be intercepted.
CTDB_ON_SESSION_LOGON
A CTDB_ON_SESSION_LOGON callback is invoked after a successful session logon but before the ctdbLogon() function returns. The handle passed as a parameter with this callback is a session handle. You can safely typecast the handle parameter to a pCTDBSESSION structure pointer. The session logon callback can be used as an indication that the session is now active and that database and table processing may occur. This callback is a good place to set session-wide parameters that may be active until a session logout is performed.
CTDB_ON_ SESSION_LOGOUT
A CTDB_ON_SESSION_LOGOUT callback is invoked before a session logout is performed. The handle passed as a parameter with this callback is a session handle and you can safely typecast the handle parameter as a pCTDBSESSION structure pointer. The session logout callback can be used to undo and cleanup operations performed by a session logon callback. No other callbacks calls will be issued after a CTDB_ON_SESSION_LOGOUT callback.
153
pCTDBSESSION pSession = (pCTDBSESSION)Handle; if (!pSession) Retval = CTDBRET_NOTSESSION; else { /* release any memory allocated by session logon callback */ if (pSession->localTag) { pSession->OnFree(pSession->localTag) pSession->localTag = NULL; } } return Retval; }
CTDB_ON_DATABASE_CONNECT
A CTDB_ON_DATABASE_CONNECT callback is invoked after a successful database connect but before the ctdbConnect() function returns. The handle passed as a parameter with this callback is a database handle and you can safely typecast the handle parameter to a pCTDBDATABASE structure pointer. The database connect callback can be used as an indication that the database connection is now active and that table processing may occur. This callback is a good place to set database-wide parameters that may be active until a database disconnect is performed. Below is an example demonstrating the database connect callback to set table open and table close callbacks.
CTDB_ON_DATABASE_DISCONNECT
A CTDB_ON_DATABASE_DISCONNECT callback is invoked just before a database disconnect is performed. The handle passed as a parameter with this callback is a database handle and you can safely typecast the handle parameter to a pCTDBDATABASE structure pointer. The database disconnect callback may be used to undo and cleanup any operations performed by a database connect callback. Below is an example demonstrating how to clear the callbacks established by the database connect callback.
FairCom Corporation
154
CTDBRET ctdbDECL OnDatabaseDisconnect(CTHANDLE Handle) { CTDBRET Retval = CTDBRET_OK; pCTDBDATABASE pDatabase = (pCTDBDATABASE)Handle; if (!pDatabase) Retval = CTDBRET_NOTDATABASE; else { Retval = ctdbClearCallback(Handle, CTDB_ON_TABLE_OPEN); if (Retval == CTDBRET_OK) Retval = ctdbClearCallback(Handle, CTDB_ON_TABLE_CLOSE); } return Retval; }
CTDB_ON_TABLE_OPEN
A CTDB_ON_TABLE_OPEN callback is invoked after the c-tree Plus data and index files are open, but before ctdbOpenTable() returns. The handle passed as a parameter with this callback is a table handle and you can safely typecast the handle parameter to a pCTDBTABLE structure pointer. The open table callback can be used as an indication that the table is active and that table and records operations may occur. Below is an example demonstrating how to obtain the record callbacks when the table open callback is called.
155
goto Exit; } /* initialize the local table data */ pLocal->pSession = pSession; pLocal->pTable = pTable; pLocal->dodaptr = NULL; pLocal->doda_size = 0; pLocal->dodacount = 0; pTable->localTag = (pVOID)pLocal; pLocal = NULL; /* set the other callbacks for this table */ if ((Retval = ctdbSetCallback(Handle, CTDB_ON_TABLE_OPEN, OnTableOpen)) != CTDBRET_OK) goto Exit; if ((Retval = ctdbSetCallback(Handle, CTDB_ON_TABLE_GET_DODA, OnTableGetDoda)) != CTDBRET_OK) goto Exit; if ((Retval = ctdbSetCallback(Handle, CTDB_ON_TABLE_GET_RECLEN, OnTableGetReclen)) != CTDBRET_OK) goto Exit; if ((Retval = ctdbSetCallback(Handle, CTDB_ON_TABLE_CLOSE, OnTableClose)) != CTDBRET_OK) goto Exit; if ((Retval = ctdbSetCallback(Handle, CTDB_ON_RECORD_INIT, OnRecordInit)) != CTDBRET_OK) goto Exit; if ((Retval = ctdbSetCallback(Handle, CTDB_ON_RECORD_RESET, OnRecordReset)) != CTDBRET_OK) goto Exit; if ((Retval = ctdbSetCallback(Handle, CTDB_ON_RECORD_BEFORE_READ, OnRecordBeforeRead)) != CTDBRET_OK) goto Exit; if ((Retval = ctdbSetCallback(Handle, CTDB_ON_RECORD_AFTER_READ, OnRecordAfterRead)) != CTDBRET_OK) goto Exit; if ((Retval = ctdbSetCallback(Handle, CTDB_ON_RECORD_BEFORE_BUILD_KEY, OnRecordBeforeBuildKey)) != CTDBRET_OK) goto Exit; if ((Retval = ctdbSetCallback(Handle, CTDB_ON_RECORD_AFTER_BUILD_KEY, OnRecordAfterBuildKey)) != CTDBRET_OK) goto Exit; if ((Retval = ctdbSetCallback(Handle, CTDB_ON_RECORD_BEFORE_WRITE, OnRecordBeforeWrite)) != CTDBRET_OK) goto Exit; if ((Retval = ctdbSetCallback(Handle, CTDB_ON_RECORD_AFTER_WRITE, OnRecordAfterWrite)) != CTDBRET_OK) goto Exit; /* set the callback for any records already allocated */ if (pTable->records) { NINT i; for (i = 0; i < pTable->records->count; i++) { CTHANDLE recHandle = (CTHANDLE)_ctdbListItem(pTable->records, i); if (recHandle) { if ((Retval = ctdbSetCallback(recHandle, CTDB_ON_RECORD_INIT, OnRecordInit)) != CTDBRET_OK) goto Exit; if ((Retval = ctdbSetCallback(recHandle, CTDB_ON_RECORD_RESET, OnRecordReset)) != CTDBRET_OK) goto Exit; if ((Retval = ctdbSetCallback(recHandle, CTDB_ON_RECORD_BEFORE_READ, OnRecordBeforeRead)) != CTDBRET_OK) goto Exit; if ((Retval = ctdbSetCallback(recHandle, CTDB_ON_RECORD_AFTER_READ, OnRecordAfterRead)) != CTDBRET_OK) goto Exit; if ((Retval = ctdbSetCallback(recHandle, CTDB_ON_RECORD_BEFORE_BUILD_KEY, OnRecordBeforeBuildKey)) != CTDBRET_OK) goto Exit; if ((Retval = ctdbSetCallback(recHandle, CTDB_ON_RECORD_AFTER_BUILD_KEY, OnRecordAfterBuildKey)) != CTDBRET_OK) goto Exit; if ((Retval = ctdbSetCallback(recHandle, CTDB_ON_RECORD_BEFORE_WRITE, OnRecordBeforeWrite)) != CTDBRET_OK) goto Exit; if ((Retval = ctdbSetCallback(recHandle, CTDB_ON_RECORD_AFTER_WRITE, OnRecordAfterWrite)) != CTDBRET_OK) goto Exit; } } } Exit:
FairCom Corporation
156
CTDB_ON_TABLE_CLOSE
A CTDB_ON_TABLE_CLOSE callback is invoked before the c-tree Plus data and index files are closed, but before the ctdbCloseTable() function returns. The handle passed as a parameter with this callback is a table handle and you can safely typecast the handle parameter to a pCTDBTABLE structure pointer. The close table callback may be used to undo and cleanup operations performed by the table open callback.
CTDB_ON_TABLE_GET_SCHEMA
A CTDB_ON_TABLE_GET_SCHEMA callback is invoked after the c-tree Plus data and index files are open and the CTDB_ON_TABLE_OPEN callback is invoked. This callback is also invoked after the c-tree Plus data file record schema object is loaded into the table handle. You may use the CTDB_ON_TABLE_GET_SCHEMA callback event to modify c-tree Plus schema information stored in the table handle. You should typecast the table handle to a pCTDBTABLE structure pointer. The following CTDBTABLE structure members keep schema information:
CTDBTABLE Structure Member Explanation c-tree ConvMap structure pointer size in bytes of allocated ConvMap structure
At the point a CTDB_ON_TABLE_GET_SCHEMA callback is invoked, the tables schema has already been loaded and stored in the schemaptr member of CTDBTABLE structure. The schema_size member contains the allocated size of schemaptr.
www.faircom.com
All Rights Reserved
157
pCTDBTABLE pTable = (pCTDBTABLE)Handle; if (!pTable) Retval = CTDBRET_NOTTABLE; else { /* change the field padding byte */ if (pTable->schemaptr) pTable->schemaptr->padding = ' '; } return Retval; }
CTDB_ON_TABLE_GET_DODA
A CTDB_ON_TABLE_GET_DODA callback is invoked after c-tree Plus data and index files are open and the CTDB_ON_TABLE_OPEN and CTDB_ON_TABLE_GET_SCHEMA callbacks have been invoked. This callback is also invoked after the c-tree Plus data file record schema and DODA object are loaded into the table handle. You can use the CTDB_ON_TABLE_GET_DODA callback event to modify the c-tree Plus DODA stored in the table handle. You should typecast the table handle to a pCTDBTABLE structure pointer. The following CTDBTABLE structure members keep DODA information:
CTDBTABLE Structure Member Explanation pointer to c-tree DODA size in bytes of allocated DODA number of fields in DODA
By the time a CTDB_ON_TABLE_GET_DODA callback is invoked, the tables DODA has already been loaded and stored in the dodaptr member of CTDBTABLE structure. The doda_size member contains the allocated size of dodaptr and dodacount keep count of the number of fields described by dodaptr. The example below shows how to use the CTDB_ON_TABLE_GET_DODA callback to modify the DODA information.
FairCom Corporation
158
{ pTable->dodaptr[i].fadr = newdoda[i].fadr; pTable->dodaptr[i].flen = newdoda[i].flen; pTable->dodaptr[i].ftype = newdoda[i].ftype; } /* fix the IFIL index segment */ if (pTable->ifilptr && pTable->ifilptr->ix && pTable->ifilptr->ix[0].seg) { pTable->ifilptr->ix[0].seg->soffset = 0; pTable->ifilptr->ix[0].seg->slength = 4; pTable->ifilptr->ix[0].seg->segmode = CTSEG_SCHSEG; } Exit: return Retval; }
CTDB_ON_TABLE_GET_RECLEN
A CTDB_ON_TABLE_GET_RECLEN callback is invoked after c-tree Plus data and index files are open and the T and CTDB_ON_TABLE_GET_SCHEMA and CTDB_ON_TABLE_GET_DODA callbacks have been invoked. This callback is also invoked after the c-tree Plus data file record schema and DODA object are loaded into the table handle. You can use the CTDB_ON_TABLE_GET_RECLEN callback event to control the length, in bytes, of the fixed portion of the record buffer. The handle passed to this callback is always a table handle and you can safely typecast the table handle to a pCTDBTABLE structure pointer. The following CTDBTABLE structure members keep the length of the fixed portion of the record buffer:
CTDBTABLE Structure Member Explanation length of fixed portion of record buffer
VRLEN fixreclen
By the time CTDB_ON_TABLE_GET_RECLEN callback is invoked, the fixreclen member of CTDBTABLE structure has already been calculated. You can use this event to modify the length of the fixed portion of the record buffer.
CTDB_ON_TABLE_GET_EXT_INFO
c-treeDB maintains extended field information that is not present in the DODA object, but is necessary for optimal c-treeSQL operation. Each DODA entry describes the field name, the field offset in the record buffer, the field type and length, but for optimal SQL operation we also need additional information such as the field precision, scale and if the field allows NULL values. A field precision is the total number of digits necessary to represent the value, while the field scale is the number of digits to the left of the decimal point. For example CT_NUMBER fields have a precision of 32 and scale from 0 to 32. CT_INT4 fields have precision of 10 and scale of 0. A NULL value for a field
www.faircom.com
All Rights Reserved
159
indicates that the field has no value (i.e., no value was assigned to the field when the record was written to the table.) A CTDB_ON_TABLE_GET_EXT_INFO callback is invoked after a c-tree Plus data and index files are open and the CTDB_ON_TABLE_OPEN and CTDB_ON_TABLE_GET_SCHEMA, CTDB_ON_TABLE_GET_DODA and CTDB_ON_TABLE_GET_RECLEN callbacks have been invoked. This callback is also invoked after the c-treeDB open table code has tried to load the extended field information resource. You can use the CTDB_ON_TABLE_GET_EXT_INFO callback event to add new, or modify existing, extended field information kept by the table handle. See the example below to see how to modify the extended field information. The handle passed to this callback is always a table handle and you can safely typecast the table handle to a pCTDBTABLE structure pointer.
/* /* /* /*
CTDBRET ctdbDECL OnTableGetExtInfo(CTHANDLE Handle) { CTDBRET Retval = CTDBRET_OK; pCTDBTABLE pTable = (pCTDBTABLE)Handle; if (!pTable) Retval = CTDBRET_NOTTABLE; else { NINT count = (pTable->fields) ? pTable->fields->count : 0; NINT i; for (i = 0; i < count; i++) { pCTDBFIELD pField = (pCTDBFIELD)pTable->fields->list[i]; if (pField) { pField->nonull = extinfo[i].nonull; pField->fprec = extinfo[i].fprec; pField->fscale = extinfo[i].fscale; } } } return Retval; }
CTDB_ON_TABLE_ALTER
A CTDB_ON_TABLE_ALTER callback is invoked at the beginning of the ctdbAlterTable function call, before any operations are performed on the table. This callback should be used to indicate if alter table operations are to be performed on a particular table.
FairCom Corporation
160
If the alter table operation is allowed, then the callback function must returns CTDBRET_OK value. On the other hand, if alter table operations are not to be allowed, the callback function must return an error code. In case of error, the suggested error code is CTDBRET_NOTSUPPORTED. The handle passed as a parameter with this callback is a table handle and you can safely typecast the handle parameter to a pCTDBTABLE structure pointer. Below demonstrates an ALTER TABLE not allowed if table name is mytable.
CTDB_ON_TABLE_REBUILD
The c-treeDB alter table function was designed and implemented to allow the modification of table properties after it was created and possibly already populated with data. Depending on which properties are modified, a full table rebuild may be necessary. A full table rebuild is accomplished by creating a temporary table with the correct properties, considering all changes made to the table, and then moving all of the records from the original table to the new temporary table. Once all of the data records have been moved, the original table is deleted and the temporary table renamed with the name of the original table. During the full table rebuild phase of moving records, a CTDB_ON_TABLE_REBUILD callback is invoked for every percentage point of progress. The progress percentage is calculated by dividing the number of records moved by the total number of records in a table. The percentage value is stored in the table handle and the callback function can access this value to display, for example, a progress report during lengthy alter table operations. If a CTDB_ON_TABLE_REBUILD callback returns a value other than CTDBRET_OK, the rebuild process will be aborted, and the alter table function will return the value. The handle passed as a parameter with this callback is a table handle and you can safely typecast the handle parameter to a pCTDBTABLE structure pointer. You can access the percentage counter by accessing the following CTDBTABLE structure member:
CTDBTABLE Structure Member Explanation percentage of table rebuild with values from 0 to 100
NINT rebuild_perc
Before any records are moved, the CTDB_ON_TABLE_REBUILD callback is called with rebuild_perc set to zero to indicate that the operation is about to start. After all records are copied, CTDB_ON_TABLE_REBUILD is called again, this time with rebuild_perc set to 100 to indicate the end of rebuild. Since CTDB_ON_TABLE_REBUILD callback is called inside the alter tables record moving loop, care must be taken with the implementation of the callback since it may adversely affect the performance of the alter table operation.
www.faircom.com
All Rights Reserved
161
You can also call the ctdbGetRebuildProgress() function to retrieve the table rebuild percentage counter.
CTDB_ON_RECORD_INIT
A CTDB_ON_RECORD_INIT callback is invoked when the record is initialized because it is being used for the first time or after an alter table. The handle passed as a parameter with this callback is a record handle and you can safely typecast the handle parameter to a pCTDBRECORD structure pointer. The record init callback can be used as an indication that the record handle is becoming active and records operations may occur from this point. The following CTDBRECORD structure members keep information regarding the record buffer kept by the record handle:
CTDBRECORD Structure Member Explanation record buffer size in bytes of memory allocated for record buffer actual length of data in record buffer
FairCom Corporation
162
CTDB_ON_RECORD_RESET
A CTDB_ON_RECORD_RESET callback is invoked when a record buffer is going inactive because the table is being closed. The handle passed as a parameter with this callback is a record handle and you can safely typecast the handle parameter to a pCTDBRECORD structure pointer. The following CTDBRECORD structure members keep information regarding the record buffer kept by the record handle:
CTDBRECORD Structure Member Explanation record buffer size in bytes of memory allocated for record buffer actual length of data in record buffer
CTDB_ON_RECORD_BEFORE_READ
A CTDB_ON_RECORD_BEFORE_READ callback is invoked just before a record is read by one of the c-tree Plus record reading functions. This callback is useful to prepare a record buffer just before data is read. The handle passed as parameter for this callback is a record handle and you can safely typecast the handle parameter to a pCTDBRECORD structure pointer. The following CTDBRECORD structure members keep information regarding the record buffer kept by the record handle:
CTDBRECORD Structure Member Explanation record buffer size in bytes of memory allocated for record buffer actual length of data in record buffer
www.faircom.com
All Rights Reserved
163
if (!pRecord) Retval = CTDBRET_NOTRECORD; else { /* swap the record buffer with the localTag */ pUTEXT ptr = pRecord->recbuf; pRecord->recbuf = pRecord->localTag; pRecord->localTag = ptr; } return Retval; }
CTDB_ON_RECORD_AFTER_READ
A CTDB_ON_RECORD_AFTER_READ callback is invoked just after a record is read by one of the c-tree Plus record reading functions. This callback is useful to adjust a record buffer just after data is read. The handle passed as parameter for this callback is a record handle and you can safely typecast the handle parameter to a pCTDBRECORD structure pointer. The following CTDBRECORD structure members keep information regarding the record buffer kept by the record handle:
CTDBRECORD Structure Member Explanation record buffer size in bytes of memory allocated for record buffer actual length of data in record buffer
FairCom Corporation
164
if ((ptr = gmtime(t)) != NULL) { if ((Retval = ctdbDatePack(&date, (ptr->tm_year + 1900), (ptr->tm_mon + 1), ptr->tm_mday)) == CTDBRET_OK { /* put converted CTDB date back into record buffer */ memcpy(&pRecord->recptr[pRecord->fields[i].offset], &date, sizeof(CTDATE)); } } else Retval = CTDBRET_INVDATE; } } } return Retval; }
CTDB_ON_RECORD_BEFORE_BUILD_KEY
A CTDB_ON_RECORD_BEFORE_BUILD_KEY callback is invoked just before a call to c-tree Plus BuildKey() function. The c-tree Plus BuildKey() function perform key segment translation from record buffer to target key. This callback is useful to prepare a record buffer just before an index key is built. The handle passed as parameter for this callback is a record handle and you can safely typecast the handle parameter to a pCTDBRECORD structure pointer. The following CTDBRECORD structure members keep information regarding the record buffer kept by the record handle:
CTDBRECORD Structure Member Explanation record buffer size in bytes of memory allocated for record buffer actual length of data in record buffer
www.faircom.com
All Rights Reserved
165
CTDBRET_OK) { time_t* tptr = (time_t*)&recptr[pRecord->fields[i].offset]; m.tm_year -= 1900; m.tm_mon--; m.tm_sec = 0; m.tm_min = 0; m.tm_hour = 0; m.tm_isdst = 0; *t = mktime(&m); } } } } return Retval; }
CTDB_ON_RECORD_AFTER_BUILD_KEY
A CTDB_ON_RECORD_AFTER_BUILD_KEY callback is invoked just after a call to the c-tree Plus BuildKey() function. The c-tree Plus BuildKey() function performs key segment translation from record buffer to target key. This callback is useful to adjust a record buffer just after a target key was built. The handle passed as a parameter with this callback is a record handle and you can safely typecast the handle parameter to a pCTDBRECORD structure pointer. The following CTDBRECORD structure members keep information regarding the record buffer kept by the record handle:
CTDBRECORD Structure Member Explanation record buffer size in bytes of memory allocated for record buffer actual length of data in record buffer
166
{ time_t* tptr = (time_t*)&recptr[pRecord->fields[i].offset]; m.tm_year -= 1900; m.tm_mon--; m.tm_sec = 0; m.tm_min = 0; m.tm_hour = 0; m.tm_isdst = 0; *t = mktime(&m); } } } } return Retval; }
CTDB_ON_RECORD_BEFORE_WRITE
A CTDB_ON_RECORD_BEFORE_WRITE callback is invoked just before a record is written with one of the c-tree Plus record writing or updating functions. This callback is useful to prepare a record buffer just before data is written to disk. The handle passed as a parameter with this callback is a record handle and you can safely typecast the handle parameter to a pCTDBRECORD structure pointer. The following CTDBRECORD structure members keep information regarding the record buffer kept by the record handle:
CTDBRECORD Structure Member Explanation record buffer size in bytes of memory allocated for record buffer actual length of data in record buffer
www.faircom.com
All Rights Reserved
167
{ time_t* tptr = (time_t*)&recptr[pRecord->fields[i].offset]; m.tm_year -= 1900; m.tm_mon--; m.tm_sec = 0; m.tm_min = 0; m.tm_hour = 0; m.tm_isdst = 0; *t = mktime(&m); } } } } return Retval; }
CTDB_ON_RECORD_AFTER_WRITE
A CTDB_ON_RECORD_AFTER_WRITE callback is invoked just after a record is written with one of the c-tree Plus record writing or updating functions. This callback is useful to adjust a record buffer just after data is written to disk. The handle passed as a parameter with this callback is a record handle and you can safely typecast the handle parameter to a pCTDBRECORD structure pointer. The following CTDBRECORD structure members keep information regarding the record buffer kept by the record handle:
CTDBRECORD Structure Member Explanation record buffer size in bytes of memory allocated for record buffer actual length of data in record buffer
FairCom Corporation
168
{ time_t* tptr = (time_t*)&recptr[pRecord->fields[i].offset]; m.tm_year -= 1900; m.tm_mon--; m.tm_sec = 0; m.tm_min = 0; m.tm_hour = 0; m.tm_isdst = 0; *t = mktime(&m); } } } } return Retval; }
CTDB_ON_RECORD_MAPTOPARENT
Called only if the the child table has the field mapping resource activated.Overides the field mapping information, i.e. if the callback function pointers are set, then the field mapping information stored in the child table resource is ignored and the callback function is responsible for copying the appropriate fields from the child record buffer to the parent record buffer (and vice-versa). The ctrouter.exe utility should be used to create a field mapping resource to the child table. Once the field mapping resource is set, and after the table is open by calling ctdbOpenTable() function, the two callback type mentioned above can be set to provide custom field mapping to and from the child table. It is recommended to set both CTDB_ON_RECORD_MAPTOPARENT and CTDB_ON_RECORD_MAPTOCHILD using a table handle, as this will automatically set the callbacks for any records allocated using the table handle. Example:
/* open the child table */ if ((Retval = ctdbOpenTable(hTable, "child", CTOPEN_NORMAL)) == CTDBRET_OK) { ctdbSetCallback(hTable, CTDB_ON_RECORD_MAPTOPARENT, MapToParent); ctdbSetCallback(hTable, CTDB_ON_RECORD_MAPTOCHILD, MapToChild); }
CTDB_ON_RECORD_MAPTOCHILD
Called only if the the child table has the field mapping resource activated.Overides the field mapping information, i.e. if the callback function pointers are set, then the field mapping information stored in the child table resource is ignored and the callback function is responsible for copying the appropriate fields from the child record buffer to the parent record buffer (and vice-versa). The ctrouter.exe utility should be used to create a field mapping resource to the child table. Once the field mapping resource is set, and after the table is open by calling ctdbOpenTable() function, the two callback type mentioned above can be set to provide custom field mapping to and from the child table. It is recommended to set both CTDB_ON_RECORD_MAPTOPARENT and CTDB_ON_RECORD_MAPTOCHILD using a table handle, as this will automatically set the callbacks for any records allocated using the table handle. Example:
/* open the child table */ if ((Retval = ctdbOpenTable(hTable, "child", CTOPEN_NORMAL)) == CTDBRET_OK) { ctdbSetCallback(hTable, CTDB_ON_RECORD_MAPTOPARENT, MapToParent); ctdbSetCallback(hTable, CTDB_ON_RECORD_MAPTOCHILD, MapToChild); }
www.faircom.com
All Rights Reserved
169
You can register any of the defined callback functions using the session handle and every time a database, table or record handle is allocated, they will automatically inherit their callbacks from the session handle. Conversely, if you register callbacks with a database handle, every time a table or a record handle is allocated they will automatically inherit their callbacks from the database handle. Record handles will inherit any callbacks registered with the table handle. You clear callbacks from a handle by calling either ctdbClearCallback() or ctdbClearAllCallback().
You can check if a given callback has been registered with a session, database, table or record handle by calling the ctdbGetCallback() function. If a callback function was set, ctdbGetCallback() returns the address of the function. If a particular callback is not set, ctdbGetCallback() returns NULL.
size is the number of bytes to be allocated. The returned value is a pointer to void. The c-treeDB session handle also has a function pointer called onFree that must be used by callback function to release memory. The onFree function pointer has the following type:
typedef void (ctdbDECL* ctdbFreeFunc)(pVOID ptr);
170
Please note that the c-treeDB database, table and record handles have a member variable called pSession which points to the current session handle. You can use this pSession member variable to obtain the reference to the onAlloc and onFree function pointers. In some cases you should typecast the pSession member as a pointer to a CTDBSESSION structure.
UNICODE UTF-16
UCS-2 and UTF-16 are alternative names for a 16-bit UNICODE Transformation Format, a character encoding form that provides a way to represent a series of abstract characters from UNICODE and ISO/IEC 10646 as a series of 16-bit words suitable for storage or transmission via data networks. UTF-16 is officially defined in Annex Q of ISO/IEC 10646-1. It is also described in The Unicode Standard version 3.0 and higher, as well as in the IETFs RFC 2871. UTF-16 represents a character that has been assigned within the lower 65536 code points of Unicode or ISO/IEC 10646 as a single code value equivalent to the characters code point: 0 for 0, hexadecimal FFFD for FFFD, for example. UTF-16 represents a character above hexadecimal FFFF as a surrogate pair of code values from the range D800-DFFF. For example, the character at code point hexadecimal 10000 becomes the code value sequence D800 DC00, and the character at hexadecimal 10FFFD, the upper limit of Unicode, becomes the code value sequence DBFF DFFD. Unicode and ISO/IEC 10646 do not assign characters to any of the code points in the D800-DFFF range, so an individual code value from a surrogate pair does not ever represent a character. These code values are then serialized as 16-bit words, one word per code value. Because the endian-ness of these words varies according to the computer architecture, UTF-16 specifies three encoding schemes: UTF-16, UTF-16LE, and UTF-16BE. UTF-16 is the native internal representation of text in the NT/2000/XP versions of Windows and in the Java and .NET bytecode environments, as well as in Mac OS Xs Cocoa and Core Foundation frameworks.
UNICODE UTF-8
UTF-8 is the byte-oriented encoding form of Unicode. The UTF-8 encoding is defined in ISO 10646-1:2000 Annex D and also described in RFC 3629 as well as section 3.9 of the Unicode 4.0 standard. UTF-8 has the following properties: UCS characters U+0000 to U+007F (ASCII) are encoded simply as bytes 0x00 to 0x7F (ASCII compatibility). This means that files and strings which contain only 7-bit ASCII characters have the same encoding under both ASCII and UTF-8. All UCS characters >U+007F are encoded as a sequence of several bytes, each of which has the most significant bit set. Therefore, no ASCII byte (0x00-0x7F) can appear as part of any other character.
www.faircom.com
All Rights Reserved
171
The first byte of a multi-byte sequence that represents a non-ASCII character is always in the range 0xC0 to 0xFD and it indicates how many bytes follow for this character. All further bytes in a multi-byte sequence are in the range 0x80 to 0xBF. This allows easy re-synchronization and makes the encoding stateless and robust against missing bytes. All possible 231 UCS codes can be encoded. UTF-8 encoded characters may theoretically be up to six bytes long, however 16-bit BMP characters are only up to three bytes long. The sorting order of big endian UCS-4 byte strings is preserved. The bytes 0xFE and 0xFF are never used in the UTF-8 encoding.
Example
TEXT tableName[9] = {0x63, 0x61, 0x6e, 0xc3, 0xa7, 0xc3, 0xa3, 0x6f, 0x00}; If ((Retval = ctdbCreateTable(hTable, tableName, CTCREATE_NORMAL)) != CTDBRET_OK) { printf(ctdbCreateTable failed with error %d\n, eRet); }
The bytes assigned to variable tableName is the UTF-8 representation of the Portuguese word cano. If the original strings are encoded using UTF-16, you can use the c-treeDB function, ctdb_u16TOu8(), to convert a UTF-16 string to a UTF-8 encoding. A UTF-8 string can also be converted back to UTF-16 by calling function ctdb_u8Tou16().
Example
CTDBRET OpenTable(CTHANDLE hTable, pWCHAR tableName) { CTDBRET Retval; TEXT buffer[512]; if ((Retval = ctdb_u16TOu8(tableName, buffer, sizeof(buffer)) == CTDBRET_OK) { if ((Retval = ctdbOpenTable(hTable, buffer, CTOPEN_NORMAL)) != CTDBRET_OK) printf(ctdbOpenTable failed with error %d\n, Retval); } else printf(ctdb_u16TOu8 failed with error %d\n, Retval); return Retval; }
FairCom Corporation
172
to prepare the library for Unicode support. Standalone and client builds need the ICU libraries from the ICU web site, as described in next chapter. c-treeDB C and C++ Unicode support is activated by defining macro ctdbUNICODE. ctdbUNICODE is activated automatically when ctUNICODE is selected with the mtmake build utility:
---- FairCom c-tree Plus UniCode Support ---This version of c-tree Plus provides support for UNICODE field types. Do you want to support UniCode field types? (Y)es (N)o (D)efaults- [N]: y
UNICODE Support
Simply storing Unicode data has always been possible with c-treeDB, provided the application treated the data as binary and performed any necessary translations. In this case using the stored Unicode data as a segment of an index was difficult since c-treeDB had no way of knowing how the underlying binary data was encoded: UTF-8. UTF-16, ASCII, etc.
www.faircom.com
All Rights Reserved
173
CT_FUNICODE CT_F2UNICODE
CT_UNICODE CT_2UNICODE
The length fields at the beginning of CT_F2UNICODE and CT_2UNICODE field types, and the length in the DODA entry for CT_FSTRING and CT_F2STRING field types, are specified in bytes. Specifying a field length in bytes is consistent with all other c-treeDB field types, but is inconsistent with the system level routines that ordinarily use a number of characters, not a number of bytes, to describe the length of UTF-16 strings. Storing a UTF-16 string longer than 64Kbytes requires a CT_UNICODE field. To store a UTF-16 string greater than 64Kbytes with a length prefix, convert the string to UTF-8 and store it in a CT_4STRING field, as discussed below. If this UTF-8 converted field is to be part of a key segment, then Extended Key Segment information must also be added to this key segment.
ctdbGetFieldAsUTF16() retrieves the field data as a Unicode UTF-16 string. If the underlying field type is not one of the Unicode field types, the data is converted to UTF-16 string. Handle is a record handle, FieldNbr is the number of the field, pValue is a pointer to a wide (UTF-16) string buffer and size indicates the size in bytes of the string area. ctdbGetFieldAsUTF16() returns CTDBRET_OK on success. Two new methods, GetFieldAsUTF16(), were added to the CTRecord class to enable applications to read data from a Unicode field types.
FairCom Corporation
174
GetFieldAsUTF16() retrieves the field data as a Unicode UTF-16 string. If the underlying field type is not one of the Unicode field types, the data is converted to a UTF-16 string. FieldNbr is the number of the field, value is a pointer to a wide (UTF-16) string buffer and size indicates the size in bytes of the string area.
void CTRecord::GetFieldAsUTF16(const CTString& FieldName, pWCHAR value, VRLEN size);
GetFieldAsUTF16() retrieves the field data as Unicode UTF-16 string. If the underlying field type is not one of the Unicode field types, the data is converted to a UTF-16 string. FieldName is a string object representing the field name, value is a pointer to a wide (UTF-16) string buffer and size indicates the size in bytes of the string area. Reading UTF-16 C Example
CTDBRET CheckData(CTHANDLE hRecord, pTEXT str, NINT val) { CTDBRET eRet; WCHAR WStr[32]; TEXT s[64]; CTSIGNED t; if ((eRet = ctdbGetFieldAsUTF16(hRecord, 0, WStr, sizeof(WStr))) != CTDBRET_OK) { printf("ctdbGetFieldAsUTF16 failed with error %d", eRet); goto Exit; } if ((eRet = (CTDBRET)ctdb_u16TOu8(WStr, s, sizeof(s))) != CTDBRET_OK) { printf("ctdb_u16TOu8 failed with error %d", eRet); goto Exit; } if (strcmp(s, str) != 0) { printf("UNICODE field contents not the same written"); eRet = CTDBRET_DIFFERENT; goto Exit; } if ((eRet = ctdbGetFieldAsSigned(hRecord, 1, &t)) != CTDBRET_OK) { printf("ctdbGetFieldAsSigned failed with error %d", eRet); goto Exit; } if ((NINT)t != val) { printf("integer field contents not the same written"); eRet = CTDBRET_DIFFERENT; goto Exit; } if ((eRet = ctdbNextRecord(hRecord)) != CTDBRET_OK) { if (eRet == INOT_ERR) eRet = CTDBRET_OK; else printf("ctdbNextRecord failed with error %d", eRet); } Exit: return eRet; }
www.faircom.com
All Rights Reserved
175
ctdbSetFieldAsUTF16() puts a Unicode UTF-16 string in a Unicode field. If the underlying field type is not one of the Unicode field types, the UTF-16 string is converted to the appropriate type before the data is stored in the field. Handle is a record handle, FieldNbr is the field number and pValue is a pointer to a wide (UTF-16) string buffer. ctdbSetFieldAsUTF16() returns CTDBRET_OK on success. Two new methods, SetFieldAsUTF16(), have been added to the CTRecord class to enable applications to write data to Unicode field types.
void CTRecord::SetFieldAsUTF16(NINT FieldNumber, pWCHAR value);
SetFieldAsUTF16() puts a Unicode UTF-16 string in a Unicode field. If the underlying field type is not one of the Unicode field types, the UTF-16 string is converted to the appropriate type before the data is stored in the field. FieldNbr is a number representing the field number and value is the wide (UTF-16) string buffer.
void CTRecord::SetFieldAsUTF16(const CTString& FieldName, pWCHAR value);
SetFieldAsUTF16() puts a Unicode UTF-16 string in a Unicode field. If the underlying field type is not one of the Unicode field types, the UTF-16 string is converted to the appropriate type before the data is stores in the field. FieldName is the field name and value is the wide (UTF-16) string buffer. Writing UTF-16 Data C Example
CTDBRET AddData(CTHANDLE hRecord, pTEXT str, NINT val) { CTDBRET eRet; WCHAR WStr[32]; if ((eRet = ctdbClearRecord(hRecord)) != CTDBRET_OK) { printf("ctdbClearRecord failed with error %d", eRet); goto Exit; } if ((eRet = (CTDBRET)ctdb_u8TOu16(str, WStr, sizeof(WStr))) != CTDBRET_OK) { printf("ctdb_u8TOu16 failed with error %d", eRet); goto Exit; } if ((eRet = ctdbSetFieldAsUTF16(hRecord, 0, WStr)) != CTDBRET_OK) { printf("ctdbSetFieldAsUTF16 failed with error %d", eRet); goto Exit; } if ((eRet = ctdbSetFieldAsSigned(hRecord, 1, (CTSIGNED)val)) != CTDBRET_OK) { printf("ctdbSetFieldAsSigned failed with error %d", eRet); goto Exit; } if ((eRet = ctdbWriteRecord(hRecord)) != CTDBRET_OK) { printf("ctdbWriteRecord failed with error %d", eRet); goto Exit; } Exit: return eRet; }
176
To accommodate both of these challenges, c-tree Plus incorporated extended key segments. The concept of an extended key segment can be applied to virtually any non-standard key segment. Our first implementation is for Unicode keys. Because of the complexity of the Unicode collation algorithm, and because of the incredible breadth of language and country support envisaged by Unicode, FairCom has chosen to implement Unicode key segments using the International Components for Unicode (ICU) open- source development project. The ICU implementation of Unicode support is available on a wide variety of platforms, but not every platform. The ICU web site can be accessed at: IBM International Components for Unicode (ICU) http://www-306.ibm.com/software/globalization/icu/index.jsp
177
If no locale default control option is made part of kseg_comp, there is no restriction on how close to the requested locale the effective locale must be. For example, if you request collation for the German language (de), you are likely to get a locale based on the system default (e.g., en_US in the United States). This is not a problem since it has been determined that the default rules work for the German language. If ctKSEG_COMPU_SYSDEFAULT_NOTOK is used, then a request to use locale xx_YY_Variant will succeed as long as collation rules for xx are available. If ctKSEG_COMPU_FALLBACK_NOTOK is used, then rules for the particular locale with its optional country and variant modifiers must be available. Falling back from xx_YY to xx is not satisfactory. In the case of the de locale noted above, the segment definition would cause an error in the call to PutXtdKeySegmentDef() if either of the NOTOK default restrictions are part of the definition. At most one of the following collation strength options can be included in kseg_comp: ctKSEG_COMPU_S_PRIMARY ctKSEG_COMPU_S_SECONDARY ctKSEG_COMPU_S_TERTIARY ctKSEG_COMPU_S_QUATERNARY ctKSEG_COMPU_S_IDENTICAL ctKSEG_COMPU_S_DEFAULT At most, one of the following normalization options can be included in kseg_comp: ctKSEG_COMPU_N_NONE ctKSEG_COMPU_N_CAN_DECMP ctKSEG_COMPU_N_CMP_DECMP ctKSEG_COMPU_N_CAN_DECMP_CMP ctKSEG_COMPU_N_CMP_DECMP_CAN ctKSEG_COMPU_N_DEFAULT One or more of the following special attributes can be included in kseg_comp After each one of the c-tree symbolic constants is the equivalent ICU-attribute value pair.
c-tree Symbolic Constant ICU Attribute value pair (UCOL_FRENCH_COLLATION,UCOL_ON) (UCOL_FRENCH_COLLATION,UCOL_OFF) (UCOL_CASE_LEVEL,UCOL_ON) (UCOL_CASE_LEVEL,UCOL_OFF) (UCOL_DECOMPOSITION_MODE,UCOL_ON) (UCOL_DECOMPOSITION_MODE,UCOL_OFF) (UCOL_ALTERNATE_HANDLING, UCOL_SHIFTED) (UCOL_ALTERNATE_HANDLING, UCOL_NON_IGNORABLE) (UCOL_CASE_FIRST,UCOL_LOWER_FIRST) (UCOL_CASE_FIRST,UCOL_UPPER_FIRST) (UCOL_NORMALIZATION_MODE, UCOL_ON_WITHOUT_HANGUL)
FairCom Corporation
ctKSEG_COMPU_A_FRENCH_ON ctKSEG_COMPU_A_FRENCH_OFF ctKSEG_COMPU_A_CASE_ON ctKSEG_COMPU_A_CASE_OFF ctKSEG_COMPU_A_DECOMP_ON ctKSEG_COMPU_A_DECOMP_OFF ctKSEG_COMPU_A_SHIFTED ctKSEG_COMPU_A_NONIGNR ctKSEG_COMPU_A_LOWER ctKSEG_COMPU_A_UPPER ctKSEG_COMPU_A_HANGUL
178
It is permissible to set kseg_comp to zero. A zero kseg_comp implies no restrictions on locale defaults, default collation strength, default normalization, and no special attributes. For a complete treatment of all of these options, please refer to the ICU web site and the Uni- code Consortiums web site and publications.
www.faircom.com
All Rights Reserved
179
The implementation of extended key segments in c-treeDB allows a single extended key segment definition to be used by more than one actual key segment. Extended key segment definitions may be set for all segments of a table, all segments of an index or for each particular key segment. If a key segment mode includes a modifier for an extended key segment definition CTSEG_UNCSEG or the segment mode is CTSEG_SCHSEG, and the field type is one of the Unicode types, then the particular extended key segment definition to use for this segment is determined according to the following hierarchy. Use the definition specified for: 1. The segment 2. The index associated with the segment 3. The data file associated with the index Once an extended key segment definition has been specified at a particular level (for a particular type of segment), an attempt to specify another definition at the same level results in an error. This is in part because of the first use strategy noted above, and because one should not change a definition if key values already exist.
FairCom Corporation
180
ctdbSetTableKSeg() establishes a table-wide extended key segment definition. Handle must be a table handle and pKSeg is a pointer to an extended key segment definition structure with the extended key definition. ctdbSetTableKSeg() returns CTDBRET_OK on success.
CTDBRET ctdbGetTableKSeg(CTHANDLE Handle, pctKSEGDEF pKSeg);
ctdbGetTableKSeg() retrieves the current table-wide extended key segment definition. Handle must be a table handle and pKSeg is a pointer to an extended key segment definition structure which will receive the definition. If no extended key segment definition is available, ctdbGetTableKSeg() returns CTDBRET_NOTFOUND. On success ctdbGetTableKSeg() returns CTDBRET_OK. The following two functions were added to implement index-wide extended key segment definitions:
CTDBRET ctdbSetIndexKSeg(CTHANDLE Handle, pctKSEGDEF pKSeg);
ctdbSetIndexKSeg() establishes an index-wide extended key segment definition. Handle must be an index handle and pKSeg is a pointer to an extended key segment definition structure with the extended key definition. ctdbSetIndexKSeg() returns CTDBRET_OK on success.
CTDBRET ctdbGetIndexKSeg(CTHANDLE Handle, pctKSEGDEF pKSeg);
ctdbGetIndexKSeg() retrieves the current index-wide extended key segment definition. Handle must be an index handle and pKSeg is a pointer to an extended key segment definition structure which will receive the definition. If no extended key segment definition is available, ctdbGetIndexKSeg() returns CTDBRET_NOTFOUND. On Success ctdbGetIndexKSeg() returns CTDBRET_OK. The following three functions were added to implement an extended key segment definition for a specific key segment:
CTDBRET ctdbSetSegmentKSeg(CTHANDLE Handle, pctKSEGDEF pKSeg);
ctdbSetSegmentKSeg() establishes a segments extended key segment definition. Handle must be a segment handle and pKSeg is a pointer to an extended key segment definition structure with the extended key definition. ctdbSetSegmentKSeg() returns CTDBRET_OK on success.
CTDBRET ctdbGetSegmentKSeg(CTHANDLE Handle, pctKSEGDEF pKSeg);
ctdbGetSegmentKSeg() retrieves the current index-wide extended key segment definition. Handle must be a segment handle and pKSeg is a pointer to an extended key segment definition structure which will receive the definition. If no extended key segment definition is available, ctdbGetSegmentKSeg() returns CTDBRET_NOTFOUND. On Success ctdbGetSegmentKSeg() returns CTDBRET_OK.
CTDBRET ctdbSetKSegDefaults(pctKSEGDEF pKSeg);
ctdbSetKSegDefaults() sets the system-wide default values for the extended key segment definition. pKSeg is a pointer to an extended key segment definition structure which will receive the definition. The default values are:
kseg_ssiz kseg_type kseg_styp kseg_comp kseg_desc = = = = = ctKSEG_SSIZ_COMPUTED; ctKSEG_TYPE_UNICODE; ctKSEG_STYP_UTF16; ctKSEG_COMPU_S_DEFAULT | ctKSEG_COMPU_N_NONE; "en_US"
length of desc string status (internal use) version info source size segment type source type comparison options future use future use text specification eg, locale string
*/ */ */ */ */ */ */ */ */ */
181
The c-tree Plus module ctport.h contains defines for all of the constants, beginning with ctKSEG, used to create an extended key segment definition. As extended key segments are currently implemented, the kseg_stat and the kseg_vrsn members are filled-in as needed by the extended key segment implementation itself. The kseg_ssiz member specifies the number of bytes of source data to use to derive the actual key segment. In addition to using a specific numeric value for the source size, kseg_ssiz may also be assigned either of two values discussed in the following two sections. ctKSEG_SSIZ_COMPUTED The information about the underlying data field will be used to compute how much source data is available. For fields without length specifiers (such as CT_STRING or CT_UNICODE) an appropriate version of strlen() will be used to determine data availability. However, this could be very inefficient if the field may hold very long strings since it is likely that only a small portion of the variable length field will actually contribute to the key segment. An alternative is to specify a fixed source size. If the variable data has less than this size, it will still be handled correctly. ctKSEG_SSIZ PROVIDED The call to create the key segment will provide the particular length of source data available. For an ICU Unicode definition, the remaining structure members are specified as follows: kseg_type Must be set to ctKSEG_TYPE_UNICODE. kseg_styp Specify the type of source data as follows: ctKSEG_STYP_UTF8 ctKSEG_STYP_UTF16 ctKSEG_STYP_PROVIDED ctKSEG_STYP_PROVIDED means that the type of source data will be determined at run-time during key value construction. (Key value construction consists of one or both of assembling the key value from its component segments and performing transformations to generate a binary sort key). In this case, if the data type is one of the conventional c-tree Plus string types (e.g., CT_STRING), the source data type is UTF8; if a Unicode string type is found (e.g., CT_UNICODE), then the source data type is UTF16. However, if the underlying data type does not fall into either of these categories, the data is treated as UTF16, and used as is. kseg_desc Contains the ICU locale formed as an ordinary, null-terminated ASCII string. The format specified by ICU is xx, xx_YY, or xx_YY_Variant where xx is the language as specified by ISO-639 (e.g., fr for French); YY is a country as specified by ISO-3166 (e.g., fr_CA for French language in Canada); and the Variant portion represents system-dependent options. Note: When ICU uses a locale to access collation rules, it attempts to get rules for the closest match to the locale specified in kseg_desc. By default, there is no restriction on how close the match of locales must be to be acceptable. You can restrict the use of alternative locales by including either ctKSEG_COMPU_FALLBACK_NOTOK or ctKSEG_COMPU_SYSDEFAULT_NOTOK as part of the bit map comprising kseg_comp discussed below. After a successful call to PutXtdKeySegmentDef(), the GetXtdKeySegmentDef() function can be used to determine the actual ICU locale used during collation. kseg_comp This member of the structure permits the full range of ICU collation options to be specified through a bit map.
FairCom Corporation
182
*/
3.10 Compatibility
Compatibility with c-tree Plus ISAM and Low-level Data Files
The basic requirement for c-tree Plus ISAM and low-level data and index files to work with c-treeDB is that the data file must have DODA describing the fields and an IFIL describing the data and index structures. The DODA resource must have an entry for every field that forms a data record. The c-treeDB interface was designed to work best with ISEG structures with schema segments, that is, each index segment is a field declared in a DODA entry. c-treeDB works with index segments defined in the ISEG structures using absolute record offsets and arbitrary lengths, that may or may not span more than one field in the record buffer, however, advanced features of c-treeDB may not work as expected. ctdbAlterTable(), ctdbSetRecordOn(), and ctdbFindRecord() are typical examples of functions that may not work as expected when dealing with absolute segment offsets. Another source of problems may come from non-standard usage of c-tree field types declared in the DODA. There have been cases where CT_ARRAY fields being used as variable length data, CT_STRING fields being used as fixed string fields. Another source of concern are CT_DATE, CT_TIME, and CT_DATETIME fields whose contents will not be compatible with the definitions of data and time used by c-treeDB. c-treeDB was designed from the outset to be as compatible as possible with existing c-tree ISAM and low-level data, however, there are situations where c-treeDB may not be able to handle very specific data type arrangements used by c-tree Plus users in their custom applications.
Field mapping between c-treeSQL, c-treeDB, and c-tree Plus for .NET
c-treeSQL Field Type c-treeDB Field Type
www.faircom.com
All Rights Reserved
183
FLOAT DOUBLE TID CHAR VARCHAR LVARCHAR BINARY VARBINARY LVARBINARY DATE TIME TIMESTAMP BIGINT MONEY NUMBER, NUMERIC, DECIMAL
CT_FLOAT CT_DOUBLE CT_UINTEGER CT_CHARS CT_VARCHAR CT_LVARCHAR CT_BINARY CT_VARBINARY CT_LVARBIN CT_DATE CT_TIME CT_TIMESTAMP CT_BIGINT CT_CURRENCY CT_NUMBER
Overview
c-treeDB, short for c-tree DataBase, is a high level, easy to use API abstracting the two popular FairCom APIs, ISAM and Low-level. c-treeDB is intended as the standard for c-tree Plus programming. If you are creating a new application and have selected c-treeDB as the API of choice to access your data, there may be situations where you need to place calls directly into the ISAM or even low-level layers while remaining in your c-treeDB code. This may be to obtain certain specific services that may not be directly supported by c-treeDB or you may want to rewrite certain c-treeDB functionality to better suit your specific requirements.
FairCom Corporation
184
It may be common to find situations were you have an existing application written using the ISAM or low-level API, however, you develop new modules using the c-treeDB API and will migrate the existing modules over time to c-treeDB. In either case you will need c-treeDB to support the mix of ISAM or low-level function calls with your c-treeDB code, specifically when you must work with a table's data and index files and record data. The C functions and C++ methods described below will present new functionality supplementing the c-treeDB C and C++ APIs.
This call will force a switch to the c-tree Plus instance indicated by the Session handle. Each session handle has a unique c-tree instance id. When most c-treeDB functions are called, they automatically perform a c-tree instance switch. ctdbSwitchInstance is used before a call to a specific c-tree ISAM or low level function to ensure the correct instance is active before instantiating the call. You may pass any c-treeDB handle to ctdbSwitchInstance. CTDBRET_OK is returned on success. Similarly, the following c-treeDB C++ method performs a c-tree instance switch:
void CTBase::SwitchInstance()
This method will force a switch to the c-tree Plus instance indicated by the Session object. Each session object has a unique c-tree instance id. When most c-treeDB C++ methods are called, they automatically perform a c-tree instance switch. If any errors are detected, a CTException is thrown. The following is an example demonstrating a server administration logon in a LOCLIB implementation then forcing a c-tree instance switch to the remote instance and calling some ctreeUserOperation function.
/* declare and allocate the remote and local session handles */ CTHANDLE hRemote = ctdbAllocSession(CTSESSION_CTREE); CTHANDLE hLocal = ctdbAllocSession(CTSESSION_CTREE); /* logon to c-tree server using the remote session handle */ if (ctdbLogon(hRemove, "FAIRCOMS", "ADMIN", "ADMIN") != CTDBRET_OK) printf("Remote ctdbLogon failed\n"); /* logon to local session using the local session handle */ if (ctdbLogon(hLocal, "local", "ADMIN", "ADMIN) != CTDBRET_OK) printf("Local ctdbLogon failed\n"); /* perform a c-tree instance switch and call ctreeUserOperation function */ if (ctdbSwitchInstance(hRemote) != CTDBRET_OK) printf("ctdbSwitchInstance failed\n"); else CtreeUserOperation("!mkdir faircom", buffer, sizeof(buffer));
www.faircom.com
All Rights Reserved
185
This call will force a switch to the c-tree Plus ISAM context indicated by the record handle. Each record handle has a c-tree ISAM context id associated with it. When most c-treeDB record handling functions are called, they will automatically perform a c-tree ISAM context switch. ctdbSwitchContext is called before specific c-tree ISAM or low level calls to make sure the correct ISAM context is active before making those calls. The handle must be a record handle. No other handle is acceptable. CTDBRET_OK is returned on success. Similarly, the following c-treeDB C++ method should be used to perform a context switch:
void CTRecord::SwitchContext()
This method will force a switch to the c-tree Plus ISAM context indicated by the record object. Each record object may have its own c-tree ISAM context id. If any errors are detected, a CTException is thrown. The following code snippet demonstrates use of the ctdbSwitchContext function to call the c-tree ISAM function ResetRecord.
/* force a context switch */ if (ctdbSwitchContext(hRecord) != CTDBRET_OK) printf("ctdbSwitchContext failed\n"); /* call ResetRecord */ if (ResetRecord((COUNT)ctdbGetDatno(hRecord), SWTCURI)) printf("ResetRecord failed\n");
Retrieve the table datno. Handle must be a table handle, or a handle that can be converted into a table handle. Return the table datno on success or -1 on failure. If ctdbGetDatno() returns -1, the error code can be retrieved by calling the ctdbGetError() function. The following c-treeDB method will similarly retrieve a data file number from a table object:
NINT CTTable::GetDatno()
186
Handle must be an index or segment handle. ctdbGetIdxnoByName will retrieve an index file number given an index name and is declared as follows:
NINT ctdbGetIdxnoByName(CTHANDLE Handle, pTEXT indexname)
Handle must be a table handle, or a handle that can be converted into a table handle. IndexName is a string containing the index name. To retrieve the index file number by index number, call the c-treeDB function ctdbGetIdxnoByNumber declared as follows:
NINT ctdbGetIdxnoByNumber(CTHANDLE Handle, NINT index)
Handle must be a table handle, or a handle that can be converted into a table handle. index is a c-treeDB index number. The first index number is zero. These c-tree DB functions will return the index number on success or -1 on failure. If -1 is returned, the error code is retrieved with a call to the ctdbGetError function. Corresponding methods were added to the c-treeDB C++ API. The following method is used to retrieve the data file number from a CTTable object:
NINT CTTable::GetDatno()
This retrieves the table datno. A CTException is thrown if an error occurs. The following methods are used to retrieve the index file number:
NINT CTIndex::GetIdxno()
This method retrieves the index file number from the index object.
NINT CTTable::GetIdxno(const CTString& IndexName)
This method retrieves the index file number from the table object, given the index name.
NINT CTTable::GetIdxno(NINT index)
This method retrieves the index file number from the table object, given the c-treeDB index number. In all cases, if the GetIdxno method fails, a CTException is thrown.
www.faircom.com
All Rights Reserved
187
FairCom Corporation
188
Chapter 4
Declaration
Function and parameter declarations
Description
A detailed description of the function and parameters. Parameter [in/out] detail.
Returns
Explanation of the common return values.
Example
A simple programming example.
See also
A list of related functions and other information.
www.faircom.com
All Rights Reserved
189
FairCom Corporation
190
Implementation Fixed length data with 1-byte length count Fixed length data with 2-byte length count Fixed length data with 4-byte length count Eight-byte signed integer Scaled BCD number Eight-byte signed integer interpreted as currency value with four fixed decimal digits. Varying length field data with 1-byte length count. Varying length field data with 2-byte length count. Variable length binary data of up to 65535 bytes. Varying length field data with 4-byte length count. Variable length binary data of up to 4294967295 bytes. Varying length field delimited data. Variable length string data.
CT_PSTRING CT_VARBINARY
CT_PSTRING CT_2STRING
pTEXT pTEXT
CT_LVB
CT_4STRING
pTEXT
CT_VARCHAR or CT_LVC
CT_STRING
pTEXT
All the c-tree Plus for .NET field types are defined using the FIELD_TYPE enum.
c-tree Plus for .NET Field Type
BOOL TINYINT UTINYINT SMALLINT USMALLINT INTEGER UINTEGER MONEY DATE TIME FLOAT DOUBLE
www.faircom.com
All Rights Reserved
191
TIMESTAMP EFLOAT BINARY CHARS FPSTRING F2STRING F4STRING BIGINT NUMBER CURRENCY PSTRING VARBINARY LVB VARCHAR/LVC
Find Modes
Use the following find modes with the record find methods:
c-treeDB Find mode c-tree Plus for .NET Find Mode Explanation Find a record equal to the target Find a record less than target Find a record less or equal than target Find a record greater than target Find a record greater or equal than target
EQ LT LE GT GE
Note: The Find Mode CTFIND_EQ requires that the target contains values for all segments that compose the index and the index cannot allow duplicates. Note: c-tree Plus for .NET defines this mode with the FIND_MODE enum.
CTINDEX_FIXED
FIXED_INDEX
FairCom Corporation
192
Fixed length keys that are likely to have leading character duplication among the key values Variable length keys for which not much leading character duplication is expected. Variable length keys for which much leading character duplication is expected. Index type error.
Note: c-tree Plus for .NET Index Key Types are defined in the KEY_TYPE enum.
Note: c-tree Plus for .NET can find the Lock Modes listed in the LOCK_MODE enum.
www.faircom.com
All Rights Reserved
193
CTLOCK_SUSPEND mode. This lock mode restores the lock mode as READ.
To be used after a call to Lock with the
CTLOCK_SUSPEND mode. This lock mode restores the lock mode as WRITE.
To be used after a call to Lock with the
CTLOCK_RESTORE _PREVIOUS
c-tree Plus for .NET Lock Modes are defined in the LOCK_MODE enum.
Segment Modes
The segment modes based on absolute field number, also known as schema fields, are the preferred modes to use in the segment definition. The preferred segment modes are: CTSEG_SCHSEG CTSEG_USCHSEG CTSEG_VSCHSEG CTSEG_UVSCHSEG CTSEG_SCHSRL You may OR in the mode CTSEG_DESCENDING to the segment mode to specify the descending sort order for a segment. You can also or in the segment mode CTSEG_ALTSEG to specify an alternate collating sequence for the segment. Using the preferred segment modes makes c-treeDB based tables fully compatible with ISAM/Low Level applications and/or c-treeSQL applications.
c-treeDB Segment Modes c-tree Plus for .NET Segment Modes SCHSEG_SEG
Explanation Absolute field number Absolute field number - uppercase Absolute field number - pad strings Absolute field number - pad strings upper Absolute field number - auto increment
FairCom Corporation
194
Explanation Descending segment mode Alternative collating sequence END segment mode
The other segment modes are kept for compatibility with existing c-tree Plus applications. Advanced c-treeDB functions like ctdbAlterTable() may not work properly if the segment mode is not one of the preferred segment modes. You may specify these segment modes with ctdbAddSegmentEx(), which expects an absolute record offset where the segment is to start instead of a field indicator, the length in bytes of the segment, and the segment mode.
c-treeDB Segment Modes c-tree Plus for .NET Segment Modes
Explanation Absolute byte offset - No transformation Absolute byte offset - unsigned int/long Absolute byte offset - uppercase Absolute byte offset - auto increment Relative field number Relative field number - uppercase Absolute byte offset - signed int/long Absolute byte offset - float/double Absolute byte offset - not yet implemented Absolute byte offset - not yet implemented Descending segment mode Alternative collating sequence
CTSEG_REGSEG CTSEG_INTSEG CTSEG_UREGSEG CTSEG_SRLSEG CTSEG_VARSEG CTSEG_UVARSEG CTSEG_SGNSEG CTSEG_FLTSEG CTSEG_DECSEG CTSEG_BCDSEG CTSEG_DESCENDING CTSEG_ALTSEG
REGSEG_SEG INTSEG_SEG UREGSEG_SEG SRLSEG_SEG VARSEG_SEG UVARSEG_SEG SGNSEG_SEG FLTSEG_SEG DECSEG_SEG BCDSEG_SEG DESCENDING_SEG ALTSEG_SEG
c-tree Plus for .NET Segment Modes are defined in the SET_MODE enum.
CTCREATE_NORMAL CTCREATE_PREIMG
NORMAL_CREATE PREIMG_CREATE
www.faircom.com
All Rights Reserved
195
Value 2
Explanation With this mode you will get the full benefit of transaction processing, including both atomicity and automatic recovery. If you are not sure of what mode to use, and you do want to use transaction processing, then use this mode. This mode forces the operating system to flush all disk cache buffers when a data write occurs. Setting this mode can slow performance of the file handler. On the other hand, it is an important feature to use if you want to ensure that all data writes are put to the disk immediately. It is particularly important if you are in an operating environment where the system crashes a lot, and you are not using transactions. However, this mode does not guarantee that operating system buffers will be flushed as expected. Tables created with this mode requires a record lock before a record can be updated. If a lock is not obtained, the error code DADV_ERR is returned.
CTCREATE_TRNLOG
TRNLOG_CREATE
CTCREATE_WRITETH RU
WRITETHRU_CREA TE
CTCREATE_CHECKL OCK
CHECKLOCK_CREA TE
16
32 64 128 Create the table without the RECBYT index. Create the table without the ROWID index. Tables create with this mode requires a record lock as records are read. Obtain at least a read lock on a record before it can be read, otherwise the function will return error code DADV_ERR. Create the table with huge file support. With this mode on, tables will support 8 byte addresses for file offsets. This mode indicate that the create is to be created without the $DELFLD$ field support. This mode indicate that the table is to be created without the $NULFLD$ field support.
HUGEFILE_CREATE
256
NODELFLD_CREAT E NONULFLD_CREAT E
512
1024
FairCom Corporation
196
CTOPEN_NORMAL CTOPEN_DATAONLY
NORMAL_OPEN DATAONLY_OPEN
CTOPEN_EXCLUSIVE
EXCLUSIVE_OPEN
CTOPEN_PERMANENT
PERMANENT_OPEN
CTOPEN_CORRUPT
CORRUPT_OPEN
www.faircom.com
All Rights Reserved
197
Explanation Tables opened with this mode requires a record lock before a record can be updated. If a lock is not obtained, the error code DADV_ERR is returned. Tables opened with this mode requires a record lock as records are read. Obtain at least a read lock on a record before it can be read, otherwise the function will return error code DADV_ERR. Opens the table in READONLY mode and does not allow any modifications to the table structure or data records.
CTOPEN_CHECKLOCK
CHECKLOCK_OPEN
CTOPEN_CHECKREAD
CHECKREAD_OPEN
CTOPEN_READONLY
READONLY_OPEN
Note: c-tree Plus for .NET users can find the open modes listed in the OPEN_MODE enum.
Table Permissions
c-tree DB Permission Constant c-tree Plus for .NET Permission Constant Explanation owner read permission owner write/update permission owner file definition permission owner file deletion permission owner granted all permissions owner grants read only without password group access denied group read permission group write/update permission group file definition permission group file deletion permission group read only access without password world access denied world read permission world write/update permission world file definition permission world file deletion permission
OPF_READ OPF_WRITE OPF_DEF OPF_DELETE OPF_ALL OPF_NOPASS GPF_NONE GPF_READ GPF_WRITE GPF_DEF GPF_DELETE GPF_NOPASS WPF_NONE WPF_READ WPF_WRITE WPF_DEF WPF_DELETE
O_READ O_WRITE O_DEF O_DELETE O_ALL O_NOPASS G_NONE G_READ G_WRITE G_DEF G_DELETE G_NOPASS W_NONE W_READ W_WRITE W_DEF W_DELETE
FairCom Corporation
198
WPF_NOPASS
W_NOPASS
Initialization
The initialization API prepares the environment for c-tree Plus operation and manages transactions.
ctdbCloseAll ctdbCloseTable ctdbConnect ctdbCreateDatabase ctdbCreateSession ctdbDeleteDatabase ctdbDisconnect ctdbDisconnectAll ctdbDropDatabase ctdbFindActiveDatabase ctdbFindActiveDatabaseByUID ctdbFindDatabase ctdbFindDatabaseByUID ctdbFirstDatabase ctdbFreeDatabase ctdbFreeSession ctdbGetActiveDatabaseUID ctdbGetDatabaseCount ctdbGetDatabaseHandle ctdbGetDatabaseName ctdbGetDatabasePath ctdbGetDatabaseUID
Transaction Processing
ctdbAbort ctdbBegin ctdbCommit ctdbGetRecordLock ctdbIsLockActive ctdbIsTransActive ctdbLock ctdbLockRecord ctdbRestoreSavePoint ctdbSetSavePoint ctdbUnlock ctdbUnlockRecord ctdbUnlockTable
Data Definition
ctdbAddDatabase ctdbAddField ctdbAddIndex ctdbAddSegment ctdbDelField ctdbDelFieldByName ctdbDelIndex ctdbDelSegment ctdbGetFieldName ctdbGetFieldNbr ctdbGetFieldNullFlag ctdbGetFieldNumber
www.faircom.com
All Rights Reserved
199
ctdbAddSegmentByName ctdbAddSegmentByNbr ctdbAddSegmentEx ctdbAddTable ctdbAllocDatabase ctdbAllocRecord ctdbAllocSession ctdbAllocTable ctdbAlterTable ctdbBlobAlloc ctdbBlobFree ctdbCreateTable ctdbDeleteTable
ctdbDelSegmentEx ctdbDropTable ctdbFindActiveTable ctdbFindActiveTableByUID ctdbFindTable ctdbFindTableByUID ctdbFirstTable ctdbFreeRecord ctdbFreeTable ctdbGetActiveTableByUID ctdbGetActiveTableUID ctdbGetDefaultIndex ctdbGetDefaultIndexName
ctdbGetFieldNumberByName ctdbGetFieldOffset ctdbGetFieldPrecision ctdbGetFieldProperties ctdbGetFieldScale ctdbGetFieldSize ctdbGetFieldType ctdbGetPadChar ctdbOpenTable ctdbOpenTableByUID ctdbSetPadChar ctdbUpdatePadChar
Data Manipulation
ctdbBuildTargetKey ctdbDeleteRecord ctdbDuplicateRecord ctdbFindRecord ctdbFindTarget ctdbFirstRecord ctdbGetField ctdbGetFieldAddress ctdbGetFieldAsBigint ctdbGetFieldAsBinary ctdbGetFieldAsBlob ctdbGetFieldAsBool ctdbGetFieldAsCurrency ctdbGetFieldAsDate ctdbGetFieldAsDateTime ctdbGetFieldAsFloat ctdbGetFieldAsMoney ctdbGetFieldAsNumber ctdbGetFieldAsSigned ctdbGetFieldAsString ctdbGetFieldAsTime ctdbGetFieldAsUnsigned ctdbGetFieldByName ctdbGetFieldDataLength ctdbGetFieldHandle ctdbGetFieldLength ctdbLastRecord ctdbNextRecord ctdbPrevRecord ctdbReadRecord ctdbRecordSetOff ctdbRecordSetOn ctdbSeekRecord ctdbWriteRecord
Data Types
ctdbBigIntToCurrency ctdbBigIntToFloat ctdbDateToString ctdbDateUnpack ctdbMoneyToString ctdbNumberAbs
FairCom Corporation
200
ctdbBigIntToLong ctdbBigIntToNumber ctdbBigIntToString ctdbBlobClear ctdbBlobCmp ctdbBlobGetData ctdbBlobGetSize ctdbBlobSet ctdbCurrencyAbs ctdbCurrencyAdd ctdbCurrencyCmp ctdbCurrencyDiv ctdbCurrencyMul ctdbCurrencyRound ctdbCurrencySub ctdbCurrencyToBigInt ctdbCurrencyToFloat ctdbCurrencyToLong ctdbCurrencyToMoney ctdbCurrencyToNumber ctdbCurrencyToString ctdbDateCheck ctdbDatePack ctdbDateTimeGetDate ctdbDateTimeGetTime ctdbDateTimePack ctdbDateTimeSetDate ctdbDateTimeSetTime ctdbDateTimeToString ctdbDateTimeUnpack
ctdbDayOfWeek ctdbFloatToBigInt ctdbFloatToCurrency ctdbFloatToMoney ctdbFloatToNumber ctdbGetDay ctdbGetDefDateType ctdbGetDefFloatFormat ctdbGetDefTimeType ctdbGetHour ctdbGetMinute ctdbGetMonth ctdbGetSecond ctdbGetYear ctdbIsLeapYear ctdbIsNumberZero ctdbLongToBigInt ctdbLongToCurrency ctdbLongToMoney ctdbLongToNumber ctdbMoneyAbs ctdbMoneyAdd ctdbMoneyCmp ctdbMoneyDiv ctdbMoneyMul ctdbMoneySub ctdbMoneyToCurrency ctdbMoneyToFloat ctdbMoneyToLong ctdbMoneyToNumber
ctdbNumberAdd ctdbNumberCmp ctdbNumberCopy ctdbNumberDiv ctdbNumberGetDecimal ctdbNumberMul ctdbNumberNegate ctdbNumberRound ctdbNumberSub ctdbNumberToBigInt ctdbNumberToCurrency ctdbNumberToFloat ctdbNumberToLong ctdbNumberToMoney ctdbNumberToString ctdbNumberZero ctdbSetDefDateType ctdbSetDefFloatFormat ctdbSetDefTimeType ctdbStringToBigInt ctdbStringToCurrency ctdbStringToDate ctdbStringToDateTime ctdbStringToMoney ctdbStringToNumber ctdbStringToTime ctdbTimePack ctdbTimeToString ctdbTimeUnpack
www.faircom.com
All Rights Reserved
201
Data Structures
ctdbGetFirstActiveDatabase ctdbGetFirstActiveTable ctdbGetIndex ctdbGetIndexByName ctdbGetIndexByUID ctdbGetIndexDuplicateFlag ctdbGetIndexEmptyChar ctdbGetIndexExtension ctdbGetIndexHandle ctdbGetIndexKeyLength ctdbGetIndexKeyType ctdbGetIndexName ctdbGetIndexNbr ctdbGetIndexNbrByName ctdbGetIndexNullFlag ctdbGetIndexSegmentCount ctdbGetIndexTemporaryFlag ctdbGetIndexUID ctdbGetLogonOnly ctdbGetNextActiveDatabase ctdbGetNextActiveTable ctdbGetRecord ctdbGetRecordBuffer ctdbGetRecordCount ctdbGetRecordHandle ctdbGetRecordLength ctdbGetRecordNbr ctdbGetRecordPos ctdbGetRecordSize ctdbGetSegment ctdbGetSegmentField ctdbInsSegmentByNbr ctdbInsSegmentEx ctdbIsActiveDatabase ctdbIsActiveSession ctdbIsActiveTable ctdbIsEditedRecord ctdbIsExtSegment ctdbIsFieldNumeric ctdbIsNewRecord ctdbIsNullField ctdbIsVariableField ctdbLogon ctdbLogout ctdbMoveField ctdbNextDatabase ctdbNextTable ctdbSetDefaultIndex ctdbSetDefaultIndexByName ctdbSetEditedRecord ctdbSetFieldAsBigint ctdbSetFieldAsBinary ctdbSetFieldAsBlob ctdbSetFieldAsBool ctdbSetFieldAsCurrency ctdbSetFieldAsDate ctdbSetFieldAsDateTime ctdbSetFieldAsFloat ctdbSetFieldAsMoney ctdbSetFieldAsNumber ctdbSetFieldAsSigned ctdbSetFieldAsString
FairCom Corporation
202
ctdbGetSegmentFieldName ctdbGetSegmentHandle ctdbGetSegmentMode ctdbGetSegmentNbr ctdbGetServerName ctdbGetSessionHandle ctdbGetSessionParams ctdbGetSessionPath ctdbGetSessionType ctdbGetTable ctdbGetTableCount ctdbGetTableCreateMode ctdbGetTableDefaultDataExtentSize ctdbGetTableDefaultIndexExtentSize ctdbGetTableExtension ctdbGetTableFieldCount ctdbGetTableGroupid ctdbGetTableHandle ctdbGetTableIndexCount ctdbGetTableName ctdbGetTableNbr ctdbGetTableOpenMode ctdbGetTablePassword ctdbGetTablePath ctdbGetTablePermission ctdbGetTableUID ctdbGetUserLogonName ctdbGetUserPassword ctdbGetUserTag ctdbHasNullFieldSupport ctdbInsField ctdbInsFieldByName
ctdbSetFieldAsTime ctdbSetFieldAsUnsigned ctdbSetFieldLength ctdbSetFieldName ctdbSetFieldNullFlag ctdbSetFieldPrecision ctdbSetFieldProperties ctdbSetFieldScale ctdbSetFieldType ctdbSetIndexDuplicateFlag ctdbSetIndexEmptyChar ctdbSetIndexExtension ctdbSetIndexKeyType ctdbSetIndexName ctdbSetIndexNullFlag ctdbSetIndexTemporaryFlag ctdbSetLogonOnly ctdbSetNewRecord ctdbSetRecordOffset ctdbSetRecordPos ctdbSetSegmentMode ctdbSetSessionParams ctdbSetSessionPath ctdbSetSessionType ctdbSetTableDefaultDataExtentSize ctdbSetTableDefaultIndexExtentSize ctdbSetTableExtension ctdbSetTableGroupid ctdbSetTablePassword ctdbSetTablePath ctdbSetTablePermission ctdbSetUserTag
www.faircom.com
All Rights Reserved
203
ctdbInsSegment ctdbInsSegmentByName
ctdbUpdateCreateMode
Utility
ctdbClearError ctdbClearField ctdbClearRecord ctdbCurrentDate ctdbCurrentDateTime ctdbCurrentTime ctdbGetError ctdbResetAll ctdbResetRecord ctdbSetError ctdbTimeCheck ctdbResetRecord
FairCom Corporation
204
ctdbAbort
Abort a transaction.
Declaration
CTDBRET ctdbAbort(CTHANDLE Handle)
Description
ctdbAbort() aborts a transaction initiated with ctdbBegin(), releasing all session-wide locks. Handle [in] the session handle.
Returns
ctdbAbort returns CTDBRET_OK if successful, or the c-tree Plus error code on failure.
Example
ctdbBegin(pSession); if (ctdbCreateTable(tHandle1,table1,CTCREATE_NORMAL) == CTDBRET_OK) ctdbCommit(pSession); else ctdbAbort(pSession);
See also
ctdbBegin(), ctdbCommit(), ctdbIsTransActive(), ctdbLock(), ctdbSetKeepLock()
www.faircom.com
All Rights Reserved
205
ctdbAddDatabase
Add an existing database to a session
Declaration
CTDBRET ctdbAddDatabase(CTHANDLE Handle, pTEXT Name, pTEXT Path)
Description
ctdbAddDatabase() adds an existing database to the present session. Handle [in] the session handle. Name [in] the database name. Path [in] the database path.
Returns
ctdbAddDatabase() returns CTDBRET_OK on success, or a c-treeDB C API error code on failure.
Example
eRet = ctdbAddDatabase(hSession, my_database, ); if (eRet != CTDBRET_OK) { if (eRet == CTDBRET_NOTFOUND) { printf("\n\nTable not found at the path.\n"); } else { printf("ctdbAddDatabase returned error code %d\n", eRet); } }
See also
Nothing in see also!
FairCom Corporation
206
ctdbAddField
Add a new field to table
Declaration
CTHANDLE ctdbAddField(CTHANDLE Handle, pTEXT FieldName, CTDBTYPE FieldType, VRLEN FieldLength)
Description
ctdbAddField() adds a new field to a table. Use ctdbInsField() and ctdbInsFieldByName() to insert a field in a table in a specified position. Use ctdbDelField() and ctdbDelFieldByName() to delete fields from the table. ctdbAddField() does the field handle allocation. After the segments, indices, and fields have been defined, the table can be created or altered with ctdbCreateTabl()e or ctdbAlterTable(). pTable [in] the table handle. FieldName [in] the field name. FieldType [in] the field type. Available types are described in "c-treeDB definitions". FieldLength [in] the field length.
Returns
ctdbAddField returns a field handle on success, or NULL on failure.
Example
pMyField1 = ctdbAddField(pMyTable, "Name", CT_FSTRING, 32); pMyField2 = ctdbAddField(pMyTable, "Balance", CT_SFLOAT, 4); pMyIndex = ctdbAddIndex(pMyTable, "iName", CTINDEX_FIXED, NO, NO); pMyIseg = ctdbAddSegment(pMyIndex, pMyField1, 2); RetVal = ctdbCreateTable(pMyTable,"Table1",CTCREATE_NORMAL);
See also
ctdbAllocTable(), ctdbInsField(), ctdbInsFieldByName(), ctdbDelField(), ctdbDelFieldByName(), ctdbMoveField(), ctdbCreateTable(), ctdbAlterTable()
www.faircom.com
All Rights Reserved
207
ctdbAddIndex
Add a new index to a table.
Declaration
CTHANDLE ctdbAddIndex(CTHANDLE Handle, pTEXT name, CTDBKEY key_type, CTBOOL AllowDuplicates, CTBOOL NullFlag)
Description
ctdbAddIndex() adds a new index to a table. Use ctdbDelIndex() to delete indices in a table. Use ctdbGetIndexKeyType() to retrieve the key type of an index. ctdbAddIndex() does the index allocation. After the segments, indices, and fields have been defined, the table can be created or altered. Handle [in] the table handle. name [in] the index name. key_type [in] the key type. Allowed key types are listed in "c-treeDB definitions".. AllowDuplicates [in] the indication if the index allow duplicate keys (YES or NO are the valid values). NullFlag [in] the indication if the index allow null keys (YES or NO are the valid values).
Returns
ctdbAddIndex() returns the index handle on success, or NULL on failure.
Example
pMyField1 = ctdbAddField(pMyTable, "Name" , CT_FSTRING,32); pMyField2 = ctdbAddField(pMyTable, "Balance", CT_SFLOAT, 4); pMyIndex = ctdbAddIndex(pMyTable, iName, CTINDEX_FIXED,NO,NO); pMyIseg = ctdbAddSegment(pMyIndex, pMyField1, 2); RetVal = ctdbCreateTable(pMyTable,"Table1",CTCREATE_NORMAL);
See also
ctdbAllocTable(), ctdbDelIndex(), ctdbGetIndexKeyType(), ctdbCreateTable(), ctdbAlterTable(), ctdbSetIndexName()
FairCom Corporation
208
ctdbAddResource
Add a new resource to a table.
DECLARATION
CTDBRET ctdbDECL ctdbAddResource(CTHANDLE resource, pVOID data, VRLEN size);
DESCRIPTION
ctdbAddResource() add a new resource to a table. When adding a Resource to a table, a special variable-length record is written to the table, containing the information from the Resource Data Block. This is done even if a data file uses fixed-length records. Every Resource is identified by a unique combination of a Resource Type and a Resource Number. The Resource Number can optionally be assigned by c-tree Plus during the call to ctdbAddResource(). In addition, each Resource can be identified by a Resource Name. The Resource Name is not guaranteed to be unique. 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 CTDB_ASSIGN_RESOURCE_NUMBER (0xffffffff), c-tree Plus assigns this Resource the next available Resource Number for this Resource Type in the specified data file. The assigned number can be retrieved by calling ctdbGetResourceNumber() before the resource handle is released. The Resource Name is optional. Names starting with FC! or RD!, are reserved for FairCom use. Resource is a handle allocated by ctdbAllocResource(). data 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. size indicate the number of bytes occupied by data.
RETURN
ctdbAddResource() returns CTDBRET_OK on success.
EXAMPLE
/* return CTDB_ASSIGN_RESOURCE_NUMBER on error */ ULONG AddMyResource(CTHANDLE Handle, ULONG type, pTEXT name, pVOID data, VRLEN size) { ULONG number = CTDB_ASSIGN_RESOURCE_NUMBER; CTHANDLE hRes = ctdbAllocResource(Handle, type, number, name); CTDBRET eRet; /* check if resource handle was allocated */ if (!hRes) { printf("ctdbAllocResource failed with error %d\n", ctdbGetError(Handle)); return number; } /* Add the resource */ if ((eRet = ctdbAddResource(hRes, data, size)) != CTDBRET_OK) { printf("ctdbAddResource failed with error %d\n", eRet); ctdbFreeResource(hRes); return eRet; } /* retrieve the assigned resource number */ number = ctdbGetResourceNumber(hRes); /* release the resource handle */ ctdbFreeResource(hRes); return number; }
www.faircom.com
All Rights Reserved
209
SEE ALSO
ctdbAllocResource, ctdbFreeResource, ctdbDeleteResource, ctdbUpdateResource, ctdbFirstResource, ctdbNextResource, ctdbFindResource, ctdbFindResourceByName, ctdbGetResourceType, ctdbSetResourceType, ctdbGetResourceNumber, ctdbSetResourceNumber, ctdbGetResourceName, ctdbSetResourceName, ctdbGetResourceDataLength, ctdbGetResourceData, ctdbSetResourceData, ctdbIsResourceLocked, ctdbUnlockResource
FairCom Corporation
210
ctdbAddSegment
Add a new index segment
Declaration
CTHANDLE ctdbAddSegment(CTHANDLE Handle, CTHANDLE FieldHandle, CTSEG_MODE SegMode)
Description
ctdbAddSegment() adds a new index segment, given the index handle. The operation of adding a segment links the index with the field in the table. In order to add a segment with this function, the segment must be defined based on individual full fields, using what is known as record schema. See the c-tree Plus documentation for further information on record schemas. Use ctdbAddSegmentByName() or ctdbAddSegmentByNbr() to add a segment given the index number. Use ctdbAddSegmentEx() to add a new extended index segment, that may use just part of the field as the index segment. Use ctdbInsSegment() to insert a segment in a specified position. Use ctdbDelSegment() to delete a segment from an index. ctdbAddSegment() does the segment allocation. After the segments, indices, and fields have been defined, the table can be created or altered with ctdbCreateTable() or ctdbAlterTable(). Handle [in] the index handle. FieldHandle [in] the index segment field handle. SegMode [in] the Index segment mode. The valid values for the segment modes are: CTSEG_SCHSEG, CTSEG_USCHSEG, CTSEG_VSCHSEG, CTSEG_UVSCHSEG, CTSEG_SCHSRL, described in "c-treeDB definitions".. If used with a different segment mode, this call will return error 4047, meaning invalid segment mode. ctdbAddSegmentEx() accepts any segment mode.
Returns
ctdbAddSegment returns the segment handle on success, or NULL on failure.
Example
pMyField1 = ctdbAddField(pMyTable, "Name", CT_FSTRING,32); pMyField2 = ctdbAddField(pMyTable, "Balance", CT_SFLOAT, 4); pMyIndex = ctdbAddIndex(pMyTable, "iName", CTINDEX_FIXED,NO,NO); pMyIseg = ctdbAddSegment(pMyIndex, pMyField1, CTSEG_USCHSEG); RetVal = ctdbCreateTable(pMyTable,"Table1",CTCREATE_NORMAL);
See also
ctdbAllocSegment(), ctdbAddSegmentByName(), ctdbAddSegmentByNbr(), ctdbAddSegmentEx(), ctdbInsSegment(), ctdbCreateTable(), ctdbAlterTable()
www.faircom.com
All Rights Reserved
211
ctdbAddSegmentByName
Add a new index segment, given the field name.
Declaration
CTHANDLE ctdbAddSegmentByName(CTHANDLE Handle, NINT IndexNbr, pTEXT FieldName, CTSEG_MODE SegMode)
Description
ctdbAddSegmentByName() adds a new index segment, given the field name and the index number. The operation of adding a segment links the index with the field in the table. In order to add a segment with this function, the segment must be defined based on individual full fields, using what is known as record schema. See the c-tree Plus documentation for further information on record schemas. Use ctdbAddSegmentByNbr() to add a new index segment given the field and index number. Use ctdbAddSegment() to add a new index segment given the index handle. Use ctdbAddSegmentEx() to add a new extended index segment. ctdbAddSegmentByName() does the segment allocation. After the segments, indices, and fields have been defined, the table can be created or altered with ctdbCreateTable() or ctdbAlterTable(). Handle [in] the table handle. IndexNbr [in] the index number. The first index is number 0. FieldName [in] the field name. SegMode [in] the Index segment mode. The valid values for the segment modes are: CTSEG_SCHSEG, CTSEG_USCHSEG, CTSEG_VSCHSEG, CTSEG_UVSCHSEG, CTSEG_SCHSRL, described in "c-treeDB definitions".. If used with a different segment mode, this call will return error 4047, meaning invalid segment mode. ctdbAddSegmentEx() accepts any segment mode.
Returns
ctdbAddSegmentByName() returns the segment handle on success, or NULL on failure
Example
ctdbAddField(pMyTable, "Name", CT_FSTRING, 32); ctdbAddField(pMyTable, "Balance", CT_SFLOAT, 4); ctdbAddIndex(pMyTable, "iName", CTINDEX_FIXED, NO, NO); ctdbAddSegmentByName(pMyTable, 0, "Name", CTSEG_USCHSEG); RetVal = ctdbCreateTable(pMyTable, "Table1", CTCREATE_NORMAL);
See also
ctdbAddSegmentEx(), ctdbAddSegmentByNbr(), ctdbAddSegment()
FairCom Corporation
212
ctdbAddSegmentByNbr
Add a new index segment, given the field and index numbers.
Declaration
CTHANDLE ctdbAddSegmentByNbr(CTHANDLE Handle, NINT IndexNbr, NINT FieldNbr, CTSEG_MODE SegMode)
Description
ctdbAddSegmentByNbr() adds a new index segment, given the index and field numbers. The operation of adding a segment links the index with the field in the table. In order to add a segment with this function, the segment must be defined based on individual full fields, using what is known as record schema. See the c-tree Plus documentation for further information on record schemas. Use ctdbAddSegmentByName() to add a new index segment given its name. Use ctdbAddSegment() to add a new index segment given the index handle. Use ctdbAddSegmentEx() to add a new extended index segment. ctdbAddSegmentByNbr() does the segment allocation. After the segments, indices, and fields have been defined, the table can be created or altered with ctdbCreateTable() or ctdbAlterTable(). Handle [in] the table handle. IndexNbr [in] the index number. The first index is number 0. FieldNbr [in] the field number. The first field is number 0. SegMode [in] the Index segment mode. The valid values for the segment modes are: CTSEG_SCHSEG, CTSEG_USCHSEG, CTSEG_VSCHSEG, CTSEG_UVSCHSEG, CTSEG_SCHSRL, described in "c-treeDB definitions".. If used with a different segment mode, this call returns error 4047, invalid segment mode. ctdbAddSegmentEx() accepts any segment mode.
Returns
ctdbAddSegmentByNbr returns the segment handle on success, or NULL on failure
Example
ctdbAddField(pMyTable, "Name", CT_FSTRING, 32); ctdbAddField(pMyTable, "Balance", CT_SFLOAT, 4); ctdbAddIndex(pMyTable, "iName", CTINDEX_FIXED, NO, NO); ctdbAddSegmentByNbr(pMyTable, 0, 0, CTSEG_USCHSEG); RetVal = ctdbCreateTable(pMyTable, "Table1", CTCREATE_NORMAL);
See also
ctdbAddSegment(), ctdbAddSegmentEx(), ctdbAddSegmentByName()
www.faircom.com
All Rights Reserved
213
ctdbAddSegmentEx
Add a new extended index segment
Declaration
CTHANDLE ctdbAddSegmentEx(CTHANDLE Handle, NINT offset, NINT length, CTSEG_MODE SegMode)
Description
ctdbAddSegmentEx() adds a new extended index segment given the index handle and the segment offset. A segment is extended if it is based on the segment offset. The operation of adding a segment links the index with the field in the table. To add a segment with this function, the segment may be defined based on partial individual fields, using offsets to indicate the segment beginning and extension. Note: The offset should account for the fields that are created automatically (unless disabled): $DELFLD$ (4 bytes to account for a deleted record), $NULFLD$ (for each user defined field, c-treeDB uses 1 bit to indicate if a null value in the field is valid - the size will be adjusted to the next byte), and $ROWID$ (8 bytes to account for the automatic auto-increment record - see the discussion on ROWID in "Hidden fields"). This variation makes it difficult to predict the correct offset of each user defined offset. FairCom strongly recommends the use of the regular functions (ctdbAddSegment(), ctdbAddSegmentByName() or ctdbAddSegmentByNbr()). The use of the extended segments may even prevent the use of advanced c-treeDB functions like ctdbAlterTable(). If, for any reason, it is mandatory to use this function, try to follow the example below. ctdbAddSegmentEx() does the segment allocation. After the segments, indices, and fields have been defined, the table can be created or altered with ctdbCreateTable() or ctdbAlterTable(). Use ctdbIsExtSegment() to verify if the segment mode is one of the extended modes. Handle [in] the index handle. offset [in] the absolute byte offset. length [in] the segment length in bytes. SegMode [in] the Index segment mode. The valid values for the segment modes are listed in "c-treeDB definitions".. Notice that ctdbAddSegmentEx() does work with Absolute byte offset segments.
Returns
ctdbAddSegmentEx() returns the segment handle on success, or NULL on failure
Example
pMyField1 = ctdbAddField(pMyTable, "Name", CT_FSTRING,32); pMyField2 = ctdbAddField(pMyTable, "Balance", CT_SFLOAT, 4); ctdbCreateTable(pMyTable,"Table1",CTCREATE_NORMAL); ctdbOpenTable(pMyTable1, "MyTable3", CTOPEN_EXCLUSIVE); pMyRec1 = ctdbAllocRecord(pMyTable1); ctdbFirstRecord(pMyRec1); fld_offset = ctdbGetFieldOffset(pMyRec1, 0); pMyIndex = ctdbAddIndex(pMyTable1, "MyTable2", 0, 1, 1); pMyIseg = ctdbAddSegmentEx(pMyIndex, fld_offset, 32, CTSEG_UREGSEG); ctdbAlterTable(pMyTable1, 0);
FairCom Corporation
214
See also
ctdbAllocSegment(), ctdbAddSegment(), ctdbInsSegmentEx(), ctdbAddSegmentByName(), ctdbAddSegmentByNbr(), ctdbGetFieldOffset(), ctdbIsExtSegment()
www.faircom.com
All Rights Reserved
215
ctdbAddTable
Add an existing table to a database.
Declaration
CTDBRET ctdbAddTable(CTHANDLE Handle, pTEXT Name, pTEXT Path)
Description
ctdbAddTable() adds an existing table to a database. Handle [in] the database handle. Name [in] the name of the table be added, including the file extension, usually .dat. Path [in] the table path. A mirrored table can be added to a c-treeDB database dictionary by calling ctdbAddTable() function and specifying the table name and path using the appropriate mirror naming convention:
if (ctdbAddTable(hDatabase, "customer|mirror", "primary_path|mirror_path")) printf("ctdbAddTable failed\n");
If a table is created originally without mirroring, it can subsequently be mirrored as follows: 1. Copy the original table to the mirror location. 2. Change the ctdbOpenTable() function to use the mirror naming convention.
Returns
ctdbAddTable() returns CTDBRET_OK on success, or the c-tree Plus error code on failure.
Example
CTHANDLE hTable; eRet = ctdbAddTable(hTable, "custmast", "");
See also
ctdbCreateTable(), ctdbAllocTable(), ctdbDeleteTable(), ctdbDropTable()
FairCom Corporation
216
ctdbAllocDatabase
Allocate and initiate a new database handle.
Declaration
CTHANDLE ctdbAllocDatabase(CTHANDLE Handle)
Description
ctdbAllocDatabase() allocates memory and initialize a new database handle. Before any operation on a database can take place, the application must allocate a database handle. Handle [in] the session handle. The database handle is released by calling ctdbFreeDatabase(). Do not release the database handle by calling the C runtime library function free().
Returns
ctdbAllocDatabase returns the database handle on success or NULL on failure.
Example
CTHANDLE hDatabase = ctdbAllocDatabase(hSession);
See also
ctdbFreeDatabase(), ctdbAllocSession(), ctdbAllocTable()
www.faircom.com
All Rights Reserved
217
ctdbAllocRecord
Allocate a new c-treeDB C API record handle.
Declaration
CTHANDLE ctdbAllocRecord(CTHANDLE Handle)
Description
ctdbAllocRecord() allocates memory and initialize a new record handle. Before any operation on records can take place, the application must allocate a record handle. Handle [in] the table handle. The record handle is released by calling ctdbFreeRecord(). Do not release the record handle by calling the C runtime library function free.
Returns
ctdbAllocRecord() returns the new allocated handle on success, or NULL on failure.
See also
ctdbAllocTable(), ctdbFreeRecord(), ctdbGetRecordHandle()
FairCom Corporation
218
ctdbAllocResource
Allocates a new resource handle.
DECLARATION
CTHANDLE ctdbDECL ctdbAllocResource(CTHANDLE Handle, ULONG type, ULONG number, pTEXT name);
DESCRIPTION
Allocate a new resource handle. Before any operations can be performed on resources, you are required to allocate a resource handle. Resource handles are opaque handles whose contents are not available to the developer. You must use the set of functions provided by c-treeDB to set and get properties and to perform operations. Handle is a c-treeDB table handle. type is the resource type. If the resource type is unknown you may set this parameter to zero. number is the resource number. If the resource number is unknown you may set this parameter to zero. name is the resource name. If you do not know this value in advance, you can set this parameter with a NULL or empty string ().
RETURN
ctdbAllocResource() returns the resource handle on success. Returns NULL if ctdbAllocResource() fails to allocate handle, in which case you should call ctdbGetError() passing the table Handle to obtain the error code.
EXAMPLE
CTDBRET DisplayAllResources(CTHANDLE hTable) { CTDBRET eRet; CTHANDLE hRes = ctdbAllocResource(hTable, 0, 0, NULL); /* check if resource was allocated */ if (!hRes) return ctdbGetError(hTable); /* get the first resource */ /* note that no resource locks are acquired since we are not changing the resources */ if ((eRet = ctdbFirstResource(hRes, false)) != CTDBRET_OK) { ctdbFreeResource(hRes); return eRet; } /* get the other resources */ do { /* display resource type, number and name */ printf("Resource type: %u, number: %u", ctdbGetResourceType(hRes), ctdbGetResourceNumber(hRes)); if (ctdbGetResourceName(hRes) != NULL) printf(", name: \"\"\n", ctdbGetResourceName(hRes)); else printf(", name: NULL"\n"); } while ((eRet = ctdbNextResource(hRes, false)) != CTDBRET_OK); ctdbFreeResource(hRes); return eRet; }
www.faircom.com
All Rights Reserved
219
SEE ALSO
ctdbFreeResource(), ctdbAddResource(), ctdbDeleteResource(), ctdbUpdateResource(), ctdbFirstResource(), ctdbNextResource(), ctdbFindResource(), ctdbFindResourceByName(), ctdbGetResourceType(), ctdbSetResourceType(), ctdbGetResourceNumber(), ctdbSetResourceNumber(), ctdbGetResourceName(), ctdbSetResourceName(), ctdbGetResourceDataLength(), ctdbGetResourceData(), ctdbSetResourceData(), ctdbIsResourceLocked(), ctdbUnlockResource()
FairCom Corporation
220
ctdbAllocSession
Allocate a new session handle and set the default attributes.
Declaration
CTHANDLE ctdbAllocSession(CTSESSION_TYPE SessionType)
Description
ctdbAllocSession() allocates memory and initialize a new session handle, setting the default attributes. Before any operation on session can take place, the application must allocate a session handle. This function takes one parameter, the session type, and returns the new session handle, or NULL if there is not enough memory to allocate the new handle. SessionType [in] the session type. There are three different session types: CTSESSION_CTREE: allocate a new session for logon only. No session or database dictionary files will be used. No database functions can be used with this session mode. Use the session handle to allocate table handles. CTSESSION_CTDB: allocate a new session using c-treeDB session and database dictionaries. CTSESSION_SQL: allocate a new session for c-treeSQL processing. This session type is not implemented yet and is reserved for future use. The session handle is released by calling ctdbFreeSession(). Do not release the session handle by calling the C runtime library function free().
Returns
Return the session handle on success or NULL on failure.
Example
CTSESSION_TYPE ctdbsess=CTSESSION_CTDB; CTHANDLE handle = ctdbAllocSession(ctdbsess); // c-treeDB session
See also
ctdbAllocDataBase(), ctdbFreeSession()
www.faircom.com
All Rights Reserved
221
ctdbAllocTable
Allocate a new table handle.
Declaration
CTHANDLE ctdbAllocTable(CTHANDLE Handle)
Description
ctdbAllocTable() allocates memory and initializes a new table handle. Before any operation on the table can take place, the application must allocate a table handle. Handle [in] the database handle, previously allocated by calling ctdbAllocDatabase(). The database handle is released by calling ctdbFreeTable(). Do not release the database handle by calling the C runtime library function free().
Returns
ctdbAllocTable() returns the table handle on success or NULL on failure.
Example
CTSESSION_TYPE ctdbsess=CTSESSION_CTDB; CTHANDLE hSession = ctdbAllocSession(ctdbsess); CTHANDLE hDatabase = ctdbAllocDatabase(hSession); CTHANDLE hTable = ctdbAllocTable(hDatabase);
See also
ctdbAllocDatabase(), ctdbFreeTable()
FairCom Corporation
222
ctdbAlterTable
Rebuild existing table based on field, index and segment changes.
Declaration
CTDBRET ctdbAlterTable(CTHANDLE Handle, NINT Action)
Description
ctdbAlterTable() rebuilds an existing table based on field, index and segment changes. Handle [in] the table handle. Action [in] the alter table action. One or more of the following actions can be selected: CTDB_ALTER_NORMAL: Check for changes before altering CTDB_ALTER_INDEX: Force rebuild of all indexes CTDB_ALTER_FULL: Force full table rebuild. Unix Note: Due to the non-exclusive nature of Unix, this function can be successfully executed on a file that was opened by several other applications in shared mode. However, although the function succeeds, it may cause havoc for the other applications. This can be prevented by enforcing exclusivity with locks, however, this is not the default mode. Mirrored Files: The c-treeDB alter table function will not operate on mirrored tables. If ctdbAlterTable() is called for a mirrored table, nothing is done and it returns error CTDBRET_NOTSUPPORTED.
Returns
ctdbAlterTable() returns CTDBRET_OK if successful, or the c-tree Plus error code on failure.
See also
ctdbCreateTable()
www.faircom.com
All Rights Reserved
223
ctdbAttachSession
Attaches an already initialized c-tree session to a c-treeDB session handle.
DECLARATION
CTDBRET ctdbDECL ctdbAttachSession(CTHANDLE Handle, pVOID source, CTATTACH_MODE mode, CTBOOL isTransactionActive);
DESCRIPTION
ctdbAttachSession() attaches an already initialized c-tree ISAM or low-level session to a c-treeDB session handle. Attached sessions have no information about the server, user name or user password, and these values are set to NULL. Handle is a Session handle allocated by ctdbAllocSession(), isTransactionActive should indicate if a transaction is active or not. mode is one of the following:
mode Parameter Description Attach to a c-treeDB session whose session handle is pointed by parameter source. Attach to a c-tree Plus session whose instance id string is pointed by parameter source. Attach to the current c-tree instance. Contents of parameter source is ignored, as the c-tree instance id is obtained by calling WCHCTREE() function.
RETURN
Value 0 Symbolic Constant NO_ERROR Explanation No error occurred.
See Appendix A for a complete listing of valid c-tree Plus error values.
EXAMPLE
/* logon to c-tree using ISAM function */ INTISAMX(10, 32, 32, 10, (USERPRF_NTKEY | USERPRF_CLRCHK)); /* attach session to server handle */ if (ctdbAttachSession(hSession, NO) != CTDBRET_OK) printf("ctdbAttachSession failed\n"); /* ... do something useful ... */ /* detach from session */ if (ctdbDetachSession(hSession) != CTDBRET_OK) printf("ctdbDetachSession failed\n"); /* perform an ISAM logout */ CLISAM();
SEE ALSO
ctdbDetachSession()
FairCom Corporation
224
ctdbAttachTable
Attaches a c-tree Plus ISAM datno object to a c-treeDB table handle.
DECLARATION
CTDBRET ctdbAttachTable(CTHANDLE Handle, NINT datno);
DESCRIPTION
ctdbAttachTable() attaches a c-tree Plus ISAM datno object to a c-treeDB table handle. This function is useful if you have opened a data and index file using one of c- trees ISAM open functions and need to attach it to a table handle to use some of the advanced c-treeDB features such as alter table or the record handler. Handle is a table handle and datno is data file number opened with one of the c-tree ISAM open functions.
RETURN
Value 0 Symbolic Constant NO_ERROR Explanation No error occurred.
See Appendix A for a complete listing of valid c-tree Plus error values.
EXAMPLE
CTHANDLE hSession = ctdbAllocSession(CTSESSION_CTREE); CTHANDLE hTable = ctdbAllocTable(hSession); CTHANDLE hRecord = ctdbAllocRecord(hTable); NINT datno, count = 0; /* logon to c-tree */ ctdbLogon(hSession, SERVER, USER, PASSWD); /* open the file using c-tree ISAM */ datno = (NINT)OPNRFILX((COUNT) -1, "test309.dat", (COUNT)0, NULL); /* attach to table */ ctdbAttachTable(hTable, datno); /* read the records */ if (ctdbFirstRecord(hRecord) == CTDBRET_OK) do { count++; } while (ctdbNextRecord(hRecord) == CTDBRET_OK); /* cleanup */ ctdbDetachtable(hTable); ctdbFreeRecord(hRecord); ctdbFreeTable(hTable); ctdbLogout(hSession); ctdbFreeSession(hSession);
SEE ALSO
ctdbAttachXtd, ctdbDetach
www.faircom.com
All Rights Reserved
225
ctdbAttachTableXtd
Attaches a c-tree Plus ISAM datno object to a CTDB table handle allowing a DODA and IFIL to be specified.
DECLARATION
CTDBRET ctdbAttachTableXtd(CTHANDLE Handle, NINT datno, NINT nbrfields, pDATOBJ dodaptr, pIFIL ifilptr)
DESCRIPTION
ctdbAttachTableXtd() attaches a c-tree Plus ISAM datno object to a c-treeDB table handle. This function is useful if you have opened a data and index file using one of c-trees ISAM open functions and need to attach it to a table handle to use some of the advanced c-treeDB features such as alter table or the record handler. This extended version allows the user to specify the DODA and IFIL for the table, enabling tables without DODA and/or IFIL to be attached to c-treeDB. Handle is a table handle and datno is the data file number. nbrfields is the number of fields described by dodaptr. If nbrfields is zero, it is assumed that the DODA is not supplied and a DODA resource will be read from the table itself. dodaptr pointer to DODA entries for each field in table. If dodaptr is NULL, it is assumed that the DODA is not supplied and a DODA resource will be read from the table itself. ifilptr is a pointer to IFIL structure describing indexes of table. If ifilptr is NULL it is assumed that an IFIL is not supplied and an IFIL resource will be read from the table itself.
RETURN
Value 0 Symbolic Constant NO_ERROR Explanation No error occurred.
See Appendix A for a complete listing of valid c-tree Plus error values.
EXAMPLE
/* DODA */ static DATOBJ doda[] = { {"f1", (pTEXT)0, CT_INT4, 4}, {"f2", (pTEXT)4, CT_FSTRING, 10} }; /* IFIL */ static ISEG iseg = {0, 4, 12}; static IIDX iidx = {4, 0, 0, 0, 0, 1, &iseg, "i311x1", NULL, NULL, NULL}; static IFIL ifil = {"test310", -1, 14, 0, 0, 1, 0, 0, &iidx, "f1", "f2", 0}; CTHANDLE hSession = ctdbAllocSession(CTSESSION_CTREE); CTHANDLE hTable = ctdbAllocTable(hSession); CTHANDLE hRecord = ctdbAllocRecord(hTable); NINT datno, count = 0; /* logon to c-tree */ ctdbLogon(hSession, SERVER, USER, PASSWD); /* open the file using c-tree ISAM */ datno = (NINT)OPNRFILX((COUNT) -1, "test309.dat", (COUNT)0, NULL); /* attach to table */ ctdbAttachTableXtd(hTable, datno, doda, &ifil); /* read the records */ if (ctdbFirstRecord(hRecord) == CTDBRET_OK) do
FairCom Corporation
226
{ count++; } while (ctdbNextRecord(hRecord) == CTDBRET_OK); /* cleanup */ ctdbDetachtable(hTable); ctdbFreeRecord(hRecord); ctdbFreeTable(hTable); ctdbLogout(hSession); ctdbFreeSession(hSession);
SEE ALSO
ctdbAttachTable(), ctdbDetachTable()
www.faircom.com
All Rights Reserved
227
ctdbBatchLoaded
Retrieves the number of batch records loaded into batch buffer.
DECLARATION
LONG ctdbDECL ctdbBatchLoaded(CTHANDLE Handle);
DESCRIPTION
ctdbBatchLoaded() retrieves the number of batch records loaded into batch buffer for CTBATCH_GET, CTBATCH_RANGE or CTBATCH_PHYS operations. This is the number of records that are ready to be retrieved by ctdbNextBatch() function. Handle must be a record handle associated with an opened table.
RETURNS
ctdbBatchLoaded() returns the number of records ready for retrieval or a negative value indicating an error. In case of an error, use the ctdbGetError() function to retrieve the error code.
EXAMPLE
/* set the partial target key */ ctdbClearRecord(hRecord); ctdbSetFieldAsSigned(hRecord, 0, Invoice); /* set the batch operation */ if (ctdbSetBatch(hRecord, CTBATCH_GET, sizeof(Invoice), 0) != CTDBRET_OK) printf("ctdbSetBatch failed with error %d\n", ctdbGetError(hRecord)); /* show how many records are ready */ printf("%d records are ready for retrieval\n", ctdbBatchLoaded(hRecord));
SEE ALSO
ctdbBatchLocked(), ctdbBatchMode(), ctdbBatchTotal(), ctdbEndBatch(), ctdbInsertBatch(), ctdbIsBatchActive(), ctdbNextBatch(), ctdbSetBatch()
FairCom Corporation
228
ctdbBatchLocked
Retrieves the number of locked batch records.
DECLARATION
LONG ctdbDECL ctdbBatchLocked(CTHANDLE Handle);
DESCRIPTION
Retrieves the number of records locked during a CTBATCH_GET, CTBATH_RANGE or CTBATCH_PHYS operation. If CTBATCH_LOCK_READ or CTBATCH_LOCK_WRITE are specified in the batch mode, ctdbBatchLocked() return the total number of records locked. If CTBATCH_LOCK_ONE is specified, or if no CTBATCH_LOCK_READ or CTBATCH_LOCK_WRITE modes are not specified, ctdbBatchLocked() return zero. Handle must be a record handle associated with an opened table.
RETURNS
ctdbBatchLocked() returns the number of locked records. In case of an error, ctdbBatchLocked() returns a negative value and you may use ctdbGetError() function to retrieve the error code
EXAMPLE
/* set the partial target key */ ctdbClearRecord(hRecord); ctdbSetFieldAsSigned(hRecord, 0, Invoice); /* set the batch operation */ if (ctdbSetBatch(hRecord, (CTBATCH_GET | CTBATCH_LOK_READ), sizeof(Invoice), 0) != CTDBRET_OK) printf("ctdbSetBatch failed with error %d\n", ctdbGetError(hRecord)); /* show how many records are locked */ printf("%d records are locked\n", ctdbBatchLoaded(hRecord));
SEE ALSO
ctdbBatchLoaded(), ctdbBatchMode(), ctdbBatchTotal(), ctdbEndBatch(), ctdbInsertBatch(), ctdbIsBatchActive(), ctdbNextBatch(), ctdbSetBatch()
www.faircom.com
All Rights Reserved
229
ctdbBatchMode
Retrieve the current batch mode.
DECLARATION
CTBATCH_MODE ctdbDECL ctdbBatchMode(CTHANDLE Handle);
DESCRIPTION
ctdbBatchMode() retrieves the current batch mode. The batch mode is set by calling ctdbSetBatch() function. If a batch operation is not active, ctdbBatchMode() return CTBATCH_NONE. Handle must be a record handle associated with an opened table.
RETURNS
ctdbBatchMode() returns the current batch mode or CTBATCH_NONE if no batch operation is currently active.
MODE Description No active batch. Retrieve a group of related records by partial key Retrieve a group of related records based on an index range expression Retrieve records from a table in physical order. The starting record for the batch retrieval may be specified. Delete a group of related records by partial key. Insert a group of records
Refer to the c-treeDB Batch Operations chapter for complete details concerning all of the optional batch modes.
EXAMPLE
/* check if a batch operation is in progress */ if (ctdbBatchMode(hRecord) != CTBATCH_NONE) printf("Batch operation is underway\n"); else printf("No batch operations\n");
SEE ALSO
ctdbBatchLoaded(), ctdbBatchLocked(), ctdbBatchTotal(), ctdbEndBatch(), ctdbInsertBatch(), ctdbIsBatchActive(), ctdbNextBatch(), ctdbSetBatch()
FairCom Corporation
230
ctdbBatchTotal
Retrieves the total number of records affected by a batch retrieval operation.
DECLARATION
LONG ctdbDECL ctdbBatchTotal(CTHANDLE Handle);
DESCRIPTION
ctdbBatchTotal() retrieves the total number of records selected by a batch retrieval operation. If a batch operation is not active, ctdbBatchTotal() returns zero. Handle must be a record handle associated with an opened table.
RETURNS
Returns the total number of records selected by a batch retrieval operation. In case of an error, ctdbBatchLocked() returns a negative value and you may use ctdbGetError() function to retrieve the error code.
EXAMPLE
ctdbClearRecord(hRecord); ctdbSetFieldAsSigned(hRecord, 0, Invoice); /* set the batch operation */ if (ctdbSetBatch(hRecord, (CTBATCH_GET | CTBATCH_LOK_READ), sizeof(Invoice), 0) != CTDBRET_OK) printf("ctdbSetBatch failed with error %d\n", ctdbGetError(hRecord)); /* show total number of records */ printf("%d records selected\n", ctdbBatchTotal(hRecord));
SEE ALSO
ctdbBatchLoaded ctdbBatchLocked ctdbBatchMode ctdbEndBatch ctdbInsertBatch ctdbIsBatchActive ctdbNextBatch ctdbSetBatch
www.faircom.com
All Rights Reserved
231
ctdbBegin
Start a transaction.
Declaration
CTDBRET ctdbBegin(CTHANDLE Handle)
Description
ctdbBegin() marks the beginning of a transaction. All files updates done after this call will be held until they are committed with a matching call to ctdbCommit(). Notice that the record locks still must be acquired with a call to ctdbLockRecord(). If for any reason the transaction cannot be committed, it can be finished with a call to ctdbAbort(). This function can be used to perform transaction-controlled file creates. Handle [in] the session handle.
Returns
ctdbBegin() returns CTDBRET_OK if successful, or the c-tree Plus error code on failure.
Example
ctdbBegin(pSession); if (ctdbCreateTable(tHandle1,table1,CTCREATE_NORMAL) == CTDBRET_OK) ctdbCommit(pSession); else ctdbAbort(pSession);
See also
ctdbCommit(), ctdbAbort(), ctdbIsTransActive(), ctdbLockRecord()
FairCom Corporation
232
ctdbBigIntToCurrency
Convert a big integer value to a CTCURRENCY value.
Declaration
CTDBRET ctdbBigIntToCurrency(CTBIGINT value, pCTCURRENCY pCurrency)
Description
ctdbBigIntToCurrency() converts a big integer (8 bytes signed integer) value to a CTCURRENCY (8 bytes signed integer) value. Use ctdbCurrencyToBigInt() to convert from a CTCURRENCY value to a big integer (CTBIGINT) value. value [in] the CTBIGINT value (8 bytes integer). pCurrency [out] the CTCURRENCY value (8 bytes integer).
Returns
ctdbBigIntToCurrency() returns CTDBRET_OK on success, or c-treeDB C API error on failure. A possible error associated with ctdbBigIntToCurrency() is CTDBRET_NULARG since a Null argument is not valid in pCurrency.
See also
ctdbCurrencyToBigInt()
www.faircom.com
All Rights Reserved
233
ctdbBigIntToFloat
Convert a big integer value to a float.
Declaration
CTDBRET ctdbBigIntToFloat(CTBIGINT value, pCTFLOAT pFloat)
Description
ctdbBigIntToFloat() converts a big integer value to a float. A big integer is an 8 bytes integer value. Use ctdbFloatToBigInt() to convert from a float to a big integer. Use ctdbBigIntToLong() to convert a big integer value to a LONG. value [in] the big integer value (8 bytes signed integer). pFloat [out] the float value.
Returns
ctdbBigIntToFloat() returns CTDBRET_OK on success, or c-treeDB C API error on failure. The possible error associated with ctdbBigIntToFloat() is CTDBRET_NULARG since a Null argument is not valid in pFloat.
See also
ctdbFloatToBigInt(), ctdbBigIntToLong()
FairCom Corporation
234
ctdbBigIntToLong
Convert a big integer value to a LONG.
Declaration
CTDBRET ctdbBigIntToLong(CTBIGINT value, pLONG pLong)
Description
ctdbBigIntToLong() converts a big integer value to a LONG. A big integer is an 8 bytes integer value. Use ctdbLongToBigInt() to convert from a LONG to a big integer. value [in] the big integer value (8 bytes signed integer). pLong [out] the CTSIGNED LONG value (4 bytes signed integer).
Returns
ctdbBigIntToLong() returns CTDBRET_OK on success, or c-treeDB C API error on failure. Possible errors associated with ctdbBigIntToLong() are: CTDBRET_NULARG (4007): Null argument not valid in pLong CTDBRET_OVERFLOW (4038): Operation caused overflow
See also
ctdbLongToBigInt()
www.faircom.com
All Rights Reserved
235
ctdbBigIntToNumber
Convert a big integer to a CTNUMBER value.
Declaration
CTDBRET ctdbBigIntToNumber(CTBIGINT value, pCTNUMBER pNumber)
Description
ctdbBigIntToNumber() converts a big integer value to CTNUMBER. Use ctdbNumberToBigInt() to convert from a big integer to CTNUMBER. value [in] the CTBIGINT value. pNumber [out] pointer to CTNUMBER.
Returns
ctdbBigIntToNumber() returns CTDBRET_OK on success, or c-treeDB C API error on failure. The possible error associated with ctdbBigIntToNumber() is: CTDBRET_NULARG (4007): Null argument not valid in pNumber
See also
ctdbNumberToBigInt()
FairCom Corporation
236
ctdbBigIntToString
Convert a big integer value to a string.
Declaration
CTDBRET ctdbBigIntToString(CTBIGINT value, pTEXT pStr, NINT size)
Description
ctdbBigIntToString() converts a big integer value to a string. A big integer is an 8 bytes integer value. Use ctdbStringToBigInt() to convert from a string to a big integer. value [in] the big integer value (8 bytes signed integer). pStr [out] the string value. size [in] the string size in bytes
Returns
ctdbBigIntToString() returns CTDBRET_OK on success, or c-treeDB C API error on failure. The possible error associated with ctdbBigIntToString() is: CTDBRET_NULARG (4007): Null argument not valid in pStr
See also
ctdbStringToBigInt()
www.faircom.com
All Rights Reserved
237
ctdbBlobAlloc
Allocate a new blob type.
Declaration
pCTBLOB ctdbBlobAlloc(VRLEN size)
Description
ctdbBlobAlloc() allocates a new blob type. size [in] the size in bytes to allocate for the blob data. The blob is released by calling ctdbBlobFree(). Do not release the blob by calling the C runtime library function free().
Returns
ctdbBlobAlloc() returns the blob pointer, or NULL on failure.
See also
ctdbBlobFree()
FairCom Corporation
238
ctdbBlobClear
Clear a blob variable by releasing memory associated with data.
Declaration
CTDBRET ctdbBlobClear(pCTBLOB pBlob)
Description
ctdbBlobClear() clears a blob variable by releasing memory associated with data, setting data to NULL and size to zero. pBlob [in] the blob pointer.
Returns
ctdbBlobClear() returns CTDBRET_OK if successful, or the c-tree Plus error code on failure.
See also
ctdbBlobGetData(), ctdbBlobCmp(), ctdbBlobGetSize(), ctdbBlobSet(), ctdbBlobFree()
www.faircom.com
All Rights Reserved
239
ctdbBlobCmp
Compare two blobs.
Declaration
NINT ctdbBlobCmp(pCTBLOB left, pCTBLOB right)
Description
ctdbBlobCmp() compares two blobs. left [in] the first blob pointer. right [in] the second blob pointer
Returns
ctdbBlobCmp() return a negative value if left < right, positive if left > right, and zero if both blobs are equal
See also
ctdbBlobGetData(), ctdbBlobClear(), ctdbBlobGetSize(), ctdbBlobSet()
FairCom Corporation
240
ctdbBlobFree
Release all resources associated with a blob.
Declaration
void ctdbBlobFree(pCTBLOB pBlob)
Description
ctdbBlobFree releases all resources associated with a blob. ctdbBlobClear clears the blob data. pBlob [in] the blob pointer
Returns
None.
See also
ctdbBlobAlloc(), ctdbBlobClear()
www.faircom.com
All Rights Reserved
241
ctdbBlobGetData
Return a pointer to the blob data.
Declaration
pVOID ctdbBlobGetData(pCTBLOB pBlob)
Description
ctdbBlobGetData() retrieves a pointer to the blob data. pBlob [in] the blob pointer.
Returns
ctdbBlobGetData() returns the pointer to the blob data
See also
ctdbBlobGetSize(), ctdbBlobClear(), ctdbBlobCmp(), ctdbBlobSet()
FairCom Corporation
242
ctdbBlobGetSize
Return the allocated size of a blob.
Declaration
VRLEN ctdbBlobGetSize(pCTBLOB pBlob)
Description
ctdbBlobGetSize() retrieves the allocated size of a blob. pBlob [in] the blob pointer.
Returns
ctdbBlobGetSize() returns the allocated size of a blob
See also
ctdbBlobGetData(), ctdbBlobClear(), ctdbBlobCmp(), ctdbBlobSet()
www.faircom.com
All Rights Reserved
243
ctdbBlobSet
Set the blob data.
Declaration
CTDBRET ctdbBlobSet(pCTBLOB pBlob, pVOID buffer, VRLEN size)
Description
ctdbBlobSet() sets the blob data. pBlob [in/out] the blob pointer. buffer [in] the pointer to data. size [in] the number of bytes in the buffer
Returns
ctdbBlobSet() returns CTDBRET_OK if successful, or the c-tree Plus error code on failure.
See also
ctdbBlobGetData(), ctdbBlobCmp(), ctdbBlobGetSize(), ctdbBlobFree()
FairCom Corporation
244
ctdbBuildTargetKey
Build a target key based on data in record buffer.
Declaration
CTDBRET ctdbBuildTargetKey(CTHANDLE Handle, CTFIND_MODE FindMode, pVOID targetkey, pVRLEN targetlen)
Description
ctdbBuildTargetKey ()builds a target key based on data in record buffer. Handle [in] the record handle. FindMode [in] the find mode. Available values are found in "c-treeDB definitions".. targetkey [out] the target key. targetlen [in/out] the target key length. Before calling ctdbBuildTargetKey set targetlen with the size of targetkey buffer. Note: The FindMode CTFIND_EQ requires that the target contains values for all segments that compose the index and the index cannot allow duplicates. Note: When using this function with the FindTarget() function, you must supress the transformation of the already-transformed key in FindTarget() since it must not be transformed. In order to do this, you may define a macro NOTRANSFORM with a value of 0x1000 and OR it into the mode passed to FindTarget().
Returns
ctdbBuildTargetKey() returns CTDBRET_OK on success, or c-treeDB C API error code on failure.
www.faircom.com
All Rights Reserved
245
ctdbClearAllCallback
Clears all callbacks associated with any c-treeDB handle.
DECLARATION
CTDBRET ctdbClearAllCallback(CTHANDLE Handle);
DESCRIPTION
ctdbClearAllCallback() clears all callbacks associated with a handle. Handle can be a session, database, table or record handle.
RETURN
Value 0 Symbolic Constant NO_ERROR Explanation No error occurred.
See Appendix A for a complete listing of valid c-tree Plus error values.
EXAMPLE
/* allocate a record handle */ CTHANDLE hRecord = ctdbAllocRecord(hTable); /* make sure there are no callbacks */ if (ctdbClearAllCallback(hRecord)) printf("ctdbClearAllCallback failed\n");
SEE ALSO
ctdbClearCallback(), ctdbGetCallback(), ctdbSetCallback()
FairCom Corporation
246
ctdbClearAllFieldDefaultValue
Clear the default value associated with all fields in a table.
DECLARATION
CTDBRET ctdbClearAllFieldDefaultValue(CTHANDLE Handle);
DESCRIPTION
ctdbClearAllFieldDefaultValue() clears the default value associated with all fields in a table. The default date and time types for each field are also reset to the default values of CTDATE_MDCY and CTIME_HMS respectively. Handle must be a table handle.
RETURN
Value 0 Symbolic Constant NO_ERROR Explanation No error occurred.
See Appendix A for a complete listing of valid c-tree Plus error values.
EXAMPLE
/* clear all default field values *. if (ctdbClearAllFieldDefaultValue(hTable) != CTDBRET_OK) printf("ctdbClearAllFieldDefaultValue failed\n");
SEE ALSO
ctdbSetFieldDefaultValue(), ctdbGetFieldDefaultValue(), ctdbClearFieldDefaultValue(), ctdbIsFieldDefaultValueSet(), ctdbSetFieldDefaultDateTimeType(), ctdbGetFieldDefaultDateType(), ctdbGetFieldDefaultTimeType()
www.faircom.com
All Rights Reserved
247
ctdbClearCallback
Clears a particular callback associated with a c-treeDB handle.
DECLARATION
CTDBRET ctdbClearCallback(CTHANDLE Handle, CTDB_CALLBACK_TYPE CallBackType);
DESCRIPTION
You can clear a particular callback associated with a handle. Handle can be a session, database, table or record handle. CallBackType is one of the valid callback types.
RETURN
Value 0 Symbolic Constant NO_ERROR Explanation No error occurred.
See Appendix A for a complete listing of valid c-tree Plus error values.
EXAMPLE
/* allocate a record handle */ CTHANDLE hSession = ctdbAllocSession(CTSESSION_CTREE); /* make sure there are no CTDB_ON_TABLE_OPEN callbacks */ if (ctdbClearCallback(hSession, CTDB_ON_TABLE_OPEN)) printf("ctdbClearCallback failed\n");
SEE ALSO
ctdbClearAllCallback(), ctdbGetCallback(), ctdbSetCallback()
FairCom Corporation
248
ctdbClearFieldDefaultValue
Clears the default value associated with a c-treeDB field.
DECLARATION
CTDBRET ctdbClearFieldDefaultValue(CTHANDLE Handle)
DESCRIPTION
Clears the default value associated with a field. The default date and time types are also reset to their default values of CTDATE_MDCY and CTTIME_HMS respectively. Handle must be a field handle.
RETURN
Value 0 Symbolic Constant NO_ERROR Explanation No error occurred.
See Appendix A for a complete listing of valid c-tree Plus error values.
EXAMPLE
/* clear the default field value */ hField = ctdbGetField(hTable, 5); if (hField) if (ctdbClearField(hField) != CTDBRET_OK) printf("ctdbClearField failed\n");
SEE ALSO
ctdbSetFieldDefaultValue(), ctdbGetFieldDefaultValue(), ctdbIsFieldDefaultValueSet(), ctdbClearAllFieldDefaultValue(), ctdbSetFieldDefaultDateTimeType(), ctdbGetFieldDefaultDateType(), ctdbGetFieldDefaultTimeType()
www.faircom.com
All Rights Reserved
249
ctdbClearError
Clear the error code.
Declaration
void ctdbClearError(CTHANDLE Handle)
Description
ctdbClearError() clears the error code set by ctdbSetError(). Handle [in] any handle inside the session (session handle, database handle, table handle, record handle, index handle, field handle or segment handle).
Returns
None.
See also
ctdbSetError(), ctdbGetError()
FairCom Corporation
250
ctdbClearField
Clear the field data.
Declaration
CTDBRET ctdbClearField(CTHANDLE Handle, NINT FieldNbr)
Description
ctdbClearField() clears the field data. Handle [in] the record handle. FieldNbr [in] the field number.
Returns
ctdbClearField() returns CTDBRET_OK on success, or c-treeDB C API error code on failure.
See also
ctdbClearRecord()
www.faircom.com
All Rights Reserved
251
ctdbClearRecord
Clear the record buffer.
Declaration
CTDBRET ctdbClearRecord(CTHANDLE Handle)
Description
ctdbClearRecord() clears the record buffer. Before clearing a record, the record should be active. After a call to ctdbClearRecord(), functions that depend on the current record will return an error (CTDBRET_NOTACTIVE). It is very important to clear the record buffer BEFORE adding a new record to a table. If the user tries to add a new record, and the buffer is not cleared, the new record will replace (rewrite) the active record, or return an error ICUR_ERR (100), in the event the record handle has been instantiated, but not cleared. Handle [in] the record handle.
Returns
ctdbClearRecord() returns CTDBRET_OK on success, or c-treeDB C API error code on failure.
See also
ctdbAllocRecord(), ctdbResetRecord()
FairCom Corporation
252
ctdbCloseAll
Close all open tables associated with a given database.
Declaration
CTDBRET ctdbCloseAll(CTHANDLE Handle)
Description
ctdbCloseAll() closes all open tables associated with a given database. To close a specific table, use ctdbCloseTable(). Handle [in] the database handle
Returns
ctdbCloseAll() returns CTDBRET_OK on success, or c-treeDB C API error code on failure.
Example
ctdbCloseAll(hDatabase); ctdbDisconnectAll(hSession); ctdbLogout(hSession); ctdbFreeTable(hTable); ctdbFreeDatabase(hDatabase); ctdbFreeSession(hSession);
See also
ctdbCloseTable()
www.faircom.com
All Rights Reserved
253
ctdbCloseTable
Close an open table.
Declaration
CTDBRET ctdbCloseTable(CTHANDLE Handle)
Description
ctdbCloseTable() closes an open table. To open a table, use ctdbOpenTable(). When the table is closed, all resources associated with the table fields, indices, and segments are freed, and the table is reset to all default initial parameters. Handle [in] the table handle
Returns
ctdbCloseTable returns CTDBRET_OK on success, or c-treeDB C API error code on failure.
Example
eRet = ctdbClose(hTable); eRet = ctdbFreeTable(hTable);
See also
ctdbAllocTable(), ctdbOpenTable()
FairCom Corporation
254
ctdbCommit
Commit a transaction.
Declaration
CTDBRET ctdbCommit(CTHANDLE Handle)
Description
ctdbCommit() commits a transaction initiated with ctdbBegin() and releases all session-wide locks. Handle [in] the session handle.
Returns
ctdbCommit() returns CTDBRET_OK if successful, or the c-tree Plus error code on failure.
Example
ctdbBegin(pSession); if (ctdbCreateTable(tHandle1,table1,CTCREATE_NORMAL) == CTDBRET_OK) ctdbCommit(pSession); else ctdbAbort(pSession);
See also
ctdbBegin(), ctdbAbort(), ctdbIsTransActive(), ctdbSetKeepLock()
www.faircom.com
All Rights Reserved
255
ctdbConnect
Connect to a database.
Declaration
CTDBRET ctdbConnect(CTHANDLE Handle, pTEXT Name)
Description
ctdbConnect() connects to a database. Before connecting a particular database, get its handle with the ctdbAllocDatabase() function. The application must connect a database before doing any operation with tables. Handle [in] the database handle. Name [in] the database name. To disconnect a database from session, use the functions ctdbDisconnect() or ctdbDisconnectAll().
Returns
ctdbConnect returns CTDBRET_OK on success, or the c-tree Plus error code on failure.
Example
eRet = ctdbCreateDatabase(hSession, database_name, database_path); eRet = ctdbConnect(hDatabase, database_name);
See also
ctdbAllocDatabase(), ctdbDisconnect(), ctdbDisconnectAll(), ctdbCreateDatabase()
FairCom Corporation
256
ctdbCreateDatabase
Create a new database.
Declaration
CTDBRET ctdbCreateDatabase(CTHANDLE Handle, pTEXT Name, pTEXT Path)
Description
ctdbCreateDatabase() creates a new database. To create a Session, use ctdbCreateSession(). To create a table, use ctdbCreateTable(). The unique identifier, UID, is associated with the Database at the time of its creation. In order to create a database, first initiate a session with ctdbAllocSession() and then logon to the c-tree Server or c-tree Plus instance using ctdbLogon(). Handle [in] the session handle. Name [in] the database name. Path [in] the database path.
Returns
ctdbCreateDatabase() returns CTDBRET_OK on success, or c-treeDB C API error code on failure.
Example
eRet = ctdbCreateDatabase(hSession, database_name, database_path); eRet = ctdbConnect(hDatabase, database_name);
See also
ctdbAllocDatabase(), ctdbAddDatabase(), ctdbCreateSession(), ctdbCreateTable(), ctdbLogon()
www.faircom.com
All Rights Reserved
257
ctdbCreateSession
Create a new session table.
Declaration
CTDBRET ctdbCreateSession(CTHANDLE Handle, pTEXT dbengine, pTEXT userid, pTEXT password)
Description
ctdbCreateSession() creates a new session and session dictionary. The session dictionary will be created by default in the Server directory (client/server) or in the application directory (stand-alone). To change the directory to locate the session dictionary, use ctdbSetSessionPath() before calling ctdbCreateSession(). To create a database, use ctdbCreateDatabase(). To create a table, use ctdbCreateTable(). A session dictionary is required to perform any task with a database, or to logon to a c-tree Server or c-tree Plus instance with ctdbLogon(). There must not be more than one session dictionary in a c-tree Server or c-tree Plus environment. Handle [in] the session handle. dbengine [in] the string with the c-tree Server name or c-tree Plus instance name. If dbengine is NULL, ctdbCreateSession() uses the string FAIRCOMS as the default server name or c-tree Plus instance. userid [in] the string with the user name. If userid is NULL, ctdbCreateSession() uses the string ADMIN as the default user name. password [in] the string with the user password. If password is NULL, ctdbCreateSession() uses the string ADMIN as the default user password.
Returns
ctdbCreateSession() returns CTDBRET_OK on success, or c-treeDB C API error code on failure. If the error code is 19, the session dictionary already exists.
Example
err = ctdbLogon(handle); if (err == FNOP_ERR) /* Session dictionary doesn't exist*/ err = ctdbCreateSession(handle, "FAIRCOMS", "ADMIN", "ADMIN");
See also
ctdbAllocSession(), ctdbCreateDatabase(), ctdbCreateTable(), ctdbLogon()
FairCom Corporation
258
ctdbCreateTable
Create a new table.
Declaration
CTDBRET ctdbCreateTable(CTHANDLE Handle, pTEXT TableName, CTCREATE_MODE CreateMode)
Description
ctdbCreateTable() creates a new table. To create a session, use ctdbCreateSession(). To create a database, use ctdbCreateDatabase(). To retrieve the table create mode, use ctdbGetTableCreateMode(). Use ctdbOpenTable() to open an existing table. The default directory for the table creation is the server (client/server) or application (stand alone) directory. To change the directory, call ctdbSetTablePath() to set the new directory before creating the table. In order to create the table, its fields, indices and segments must be created first using, for instance, ctdbAddField(), ctdbAddIndex(), ctdbAddSegment(). Handle [in] the table handle. TableName [in] the table name. CreateMode [in] the table create mode. The valid values for the table create mode are listed in "c-treeDB definitions".. Mirrored Files The FairCom mirroring feature makes it possible to store important files on different drive volumes, partitions or physical drives. If the primary storage location is damaged or lost, the mirroring logic will automatically detect the situation and switch to the secondary or mirrored storage area. The mirrored file is easily specified by appending a vertical bar ( | ) after the table name followed by the table mirror name. For example, to mirror a table named customer to mirror, specify the table name as customer|mirror. If no path is specified for the mirrored table, both tables will be located in the same directory. If the primary table and the mirrored table are to be located in different directories, then the path names must be specified the same way as the table names: primary-path|mirrored-path.To create a mirrored table, use the ctdbCreateTable() function passing as the table name a proper mirrored naming convention:
if (ctdbCreateTable(hTable, "customer|mirror", CTCREATE_TRNLOG) ) printf("Create table failed\n");
If you need to specify different locations for the mirrored tables, use ctdbSetTablePath() to specify the mirrored paths:
if (ctdbSetTablePath(hTable, "primary_path|mirrored_path")) printf("ctdbSetTablePath failed\n");
Under c-tree Server operation, all mirroring can be suspended by adding the following entry to the server configuration file (ctsrvr.cfg):
MIRRORS NO
This may be useful when the mirroring hardware is not operational and the use of the primary data is necessary. By default, read and write operations on mirrored tables will continue without returning an error if either one of the files fail, but the other succeeds. When this happens, the failed file is shut down and subsequent I/O operations continue only with the remaining good file. If mirroring is used in the client/server model, the SystemMonitor() function receives an event when one of the files succeed and the other fails. Note: The c-treeDB alter table function will not operate on mirrored tables. If ctdbAlterTable() is called for a mirrored table, nothing is done and it returns error CTDBRET_NOTSUPPORTED.
www.faircom.com
All Rights Reserved
259
Mirroring is supplied for c-tree Server and single-user operations. It applies to all c-tree Plus file modes including transaction processing. Once a table is created and opened with mirroring, all subsequent file opens must be mirrored, except when the table is open exclusive.
Returns
ctdbCreateTable() returns CTDBRET_OK on success or the c-treeDB C API error code on failure.
Example
pMyField = ctdbAddField(pMyTable, "Name", CT_FSTRING,32); pMyIndex = ctdbAddIndex(pMyTable, "iName", CTINDEX_FIXED,NO,NO); pMyIseg = ctdbAddSegment(pMyIndex, pMyField, 2); RetVal = ctdbCreateTable(pMyTable,"Table1",CTCREATE_NORMAL);
See also
ctdbCreateSession(), ctdbCreateSession(), ctdbCreateDatabase(), ctdbGetTableCreateMode(), ctdbOpenTable(), ctdbSetTablePath(), ctdbAddField(), ctdbAddIndex(), ctdbAddSegment(), ctdbSetIndexFilename(), ctdbGetIndexFileName()
FairCom Corporation
260
ctdbCurrencyAbs
Return the absolute value of a CTCURRENCY type value.
Declaration
CTCURRENCY ctdbCurrencyAbs(CTCURRENCY left)
Description
ctdbCurrencyAbs() returns the absolute value of a CTCURRENCY type value. left [in] the value to be converted to absolute.
Returns
ctdbCurrencyAbs() returns the absolute value.
See also
ctdbCurrencyAdd(), ctdbCurrencySub(), ctdbCurrencyMul(), ctdbCurrencyDiv(), ctdbCurrencyCmp(), ctdbCurrencyRound()
www.faircom.com
All Rights Reserved
261
ctdbCurrencyAdd
Add two currency values. pResult = left + right
Declaration
CTDBRET ctdbCurrencyAdd(CTCURRENCY left, CTCURRENCY right, pCTCURRENCY pResult)
Description
ctdbCurrencyAdd() adds two currency values. pResult = left + right. Do not make regular additions with CTCURRENCY values. left [in] the first value to be added. right [in] the second value to be added. pResult [out] the result of the add operation.
Returns
ctdbCurrencyAdd() returns CTDBRET_OK on success, or c-treeDB C API error on failure. The possible errors associated with ctdbCurrencyAdd() are: CTDBRET_NULARG (4007): Null argument not valid in any operand CTDBRET_UNDERFLOW (4039): Operation caused underflow CTDBRET_OVERFLOW (4038): Operation caused overflow
See also
ctdbCurrencySub(), ctdbCurrencyMul(), ctdbCurrencyDiv()
FairCom Corporation
262
ctdbCurrencyCmp
Compare two CTCURRENCY type values.
Declaration
NINT ctdbCurrencyCmp(CTCURRENCY left, CTCURRENCY right)
Description
ctdbCurrencyCmp() compares two CTCURRENCY values. left [in] the first value to be compared. right [in] the second value to be compared.
Returns
ctdbCurrencyCmp() returns a negative value if left < right, positive value if left > right, and zero if left == right
See also
ctdbCurrencyAdd(), ctdbCurrencySub(), ctdbCurrencyMul(), ctdbCurrencyDiv(), ctdbCurrencyAbs(), ctdbCurrencyRound()
www.faircom.com
All Rights Reserved
263
ctdbCurrencyDiv
Divide a currency value by another currency value. pResult = left / right.
Declaration
CTDBRET ctdbCurrencyDiv(CTCURRENCY left, CTCURRENCY right, pCTCURRENCY pResult)
Description
ctdbCurrencyDiv() divides the left currency value by the right currency value (e.g., pResult = left / right). Do not make regular division with CTCURRENCY values. Use regular division between a CTCURRENCY value and a numeric value (int, COUNT, FLOAT, etc.). left [in] the value to be divided (divisor). right [in] the value to divide (dividend). pResult [out] the result of the Div operation.
Returns
ctdbCurrencyDiv() returns CTDBRET_OK on success, or c-treeDB C API error on failure. The possible errors associated with ctdbCurrencyDiv() are: CTDBRET_NULARG (4007): Null argument not valid in any operand CTDBRET_DIVBYZERO (4040): Division by zero error
See also
ctdbCurrencyAdd(), ctdbCurrencySub(), ctdbCurrencyMul()
FairCom Corporation
264
ctdbCurrencyMul
Multiply two CTCURRENCY values.
Declaration
CTDBRET ctdbCurrencyMul(CTCURRENCY left, CTCURRENCY right, pCTCURRENCY pResult)
Description
ctdbCurrencyMul() multiplies two currency values. pResult = left * right. Do not use regular multiplication with CTCURRENCY values. Use regular multiplication with a combination of a CTCURRENCY value and a numeric value (int, COUNT, FLOAT, etc.). left [in] the first value to be multiplied. right [in] the second value to be multiplied. pResult [out] the result of the multiplication operation.
Returns
ctdbCurrencyMul() returns CTDBRET_OK on success, or c-treeDB C API error on failure. The possible errors associated with ctdbCurrencyMul() are: CTDBRET_NULARG (4007): Null argument not valid in any operand CTDBRET_OVERFLOW (4038): Operation caused overflow
See also
ctdbCurrencyAdd(), ctdbCurrencySub(), ctdbCurrencyDiv()
www.faircom.com
All Rights Reserved
265
ctdbCurrencyRound
Round a currency value to a given number of decimal places.
Declaration
CTDBRET ctdbCurrencyRound(pCTCURRENCY value, NINT scale)
Description
ctdbCurrencyRound() rounds a currency value to a given number of decimal places. value [in/out] the value to be converted to absolute. scale [in] the number of decimal digits.
Returns
ctdbCurrencyRound() returns CTDBRET_OK on success, or c-treeDB C API error on failure. The possible error associated with ctdbCurrencyMu()l is: CTDBRET_NULARG (4007): Null argument not valid in any operand
See also
ctdbCurrencyAdd(), ctdbCurrencySub(), ctdbCurrencyMul(), ctdbCurrencyDiv(), ctdbCurrencyCmp(), ctdbCurrencyAbs()
FairCom Corporation
266
ctdbCurrencySub
Subtract two currency values. pResult = left - right.
Declaration
CTDBRET ctdbCurrencySub(CTCURRENCY left, CTCURRENCY right, pCTCURRENCY pResult)
Description
ctdbCurrencySub() subtracts two currency values. pResult = left - right. Do not make regular subtractions with CTCURRENCY values. left [in] the first value, to be subtracted by right. right [in] the second value, to subtract from left. pResult [out] the result of the subtraction operation.
Returns
ctdbCurrencySub() returns CTDBRET_OK on success, or c-treeDB C API error on failure. The possible errors associated with ctdbCurrencySub() are: CTDBRET_NULARG (4007): Null argument not valid in any operand CTDBRET_UNDERFLOW (4039): Operation caused underflow CTDBRET_OVERFLOW (4038): Operation caused overflow
See also
ctdbCurrencyAdd(), ctdbCurrencyMul(), ctdbCurrencyDiv()
www.faircom.com
All Rights Reserved
267
ctdbCurrencyToBigInt
Convert a CTCURRENCY value to a big integer value.
Declaration
CTDBRET ctdbCurrencyToBigInt(CTCURRENCY currency, pCTBIGIND pValue)
Description
ctdbCurrencyToBigInt() converts a CTCURRENCY (8 bytes signed integer) value to a big integer (8 bytes signed integer) value. Use ctdbBigIntToCurrency() to convert from a big integer (CTBIGINT) value to a CTCURRENCY value. Use ctdbCurrencyToLong() to convert from CTCURRENCY to a CTSIGNED (4 bytes signed integer). currency [in] the CTCURRENCY value (8 bytes integer). pValue [out] the CTBIGINT value (8 bytes integer).
Returns
ctdbCurrencyToBigInt() returns CTDBRET_OK on success, or c-treeDB C API error on failure. The possible error associated with ctdbCurrencyToBigInt() is: CTDBRET_NULARG (4007): Null argument not valid in pValue
See also
ctdbBigIntToCurrency()
FairCom Corporation
268
ctdbCurrencyToFloat
Convert a CTCURRENCY value to a float value.
Declaration
CTDBRET ctdbCurrencyToFloat(CTCURRENCY currency, pCTFLOAT pValue)
Description
ctdbCurrencyToFloat() converts a CTCURRENCY (8 bytes signed integer) value to a float value. Use ctdbFloatToCurrency() to convert from a float to a CTCURRENCY value. currency [in] the CTCURRENCY value (8 bytes integer). pValue [out] the CTFLOAT value.
Returns
ctdbCurrencyToFloat() returns CTDBRET_OK on success, or c-treeDB C API error on failure. The possible error associated with ctdbCurrencyToFloat() is: CTDBRET_NULARG (4007): Null argument not valid in pValue
See also
ctdbFloatToCurrency()
www.faircom.com
All Rights Reserved
269
ctdbCurrencyToLong
Convert a CTCURRENCY value to a LONG value.
Declaration
CTDBRET ctdbCurrencyToLong(CTCURRENCY currency, pCTSIGNED pValue)
Description
ctdbCurrencyToLong() converts a CTCURRENCY (8 bytes signed integer) value to a CTSGINED (4 bytes signed integer) value. Use ctdbLongToCurrency() to convert from a LONG value to a CTCURRENCY value. currency [in] the CTCURRENCY value (8 bytes integer). pValue [out] the CTSIGNED value (4 bytes integer).
Returns
ctdbCurrencyToLong() returns CTDBRET_OK on success, or c-treeDB C API error on failure. The possible error associated with ctdbCurrencyToLong() is: CTDBRET_NULARG (4007): Null argument not valid in pValue
See also
ctdbLongToCurrency()
FairCom Corporation
270
ctdbCurrencyToMoney
Convert a CTCURRENCY value to a CTMONEY value.
Declaration
CTDBRET ctdbCurrencyMoney(CTCURRENCY currency, pCTMONEY pMoney)
Description
ctdbCurrencyToMoney() converts a CTCURRENCY value to a CTMONEY value. A currency value is an 8 bytes integer. Use ctdbMoneyToCurrency() to convert from a CTMONEY value to a CTCURRENCY value. currency [in] the CTCURRENCY value (8 bytes integer). pMoney [out] the CTMONEY value.
Returns
ctdbCurrencyToMoney() returns CTDBRET_OK on success, or c-treeDB C API error on failure. The possible error associated with ctdbCurrencyToMoney() is: CTDBRET_NULARG (4007): Null argument not valid in pMoney CTDBRET_OVERFLOW (4038): Operation caused overflow CTDVRET_UNDERFLOW (4039): Operation caused underflow
See also
ctdbMoneyToCurrency()
www.faircom.com
All Rights Reserved
271
ctdbCurrencyToNumber
Convert a CTCURRENCY value to a CTNUMBER value.
Declaration
CTDBRET ctdbCurrencyToNumber(CTCURRENCY value, pCTNUMBER pNumber)
Description
ctdbCurrencyToNumber() converts a CTCURRENCY value to a CTNUMBER value. Use ctdbNumberToCurrency() to convert from a CTNUMBER to CTCURRENCY. value [in] the CTCURRENCY value. pNumber [out] pointer to CTNUMBER.
Returns
ctdbCurrencyToNumber() returns CTDBRET_OK on success, or c-treeDB C API error on failure. The possible error associated with ctdbCurrencyToNumber() is: CTDBRET_NULARG (4007): Null argument not valid in pNumber
See also
ctdbNumberToCurrency(), ctdbNumberToLong()
FairCom Corporation
272
ctdbCurrencyToString
Convert a CTCURRENCY value to a string value.
Declaration
CTDBRET ctdbCurrencyToString(CTCURRENCY currency, pTEXT pStr, VRLEN size)
Description
ctdbCurrencyToString() converts a CTCURRENCY (8 bytes signed integer) value to a string value. Use ctdbStringToCurrency() to convert from a string to a CTCURRENCY value. currency [in] the CTCURRENCY value (8 bytes integer). pStr [out] the string value. size [in] the string size in bytes.
Returns
ctdbCurrencyToString() returns CTDBRET_OK on success, or c-treeDB C API error on failure. The possible error associated with ctdbCurrencyToString() is: CTDBRET_NULARG (4007): Null argument not valid in pStr
See also
ctdbStringToCurrency()
www.faircom.com
All Rights Reserved
273
ctdbCurrentDate
Retrieve the current system date.
Declaration
CTDBRET ctdbCurrentDate(pCTDATE pDate)
Description
ctdbCurrentDate() retrieves the current system date. ctdbCurrentDateTime() retrieves the current date and time. pDate [out] pointer to a CTDATE value to receive the current date.
Returns
ctdbCurrentDate() returns CTDBRET_OK on success, or c-treeDB C API error code on failure.
See also
ctdbCurrentTime(), ctdbCurrentDateTime()
FairCom Corporation
274
ctdbCurrentDateTime
Retrieve the current system date and time.
Declaration
CTDBRET ctdbCurrentDateTime(pCTDATETIME pDateTime)
Description
ctdbCurrentDateTime() retrieves the current system date and time. pDateTime [out] pointer to a CTDATETIME value to receive the current date and time.
Returns
ctdbCurrentDateTime() returns CTDBRET_OK on success, or c-treeDB C API error code on failure.
See also
ctdbCurrentDate(), ctdbCurrentTime()
www.faircom.com
All Rights Reserved
275
ctdbCurrentTime
Retrieve the current system time.
Declaration
CTDBRET ctdbCurrentTime(pCTTIME pTime)
Description
ctdbCurrentTime() retrieves the current system time. ctdbCurrentDateTime() retrieves the current date and time. pTime [out] pointer to a CTTIME value to receive the current time.
Returns
ctdbCurrentTime() returns CTDBRET_OK on success, or c-treeDB C API error code on failure.
See also
ctdbCurrentDate(), ctdbCurrentDateTime()
FairCom Corporation
276
ctdbDateCheck
$ Check if a given date is valid.
Declaration
CTDBRET ctdbDateCheck(NINT year, NINT month, NINT day)
Description
ctdbDateCheck() checks to see if the given date is valid. To check if the time is valid, use ctdbTimeCheck(). year [in] the year, and it is supposed to be 0. month 12. day 28, or 29, or 30, or 31, depending on the month [in] the month, and it supposed to be in the range 1 day [in] the day, and it supposed to be in the range 1 month and year.
Returns
ctdbDateCheck() returns CTDBRET_OK if date is ok, or c-treeDB C API error on failure. The possible errors associated with ctdbDateCheck() are: CTDBRET_INVYEAR (4032): Invalid year CTDBRET_INVMONTH (4031): Invalid month CTDBRET_INVDAY (4030): Invalid day
See also
ctdbTimeCheck()
www.faircom.com
All Rights Reserved
277
ctdbDatePack
Pack a date in the form day, month and year into a CTDATE form.
Declaration
CTDBRET ctdbDatePack(pCTDATE pDate, NINT year, NINT month, NINT day)
Description
ctdbDatePack() pack a date in the form day, month and year into a CTDATE form. pDate [out] the packed date. year [in] the year, and it is supposed to be 0. month 12. day 28, or 29, or 30, or 31, depending on the month [in] the month, and it supposed to be in the range 1 day [in] the day, and it supposed to be in the range 1 month and year.
Returns
ctdbDatePack() returns CTDBRET_OK on success, or c-treeDB C API error on failure.
See also
ctdbDateUnpack(), ctdbDateTimePack()
FairCom Corporation
278
ctdbDateTimeGetDate
Retrieve a CTDATE type value from a CTDATETIME type value
Declaration
CTDBRET ctdbDateTimeGetDate(CTDATETIME DateTime, pCTDATE pDATE)
Description
ctdbDateTimeGetDate() retrieves a CTDATE type value from a CTDATETIME type value. DateTime [in] the packed date and time value. pDate [out] the CTDATE value.
Returns
ctdbDateTimeGetDate() returns CTDBRET_OK on success, or c-treeDB C API error on failure.
See also
ctdbDateTimeSetDate(), ctdbDateTimeGetTime()
www.faircom.com
All Rights Reserved
279
ctdbDateTimeGetTime
Retrieve a CTTIME type value from a CTDATETIME type value
Declaration
CTDBRET ctdbDateTimeGetTime(CTDATETIME DateTime, pCTTIME pTIME)
Description
ctdbDateTimeGetTime() retrieves a CTTIME type value from a CTDATETIME type value. DateTime [in] the packed date and time value. pTime [out] the CTTIME value.
Returns
ctdbDateTimeGetTime() returns CTDBRET_OK on success, or c-treeDB C API error on failure.
See also
ctdbDateTimeGetDate(), ctdbDateTimeSetTime()
FairCom Corporation
280
ctdbDateTimePack
Pack a date and time in the form day, month, year, hour, minute, second into a CTDATETIME form.
Declaration
CTDBRET ctdbDateTimePack(pCTDATETIME pDateTime, NINT year, NINT month, NINT day, NINT hour, NINT minute, NINT second)
Description
ctdbDateTimePack() pack a date and time value in the form day, month, year, hour, minute, second into a CTDATETIME form. pDateTime [out] the packed date and time value. year [in] the year. month [in] the month. day [in] the day. hour [in] the hour. minute [in] the minute. second [in] the second.
Returns
ctdbDateTimePack() returns CTDBRET_OK on success, or c-treeDB C API error on failure.
See also
ctdbDateTimeUnpack()
www.faircom.com
All Rights Reserved
281
ctdbDateTimeSetDate
Set a CTDATETIME type value with a CTDATE type value.
Declaration
CTDBRET ctdbDateTimeSetDate(pCTDATETIME pDateTime, CTDATE DATE)
Description
ctdbDateTimeSetDate() sets a CTDATETIME type value with a CTDATE type value. The time component of the CTDATETIME type value is left unchanged. pDateTime [in/out] the packed date and time value. Date [in] the CTDATE value.
Returns
ctdbDateTimeSetDate() returns CTDBRET_OK on success, or c-treeDB C API error on failure.
See also
ctdbDateTimeGetDate(), ctdbDateTimeSetTime()
FairCom Corporation
282
ctdbDateTimeSetTime
Set a CTDATETIME type value with a CTTIME type value.
Declaration
CTDBRET ctdbDateTimeSetTime(pCTDATETIME pDateTime, CTTIME TIME)
Description
ctdbDateTimeSetTime() sets a CTDATETIME type value with a CTTIME type value. The date component of the CTDATETIME type value is left unchanged. pDateTime [in/out] the packed date and time value. Time [in] the CTTIME value.
Returns
ctdbDateTimeSetTime() returns CTDBRET_OK on success, or c-treeDB C API error on failure.
See also
ctdbDateTimeSetDate(), ctdbDateTimeGetTime()
www.faircom.com
All Rights Reserved
283
ctdbDateTimeToString
Convert a packed CTDATETIME into a string.
Declaration
CTDBRET ctdbDateTimeToString(CTDATETIME DateTime, CTDATE_TYPE DateType, CTTIME_TYPE TimeType, pTEXT pStr, VRLEN size)
Description
ctdbDateTimeToString() converts a packed CTDATETIME into a string. The date is converted to string based on the DateType parameter, and the time is converted to string based on the TimeType parameter. DateTime [in] the date and time, in CTDATETIME format. DateType [in] the date type. Valid types are listed in "c-treeDB definitions".. TimeType [in] the time type. Valid types are listed in "c-treeDB definitions".. pStr [out] a pointer to the string that will result from the conversion. size [in] the buffer size for the string.
Returns
ctdbDateTimeToString() returns CTDBRET_OK on success, or c-treeDB C error on failure. The possible errors associated with ctdbDateTimeToString() are: CTDBRET_NULARG (4007): Null argument not valid in pStr CTDBRET_INVDATE (4029): Invalid format in DateType CTDBRET_INVTYPE (4019): Invalid type in DateType or TimeType CTDBRET_ARGSMALL (4006): Buffer is too small (increase size)
See also
ctdbTimeToString(), ctdbDateToString(), ctdbStringToDateTime()
FairCom Corporation
284
ctdbDateTimeUnpack
Unpack a date and time CTDATETIME value into the form day, month, year, hour, minute, second.
Declaration
CTDBRET ctdbDateTimeUnpack(CTDATETIME DateTime, pNINT pYear, pNINT pMonth, pNINT pDay, pNINT pHour, pNINT pMinute, pNINT pSecond)
Description
ctdbDateTimeUnpack() unpacks a date and time CTDATETIME value into the form day, month, year, hour, minute, second. DateTime [in] the packed date and time value. pyear [out] the year. pmonth [out] the month. pday [out] the day. phour [out] the hour. pminute [out] the minute. psecond [out] the second.
Returns
ctdbDateTimeUnpack() returns CTDBRET_OK on success, or c-treeDB C API error on failure.
See also
ctdbDateTimePack()
www.faircom.com
All Rights Reserved
285
ctdbDateToString
Convert a packed CTDATE into a string.
Declaration
CTDBRET ctdbDateToString(CTDATE date, CTDATE_TYPE DateType, pTEXT pStr, VRLEN size)
Description
ctdbDateToString() converts a packed CTDATE into a string. The date is converted to string based on the DateType parameter. To convert a packed CTTIME to string, use ctdbTimeToString(). Use ctdbStringToDate() to convert from a string to CTDATE. date [in] the date, in CTDATE format. DateType [in] the date type. Valid types are listed in "c-treeDB definitions".. pStr [in] the pointer to the string that will result from the conversion. size [in] the buffer size of the string.
Returns
ctdbDateToString() returns CTDBRET_OK on success, or c-treeDB C error on failure. The possible errors associated with ctdbDateToString() are: CTDBRET_NULARG (4007): Null argument not valid in pStr CTDBRET_INVDATE (4029): Invalid format in DateType CTDBRET_INVTYPE (4019): Invalid type in DateType CTDBRET_ARGSMALL (4006): Buffer is too small (increase size)
See also
ctdbStringToDate(), ctdbTimeToString(), ctdbDateTimeToString()
FairCom Corporation
286
ctdbDateUnpack
Unpack a CTDATE date into the form day, month and year.
Declaration
CTDBRET ctdbDateUnpack(CTDATE Date, pNINT pyear, pNINT pmonth, pNINT pday)
Description
ctdbDateUnpack() unpacks a CTDATE date into the form day, month and year. Date [in] the packed date. pyear [out] the year. pmonth [out] the month. pday [out] the day
Returns
ctdbDateUnpack() returns CTDBRET_OK on success, or c-treeDB C API error on failure.
See also
ctdbDatePack()
www.faircom.com
All Rights Reserved
287
ctdbDayOfWeek
Retrieve the day of the week from a packed CTDATE.
Declaration
NINT ctdbDayOfWeek(CTDATE date)
Description
ctdbDayOfWeek() retrieves the number of the day of the week from a packed CTDATE. Sunday is 0, Monday is 1, Tuesday is 2, Wednesday is 3, Thursday is 4, Friday is 5 and Saturday is 6. To retrieve the day of the month, use ctdbGetDay(). date [in] the date, in CTDATE format.
Returns
ctdbDayOfWeek() returns the number of the day of the week, or -1 on error.
See also
ctdbGetDay()
FairCom Corporation
288
ctdbDeleteDatabase
Drop the database from session and delete database file and index.
Declaration
CTDBRET ctdbDeleteDatabase(CTHANDLE Handle, pTEXT Name)
Description
ctdbDeleteDatabase() drops the database from the session and deletes the database file and index. Handle [in] the session handle. Name [in] the database name. Use ctdbAddDatabase() to add a database to a session. Use ctdbDropDatabase() to drop the database from the session without deleting the database files.
Returns
ctdbDeleteDatabase() returns CTDBRET_OK on success, or the c-tree Plus error code on failure.
Example
eRet = ctdbLogon(hSession, "FAIRCOMS", "ADMIN", "ADMIN"); eRet = ctdbDeleteDatabase(hSession, database_name);
See also
ctdbAllocSession(), ctdbAddDatabase(), ctdbDropDatabase()
www.faircom.com
All Rights Reserved
289
ctdbDeleteRecord
Delete an existing record.
Declaration
CTDBRET ctdbDeleteRecord(CTHANDLE Handle)
Description
ctdbDeleteRecord() deletes an existing record. In order to delete a record, the record must be locked first with the WRITE_LOCK mode. To lock a record use ctdbLock() or ctdbdbLockRecord(). Handle [in] the record handle.
Returns
ctdbDeleteRecord() returns CTDBRET_OK if successful, or the c-tree Plus error code on failure.
See also
ctdbAllocRecord(), ctdbLock(), ctdbdbLockRecord(), ctdbReadRecord(), ctdbWriteRecord()
FairCom Corporation
290
ctdbDeleteTable
Drop a table from a database and delete table from disk.
Declaration
CTDBRET ctdbDeleteTable(CTHANDLE Handle, pTEXT TableName, pTEXT Password)
Description
ctdbDeleteTable() drops the table from the database and deletes the table from disk. This function should be used with care, since it will remove from disk the data and index file(s) associated with the given name. Handle [in] the database handle. TableName [in] the name of the table to be deleted. Password [in] the table password. Use ctdbAddTable() to add a table to a database. Use ctdbDropTable() to drop the table from the database, but do not delete the table files from disk.
Returns
ctdbDeleteTable() returns CTDBRET_OK on success, or the c-tree Plus error code on failure.
Example
eRet=ctdbConnect(hDatabase, database_name); eRet = ctdbDeleteTable(hDatabase, table_name, NULL);
See also
ctdbAddTable(), ctdbDropTable(), ctdbAllocDatabase()
www.faircom.com
All Rights Reserved
291
ctdbDelField
Delete the field indicated by the field number Index.
Declaration
CTDBRET ctdbDelField(CTHANDLE Handle, NINT Index)
Description
ctdbDelField() deletes the field indicated by the field number Index. Use ctdbDelFieldByName() to delete a field by name. Use ctdbAddField(), ctdbInsField() and ctdbInsFieldByName() to add fields to a table. Handle [in] the Table handle. Index [in] the field number to be deleted.
Returns
ctdbDelField() returns CTDBRET_OK on success or c-treeDB SDK error code on failure.
See also
ctdbAllocTable(), ctdbAddField(), ctdbInsField(), ctdbInsFieldByName(), ctdbDelFieldByName(), ctdbMoveField()
FairCom Corporation
292
ctdbDelFieldByName
Delete the field indicated by the field name
Declaration
CTDBRET ctdbDelFieldByName(CTHANDLE Handle, pTEXT FieldName)
Description
ctdbDelFieldByName() deletes the field indicated by the field name. Use ctdbDelField() to delete a field by number. Use ctdbAddField(), ctdbInsField() and ctdbInsFieldByName() to add fields to a table. Handle [in] the Table handle. FieldName [in] the name of the field to be deleted.
Returns
ctdbDelFieldByName() returns CTDBRET_OK on success or c-treeDB SDK error code on failure.
See also
ctdbAllocTable(), ctdbAddField(), ctdbInsField(), ctdbInsFieldByName(), ctdbDelField(), ctdbMoveField()
www.faircom.com
All Rights Reserved
293
ctdbDelIndex
Delete an index from a table.
Declaration
CTDBRET ctdbDelIndex(CTHANDLE Handle, NINT IndexNumber)
Description
ctdbDelIndex() deletes an index from a table. Use ctdbAddIndex() to add indices in a table. Handle [in] the table handle. IndexNumber [in] the number of the index in the table.
Returns
ctdbDelIndex() returns CTDBRET_OK on success, or c-treeDB SDK error code on failure.
See also
ctdbAllocTable(), ctdbAddIndex()
FairCom Corporation
294
ctdbDeleteResource
Delete an existing resource from a table.
DECLARATION
CTDBRET ctdbDECL ctdbDeleteResource(CTHANDLE resource);
DESCRIPTION
ctdbDeleteResource() delete a resource from a table. Before a resource can be deleted, the table must be opened exclusive. The resource type and resource number that identify this resource must be passed to ctdbAllocResource(). Resource is a handle allocated by ctdbAllocResource().
RETURN
ctdbDeleteResource() returns CTDBRET_OK on success
EXAMPLE
/* delete a resource */ CTDBRET DelMyResource(CTHANDLE Handle, ULONG type, ULONG number, pTEXT name) { CTDBRET Retval; CTHANDLE hRes = ctdbAllocResource(Handle, type, number, name); if (hRes) { if ((Retval = ctdbDeleteResource(hRes)) != CTDBRET_OK) printf("ctdbDeleteResource failed with error %d\n", Retval); ctdbFreeResource(hRes); } else { printf("Failed to allocate resource handle\n"); Retval = CTDBRET_NOMEMORY; } return Retval; }
SEE ALSO
ctdbAllocResource(), ctdbFreeResource(), ctdbAddResource(), ctdbUpdateResource(), ctdbFirstResource(), ctdbNextResource(), ctdbFindResource, ctdbFindResourceByName, ctdbGetResourceType, ctdbSetResourceType, ctdbGetResourceNumber, ctdbSetResourceNumber, ctdbGetResourceName, ctdbSetResourceName, ctdbGetResourceDataLength, ctdbGetResourceData, ctdbSetResourceData, ctdbIsResourceLocked, ctdbUnlockResource
www.faircom.com
All Rights Reserved
295
ctdbDelSegment
Delete segment indicated by SegNumber.
Declaration
CTDBRET ctdbDelSegment(CTHANDLE Handle, NINT SegNumber)
Description
ctdbDelSegment() deletes a segment from an index. The segment to be deleted is indicated by SegNumber. Use ctdbAddSegment() and ctdbInsSegment() to add new index segments. Handle [in] the index handle. SegNumber [in] the index segment number to be deleted.
Returns
ctdbDelSegment() returns CTDBRET_OK on success, or c-treeDB SDK error code on failure.
See also
ctdbAllocIndex(), ctdbAddSegment(), ctdbInsSegment()
FairCom Corporation
296
ctdbDelSegmentEx
Delete extended segment.
Declaration
CTDBRET ctdbDelSegmentEx(CTHANDLE Handle)
Description
ctdbDelSegmentEx() deletes an extended segment from an index. Handle [in] the segment handle.
Returns
ctdbDelSegmentEx() returns CTDBRET_OK on success, or c-treeDB SDK error code on failure.
See also
ctdbDelSegment()
www.faircom.com
All Rights Reserved
297
ctdbDetachSession
Detaches a c-treeDB session handle from an existing c-tree connection.
DECLARATION
CTDBRET ctdbDECL ctdbDetachSession(CTHANDLE Handle);
DESCRIPTION
ctdbDetachSession() detaches a c-treeDB session handle. The c-tree ISAM or low-level un-initialization is not called, but the session handle control structures are released and re- initialized. Handle is a session handle allocated by ctdbAllocSesison().
RETURN
Value 0 Symbolic Constant NO_ERROR Explanation No error occurred.
See Appendix A for a complete listing of valid c-tree Plus error values.
EXAMPLE
/* logon to c-tree using ISAM function */ INTISAMX(10, 32, 32, 10, (USERPRF_NTKEY | USERPRF_CLRCHK)); /* attach session to server handle */ if (ctdbAttachSession(hSession, NO) != CTDBRET_OK) printf("ctdbAttachSession failed\n"); /* ... do something useful ... */ /* detach from session */ if (ctdbDetachSession(hSession) != CTDBRET_OK) printf("ctdbDetachSession failed\n"); /* perform an ISAM logout */ CLISAM();
SEE ALSO
ctdbAttachSession()
FairCom Corporation
298
ctdbDetachTable
Detaches a c-treeDB table handle from a c-tree data and index files.
DECLARATION
CTDBRET ctdbDetachTable(CTHANDLE Handle);
DESCRIPTION
ctdbDetachTable() detaches a c-treeDB table handle from a c-tree data and index files. The table is not closed but the c-treeDB table handle resources are released and the handle re-initialized. Handle is a c-treeDB table handle allocated by ctdbAllocTable().
RETURN
Value 0 Symbolic Constant NO_ERROR Explanation No error occurred.
See Appendix A for a complete listing of valid c-tree Plus error values.
EXAMPLE
CTHANDLE hSession = ctdbAllocSession(CTSESSION_CTREE); CTHANDLE hTable = ctdbAllocTable(hSession); CTHANDLE hRecord = ctdbAllocRecord(hTable); NINT datno, count = 0; /* logon to c-tree */ ctdbLogon(hSession, SERVER, USER, PASSWD); /* open the file using c-tree ISAM */ datno = (NINT)OPNRFILX((COUNT) -1, "test309.dat", (COUNT)0, NULL);) /* attach to table */ ctdbAttachTable(hTable, datno); /* read the records */ if (ctdbFirstRecord(hRecord) == CTDBRET_OK) do { count++; } while (ctdbNextRecord(hRecord) == CTDBRET_OK); /* cleanup */ ctdbDetachtable(hTable); ctdbFreeRecord(hRecord); ctdbFreeTable(hTable); ctdbLogout(hSession); ctdbFreeSession(hSession);
SEE ALSO
ctdbAttachTable(), ctdbAttachTableXtd()
www.faircom.com
All Rights Reserved
299
ctdbDisconnect
Disconnect a database.
Declaration
CTDBRET ctdbDisconnect(CTHANDLE Handle)
Description
ctdbDisconnect() disconnects a database. Handle [in] the database handle. Use ctdbConnect() to connect a database to a Session. Use ctdbDisconnectAll() to disconnect all databases associated with a Session. A database created with ctdbCreateDatabase() is automatically connected to the present Session.
Returns
ctdbDisconnect() returns CTDBRET_OK on success, or the c-tree Plus error code on failure.
Example
ctdbDisconnect(hDatabase); ctdbLogout(hSession); ctdbFreeDatabase(hDatabase); ctdbFreeSession(hSession);
See also
ctdbAllocDatabase(), ctdbConnect(), ctdbDisconnectAll(), ctdbCreateDatabase()
FairCom Corporation
300
ctdbDisconnectAll
Disconnect all databases.
Declaration
CTDBRET ctdbDisconnectAll(CTHANDLE Handle)
Description
ctdbDisconnectAll() disconnects all connected databases. Handle [in] the session handle. Use ctdbConnect() to connect a database to a session. Use ctdbDisconnect() to disconnect just one database. A database created with ctdbCreateDatabase() is automatically connected to the present session.
Returns
ctdbDisconnect() returns CTDBRET_OK on success, or the c-tree Plus error code on failure.
Example
ctdbCloseAll(hDatabase); ctdbDisconnectAll(hSession); ctdbLogout(hSession); ctdbFreeTable(hTable); ctdbFreeDatabase(hDatabase); ctdbFreeSession(hSession);
See also
ctdbAllocSession(), ctdbConnect(), ctdbDisconnect(), ctdbCreateDatabase()
www.faircom.com
All Rights Reserved
301
ctdbDropDatabase
Drop a database from a session dictionary. The data and index files are not deleted from disk.
Declaration
CTDBRET ctdbDropDatabase(CTHANDLE Handle, pTEXT Name)
Description
ctdbDropDatabase() drops the database from the session dictionary, but does not delete the database file and index. Handle [in] the session handle. Name [in] the database name. Use ctdbAddDatabase() to add a database to a session. Use ctdbDeleteDatabase() to drop the database from the session and delete the database file and index.
Returns
ctdbDropDatabase() returns CTDBRET_OK on success, or the c-tree Plus error code on failure.
Example
eRet = ctdbLogon(hSession, "FAIRCOMS", "ADMIN", "ADMIN"); eRet = ctdbDropDatabase(hSession, database_name);
See also
ctdbAllocSession(), ctdbAddDatabase(), ctdbDeleteDatabase()
FairCom Corporation
302
ctdbDropTable
Drop the table from the database.
Declaration
CTDBRET ctdbDropTable(CTHANDLE Handle, pTEXT TableName)
Description
ctdbDropTable() drops the table from the database, but does not delete the table from disk. When a table is dropped, the allocated records, fields, index and segments are freed. Handle [in] the database handle. TableName [in] the name of the table to be deleted. Use ctdbAddTable() to add a table to a database. Use ctdbDeleteTable() to drop the table from the database and delete the table files from disk.
Returns
ctdbDropTable() returns CTDBRET_OK on success, or the c-tree Plus error code on failure.
Example
eRet=ctdbConnect(hDatabase, database_name); eRet = ctdbDropTable(hDatabase, table_name);
See also
ctdbDeleteTable(), ctdbAddTable(), ctdbAllocDatabase()
www.faircom.com
All Rights Reserved
303
ctdbDuplicateRecord
Return a duplicate copy of a record.
Declaration
CTHANDLE ctdbDuplicateRecord(CTHANDLE Handle)
Description
ctdbDuplicateRecord ()duplicates an existing record. Handle [in] the record handle to be duplicated.
Returns
ctdbDuplicateRecord() returns a copy of the record, or NULL on failure.
FairCom Corporation
304
ctdbEndBatch
Terminates or cancels a batch operation.
DECLARATION
CTDBRET ctdbDECL ctdbEndBatch(CTHANDLE Handle);
DESCRIPTION
A batch operation must be terminated by calling the ctdbEndBatch() function. Once a batch operation is started with ctdbSetBatch(), no other batch operation is allowed to start until the current batch operation is terminated. When performing batch retrieval operations, you may cancel the batch operation before retrieving all the records by calling ctdbEndBatch(). If the batch operation is a CTBATCH_RANGE then you must also call ctdbRecordRangeOff() function to terminate the index range used for the batch operation. Handle must be a c-treeDB record handle associated with an opened table.
RETURNS
Value 0 Symbolic Constant NO_ERROR Explanation No error occurred.
See Appendix A for a complete listing of valid c-tree Plus error values.
EXAMPLE
/* set the partial target key */ ctdbClearRecord(hRecord); ctdbSetFieldAsSigned(hRecord, 0, Invoice); /* set the batch operation */ if (ctdbSetBatch(hRecord, CTBATCH_DEL, sizeof(Invoice), 0) != CTDBRET_OK) printf("ctdbSetBatch failed with error %d\n", ctdbGetError(hRecord)); /* end the batch operation */ if (ctdbEndBatch(hRecord) != CTDBRET_OK) printf("ctdbEndBatch failed with error %d\n", ctdbGetError(hRecord));
SEE ALSO
ctdbBatchLoaded(), ctdbBatchLocked(), ctdbBatchMode(), ctdbBatchTotal(), ctdbInsertBatch(), ctdbIsBatchActive(), ctdbNextBatch(), ctdbSetBatch()
www.faircom.com
All Rights Reserved
305
ctdbEstimateSpan
Estimate an approximate number of records between two key target values.
Declaration
LONG ctdbEstimateSpan(CTHANDLE Handle, pVOID key1, pVOID key2);
Description
Handle is a record handle. key1 and key2 are two key target values used to obtain the estimated number of records. If ctdbEstimateSpan() returns 0, use ctdbGetError() function to retrieve the error code. If ctdbEstimateSpan() returns 0 and ctdbGetError() returns CTDBRET_OK then there are no records between the two key values supplied. The estimation is based on the record handle current index. The current index may be changed by calling ctdbSetDefaultIndex(). The table must have at least one index to be able to use this function. ctdbEstimateSpan(), which is based on c-tree low level function EstimateKeySpan(), does not traverse the index to compute the values. Instead, it makes about ten calls to the c-tree low level function KeyAtPercentile() to determine the relative location of the target values. The key target values used by ctdbEstimateSpan() can be created using ctdbBuildTargetKey().
Return
ctdbEstimateSpan() returns an estimate of the number of records between key1 and key2. Call ctdbGetError() to retrieve the error code. See "c-treeDB Errors and Return Values" for a complete listing of valid c-treeDB error codes and return values.
Example
Suppose that a student table has two fields (Name - CT_FSTRING and Age - CT_INT2) and one index on field Age. The sample function estimate the number of students with ages between 10 and 12:
LONG EstimateStudents(CTHANDLE hRecord) { TEXT key1[32]; TEXT key2[32]; /* build the first key for age = 10 years */ ctdbClearRecord(hRecord); ctdbSetFieldAsSigned(hRecord, 1, 10); if (ctdbBuildTargetKey(hRecord, CTFIND_EQ, key1, 32)) return 0; /* build the second key for age = 12 years */ ctdbClearRecord(hRecord); ctdbSetFieldAsSigned(hRecord, 1, 12); if (ctdbBuildTagetKey(hRecord, CTFIND_EQ, key2, 32)) return 0; /* estimate the number of students */ return ctdbEstimateSpan(hRecord, key1, key2); }
FairCom Corporation
306
See also
ctdbSetDefaultIndex(), ctdbBuildTargetKey()
www.faircom.com
All Rights Reserved
307
ctdbFilterRecord
Set the filtering logic for the table.
Declaration
CTDBRET ctdbFilterRecord(CTHANDLE Handle, pTEXT expr)
Description
ctdbFilterRecord() sets the filtering for a table. When set, all records retrieved from the table are filtered against the expression and only records matching this criteria will be returned. This feature is temporary and the effect is limited to the user who sets the filter. The filter is turned off when the table is closed, or when ctdbFilterRecord() is called with the record or table handle and NULL in the parameter expr. If a new expression is set to a table with a current filter, the old filter is replaced with the new one. Just one filter may be active per table per user. When used in the client/server model, this feature has the potential to increase the performance since only records matching the criteria will be returned, reducing the network traffic. ctdbGetFilter() may be used to retrieve the filter and ctdbIsFilteredRecordv() to verify if there is a filter in the table. Handle [in] the table or record handle. expr [in] the filtering expression. The valid expressions are given in the table below.
Expression int atoi( char* String ) int atol( char* String ) double atof( char* String ) int cabs( into Value ) int labs( into Value ) double fabs( double Value ) double ceil( double Value ) double floor( double Value ) double fmod( double r, double t ) int strlen( char* String ) int strcmp( char* s, char* t ) int stricmp( char* s, char* t ) int strncmp( char* s, char* t, int length ) int strnicmp( char* s, char *t, int length ) Explanation ASCII to integer. ASCII to long. ASCII to float. Calculate the absolute value of a complex number. Calculate the absolute value of a long integer. Calculate the absolute value of a float. Calculate the ceiling of a value. Calculate the floor of a value. Calculate the floating-point remainder. Get the length of a string. Compare strings. Compare strings without regard to case. Compare characters of two strings. Compare characters of two strings without regard to case.
If none of the above expressions is enough for the filtering logic the user would like to implement, there is yet a possibility of a user defined expression to be used. This so called callback routine is passed to the filter with an at sign (@) in the beginning of the expression. If this is done, what follows the @ is going to be the identifier to the user to handle in the routine ctfiltercb() (located in ctclbk.c). Notice, though, that this is considered an advanced feature since it will require the editing of one of c-tree Plus source files to insert the call to the user defined routine(s).
FairCom Corporation
308
Returns
ctdbFilterRecord() returns CTDBRET_OK on success, or the c-tree Plus error code on failure.
See also
ctdbGetFilter(), ctdbIsFilteredRecord(), ctdbRecordSetOn()
www.faircom.com
All Rights Reserved
309
ctdbFindActiveDatabase
Locate an active database by name.
Declaration
CTHANDLE ctdbFindActiveDatabase(CTHANDLE Handle, pTEXT Name)
Description
ctdbFindActiveDatabase() locates an active database by name, and returns its handle. To locate a database by the Unique Identifier, use ctdbFindActiveDatabaseByUID(). To locate a database by name, use ctdbFindDatabase(). Handle [in] the session handle. Name [in] the string with the database name to lookup in the session.
Returns
ctdbFindActiveDatabase() returns the database handle or NULL if not found.
See also
ctdbFindActiveDatabaseByUID(), ctdbFindDatabase()
FairCom Corporation
310
ctdbFindActiveDatabaseByUID
Locate an active database by its unique identifier.
Declaration
CTHANDLE ctdbFindActiveDatabaseByUID(CTHANDLE Handle, ULONG uid)
Description
ctdbFindActiveDatabaseByUID() locates a database in a session by its unique identifier, and returns its handle. Use ctdbFindActiveDatabase() to find an active database by name. Use ctdbGetDatabaseUID() to retrieve the database UID. Handle [in] session handle. uid [in] the unique database identifier, used to locate the database. It is set automatically when the database is created.
Returns
ctdbFindActiveDatabaseByUID() returns the database handle or NULL if not found.
See also
ctdbFindDatabaseByUID(), ctdbFindActiveDatabase(), ctdbGetDatabaseUID()
www.faircom.com
All Rights Reserved
311
ctdbFindActiveTable
Locate an active table by name.
Declaration
CTHANDLE ctdbFindActiveTable(CTHANDLE Handle, pTEXT Name)
Description
ctdbFindActiveTable() locates an active table by name, and return its handle. To locate a table by the Unique Identifier, use ctdbFindActiveTableByUID(). To retrieve the table handle of the first table, use ctdbGetFirstActiveTable(). To locate a table by name, and retrieve information like its path, use ctdbFindTable(). Handle [in] the database handle. Name [in] the string with the database name to lookup in the session.
Returns
ctdbFindActiveTable() returns the database handle or NULL if not found.
See also
ctdbFindActiveDatabaseByUID(), ctdbFindTable(), ctdbGetFirstActiveTable()
FairCom Corporation
312
ctdbFindActiveTableByUID
Locate an active table by its unique identifier.
Declaration
CTHANDLE ctdbFindActiveTableByUID(CTHANDLE Handle, ULONG uid)
Description
ctdbFindActiveTableByUID() locates a table in a database by its unique identifier, and returns its handle. Use ctdbFindActiveTable() to find an active table by name. Use ctdbFindTableByUID() to find a table by its Unique identifier. Handle [in] the database handle. uid [in] the unique table identifier, used to locate the table. It is set automatically when the table is created.
Returns
ctdbFindActiveTableByUID() returns the database handle or NULL if not found.
See also
ctdbFindTableByUID(), ctdbFindActiveTable(), ctdbGetDatabaseUID()
www.faircom.com
All Rights Reserved
313
ctdbFindDatabase
Locate a database by name.
Declaration
CTDBRET ctdbFindDatabase(CTHANDLE Handle, pTEXT Name, pTEXT Path, VRLEN PathSize)
Description
ctdbFindDatabase() locates a database by name. Use ctdbFindDatabaseByUID() to locate a database by its unique identifier. Use ctdbFindActiveDatabase() to find an active database by name. Handle [in] the session handle. Name [in] the string with the database name to lookup in the session. Path [out] receives the database path, if the name is located and it is large enough to hold the path. PathSize [in] the size in bytes of Path. If Path is not large enough to receive the database path, ctdbFindDatabase() will return CTDBRET_ARGSMALL (4006).
Returns
ctdbFindDatabase() returns CTDBRET_OK on success, or the c-tree Plus error code on failure.
Example
eRet = ctdbLogon(hSession, "FAIRCOMS", "ADMIN", "ADMIN"); eRet = ctdbFindDatabase(hSession, db_name, db_path, sizeof(db_path));
See also
ctdbFindDatabaseByUID(), ctdbFirstDatabase(), ctdbNextDatabase(), ctdbFindActiveDatabase()
FairCom Corporation
314
ctdbFindDatabaseByUID
Locate a database by its unique identifier.
Declaration
CTDBRET ctdbFindDatabaseByUID(CTHANDLE Handle, ULONG uid, pTEXT Name, VRLEN NameSize, pTEXT Path, VRLEN PathSize)
Description
ctdbFindDatabaseByUID() locates a database in a session by its unique identifier. Use ctdbFindDatabase() to find a database by name. Use ctdbGetDatabaseUID() to retrieve the database UID. Handle [in] the session handle. uid [in] the unique database identifier, used to locate the database. It is set automatically when the database is created. Name [out] the string with the database name. NameSize [in] the size in bytes of Name. If Name is not large enough to receive the database name, ctdbFindDatabaseByUID() will return CTDBRET_ARGSMALL (4006). Path [out] the database path, if the name is located and it is large enough to hold the path. The path includes drive, directory, file name and file extension. PathSize [in] the size in bytes of Path. If Path is not large enough to receive the database path, ctdbFindDatabaseByUID() will return CTDBRET_ARGSMALL (4006).
Returns
ctdbFindDatabaseByUID() returns CTDBRET_OK on success, or the c-tree Plus error code on failure.
See also
ctdbFindDatabase(), ctdbGetDatabaseUID()
www.faircom.com
All Rights Reserved
315
ctdbFindRecord
Find a record using the FindMode as the find strategy.
Declaration
CTDBRET ctdbFindRecord(CTHANDLE Handle, CTFIND_MODE FindMode)
Description
ctdbFindRecord() finds a record using the FindMode strategy. Handle [in] the record handle. FindMode [in] the mode to use to look for the record in the table. The find modes are listed in "c-treeDB definitions".. Before using ctdbFindRecord(), clear the record buffer with ctdbClearRecord() select the index to search with ctdbSetDefaultIndex() set search target values with one or more of the ctdbSetFieldAs() functions call ctdbFindRecord() Note: The FindMode CTFIND_EQ requires that the target contains values for all segments that compose the index and the index cannot allow duplicates. Use ctdbFirstRecord() to retrieve the first record on a table, ctdbNextRecord() to retrieve the next record on a table, ctdbPrevRecord() to retrieve the previous record on a table, and ctdbLastRecord() to retrieve the last record on a table. Use ctdbFindTarget() to find a record using a given target key.
Returns
ctdbFindRecord() returns CTDBRET_OK if the record was found or c-treeDB C API error on failure.
Example
ctdbClearRecord(hRec); ctdbSetDefaultIndex(hRec, 1); ctdbSetFieldAsString(hRec, ctdbGetFieldNumberByName(hRec, "Name"), name)); ctdbFindRecord(hRec, CTFIND_EQ);
See also
ctdbAllocRecord(), ctdbFirstRecord(), ctdbNextRecord(), ctdbPrevRecord(), ctdbLastRecord(), ctdbFindTarget(), ctdbClearRecord(), ctdbSetDefaultIndex()
FairCom Corporation
316
ctdbFindResource
Locate and retrieve a resource by type and number.
DECLARATION
CTDBRET ctdbDECL ctdbFindResource(CTHANDLE resource, ULONG type, ULONG number, CTBOOL lock)
DESCRIPTION
ctdbFindResource() locate and retrieve a resource in a table based on type and number. resource is a handle allocated with ctdbAllocHandle(). type and number identify the resource and lock is used to indicate if the resource should be locked, if it is found.
RETURN
ctdbFindResource() returns CTDBRET_OK on success. If there are no resources for the table, ctdbFirstResource() returns RNOT_ERR (408).
EXAMPLE
/* display a particular resource */ CTDBRET DisplayResource(CTHANDLE hTable, ULONG type, ULONG number) { CTDBRET eRet; CTHANDLE hRes = ctdbAllocResource(hTable, 0, 0, NULL); /* check if resource was allocated */ if (!hRes) return ctdbGetError(hTable); /* note that no resource locks are acquired since we are not changing the resources */ if ((eRet = ctdbFindResource(hRes, type, number, NO)) == CTDBRET_OK) { printf("Resource type: %u, number: %u", ctdbGetResourceType(hRes), ctdbGetResourceNumber(hRes)); if (ctdbGetResourceName(hRes) != NULL) printf(", name: \"\"\n", ctdbGetResourceName(hRes)); else printf(", name: NULL"\n"); } ctdbFreeResource(hRes); return eRet; }
SEE ALSO
ctdbAllocResource, ctdbFreeResource, ctdbAddResource, ctdbDeleteResource, ctdbUpdateResource, ctdbFirstResource, ctdbNextResource, ctdbFindResourceByName, ctdbGetResourceType, ctdbSetResourceType, ctdbGetResourceNumber, ctdbSetResourceNumber, ctdbGetResourceName, ctdbSetResourceName, ctdbGetResourceDataLength, ctdbGetResourceData, ctdbSetResourceData, ctdbIsResourceLocked, ctdbUnlockResource
www.faircom.com
All Rights Reserved
317
ctdbFindResourceByName
Locate and retrieve a resource by name.
DECLARATION
CTDBRET ctdbDECL ctdbFindResourceByName(CTHANDLE resource, pTEXT name, CTBOOL lock);
DESCRIPTION
ctdbFindResourceByName() locates and retrieves a resource by name. c-tree Plus cannot guarantee unique resource names. resource is a handle allocated with ctdbAllocHandle(). name is the resource name and lock is used to indicate if the resource should locked, if it is found.
RETURN
ctdbFindResourceByName() returns CTDBRET_OK on success. If there are no resources for the table, ctdbFirstResource() returns RNOT_ERR (408).
EXAMPLE
/* display a particular resource */ CTDBRET DisplayResource(CTHANDLE hTable, pTEXT name) { CTDBRET eRet; CTHANDLE hRes = ctdbAllocResource(hTable, 0, 0, NULL); /* check if resource was allocated */ if (!hRes) return ctdbGetError(hTable); /* note that no resource locks are acquired since we are not changing the resources */ if ((eRet = ctdbFindResourceByName(hRes, name, NO)) == CTDBRET_OK) { printf("Resource type: %u, number: %u", ctdbGetResourceType(hRes), ctdbGetResourceNumber(hRes)); if (ctdbGetResourceName(hRes) != NULL) printf(", name: \"\"\n", ctdbGetResourceName(hRes)); else printf(", name: NULL"\n"); } ctdbFreeResource(hRes); return eRet; }
SEE ALSO
ctdbAllocResource, ctdbFreeResource, ctdbAddResource, ctdbDeleteResource, ctdbUpdateResource, ctdbFirstResource, ctdbNextResource, ctdbFindResource, ctdbGetResourceType, ctdbSetResourceType, ctdbGetResourceNumber, ctdbSetResourceNumber, ctdbGetResourceName, ctdbSetResourceName, ctdbGetResourceDataLength, ctdbGetResourceData, ctdbSetResourceData, ctdbIsResourceLocked, ctdbUnlockResource
FairCom Corporation
318
ctdbFindRowid
Find a record based on its rowid.
Declaration
CTDBRET ctdbFindRowid(CTHANDLE Handle, CTROWID rowid, CTFIND_MODE FindMode)
Description
ctdbFindRowid() retrieves the record, given its rowid. Handle [in] the record handle. rowid [in] the rowid value. FindMode [in] the mode to use to look for the record in the table. The find modes are listed in "c-treeDB definitions".. Note: The FindMode CTFIND_EQ requires that the target contains values for all segments that compose the index and the index cannot allow duplicates.
Returns
ctdbFindRowid() returns CTDBRET_OK on success, or a c-treeDB C API error code on failure
See also
ctdbAllocRecord(), ctdbGetRowid(), ctdbHasRowid()
www.faircom.com
All Rights Reserved
319
ctdbFindTable
Find a table in a database dictionary.
Declaration
CTDBRET ctdbFindTable(CTHANDLE Handle, pTEXT Name, pTEXT Path, VRLEN PathSize)
Description
ctdbFindTable() finds a table in a database dictionary. Use ctdbFindTableByUID() to find a table by its unique identifier. Use ctdbFindActiveTable() to locate an active table by name, and return its handle. Handle [in] the database handle. Name [in] the string with the table name to lookup in the database. Path [out] receives the table path. PathSize [in] the path size in bytes. ctdbFirstTable() and ctdbNextTable() may be used to obtain the names of all tables available to this Database.
Returns
ctdbFindTable() returns CTDBRET_OK on success, or the c-tree Plus error code on failure.
Example
eRet=ctdbFindTable(hDbase, tb_name, tb_path, sizeof (tb_path));
See also
ctdbAllocDatabase(), ctdbFindTableByUID(), ctdbFirstTable(), ctdbNextTable()
FairCom Corporation
320
ctdbFindTableByUID
Locate a table in a database dictionary by its unique identifier.
Declaration
CTDBRET ctdbFindTableByUID(CTHANDLE Handle, ULONG uid, pTEXT Name, VRLEN NameSize, pTEXT Path, VRLEN PathSize)
Description
ctdbFindTableByUID() locates a table in a database dictionary by its unique identifier. Use ctdbFindTable() to find a table by name. Use ctdbGetTableUID() to retrieve the table UID. Handle [in] the database handle. uid [in] the unique table identifier, used to find the table. Name [out] the string with the table name. NameSize [in] the name size in bytes. If Name is not large enough to receive the table name, ctdbFindTableByUID() will return CTDBRET_ARGSMALL (4006). Path [out] the path of the table, if the table is located, and it is large enough to hold the path. The path includes drive, directory, name and extension. PathSize [in] the path size in bytes. If Path is not large enough to receive the table path, ctdbFindTableByUID() will return CTDBRET_ARGSMALL (4006).
Returns
ctdbFindTableByUID() returns CTDBRET_OK on success, or the c-tree Plus error code on failure.
See also
ctdbFindTable(), ctdbFirstTable(), ctdbNextTable(), ctdbGetTableUID()
www.faircom.com
All Rights Reserved
321
ctdbFindTarget
Find a record using a target key.
Declaration
CTDBRET ctdbFindTarget(CTHANDLE Handle, pVOID target, CTFIND_MODE FindMode)
Description
ctdbFindTarget() finds a record with a given target key. Use ctdbFindRecord() to find a record with the FindMode() strategy. Handle [in] the record handle. target [in] string with the key target to lookup in the table. FindMode [in] the mode to use to look for the record in the table. The find modes are listed in "c-treeDB definitions".. Note: The Find Mode CTFIND_EQ requires that the target contains values for all segments that compose the index and the index cannot allow duplicates. Note: Keep in mind that the key target in FindTarget() must not be transformed. When using functions such as TransformKey() or BuildTargetKe()y, you must supress the transformation of the already-transformed key. In order to do this, you may define a macro NOTRANSFORM with a value of 0x1000 and OR it into the mode passed to FindTarget().
Returns
ctdbFindTarget() returns CTDBRET_OK if the record was found, or c-treeDB C API error on failure.
See also
ctdbAllocRecord(), ctdbFindRecord()
FairCom Corporation
322
ctdbFirstDatabase
Get the first database that belongs to this session.
Declaration
CTDBRET ctdbFirstDatabase(CTHANDLE Handle, pTEXT Name, VRLEN NameSize, pTEXT Path, VRLEN PathSize)
Description
ctdbFirstDatabase() gets the first database that belongs to the associated session. Handle [in] the a session handle. Name [out] receives the database name. NameSize [in] the name size in bytes. If Name is not large enough to receive the database name, ctdbFirstDatabase() will return CTDBRET_ARGSMALL (4006). Path [out] receives the database path, if the name is located and it is large enough to hold the path, and is returned by the function ctdbFirstDatabase(). PathSize [in] the path size in bytes. If Path is not large enough to receive the database path, ctdbFirstDatabase() will return CTDBRET_ARGSMALL (4006). ctdbFirstDatabase(), in conjunction with ctdbNextDatabase(), may be used to obtain the names of all Databases available to this Session. ctdbGetDatabaseCount() may be used to retrieve the total number of databases in the session.
Returns
ctdbFirstDatabase() returns CTDBRET_OK on success, or the c-tree Plus error code on failure.
Example
ctdbFirstDatabase(hSession, name, sizeof(name), path, sizeof(path)); do { printf("\n\nDatabase: %s (%s)\n", path, name); } while ( ctdbNextDatabase(hSession, name, sizeof(name), path, sizeof(path)) == CTDBRET_OK );
See also
ctdbNextDatabase(), ctdbGetDatabaseCount(), ctdbFindDatabase(), ctdbFirstTable()
www.faircom.com
All Rights Reserved
323
ctdbFirstRecord
Get the first record on a table
Declaration
CTDBRET ctdbFirstRecord(CTHANDLE Handle)
Description
ctdbFirstRecord() retrieves the first record on a table. The ordering of the records is done through one of the indices that was defined during the table creation. In order to define which index is sorting the table, use ctdbSetDefaultIndex(). Initially, the default index is the first defined index during the table creation. Handle [in] the record handle. If sets are enabled by ctdbRecordSetOn(), ctdbFirstRecord() will retrieve the first record in the set. Use ctdbNextRecord() to retrieve the next record on a table, ctdbPrevRecord() to retrieve the previous record on a table, and ctdbLastRecord() to retrieve the last record on a table. Use ctdbFindRecord() to find a specific record on a table.
Returns
ctdbFirstRecord() returns CTDBRET_OK on success, or c-treeDB C API error on failure.
See also
ctdbAllocRecord(), ctdbNextRecord(), ctdbPrevRecord(), ctdbLastRecord(), ctdbFindRecord(), ctdbRecordSetOn(), ctdbSetDefaultIndex()
FairCom Corporation
324
ctdbFirstResource
Locate and retrieve the first resource in a table.
DECLARATION
CTDBRET ctdbDECL ctdbFirstResource(CTHANDLE resource, CTBOOL lock);
DESCRIPTION
ctdbFirstResource() retrieve the first resource stored in a table. resource is a handle allocated with ctdbAllocHandle(). lock is used to indicate if the resource should be locked, if it is found.
RETURN
ctdbFirstResource() returns CTDBRET_OK on success. If there are no resources for the table, ctdbFirstResource() return RNOT_ERR (408).
EXAMPLE
CTDBRET DisplayAllResources(CTHANDLE hTable) { CTDBRET eRet; CTHANDLE hRes = ctdbAllocResource(hTable, 0, 0, NULL); /* check if resource was allocated */ if (!hRes) return ctdbGetError(hTable); /* get the first resource */ /* note that no resource locks are acquired since we are not changing the resources */ if ((eRet = ctdbFirstResource(hRes, false)) != CTDBRET_OK) { ctdbFreeResource(hRes); return eRet; } /* get the other resources */ do { /* display resource type, number and name */ printf("Resource type: %u, number: %u", ctdbGetResourceType(hRes), ctdbGetResourceNumber(hRes)); if (ctdbGetResourceName(hRes) != NULL) printf(", name: \"\"\n", ctdbGetResourceName(hRes)); else printf(", name: NULL"\n"); } while ((eRet = ctdbNextResource(hRes, false)) != CTDBRET_OK); ctdbFreeResource(hRes); return eRet; }
SEE ALSO
ctdbAllocResource, ctdbFreeResource, ctdbAddResource, ctdbDeleteResource, ctdbUpdateResource, ctdbNextResource, ctdbFindResource, ctdbFindResourceByName, ctdbGetResourceType, ctdbSetResourceType, ctdbGetResourceNumber, ctdbSetResourceNumber, ctdbGetResourceName, ctdbSetResourceName, ctdbGetResourceDataLength, ctdbGetResourceData, ctdbSetResourceData, ctdbIsResourceLocked, ctdbUnlockResource
www.faircom.com
All Rights Reserved
325
ctdbAllocResource
Allocates a new resource handle.
DECLARATION
CTHANDLE ctdbDECL ctdbAllocResource(CTHANDLE Handle, ULONG type, ULONG number, pTEXT name);
DESCRIPTION
Allocate a new resource handle. Before any operations can be performed on resources, you are required to allocate a resource handle. Resource handles are opaque handles whose contents are not available to the developer. You must use the set of functions provided by c-treeDB to set and get properties and to perform operations. Handle is a c-treeDB table handle. type is the resource type. If the resource type is unknown you may set this parameter to zero. number is the resource number. If the resource number is unknown you may set this parameter to zero. name is the resource name. If you do not know this value in advance, you can set this parameter with a NULL or empty string ().
RETURN
ctdbAllocResource() returns the resource handle on success. Returns NULL if ctdbAllocResource() fails to allocate handle, in which case you should call ctdbGetError() passing the table Handle to obtain the error code.
EXAMPLE
CTDBRET DisplayAllResources(CTHANDLE hTable) { CTDBRET eRet; CTHANDLE hRes = ctdbAllocResource(hTable, 0, 0, NULL); /* check if resource was allocated */ if (!hRes) return ctdbGetError(hTable); /* get the first resource */ /* note that no resource locks are acquired since we are not changing the resources */ if ((eRet = ctdbFirstResource(hRes, false)) != CTDBRET_OK) { ctdbFreeResource(hRes); return eRet; } /* get the other resources */ do { /* display resource type, number and name */ printf("Resource type: %u, number: %u", ctdbGetResourceType(hRes), ctdbGetResourceNumber(hRes)); if (ctdbGetResourceName(hRes) != NULL) printf(", name: \"\"\n", ctdbGetResourceName(hRes)); else printf(", name: NULL"\n"); } while ((eRet = ctdbNextResource(hRes, false)) != CTDBRET_OK); ctdbFreeResource(hRes); return eRet; }
FairCom Corporation
326
SEE ALSO
ctdbFreeResource(), ctdbAddResource(), ctdbDeleteResource(), ctdbUpdateResource(), ctdbFirstResource(), ctdbNextResource(), ctdbFindResource(), ctdbFindResourceByName(), ctdbGetResourceType(), ctdbSetResourceType(), ctdbGetResourceNumber(), ctdbSetResourceNumber(), ctdbGetResourceName(), ctdbSetResourceName(), ctdbGetResourceDataLength(), ctdbGetResourceData(), ctdbSetResourceData(), ctdbIsResourceLocked(), ctdbUnlockResource()
www.faircom.com
All Rights Reserved
327
ctdbFirstTable
Get the first table in a database dictionary.
Declaration
CTDBRET ctdbFirstTable(CTHANDLE Handle, pTEXT Name, VRLEN NameSize, pTEXT Path, VRLEN PathSize)
Description
ctdbFirstTable() gets the first table in a database dictionary. Handle [in] the database handle. Name [out] receives the table name. NameSize [in] the Name size in bytes. Path [out] receives the table path. PathSize [in] the Path size in bytes. ctdbFirstTable(), in conjunction with ctdbNextTable(), may be used to obtain the names of all tables available to this Database. ctdbGetTableCount() may be used to retrieve the total number of tables in the database.
Returns
ctdbFirstTable() returns CTDBRET_OK on success, or the c-tree Plus error code on failure.
Example
ctdbFirstTable(hDB, t_name, sizeof(t_name), t_path, sizeof (t_path)); do { printf(\ntable name: %s, t_name); } while (ctdbNextTable(hDB, t_name, sizeof(t_name), t_path, sizeof(t_path)) == CTDBRET_OK);
See also
ctdbFirstDatabase(), ctdbNextTable(), ctdbFindTable(), ctdbGetTableCount()
FairCom Corporation
328
ctdbFloatToBigInt
Convert a float to a big integer value.
Declaration
CTDBRET ctdbFloatToBigInt(CTFLOAT value, pCTBIGINT pBigInt)
Description
ctdbFloatToBigInt() converts a float to a big integer value. A big integer is an 8 bytes integer value. Use ctdbBigIntToFloat() to convert from a big integer to a float. value [in] the float value. pBigInt [out] the big integer value (8 bytes signed integer).
Returns
ctdbFloatToBigInt() returns CTDBRET_OK on success, or c-treeDB C API error on failure. The possible error associated with ctdbFloatToBigInt() is: CTDBRET_NULARG (4007): Null argument not valid in pStr
See also
ctdbBigIntToFloat()
www.faircom.com
All Rights Reserved
329
ctdbFloatToCurrency
Convert a float value to a CTCURRENCY value.
Declaration
CTDBRET ctdbFloatToCurrency(CTFLOAT value, pCTCURRENCY pCurrency)
Description
ctdbFloatToCurrency() converts a floating point value to a CTCURRENCY (8 bytes signed integer) value. Use ctdbCurrencyToFloat() to convert from a float to a CTCURRENCY value. value [in] the CTFLOAT value. pCurrency [out] the CTCURRENCY value (8 bytes integer).
Returns
ctdbFloatToCurrency() returns CTDBRET_OK on success, or c-treeDB C API error on failure. The possible error associated with ctdbFloatToCurrency() is: CTDBRET_NULARG (4007): Null argument not valid in pStr
See also
ctdbCurrencyToFloat()
FairCom Corporation
330
ctdbFloatToMoney
Converts a floating point value to a CTMONEY type
Declaration
CTDBRET ctdbFloatToMoney(CTFLOAT value, pCTMONEY pMoney)
Description
ctdbFloatToMoney() converts from a floating point number to CTMONEY. Use ctdbMoneyToFloat() to convert a CTMONEY value to a floating point number. value [in] the floating point value to convert. pMoney [out] the pointer to the CTMONEY value.
Returns
ctdbFloatToMoney() returns CTDBRET_OK on success, or c-treeDB C API error on failure. The possible errors associated with ctdbFloatToMoney() are: CTDBRET_NULARG (4007): Null argument not valid in pStr CTDBRET_OVERFLOW (4038): Operation caused overflow
See also
ctdbMoneyToFloat()
www.faircom.com
All Rights Reserved
331
ctdbFloatToNumber
Convert a float to a CTNUMBER value.
Declaration
CTDBRET ctdbFloatToNumber(CTFLOAT value, pCTNUMBER pNumber)
Description
ctdbFloatToNumber() converts a floating point value to a CTNUMBER value. Use ctdbNumberToFloat() to convert a CTNUMBER to float. value [in] the float value. pNumber [out] pointer to CTNUMBER.
Returns
ctdbFloatToNumber() returns CTDBRET_OK on success, or c-treeDB C API error on failure. The possible error associated with ctdbFloatToNumber() is: CTDBRET_NULARG (4007): Null argument not valid in pNumber
See also
ctdbNumberToFloat()
FairCom Corporation
332
ctdbFreeDatabase
Release all resources associated with a database handle
Declaration
void ctdbFreeDatabase(CTHANDLE Handle)
Description
ctdbFreeDatabase() releases all resources associated with a database. After a call to ctdbFreeDatabase(), the database handle cannot be used for other operations. For each ctdbAllocDatabase() call, there must be a ctdbFreeDatabase() call. Handle [in] the database handle.
Returns
None.
Example
CTHANDLE hDatabase = ctdbAllocDatabase(hSession); ctdbCreateDatabase(hDatabase, "Database1", ""); ctdbFreeDatabase(hDatabase); // the handle cannot be used anymore
See also
ctdbAllocDatabase(), ctdbFreeSession()
www.faircom.com
All Rights Reserved
333
ctdbFreeRecord
Release resources allocated for the record handle.
Declaration
void ctdbFreeRecord(CTHANDLE Handle)
Description
ctdbFreeRecord() releases resources allocated for the record handle. Any record allocated with ctdbAllocRecord() should be released with a call to ctdbFreeRecord(). After a call to ctdbFreeRecord(), the record handle cannot be used for other operations. Handle [in] the record handle.
Returns
None.
See also
ctdbAllocRecord(), ctdbFreeTable()
FairCom Corporation
334
ctdbFreeResource
Release memory and system resources allocated by ctdbAllocResource().
DECLARATION
CTDBRET ctdbDECL ctdbFreeResource(CTHANDLE resource)
DESCRIPTION
Release system resources allocated by ctdbAllocResource(). resource is a resource handle allocated by ctdbAllocResource().
RETURN
ctdbFreeResource() returns CTDBRET_OK on success or CTDBRET_NOTRESOURCE error if the handle passed to ctdbFreeResource() was not allocated by ctdbAllocResource() or is invalid.
EXAMPLE
CTDBRET DisplayAllResources(CTHANDLE hTable) { CTDBRET eRet; CTHANDLE hRes = ctdbAllocResource(hTable, 0, 0, NULL); /* check if resource was allocated */ if (!hRes) return ctdbGetError(hTable); /* get the first resource */ /* note that no resource locks are acquired since we are not changing the resources */ if ((eRet = ctdbFirstResource(hRes, false)) != CTDBRET_OK) { ctdbFreeResource(hRes); return eRet; } /* get the other resources */ do { /* display resource type, number and name */ printf("Resource type: %u, number: %u", ctdbGetResourceType(hRes), ctdbGetResourceNumber(hRes)); if (ctdbGetResourceName(hRes) != NULL) printf(", name: \"\"\n", ctdbGetResourceName(hRes)); else printf(", name: NULL"\n"); } while ((eRet = ctdbNextResource(hRes, false)) != CTDBRET_OK); ctdbFreeResource(hRes); return eRet; }
SEE ALSO
ctdbAllocResource, ctdbAddResource, ctdbDeleteResource, ctdbUpdateResource, ctdbFirstResource, ctdbNextResource, ctdbFindResource, ctdbFindResourceByName, ctdbGetResourceType, ctdbSetResourceType, ctdbGetResourceNumber, ctdbSetResourceNumber, ctdbGetResourceName, ctdbSetResourceName, ctdbGetResourceDataLength, ctdbGetResourceData, ctdbSetResourceData, ctdbIsResourceLocked, ctdbUnlockResource
www.faircom.com
All Rights Reserved
335
ctdbFreeSession
Release all resources associated with a session
Declaration
void ctdbFreeSession(CTHANDLE Handle)
Description
ctdbFreeSession() releases all resources associated with a session and must be called at application close to free all resources allocated with ctdbAllocSession(). After a call to ctdbFreeSession(), the session handle cannot be used for other operations. For each ctdbAllocSession() call, there must be ctdbFreeSession(). Handle [in] the session handle.
Returns
None.
Example
CTSESSION_TYPE ctdbsess=CTSESSION_CTDB; CTHANDLE handle = ctdbAllocSession(ctdbsess); ctdbCreateSession(handle, "FAIRCOMS", "ADMIN", "ADMIN"); ctdbFreeSession(handle);
See also
ctdbAllocSession(), ctdbFreeDatabase()
FairCom Corporation
336
ctdbFreeTable
Release resources allocated for the table handle.
Declaration
void ctdbFreeTable(CTHANDLE Handle)
Description
ctdbFreeTable() releases all resources associated with a table. After a call to ctdbFreeTable(), the table handle cannot be used for other operations. Handle [in] the Table Handle.
Returns
None.
Example
ctdbClose(hTable); ctdbFreeTable(hTable);
See also
ctdbAllocTable(), ctdbFreeDatabase()
www.faircom.com
All Rights Reserved
337
ctdbGetActiveDatabaseUID
Retrieve the database UID.
Declaration
CTDBRET ctdbGetActiveDatabaseUID(CTHANDLE Handle, pULONG puid)
Description
ctdbGetActiveDatabaseUID() retrieves the database Unique Identifier, UID, given the Database Handle. Use ctdbGetDatabaseUID() to retrieve the database UID, given the database name. Use ctdbFindDatabaseByUID() to locate a database in a session by its unique identifier. Handle [in] the Database Handle. puid [out] the database UID.
Returns
ctdbGetActiveDatabaseUID() returns CTDBRET_OK on success, or c-treeDB C API error on failure.
See also
ctdbAllocDatabase(), ctdbFindDatabaseByUID(), ctdbGetDatabaseUID()
FairCom Corporation
338
ctdbGetActiveTableByUID
Retrieve the active table handle given its UID.
Declaration
CTHANDLE ctdbGetActiveTableByUID(CTHANDLE Handle, ULONG uid)
Description
ctdbGetActiveTableByUID() retrieves the active table handle given its UID. Use ctdbGetActiveTableUID() to retrieve the table UID, given the table Handle. Handle [in] the Table Handle. uid [in] the table unique identifier number.
Returns
ctdbGetActiveTableByUID() returns the table Handle on success, or NULL on failure.
See also
ctdbGetActiveTableUID()
www.faircom.com
All Rights Reserved
339
ctdbGetActiveTableUID
Retrieve the table uid.
Declaration
CTDBRET ctdbGetActiveTableUID(CTHANDLE Handle, pULONG puid)
Description
ctdbGetActiveTableUID() retrieves the table UID, given the Table Handle. Use ctdbGetTableUID() to retrieve the table UID, given the table name. Use ctdbFindTableByUID() to locate a table in a database by its unique identifier. Handle [in] the Table Handle. puid [out] the table unique identifier.
Returns
ctdbGetActiveTableUID() returns CTDBRET_OK on success, or c-treeDB C API error on failure.
See also
ctdbAllocTable(), ctdbFindTableByUID(), ctdbGetTableUID()
FairCom Corporation
340
ctdbGetAttachMode
Declaration
CTATTACH_MODE ctdbDECL ctdbGetAttachMode(CTHANDLE Handle);
Description
Retrieve the current session attach mode. ctdbGetAttachMode() will not execute a c-tree instance switch. Handle is a session handle.
Return Values
One of the following values is returned:
Returned CTATTACH mode Description Handle or Session object is not attached, or Handle not a valid session handle. Handle or Session object is attached to a c-treeDB session. Handle or Session object is attached to a c-tree instance id. Handle or Session object was attached to current c-tree instance.
See Also
ctdbAttachSession(), ctdbDetachSession()
www.faircom.com
All Rights Reserved
341
ctdbGetAutoCommit
Declaration
CTBOOL ctdbDECL ctdbGetAutoCommit(CTHANDLE Handle);
Description
ctdbGetAutoCommit() retrieves the c-treeDB auto commit mode. The auto commit of transactions are invoked automatically when records are added or updated by ctdbWriteRecord() call. Handle must be a session handle.
Return Values
Value 0 1 Symbolic Constant Explanation auto commit is enabled. auto commit is not enabled.
YES NO
See Also
ctdbSetAutoCommit() ctdbSetOperationState() ctdbGetOperationState()
FairCom Corporation
342
ctdbGetCallback
Retrieves the callback function pointer associate with the callback type.
DECLARATION
ctdbCallbackFunction ctdbGetCallback(CTHANDLE Handle, CTDB_CALLBACK_TYPE CallBackType)
DESCRIPTION
Handle is a valid c-treeDB session, database, table or record handle. CallBackType is one of the valid callback types. You can check if a given callback has been registered with a session, database, table or record handle by calling the ctdbGetCallback() function. If a callback function was set, ctdbGetCallback() returns the address of the function. If a particular callback is not set, ctdbGetCallback() returns NULL.
RETURN
Returns the function pointer, or NULL if the callback was not registered.
EXAMPLE
/* allocate a table handle */ CTHANDLE hTable = ctdbAllocTable(hDatabase); /* make sure CTDB_ON_TABLE_OPEN callback is set */ if (ctdbGetCallback(hTable, CTDB_ON_TABLE_OPEN) == NULL) if (ctdbSetCallback(hTable, CTDB_ON_TABLE_OPEN, OnTableOpen) != CTDBRET_OK) printf("ctdbSetCallback failed\n");
SEE ALSO
ctdbClearAllCallback(), ctdbClearCallback(), ctdbSetCallback()
www.faircom.com
All Rights Reserved
343
ctdbGetCndxIndex
Retrieve the conditional index expression string, given the index number.
Declaration
CTDBRET ctdbGetCndxIndex(CTHANDLE Handle, NINT indexnbr, pTEXT buffer, NINT bufferlen)
Description
ctdbGetCndxIndex() retrieves the conditional index expression string, given the index number. The conditional expression is added, deleted or updated with ctdbUpdateCndxIndex() or ctdbUpdateCndxIndexByName(). Handle [in] the Table Handle. indexnbr [in] the index number. buffer [OUT] pointer to buffer to receive the conditional expression. bufferlen [IN] size in bytes of buffer. Maybe retrieved with ctdbGetCndxIndexLength() or ctdbGetCndxIndexLengthByName().
Returns
ctdbGetCndxIndex() returns CTDBRET_OK on success, or c-treeDB C API error on failure.
See also
ctdbUpdateCndxIndex(), ctdbUpdateCndxIndexByName(), ctdbGetCndxIndexLength(), ctdbGetCndxIndexLengthByName()
FairCom Corporation
344
ctdbGetCndxIndexByName
Retrieve the conditional index expression string, given the index name.
Declaration
CTDBRET ctdbGetCndxIndexByName(CTHANDLE Handle, pTEXT indexname, pTEXT buffer, NINT bufferlen)
Description
ctdbGetCndxIndexByName() retrieves the conditional index expression string, given the index name. The conditional expression is added, deleted or updated with ctdbUpdateCndxIndex() or ctdbUpdateCndxIndexByName(). Handle [in] the Table Handle. indexname [in] the index name. buffer [OUT] pointer to buffer to receive the conditional expression. bufferlen [IN] size in bytes of buffer. Maybe retrieved with ctdbGetCndxIndexLength() or ctdbGetCndxIndexLengthByName().
Returns
ctdbGetCndxIndexByName() returns CTDBRET_OK on success, or c-treeDB C API error on failure.
See also
ctdbGetCndxIndex(), ctdbUpdateCndxIndex(), ctdbUpdateCndxIndexByName(), ctdbGetCndxIndexLength(), ctdbGetCndxIndexLengthByName()
www.faircom.com
All Rights Reserved
345
ctdbGetCndxIndexLength
Retrieve the length in bytes of the conditional expression string, given the index number.
Declaration
NINT ctdbGetCndxIndexLength(CTHANDLE Handle, NINT indexnbr)
Description
ctdbGetCndxIndexLength() retrieves the length in bytes of the conditional expression string, given the index number. To retrieve the conditional expression, use ctdbGetCndxIndex() or ctdbGetCndxIndexByName(). The conditional expression is added, deleted or updated with ctdbUpdateCndxIndex() or ctdbUpdateCndxIndexByName(). Handle [in] the Table Handle. indexnbr [in] the index number.
Returns
ctdbGetCndxIndexLength() returns the conditional index lengh in bytes on success or -1 on failure.
See also
ctdbGetCndxIndexLengthByName(), ctdbUpdateCndxIndex(), ctdbUpdateCndxIndexByName()
FairCom Corporation
346
ctdbGetCndxIndexLengthByName
Retrieve the length in bytes of the conditional expression string, given the index name.
Declaration
NINT ctdbGetCndxIndexLengthByName(CTHANDLE Handle, pTEXT indexname)
Description
ctdbGetCndxIndexLengthByName() retrieves the length in bytes of the conditional expression string, given the index name. To retrieve the conditional expression, use ctdbGetCndxIndex() or ctdbGetCndxIndexByName(). The conditional expression is added, deleted or updated with ctdbUpdateCndxIndex() or ctdbUpdateCndxIndexByName(). Handle [in] the Table Handle. indexname [in] the index name.
Returns
ctdbGetCndxIndexLengthByName() returns the conditional index length in bytes on success or -1 on failure.
See also
ctdbGetCndxIndexLength(), ctdbUpdateCndxIndex(), ctdbUpdateCndxIndexByName()
www.faircom.com
All Rights Reserved
347
ctdbGetDatabaseCount
Retrieve the number of databases in the session dictionary.
Declaration
NINT ctdbGetDatabaseCount(CTHANDLE Handle)
Description
ctdbGetDatabaseCount() returns the number of databases in the session dictionary. Handle [in] the session handle.
Returns
ctdbGetDatabaseCount() returns the number of databases in the session dictionary, or -1 on error.
See also
ctdbGetTableCount()
FairCom Corporation
348
ctdbGetDatabaseHandle
Return the database handle.
Declaration
CTHANDLE ctdbGetDatabaseHandle(CTHANDLE Handle)
Description
ctdbGetDatabaseHandle() returns the database handle. To allocate a database handle, use ctdbAllocDatabase(). Handle [in] may be a table handle, a record handle, a field handle, an index handle, or a segment handle.
Returns
ctdbGetDatabaseHandle() returns the database handle or NULL on failure.
Example
db_name = ctdbGetDatabaseName(ctdbGetDatabaseHandle(hTable));
See also
ctdbAllocDatabase(), ctdbGetSessionHandle(), ctdbGetTableHandle()
www.faircom.com
All Rights Reserved
349
ctdbGetDatabaseName
Return the database name.
Declaration
pTEXT ctdbGetDatabaseName(CTHANDLE Handle)
Description
ctdbGetDatabaseName() returns the database name. Handle [in] the Database Handle.
Returns
ctdbGetDatabaseName() returns the database name, or NULL on error.
Example
db_name = ctdbGetDatabaseName(ctdbGetDatabaseHandle(hTable));
See also
ctdbAllocDatabase(), ctdbGetDatabasePath()
FairCom Corporation
350
ctdbGetDatabasePath
Return the database path.
Declaration
pTEXT ctdbGetDatabasePath(CTHANDLE Handle)
Description
ctdbGetDatabasePath() returns the database path. Handle [in] the Database Handle.
Records
ctdbGetDatabasePath() returns the database path, or NULL if no database path is available.
Example
eRet=ctdbConnect(hDatabase, myDatabase, ); db_path=ctdbGetDatabasePath(hDatabase);
See also
ctdbAllocDatabase(), ctdbGetDatabaseName()
www.faircom.com
All Rights Reserved
351
ctdbGetDatabaseUID
Return the database handle.
Declaration
CTDBRET ctdbGetDatabaseUID(CTHANDLE Handle, pTEXT Name, pULONG puid)
Description
ctdbGetDatabaseUID() returns the database unique identifier, UID, given the database name. Use ctdbGetActiveDatabaseUID() to retrieve the database UID, given the Database Handle. Use ctdbFindDatabaseByUID() to locate a database in a session by its unique identifier. Handle [in] the session handle, and it is. Name [in] the database name. pUid [out] the database unique identifier.
Returns
ctdbGetDatabaseUID() returns CTDBRET_OK on success, or c-treeDB C API error on failure.
See also
ctdbAllocSession(), ctdbFindDatabaseByUID(), ctdbGetActiveDatabaseUID()
FairCom Corporation
352
ctdbGetDatno
Retrieve the table data file number.
DECLARATION
NINT ctdbGetDatno(CTHANDLE Handle)
DESCRIPTION
Retrieves the table data file number. Handle must be a table handle, or a handle that can be converted into a table handle such as a record, segment, index or field handle. Return the table datno on success or -1 on failure. If ctdbGetDatno() returns -1, the error code can be retrieved by calling the ctdbGetError() function.
RETURN
Value 0 -1 Symbolic Constant NO_ERROR Explanation No error occurred.
ctdbGetDatno() failed. You can retrieve the error code by calling ctdbGetError() function.
See Appendix A for a complete listing of valid c-tree Plus error values.
EXAMPLE
CTDBRET DeleteTable(CTHANDLE hSession, pTEXT tablename) { CTDBRET Retval = CTDBRET_OK; CTHANDLE hTable = ctdbAllocTable(hSession); if (hTable) { /* open the table exclusive */ if ((Retval = ctdbOpenTable(hTable, tablename, CTOPEN_EXCLUSIVE)) != CTDBRET_OK) return Retval; /* delete a file */ if ((Retval = (CTDBRET)DeleteRFile((COUNT)ctdbGetDatno(hTable)) != CTDBRET_OK) return Retval; } else Retval = CTDBRET_NOMEMORY; return Retval; }
SEE ALSO
ctdbSwitchInstance(), ctdbSwitchContext(), ctdbGetIdxno(), ctdbGetIdxnoByName(), ctdbGetIdxnoByNumber(), ctdbGetError()
www.faircom.com
All Rights Reserved
353
ctdbGetDay
Retrieve the day of the month from a packed CTDATE.
Declaration
NINT ctdbGetDay(CTDATE date)
Description
ctdbGetDay() retrieves the day of the month from as packed CTDATE. To retrieve the month from a packed CTDATE, use ctdbGetMonth(). To retrieve the year from a packed CTDATE, use ctdbGetYear(). To retrieve the day of the week from a packed CTDATE, use ctdbDayOfWeek(). date is the date in CTDATE format.
Returns
ctdbGetDay() returns the day of the month on success or 0 on error.
See also
ctdbGetMonth(), ctdbGetYear(), ctdbDayOfWeek()
FairCom Corporation
354
ctdbGetDefaultIndex
Return the current default index.
Declaration
NINT ctdbGetDefaultIndex(CTHANDLE Handle)
Description
ctdbGetDefaultIndex() returns the current default index number. When the record handle is initialized for the first time, the default index is set to zero. To retrieve the index name, use ctdbGetDefaultIndexName(). Use ctdbSetDefaultIndex() to set the default index for the table. Handle [in] the record handle.
Returns
ctdbGetDefaultIndex() returns the table default index, or -1 on error.
See also
ctdbAllocRecord(), ctdbGetTableIndexCount(), ctdbSetDefaultIndex(), ctdbGetDefaultIndexName()
www.faircom.com
All Rights Reserved
355
ctdbGetDefaultIndexName
Return the default index name.
Declaration
pTEXT ctdbGetDefaultIndexName(CTHANDLE Handle)
Description
ctdbGetDefaultIndexName() retrieves the current default index name. When the record handle is initialized for the first time, the default index is set to zero. Handle [the] record handle.
Records
ctdbGetDefaultIndexName() returns the current default index name.
See also
ctdbAllocRecord(), ctdbGetDefaultIndex(), ctdbSetDefaultIndexByName()
FairCom Corporation
356
ctdbGetDefDateType
Retrieve the default date type.
Declaration
CTDATE_TYPE ctdbGetDefDateType(CTHANDLE Handle)
Description
ctdbGetDefDateType() retrieves the default date type for the present session. Use ctdbSetDefDateType() to define the default date type. Initially, the default is CTDATE_MDCY, indicating month, day, century, year (4 digits for the year). The possible date types are given in "c-treeDB definitions".. Handle [in] any c-treeDB Handle.
Returns
ctdbGetDefDateType() returns the default date type, or 0 on error.
See also
ctdbSetDefDateType()
www.faircom.com
All Rights Reserved
357
ctdbGetDefFloatFormat
Retrieve the default floating point format string
Declaration
pTEXT ctdbGetDefFloatFormat(CTHANDLE Handle)
Description
ctdbGetDefFloatFormat() retrieves the default floating point format string. Handle [in] any c-treeDB Handle.
Returns
ctdbGetDefFloatFormat() returns the string format to be used by sprintf() or sscanf().
See also
ctdbSetDefFloatFormat()
FairCom Corporation
358
ctdbGetDefTimeType
Retrieve the default time type.
Declaration
CTTIME_TYPE ctdbGetDefTimeType(CTHANDLE Handle)
Description
ctdbGetDefTimeType() retrieves the default time type for the present session. Initially, the default is CTTIME_HMP, indicating hour, minute and am/pm. The possible time types are given in "c-treeDB definitions".. Use ctdbSetDefTimeType() to define the default time type. Handle [in] any c-treeDB Handle.
Returns
ctdbGetDefTimeType() returns the default time type, or 0 on error.
See also
ctdbSetDefTimeType()
www.faircom.com
All Rights Reserved
359
ctdbGetError
Return the last error logged by any function in the c-treeDB C API.
Declaration
CTDBRET ctdbGetError(CTHANDLE Handle)
Description
ctdbGetError() returns the last error logged by any function in the c-treeDB C API. This function should only be called to check for errors if a c-treeDB C API function fails. In this situation, it does return the last error condition. Handle should be any Handle inside the Session (session handle, database handle, table handle, record handle, index handle, field handle or segment handle).
Returns
ctdbGetError() returns the last error logged by any function in the c-treeDB C API, or NULL on failure.
See also
ctdbAllocSession(), ctdbAllocDatabase(), ctdbAllocTable(), ctdbAllocRecord(), ctdbAllocField(), ctdbAllocIndex(), ctdbAllocSegment(), ctdbClearError(), ctdbSetError()
FairCom Corporation
360
ctdbGetErrorIndex
Declaration
NINT ctdbDECL ctdbGetErrorIndex(CTHANDLE Handle);
Description
Retrieves the index number that cause a record insert or record update operation to fail. This function should only be called after a ctdbWriteRecord() call fails. The error index number value is maintained until the next call to ctdbWriteRecord(). Handle must be a record handle
Return Values
A number from 0 to n to indicate which index caused the error. A value of 0 represents the first index, 1 represents the second index, and so on. If the index number can not be obtained, ctdbGetErrorIndex() returns -1.
See Also
ctdbWriteRecord()
www.faircom.com
All Rights Reserved
361
ctdbGetField
Retrieve a field handle from a table, based on the field number.
Declaration
CTHANDLE ctdbGetField(CTHANDLE Handle, NINT Index)
Description
ctdbGetField() retrieves a field handle from a table, based on the field number. To retrieve a field handle from a table, based on the field name, use ctdbGetFieldByName(). To retrieve the field number, use ctdbGetFieldNumber(). Handle [in] the Table Handle. Index [in] the field number that identifies the field in the table.
Returns
ctdbGetField() returns the field handle or NULL on error.
See also
ctdbAllocTable(), ctdbGetFieldByName(), ctdbGetFieldNumber()
FairCom Corporation
362
ctdbGetFieldAddress
Retrieve the field address in record buffer
Declaration
pVOID ctdbGetFieldAddress(CTHANDLE Handle, NINT FieldNbr)
Description
ctdbGetFieldAddress() retrieves the field address in record buffer. Handle [in] the record handle. FieldNbr [in] the field number.
Returns
ctdbGetFieldAddress() returns the field address.
See also
ctdbGetFieldOffset()
www.faircom.com
All Rights Reserved
363
ctdbGetFieldAsBigint
Retrieve field as big integer value.
Declaration
CTDBRET ctdbGetFieldAsBigint(CTHANDLE Handle, NINT FieldNbr, pCTBIGINT pValue)
Description
ctdbGetFieldAsBigint() retrieves field as big integer. Use ctdbSetFieldAsBigint() to set field as a big integer value. Handle [in] the record handle. FieldNbr [in] the field number to be retrieved. To retrieve the field number given the record handle, use ctdbGetFieldNumberByName(). pValue [out] the pointer to the big integer value.
Returns
ctdbGetFieldAsBigint() returns CTDBRET_OK if successful, or the c-tree Plus error code on failure.
See also
ctdbAllocRecord(), ctdbSetFieldAsBigint(), ctdbGetFieldAsBool(), ctdbGetFieldAsSigned(), ctdbGetFieldAsUnsigned(), ctdbGetFieldAsDate(), ctdbGetFieldAsTime(), ctdbGetFieldAsMoney(), ctdbGetFieldAsFloat(), ctdbGetFieldAsString(), ctdbGetFieldAsBlob(), ctdbSetFieldAsDateTime(), ctdbGetFieldNumber()
FairCom Corporation
364
ctdbGetFieldAsBinary
Retrieve field as binary value.
Declaration
CTDBRET ctdbGetFieldAsBinary(CTHANDLE Handle, NINT FieldNbr, pVOID pValue, VRLEN size)
Description
ctdbGetFieldAsBinary() retrieves field as binary. Any field may be retrieved as a binary value, and when this happens, no conversion is applied, and the binary value of the field is copied into the binary buffer. Use ctdbSetFieldAsBinary() to set field as a binary value. Handle [in] the record handle. FieldNbr [in] the field number to be retrieved. To retrieve the field number given the record handle, use ctdbGetFieldNumberByName(). pValue [out] the pointer to the binary value. size [in] pValue size in bytes.
Returns
ctdbGetFieldAsBinary() returns CTDBRET_OK if successful, or the c-tree Plus error code on failure.
See also
ctdbAllocRecord(), ctdbSetFieldAsBinary(), ctdbGetFieldAsBool(), ctdbGetFieldAsSigned(), ctdbGetFieldAsUnsigned(), ctdbGetFieldAsDate(), ctdbGetFieldAsTime(), ctdbGetFieldAsMoney(), ctdbGetFieldAsFloat(), ctdbGetFieldAsString(), ctdbGetFieldAsBlob(), ctdbSetFieldAsDateTime(), ctdbGetFieldNumber()
www.faircom.com
All Rights Reserved
365
ctdbGetFieldAsBlob
Retrieve field as blob value.
Declaration
CTDBRET ctdbGetFieldAsBlob(CTHANDLE Handle, NINT FieldNbr, pCTBLOB pValue)
Description
ctdbGetFieldAsBlob() retrieves field as a blob value. Any field may be retrieved as a CTBLOB, and when this happens, no conversion is applied, and the binary value of the field is copied into the binary buffer. Use ctdbSetFieldAsBlob() to set field as a CTBLOB value. Handle [in] the record handle. FieldNbr [in] the field number to be retrieved. To retrieve the field number given the record handle, use ctdbGetFieldNumberByName(). pValue [out] the pointer to the blob value.
Returns
ctdbGetFieldAsBlob() returns CTDBRET_OK if successful, or the c-tree Plus error code on failure.
See also
ctdbAllocRecord(), ctdbGetFieldAsBool(), ctdbGetFieldAsSigned(), ctdbGetFieldAsUnsigned(), ctdbGetFieldAsDate(), ctdbGetFieldAsTime(), ctdbGetFieldAsMoney(), ctdbGetFieldAsFloat(), ctdbGetFieldAsDateTime(), ctdbGetFieldAsString(), ctdbSetFieldAsBlob()
FairCom Corporation
366
ctdbGetFieldAsBool
Retrieve field as boolean value.
Declaration
CTDBRET ctdbGetFieldAsBool(CTHANDLE Handle, NINT FieldNbr, pCTBOOL pValue)
Description
ctdbGetFieldAsBool() retrieves field as boolean value. Use ctdbSetFieldAsBool() to set field as a CTBOOL value. Handle [in] the record handle. FieldNbr [in] the field number to be retrieved. To retrieve the field number given the record handle, use ctdbGetFieldNumberByName(). pValue [out] the pointer to the bool value.
Returns
ctdbGetFieldAsBool() returns CTDBRET_OK if successful, or the c-tree Plus error code on failure.
See also
ctdbAllocRecord(), ctdbGetFieldAsSigned(), ctdbGetFieldAsUnsigned(), ctdbGetFieldAsDate(), ctdbGetFieldAsTime(), ctdbGetFieldAsMoney(), ctdbGetFieldAsFloat(), ctdbGetFieldAsDateTime(), ctdbGetFieldAsString(), ctdbGetFieldAsBlob(), ctdbSetFieldAsBool(), ctdbGetFieldNumber()
www.faircom.com
All Rights Reserved
367
ctdbGetFieldAsCurrency
Retrieve field as a currency value.
Declaration
CTDBRET ctdbGetFieldAsCurrency(CTHANDLE Handle, NINT FieldNbr, pCTCURRENCY pValue)
Description
ctdbGetFieldAsCurrency() retrieves field as currency value. Use ctdbSetFieldAsCurrency() to set field as a currency value. Handle [in] the record handle. FieldNbr [in] the field number to be retrieved. To retrieve the field number given the record handle, use ctdbGetFieldNumberByName() pValue [out] the pointer to the currency value.
Returns
ctdbGetFieldAsCurrency() returns CTDBRET_OK if successful, or the c-tree Plus error code on failure.
See also
ctdbAllocRecord(), ctdbSetFieldAsCurrency(), ctdbGetFieldAsBool(), ctdbGetFieldAsSigned(), ctdbGetFieldAsUnsigned(), ctdbGetFieldAsDate(), ctdbGetFieldAsTime(), ctdbGetFieldAsMoney(), ctdbGetFieldAsFloat(), ctdbGetFieldAsString(), ctdbGetFieldAsBlob(), ctdbSetFieldAsDateTime(), ctdbGetFieldNumber()
FairCom Corporation
368
ctdbGetFieldAsDate
Retrieve field as CTDATE value.
Declaration
CTDBRET ctdbGetFieldAsDate(CTHANDLE Handle, NINT FieldNbr, pCTDATE pValue)
Description
ctdbGetFieldAsDate() retrieves field as CTDATE value. The type CTDATE is an unsigned four-byte integer, interpreted as date. Use ctdbSetFieldAsDate() to set field as a CTDATE value. Handle [in] the record handle. FieldNbr [in] the field number to be retrieved. To retrieve the field number given the record handle, use ctdbGetFieldNumberByName(). pValue [out] the pointer to the date value.
Returns
ctdbGetFieldAsDate() returns CTDBRET_OK if successful, or the c-tree Plus error code on failure.
See also
ctdbAllocRecord(), ctdbGetFieldAsBool(), ctdbGetFieldAsSigned(), ctdbGetFieldAsUnsigned(), ctdbGetFieldAsTime(), ctdbGetFieldAsMoney(), ctdbGetFieldAsFloat(), ctdbGetFieldAsDateTime(), ctdbGetFieldAsString(), ctdbGetFieldAsBlob(), ctdbSetFieldAsDate(), ctdbGetFieldNumber()
www.faircom.com
All Rights Reserved
369
ctdbGetFieldAsDateTime
Retrieve field as CTDATETIME value.
Declaration
CTDBRET ctdbGetFieldAsDateTime(CTHANDLE Handle, NINT FieldNbr, pCTDATETIME pValue)
Description
ctdbGetFieldAsDateTime() retrieves field as CTDATETIME value. Use ctdbSetFieldAsDateTime() to set field as a CTDATETIME value. Handle [in] the record handle. FieldNbr [in] the field number to be retrieved. To retrieve the field number given the record handle, use ctdbGetFieldNumberByName(). pValue [out] the pointer to the datetime value.
Returns
ctdbGetFieldAsDateTime() returns CTDBRET_OK if successful, or the c-tree Plus error code on failure.
See also
ctdbAllocRecord(), ctdbGetFieldAsBool(), ctdbGetFieldAsSigned(), ctdbGetFieldAsUnsigned(), ctdbGetFieldAsDate(), ctdbGetFieldAsTime(), ctdbGetFieldAsMoney(), ctdbGetFieldAsFloat(), ctdbGetFieldAsString(), ctdbGetFieldAsBlob(), ctdbSetFieldAsDateTime(), ctdbGetFieldNumber()
FairCom Corporation
370
ctdbGetFieldAsFloat
Retrieve field as CTFLOAT value.
Declaration
CTDBRET ctdbGetFieldAsFloat(CTHANDLE Handle, NINT FieldNbr, pCTFLOAT pValue)
Description
ctdbGetFieldAsFloat() retrieves field as float value. Use ctdbSetFieldAsFloat() to set field as a CTFLOAT value. Handle [in] the record handle. FieldNbr [in] the field number to be retrieved. To retrieve the field number given the record handle, use ctdbGetFieldNumberByName(). pValue [out] the pointer to the float value.
Returns
ctdbGetFieldAsFloat() returns CTDBRET_OK if successful, or the c-tree Plus error code on failure.
See also
ctdbAllocRecord(), ctdbGetFieldAsBool(), ctdbGetFieldAsSigned(), ctdbGetFieldAsUnsigned(), ctdbGetFieldAsDate(), ctdbGetFieldAsTime(), ctdbGetFieldAsMoney(), ctdbGetFieldAsDateTime(), ctdbGetFieldAsString(), ctdbGetFieldAsBlob(), ctdbSetFieldAsFloat(), ctdbGetFieldNumber()
www.faircom.com
All Rights Reserved
371
ctdbGetFieldAsMoney
Retrieve field as CTMONEY value.
Declaration
CTDBRET ctdbGetFieldAsMoney(CTHANDLE Handle, NINT FieldNbr, pCTMONEY pValue)
Description
ctdbGetFieldAsMoney() retrieves field as CTMONEY value. Use ctdbSetFieldAsMoney() to set field as a CTMONEY value. Handle [in] the record handle. FieldNbr [in] the field number to be retrieved. To retrieve the field number given the record handle, use ctdbGetFieldNumberByName(). pValue [out] the pointer to the money value.
Returns
ctdbGetFieldAsMoney() returns CTDBRET_OK if successful, or the c-tree Plus error code on failure.
See also
ctdbAllocRecord(), ctdbGetFieldAsBool(), ctdbGetFieldAsSigned(), ctdbGetFieldAsUnsigned(), ctdbGetFieldAsDate(), ctdbGetFieldAsTime(), ctdbGetFieldAsFloat(), ctdbGetFieldAsDateTime(), ctdbGetFieldAsString(), ctdbGetFieldAsBlob(), ctdbSetFieldAsMoney(), ctdbGetFieldNumber()
FairCom Corporation
372
ctdbGetFieldAsNumber
Retrieve field as a number value.
Declaration
CTDBRET ctdbGetFieldAsNumber(CTHANDLE Handle, NINT FieldNbr, pCTNUMBER pValue)
Description
ctdbGetFieldAsNumber() retrieves field as number value. Use ctdbSetFieldAsNumber() to set field as a number value. Handle [in] the record handle. FieldNbr [in] the field number to be retrieved. To retrieve the field number given the record handle, use ctdbGetFieldNumberByName(). pValue [out] the pointer to the number value.
Returns
ctdbGetFieldAsNumber() returns CTDBRET_OK if successful, or the c-tree Plus error code on failure.
See also
ctdbAllocRecord(), ctdbSetFieldAsNumber(), ctdbGetFieldAsBool(), ctdbGetFieldAsSigned(), ctdbGetFieldAsUnsigned(), ctdbGetFieldAsDate(), ctdbGetFieldAsTime(), ctdbGetFieldAsMoney(), ctdbGetFieldAsFloat(), ctdbGetFieldAsString(), ctdbGetFieldAsBlob(), ctdbGetFieldNumber(), ctdbSetFieldAsNumber()
www.faircom.com
All Rights Reserved
373
ctdbGetFieldAsSigned
Retrieve field as signed value.
Declaration
CTDBRET ctdbGetFieldAsSigned(CTHANDLE Handle, NINT FieldNbr, pCTSIGNED pValue)
Description
ctdbGetFieldAsSigned() retrieves a field as a signed value. Use ctdbSetFieldAsSigned() to set a field as a CTSIGNED value. Handle [in] the record handle. FieldNbr [in] the field number to be retrieved. To retrieve the field number given the record handle, use ctdbGetFieldNumberByName(). pValue [out] the pointer to the signed value.
Returns
ctdbGetFieldAsSigned() returns CTDBRET_OK if successful, or the c-tree Plus error code on failure.
See also
ctdbAllocRecord(), ctdbGetFieldAsBool(), ctdbGetFieldAsUnsigned(), ctdbGetFieldAsDate(), ctdbGetFieldAsTime(), ctdbGetFieldAsMoney(), ctdbGetFieldAsFloat(), ctdbGetFieldAsDateTime(), ctdbGetFieldAsString(), ctdbGetFieldAsBlob(), ctdbSetFieldAsSigned(), ctdbGetFieldNumber()
FairCom Corporation
374
ctdbGetFieldAsString
Retrieve field as CTSTRING value.
Declaration
CTDBRET ctdbGetFieldAsString(CTHANDLE Handle, NINT FieldNbr, pCTSTRING pValue, VRLEN size)
Description
ctdbGetFieldAsString() retrieves field as CTSTRING value. Use ctdbSetFieldAsString() to set field as a CTSTRING value. Handle [in] the record handle. FieldNbr [in] the field number to be retrieved. To retrieve the field number given the record handle, use ctdbGetFieldNumberByName(). pValue [out] the pointer to the string value. size [in] pValue size in bytes.
Returns
ctdbGetFieldAsString() returns CTDBRET_OK if successful, or the c-tree Plus error code on failure.
See also
ctdbAllocRecord(), ctdbGetFieldAsBool(), ctdbGetFieldAsSigned(), ctdbGetFieldAsUnsigned(), ctdbGetFieldAsDate(), ctdbGetFieldAsTime(), ctdbGetFieldAsMoney(), ctdbGetFieldAsFloat(), ctdbGetFieldAsDateTime(), ctdbGetFieldAsBlob(), ctdbSetFieldAsString(), ctdbGetFieldNumber()
www.faircom.com
All Rights Reserved
375
ctdbGetFieldAsTime
Retrieve field as CTTIME value.
Declaration
CTDBRET ctdbGetFieldAsTime(CTHANDLE Handle, NINT FieldNbr, pCTTIME pValue)
Description
ctdbGetFieldAsTime() retrieves field as CTTIME value. Use ctdbSetFieldAsTime() to set field as a CTIME value. Handle [in] the record handle. FieldNbr [in] the field number to be retrieved. To retrieve the field number given the record handle, use ctdbGetFieldNumberByName(). pValue [out] the pointer to the time value.
Returns
ctdbGetFieldAsTime() returns CTDBRET_OK if successful, or the c-tree Plus error code on failure.
See also
ctdbAllocRecord(), ctdbGetFieldAsBool(), ctdbGetFieldAsSigned(), ctdbGetFieldAsUnsigned(), ctdbGetFieldAsDate(), ctdbGetFieldAsMoney(), ctdbGetFieldAsFloat(), ctdbGetFieldAsDateTime(), ctdbGetFieldAsString(), ctdbGetFieldAsBlob(), ctdbSetFieldAsTime(), ctdbGetFieldNumber()
FairCom Corporation
376
ctdbGetFieldAsUnsigned
Retrieve field as unsigned value.
Declaration
CTDBRET ctdbGetFieldAsUnsigned(CTHANDLE Handle, NINT FieldNbr, pCTUNSIGNED pValue)
Description
ctdbGetFieldAsUnsigned() retrieves field as an unsigned value. Use ctdbSetFieldAsUnsigned() to set field as a CTUNSIGNED value. Handle [in] the record handle. FieldNbr [in] the field number to be retrieved. To retrieve the field number given the record handle, use ctdbGetFieldNumberByName(). pValue [out] the pointer to the unsigned value.
Returns
ctdbGetFieldAsUnsigned() returns CTDBRET_OK if successful, or the c-tree Plus error code on failure.
See also
ctdbAllocRecord(), ctdbGetFieldAsBool(), ctdbGetFieldAsSigned(), ctdbGetFieldAsDate(), ctdbGetFieldAsTime(), ctdbGetFieldAsMoney(), ctdbGetFieldAsFloat(), ctdbGetFieldAsDateTime(), ctdbGetFieldAsString(), ctdbGetFieldAsBlob(), ctdbSetFieldAsUnsigned(), ctdbGetFieldNumber()
www.faircom.com
All Rights Reserved
377
ctdbGetFieldAsUTF16
Retrieves the field data as a Unicode UTF-16 string.
DECLARATION
CTDBRET ctdbGetFieldAsUTF16(CTHANDLE Handle, NINT FieldNbr, pWCHAR pValue, VRLEN size);
DESCRIPTION
ctdGetFieldAsUTF16() retrieves the field data as a UNICODE UTF-16 string. If the underlying field type is not one of the Unicode field types, the data is converted to UTF-16 strings. Handle is a record handle, FieldNbr is the number of the field, pValue is a pointer to a wide (UTF-16) string buffer and size indicates the size in bytes of the string area.
RETURN
Value 0 Symbolic Constant NO_ERROR Explanation No error occurred.
See Appendix A for a complete listing of valid c-tree Plus error values.
EXAMPLE
CTDBRET CheckData(CTHANDLE hRecord, pTEXT str, NINT val) { CTDBRET eRet; WCHAR WStr[32]; TEXT s[64]; CTSIGNED t; if ((eRet = ctdbGetFieldAsUTF16(hRecord, 0, WStr, sizeof(WStr))) != CTDBRET_OK) { printf("ctdbGetFieldAsUTF16 failed with error %d", eRet); goto Exit; } if ((eRet = (CTDBRET)ctdb_u16TOu8(WStr, s, sizeof(s))) != CTDBRET_OK) { printf("ctdb_u16TOu8 failed with error %d", eRet); goto Exit; } if (strcmp(s, str) != 0) { printf("UNICODE field contents not the same written"); eRet = CTDBRET_DIFFERENT; goto Exit; } if ((eRet = ctdbGetFieldAsSigned(hRecord, 1, &t)) != CTDBRET_OK) { printf("ctdbGetFieldAsSigned failed with error %d", eRet); goto Exit; } if ((NINT)t != val) { printf("integer field contents not the same written"); eRet = CTDBRET_DIFFERENT; goto Exit; } Exit: return eRet; }
FairCom Corporation
378
SEE ALSO
ctdbSetFieldAsUTF16()
www.faircom.com
All Rights Reserved
379
ctdbGetFieldByName
Retrieve a field handle from a table, based on the field name.
Declaration
CTHANDLE ctdbGetFieldByName(CTHANDLE Handle, pTEXT FieldName)
Description
ctdbGetFieldByName() retrieves a field handle from a table, based on the field name. To retrieve a field handle from a table, based on the field number, use ctdbGetField(). To retrieve the field number, use ctdbGetFieldNumber(). Handle [in] the Table Handle. FieldName [in] the field name.
Returns
ctdbGetFieldByName() returns the field handle or NULL on error.
See also
ctdbAllocTable(), ctdbGetField(), ctdbGetFieldNumber()
FairCom Corporation
380
ctdbGetFieldDataLength
Retrieve the field data actual length
Declaration
VRLEN ctdbGetFieldDataLength(CTHANDLE Handle, NINT FieldNbr)
Description
ctdbGetFieldDataLength() retrieves the field data actual length. Use ctdbGetFieldSize() to retrieve the defined field size. Use ctdbGetFieldData() to retrieve the field data. Handle [in] the record handle. FieldNbr [in] the field number.
Returns
ctdbGetFieldDataLength() returns the field length.
See also
ctdbGetFieldSize()
www.faircom.com
All Rights Reserved
381
ctdbGetFieldDefaultDateType
Retrieves the default value date type.
DECLARATION
CTDATE_TYPE ctdbGetFieldDefaultDateType(CTHANDLE Handle);
DESCRIPTION
Retrieves the default value date type used when converting strings to dates. Handle must be a c-treeDB field handle.
RETURN
Value 1 2 3 4 5 6 Symbolic Constant Explanation Date format is mm/dd/ccyy Date format is mm/dd/yy Date format is dd/mm/ccyy Date format is dd/mm/yy Date format is ccyymmdd Date format is yymmdd
See Appendix A for a complete listing of valid c-tree Plus error values.
EXAMPLE
/* check the default date type */ hField = ctdbGetField(hTable, 5); if (ctdbGetFieldDefaultDateType(hField) != CTDATE_MDCY) printf("Default date type is not OK\n");
SEE ALSO
ctdbSetFieldDefaultValue(), ctdbGetFieldDefaultValue(), ctdbClearFieldDefaultValue(), ctdbIsFieldDefaultValueSet(), ctdbClearAllFieldDefaultValue(), ctdbSetFieldDefaultDateTimeType(), ctdbGetFieldDefaultTimeType()
FairCom Corporation
382
ctdbGetFieldDefaultTimeType
Retrieves the default value time type.
DECLARATION
CTTIME_TYPE ctdbGetFieldDefaultTimeType(CTHANDLE Handle);
DESCRIPTION
Retrieves the default value time type used when converting strings to dates. Handle must be a c-treeDB field handle.
RETURN
Value 1 2 3 4 5 Symbolic Constant Explanation Time format is hh:mm:ss am|pm Time format is hh:mm am|pm Time format is hh:mm:ss (24 hour) Time format is hh:mm (24 hour) Time format is hhmm (military)
See Appendix A for a complete listing of valid c-tree Plus error values.
EXAMPLE
/* check the default time type */ hField = ctdbGetField(hTable, 5); if (ctdbGetFieldDefaultTimeType(hField) != CTDBRET_OK) printf("Default time type is not OK\n");
SEE ALSO
ctdbSetFieldDefaultValue(), ctdbGetFieldDefaultValue(), ctdbClearFieldDefaultValue(), ctdbIsFieldDefaultValueSet(), ctdbClearAllFieldDefaultValue(), ctdbSetFieldDefaultDateTimeType(), ctdbGetFieldDefaultTimeType()
www.faircom.com
All Rights Reserved
383
ctdbGetFieldDefaultValue
Retrieves the current field default value.
DECLARATION
pTEXT ctdbGetFieldDefaultValue(CTHANDLE Handle, pVRLEN pLength);
DESCRIPTION
If no default value is set ctdbGetFieldDefaultValue() returns NULL and no value is set to pLength. You can use ctdbIsFieldDefaultValueSet() function to check if a field default value is set or not. Handle must be a field handle. If pLength is not NULL, returns the length of the default value string.
RETURN
Returns the current field default value or NULL if no default value was set for the field.
EXAMPLE
/* check if default field value is 'USA' */ hField = ctdbGetField(hTable, 5); if (hField) { VRLEN len; pTEXT value = ctdbGetFieldDefaultValue(hField, &len); if (value) { if (strcmp(value, "USA") == 0) printf("Default value is 'USA'\n"); else printf("Default value is not 'USA'\n"); } else printf("No default value set\n"); }
SEE ALSO
ctdbSetFieldDefaultValue(), ctdbGetFieldDefaultValue(), ctdbClearFieldDefaultValue(), ctdbIsFieldDefaultValueSet(), ctdbClearAllFieldDefaultValue(), ctdbSetFieldDefaultDateTimeType(), ctdbGetFieldDefaultTimeType()
FairCom Corporation
384
ctdbGetFieldHandle
Retrieve a Field Handle.
Declaration
CTHANDLE ctdbGetFieldHandle(CTHANDLE Handle)
Description
ctdbGetFieldHandle() retrieves a Field Handle. This function can be used to test if a handle is really a field handle. For example, assume a function should take a field handle, but inside the function you cast the CTHANDLE type to the field CTDFIELD structure. For safety, it is a good idea to make sure that the handle is really a field handle as shown in the example below. Another minor reason for this call is to perform a ctdbSWTCREEI() call.
CTBOOL IsFieldNumeric(CTHANDLE hField) { CTBOOL Retval = FALSE; pCTDBFIELD pField = (pCTDBFIELD)ctdbGetFieldHandle(hField); if (!pField) { printf("Error: hField is not a field handle"); } ... ... return Retval; }
To allocate a field handle, use ctdbAllocField(). Handle [in] maybe a field handle, an index handle, or a segment handle.
Returns
ctdbGetFieldHandle() returns a field handle on success or NULL on error.
See also
ctdbAllocField(), ctdbGetRecordHandle(), ctdbGetIndexHandle(), ctdbGetSegmentHandle()
www.faircom.com
All Rights Reserved
385
ctdbGetFieldLength
Retrieve the field length
Declaration
VRLEN ctdbGetFieldLength(CTHANDLE Handle)
Description
ctdbGetFieldLength() retrieves the field length, given a field handle. Use ctdbGetFieldNumber() to retrieve the field number given the field name. Handle [in] the Field Handle.
Returns
ctdbGetFieldLength() returns the field length, or -1 on failure
See also
ctdbAllocField(), ctdbGetFieldNumber(), ctdbGetFieldName(), ctdbGetFieldType(), ctdbGetFieldLength(), ctdbSetFieldLength()
FairCom Corporation
386
ctdbGetFieldName
Retrieve the field name
Declaration
pTEXT ctdbGetFieldName(CTHANDLE Handle)
Description
ctdbGetFieldName() retrieves the field name, given a field handle. Use ctdbGetFieldNumber() to retrieve the field number given the field name. Handle [in] the Field Handle.
Returns
ctdbGetFieldName() returns the field name, or NULL on failure
See also
ctdbAllocField(), ctdbGetFieldNumber(), ctdbGetFieldNumberByName(), ctdbGetFieldNbr(), ctdbGetFieldLength(), ctdbSetFieldName()
www.faircom.com
All Rights Reserved
387
ctdbGetFieldNbr
Retrieve the field number in the table fields list
Declaration
NINT ctdbGetFieldNbr(CTHANDLE Handle)
Description
ctdbGetFieldNbr() retrieves the field number in the table fields list, given a field handle. Use ctdbGetFieldNumber() to retrieve the field number given the field name. Use ctdbGetFieldNumberByName() to retrieve the field number given the record handle. Handle [in] the Field Handle.
Returns
ctdbGetFieldNbr() returns the field number, or -1 on failure
See also
ctdbAllocField(), ctdbSetFieldProperties(), ctdbGetFieldNumber(), ctdbGetFieldNumberByName(), ctdbGetFieldLength(), ctdbGetFieldName()
FairCom Corporation
388
ctdbGetFieldNullFlag
Retrieve the field null flag.
Declaration
CTBOOL ctdbGetFieldNullFlag(CTHANDLE Handle)
Description
ctdbGetFieldNullFlag() retrieves the field null flag. Handle [in] the Field Handle.
Returns
ctdbGetFieldNullFlag() returns the field NULL flag.
See also
ctdbGetField(), ctdbGetFieldNbr(), ctdbGetFieldLength(), ctdbGetFieldName(), ctdbSetFieldNullFlag(), ctdbIsNullField()
www.faircom.com
All Rights Reserved
389
ctdbGetFieldNumber
Given the field Name and the table handle, returns the field number.
Declaration
NINT ctdbGetFieldNumber(CTHANDLE Handle, pTEXT FieldName)
Description
ctdbGetFieldNumber() returns the field number given the field name. Use ctdbGetFieldNbr() to retrieve the field number given a field handle. Use ctdbGetFieldNumberByName() to retrieve the field number given the record handle. Handle [in] the Table Handle. FieldName [in] the name that identifies the field in the table.
Returns
ctdbGetFieldNumber() returns the field number, or -1 on error.
Example
pMyTable1 = ctdbAllocTable(pMyDB1); ctdbOpenTable(pMyTable1, customer, CTOPEN_NORMAL); fldnbr = ctdbGetFieldNumberByName(pMyTable1, Name);
See also
ctdbAllocTable(), ctdbGetField(), ctdbGetFieldNbr(), ctdbGetFieldByName(), ctdbGetFieldNumberByName(), ctdbGetFieldLength(), ctdbGetFieldName()
FairCom Corporation
390
ctdbGetFieldNumberByName
Return the field number, based on the field name and record handle.
Declaration
NINT ctdbGetFieldNumberByName(CTHANDLE Handle, pTEXT FieldName)
Description
ctdbGetFieldNumberByName() returns the field number given the field name and the record handle. Use ctdbGetFieldNumber() to retrieve the field number given the table handle. Use ctdbGetFieldNbr() to retrieve the field number given a field handle. Handle [in] the record handle. FieldName [in] the name that identifies the field in the table.
Returns
ctdbGetFieldNumberByName() returns the field number, or -1 on error.
Example
pMyRec1 = ctdbAllocRecord(pMyTable1); ctdbFirstRecord(pMyRec1); fldnbr = ctdbGetFieldNumberByName(pMyRec1, Name);
See also
ctdbAllocTable(), ctdbGetField(), ctdbGetFieldNbr(), ctdbGetFieldByName(), ctdbGetFieldLength(), ctdbGetFieldName()
www.faircom.com
All Rights Reserved
391
ctdbGetFieldOffset
Retrieve the field offset in record buffer
Declaration
VRLEN ctdbGetFieldOffset(CTHANDLE Handle, NINT FieldNbr)
Description
ctdbGetFieldOffset() retrieves the field offset in record buffer. Handle [in] the record handle. FieldNbr [in] the field number.
Returns
ctdbGetFieldOffset() returns the field offset.
Example
pMyRec1 = ctdbAllocRecord(pMyTable1); ctdbFirstRecord(pMyRec1); field1_offset = ctdbGetFieldOffset(pMyRec1, 0);
See also
ctdbGetFieldAddress()
FairCom Corporation
392
ctdbGetFieldPrecision
Retrieve the field precision.
Declaration
NINT ctdbGetFieldPrecision(CTHANDLE Handle)
Description
ctdbGetFieldPrecision() retrieves the field precision. The field precision represents the total number of digits in a BCD number. Handle [in] the Field Handle.
Returns
ctdbGetFieldPrecision() returns the field precision (maximum number of digits).
See also
ctdbGetField(), ctdbGetFieldLength(), ctdbGetFieldName(), ctdbGetFieldNullFlag(), ctdbGetFieldScale(), ctdbSetFieldPrecision()
www.faircom.com
All Rights Reserved
393
ctdbGetFieldProperties
Retrieve field properties such as name, type and length, given a field handle.
Declaration
CTDBRET ctdbGetFieldProperties(CTHANDLE Handle, ppTEXT FieldName, pCTDBTYPE pType, pVRLEN pLength)
Description
ctdbGetFieldProperties() retrieves field properties such as name, type and length, given a field handle. Use ctdbSetFieldProperties() to set the field properties. Handle [in] the Field Handle. FieldName [out] the field name. pType [out] the field type. pLength [out] the field length.
Returns
ctdbGetFieldProperties() returns CTDBRET_OK on success, or a c-treeDB C API error code on failure
See also
ctdbAllocField(), ctdbSetFieldProperties()
FairCom Corporation
394
ctdbGetFieldScale
Retrieve the field scale.
Declaration
NINT ctdbGetFieldScale(CTHANDLE Handle)
Description
ctdbGetFieldScale() retrieves the field scale (the number of digits to the right of the decimal point). Handle [in] the Field Handle.
Returns
ctdbGetFieldScale() returns the field scale.
See also
ctdbGetField(), ctdbGetFieldLength(), ctdbGetFieldName(), ctdbGetFieldNullFlag(), ctdbGetFieldPrecision(), ctdbSetFieldScale()
www.faircom.com
All Rights Reserved
395
ctdbGetFieldSize
Retrieve the defined field size.
Declaration
VRLEN ctdbGetFieldSize(CTHANDLE Handle, NINT FieldNbr)
Description
ctdbGetFieldSize() retrieves the defined field size. Use ctdbGetFieldDataLength() to retrieve the field data actual length. Handle [in] the record handle. FieldNbr [in] the field number.
Returns
ctdbGetFieldSize() returns the defined field size.
See also
ctdbGetFieldDataLength(), ctdbGetFieldLength()
FairCom Corporation
396
ctdbGetFieldStatus
Retrieves the changed status of a field handle.
DECLARATION
ULONG ctdbGetFieldStatus(CTHANDLE Handle);
DESCRIPTION
Retrieves the changed status of a field handle. Handle must be a c-treeDB field handle. The status of a field handle is a bit map describing one or more changes that have occurred with the field object.
RETURN
ctdbGetFieldStatus() returns a bitmap of the following:
Value 0x00 0x01 0x02 0x04 0x10 0x20 0x40 0x80 Symbolic Constant Explanation Original field as read from table Field added or inserted Original field deleted Original field moved Field name changed Field type changed Field length changed Field resource changed
See Appendix A for a complete listing of valid c-tree Plus error values.
EXAMPLE
/* if field is new delete it */ for (i = 0; i < (NINT) ctdbGetTableFieldCount(hTable); i++) { CTHANDLE hField = ctdbGetField(hTable, i); if (ctdbGetFieldStatus(hField) & CTDBFIELD_NEW) if (ctdbDelField(hTable, 0) != CTDBRET_OK) printf("ctdbDelField failed\n"); }
SEE ALSO
ctdbGetIndexStatus(), ctdbGetSegmentStatus()
www.faircom.com
All Rights Reserved
397
ctdbGetFieldType
Retrieve the field type.
Declaration
CTDBTYPE ctdbGetFieldType(CTHANDLE Handle)
Description
ctdbGetFieldType() retrieves the field type, given a field handle. Use ctdbGetFieldLength() to retrieve the field length. Handle [in] the Field Handle.
Returns
ctdbGetFieldType() returns the field type, or 0 on failure. Available types are described in "c-treeDB definitions"..
See also
ctdbAllocField(), ctdbGetFieldNumber(), ctdbGetFieldName(), ctdbGetFieldLength(), ctdbSetFieldType()
FairCom Corporation
398
ctdbGetFilter
Retrieve the filter from the table.
Declaration
pTEXT ctdbGetFilter(CTHANDLE Handle)
Description
ctdbGetFilter() retrieves the current filter expression for the table. To insert a filter, use ctdbFilterRecord(). To verify if there is a filter active in the table, use ctdbIsFilteredRecord(). Handle [in] the Table or record handle.
Returns
ctdbGetFilter() returns a pointer to a string with the filter expression. If no filters are active, return NULL.
See also
ctdbFilterRecord(), ctdbIsFilteredRecord()
www.faircom.com
All Rights Reserved
399
ctdbGetFirstActiveDatabase
Retrieve the handle of the first active database in the session.
Declaration
CTHANDLE ctdbGetFirstActiveDatabase(CTHANDLE Handle, pVRLEN pScanIndex)
Description
ctdbGetFirstActiveDatabase() retrieves the handle of the first active database in the session. Handle [in] the session handle. pScanIndex [out] the pointer to a VRLEN to hold the scan state. It is returned by ctdbGetFirstActiveDatabase() and it will be an input to ctdbGetNextActiveDatabase().
Returns
ctdbGetFirstActiveDatabase() returns the handle of the database or NULL if not found.
See also
ctdbAllocSession(), ctdbGetNextActiveDatabase(), ctdbFindActiveDatabase(), ctdbFindActiveDatabaseByUID()
FairCom Corporation
400
ctdbGetFirstActiveTable
Retrieve the handle of the first active table in the database.
Declaration
CTHANDLE ctdbGetFirstActiveTable(CTHANDLE Handle, pVRLEN pScanRec)
Description
ctdbGetFirstActiveTable() retrieves the handle of the first active table in database. To retrieve the table handle, given the table name, use ctdbFindActiveTable(). Handle [in] the Database Handle. pScanRec [out] the pointer to a VRLEN to hold the scan state. It is returned by ctdbGetFirstActiveTable() and it will be an input and output to/from ctdbGetNextActiveTable().
Returns
ctdbGetFirstActiveTable() returns the table handle or NULL if not found.
See also
ctdbAllocDatabase(), ctdbGetNextActiveTable(), ctdbFindActiveTable()
www.faircom.com
All Rights Reserved
401
ctdbGetHandleType
Retrieves the handle type.
DECLARATION
NINT ctdbGetHandleType(CTHANDLE Handle);
DESCRIPTION
ctdbGetHandleType() retrieves the handle type. Handle can be any valid c-treeDB handle.
RETURN
ctdbGetHandleType() return one of the following values:
Value 0 0x0db1 0x0db2 0x0db3 0x0db4 0x0db5 0x0db6 0x0db7 Symbolic Constant NULL or invalid Handle.
EXAMPLE
pCTDBSESSION pSession; if (ctdbGetHandleType(Handle) == CTDB+_RECORD_HANDLE_ID) pSession = ((pCTDBRECORD)Handle)->pSession;
SEE ALSO
ctdbGetLocalTag(), ctdbSetLocalTag()
FairCom Corporation
402
ctdbGetHour
Get the hour from a packed CTTIME.
Declaration
NINT ctdbGetHour(CTTIME Time)
Description
ctdbGetHour() gets the hour from a packed CTTIME. Time is the packed time in CTTIME format.
Returns
ctdbGetHour() returns the hour on success, or -1 on error.
See also
ctdbGetMinute(), ctdbGetSecond()
www.faircom.com
All Rights Reserved
403
ctdbGetIdxnoByName
Retrieve the index file number from a table handle.
Declaration
NINT ctdbGetIdxnoByName(CTHANDLE Handle, pTEXT indexname)
Description
Retrieve the index file number to be used with c-tree ISAM or low-level index functions. Handle is a table handle. indexname is a string containing the index name. Return the index number on success or -1 on failure. If ctdbGetIdxnoByNumber() return -1, the error code can be retrieved by calling ctdbGetError() function.
Return
Value -1 Symbolic Constant N/A Explanation
ctdbGetIdxnoByNumber() failed. You can retrieve the error code by calling ctdbGetError() function. c-tree Plus Programmer's Reference Guide for a complete listing of valid c-tree Plus error values.
Example
/* retrieve the first key of first index */ TEXT keyval[256]; COUNT idxno = (COUNT)ctdbGetIdxnoByName(hTable, "indexname"); if (FirstKey(idxno, 0), keyval) printf("FirstKey failed\n");
See also
ctdbSwitchInstance(), ctdbSwitchContext(), ctdbGetDatno(), ctdbGetIdxno(), ctdbGetIdxnoByNumber(), ctdbGetError()
FairCom Corporation
404
ctdbGetIdxno
Retrieve the index file number from a index handle.
DECLARATION
NINT ctdbGetIdxno(CTHANDLE Handle)
DESCRIPTION
Retrieves the index file number to be used with c-tree ISAM or low-level index functions. Handle must be an index or segment handle. Returns the index number on success or -1 on failure. If ctdbGetIdxno() function returns -1, the error code can be retrieved by calling the ctdbGetError() function.
RETURN
Value 0 -1 Symbolic Constant NO_ERROR Explanation No error occurred.
ctdbGetDIdxno() failed. You can retrieve the error code by calling ctdbGetError() function.
See Appendix A for a complete listing of valid c-tree Plus error values.
EXAMPLE
/* retrieve the first key of first index */ TEXT keyval[256]; COUNT idxno = (COUNT)ctdbGetIdxno(ctdbGetIdnex(hTable, 0)); if (FirstKey(idxno, 0), keyval) printf("FirstKey failed\n");
SEE ALSO
ctdbSwitchInstance(), ctdbSwitchContext(), ctdbGetDatno(), ctdbGetIdxnoByName(), ctdbGetIdxnoByNumber(), ctdbGetError()
www.faircom.com
All Rights Reserved
405
ctdbGetIdxnoByNumber
Retrieve the index file number from a table handle.
DECLARATION
NINT ctdbGetIdxnoByNumber(CTHANDLE Handle, NINT index)
DESCRIPTION
Retrieves the index file number to be used with c-tree ISAM and low-level index functions. Handle is a table handle. index is a c-treeDB index number. The first c-treeDB index number is zero. Returns the index number on success or -1 on failure. If ctdbGetIdxnoByNumber() returns -1, the error code can be retrieved by calling ctdbGetError() function.
RETURN
Value 0 -1 Symbolic Constant NO_ERROR Explanation No error occurred.
ctdbGetDIdxnoByNumber() failed. You can retrieve the error code by calling ctdbGetError() function.
See Appendix A for a complete listing of valid c-tree Plus error values.
EXAMPLE
/* retrieve the first key of first index */ TEXT keyval[256]; COUNT idxno = (COUNT)ctdbGetIdxnoByNumber(hTable, 0); if (FirstKey(idxno, 0), keyval) printf("FirstKey failed\n");
SEE ALSO
ctdbSwitchInstance(), ctdbSwitchContext(), ctdbGetDatno(), ctdbGetIdxno(), ctdbGetIdxnoByName(), ctdbGetError()
FairCom Corporation
406
ctdbGetIndex
Retrieve the handle for index identified by IndexNumber.
Declaration
CTHANDLE ctdbGetIndex(CTHANDLE Handle, NINT IndexNumber)
Description
ctdbGetIndex retrieves the handle for index identified by index number. To retrieve the index handle given the segment handle, use ctdbGetIndexHandle(). Handle [in] the table handle. IndexNumber [in] the number of the index in the table.
Returns
ctdbGetIndex() returns index handle on success, or NULL on failure.
See also
ctdbAllocTable(), ctdbGetIndexHandle(), ctdbGetIndexNbr()
www.faircom.com
All Rights Reserved
407
ctdbGetIndexByName
Retrieve the index handle given the index name
Declaration
CTHANDLE ctdbGetIndexByName(CTHANDLE Handle, pTEXT name)
Description
ctdbGetIndexByName() retrieves the index handle given the index name. Handle [in] the Table Handle. name [in] the index name.
Returns
ctdbGetIndexByName() returns index handle on success, or NULL on failure.
See also
ctdbGetIndex(), ctdbGetIndexByUID(), ctdbGetIndexNbrByName()
FairCom Corporation
408
ctdbGetIndexByUID
Retrieve the index handle given the index UID
Declaration
CTHANDLE ctdbGetIndexByUID(CTHANDLE Handle, ULONG uid)
Description
ctdbGetIndexByUID() retrieves the index handle given the index unique identifier, uid. Handle [in] the Table Handle. uid [in] the Index uid number.
Returns
ctdbGetIndexByUID() returns index handle on success, or NULL on failure.
See also
ctdbGetIndexNbr(), ctdbGetIndexNbrByName()
www.faircom.com
All Rights Reserved
409
ctdbGetIndexDuplicateFlag
Retrieve the allow duplicate key flag for this index.
Declaration
CTBOOL ctdbGetIndexDuplicateFlag(CTHANDLE Handle)
Description
ctdbGetIndexDuplicateFlag() retrieves the allow duplicate key flag for this index. Use ctdbSetIndexDuplicateFlag() to set the allow duplicate key flag for the desired index. Handle [in] the index handle.
Returns
ctdbGetIndexDuplicateFlag() returns the duplicate key flag for this index (YES or NO).
See also
ctdbAllocIndex(), ctdbSetIndexDuplicateFlag()
FairCom Corporation
410
ctdbGetIndexEmptyChar
Retrieve the empty char property for this index
Declaration
NINT ctdbGetIndexEmptyChar(CTHANDLE Handle)
Description
ctdbGetIndexEmptyChar() retrieves the empty char property for this index. Use ctdbSetIndexEmptyChar() to set the empty char property for this index. The empty char property is expressed as the decimal equivalent of the ASCII table. For instance, an ASCII space is specified a value of 32, and NULL byte is specified as 0. Handle [in] the index handle.
Returns
ctdbGetIndexEmptyChar() returns the empty char property.
See also
ctdbAllocIndex(), ctdbSetIndexEmptyChar()
www.faircom.com
All Rights Reserved
411
ctdbGetIndexExtension
Retrieve the table index file name extension.
Declaration
pTEXT ctdbGetIndexExtension(CTHANDLE Handle)
Description
ctdbGetIndexExtension() retrieves the table index file name extension. The default index extension is .idx. To set the index file name extension, use ctdbSetIndexExtension(). Handle [in] the Table Handle.
Returns
ctdbGetIndexExtension() returns the index file name extension.
See also
ctdbAllocTable(), ctdbSetIndexExtension()
FairCom Corporation
412
ctdbGetIndexFileName
Retrieves the current index file name associated with an index.
Declaration
pTEXT ctdbGetIndexFileName(CTHANDLE Handle);
Description
Handle is an index handle returned by ctdbAddIndex() or ctdbGetIndex() calls. ctdbGetIndexFilename() may return NULL indicating that the index is a member of an index superfile.
Return
ctdbGetIndexFileName() returns the physical filename of the index.
See Appendix A c-tree Plus Error Codes in
c-tree Plus Programmer's Reference Guide for a complete listing of valid c-tree Plus error values.
See also
ctdbSetIndexFilename(), ctdbAddIndex(), ctdbGetIndex()
www.faircom.com
All Rights Reserved
413
ctdbGetIndexHandle
Retrieve the index handle.
Declaration
CTHANDLE ctdbGetIndexHandle(CTHANDLE Handle)
Description
ctdbGetIndexHandle() retrieves the index handle. To allocate an index handle, use ctdbAllocIndex(). To retrieve the index handle given the table and index number, use ctdbGetIndex(). Handle [in] may be an index handle, or the segment handle.
Returns
ctdbGetIndexHandle() returns the index handle or NULL on failure.
See also
ctdbAllocSegment(), ctdbGetFieldHandle(), ctdbAllocIndex(), ctdbGetIndex()
FairCom Corporation
414
ctdbGetIndexKeyLength
Retrieve the key length for this index.
Declaration
VRLEN ctdbGetIndexKeyLength(CTHANDLE Handle)
Description
ctdbGetIndexKeyLength() retrieves the key length for this index. Handle [in] the index handle.
Returns
ctdbGetIndexKeyLength() returns the key length or -1 on error.
See also
ctdbAllocIndex()
www.faircom.com
All Rights Reserved
415
ctdbGetIndexKeyType
Retrieve the key type for this index.
Declaration
CTDBKEY ctdbGetIndexKeyType(CTHANDLE Handle)
Description
ctdbGetIndexKeyType() retrieves the key type for this index. Use ctdbAddIndex() to add an index to a table. Handle [in] the index handle. Use ctdbSetIndexKeyType() to set the Index key type.
Returns
ctdbGetIndexKeyType() returns the key type, or CTINDEX_ERROR on error. Allowed key types are listed in "c-treeDB definitions"..
See also
ctdbAllocIndex(), ctdbAddIndex(), ctdbSetIndexKeyType()
FairCom Corporation
416
ctdbGetIndexName
Retrieve the index name
Declaration
pTEXT ctdbGetIndexName(CTHANDLE Handle)
Description
ctdbGetIndexName() retrieves the index name. Handle [in] the index handle.
Returns
ctdbGetIndexName() returns the pointer to the index name on success, or NULL on failure.
See also
ctdbAllocIndex(), ctdbGetSegmentNbr(), ctdbGetIndexNbrByName(), ctdbGetIndexNbr()
www.faircom.com
All Rights Reserved
417
ctdbGetIndexNbr
Retrieve the index number in the table list
Declaration
CTDBRET ctdbGetIndexNbr(CTHANDLE Handle, pVRLEN pNumber)
Description
ctdbGetIndexNbr() retrieves the index number in the table list, given an index handle. Use ctdbGetSegmentNbr() to retrieve the segment number. Handle [in] the index handle. pNumber [out] the index number.
Returns
ctdbGetIndexNbr() returns CTDBRET_OK on success, or a c-treeDB C API error code on failure.
See also
ctdbAllocIndex(), ctdbGetSegmentNbr(), ctdbGetIndexNbrByName(), ctdbGetIndexName()
FairCom Corporation
418
ctdbGetIndexNbrByName
Retrieve the index number given the index name
Declaration
NINT ctdbGetIndexNbrByName(CTHANDLE Handle, pTEXT name)
Description
ctdbGetIndexNbrByName() retrieves the index number given the index name. Handle [in] the Table Handle. name [in] the index name.
Returns
ctdbGetIndexNbrByName() returns the index number on success, or -1 on error.
See also
ctdbGetIndexNbr(), ctdbGetIndexByName(), ctdbGetIndexByUID()
www.faircom.com
All Rights Reserved
419
ctdbGetIndexNullFlag
Retrieve the null key flag for this index
Declaration
CTBOOL ctdbGetIndexNullFlag(CTHANDLE Handle)
Description
ctdbGetIndexNullFlag() retrieves the null key flag for this index. Use ctdbSetIndexNullFlag() to set the null key flag for the desired index. Handle [in] the index handle.
Returns
ctdbGetIndexNullFlag() returns the null key flag (YES or NO).
See also
ctdbAllocIndex(), ctdbSetIndexNullFlag()
FairCom Corporation
420
ctdbGetIndexKSeg
Retrieves the index current extended key segment definition.
DECLARATION
CTDBRET ctdbGetIndexKSeg(CTHANDLE Handle, pctKSEGDEF pKSeg);
DESCRIPTION
ctdbGetIndexKSeg() retrieves the current index-wide extended key segment definition. Handle must be a c-treeDB index handle and pKSeg is a pointer to an extended key segment definition structure which will receive the definition.
RETURN
Value 0 4096 Symbolic Constant Explanation No error occurred. Not found.
CTDBRET_OK CTDBRET_NOTFOUND
See Appendix A for a complete listing of valid c-tree Plus error values.
EXAMPLE
ctKSEGDEF kseg; if ((eRet = ctdbGetIndexKSeg(hTable, &kseg)) != CTDBRET_OK) printf(ctdbGetIndexKSeg failed with error %d\n, eRet);
SEE ALSO
ctdbSetTableKSeg(), ctdbGetTableKSeg(), ctdbSetIndexKSeg(), ctdbSetSegmentKSeg(), ctdbGetSegmentKSeg(), ctdbSetKSegDefaults()
www.faircom.com
All Rights Reserved
421
ctdbGetIndexSegmentCount
Retrieve the number of segments associated with this index
Declaration
VRLEN ctdbGetIndexSegmentCount(CTHANDLE Handle)
Description
ctdbGetIndexSegmentCount() retrieves the number of segments associated with this index. Handle [in] the index handle.
Returns
ctdbGetIndexSegmentCount() returns the number of segments or -1 on error.
See also
ctdbAllocIndex()
FairCom Corporation
422
ctdbGetIndexStatus
Retrieves the status of the index handle.
DECLARATION
ULONG ctdbGetIndexStatus(CTHANDLE Handle);
DESCRIPTION
Retrieves the status of the index handle. Handle is a c-treeDB index handle.The status of the index handle is a bit map describing one or more changes that have occurred to the index object.
RETURN
ctdbGetIndexStatus() returns a bitmap of the following::
Value 0x00 0x01 0x02 0x04 0x10 0x20 0x40 0x80 Symbolic Constant Explanation Original value (no changes) Index added Original Index deleted Index key type changed Index empty char changed Index duplicate flag changed Index null flag changed Index file name changed
See Appendix A for a complete listing of valid c-tree Plus error values.
EXAMPLE
/* if the index has been changed, call alter table */ CTHANDLE hIndex = ctdbGetIndex(hTable, 0); if (ctdbGetIndexStatus(hIndex) != CTDBINDEX_OLD) if (ctdbAlterTable(hTable, CTDB_ALTER_NORMAL) != CTDBRET_OK) printf("ctdbAlterTable failed\n");
SEE ALSO
ctdbGetFieldStatus(), ctdbGetSegmentStatus()
www.faircom.com
All Rights Reserved
423
ctdbGetIndexTemporaryFlag
Retrieve the flag that indicates this index as temporary.
Declaration
CTBOOL ctdbGetIndexTemporaryFlag(CTHANDLE Handle)
Description
ctdbGetIndexTemporaryFlag() retrieves the flag that indicates this index as temporary. Use ctdbSetIndexTemporaryFlag() to set the temporary flag for this index. Handle [in] the index handle.
Returns
ctdbGetIndexTemporaryFlag() returns the temporary flag (YES or NO).
See also
ctdbAllocIndex(), ctdbSetIndexTemporaryFlag()
FairCom Corporation
424
ctdbGetIndexUID
Retrieve the index UID number
Declaration
CTDBRET ctdbGetIndexUID(CTHANDLE Handle, pTEXT Name, pULONG puid)
Description
ctdbGetIndexUID() retrieves the index unique identifier number. Handle [in] the Database Handle. Name [in] the Table name puid [out] the UID value
Returns
ctdbGetIndexUID() returns CTDBRET_OK on success, or c-treeDB C API error code on failure.
See also
ctdbGetIndexNbr()
www.faircom.com
All Rights Reserved
425
ctdbGetLibType
Retrieves the c-tree Plus operational model used when compiling the c-treeDB library.
Declaration
CTLIB_TYPE ctdbGetLibType(CTHANDLE Handle)
Description
ctdbGetLibType provides the ability to detect c-tree Plus operational model used when compiling a c-treeDB C library. Handle the Database Handle.
Returns
ctdbGetLibType returns a value of type CTLIB_TYPE.
CTLIB_TYPE Description Single user libary. Multi-user libary. Client libary LOCLIB model. Server side library. Multi-threaded enabled. Transaction processing enabled.
The return value has the following bits set if the library supports optional features.
Optional Bits Description Multi-threaded enabled. Transaction processing enabled.
CTLIB_THREA CTLIB_TRAN
See
"c-treeDB Errors and Return Values" for a complete listing of valid c-treeDB error codes and return values.
FairCom Corporation
426
ctdbGetKeepLock
Retrieves the current extended keep lock mode.
DECLARATION
CTKEEP_MODE ctdbDECL ctdbGetKeepLock(CTHANDLE Handle);
DESCRIPTION
ctdbGetKeepLock() retrieves the current state of how the transaction commit and abort will handle locks acquired before and during the transaction. Handle is a session handle.
RETURN
One of the following keep lock modes is returned:
Value 0 1 2 Symbolic Constant Explanation Release all locks. Clear LKISAM state. This is the default mode. Keep all locks acquired before and during transaction. The LKISAM state is not cleared. Release only locks obtained within transaction and/or locks on records updated within transaction. The LKISAM state is not cleared. Unconditionally keep all locks acquired before transaction began. Free locks obtained within the transaction. The LKISAM state is not cleared.
CTKEEP_OUTALL
See Appendix A for a complete listing of valid c-tree Plus error values.
EXAMPLE
/* make sure the current keep lock mode is CTKEEP_LOCK */ if (ctdbGetKeepLock(hSession) != CTKEEP_LOCK) if (ctdbSetKeepLock(hSession, CTKEEP_LOCK) != CTDBRET_OK) printf("ctdbSetKeepLock failed\n");
SEE ALSO
ctdbAbort ctdbBegin(), ctdbCommit(), ctdbSetKeepLock()
www.faircom.com
All Rights Reserved
427
ctdbGetLocalTag
Retrieves the local tag associate with a handle.
DECLARATION
pVOID ctdbGetLocalTag(CTHANDLE Handle);
DESCRIPTION
Retrieves the local tag associated with a handle. A localTag pointer is available for session, database, table and record handles, and is initialized with NULL when the handle is allocated. Handle is any c-treeDB session, table, record, or index handle.
RETURN
A pointer to a localTag, or NULL if Handle is NULL.
EXAMPLE
if (ctdbGetLocalTag(Handle)) { pSession->onFree(ctdbGetLocalTag(Handle)); ctdbSetLocalTag(Handle, NULL); }
SEE ALSO
ctdbGetHandleType(), ctdbSetLocalTag()
FairCom Corporation
428
ctdbGetLockMode
Retrieve the current session-wide lock mode.
Declaration
CTLOCK_MODE ctdbGetLockMode(CTHANDLE Handle)
Description
ctdbGetLockMode() retrieves the current session-wide lock mode. Valid lock modes are presented in "c-treeDB definitions".. Handle [in] the Session or any other c-treeDB Handle.
Returns
ctdbGetLockMode() returns the session-wide lock mode.
See also
ctdbLock(), ctdbIsLockActive()
www.faircom.com
All Rights Reserved
429
ctdbGetLogonOnly
Retrieve the session logon only flag.
Declaration
CTBOOL ctdbGetLogonOnly(CTHANDLE Handle)
Description
ctdbGetLogonOnly() retrieves the session logon only flag. This flag, when set to YES before the session Logon, will prevent the session from using the session dictionary. If the session dictionary may not be used, the database dictionary cannot be used. With this, any information related to databases or tables cannot be use, but the tables can yet be opened or created using the session handle. To set the flag, use ctdbSetLogonOnly(). Handle [in] the session handle.
Returns
ctdbGetLogonOnly() returns YES if the flag was set, and NO otherwise.
Example
if (!cdbGetLogonOnly(hSession)) err = ctdbConnect(hDatabase, "MyDatabase");
See also
ctdbSetLogonOnly()
FairCom Corporation
430
ctdbGetMinute
Get the minute from a packed CTTIME.
Declaration
NINT ctdbGetMinute(CTTIME Time)
Description
ctdbGetMinute() gets the minute from a packed CTTIME. Time is the packed time in CTTIME format.
Returns
ctdbGetMinute() returns the minute, on success or -1 on error.
See also
ctdbGetHour(), ctdbGetSecond()
www.faircom.com
All Rights Reserved
431
ctdbGetMonth
Retrieve the month of the year from a packed CTDATE.
Declaration
NINT ctdbGetMonth(CTDATE date)
Description
ctdbGetMonth() retrieves the month of the year from a packed CTDATE. To retrieve the day of the month from a packed CTDATE, use ctdbGetDay(). To retrieve the year from a packed CTDATE, use ctdbGetYear(). date is the date in CTDATE format.
Returns
ctdbGetMonth() returns the month of the year on success or 0 on error.
See also
ctdbGetDay(), ctdbGetYear()
FairCom Corporation
432
ctdbGetNextActiveDatabase
Retrieve the handle of the next active database in the session.
Declaration
CTHANDLE ctdbGetNextActiveDatabase(CTHANDLE Handle, pVRLEN pScanIndex)
Description
ctdbGetNextActiveDatabase() retrieves the handle of the next active database in the session. You must get the first active database with ctdbGetFirstActiveDatabase() before searching for the next active database. Handle [in] the session handle. pScanIndex [out] the pointer to a VRLEN to hold the scan state. It is returned by ctdbGetFirstActiveDatabase(), and it is updated in the ctdbGetNextActiveDatabase() function.
Returns
ctdbGetNextActiveDatabase() returns the database handle, or NULL if not found.
See also
ctdbAllocSession(), ctdbGetFirstActiveDatabase(), ctdbFindActiveDatabase(), ctdbFindActiveDatabaseByUID()
www.faircom.com
All Rights Reserved
433
ctdbGetNextActiveTable
Retrieve the handle of the next active table in the database.
Declaration
CTHANDLE ctdbGetNextActiveTable(CTHANDLE Handle, pVRLEN pScanRec)
Description
ctdbGetNextActiveTable() retrieves the handle of the next active table in the database. Obtain the first active database with ctdbGetFirstActiveTable() before searching for the next active database. Handle [in] the Database Handle. pScanRec [out] the pointer to a VRLEN to hold the scan state. It is first returned by ctdbGetFirstActiveTable(), and it is updated in the ctdbGetNextActiveTable() function.
Returns
ctdbGetNextActiveTable() returns the database handle, or NULL if not found.
See also
ctdbAllocSession(), ctdbGetFirstActiveTable(), ctdbFindActiveTable()
FairCom Corporation
434
ctdbGetOperationState
Declaration
CTOPS_MODE ctdbDECL ctdbGetOperationState(CTHANDLE Handle);
Description
Retrieve the c-tree operation modes for special performance-related functionality and test operational states for critical events. Handle is a session handle.
Return Values
ctdbGetOperationState() returns a combination of the following CTOPS_MODE codes on success:
Operations Mode Description Enable automatic, low level, blocking read locks on each record access that does not already have a lock. Lock next fetch only. Automatic unlock on add. Automatic unlock on rewrite. (OPS_UNLOCK_ADD | OPS_UNLOCK_RWT) Blocking lock on next fetch only. Toggle function monitor. (Server) Toggle lock monitor. (Server) Toggle memory track monitor. (Server) Dont continue if mirror or primary fails. (Server) A primary or mirror has been shutdown. Memory swapping active. Automatic ISAM transactions. Auto commit on swap occurred. Changes GetSerialNbr() operation. Defer file closes or deletes during transactions. Change all CT_STRING fields having a non-zero field length in the fixed length portion of the record buffer to CT_FSTRING fields. (Client) Set sysiocod on disk reads and writes.
OPS_READLOCK OPS_LOCKON_GET OPS_UNLOCK_ADD OPS_UNLOCK_RWT OPS_UNLOCK_UPD OPS_LOCKON_BLK OPS_FUNCTION_MON OPS_LOCK_MON OPS_TRACK_MON OPS_MIRROR_NOSWITCH OPS_MIRROR_TRM OPS_MEMORY_SWP OPS_AUTOISAM_TRN OPS_COMMIT_SWP OPS_SERIAL_UPD OPS_DEFER_CLOSE OPS_CONV_STRING
OPS_DISK_IO
See Also
ctdbGetOperationState() ctdbGetAutoCommit() ctdbSetAutoCommit()
www.faircom.com
All Rights Reserved
435
ctdbGetPadChar
Retrieve the table pad and field delimiter characters.
Declaration
CTDBRET ctdbGetPadChar(CTHANDLE Handle, pTEXT pPadChar, pTEXT pDmlChar)
Description
ctdbGetPadChar() retrieves the table pad and field delimiter characters. These characters are used to pad fixed string fields (CT_FSTRING) to allow proper target key formation. Handle [in] the Table Handle. pPadChar [out] Pointer to receive the pad character pDmlChar [out] Pointer to receive the field delimiter character.
Returns
ctdbGetPadChar() returns CTDBRET_OK on success, or c-treeDB C API error code on failure.
See also
ctdbSetPadChar(), ctdbUpdatePadChar()
FairCom Corporation
436
ctdbGetPathPrefix
Returns the client-side path prefix.
DECLARATION
pTEXT ctdbGetPathPrefix(CTHANDLE hSession);
DESCRIPTION
A path prefix can be set anytime after the session handle is allocated. If a path prefix is set before a session logon, the new path prefix will affect the location of the session dictionary file. If a path prefix is set after a session logon, but before a database connect, then the path prefix affects only the database dictionary and any tables that are manipulated during that session. A path prefix can be removed at any time by setting a NULL value for the path prefix. You can use ctdbGetPathPrefix() to check if a path prefix is set or not. If ctdbGetPathPrefix() returns NULL, then no path prefix is set.
RETURN
Value 0 NULL Symbolic Constant NO_ERROR NULl Explanation No error occurred. No path prefix was set.
See Appendix A for a complete listing of valid c-tree Plus error values.
EXAMPLE
/* get the current path prefix */ YourPathPrefix = ctdbGetPathPrefix(AnyHandle); if (CurrentPathPrefix == NULL) printf("ctdbGetPathPrefix() returned no path.\n");
SEE ALSO
ctdbSetPathPrefix()
www.faircom.com
All Rights Reserved
437
ctdbGetRebuildProgress
Retrieves the tables rebuild progress counter.
DECLARATION
NINT ctdbGetRebuildProgress(CTHANDLE Handle);
DESCRIPTION
When a full alter table rebuild is in progress, the table handle keeps a counter of the progress. The progress is kept in terms of percent completed with values from 0% to 100%. You can use this function with a CTDB_ON_TABLE_REBUILD callback to retrieve the progress indicator. CTDB_ON_TABLE_REBUILD is called for each percentage point. Before any records are processed, CTDB_ON_TABLE_REBUILD callback is called with a percentage value of zero to indicate that the operation is about to start. After all records are processed, CTDB_ON_TABLE_REBUILD is called again, this time with a percentage value of 100 to indicate the end of rebuild.
RETURN
A progress counter value from 0 to 100.
EXAMPLE
CTDBRET ctdbDECL OnTableRebuild(CTHANDLE Handle) { /* display a dot for every 5% rebuild completed */ NINT perc = ctdbGetREbuildProgress(Handle); if (perc > 0 && (perc % 5) == 0) printf("."); return CTDBRET_OK; }
SEE ALSO
ctdbClearAllCallback(), ctdbClearCallback(), ctdbGetCallback(), ctdbSetCallback()
FairCom Corporation
438
ctdbGetRecord
Retrieve the record handle from the table's active record list.
Declaration
CTHANDLE ctdbGetRecord(CTHANDLE Handle)
Description
ctdbGetRecord() retrieves the record handle from the table's active record list. Handle [in] the Table Handle.
Returns
ctdbGetRecord() returns the record handle on success, or NULL on error.
See also
ctdbAllocRecord(), ctdbGetDatabaseHandle(), ctdbGetFieldHandle()
www.faircom.com
All Rights Reserved
439
ctdbGetRecordBuffer
Return a pointer to the current record buffer.
Declaration
pVOID ctdbGetRecordBuffer(CTHANDLE Handle)
Description
ctdbGetRecordBuffer() returns a pointer to the current record buffer. Handle [in] the record handle.
Returns
ctdbGetRecordBuffer() returns the record buffer, or NULL on error
See also
ctdbAllocRecord(), ctdbGetRecordLength()
FairCom Corporation
440
ctdbGetRecordCount
Retrieve the number of records in Table.
Declaration
CTDBRET ctdbGetRecordCount(CTHANDLE Handle, pCTUINT64 pCount)
Description
ctdbGetRecordCount() retrieves the number of records in the table. Handle [in] the record handle. pCount [out] receives the number of records in the table.
Returns
ctdbGetRecordCount() returns CTDBRET_OK on success, or a c-treeDB C API error code on failure
See also
ctdbAllocRecord()
www.faircom.com
All Rights Reserved
441
ctdbGetRecordHandle
Retrieve the record handle
Declaration
CTHANDLE ctdbGetRecordHandle(CTHANDLE Handle)
Description
ctdbGetRecordHandle() retrieves the record handle. To allocate a record handle, use ctdbAllocRecord(). Handle [in] must be a record handle, otherwise ctdbGetRecordHandle() returns NULL.
Returns
ctdbGetRecordHandle() returns a record handle on success or NULL on error.
See also
ctdbAllocRecord()
FairCom Corporation
442
ctdbGetRecordLength
Return the current record length.
Declaration
VRLEN ctdbGetRecordLength(CTHANDLE Handle)
Description
ctdbGetRecordLength() returns the current record length. Handle [in] the record handle.
Returns
ctdbGetRecordLength() returns the record length or 0 on error.
See also
ctdbAllocRecord(), ctdbGetRecordBuffer(), ctdbGetRecordSize()
www.faircom.com
All Rights Reserved
443
ctdbGetRecordLock
Return the record lock status.
Declaration
CTLOCKMODE ctdbGetRecordLock(CTHANDLE Handle)
Description
ctdbGetRecordLock() retrieves the record lock status. Handle [in] the record handle.
Returns
ctdbGetRecordLock() returns the lock mode, in particular, CTLOCK_FREE if the record is not locked, CTLOCK_READ if the record has a read lock or CTLOCK_WRITE if the record has a write lock.
See also
ctdbAllocRecord(), ctdbLockRecord(), ctdbUnlockRecord()
FairCom Corporation
444
ctdbGetRecordNbr
Retrieve the record index number in the table's active record list
Declaration
NINT ctdbGetRecordNbr(CTHANDLE Handle)
Description
ctdbGetRecordNbr() retrieves the record index number in the table's active record list. Handle [in] the record handle.
Returns
ctdbGetRecordNbr() returns the record index number or -1 on error.
See also
ctdbAllocRecord(), ctdbGetRecordBuffer(), ctdbGetRecordLength()
www.faircom.com
All Rights Reserved
445
ctdbGetRecordPos
Retrieve the current record offset position.
Declaration
CTDBRET ctdbGetRecordPos(CTHANDLE Handle, pCTOFFSET pOffset)
Description
ctdbGetRecordPos() retrieves the current record offset position if the table has support to a RECBYT index. When the table is created, by default it includes a RECBYT index. In order to verify if the table has support to a RECBYT index, use ctdbHasRecbyt(). Handle [in] the record handle. pOffset [out] receives the current record offset position.
Returns
ctdbGetRecordPos() returns CTDBRET_OK on success, or a c-treeDB C API error code on failure
See also
ctdbSetRecordPos(), ctdbSetRecordOffset(), ctdbSeekRecord(), ctdbHasRecbyt(), ctdbCreateTable()
FairCom Corporation
446
ctdbGetRecordSize
Return the allocated record buffer size in bytes.
Declaration
VRLEN ctdbGetRecordSize(CTHANDLE Handle)
Description
ctdbGetRecordSize() returns the allocated record buffer size in bytes. Handle [in] the record handle.
Returns
ctdbGetRecordSize() returns the record size or 0 on error.
See also
ctdbAllocRecord(), ctdbGetRecordBuffer(), ctdbGetRecordLength()
www.faircom.com
All Rights Reserved
447
ctdbGetResourceData
Return a pointer to the resource data .
DECLARATION
pVOID ctdbDECL ctdbGetResourceData(CTHANDLE resource);
DESCRIPTION
Returns a pointer to the resource data. Call this function to retrieve the resource data pointer after a resource is read by one of ctdbFirstResource(), ctdbNextResource(), ctdbFindResource() or ctdbFindResourceByName(). resource is a handle returned by ctdbAllocResource().
RETURN
Return a pointer to resource data
EXAMPLE
CTDBRET ReadMyResource(CTHANDLE Handle, ULONG type, ULONG number, ppVOID data, pVRLEN size) { CTDBRET eRet; CTHANDLE hRes = ctdbAllocResource(Handle, type, number, NULL); /* check the resource handle allocation */ if (hRes == NULL) { eRet = ctdbGetError(Handle); goto Exit; } /* get the resource */ if ((eRet = ctdbFindResource(hRes, type, number, NO)) != CTDBRET_OK) goto Exit; /* allocate a buffer large enough for the resource data */ *size = ctdbGetResourceDataLength(hRes); if (*size > 0) { *data = (pVOID)malloc(*size); if (*data == NULL) { eRet = CTDBRET_NOMEMORY; goto Exit; } memcpy(*data, ctdbGetResourceData(hRes), *size); } Exit: if (hRes) ctdbFreeResource(hRes); return eRet; }
SEE ALSO
ctdbAllocResource, ctdbFreeResource, ctdbAddResource, ctdbDeleteResource, ctdbUpdateResource, ctdbFirstResource, ctdbNextResource, ctdbFindResource, ctdbFindResourceByName, ctdbGetResourceType, ctdbSetResourceType, ctdbGetResourceNumber, ctdbSetResourceNumber, ctdbGetResourceName, ctdbSetResourceName, ctdbGetResourceDataLength, ctdbSetResourceData, ctdbIsResourceLocked, ctdbUnlockResource
FairCom Corporation
448
ctdbGetResourceDataLength
Retrieves the resource data length.
DECLARATION
VRLEN ctdbDECL ctdbGetResourceDataLength(CTHANDLE resource);
DESCRIPTION
Retrieves the resource data length as the number of bytes occupied by the resource data. resource is a handle allocated by ctdbAllocResource().
RETURN EXAMPLE
CTDBRET ReadMyResource(CTHANDLE Handle, ULONG type, ULONG number, ppVOID data, pVRLEN size) { CTDBRET eRet; CTHANDLE hRes = ctdbAllocResource(Handle, type, number, NULL); /* check the resource handle allocation */ if (hRes == NULL) { eRet = ctdbGetError(Handle); goto Exit; } /* get the resource */ if ((eRet = ctdbFindResource(hRes, type, number, NO)) != CTDBRET_OK) goto Exit; /* allocate a buffer large enough for the resource data */ *size = ctdbGetResourceDataLength(hRes); if (*size > 0) { *data = (pVOID)malloc(*size); if (*data == NULL) { eRet = CTDBRET_NOMEMORY; goto Exit; } memcpy(*data, ctdbGetResourceData(hRes), *size); } Exit: if (hRes) ctdbFreeResource(hRes); return eRet; }
SEE ALSO
ctdbAllocResource, ctdbFreeResource, ctdbAddResource, ctdbDeleteResource, ctdbUpdateResource, ctdbFirstResource, ctdbNextResource, ctdbFindResource, ctdbFindResourceByName, ctdbGetResourceType, ctdbSetResourceType, ctdbGetResourceNumber, ctdbSetResourceNumber, ctdbGetResourceName, ctdbSetResourceName, ctdbGetResourceData, ctdbSetResourceData, ctdbIsResourceLocked, ctdbUnlockResource
www.faircom.com
All Rights Reserved
449
ctdbGetResourceName
Retrieve the resource name.
DECLARATION
pTEXT ctdbDECL ctdbGetResourceName(CTHANDLE resource);
DESCRIPTION
Retrieve the resource name. A NULL value may be returned to indicate that the resource name was not set.
RETURN
Returns a pointer to the resource name
EXAMPLE
if (ctdbGetResourceName(hRes) == NULL) ctdbSetResourceName(hRes, MyResource);
SEE ALSO
ctdbAllocResource, ctdbFreeResource, ctdbAddResource, ctdbDeleteResource, ctdbUpdateResource, ctdbFirstResource, ctdbNextResource, ctdbFindResource, ctdbFindResourceByName, ctdbGetResourceType, ctdbSetResourceType, ctdbGetResourceNumber, ctdbSetResourceNumber, ctdbSetResourceName, ctdbGetResourceDataLength, ctdbGetResourceData, ctdbSetResourceData, ctdbIsResourceLocked, ctdbUnlockResource
FairCom Corporation
450
ctdbGetResourceNumber
Retrieve the resource number.
DECLARATION
ULONG ctdbDECL ctdbGetResourceNumber(CTHANDLE resource);
DESCRIPTION
Retrieves the resource number. resource is a handle allocated by ctdbAllocResource().
RETURN
Return the resource name
EXAMPLE
if (ctdbGetResourceNumber(hRes) != number) ctdbSetResourceNumber(hRes, number);
SEE ALSO
ctdbAllocResource, ctdbFreeResource, ctdbAddResource, ctdbDeleteResource, ctdbUpdateResource, ctdbFirstResource, ctdbNextResource, ctdbFindResource, ctdbFindResourceByName, ctdbGetResourceType, ctdbSetResourceType, ctdbSetResourceNumber, ctdbGetResourceName, ctdbSetResourceName, ctdbGetResourceDataLength, ctdbGetResourceData, ctdbSetResourceData, ctdbIsResourceLocked, ctdbUnlockResource
www.faircom.com
All Rights Reserved
451
ctdbGetResourceType
Retrieve the resource type.
DECLARATION
ULONG ctdbDECL ctdbGetResourceType(CTHANDLE resource);
DESCRIPTION
Retrieve the resource type. resource is a handle allocated by ctdbAllocResource().
RETURN
Returns the resource type.
EXAMPLE
if (ctdbGetResourceType(hRes) != type) ctdbSetResourceType(hRes, type);
SEE ALSO
ctdbAllocResource, ctdbFreeResource, ctdbAddResource, ctdbDeleteResource, ctdbUpdateResource, ctdbFirstResource, ctdbNextResource, ctdbFindResource, ctdbFindResourceByName, ctdbSetResourceType, ctdbGetResourceNumber, ctdbSetResourceNumber, ctdbGetResourceName, ctdbSetResourceName, ctdbGetResourceDataLength, ctdbGetResourceData, ctdbSetResourceData, ctdbIsResourceLocked, ctdbUnlockResource
FairCom Corporation
452
ctdbGetRowid
Retrieve the record rowid.
Declaration
CTDBRET ctdbGetRowid(CTHANDLE Handle, pCTROWID pRowid)
Description
ctdbGetRowid() retrieves the record ROWID. Handle [in] the record handle. pRowid [out] the ROWID value.
Returns
ctdbGetRowid() returns CTDBRET_OK on success, or a c-treeDB C API error code on failure
See also
ctdbAllocRecord(), ctdbFindRowid(), ctdbHasRowid()
www.faircom.com
All Rights Reserved
453
ctdbGetSecond
Get the second from a packed CTTIME.
Declaration
NINT ctdbGetSecond(CTTIME Time)
Description
ctdbGetSecond() gets the second from a packed CTTIME. Time is the packed time in CTTIME format.
Returns
ctdbGetSecond() returns the minute, on success or -1 on error.
See also
ctdbGetMinute(), ctdbGetHour()
FairCom Corporation
454
ctdbGetSegment
Retrieve the segment handle of the segment indicated by SegNumber.
Declaration
CTHANDLE ctdbGetSegment(CTHANDLE Handle, NINT SegNumber)
Description
ctdbGetSegment() retrieves the segment handle of the segment indicated by SegNumber. Handle [in] the index handle. SegNumber [in] the Index segment number to be retrieved.
Returns
ctdbGetSegment() returns the segment handle, or NULL on error.
See also
ctdbAllocIndex()
www.faircom.com
All Rights Reserved
455
ctdbGetSegmentField
Retrieve the field handle of the segment.
Declaration
CTHANDLE ctdbGetSegmentField(CTHANDLE Handle)
Description
ctdbGetSegmentField() retrieve the field handle of the segment. Handle [in] the Segment Handle.
Returns
ctdbGetSegmentField() returns the field handle, or NULL on error.
See also
ctdbAllocSegment()
FairCom Corporation
456
ctdbGetSegmentFieldName
Get the field name of the index segment.
Declaration
pTEXT ctdbGetSegmentFieldName(CTHANDLE Handle)
Description
ctdbGetSegmentFieldName() gets the field name of the index segment. Handle [in] the Segment Handle.
Returns
ctdbGetSegmentFieldName() returns the field name, or NULL on error
See also
ctdbAllocSegment()
www.faircom.com
All Rights Reserved
457
ctdbGetSegmentHandle
Retrieve a segment handle.
Declaration
CTHANDLE ctdbGetSegmentHandle(CTHANDLE Handle)
Description
ctdbGetSegmentHandle() retrieves a segment handle. Handle [in] the Segment Handle.
Returns
ctdbGetSegmentHandle() returns segment handle on success or NULL on failure.
See also
ctdbAllocSegment()
FairCom Corporation
458
ctdbGetSegmentKSeg
Retrieves the segment extended key definition.
DECLARATION
CTDBRET ctdbGetSegmentKSeg(CTHANDLE Handle, pctKSEGDEF pKSeg);
DESCRIPTION
ctdbGetSegmentKSeg() retrieves the current extended key segment definition. Handle must be a segment handle and pKSeg is a pointer to an extended key segment definition structure which will receive the definition.
RETURN
Value 0 4096 Symbolic Constant Explanation No error occurred. Not found.
CTDBRET_OK CTDBRET_NOTFOUND
See Appendix A for a complete listing of valid c-tree Plus error values.
EXAMPLE
ctKSEGDEF kseg; if ((eRet = ctdbGetSegmentKSeg(hTable, &kseg)) != CTDBRET_OK) printf(ctdbGetSegmentKSeg failed with error %d\n, eRet);
SEE ALSO
ctdbSetTableKSeg(), ctdbGetTableKSeg(), ctdbSetIndexKSeg(), ctdbGetIndexKSeg(), ctdbSetSegmentKSeg(), ctdbSetKSegDefaults()
www.faircom.com
All Rights Reserved
459
ctdbGetSegmentMode
Retrieve the segment mode
Declaration
CTSEG_MODE ctdbGetSegmentMode(CTHANDLE Handle)
Description
ctdbGetSegmentMode() retrieves the segment mode. Use ctdbSetSegmentMode() to set the segment mode. Handle [in] the Segment Handle.
Returns
ctdbGetSegmentMode() returns the segment mode, or c-treeDB C API error on failure.
See also
ctdbAllocSegment(), ctdbSetSegmentMode()
FairCom Corporation
460
ctdbGetSegmentNbr
Retrieve the segment number in the segment list on the index handle.
Declaration
CTDBRET ctdbGetSegmentNbr(CTHANDLE Handle, pVRLEN pNumber)
Description
ctdbGetSegmentNbr() retrieves the segment number in the segment list, given a Segment Handle. Use ctdbGetIndexNbr() to retrieve the index number. Handle [in] the Segment Handle. pNumber [out] the segment number.
Returns
ctdbGetSegmentNbr() returns CTDBRET_OK on success, or a c-treeDB C API error code on failure.
See also
ctdbGetIndexNbr()
www.faircom.com
All Rights Reserved
461
ctdbGetSegmentPartialField
Retrieves the field handle on which a key segment is based, even if the segment does not match the entire field length.
DECLARATION
CTHANDLE ctdbDECL ctdbGetSegmentPartialField(CTHANDLE Handle);
DESCRIPTION
c-treeDB was able to find the matching between a key segment and a field only if the key segment started at the beginning of a field and exactly matched the field length, as it is required by c-treeSQL. It was desirable to retrieve a field on which the key segment start at the beginning of a field but does not exactly match the entire field. CtdbGetSegmentPartialField() was added to c-treeDB C API to retrieve the field handle on which a key segment is based, even if the segment does not match the entire field length. Handle is the segment handle that we are trying to match to one of the table fields. ctdbGetSegmentPartialField() returns the handle of the field that matches the key segment definition. If a match cant be found, or if an error is detected, this function returns NULL.
RETURN
Returns the field handle that matches the segment or NULL if no such match exists.
EXAMPLE
/* try to find a match, or partial match, for the key segment */ CTHANDLE GetFieldMatch(CTHANDLE hIndex, NINT segnbr) { CTHANDLE hField = NULL; CTHANDLE hSegment = ctdbGetSegment(hIndex, segnbr); if (hSegment) hField = ctdbGetSegmentPartialField(hSegment); return hField; }
SEE ALSO
ctdbGetSegmentField(), ctdbGetSegmentFieldName()
FairCom Corporation
462
ctdbGetSegmentStatus
Retrieves the status of the segment handle.
DECLARATION
ULONG ctdbGetSegmentStatus(CTHANDLE Handle);
DESCRIPTION
Retrieves the status of a segment handle. Handle is a segment handle. The status of the segment handle is a bit map describing one or more changes that have occurred to the segment handle.
RETURN
ctdbGetSegmentStatus returns a bitmap of the following:
Value 0x00 0x01 0x02 0x04 0x10 0x20 Symbolic Constant Explanation Original segment as read from file Segment added or inserted Original segment deleted Original segment moved Segment mode changed Segment field changed
See Appendix A for a complete listing of valid c-tree Plus error values.
EXAMPLE
/* if any segment of an index has changed, call alter table */ for (i = 0; i < (NINT) ctdbGetIndexSegmentCount(hIndex); i++) { CTHANDLE hSeg = ctdbGetSegment(hIndex, i); if (ctdbGetSegmentStatus(hSeg) != CTDBISEG_OLD) if (ctdbAlterTable(hIndex, CTDB_ALTER_NORMAL) != CTDBRET_OK) printf("ctdbAlterTable failed\n"); }
SEE ALSO
ctdbGetFieldStatus(), ctdbGetIndexStatus()
www.faircom.com
All Rights Reserved
463
ctdbGetServerName
Return the server name associated with the session.
Declaration
pTEXT ctdbGetServerName(CTHANDLE Handle)
Description
ctdbGetServerName() returns the server name associated with the session. You must log on to the server with ctdbLogon() before getting the server name. Handle [in] the session handle.
Returns
ctdbGetServerName() returns a pointer to the Server name, or Null on failure.
Example
username=ctdbGetUserLogonName(hSession); userpass=ctdbGetUserPassword(hSession); servname=ctdbGetServerName(hSession);
See also
ctdbLogon(), ctdbAllocSession(), ctdbGetUserLogonName()
FairCom Corporation
464
ctdbGetSessionHandle
Return the session handle from the opaque handle.
Declaration
CTHANDLE ctdbGetSessionHandle(CTHANDLE Handle)
Description
ctdbGetSessionHandle() returns the session handle from the opaque handle, having as parameter any handle inside the session. To allocate a session handle, use ctdbAllocSession(). Handle [in] may be a session handle, a database handle, a table handle, a record handle, a field handle, an index handle, or a segment handle.
Returns
ctdbGetSessionHandle() returns the session handle or NULL on failure.
Example
hSess=ctdbGetSessionHandle(hDatabase);
See also
ctdbAllocSession(), ctdbAllocDatabase(), ctdbAllocTable(), ctdbAllocRecord(), ctdbAllocField(), ctdbAllocIndex(), ctdbAllocSegment(), ctdbGetDatabaseHandle()
www.faircom.com
All Rights Reserved
465
ctdbGetSessionParams
Return the session parameter based on the parameter type.
Declaration
NINT ctdbGetSessionParams(CTHANDLE Handle, CTSESSION_PARAM ParamType)
Description
ctdbGetSessionParams() returns the session parameter based on the parameter type. The application must log on to the server with ctdbLogon() before getting the session parameter type. Handle [in] the session handle. ParamType [in] the parameter type. Valid values for ParamTypes are: CT_BUFS: the number of index file buffers, minimum 3 CT_FILS: initial block of file structures. CT_SECT: the number of node sectors. Minimum of one required. sect multiplied by 128 equals the index node size. CT_DBUFS: the number of buffers for data files I/O CT_USERPROF: is the user profile mask, and accepts the following values: USERPRF_CLRCHK - instructs single-user TRANPROC applications to remove S*.FCS and L*.FCS files upon a successful application shutdown. The c-tree Plus checkpoint code determines at the time of a final checkpoint if there are no pending transactions or file opens, and if this user profile bit has been turned on. If so, the S*.FCS and L*.FCS files are deleted. However, if the application is causing log files to be saved (very unusual for a single-user application), then the files are not cleared. The USERPRF_CLRCHK option is off by default. See 13.3 Single-User Transaction Processing in the c-tree Plus Programmer's Reference Guide for additional information. USERPRF_LOCLIB - specifies this instance of c-tree Plus is to be directed to a local database. Applicable only to client/server when using Local Library Support. USERPRF_NDATA - enable the manual mode of UNIFRMAT support. Enabling the manual record transformation mode would only be desirable when performing custom record level byte flipping or when record structures contain no numeric data (i.e., LONG, FLOAT, . . .). A side benefit of enabling this manual mode is the virtual elimination of Server DODA requests, thereby reducing network traffic by one function call per file open. USERPRF_NTKEY - disables the automatic TransformKey() feature. See TransformKey in the c-tree Plus Programmer's Reference Guide for more information. USERPRF_PTHTMP - changes GetCtTempFileName() from its default operation of returning a temporary file name to specifying a directory name where temporary files are to reside. USERPRF_SAVENV - enable the automatic SAVENV feature. See the Begin() function description for more information. To use more than one value, OR the values together. Leave CT_USERPROF set to zero to accept the defaults.
Returns
Returns the parameter value. If an invalid handle or parameter type is passed, ctdbGetSessionParams() returns 0.
Example
FairCom Corporation
466
CTSESSION_TYPE ctdbsess=CTSESSION_CTDB; CTHANDLE hSession = ctdbAllocSession(ctdbsess); CTDBRET err; NINT ret, newbuf; err = ctdbLogon(hSession, "FAIRCOMS", "ADMIN", "ADMIN"); ret = ctdbGetSessionParams(hSession, CT_BUFS); newbuf = ret + 2; err = ctdbSetSessionParams(hSession, CT_BUFS, newbuf);
See also
ctdbGetServerName(), ctdbGetUserLogonName(), ctdbAllocSession(), ctdbSetSessionParams()
www.faircom.com
All Rights Reserved
467
ctdbGetSessionPath
Return the default session path.
Declaration
CTDBRET ctdbGetSessionPath(CTHANDLE Handle, pTEXT Path, VRLEN PathSize)
Description
ctdbGetSessionPath() returns the session path. Use ctdbSetSessionPath() to set the session path. Handle [in] the session handle. Path [out] the pointer to a C string where the session path is returned. PathSize [in] the Path size in bytes. If Path is not large enough to hold the session path, the error CTDBRET_ARGSMALL (4006) is returned.
Returns
ctdbGetSessionPath() returns CTDBRET_OK if successful, or the c-tree Plus error code on failure, or CTDBRET_ARGSMALL (4006) if the Path is not large enough to hold the session path.
Example
eRet = ctdbLogon(handle, "FAIRCOMS", "ADMIN", "ADMIN"); eRet = ctdbGetSessionPath(handle, ses_path, sizeof(ses_path));
See also
ctdbSetSessionPath()
FairCom Corporation
468
ctdbGetSessionType
Retrieve the current session type.
Declaration
CTSESSION_TYPE ctdbGetSessionType(CTHANDLE Handle)
Description
ctdbGetSessionType() retrieves the current session type. The session type is initially set when ctdbAllocSession() is called to allocate a new session handle, and it can be modified using ctdbSetSessionType(). Handle [in] the session handle.
Returns
ctdbGetSessionType() returns the session type. If the session handle is not valid, ctdbGetSessionType() always return CTSESSION_CTDB.
See also
ctdbSetSessionType()
www.faircom.com
All Rights Reserved
469
ctdbGetSystemConfig
Retrieves c-tree Plus system configuration values.
DECLARATION
LONG ctdbGetSystemConfig(NINT index);
DESCRIPTION
ctdbGetSystemConfig() retrieves c-tree Plus system configuration values, as well as some of the important dynamic aspects of the system, such as the memory usage and the number of files in use. To determine if a particular system configuration option is active, call ctdbGetSystemConfig(), passing the corresponding pre-defined constant for that option, and check if the value returned is non-zero. The following pre-defined constant should be passed to ctdbGetSystemConfig():
Constant Description Current system memory usage. Highest system memory use. Current system net allocations. c-tree Plus files opened by system. Physical c-tree Plus files open. Includes c-tree Superfile members omitted from cfgOPEN_FILES count. c-tree Plus file control blocks in use by system. Is file mode ctLOGIDX supported?
cfgDNODE_QLENGTH cfgCHKPNT_QLENGTH cfgSYSMON_QLENGTH cfgLOGONS cfgNET_LOCKS cfgUSERS cfgMAX_CONNECT cfgUSER_FILES cfgUSER_MEMORY cfgPATH_SEPARATOR
FairCom Corporation
470
The constants above and the pre-initialization resources section below have client and c-tree Server versions, except for the following three subscripts:
Constant Description Determine whether c-tree Plus has been initialized. The c-tree Server serial number. Indicates if threading has been enabled.
Constants ending with app are specific to the client side of a client/server application. To check the same system setting for the c-tree Server, use the same subscript without the app extension. For example, to determine if Conditional Index support is active on the c-tree Server, use cfgCONDIDX as the subscript and cfgCONDIDXapp for the client side.
Constant Description Indicates if the application is bound to a database library. See the discussion on the different FairCom I/O models in these notes. A non-zero value indicates a stand-alone multi-user I/O model i.e. FPUTFGET. A non-zero value indicates Local Library support. A non-zero value indicates no globals are supported i.e. indicating all globals are stored in an allocated structure. This is the default setting. A non-zero value indicates FairCom's automatic byte flipping (UNIFRMAT) is active.
The pre-initialization resource constants below may be specified prior to a c-treeDB initialization call, i.e ctdbLogon(), CTSession::Logon(), or CTSession.Logon(), in addition to having both a client and c-tree Server version, as discussed above.
Constant Description Specifies whether to use ANSI. A non-zero value indicates ANSI. A non-zero value indicates the application supports. FairCom's Conditional Index Logic. A non-zero value indicates the application supports. Batch Operations. A non-zero value indicates the application supports c-tree Superfiles. A non-zero value indicates the application supports FairCom's ISAM API. A non-zero value indicates the application supports FairCom's History Logic.
www.faircom.com
All Rights Reserved
471
Constant
Description A non-zero value indicates c-tree Plus has been initialized. A non-zero value indicates the application supports the ctLOGIDX Logic. A non-zero value indicates parameter files are supported. A non-zero value indicates 2-byte/4-byte length delimited strings are using the traditional pascal length convention. A non-zero value indicates byte length delimited strings are using the traditional pascal length convention. Return the ASCII value for the file name path separator. A non-zero value indicates the application supports Prototypes. A non-zero value indicates the application supports Resource Records. A non-zero value indicates the application supports the r-tree report engine. Return c-tree Server serial number. A non-zero value indicates the application supports FairCom's threading API. A non-zero value indicates the application supports Transaction Processing. A non-zero value indicates the application supports Variable Length Records. A non-zero value indicates the application supports Variable Length Keys i.e. Key compression. Indicates the client data order: Low_High or High_Low. A non-zero value indicates Low_High.
cfgINIT_CTREEapp cfgLOGIDXapp cfgPARMFILEapp cfgPASCAL24app1 cfgPASCALstapp1 cfgPATH_SEPARATORapp cfgPROTOTYPEapp cfgRESOURCEapp cfgRTREEapp cfgSERIALNBR cfgTHREADapp cfgTRANPROCapp cfgVARLDATAapp cfgVARLKEYSapp cfgWORD_ORDERapp
1Pascal length byte c-tree Plus supports two different methods for specifying the length byte in a pascal data type. The original and non-traditional approach does not include the length byte in the byte count. For example, with a 1-byte data type, CT_FPSTRING, the smallest valid length byte would be 0. The new method follows the more traditional pascal convention of including the length byte in the byte count. For example, with the traditional approach, the smallest valid length for a 1-byte data type would be 1. Therefore, if cfgPASCALstapp or cfgPASCAL24app return a non-zero value, the new traditional approach is active. To receive a valid return value from cfgPATH_SEPARATOR, ctPATH_SEP must be defined. The default definition found in ctopt2.h is:
#define ctPATH_SEP '?'
This definition specifies that the system default path separator will be used. To use the same separator for all platforms, you might want to choose one of the following:
#define ctPATH_SEP '\\' /* define for Windows, DOS and OS/2 */ #define ctPATH_SEP '/' /* define for most Unix systems */ #define ctPATH_SEP ':'
FairCom Corporation
472
/* define for Apple System 7 and PowerMac */ /* where the Uninitialized value is NINT_ERR for a client or FINT_ERR for a bound application */
The following constants can be used to capture system-wide cache and buffer statistics, (cache pages hold data record images and buffers hold index nodes), allowing an application to track the use of these resources.
Constant Description Available cache pages Cache pages in use Maximum cache pages used Available dedicated cache pages Dedicated cache pages in use Maximum dedicated cache pages used Available index buffers Index buffers in use Maximum index buffers used
RETURN
Returns a value that depends on the configuration constant passed to ctdbGetSystemConfig()
EXAMPLE
/* check if TRANPROC was turned on */ if (ctdbGetSystemConfig(ctTRANPROC)) printf("TRANPROC was turned on during compilation\n"); else printf("TRANPROC was turned off during compilation\n");
SEE ALSO
none
www.faircom.com
All Rights Reserved
473
ctdbGetTable
Return the table handle, given its position in the database active table list.
Declaration
CTHANDLE ctdbGetTableNbr(CTHANDLE Handle, NINT index)
Description
ctdbGetTable() retrieves the table handle, given its position in the database's active table list. Handle [in] Database Handle. index [in] the table position in the database table list.
Returns
ctdbGetTable() returns the table handle or null on error
See also
ctdbGetTableName(), ctdbGetTableNbr()
FairCom Corporation
474
ctdbGetTableCount
Retrieve the number of tables in the database dictionary.
Declaration
NINT ctdbGetTableCount(CTHANDLE Handle)
Description
ctdbGetTableCount() returns the number of tables in the database dictionary. Handle [in] the Database Handle.
Returns
ctdbGetTableCount() returns the number of tables in the database dictionary, or -1 on error.
See also
ctdbGetDatabaseCount()
www.faircom.com
All Rights Reserved
475
ctdbGetTableCreateMode
Retrieve the table create mode.
Declaration
CTCREATE_MODE ctdbGetTableCreateMode(CTHANDLE Handle)
Description
ctdbGetTableCreateMode() retrieves the table creation mode. To retrieve the table open mode, use ctdbGetTableOpenMode(). To create a table, use ctdbCreateTable(). Handle [in] the Table Handle.
Returns
ctdbGetTableCreateMode() returns the table create mode. The valid values for the table create mode are listed in "c-treeDB definitions"..
See also
ctdbAllocTable(), ctdbGetTableOpenMode(), ctdbCreateTable()
FairCom Corporation
476
ctdbGetTableDefaultDataExtentSize
Retrieve the table default data extent size
Declaration
NINT ctdbGetTableDefaultDataExtentSize(CTHANDLE Handle)
Description
ctdbGetTableDefaultDataExtentSize() retrieves the table default data extent size. Use ctdbGetTableDefaultIndexExtentSize() to retrieve the table default index extend size. Use ctdbSetTableDefaultDataExtentSize() to set the table default data extent size. Handle [in] the Table Handle.
Returns
ctdbGetTableDefaultDataExtentSize() returns the table default data extent size.
See also
ctdbGetTableDefaultIndexExtentSize(), ctdbSetTableDefaultDataExtentSize()
www.faircom.com
All Rights Reserved
477
ctdbGetTableDefaultIndexExtentSize
Retrieve the table default index extent size
Declaration
NINT ctdbGetTableDefaultIndexExtentSize(CTHANDLE Handle)
Description
ctdbGetTableDefaultIndexExtentSize() retrieves the table default index extent size. Use ctdbGetTableDefaultDataExtentSize() to retrieve the table default data extend size. Use ctdbSetTableDefaultIndexExtentSize() to set the table default index extent size. Use ctdbGetDefaultIndex() to retrieve the table default index. Handle [in] the Table Handle.
Returns
ctdbGetTableDefaultIndexExtentSize() returns the table default index extent size.
See also
ctdbGetDefaultIndex(), ctdbGetTableDefaultDataExtentSize(), ctdbSetTableDefaultIndexExtentSize()
FairCom Corporation
478
ctdbGetTableExtension
Retrieve the table filename extension.
Declaration
pTEXT ctdbGetTableExtension(CTHANDLE Handle)
Description
ctdbGetTableExtension() retrieves the table filename extension. To retrieve the path, use ctdbGetTablePath(), and to retrieve the name, use ctdbGetTableName(). Handle [in] the Table Handle.
Returns
ctdbGetTableExtension() returns the Table extension name or NULL on failure
See also
ctdbAllocTable(), ctdbGetTableName(), ctdbGetTablePath(), ctdbSetTableExtension()
www.faircom.com
All Rights Reserved
479
ctdbGetTableFieldCount
Retrieve the number of fields associated with the table.
Declaration
VRLEN ctdbGetTableFieldCount(CTHANDLE Handle)
Description
ctdbGetTableFieldCount() retrieves the number of fields associated with the table. Handle [in] the Table Handle.
Returns
ctdbGetTableFieldCount() returns the number of fields or -1 on error.
See also
ctdbAllocTable(), ctdbGetTableIndexCount()
FairCom Corporation
480
ctdbGetTableGroupid
Retrieve the table group ID.
Declaration
pTEXT ctdbGetTableGroupid(CTHANDLE Handle, pTEXT groupid)
Description
ctdbGetTableGroupid() retrieves the table group ID. To set the table group ID, use ctdbSetTableGroupid(). Handle [in] the Table Handle.
Returns
ctdbGetTableGroupid() returns the table group ID.
See also
ctdbAllocTable(), ctdbSetTableGroupid()
www.faircom.com
All Rights Reserved
481
ctdbGetTableHandle
Return a table handle
Declaration
CTHANDLE ctdbGetTableHandle(CTHANDLE Handle)
Description
ctdbGetTableHandle() retrieves the table handle. Handle [in] may be table handle, a record handle, a field handle, an index handle, a segment handle.
Returns
ctdbGetTableHandle() returns the table handle or NULL on failure.
See also
ctdbAllocTable(), ctdbGetDatabaseHandle(), ctdbGetSessionHandle(), ctdbGetRecordHandle()
FairCom Corporation
482
ctdbGetTableIndexCount
Retrieve the number of indices associated with the table.
Declaration
VRLEN ctdbGetTableIndexCount(CTHANDLE Handle)
Description
ctdbGetTableIndexCount() retrieves the number of indices associated with the table. Handle [in] the Table Handle.
Returns
ctdbGetTableIndexCount() returns the number of indices or -1 on error.
See also
ctdbAllocTable(), ctdbGetDefaultIndex()
www.faircom.com
All Rights Reserved
483
ctdbGetTableKSeg
Retrieves the current table-wide extended key segment definition.
DECLARATION
CTDBRET ctdbGetTableKSeg(CTHANDLE Handle, pctKSEGDEF pKSeg);
DESCRIPTION
ctdbGetTableKSeg() retrieves the current table-wide extended key segment definition. Handle must be a c-treeDB table handle and pKSeg is a pointer to an extended key segment definition structure which will receive the definition.
RETURN
Value 0 4096 Symbolic Constant Explanation No error occurred. Not found.
CTDBRET_OK CTDBRET_NOTFOUND
See Appendix A for a complete listing of valid c-tree Plus error values.
EXAMPLE
ctKSEGDEF kseg; if ((eRet = ctdbGetTableKSeg(hTable, &kseg)) != CTDBRET_OK) printf(ctdbGetTableKSeg failed with error %d\n, eRet);
SEE ALSO
ctdbSetTableKSeg(), ctdbSetIndexKSeg(), ctdbGetIndexKSeg(), ctdbSetSegmentKSeg(), ctdbGetSegmentKSeg(), ctdbSetKSegDefaults()
FairCom Corporation
484
ctdbGetTableName
Retrieve the table name.
Declaration
pTEXT ctdbGetTableName(CTHANDLE Handle)
Description
ctdbGetTableName() retrieves the table name. The name has no path (drive/directory) or filename extension. To retrieve the path, use ctdbGetTablePath(); to retrieve the filename extension, use ctdbGetTableExtension(). Handle [in] the Table Handle.
Returns
ctdbGetTableName() returns the Table name or NULL on failure
See also
ctdbAllocTable(), ctdbGetTablePath(), ctdbGetTableExtension()
www.faircom.com
All Rights Reserved
485
ctdbGetTableNbr
Return the table index number in the database's active table list.
Declaration
NINT ctdbGetTableNbr(CTHANDLE Handle)
Description
ctdbGetTableNbr() retrieves the table index number in the database's active table list. Given the index number, the table handle may be retrieved using ctdbGetTable(). Handle [in] Table Handle.
Returns
ctdbGetTableNbr() returns the table index number or -1 on error
See also
ctdbGetTableName(), ctdbGetTable()
FairCom Corporation
486
ctdbGetTableOpenMode
Retrieve the table open mode.
Declaration
CTOPEN_MODE ctdbGetTableOpenMode(CTHANDLE Handle)
Description
ctdbGetTableOpenMode() retrieves the table open mode. Notice that a few modes are used when a file is created and cannot be changed after that. Two such modes are ctFIXED and VLENGTH, since it is not possible to change a file from fixed to variable length after its creation. Other values like EXCLUSIVE or SHARED may be changed after the table creation. To retrieve the table creation mode, use ctdbGetTableCreateMode(). To open a table, use ctdbOpenTable(). Handle [in] the Table Handle. The valid values for the table open mode are listed in "c-treeDB definitions"..
Returns
ctdbGetTableOpenMode() returns the table open mode.
See also
ctdbAllocTable(), ctdbOpenTable()
www.faircom.com
All Rights Reserved
487
ctdbGetTableOwner
Declaration
pTEXT ctdbGetTableOwner(CTHANDLE Handle);
Description
Retrieves the table owner.
Return Values
If the table owner was not previously set by ctdbSetTableOwner(), ctdbGetTableOwner() returns NULL. Handle is a table handle allocated by ctdbAllocTable().
See Also
ctdbSetTableOwner(),
FairCom Corporation
488
ctdbGetTablePassword
Retrieve the table password.
Declaration
pTEXT ctdbGetTablePassword(CTHANDLE Handle)
Description
ctdbGetTablePassword() retrieves the table password. Use ctdbSetTablePassword() to set the table password. Handle [in] the Table Handle.
Returns
ctdbGetTablePassword() returns the table password.
See also
ctdbAllocTable(), ctdbSetTablePassword()
www.faircom.com
All Rights Reserved
489
ctdbGetTablePath
Retrieve the table drive/directory path
Declaration
pTEXT ctdbGetTablePath(CTHANDLE Handle)
Description
ctdbGetTablePath() retrieves the table drive/directory path. To retrieve the table name, use ctdbGetTableName(). Use ctdbSetTablePath() to set the table path. Handle [in] the Table Handle.
Returns
ctdbGetTablePath() returns the Table path or NULL on failure
See also
ctdbAllocTable(), ctdbGetTableName(), ctdbSetTablePath()
FairCom Corporation
490
ctdbGetTablePermission
Retrieve the table permission.
Declaration
LONG ctdbGetTablePermission(CTHANDLE Handle)
Description
ctdbGetTablePermission() retrieves the table permission. The possible permissions are set by ctdbSetTablePermission() and they are all listed in "c-treeDB definitions".. Handle [in] the Table Handle.
Returns
ctdbGetTablePermission() returns the table permission.
See also
ctdbAllocTable(), ctdbSetTablePermission()
www.faircom.com
All Rights Reserved
491
ctdbGetTableStatus
Declaration
ULONG ctdbGetTableStatus(CTHANDLE Handle);
Description
Retrieves the table status. The table status indicates which rebuild action will be taken by an alter table operation. Handle is a table handle.
Return Values
Returns CTDB_REBUILD_NONE if the table is not changed or a bit mask of the values below describing the table status. The possible rebuild status returns are:
Rebuild Status Value 0 1 2 4 8 16 Rebuild Status Symbolic Code Explanation Nothing to be done, no changes to table Update the table DODA Update table FC!DFLD resource Add new indices to table Rebuild all indices Full table rebuild. A temporary table is created and all data is moved to new table and the indexes are built on the fly.
Example
ULONG status = ctdbGetTableStatus(hTable); if (status & CTDB_REBUILD_ALL || status & CTDB_REBUILD_FULL) ctdbAlterTable(hTable, CTDB_ALTER_FULL) else if (status) ctdbAlterTable(hTable, CTDB_ALTER_NORMAL);
See Also
ctdbGetIndexStatus(), ctdbGetSegmentStatus(), ctdbAlterTable()
FairCom Corporation
492
ctdbGetTableUID
Return the table Unique Identifier.
Declaration
CTDBRET ctdbGetTableUID(CTHANDLE Handle, pTEXT Name, pULONG puid)
Description
ctdbGetTableUID() returns the table unique identifier, UID, given the table name. Use ctdbGetActiveTableUID() to retrieve table UID, given the Table Handle. Use ctdbFindTableByUID() to locate a table in a database by its unique identifier. Handle [in] the Database Handle. Name [in] the table name. puid [out] the table unique identifier.
Returns
ctdbGetTableUID() returns CTDBRET_OK on success, or c-treeDB C API error on failure.
See also
ctdbAllocDatabase(), ctdbFindTableByUID(), ctdbGetActiveTableUID()
www.faircom.com
All Rights Reserved
493
ctdbGetTransactionMode
Declaration
CTBEGIN_MODE ctdbDECL ctdbGetTransactionMode(CTHANDLE Handle);
Description
Returns the transaction mode used when starting a transaction. c-tree Plus offers a rich array of data integrity options. Full transaction processing offers the safest and best performance of all the available options. There are times when other c-tree Plus options, such as PREIMG, might be advantageous.
Return Values
ctdbGetTransactionMode() returns one of the following values:
CTBEGIN_MODE Symbolic Constant Description No begin transaction mode set. Default mode apply. Transaction atomicity only. Auto-recovery is not available. Mutually exclusive with CTBEGIN_TRNLOG. Full transaction processing functionality including auto-recovery. Mutually exclusive to CTBEGIN_PREIMG. This is the default begin transaction mode. Defer begin transaction until update. Automatically invokes savepoints after each successful record or resource update.
CTBEGIN_DEFER CTBEGIN_AUTOSAVE
See Also
ctdbGetTransactionMode()
FairCom Corporation
494
ctdbGetUserLogonName
Return the user name associated with the session.
Declaration
pTEXT ctdbGetUserLogonName(CTHANDLE Handle)
Description
ctdbGetUserLogonName() returns the user name associated with the session. It is necessary to logon to the server with ctdbLogon() before getting the user name. Handle [in] the session handle.
Returns
ctdbGetUserLogonName() returns a pointer to the User name, or Null on failure.
Example
username=ctdbGetUserLogonName(hSession); userpass=ctdbGetUserPassword(hSession); servname=ctdbGetServerName(hSession);
See also
ctdbGetServerName(), ctdbGetUserPassword(), ctdbAllocSession()
www.faircom.com
All Rights Reserved
495
ctdbGetUserPassword
Return the user password associated with the session.
Declaration
pTEXT ctdbGetUserPassword(CTHANDLE Handle)
Description
ctdbGetUserPassword() returns the user password associated with the session. It is necessary to logon to the server with ctdbLogon() before getting the user password. Handle [in] the session handle.
Returns
ctdbGetUserPassword() returns a pointer to the User password, or Null on failure.
Example
username=ctdbGetUserLogonName(hSession); userpass=ctdbGetUserPassword(hSession); servname=ctdbGetServerName(hSession);
See also
ctdbGetServerName(), ctdbGetUserLogonName(), ctdbAllocSession()
FairCom Corporation
496
ctdbGetUserTag
Retrieve the user tag.
Declaration
CTDBRET ctdbGetUserTag(CTHANDLE Handle, pVOID tagptr)
Description
ctdbGetUserTag() retrieves the user tag. Handle [in] any c-treeDB SDK Handle. tagptr [out] the pointer to receive the user tag.
Returns
ctdbGetUserTag() returns CTDBRET_OK on success, or c-treeDB C API error on failure.
See also
ctdbSetUserTag()
www.faircom.com
All Rights Reserved
497
ctdbGetYear
Retrieve the year from a packed CTDATE.
Declaration
NINT ctdbGetYear(CTDATE date)
Description
ctdbGetYear() retrieves the year from a packed CTDATE. To retrieve the day of the month from a packed CTDATE, use ctdbGetDay(). To retrieve the month of the year from a packed CTDATE, use ctdbGetMonth(). date is the date in CTDATE format.
Returns
ctdbGetYear() returns the day of the month on success or 0 on error.
See also
ctdbGetMonth(), ctdbGetDay()
FairCom Corporation
498
ctdbHasDelField
ctdbHasDelField() tests for the presence of the internal delete flag.
Declaration
CTBOOL ctdbDECL ctdbHasDelField(CTHANDLE Handle);
Description
ctdbHasDelField() tests for the presence of the internal delete flag, $DELFLD$, field in a table. $DELFLD$ is a hidden field that c-treeDB automatically creates as the first field in the record buffer. $DELFLD$ is defined as a 4-byte CT_ARRAY field (to ensure proper alignment of subsequent fields) and its only purpose is to keep a place at the beginning of the record to hold the c-tree delete record flag byte when a record is deleted. This field is handled internally by c-treeDB and should never be modified by the user. ctdbHasDelField() receives a table handle as parameter and returns YES if the table was created with a $DELFLD$ field. ctdbHasDelField() returns NO if the table was not created with a $DELFLD$ field.
Return
Symbolic Constant YES NO Explanation
www.faircom.com
All Rights Reserved
499
ctdbHasNullFieldSupport
Indicate if a table has Null field support.
Declaration
CTBOOL ctdbHasNullFieldSupport(CTHANDLE Handle)
Description
ctdbHasNullFieldSupport() indicates if a table has Null field support. Handle [in] the Table Handle.
Returns
ctdbHasNullFieldSupport() returns YES if the table has NULL field support, NO otherwise.
See also
ctdbIsNullField()
FairCom Corporation
500
ctdbHasRecbyt
Indicate if the table has support for recbyt index.
Declaration
CTBOOL ctdbHasRecbyt(CTHANDLE Handle)
Description
ctdbHasRecbyt() indicates if the table has support for RECBYT index. This support is enabled by default when the table is created. If a table has support to a RECBYT index, the record position or offset may be retrieved with ctdbGetRecordPos(). Handle [in] the Table Handle.
Returns
ctdbHasRecbyt() returns yes if the function has support, and no otherwise.
See also
ctdbAllocTable(), ctdbGetRecordPos(), ctdbCreateTable()
www.faircom.com
All Rights Reserved
501
ctdbHasRowid
Indicate if the table has support for rowid index.
Declaration
CTBOOL ctdbHasRowid(CTHANDLE Handle)
Description
ctdbHasRowid() indicates if the table has support for rowid index. By default, all c-treeDB created tables have support for rowid. To create a table without support for rowid, use the create mode CTCREATE_NOROWID in ctdbCreateTable(). Rowid holds the auto increment value generated automatically by c-tree every time a new record is added to the table. This is a read-only field. Handle [in] the Table Handle.
Returns
ctdbHasRowid() returns yes if the function has support, and no otherwise.
See also
ctdbAllocTable(), ctdbFindRowid(), ctdbGetRowid(), ctdbCreateTable(), ctdbHasRecbyt()
FairCom Corporation
502
ctdbInsertBatch
Inserts a new record into a batch buffer.
DECLARATION
CTDBRET ctdbDECL ctdbInsertBatch(CTHANDLE Handle);
DESCRIPTION
ctdbInsertBatch() inserts a new record into a batch buffer maintained internally by c-treeDB. When the batch buffer fills up, the group of records stored in the batch buffer are inserted into the table. If ctdbEndBatch() is called and the batch buffer still contains records, a new insert record operation is performed for the remaining records before the batch operation is terminated. For transaction controlled files, the batch insertion operation is treated as one all or nothing operation. If no explicit transaction is started, each insertion of records with will start and end its own transaction. Even if an explicit transaction is started, each insertion operation is treated independently through safe points. Note: currently, all records insertion operations will not perform any conversion of records images, key values and records position for heterogeneous client/server implementations. The following steps must be taken to perform a batch insert record operation: 1. Call ctdbSetBatch() function, with CTBATCH_INS mode, to insert a group of records. 2. For each record to be inserted perform the following operations: 3. Call ctdbClearRecord() to clear a record buffer 4. For each field in the record call one of the ctdbSetFieldAs..() functions to set the field data. 5. Call ctdbInsertBatch() to insert the record into the batch buffer. 6. Call ctdbEndBatch() to indicate that no more records will be inserted. Handle must be a record handle associated with an opened table.
RETURNS
Value 0 Symbolic Constant CTDBRET_OK Explanation No error occurred.
See Appendix A for a complete listing of valid c-tree Plus error values.
EXAMPLE
/* set the batch operation */ if (ctdbSetBatch(hRecord, CTBATCH_INS, 0, 0) != CTDBRET_OK) printf("ctdbSetBatch failed with error %d\n", ctdbGetError(hRecord)); /* prepare the first record */ ctdbClearRecord(hRecord); ctdbSetFieldAsSigned(hRecord, 0, Invoice);/* invoice number */ ctdbSetFieldAsSigned(hRecord, 1, 0); /* invoice item */ ctdbSetFieldAsSigned(hRecord, 2, 100); /* item quantity */ ctdbSetFieldAsSigned(hRecord, 3, 1001); /* item code */ if (ctdbInsertBatch(hRecord) != CTDBRET_OK) /* insert */ printf("ctdbInsertBatch failed with error %d\n", ctdbGetError(hRecord)); /* prepare the second record */ ctdbClearRecord(hRecord); ctdbSetFieldAsSigned(hRecord, 0, Invoice);/* invoice number */
www.faircom.com
All Rights Reserved
503
ctdbSetFieldAsSigned(hRecord, 1, 1); /* invoice item */ ctdbSetFieldAsSigned(hRecord, 2, 200); /* item quantity */ ctdbSetFieldAsSigned(hRecord, 3, 1002); /* item code */ if (ctdbInsertBatch(hRecord) != CTDBRET_OK) /* insert */ printf("ctdbInsertBatch failed with error %d\n", ctdbGetError(hRecord)); /* terminate the batch operation */ if (ctdbEndBatch(hRecord) != CTDBRET_OK) printf("ctdbEndBatch failed with error %d\n", ctdbGetError(hRecord));
SEE ALSO
ctdbBatchLoaded(), ctdbBatchLocked(), ctdbBatchMode(), ctdbBatchTotal(), ctdbEndBatch(), ctdbIsBatchActive(), ctdbNextBatch(), ctdbSetBatch()
FairCom Corporation
504
ctdbInsField
Insert a field before the field number given by Index.
Declaration
CTHANDLE ctdbInsField(CTHANDLE Handle, NINT Index, pTEXT FieldName, CTDBTYPE FieldType, VRLEN FieldLength)
Description
ctdbInsField() inserts a field before the field number given by the Index parameter. Use ctdbInsFieldByName() to insert a field in a table in a position specified by name. Use ctdbAddField() to add a field to the end of the table. Use ctdbDelField() and ctdbDelFieldByName() to delete fields from table. ctdbInsField() does the field handle allocation. After the segments, indices, and fields have been defined, the table can be created or altered with ctdbCreateTable() or ctdbAlterTable(). Handle [in] the Table handle. Index [in] the field number - notice that the new field will be added before this field. FieldName [in] the field name. FieldType [in] the field type. Available types are listed in "c-treeDB definitions".. FieldLength [in] the field length.
Returns
ctdbInsField() returns a field handle on success, or NULL on failure.
See also
ctdbAllocTable(), ctdbAddField(), ctdbInsFieldByName(), ctdbDelField(), ctdbDelFieldByName(), ctdbMoveField()
www.faircom.com
All Rights Reserved
505
ctdbInsFieldByName
Insert a field before the field given by FieldIndex.
Declaration
CTHANDLE ctdbInsFieldByName(CTHANDLE Handle, pTEXT FieldIndex, pTEXT FieldName, CTDBTYPE FieldType, VRLEN FieldLength)
Description
ctdbInsFieldByName() inserts a field before the field given by the FieldIndex parameter. Use ctdbInsField() to insert a field in a table in a position specified by number. Use ctdbAddField() to add a field to the end of the table. Use ctdbDelField() and ctdbDelFieldByName() to delete fields from table. ctdbInsFieldByName() does the field handle allocation. After the segments, indices, and fields have been defined, the table can be created or altered with ctdbCreateTable() or ctdbAlterTable(). Handle [in] the Table handle. FieldIndex [in] the field name - notice that the new field will be added before this field. FieldName [in] the new field name. FieldType [in] the field type. Available types are listed in "c-treeDB definitions".. FieldLength [in] the field length.
Returns
ctdbInsFieldByName() returns a field handle on success, or NULL on failure.
See also
ctdbAllocTable(), ctdbAddField(), ctdbInsField(), ctdbDelField(), ctdbDelFieldByName(), ctdbMoveField()
FairCom Corporation
506
ctdbInsSegment
Insert a segment before the segment indicated by SegNumber
Declaration
CTHANDLE ctdbInsSegment(CTHANDLE Handle, NINT SegNumber, CTHANDLE FieldHandle, CTSEG_MODE SegMode)
Description
ctdbInsSegment() inserts a segment before the segment indicated by SegNumber segment, given the index handle. The operation of inserting a segment links the index with the field in the table. In order to insert a segment with this function, the segment must be defined based on individual full fields, using what is known as record schema. See the c-tree Plus documentation for further information on record schemas. Use ctdbInsSegmentByName() or ctdbInsSegmentByNbr() to insert a segment given the index number.Use ctdbAddSegment() to add a segment to an index. Use ctdbDelSegment() to delete a segment from an index. After the segments, indices, and fields have been defined, the table can be created or altered with ctdbCreateTable() or ctdbAlterTable(). Handle [in] the index handle. SegNumber [in] the position to insert the new segment - insert the new segment before this segment number. FieldHandle [in] the Field Handle. SegMode [in] the Index segment mode. The valid values for the segment modes are: CTSEG_SCHSEG, CTSEG_USCHSEG, CTSEG_VSCHSEG, CTSEG_UVSCHSEG, CTSEG_SCHSRL, described in "c-treeDB definitions".. If used with a different segment mode, this call will return error 4047, meaning invalid segment mode. ctdbInsSegmentEx() accepts any segment mode.
Returns
ctdbInsSegment() returns the new segment handle on success, or NULL on failure.
Example
pMyIndex = ctdbGetIndex(pMyTable, 0); // retrieve first index handle pMyNewIseg = ctdbInsSegment(pMyIndex, 0, , CTSEG_ UREGSEG); RetVal = ctdbAlterTable(pMyTable, 0);
See also
ctdbAddSegment(), ctdbDelSegment(), ctdbInsSegmentByName(), ctdbInsSegmentByNbr(), ctdbInsSegmentEx()
www.faircom.com
All Rights Reserved
507
ctdbInsSegmentByName
Insert a segment before the segment indicated by SegNumber, given the field name.
Declaration
CTHANDLE ctdbInsSegmentByName(CTHANDLE Handle, NINT IndexNbr, NINT SegNumber, pTEXT FieldName, CTSEG_MODE SegMode)
Description
ctdbInsSegmentByName() inserts a new segment index before the segment indicated by SegNumber, given the index number and the field name. The operation of inserting a segment links the index with the field in the table. In order to insert a segment with this function, the segment must be defined based on individual full fields, using what is known as record schema. See the c-tree Plus documentation for further information on record schemas. After the segments, indices, and fields have been defined, the table can be created or altered with ctdbCreateTable() or ctdbAlterTable(). Handle [in] the Table Handle. IndexNbr [in] the Index number. SegNumber [in] the segment before which the new segment will be inserted. FieldName [in] the Field name. SegMode [in] the Index segment mode. The valid values for the segment modes are: CTSEG_SCHSEG, CTSEG_USCHSEG, CTSEG_VSCHSEG, CTSEG_UVSCHSEG, CTSEG_SCHSRL, described in "c-treeDB definitions".. If used with a different segment mode, this call will return error 4047, meaning invalid segment mode. ctdbInsSegmentEx() accepts any segment mode.
Returns
ctdbInsSegmentByName() returns the segment handle on success, or NULL on failure
Example
pMyNewIseg = ctdbInsSegmentByNbr(pMyTable,0,0,Balance,CTSEG_ REGSEG); RetVal = ctdbAlterTable(pMyTable, 0);
See also
ctdbInsSegment(), ctdbInsSegmentByNbr(), ctdbInsSegmentEx()
FairCom Corporation
508
ctdbInsSegmentByNbr
Insert a segment before the segment indicated by SegNumber, given the field and index numbers.
Declaration
CTHANDLE ctdbInsSegmentByNbr(CTHANDLE Handle, NINT IndexNbr, NINT SegNumber, NINT FieldNbr, CTSEG_MODE SegMode)
Description
ctdbInsSegmentByNbr() inserts a segment before the segment indicated by SegNumber, given the index and field numbers. The operation of inserting a segment links the index with the field in the table. In order to insert a segment with this function, the segment must be defined based on individual full fields, using what is known as record schema. See the c-tree Plus documentation for further information on record schemas. After the segments, indices, and fields have been defined, the table can be created or altered with ctdbCreateTable() or ctdbAlterTable(). Handle [in] the Table Handle. IndexNbr [in] the Index number. SegNumber [in] the segment before which the new segment will be inserted. FieldNbr [in] the Field number. SegMode [in] the Index segment mode. The valid values for the segment modes are: CTSEG_SCHSEG, CTSEG_USCHSEG, CTSEG_VSCHSEG, CTSEG_UVSCHSEG, CTSEG_SCHSRL, described in "c-treeDB definitions".. If used with a different segment mode, this call will return error 4047, meaning invalid segment mode. ctdbInsSegmentEx() accepts any segment mode.
Returns
ctdbInsSegmentByNbr() returns the segment handle on success, or NULL on failure
Example
pMyNewIseg = ctdbInsSegmentByNbr(pMyTable, 0, 0, 1, CTSEG_ REGSEG); RetVal = ctdbAlterTable(pMyTable, 0);
See also
ctdbInsSegmentByName(), ctdbInsSegment(), ctdbInsSegmentEx()
www.faircom.com
All Rights Reserved
509
ctdbInsSegmentEx
Insert a new extended index segment before the segment indicated.
Declaration
CTHANDLE ctdbInsSegmentEx(CTHANDLE Handle, NINT SegNumber, NINT offset, NINT length, CTSEG_MODE SegMode)
Description
ctdbInsSegmentEx() inserts a new extended index segment before the segment SegNumber. A segment is denominated extended if it is based on the segment offset. After the segments, indices, and fields have been defined, the table can be created or altered with ctdbCreateTable() or ctdbAlterTable(). Handle [in] the index handle. SegNumber [in] the segment number before which we should insert the new segment. offset [in] the absolute byte offset. length [in] the segment length in bytes. SegMode [in] the Index segment mode. The valid values for the segment modes are listed in Section "c-treeDB definitions".. Notice that ctdbInsSegmentEx() does work with Absolute byte offset segments.
Returns
ctdbInsSegmentEx() returns the segment handle on success, or NULL on failure
Example
pMyIndex = ctdbGetIndex(pMyTable, 0); // retrieve first index handle pMyNewIseg = ctdbInsSegmentEx(pMyIndex, 0, 32, 4, CTSEG_ UREGSEG); RetVal = ctdbAlterTable(pMyTable, 0);
See also
ctdbInsSegmentByName(), ctdbInsSegment(), ctdbInsSegmentByNbr(), ctdbAddSegmentEx()
FairCom Corporation
510
ctdbIsActiveDatabase
Retrieve the active state of a database.
Declaration
CTBOOL ctdbIsActiveDatabase(CTHANDLE Handle)
Description
ctdbIsActiveDatabase() retrieves the active state of a database, connected or disconnected. A database is active when it is connected. To connect the database, use ctdbConnect(). Handle [in] the Database Handle.
Returns
ctdbIsActiveDatabase() returns YES if the database is connected and NO if the database is disconnected.
See also
ctdbAllocDatabase(), ctdbIsActiveSession(), ctdbIsActiveTable(), ctdbConnect()
www.faircom.com
All Rights Reserved
511
ctdbIsActiveSession
Check if a session is active. A session is active when the session handle has been allocated and the session is logged in to the server.
Declaration
CTBOOL ctdbIsActiveSession(CTHANDLE Handle)
Description
ctdbIsActiveSession() checks to see if a session is active. A session is defined active when the session handle has been allocated by ctdbAllocSession() and the session is logged in to the server with ctdbLogon(). Handle [in] the session handle.
Returns
ctdbIsActiveSession() returns YES if the session is active and NO otherwise.
Example
act=ctdbIsActiveSession(hSession); if (act) printf("\n\nThe server is active.\n"); else { printf("\n\nThe Session is not active. Logon first.\n"); ctdbLogon(hSession, "FAIRCOMS", "ADMIN", "ADMIN"); }
See also
ctdbLogon(), ctdbAllocSession(), ctdbIsActiveDatabase(), ctdbIsActiveTable()
FairCom Corporation
512
ctdbIsActiveTable
Retrieve the active state of a table.
Declaration
CTBOOL ctdbIsActiveTable(CTHANDLE Handle)
Description
ctdbIsActiveTable() retrieves the active state of a table. A table is active if it is open. Handle [in] the Table Handle.
Returns
ctdbIsActiveTable() returns YES if the table is open and NO otherwise.
See also
ctdbAllocTable(), ctdbFreeTable(), ctdbIsActiveSession(), ctdbIsActiveDatabase()
www.faircom.com
All Rights Reserved
513
ctdbIsBatchActive
Indicates if a batch operation is underway or not.
DECLARATION
CTBOOL ctdbDECL ctdbIsBatchActive(CTHANDLE Handle);
DESCRIPTION
ctdbIsBatchActive() indicates if a batch operation is active or not. This is equivalent to ctdbBatchMode() returning CTBATCH_NONE. Handle must be a c-treeDB record handle associated with an opened table.
RETURNS
Value 0 1 Symbolic Constant NO YES Explanation Batch operation not underway. Batch operation underway.
See Appendix A for a complete listing of valid c-tree Plus error values.
EXAMPLE
/* check if a batch operation is active */ if (ctdbIsBatchActive(hRecord)) printf("Batch operation underway\n"); else printf("No batch operation\n");
SEE ALSO
ctdbBatchLoaded(), ctdbBatchLocked(), ctdbBatchMode(), ctdbBatchTotal(), ctdbEndBatch(), ctdbInsertBatch(), ctdbNextBatch(), ctdbSetBatch()
FairCom Corporation
514
ctdbIsDatabaseExclusive
Retrieves the status of the database exclusive flag.
DECLARATION
CTBOOL ctdbIsDatabaseExclusive(CTHANDLE Handle);
DESCRIPTION
ctdbIsDatabaseExclusive() retrieves the status of the database exclusive flag. Handle is a session Handle.
RETURN
Value 0 1 Symbolic Constant NO YES Explanation Batch operation not underway. Batch operation underway.
See Appendix A for a complete listing of valid c-tree Plus error values.
EXAMPLE
/* verify an exclusive logon and connect */ CTHANDLE hSession = ctdbAllocSession(CTSESSION_CTDB); if (hSession) { ctdbSetSessionExclusive(hSession, YES); if (ctdbLogon(hSession, "FAIRCOM", "ADMIN", "ADMIN") != CTDBRET_OK) printf("ctdbLogon failed\n"); } if (ctdbIsSessionExclusive(hSession)) printf("Session is exclusive\n"); else printf("Session is shared\n"); if (ctdbIsDatabaseExclusive(hDatabase)) printf("Database is exclusive\n"); else printf("Database is shared\n"); ctdbFreeDatabase(hDatabase); ctdbFreeSession(hSession);
SEE ALSO
ctdbSetSessionExclusive(), ctdbIsSessionExclusive(), ctdbSetDatabaseExclusive()
www.faircom.com
All Rights Reserved
515
ctdbIsEditedRecord
Retrieve the edited record flag.
Declaration
CTBOOL ctdbIsEditedRecord(CTHANDLE Handle)
Description
ctdbIsEditedRecord() retrieves the edited record flag. If YES, the record has been edited since it has been read from the table. Functions like ctdbSetFieldAsString() and all other ctdbSetFieldAs...() functions set the edited record flag to YES. Functions like ctdbAllocRecord(), ctdbClearRecord(), ctdbResetRecord(), ctdbFindRecord() and other search functions clear the edited record flag. Use ctdbIsNewRecord() to check the new record flag. Handle [in] the record handle.
Returns
ctdbIsEditedRecord() returns the edited record flag.
See also
ctdbAllocRecord(), ctdbIsNewRecord()
FairCom Corporation
516
ctdbIsExtSegment
Check if the segment mode is one of the extended modes.
Declaration
CTBOOL ctdbIsExtSegment(CTSEG_MODE SegMode)
Description
ctdbIsExtSegment() checks to see if the segment mode is one of the extended modes. Extended segments must have been added to the index with ctdbAddSegmentEx(). SegMode [in] the segment mode.
Returns
ctdbIsExtSegment() returns YES if the segment mode is extended, NO otherwise.
See also
ctdbAddSegmentEx()
www.faircom.com
All Rights Reserved
517
ctdbIsFieldDefaultValueSet
Checks if a field default value has been set or not.
DECLARATION
TYPE FunctionTemplate(parameters) TYPE parameters;
DESCRIPTION
Checks if a field default value has been set or not. Returns YES if a field default value was set, otherwise returns NO.
RETURN
Value 0 1 Symbolic Constant NO YES Explanation Batch operation not underway. Batch operation underway.
See Appendix A for a complete listing of valid c-tree Plus error values.
EXAMPLE
/* check if default field value is set */ hField = ctdbGetField(hTable, 5); if (ctdbIsFieldDefaultValueSet(hField)) printf("Default field value is set\n"); else printf("No default field value\n");
SEE ALSO
ctdbSetFieldDefaultValue(), ctdbGetFieldDefaultValue(), ctdbClearFieldDefaultValue(), ctdbClearAllFieldDefaultValue(), ctdbSetFieldDefaultDateTimeType(), ctdbGetFieldDefaultDateType(), ctdbGetFieldDefaultTimeType()
FairCom Corporation
518
ctdbIsFieldNumeric
Indicate if a field represents a numeric field type.
Declaration
CTBOOL ctdbIsFieldNumeric(CTHANDLE Handle)
Description
ctdbIsFieldNumeric() indicates if the field handle represents a field with a numeric value. The numeric field types are: CT_CHAR, CT_CHARU, CT_INT2, CT_INT2U, CT_INT4, CT_INT4U, CT_DATE, CT_TIME, CT_MONEY, CT_TIMES, CT_SFLOAT, CT_DFLOAT, CT_EFLOAT, CT_CURRENCY, CT_NUMBER, and CT_INT8. Handle [in] a Field Handle.
Returns
ctdbIsFieldNumeric() returns YES if the field represents a numeric value and NO if the field does not represent a numeric value
Example
/* if fields hField1 and hField2 are numeric, add the values and store the result in hField1 */ if (ctdbIsFieldNumeric(hField1) && ctdbIsFieldNumeric(hField2)) { CTNUMBER res, val1, val2; ctdbGetFieldAsNumber(hRecord, ctdbGetFieldNbr(hField1), &val1); ctdbGetFieldAsNumber(hRecord, ctdbGetFieldNbr(hField2), &val2); ctdbNumberAdd(&val1, &val2, &res); ctdbSetFieldAsNumber(hRecord, ctdbGetFieldNbr(hField1), &res); }
See also
ctdbGetFieldNbr(), ctdbGetFieldProperties()
www.faircom.com
All Rights Reserved
519
ctdbIsFilteredRecord
Indicate if the record is being filtered or not.
Declaration
CTBOOL ctdbIsFilteredRecord(CTHANDLE Handle)
Description
ctdbIsFilteredRecord() indicates if the records are being filtered or not. To insert filtering logic to the record retrieval, use ctdbFilterRecord(). Handle [in] the Record or Table Handle.
Returns
ctdbIsFilteredRecord() returns YES if the record has been filtered, and NO otherwise.
See also
ctdbGetFilter(), ctdbFilterRecord()
FairCom Corporation
520
ctdbIsLeapYear
Indicate if the year in a packed CTDATE is a leap year.
Declaration
CTBOOL ctdbIsLeapYear(CTDATE date)
Description
ctdbIsLeapYear() indicates if the year in a packed CTDATE is a leap year. date is the date in CTDATE format.
Returns
ctdbIsLeapYear() returns YES if the year in a packed CTDATE is a leap year, and NO otherwise.
www.faircom.com
All Rights Reserved
521
ctdbIsLockActive
Indicates if a call to ctdbLock() has been made.
Declaration
CTBOOL ctdbIsLockActive(CTHANDLE Handle)
Description
ctdbIsLockActive() indicates if a call to ctdbLock() with one of the READ or WRITE segment mode variations, has been made. The lock active flag is cleared with a call to ctdbUnlock() or ctdbLock() with lock mode set to CTLOCK_FREE or CTLOCK_SUSPEND. This function does not verify if a call to ctdbLockRecord() was made or not. Handle [in] the Session or any other Handle.
Returns
ctdbIsLockActive() returns YES if the lock mode is one of the READ or WRITE variations, NO otherwise.
Example
if (ctdbIsLockActive(pSession)) ctdbUnlock(pSession);
See also
ctdbLock(), ctdbUnlock(), ctdbGetLockMode(), ctdbLockRecord()
FairCom Corporation
522
ctdbIsNewRecord
Retrieve the new record flag.
Declaration
CTBOOL ctdbIsNewRecord(CTHANDLE Handle)
Description
ctdbIsNewRecord() retrieves the new record flag. The new record flag is set to YES by functions like ctdbAllocRecord(), ctdbClearRecord(), ctdbDeleteRecord(). Functions like ctdbFindRecord(), ctdbWriteRecord() set the new record flag to NO. Use ctdbIsEditedRecord() to check the edited record flag. Handle [in] the record handle.
Returns
ctdbIsNewRecord() returns the new record flag.
See also
ctdbAllocRecord(), ctdbIsEditedRecord()
www.faircom.com
All Rights Reserved
523
ctdbIsNullField
Check if a field is null.
Declaration
CTBOOL ctdbIsNullField(CTHANDLE Handle, NINT FieldNbr)
Description
ctdbIsNullField() checks to see if a field is null. Handle [in] the record handle. FieldNbr [in] the field number.
Returns
ctdbIsNullField() returns YES if the field is NULL, or NO if the field is not NULL
See also
ctdbHasNullFieldSupport(), ctdbGetFieldNullFlag()
FairCom Corporation
524
ctdbIsNumberZero
Check if a number is zero.
Declaration
CTBOOL ctdbIsNumberZero(pCTNUMBER pNumber)
Description
ctdbIsNumberZero() checks to see if a number is zero. pNumber [in] pointer to a number.
Returns
ctdbIsNumberZero() returns YES if the number is zero, NO otherwise.
See also
ctdbNumberZero()
www.faircom.com
All Rights Reserved
525
ctdbIsRecordRangeOn
Indicate if an index range operation is active for this record handle.
Declaration
CTBOOL ctdbIsRecordRangeOn(CTHANDLE Handle);
Description
ctdbIsRecordRangeOn() returns YES if a index range operation is active for this record handle, or NO is no index range is active. Handle is a record handle.
Return
Value 0 1 Symbolic Constant NO YES Explanation No index range operation is active Index range operation is active
See "c-treeDB Errors and Return Values" for a complete listing of valid c-treeDB error codes and return values.
Example
/* display all records where age is greater than 65 */ void DisplayAll(CTHANDLE hRecord) { UTEXT lRange[32]; NINT op[1] = {CTIX_GT}; NINT fldno = ctdbGetFieldNumberByName(hHandle, "age"); CTDBRET eRet; ctdbClearRecord(hRecord); ctdbSetFieldAsSigned(hRecord, fldno, 65); ctdbSetDefaultIndex(hRecord, 0); ctdbBuildTargetKey(hRecord, CTFIND_EQ, lRange, 32); eRet = ctdbRecordRangeOn(hRecord, 1, lRange, NULL, op); if (eRet == CTDBRET_OK) { eRet = ctdbFirstRecord(hRecord); while (eRet == CTDBRET_OK) { TEXT str[128]; ctdbGetFieldAsString(hRecord, 0, str, sizeof(str)); printf("%s\n", str); eRet = ctdbNextRecord(hRecord); } } if (ctdbIsRecordRangeOn(hRecord)) ctdbRecordRangeOff(hRecord); }
See also
ctdbRecordRangeOn(), ctdbRecordRangeOff()
FairCom Corporation
526
ctdbIsRecordSetOn
Declaration
CTBOOL ctdbDECL ctdbIsRecordSetOn(CTHANDLE Handle);
Description
Indicates if record set is active or not. A record set is active after a successful call to ctdbRecordSetOn(). A record set can be switched off by calling ctdbRecordSetOff(). Handle must be a record handle.
Return Values
Returns YES if a record set if active and NO if a record set is not active.
See Also
ctdbRecordSetOn(), ctdbRecordSetOff()
www.faircom.com
All Rights Reserved
527
ctdbIsResourceLocked
Indicate if a resource is locked.
DECLARATION
CTBOOL ctdbDECL ctdbIsResourceLocked(CTHANDLE resource);
DESCRIPTION
Retrieve indication if the resource is locked. resource is a handle allocated by ctdbAllocResource().
RETURN
Returns YES if resource is locked, or NO if resource is not locked.
EXAMPLE
if (ctdbIsResourceLocked(hRes)) ctdbUnlockResource(hRes);
SEE ALSO
ctdbAllocResource, ctdbFreeResource, ctdbAddResource, ctdbDeleteResource, ctdbUpdateResource, ctdbFirstResource, ctdbNextResource, ctdbFindResource, ctdbFindResourceByName, ctdbGetResourceType, ctdbSetResourceType, ctdbGetResourceNumber, ctdbSetResourceNumber, ctdbGetResourceName, ctdbSetResourceName, ctdbGetResourceDataLength, ctdbGetResourceData, ctdbSetResourceData, ctdbUnlockResource
FairCom Corporation
528
ctdbIsSessionExclusive
Retrieves the status of the session exclusive flag.
DECLARATION
CTBOOL ctdbIsSessionExclusive(CTHANDLE Handle);
DESCRIPTION
ctdbIsSessionExclusive() retrieves the status of the session exclusive flag. Handle is a session handle.
RETURN
Value 0 1 Symbolic Constant NO YES Explanation Batch operation not underway. Batch operation underway.
See Appendix A for a complete listing of valid c-tree Plus error values.
EXAMPLE
/* verify an exclusive logon */ CTHANDLE hSession = ctdbAllocSession(CTSESSION_CTDB); if (hSession) { ctdbSetSessionExclusive(hSession, YES); if (ctdbLogon(hSession, "FAIRCOM", "ADMIN", "ADMIN") != CTDBRET_OK) printf("ctdbLogon failed\n"); } if (ctdbIsSessionExclusive(hSession)) printf("Session is exclusive\n"); else printf("Session is shared\n"); ctdbFreeSession(hSession);
SEE ALSO
ctdbSetSessionExclusive(), ctdbSetDatabaseExclusive(), ctdbIsDatabaseExclusive()
www.faircom.com
All Rights Reserved
529
ctdbIsTransActive
Check whether a transaction commit or abort is pending.
Declaration
CTBOOL ctdbIsTransActive(CTHANDLE Handle)
Description
ctdbIsTransActive() checks whether a transaction commit or abort is pending. An active transaction is one that has been initiated with a ctdbBegin() call. Handle [in] the session handle.
Returns
ctdbIsTransActive() returns True if the transaction is active, False otherwise.
See also
ctdbBegin(), ctdbCommit(), ctdbAbort()
FairCom Corporation
530
ctdbIsVariableField
Indicate if a field is allocated in the variable portion of the record.
Declaration
CTBOOL ctdbIsVariableField(CTHANDLE Handle, NINT FieldNbr)
Description
ctdbIsVariableField() Indicates if a field, represented by the field number, is allocated in the variable portion of the record. Handle [in] the record handle. FieldNbr [in] the field number.
Returns
ctdbIsVariableField() returns True if the field is allocated in the variable portion of the record, False otherwise.
www.faircom.com
All Rights Reserved
531
ctdbLastRecord
Get the last record on a table.
Declaration
CTDBRET ctdbLastRecord(CTHANDLE Handle)
Description
ctdbLastRecord() retrieves the last record on a table. Handle [in] the record handle. If sets are enabled by ctdbRecordSetOn(), ctdbLastRecord() will retrieve the last record in the set. Use ctdbFirstRecord() to retrieve the first record on a table, ctdbNextRecord() to retrieve the next record on a table, and ctdbPrevRecord() to retrieve the previous record on a table. Use ctdbFindRecord() to find a specific record on a table.
Returns
ctdbLastRecord() returns CTDBRET_OK on success, or c-treeDB C API error on failure.
See also
ctdbAllocRecord(), ctdbFirstRecord(), ctdbNextRecord(), ctdbPrevRecord(), ctdbFindRecord(), ctdbRecordSetOn()
FairCom Corporation
532
ctdbLock
Perform a lock or unlock operation.
Declaration
CTDBRET ctdbLock(CTHANDLE Handle, CTLOCK_MODE mode)
Description
ctdbLock adjusts the current session-wide lock mode used by the lock manager. After a call to ctdbLock with a mode other than CTLOCK_FREE or CTLOCK_SUSPEND, all operations handling files will be locked. For instance, all records read (ctdbFirstRecord, ctdbNextRecord, ctdbLastRecord, ctdbFindRecord, etc.) after a call to ctdbLock, will be locked. To just lock the current record, use ctdbLockRecord. Note: At the moment ctdbLock is called, no file or record is locked. Instead, a flag is set internally to indicate that all new record reads will lock the records with the given lock mode. Handle [in] the Session or other internal Handle. mode [in] one of the valid c-treeDB lock modes. The valid lock modes are listed in "c-treeDB definitions".. A READ lock on a record allows an unlimited number of READ locks on that record, but prevents WRITE locks. A WRITE lock prevents any other locks on that record. Call ctdbUnlock(), or ctdbLock() with mode set to CTLOCK_FREE, to free all locks. Notice that, if called inside a transaction, this free operation will result in the suspension of the locks, and not in their release. The locks will only be released when the transaction is finished with a call to ctdbCommit() or ctdbAbort(). If the locks are suspended, it means that new records read will not be locked. To restore the suspended locks, use ctdbLock() with one of the READ or WRITE lock modes (or the RESTORE options). If, for any special reason, the unused locks from a particular table must be released inside a transaction, ctdbUnlockTable() may be used. Unused locks are records that where locked but not updated/deleted/added. Note: Mixing ctdbLockRecord() and ctdbLock() may result in DLOK_ERR (42) returns when an automatic lock is attempted on a manually locked record, or vice versa. DLOK_ERR (42) simply means a lock could not be obtained. Check sysiocod for the system-level error to determine why the record could not be locked. In the example above, a locked record cannot be re-locked.
Returns
ctdbLock() returns CTDBRET_OK on success, or c-treeDB C API error code on failure. Related common errors to are: CTDBRET_INVLOCKMODE (4055): Invalid lock mode. CTDBRET_NOTSESSION (4003): Invalid handle - use a Session handle.
See also
ctdbCommit(), ctdbAbort(), ctdbIsLockActive(), ctdbUnlock(), ctdbGetLockMode(), ctdbLockRecord(), ctdbSetKeepLock(), ctdbUnlockTable()
www.faircom.com
All Rights Reserved
533
ctdbLockRecord
Lock the current record.
Declaration
CTDBRET ctdbLockRecord(CTHANDLE Handle, CTLOCK_MODE Mode)
Description
ctdbLockRecord() locks the current record. To lock all records read, use ctdbLock(). To unlock a record locked with ctdbLockRecord(), use ctdbUnlockRecord() or ctdbUnlockTable(). Lock modes are available in "c-treeDB definitions".. Handle [in] the record handle. A READ lock on a record allows an unlimited number of READ locks on that record, but prevents WRITE locks. A WRITE lock prevents any other locks on that record.
Returns
ctdbLockRecord() returns CTDBRET_OK on success, or c-treeDB C API error code on failure. If there is no current record, ctdbLockRecord() returns CTDBRET_NOTACTIVE (4012).
See also
ctdbUnlockRecord(), ctdbLock(), ctdbBegin(), ctdbSetKeepLock(), ctdbUnlockTable()
FairCom Corporation
534
ctdbLogon
Logon to c-tree Server or c-tree Plus instance session.
Declaration
CTDBRET ctdbLogon(CTHANDLE Handle, pTEXT dbengine, pTEXT userid, pTEXT password)
Description
ctdbLogon() logs on to the c-tree Server or c-tree Plus instance. Before any database operation can take place, initiate a session with ctdbAllocSession() and then logon to the c-tree Server or c-tree Plus instance using ctdbLogon() before calling ctdbAllocDatabase(). Before logon to the c-tree Server or a c-tree Plus instance, it is necessary to have a session dictionary. To create a session dictionary, use the function ctdbCreateSession(). Handle [in] the session handle. dbengine [in] the string with the c-tree Server name or c-tree Plus instance name. If dbengine is NULL ctdbLogon() uses the string FAIRCOMS as the default server name or c-tree Plus instance. userid [in] the string with the user name. If userid is NULL ctdbLogon() uses the string as the default user name. password [in] the string with the user password. If password is NULL ctdbLogon() uses the string as the default user password. To logout from the c-tree Server or c-tree Plus instance, use the ctdbLogout() function.
Returns
ctdbLogon() returns CTDBRET_OK on success, or c-treeDB C API error code on failure.
Example
CTSESSION_TYPE ctdbsess=CTSESSION_CTDB; CTHANDLE hSession = ctdbAllocSession(ctdbsess); CTDBRET err; err = ctdbLogon(hSession, "FAIRCOMS", "ADMIN", "ADMIN"); err = ctdbCreateDatabase(hSession, "MyDatabase", ""); err = ctdbLogout(hSession); ctdbFreeSession(hSession);
See also
ctdbLogout(), ctdbAllocDatabase(), ctdbCreateSession(), ctdbIsActiveSession()
www.faircom.com
All Rights Reserved
535
ctdbLogout
Logout from a c-tree Server session or from a c-tree Plus instance.
Declaration
CTDBRET ctdbLogout(CTHANDLE Handle)
Description
ctdbLogout() logs out from the c-tree Server or c-tree Plus instance. Handle [in] the session handle.
Returns
ctdbLogout() returns CTDBRET_OK on success or c-treeDB C API error code on failure.
Example
CTSESSION_TYPE ctdbsess=CTSESSION_CTDB; CTHANDLE hSession = ctdbAllocSession(ctdbsess); CTDBRET err; err = ctdbLogon(hSession, "FAIRCOMS", "ADMIN", "ADMIN"); err = ctdbCreateDatabase(hSession, "MyDatabase", ""); err = ctdbLogout(hSession); ctdbFreeSession(hSession);
See also
ctdbLogon(), ctdbAllocSession()
FairCom Corporation
536
ctdbLongToBigInt
Convert a LONG value to a big integer.
Declaration
CTDBRET ctdbLongToBigInt(LONG value, pCTBIGINT pBigInt)
Description
ctdbLongToBigInt() converts a LONG value to a big integer value. A big integer is an 8 bytes integer value. Use ctdbBigIntToLong() to convert from a big integer to a LONG. value [in] the CTSIGNED LONG value (4 bytes signed integer). pBigInt [out] the big integer value (8 bytes signed integer).
Returns
ctdbLongToBigInt() returns CTDBRET_OK on success, or c-treeDB C API error on failure. The possible error associated with ctdbLongToBigInt() is: CTDBRET_NULARG (4007): Null argument not valid in pStr
See also
ctdbBigIntToLong()
www.faircom.com
All Rights Reserved
537
ctdbLongToCurrency
Convert a LONG value to a CTCURRENCY value.
Declaration
CTDBRET ctdbLongToCurrency(CTSIGNED value, pCTCURRENCY pCurrency)
Description
ctdbLongToCurrency() converts a CTSIGNED (4 bytes signed integer) value to a CTCURRENCY (8 bytes signed integer) value. Use ctdbCurrencyToLong() to convert from a CTCURRENCY value to a LONG value. value [in] the CTSIGNED value (4 bytes integer). pCurrency [out] the CTCURRENCY value (8 bytes integer).
Returns
ctdbLongToCurrency() returns CTDBRET_OK on success, or c-treeDB C API error on failure. The possible error associated with ctdbLongToCurrency() is: CTDBRET_NULARG (4007): Null argument not valid in pStr
See also
ctdbCurrencyToLong()
FairCom Corporation
538
ctdbLongToMoney
Convert a LONG value to a CTMONEY.
Declaration
CTDBRET ctdbLongToMoney(CTSIGNED value, pCTMONEY pMoney)
Description
ctdbLongToMoney() converts a LONG value to a CTMONEY value. The long value is multiplied by 100 before the conversion. Use ctdbMoneyToLong() to convert from a LONG to CTMONEY. value [in] the CTSIGNED LONG value. pMoney [out] the CTMONEY value.
Returns
ctdbLongToMoney() returns CTDBRET_OK on success, or c-treeDB C API error on failure. The possible error associated with ctdbLongToMoney() is: CTDBRET_NULARG (4007): Null argument not valid in pStr
See also
ctdbMoneyToLong()
www.faircom.com
All Rights Reserved
539
ctdbLongToNumber
Convert a LONG to a CTNUMBER value.
Declaration
CTDBRET ctdLongTobNumber(LONG value, pCTNUMBER pNumber)
Description
ctdbLongToNumber() converts a LONG to a CTNUMBER value. Use ctdbNumberToLong() to convert from CTNUMBER to a LONG. value [in] the LONG value. pNumber [out] pointer to CTNUMBER.
Returns
ctdbLongToNumber() returns CTDBRET_OK on success, or c-treeDB C API error on failure. The possible error associated with ctdbLongToNumber() is: CTDBRET_NULARG (4007): Null argument not valid in pValue
See also
ctdbNumberToLong()
FairCom Corporation
540
ctdbMergeDatabaseDictionary
Compare and merge c-treeDB database dictionaries.
Declaration
ctdbEXPORT CTDBRET ctdbDECL ctdbMergeDatabaseDictionary (CTHANDLE src, CTHANDLE dst, mergeFunPtr mrgfun, logFunPtr logfun);
Description
Parameters src: handle of an exclusively open session where the database dictionary is the dictionary containing the entry to be merged. dst: handle of an exclusively open session where the database dictionary is the target dictionary for the merge. mrgfun: function that the c-treeDB engine calls to perform the comparison and set the actions on the compared items. The function prototype is:
CTDBRET (ctdbDECL *mergeFunPtr) (pCTDBLIST src_list, pCTDBLIST dst_list);
mrgfun must return either an error code (in which case the ctdbMergeSessionDictionary () function will fail with that error code) or CTDBRET_OK if no error occurred. The c-treeDB engine will pass two lists (CTDBLIST) containing items of type MERGEINFO. One per each dictionary entry. The MERGEINFO structure is defined as follows:
struct tagMERGEINFO { DICTDATA info; NINT todo; };
info contains the dictionary record. todo must be set to the action to perform on that entry. src_list contains the elements from the source dictionary dst_list contains the elements from the target dictionary. The function must set for each entry the action to be performed on that entry as follows:
Source List Actions Description Ignore the record in the source list and do not copy it on the target dictionary Copy the record to the target dictionary for entries on the dst_list. Description Keep the entry as it is. Remove the entry. Replace the dest record on disk with the one in the list (in case we merge only some information). Note: This cannot change the UID.
DIFF_SRC_IGNORE DIFF_SRC_COPY2DST
Destination List Actions
For example, to replace an entry on the target dictionary with one from the source dictionary, the todo of the item in dsl_list must be set to DIFF_DST_REMOVE, the todo of the item in src_list to DIFF_SRC_COPY2DST. logfun: the function called to return additional information about errors.
www.faircom.com
All Rights Reserved
541
lvl: number indication the error message level. (1 indicating fewer and higher level messages to 3 indicating more numerous detailed messages.) mesg: the error message error: the error code extra: extra information such as the table or database name. Note: Depending on where an error occurred, this function could be called multiple times with different lvl and mesg.
Return Values
See c-tree Plus Error Codes for a complete listing of valid c-tree Plus error values.
Example
Please review the source code for ctsqlmdd.c, c-treeSQL Database Move Utility, for a complete implementation using this c-treeDB function.
See Also
ctrdbMergeSessionDictionary()
FairCom Corporation
542
ctdbMergeSessionDictionary
Compare and merge c-treeDB session dictionaries.
Declaration
ctdbEXPORT CTDBRET ctdbDECL ctdbMergeSessionDictionary (CTHANDLE src, CTHANDLE dst, mergeFunPtr mrgfun, logFunPtr logfun);
Description
Parameters src: handle of an exclusively open session where the session dictionary is the dictionary containing the entry to be merged. dst: handle of an exclusively open session where the session dictionary is the target dictionary for the merge. mrgfun: function that the c-treeDB engine calls to perform the comparison and set the actions on the compared items. The function prototype is:
CTDBRET (ctdbDECL *mergeFunPtr) (pCTDBLIST src_list, pCTDBLIST dst_list);
mrgfun must return either an error code (in which case the ctdbMergeSessionDictionary () function will fail with that error code) or CTDBRET_OK if no error occurred. The c-treeDB engine will pass two lists (CTDBLIST) containing items of type MERGEINFO. One per each dictionary entry. The MERGEINFO structure is defined as follows:
struct tagMERGEINFO { DICTDATA info; NINT todo; };
info contains the dictionary record. todo must be set to the action to perform on that entry. src_list contains the elements from the source dictionary dst_list contains the elements from the target dictionary. The function must set for each entry the action to be performed on that entry as follows:
Source List Actions Description Ignore the record in the source list and do not copy it on the target dictionary Copy the record to the target dictionary for entries on the dst_list. Description Keep the entry as it is. Remove the entry. Replace the dest record on disk with the one in the list (in case we merge only some information). Note: This cannot change the UID.
DIFF_SRC_IGNORE DIFF_SRC_COPY2DST
Destination List Actions
For example, to replace an entry on the target dictionary with one from the source dictionary, the todo of the item in dsl_list must be set to DIFF_DST_REMOVE, the todo of the item in src_list to DIFF_SRC_COPY2DST. logfun: the function called to return additional information about errors.
www.faircom.com
All Rights Reserved
543
lvl: number indication the error message level. (1 indicating fewer and higher level messages to 3 indicating more numerous detailed messages.) mesg: the error message error: the error code extra: extra information such as the table or database name. Note: Depending on where an error occurred, this function could be called multiple times with different lvl and mesg.
Return Values
See c-tree Plus Error Codes for a complete listing of valid c-tree Plus error values.
Example
Please review the source code for ctsqlmdd.c, c-treeSQL Database Move Utility, for a complete implementation using this c-treeDB function.
See Also
ctrdbMergeDatabaseDictionary()
FairCom Corporation
544
ctdbMoneyAbs
Return the absolute value of a CTMONEY type value.
Declaration
CTMONEY ctdbMoneyAbs(CTMONEY left)
Description
ctdbMoneyAbs() returns the absolute value of a CTMONEY type value. left [in] the value to be converted to absolute.
Returns
ctdbMoneyAbs() returns the absolute value.
See also
ctdbMoneyAdd(), ctdbMoneySub(), ctdbMoneyMul(), ctdbMoneyDiv(), ctdbMoneyCmp()
www.faircom.com
All Rights Reserved
545
ctdbMoneyAdd
Add two money values. pResult = left + right
Declaration
CTDBRET ctdbMoneyAdd(CTMONEY left, CTMONEY right, pCTMONEY pResult)
Description
ctdbMoneyAdd() add two money values. pResult = left + right. Do not make regular additions with CTMONEY values. left [in] the first value to be added. right [in] the second value to be added. pResult [out] the result of the add operation.
Returns
ctdbMoneyAdd() returns CTDBRET_OK on success, or c-treeDB C API error on failure. The possible errors associated with ctdbMoneyAdd() are: CTDBRET_NULARG (4007): Null argument not valid in any operand CTDBRET_UNDERFLOW (4039): Operation caused underflow CTDBRET_OVERFLOW (4038): Operation caused overflow
See also
ctdbMoneySub(), ctdbMoneyMul(), ctdbMoneyDiv()
FairCom Corporation
546
ctdbMoneyCmp
Compare two CTMONEY type values.
Declaration
NINT ctdbMoneyCmp(CTMONEY left, CTMONEY right)
Description
ctdbMoneyCmp() compares two CTMONEY values. left [in] the first value to be compared. right [in] the second value to be compared.
Returns
ctdbMoneyCmp() returns a negative value if left < right, positive value if left > right, and zero if left == right
See also
ctdbMoneyAdd(), ctdbMoneySub(), ctdbMoneyMul(), ctdbMoneyDiv(), ctdbMoneyAbs()
www.faircom.com
All Rights Reserved
547
ctdbMoneyDiv
Divide one money value by another money value. pResult = left / right.
Declaration
CTDBRET ctdbMoneyDiv(CTMONEY left, CTMONEY right, pCTMONEY pResult)
Description
ctdbMoneyDiv() divide one money value by another money value. pResult = left / right. Do not make regular division with CTMONEY values. You may user regular division between a CTMONEY value and a numeric value (int, COUNT, FLOAT, etc.). left [in] the value to be divided (divisor). right [in] the value to divide (dividend). pResult [out] the result of the Div operation.
Returns
ctdbMoneyDiv() returns CTDBRET_OK on success, or c-treeDB C API error on failure. The possible errors associated with ctdbMoneyDiv() are: CTDBRET_NULARG (4007): Null argument not valid in any operand CTDBRET_DIVBYZERO (4040): Division by zero error
See also
ctdbMoneyAdd(), ctdbMoneySub(), ctdbMoneyMul()
FairCom Corporation
548
ctdbMoneyMul
Multiply two CTMONEY values.
Declaration
CTDBRET ctdbMoneyMul(CTMONEY left, CTMONEY right, pCTMONEY pResult)
Description
ctdbMoneyMul() multiplies two money values. pResult = left * right. Do not make regular multiplication with CTMONEY values. It is possible to use regular multiplication with a CTMONEY value and a numeric value (int, COUNT, FLOAT, etc.). left [in] the first value to be multiplied. right [in] the second value to be multiplied. pResult [out] the result of the multiplication operation.
Returns
ctdbMoneyMul() returns CTDBRET_OK on success, or c-treeDB C API error on failure. The possible errors associated with ctdbMoneyMul() are: CTDBRET_NULARG (4070): Null argument not valid in any operand CTDBRET_OVERFLOW (4038): Operation caused overflow
See also
ctdbMoneyAdd(), ctdbMoneySub(), ctdbMoneyDiv()
www.faircom.com
All Rights Reserved
549
ctdbMoneySub
Subtract two money values. pResult = left - right.
Declaration
CTDBRET ctdbMoneySub(CTMONEY left, CTMONEY right, pCTMONEY pResult)
Description
ctdbMoneySub() subtracts two money values. pResult = left - right. Do not make regular subtractions with CTMONEY values. left [in] the first value, to be subtracted by right. right [in] the second value, to subtract from left. pResult [out] the result of the subtraction operation.
Returns
ctdbMoneySub() returns CTDBRET_OK on success, or c-treeDB C API error on failure. The possible errors associated with ctdbMoneySub() are: CTDBRET_NULARG (4007): Null argument not valid in any operand CTDBRET_UNDERFLOW (4039): Operation caused underflow CTDBRET_OVERFLOW (4038): Operation caused overflow
See also
ctdbMoneyAdd(), ctdbMoneyMul(), ctdbMoneyDiv()
FairCom Corporation
550
ctdbMoneyToCurrency
Convert a CTMONEY value to a CTCURRENCY value.
Declaration
CTDBRET ctdbMoneyToCurrency(CTMONEY money, pCTCURRENCY pCurrency)
Description
ctdbMoneyToCurrency() converts a CTMONEY value to a CTCURRENCY value. A currency value is an 8 bytes integer. Use ctdbCurrencyToMoney() to convert from a CTCURRENCY value to a CTMONEY value. money [in] the CTMONEY value. pCurrency [out] the CTCURRENCY value (8 bytes integer).
Returns
ctdbMoneyToCurrency() returns CTDBRET_OK on success, or c-treeDB C API error on failure. The possible error associated with ctdbMoneyToCurrency() is: CTDBRET_NULARG (4007): Null argument not valid in pStr
See also
ctdbCurrencyToMoney()
www.faircom.com
All Rights Reserved
551
ctdbMoneyToFloat
Convert a CTMONEY value to a floating point number
Declaration
CTDBRET ctdbMoneyToFloat(CTMONEY money, pCTFLOAT pValue)
Description
ctdbMoneyToFloat() converts a CTMONEY value to a floating point number. Use ctdbFloatToMoney() to convert from a floating point number to CTMONEY. money [in] the CTMONEY type value. pValue [out] the floating point value.
Returns
ctdbMoneyToFloat() returns CTDBRET_OK on success, or c-treeDB C API error on failure. The possible error associated with ctdbMoneyToFloat() is: CTDBRET_NULARG (4007): Null argument not valid in pStr
See also
ctdbFloatToMoney()
FairCom Corporation
552
ctdbMoneyToLong
Convert a CTMONEY value to a LONG.
Declaration
CTDBRET ctdbMoneyToLong(CTMONEY money, pLONG pValue)
Description
ctdbMoneyToLong() converts a CTMONEY value to a LONG. The Fraction part of CTMONEY is discarded and only the integer part is assigned. Use ctdbLongToMoney() to convert from a LONG to CTMONEY. money [in] the CTMONEY value. pValue [out] the LONG value representing the integer part of the monetary value.
Returns
ctdbMoneyToLong() returns CTDBRET_OK on success, or c-treeDB C API error on failure. The possible error associated with ctdbMoneyToLong() is: CTDBRET_NULARG (4007): Null argument not valid in pStr
See also
ctdbLongToMoney()
www.faircom.com
All Rights Reserved
553
ctdbMoneyToNumber
Convert a CTMONEY value to a CTNUMBER.
Declaration
CTDBRET ctdbMoneyToNumber(CTMONEY money, pCTNUMBER pNumber)
Description
ctdbMoneyToNumber() converts a CTMONEY value to a CTNUMBER. Use ctdbNumberToMoney() to convert from a CTNUMBER to CTMONEY. money [in] the CTMONEY value. pNumber[out] pointer to CTNUMBER.
Returns
ctdbMoneyToNumber() returns CTDBRET_OK on success, or c-treeDB C API error on failure. The possible error associated with ctdbMoneyToLong() is: CTDBRET_NULARG (4007): Null argument not valid in pStr
See also
ctdbNumberToMoney()
FairCom Corporation
554
ctdbMoneyToString
Convert a CTMONEY type value to a string.
Declaration
CTDBRET ctdbMoneyToString(CTMONEY money, pTEXT pStr, VRLEN size)
Description
ctdbMoneyToString() converts a CTMONEY value to a string. Use ctdbStringToMoney() to convert from a string to CTMONEY. money [in] the CTMONEY value. pStr [out] the pointer to the string that will result from the conversion. size [in] the buffer size of the string.
Returns
ctdbMoneyToString() returns CTDBRET_OK on success, or c-treeDB C API error on failure. The possible errors associated with ctdbMoneyToString() are: CTDBRET_NULARG (4007): Null argument not valid in pStr CTDBRET_ARGSMALL (4006): Argument is too small - increase size
See also
ctdbStringToMoney()
www.faircom.com
All Rights Reserved
555
ctdbMoveField
Move a field to another location.
Declaration
CTDBRET ctdbMoveField(CTHANDLE Handle, NINT newIndex)
Description
ctdbMoveField() moves the field to a new location. Handle [in] the Index handle. newIndex [in] Index of the new location of the field.
Returns
ctdbMoveField() returns CTDBRET_OK on success or c-treeDB SDK error code on failure.
See also
ctdbAllocTable(), ctdbAddField(), ctdbInsField(), ctdbDelField()
FairCom Corporation
556
ctdbMoveSegment
Moves a key segment to a location indicated by newIndex .
DECLARATION
CTDBRET ctdbDECL ctdbMoveSegment(CTHANDLE Handle, NINT newIndex);
DESCRIPTION
ctdbMoveSegment() moves a key segment to a location indicated by newIndex. Handle is a segment handle and newIndex indicates the relative position were the key segment should be moved to.
RETURN
Value 0 Symbolic Constant CTDBRET_OK Explanation No error occurred.
See Appendix A for a complete listing of valid c-tree Plus error values.
EXAMPLE
/* move the last segment to first */ NINT count = ctdbGetIndexSegmentCount(hIndex); if (count > 0) { CTHANDLE hSeg = ctdbGetSegment(hIndex, (count - 1)); if (ctdbMoveSegment(hSeg, 0) != CTDBRET_OK) printf("ctdbMoveSegment failed\n"); }
SEE ALSO
ctdbAddSegment(), ctdbInsSegment(), ctdbDelSegment()
www.faircom.com
All Rights Reserved
557
ctdbNextBatch
Retrieves the next record from batch buffer.
DECLARATION
CTDBRET ctdbDECL ctdbNextBatch(CTHANDLE Handle);
DESCRIPTION
If the mode of the batch operation is one of CTBATCH_GET, CTBATCH_RANGE or CTBATCH_PHYS then it may be necessary to retrieve all records that match the batch criteria. The records are retrieved by calling the ctdbNextBatch() function. The ctdbNextBatch() function retrieves the record data from the batch buffer maintained by c-treeDBs record handle. After a successful call to the ctdbNextBatch() function the field data can be retrieved by calling the appropriate ctdbGetFieldAs..() functions. Handle must be a record handle associated with an opened table.
RETURNS
Value 0 428 Symbolic Constant Explanation No error occurred. No more records can be retrieved. (Indicates every record in batch was retrieved.)
CTDBRET_OK BTMT_ERR
See Appendix A for a complete listing of valid c-tree Plus error values.
EXAMPLE
/* retrieve records */ while (ctdbNextBatch(hRecord) == CTDBRET_OK) { TEXT invoice[32], item[32]; ctdbGetFieldAsString(hRecord, 0, invoice, sizeof(invoice)); ctdbGetFieldAsString(hRecord, 1, item, sizeof(item)); printf("%-11s %s\n", invoice, item); }
SEE ALSO
ctdbBatchLoaded(), ctdbBatchLocked(), ctdbBatchMode(), ctdbBatchTotal(), ctdbEndBatch(), ctdbInsertBatch(), ctdbIsBatchActive(), ctdbSetBatch()
FairCom Corporation
558
ctdbNextDatabase
Get the next database that belongs to this session.
Declaration
CTDBRET ctdbNextDatabase(CTHANDLE Handle, pTEXT Name, VRLEN NameSize, pTEXT Path, VRLEN PathSize)
Description
ctdbNextDatabase() gets the next database that belongs to this session. Handle [in] the session handle. Name [out] receives the database name. NameSize [in] the Name size in bytes. If Name is not large enough to receive the database name, ctdbNextDatabase() will return CTDBRET_ARGSMALL (4006). Path [out] receives the database path, if the name is located and it is large enough to hold the path. PathSize [in] the Path size in bytes. If Path is not large enough to receive the database path, ctdbNextDatabase() will return CTDBRET_ARGSMALL (4006). Use ctdbNextDatabase() with ctdbFirstDatabase() to obtain the names of all Databases available to this Session. Use ctdbGetDatabaseCount() to retrieve the total number of databases in the session.
Returns
ctdbNextDatabase() returns CTDBRET_OK on success, or the c-tree Plus error code on failure.
Example
ctdbFirstDatabase(hSession, name, sizeof(name), path, sizeof(path)); do { printf("\n\nDatabase: %s (%s)\n", path, name); } while ( ctdbNextDatabase(hSession, name, sizeof(name), path, sizeof(path)) == CTDBRET_OK );
See also
ctdbFirstDatabase(), ctdbFindDatabase(), ctdbGetDatabaseCount()
www.faircom.com
All Rights Reserved
559
ctdbNextRecord
Get the next record on a table.
Declaration
CTDBRET ctdbNextRecord(CTHANDLE Handle)
Description
ctdbNextRecord() retrieves the next record on a table. Handle [in] the record handle. If sets are enabled by ctdbRecordSetOn(), ctdbNextRecord() will retrieve the next record in the set. Use ctdbFirstRecord() to retrieve the first record on a table, ctdbPrevRecord() to retrieve the previous record on a table, and ctdbLastRecord() to retrieve the last record on a table. Use ctdbFindRecord() to find a specific record on a table. ctdbNextRecord() and ctdbPrevRecord() must be used after at least one call was done to ctdbFirstRecord(), ctdbLastRecord(), or ctdbFindRecord().
Returns
ctdbNextRecord() returns CTDBRET_OK on success, or c-treeDB C API error on failure.
See also
ctdbAllocRecord(), ctdbFirstRecord(), ctdbPrevRecord(), ctdbLastRecord(), ctdbFindRecord(), ctdbRecordSetOn()
FairCom Corporation
560
ctdbNextResource
Locate and retrieve the next resource in a table.
DECLARATION
CTDBRET ctdbDECL ctdbNextResource(CTHANDLE resource, CTBOOL lock)
DESCRIPTION
ctdbNextResource() retrieve the next resource stored in a table. resource is a handle allocated with ctdbAllocHandle(). lock is used to indicate if the resource should be locked, if it is found.
RETURN
ctdbNextResource() returns CTDBRET_OK on success. If there are no resources for the table, ctdbFirstResource() return RNOT_ERR (408).
EXAMPLE
/* read resources with type >= type and number > 0 */ CTDBRET DisplayResources(CTHANDLE hTable, ULONG type) { CTDBRET eRet; CTHANDLE hRes = ctdbAllocResource(hTable, type, 0, NULL); /* check if resource was allocated */ if (!hRes) return ctdbGetError(hTable); /* note that no resource locks are acquired since we are not changing the resources */ while ((eRet = ctdbNextResource(hRes)) == CTDBRET_OK) { /* display resource type, number and name */ printf("Resource type: %u, number: %u", ctdbGetResourceType(hRes), ctdbGetResourceNumber(hRes)); if (ctdbGetResourceName(hRes) != NULL) printf(", name: \"\"\n", ctdbGetResourceName(hRes)); else printf(", name: NULL"\n"); } ctdbFreeResource(hRes); return eRet; }
SEE ALSO
ctdbAllocResource, ctdbFreeResource, ctdbAddResource, ctdbDeleteResource, ctdbUpdateResource, ctdbFirstResource, ctdbFindResource, ctdbFindResourceByName, ctdbGetResourceType, ctdbSetResourceType, ctdbGetResourceNumber, ctdbSetResourceNumber, ctdbGetResourceName, ctdbSetResourceName, ctdbGetResourceDataLength, ctdbGetResourceData, ctdbSetResourceData, ctdbIsResourceLocked, ctdbUnlockResource
www.faircom.com
All Rights Reserved
561
ctdbNextTable
Get the next table in a database dictionary.
Declaration
CTDBRET ctdbNextTable(CTHANDLE Handle, pTEXT Name, VRLEN NameSize, pTEXT Path, VRLEN PathSize)
Description
ctdbNextTable gets the first table in a database dictionary. Handle [in] the Database Handle. Name [out] receives the table name. NameSize [in] the Name size in bytes. Path [out] receives the table path. PathSize [in] the Path size in bytes. ctdbNextTable(), in conjunction with ctdbFirstTable(), may be used to obtain the names of all tables available to this Database. ctdbGetTableCount() may be used to retrieve the total number of tables in the database.
Returns
ctdbNextTable() returns CTDBRET_OK on success, or the c-tree Plus error code on failure.
Example
ctdbFirstTable(hDB, t_name, sizeof(t_name), t_path, sizeof (t_path)); do { printf(\ntable name: %s, t_name); } while (ctdbNextTable(hDB, t_name, sizeof(t_name), t_path, sizeof(t_path)) == CTDBRET_OK);
See also
ctdbFirstTable(), ctdbFindTable(), ctdbGetTableCount()
FairCom Corporation
562
ctdbNumberAbs
Return the absolute value of a CTNUMBER type value.
Declaration
CTDBRET ctdbNumberAbs(pCTNUMBER pSource, pCTNUMBER pResult)
Description
ctdbNumberAbs() returns the absolute value of a CTNUMBER type value. pSource [in] the value to be converted to absolute. pResult [out] the absolute value.
Returns
ctdbNumberAbs() returns CTDBRET_OK on success, or c-treeDB C API error on failure. The possible errors associated with ctdbNumberAbs() are: CTDBRET_NULARG (4007): Null argument not valid in any operand
See also
ctdbNumberAdd(), ctdbNumberSub(), ctdbNumberMul(), ctdbNumberDiv(), ctdbNumberCmp(), ctdbNumberNegate(), ctdbNumberZero(), ctdbNumberRound(), ctdbNumberCopy(), ctdbNumberGetDecimal()
www.faircom.com
All Rights Reserved
563
ctdbNumberAdd
Add two Number values. pResult = left + right
Declaration
CTDBRET ctdbNumberAdd(pCTNUMBER pLeft, pCTNUMBER pRight, pCTNUMBER pResult)
Description
ctdbNumberAdd() add number pLeft to pRight and store the result in pResult. Do not make regular additions with CTNUMBER values. pLeft [in] the first value to be added. pRight [in] the second value to be added. pResult [out] the result of the add operation.
Returns
ctdbNumberAdd() returns CTDBRET_OK on success, or c-treeDB C API error on failure. The possible error associated with ctdbNumberAdd() is: CTDBRET_OVERFLOW (4038): Operation caused overflow
See also
ctdbNumberSub(), ctdbNumberMul(), ctdbNumberDiv()
FairCom Corporation
564
ctdbNumberCmp
Compare two CTNUMBER type values.
Declaration
NINT ctdbNumberCmp(CTNUMBER pSource, pCTNUMBER pResult)
Description
ctdbNumberCmp() compares two CTNUMBER values. pSource [in] the value to be converted to absolute. pResult [out] the absolute value.
Returns
ctdbNumberCmp() returns a negative value if num1 < num2, positive value if num1> num2, and zero if num1 == num2
See also
ctdbNumberAdd(), ctdbNumberSub(), ctdbNumberMul(), ctdbNumberDiv(), ctdbNumberAbs(), ctdbNumberNegate(), ctdbNumberZero(), ctdbNumberRound(), ctdbNumberCopy(), ctdbNumberGetDecimal()
www.faircom.com
All Rights Reserved
565
ctdbNumberCopy
Copy a number from pSource to pDest.
Declaration
CTDBRET ctdbNumberCopy(pCTNUMBER pDest, pCTNUMBER pSource)
Description
ctdbNumberAbs() copies a number from pSource to pDest. pDest [out] pointer to the copy. pSource [in] the value to be copied.
Returns
ctdbNumberAbs() returns CTDBRET_OK on success, or c-treeDB C API error on failure. The possible errors associated with ctdbNumberAbs() are: CTDBRET_NULARG (4007): Null argument not valid in any operand
See also
ctdbNumberAdd(), ctdbNumberSub(), ctdbNumberMul(), ctdbNumberDiv(), ctdbNumberCmp(), ctdbNumberNegate(), ctdbNumberZero(), ctdbNumberRound(), ctdbNumberCopy(), ctdbNumberGetDecimal()
FairCom Corporation
566
ctdbNumberDiv
Divide one Number value by another Number value. pResult = pLeft / pRight.
Declaration
CTDBRET ctdbNumberDiv(CTNUMBER pLeft, pCTNUMBER pRight, pCTNUMBER pResult)
Description
ctdbNumberDiv() divide one Number value by another Number value. pResult = pLeft / pRight. Do not make regular division with CTNUMBER values. pLeft [in] the value to be divided (divisor). pRight [in] the value to divide (dividend). pResult [out] the result of the Div operation.
Returns
ctdbNumberDiv() returns CTDBRET_OK on success, or c-treeDB C API error on failure. The possible errors associated with ctdbNumberDiv() are: CTDBRET_NULARG (4007): Null argument not valid in any operand CTDBRET_DIVBYZERO (4040): Division by zero error
See also
ctdbNumberAdd(), ctdbNumberSub(), ctdbNumberMul()
www.faircom.com
All Rights Reserved
567
ctdbNumberGetDecimal
Retrieve the number of digits before and after the decimal point.
Declaration
CTDBRET ctdbNumberGetDecimal(pCTNUMBER data, pNINT digit_before, pNINT digit_after)
Description
ctdbNumberGetDecimal() retrieves the number of digits before and after the decimal point. data [in] pointer to number. digit_before [out] the number of digits before the decimal place. digit_after [out] the number of digits after the decimal place.
Returns
ctdbNumberGetDecimal() returns CTDBRET_OK on success, or c-treeDB C API error on failure. The possible errors associated with ctdbNumberGetDecimal() are: CTDBRET_NULARG (4007): Null argument not valid in any operand CTDBRET_INVNUMBER (4060): Number value invalid (out of bounds)
See also
ctdbNumberAdd(), ctdbNumberSub(), ctdbNumberMul(), ctdbNumberDiv(), ctdbNumberAbs(), ctdbNumberCmp(), ctdbNumberZero(), ctdbNumberCopy(), ctdbNumberGetDecimal(), ctdbNumberCopy(), ctdbNumberRound()
FairCom Corporation
568
ctdbNumberMul
Multiply two CTNUMBER values.
Declaration
CTDBRET ctdbNumberMul(CTNUMBER pLeft, pCTNUMBER pRight, pCTNUMBER pResult)
Description
ctdbNumberMul multiplies two Number values. pResult = pLeft * pRight. Do not make regular multiplication with CTNUMBER values. pLeft [in] the first value to be multiplied. pRight [in] the second value to be multiplied. pResult [out] the result of the multiplication operation.
Returns
ctdbNumberMul() returns CTDBRET_OK on success, or c-treeDB C API error on failure. The possible errors associated with ctdbNumberMul() are: CTDBRET_NULARG (4007): Null argument not valid in any operand CTDBRET_OVERFLOW (4038): Operation caused overflow
See also
ctdbNumberAdd(), ctdbNumberSub(), ctdbNumberDiv()
www.faircom.com
All Rights Reserved
569
ctdbNumberNegate
Negate a number.
Declaration
CTDBRET ctdbNumberNegate(CTNUMBER pSource, pCTNUMBER pResult)
Description
ctdbNumberNegate negates a number (eg. -Number). pSource [in] the value to be negated. pResult [out] the negated value (= -pSource).
Returns
ctdbNumberNegate() returns CTDBRET_OK on success, or c-treeDB C API error on failure. The possible errors associated with ctdbNumberNegate() are: CTDBRET_NULARG (4007): Null argument not valid in any operand CTDBRET_OVERFLOW (4038): Operation caused overflow
See also
ctdbNumberAdd(), ctdbNumberSub(), ctdbNumberMul(), ctdbNumberDiv(), ctdbNumberAbs(), ctdbNumberCmp(), ctdbNumberZero(), ctdbNumberRound(), ctdbNumberCopy(), ctdbNumberGetDecimal()
FairCom Corporation
570
ctdbNumberOfKeyEntries
Declaration
LONG ctdbDECL ctdbNumberOfKeyEntries(CTHANDLE Handle, NINT index);
Description
ctdbNumberOfKeyEntries() retrieves the number key entries in an index file identified by its index number. Handle is a table handle or a handle that can be evaluated into a table handle. index identifies the index to obtain the number of entries. The first index number is zero.
Return Values
ctdbNumberOfKeyEntries() returns the number of key entries in the index. ctdbNumberOfKeyEntries() returns -1 and users should call the ctdbGetError() function to retrieve the error code.
See c-tree Plus Error Codes for a complete listing of valid c-tree Plus error values.
Example
LONG Estimate(CTHANDLE Handle, NINT index) { LONG Retval = 0; TEXT key1[16], key2[16]; VRLEN klen; /* set the default index */ ctdbSetDefaultIndex(Handle, index); /* load the first record */ ctdbFirstRecord(Handle); /* build the target key for the first record */ klen = sizeof(key1); ctdbBuildTargetKey(Handle, CTFIND_EQ, key1, &klen); /* load the last record */ ctdbLastRecord(Handle); /* build the target key for the last record */ klen = sizeof(key2); ctdbBuildTargetKey(Handle, CTFIND_EQ, key2, &klen); /* get the estimated span */ Retval = ctdbEstimateSpan(Handle, key1, key2); if (Retval > 0) Retval--; return Retval; }
See Also
ctdbGetError(), ctdbEstimateKeySpan()
www.faircom.com
All Rights Reserved
571
ctdbNumberRound
Round a number to a scale.
Declaration
CTDBRET ctdbNumberRound(pCTNUMBER num, NINT scale)
Description
ctdbNumberRound() rounds a number to a certain number of decimal digits. num [in] the number to be rounded. scale [out] the number of decimal digits.
Returns
ctdbNumberRound() returns CTDBRET_OK on success, or c-treeDB C API error on failure. The possible errors associated with ctdbNumberRound() are: CTDBRET_NULARG (4007): Null argument not valid in any operand CTDBRET_OVERFLOW (4038): Operation caused overflow
See also
ctdbNumberAdd(), ctdbNumberSub(), ctdbNumberMul(), ctdbNumberDiv(), ctdbNumberAbs(), ctdbNumberCmp(), ctdbNumberZero(), ctdbNumberCopy(), ctdbNumberGetDecimal(), ctdbNumberCopy(), ctdbNumberGetDecimal()
FairCom Corporation
572
ctdbNumberSub
Subtract two Number values. pResult = pLeft - pRight.
Declaration
CTDBRET ctdbNumberSub(CTNUMBER pLeft, pCTNUMBER pRight, pCTNUMBER pResult)
Description
ctdbNumberSub() subtracts two Number values. pResult = pLeft - pRight. Do not make regular subtractions with CTNUMBER values. pLeft [in] the first value, to be subtracted by right. pRight [in] the second value, to subtract from left. pResult [out] the result of the subtraction operation.
Returns
ctdbNumberSub() returns CTDBRET_OK on success, or c-treeDB C API error on failure. The possible errors associated with ctdbNumberSub() are: CTDBRET_NULARG (4007): Null argument not valid in any operand CTDBRET_UNDERFLOW (4039): Operation caused underflow CTDBRET_OVERFLOW (4038): Operation caused overflow
See also
ctdbNumberAdd(), ctdbNumberMul(), ctdbNumberDiv()
www.faircom.com
All Rights Reserved
573
ctdbNumberToBigInt
Convert a CTNUMBER value to a big integer.
Declaration
CTDBRET ctdbNumberToBigInt(pCTNUMBER pNumber, pCTBIGINT pValue)
Description
ctdbNumberToBigInt() converts a CTNUMBER value to a big integer (8 bytes). Use ctdbBigIntToNumber() to convert from a big integer to CTNUMBER. Use ctdbNumberToLong() to convert CTNUMBER to a LONG (4 bytes integer). pNumber [in] pointer to CTNUMBER. pValue [out] the CTBIGINT value.
Returns
ctdbNumberToBigInt() returns CTDBRET_OK on success, or c-treeDB C API error on failure. The possible error associated with ctdbNumberToBigInt() is: CTDBRET_NULARG (4007): Null argument not valid in pValue
See also
ctdbBigIntToNumber(), ctdbNumberToLong()
FairCom Corporation
574
ctdbNumberToCurrency
Convert a CTNUMBER value to a currency.
Declaration
CTDBRET ctdbNumberToCurrency(pCTNUMBER pNumber, pCTCURRENCY pValue)
Description
ctdbNumberToCurrency() converts a CTNUMBER value to a CTCURRENCY value. Use ctdbCurrencyToNumber() to convert from a CTCURRENCY to CTNUMBER. Use ctdbNumberToMoney() to convert CTNUMBER to a CTMONEY. pNumber [in] pointer to CTNUMBER. pValue [out] the CTCURRENCY value.
Returns
ctdbNumberToCurrency() returns CTDBRET_OK on success, or c-treeDB C API error on failure. The possible error associated with ctdbNumberToCurrency() is: CTDBRET_NULARG (4007): Null argument not valid in pValue
See also
ctdbCurrencyToNumber(), ctdbNumberToLong(), ctdbNumberToMoney()
www.faircom.com
All Rights Reserved
575
ctdbNumberToFloat
Convert a CTNUMBER value to a float.
Declaration
CTDBRET ctdbNumberToFloat(pCTNUMBER pNumber, pCTFLOAT pValue)
Description
ctdbNumberToFloat() converts a CTNUMBER value to a floating point value. Use ctdbFloatToNumber() to convert from float to CTNUMBER. pNumber [in] pointer to CTNUMBER. pValue [out] the float value.
Returns
ctdbNumberToFloat() returns CTDBRET_OK on success, or c-treeDB C API error on failure. The possible error associated with ctdbNumberToFloat() is: CTDBRET_NULARG (4007): Null argument not valid in pValue
See also
ctdbFloatToNumber()
FairCom Corporation
576
ctdbNumberToLong
Convert a CTNUMBER value to a LONG.
Declaration
CTDBRET ctdbNumberToLong(pCTNUMBER pNumber, pLONG pValue)
Description
ctdbNumberToLong() converts a CTNUMBER value to a LONG. Use ctdbLongToNumber() to convert from LONG to CTNUMBER. Use ctdbNumberToBigInt() to convert a CTNUMBER to a big integer (8 byte integer). pNumber [in] pointer to CTNUMBER. pValue [out] the LONG value.
Returns
ctdbNumberToLong() returns CTDBRET_OK on success, or c-treeDB C API error on failure. The possible error associated with ctdbNumberToLong() is: CTDBRET_NULARG (4007): Null argument not valid in pValue
See also
ctdbLongToNumber(), ctdbNumberToBigInt()
www.faircom.com
All Rights Reserved
577
ctdbNumberToMoney
Convert a CTNUMBER value to a CTMONEY.
Declaration
CTDBRET ctdbNumberToMoney(pCTNUMBER pNumber, pCTMONEY pMoney)
Description
ctdbNumberToMoney() converts a CTNUMBER value to a CTMONEY. Use ctdbMoneyToNumber() to convert from CTMONEY to CTNUMBER. Use ctdbNumberToCurrency() to convert CTNUMBER to a CTCURRENCY. pNumber [in] pointer to CTNUMBER. pMoney [out] the CTMONEY value.
Returns
ctdbNumberToMoney() returns CTDBRET_OK on success, or c-treeDB C API error on failure. The possible error associated with ctdbNumberToMoney() is: CTDBRET_NULARG (4007): Null argument not valid in pMoney
See also
ctdbMoneyToNumber(), ctdbNumberToCurrency()
FairCom Corporation
578
ctdbNumberToString
Convert a CTNUMBER type value to a string.
Declaration
CTDBRET ctdbNumberToString(pCTNUMBER pNumber, pTEXT pStr, VRLEN size)
Description
ctdbNumberToString() converts a CTNUMBER value to a string. Use ctdbStringToNumber() to convert from a string to CTNUMBER. pNumber [in] pointer to CTNUMBER. pStr [out] the pointer to the string that will result from the conversion. size [in] the buffer size of the string.
Returns
ctdbNumberToString() returns CTDBRET_OK on success, or c-treeDB C API error on failure. The possible errors associated with ctdbNumberToString() are: CTDBRET_NULARG (4007): Null argument not valid in pStr CTDBRET_OVERFLOW (4038): Operation caused overflow
See also
ctdbStringToNumber()
www.faircom.com
All Rights Reserved
579
ctdbNumberZero
Set the value of a number to zero.
Declaration
CTDBRET ctdbNumberZero(pCTNUMBER pNumber)
Description
ctdbNumberZero() sets the value of a number to zero. pNumber [in] pointer to a number.
Returns
ctdbNumberZero() returns CTDBRET_OK on success, or c-treeDB C API error on failure. Use ctdbIsNumberZero() to check if a number is zero. The possible error associated with ctdbNumberZero() is: CTDBRET_NULARG (4007): Null argument not valid in any operand
See also
ctdbIsNumberZero(), ctdbNumberAbs(), ctdbNumberCmp(), ctdbNumberNegate(), ctdbNumberRound(), ctdbNumberCopy(), ctdbNumberGetDecimal()
FairCom Corporation
580
ctdbOpenTable
Open an existing table given its name.
Declaration
CTDBRET ctdbOpenTable(CTHANDLE Handle, pTEXT TableName, CTOPEN_MODE OpenMode)
Description
ctdbOpenTable() opens an existing table, given its name. To open an existing table given its unique identifier, use ctdbOpenTableByUID(). To create a table, use ctdbCreateTable(). To retrieve the table open mode, use ctdbGetTableOpenMode(). To close an open table, use ctdbCloseTable(). Handle [in] the Table Handle. TableName [in] the table name. OpenMode [in] the table open mode. The valid values for the table open mode are listed in "c-treeDB definitions".. To open an existing mirrored table, use ctdbOpenTable() specifying the proper mirror naming convention:
if (ctdbOpenTable(hTable, CTOPEN_NORMAL, "customer|mirror")) printf("ctdbOpenTable failed\n");
Returns
ctdbOpenTable() returns CTDBRET_OK on success, or c-treeDB C API error on failure.
See also
ctdbAllocTable(), ctdbCreateTable(), ctdbGetTableOpenMode(), ctdbCloseTable(), ctdbOpenTableByUID()
www.faircom.com
All Rights Reserved
581
ctdbOpenTableByUID
Open an existing table, given its UID.
Declaration
CTDBRET ctdbOpenTableByUID(CTHANDLE Handle, ULONG uid, CTOPEN_MODE OpenMode)
Description
ctdbOpenTableByUID() opens an existing table, given its unique identifier. To open the table given its name, use ctdbOpenTable(). To create a table, use ctdbCreateTable(). To retrieve the table open mode, use ctdbGetTableOpenMode(). To close an open table, use ctdbCloseTable(). Handle [in] the Table Handle. TableName [in] the table name. OpenMode [in] the table open mode. The valid values for the table open mode are listed in "c-treeDB definitions"..
Returns
ctdbOpenTableByUID() returns CTDBRET_OK on success, or c-treeDB C API error on failure.
See also
ctdbAllocTable(), ctdbCreateTable(), ctdbGetTableOpenMode(), ctdbCloseTable(), ctdbOpenTable()
FairCom Corporation
582
ctdbPrevRecord
Get the previous record on a table.
Declaration
CTDBRET ctdbPrevRecord(CTHANDLE Handle)
Description
ctdbPrevRecord() retrieves the previous record on a table. Handle [in] the record handle. If sets are enabled by ctdbRecordSetOn(), ctdbPrevRecord() will retrieve the previous record in the set. Use ctdbFirstRecord() to retrieve the first record on a table, ctdbNextRecord() to retrieve the next record on a table, and ctdbLastRecord() to retrieve the last record on a table. Use ctdbFindRecord() to find a specific record on a table. ctdbNextRecord() and ctdbPrevRecord() must be used after at least one call was done to ctdbFirstRecord(), ctdbLastRecord(), or ctdbFindRecord().
Returns
ctdbPrevRecord() returns CTDBRET_OK on success, or c-treeDB C API error on failure.
See also
ctdbAllocRecord(), ctdbFirstRecord(), ctdbNextRecord(), ctdbLastRecord(), ctdbFindRecord(), ctdbRecordSetOn()
www.faircom.com
All Rights Reserved
583
ctdbReadRecord
Reread a record from its offset
Declaration
CTDBRET ctdbReadRecord(CTHANDLE Handle)
Description
ctdbReadRecord() rereads a record from its offset. The record cursor must have been activated with a call to one of the search routines, and no subsequent call to ctdbClearRecord(). Handle [in] the record handle.
Returns
ctdbReadRecord() returns CTDBRET_OK if successful, or the c-tree Plus error code on failure.
See also
ctdbAllocRecord(), ctdbWriteRecord(), ctdbClearRecord()
FairCom Corporation
584
ctdbRebuildTable
Declaration
CTDBRETURN ctdbRebuildTable(CTHANDLE Handle, CTREBUILD_MODE mode);
Description
Handle [IN] Table handle mode [IN] The following modes are available:
CTREBUILD Mode Description The normal rebuild mode. Purge duplicate records during rebuild. Update the IFIL structure in the table. Rebuild only the datafile.
Note: Exercise care when using CTREBUILD_DATAONLY and CTCREBUILD_UPDATEIFIL modes together as the index files will be removed from the table IFIL definition even if the index files still exist in the file system. This can cause later problems if ctdbAlterTable() is called to recreate the removed indexes. ctdbRebuildTable() calls the c-treeACE CTRBLIFILX() function to rebuild a c-tree table. When used in conjunction with the open modes CTOPEN_CORRUPT and CTOPEN_DATAONLY, the ctdbRebuildTable() function can be used as a direct replacement for the c-tree Plus ctrbldif rebuild utility. The following steps are performed by c-treeDB during a table rebuild process: 1. If a transaction is active, and the table being rebuilt was created with CTCREATE_TRNLOG or CTCREATE_PREIMG, the transaction is committed before the table is rebuilt, and the transaction is restarted after the table rebuild process is completed. 2. The update corrupt flag, updflg, of the header of the data file is cleared. 3. The internal delete stack chain of fixed-length data files or the internal delete management index of variable length data files are rebuilt. 4. The existing index files are removed and new index files are rebuilt over the existing files, optimized for both size and speed. You must open the table before ctdbRebuildTable() is executed. It is recommended that the table be opened with CTOPEN_EXCLUSIVE mode. If the table is corrupt, you will need to open the table with the CTOPEN_CORRUPT mode and then call ctdbRebuildTable() to rebuild the data and index files. If there are missing or corrupt index files, open the table with CTOPEN_DATAONLY mode and ctdbRebuildTable() will reconstruct the missing index files. There may be situations when you need to invoke this function to rebuild only the data file. After the data file rebuild is successful, you may need to call ctdbRebuildTable() again to rebuild the index files.
Return Values
Value 0 650 Symbolic Constant NO_ERROR Explanation Successful operation. Duplicate keys purged and logged.
DUPJ_ERR
www.faircom.com
All Rights Reserved
585
See c-tree Plus Error Codes for a complete listing of valid c-tree Plus error values.
See Also
ctdbAlterTable()
FairCom Corporation
586
ctdbRecordAtPercentile
Find a record located at about the given percentile value.
Declaration
CTDBRET ctdbRecordAtPercentile(CTHANDLE Handle, NINT pecent);
Description
ctdbRecordAtPercentile() read the record located at, approximately, the given percentile value. Handle is a record handle and percent indicate the percentile value. The valid values for percent are from 0 to 100, indicating 0% to 100%. ctdbRecordAtPercentile() return CTDBRET_OK on success. The record is located using the record handle current index. You may select a new current index by calling ctdbSetDefaultIndex() function. The table must have at least one index to be able to use this function. The record returned is an approximation location indicated by the percentual value passed to ctdbRecordAtPercentile(). ctdbRecordAtPercentile(), which is based on c-tree low level function KeyAtPercentile(), and it is very efficient since it does not traverse all of the key values in order to determine the record located at the specified percentile. However, ctdbRecordAtPercentile() is only an approximation since it assumes that key values are uniformly distributed among all of the b-tree leaf nodes. ctdbRecordAtPercentile() may be used to support scroll bar positioning, found in many GUI windowing environments, in the cases when the position must be maintained in key sequential order.
Return
Value Symbolic Constant Explanation
CTDBRET_OK
See "c-treeDB Errors and Return Values" for a complete listing of valid c-treeDB error codes and return values.
Example
/* display the record at 50% of table */ if (ctdbRecordAtPercentile(hRecord, 50) == CTDBRET_OK) { DisplayTheRecord(hRecord); } else { printf("Faield with error %d\n", ctdbGetError(hRecord)); }
See also
ctdbSetDefaultIndex()
www.faircom.com
All Rights Reserved
587
ctdbRecordRangeOff
Terminate a record index range operation established by ctdbRecordRangeOn().
Declaration
CTDBRET ctdbRecordRangeOff(CTHANDLE Handle);
Description
ctdbRecordRangeOff() terminate a range operation. Handle is a record handle.
Return
Value 0 Symbolic Constant CTDBRET_OK Explanation
See "c-treeDB Errors and Return Values" for a complete listing of valid c-treeDB error codes and return values.
Example
/* display all records where age is greater than 65 */ void DisplayAll(CTHANDLE hRecord) { UTEXT lRange[32]; NINT op[1] = {CTIX_GT}; NINT fldno = ctdbGetFieldNumberByName(hHandle, "age"); CTDBRET eRet; ctdbClearRecord(hRecord); ctdbSetFieldAsSigned(hRecord, fldno, 65); ctdbSetDefaultIndex(hRecord, 0); ctdbBuildTargetKey(hRecord, CTFIND_EQ, lRange, 32); eRet = ctdbRecordRangeOn(hRecord, 1, lRange, NULL, op); if (eRet == CTDBRET_OK) { eRet = ctdbFirstRecord(hRecord); while (eRet == CTDBRET_OK) { TEXT str[128]; ctdbGetFieldAsString(hRecord, 0, str, sizeof(str)); printf("%s\n", str); eRet = ctdbNextRecord(hRecord); } } if (ctdbIsRecordRangeOn(hRecord)) ctdbRecordRangeOff(hRecord); }
See also
ctdbRecordRangeOn(), ctdbIsRecordRangeOn()
FairCom Corporation
588
ctdbRecordRangeOn
Establish a new index range on a record handle.
Declaration
CTDBRET ctdbRecordRangeOn(CTHANDLE Handle, NINT SegCount, pVOID lRange, pVOID uRange, pNINT operators);
Description
ctdbRecordRangeOn() establish a new range based on the key segment values passed on lRange and uRange buffers, and the operators for each segment. Once the range is set, use ctdbFirstRecord(), ctdbNextRecord(), ctdbPrevRecord() and ctdbLastRecord() to navigate the records in the specified range. The range is set for all index entries that are situated between the lower bounds and upper bounds values. The segment values are stored in lRange and uRange buffers in the same order and type of the index segment definition. If a previous range exists for this index, the previous range is released and the new range is established. Ranges take precedence over sets. If a record handle has a set established, record from a range will fetched instead of records from a range. Once the range is terminated, the records from a set is established. Handle is the record handle. SegCount indicates the number of index segments values that should be used for setting the range, and the number of operators, since there must be one operator for each key segment in lRange and/or uRange. lRange is a buffer with the lower range segment values. Use the function ctdbBuildTargetKey() to build the lRange buffer. uRange is a buffer with the upper range segment values. Use the function ctdbBuildTargetKey() to build the uRange buffer. operators operators is an array of operators. There must be one operator for each key segment in lRange and/or uRange. 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 and the equivalent key segment in uRange is ignored and maybe set to null (ascii \0 values). 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 values.
Return
Value 0 Symbolic Constant CTDBRET_OK Explanation
See "c-treeDB Errors and Return Values" for a complete listing of valid c-treeDB error codes and return values.
Example
/* display all records where age is greater than 65 */ void DisplayAll(CTHANDLE hRecord) { UTEXT lRange[32]; NINT op[1] = {CTIX_GT}; NINT fldno = ctdbGetFieldNumberByName(hHandle, "age"); CTDBRET eRet; ctdbClearRecord(hRecord); ctdbSetFieldAsSigned(hRecord, fldno, 65);
www.faircom.com
All Rights Reserved
589
ctdbSetDefaultIndex(hRecord, 0); ctdbBuildTargetKey(hRecord, CTFIND_EQ, lRange, 32); eRet = ctdbRecordRangeOn(hRecord, 1, lRange, NULL, op); if (eRet == CTDBRET_OK) { eRet = ctdbFirstRecord(hRecord); while (eRet == CTDBRET_OK) { TEXT str[128]; ctdbGetFieldAsString(hRecord, 0, str, sizeof(str)); printf("%s\n", str); eRet = ctdbNextRecord(hRecord); } } if (ctdbIsRecordRangeOn(hRecord)) ctdbRecordRangeOff(hRecord); }
See also
ctdbRecordRangeOff(), ctdbIsRecordRangeOn()
FairCom Corporation
590
ctdbRecordSetOff
Disable and free an existing record set.
Declaration
CTDBRET ctdbRecordSetOff(CTHANDLE Handle)
Description
ctdbRecordSetOff() disables and free an existing record set. To enable a new record set, use ctdbRecordSetOn(). Handle [in] the record handle.
Returns
ctdbRecordSetOff() returns CTDBRET_OK if successful, or the c-tree Plus error code on failure. The possible errors associated with ctdbRecordSetOff() are: CTDBRET_NOTRECORD (4024): Invalid Record Handle
Example
ctdbRecordSetOn(pRec, 5); ctdbSetDefaultIndexByName(pRec, last name); ctdbSetFieldAsString(pRec, 0, silva); ctdbFirstRecord(pRec); ctdbRecordSetOff(pRec);
See also
ctdbAllocRecord(), ctdbRecordSetOn()
www.faircom.com
All Rights Reserved
591
ctdbRecordSetOn
Enable a new record set. The target key is built from the contents of the record buffer.
Declaration
CTDBRET ctdbRecordSetOn(CTHANDLE Handle, NINT siglen)
Description
ctdbRecordSetOn() enables a new record set. The target key is built from the contents of the record buffer. Handle [in] the record handle. siglen [in] the number of key bytes to be used by the set. When record set is enabled, the record operations will be substituted by the set operations. This means that, when record set is enabled, operations like ctdbFirstRecord() will search for the first record in the set instead of the first record in the entire table. Just one record set can be enabled for each record handle. If it is necessary to have more than one record set enabled at the same time, more than one record handle will be required. To disable and free an existing record set, use ctdbRecordSetOff(). If used in conjunction with filters (ctdbFilterRecord()), may behavior as a simple query. Returns ctdbRecordSetOn() returns CTDBRET_OK if successful, or the c-tree Plus error code on failure. The possible errors associated with ctdbRecordSetOn() are: CTDBRET_NOTRECORD (4024): Invalid record handle CTDBRET_NOTACTIVE (4012): Table is not active CTDBRET_NOINDEX (4048): No index in the active table CTDBRET_NOMEMORY (4001): No memory to allocate the key
Example
/* display all records in set - no error checking */ void DisplayAll(CTHANDLE pRec) { NINT count = 0; ctdbClearRecord(pRec); ctdbSetDefaultIndexByName(pRec, "index_name"); ctdbSetFieldAsString(pRec, 0, "silva"); ctdbRecordSetOn(pRec, 5); if (ctdbFirstRecord(pRec) == CTDBRET_OK) { do { count++; PrintRecord(pRec); } while (ctdbNextRecord(pRec) == CTDBRET_OK); } printf("%d records in set\n", count); }
See also
ctdbAllocRecord(), ctdbRecordSetOff(), ctdbFilterRecord()
FairCom Corporation
592
ctdbRemoveTable
Removes any c-treeDB table.
Declaration
CTDBRET ctdbDECL ctdbRemoveTable(CTHANDLE Handle);
Description
The ctdbRemoveTable() function allows any table to be deleted, including tables that are not members of a database. Handle is a table handle. The ctdbRemoveTable() function deletes a c-tree data file and the associated index files from disk. If the table was opened under a database handle, the table is closed and ctdbDeleteTable() is called. If the handle is not active, the table is opened exclusive and then deleted. If the table handle is not active, you must set the path, file extension and password for the handle before calling ctdbRemoveTable().
Return
Value 0 Symbolic Constant CTDBRET_OK Explanation
See "c-treeDB Errors and Return Values" for a complete listing of valid c-treeDB error codes and return values.
Example
/* delete a c-treeDB table */ if (ctdbRemoveTable(MyHandle) != CTDBRET_OK) printf("ctdbRemoveTable Failed!\n");
See also
ctdbDeleteTable()
www.faircom.com
All Rights Reserved
593
ctdbResetAll
Reset all record buffers associated with a table.
Declaration
CTDBRET ctdbResetAll(CTHANDLE Handle)
Description
ctdbResetAll() resets all record buffers associated with a table. Handle [in] the Table Handle.
Returns
ctdbResetAll() returns CTDBRET_OK if successful, or the c-tree Plus error code on failure.
See also
ctdbResetRecord()
FairCom Corporation
594
ctdbResetRecord
Reset the record buffer to its original state
Declaration
CTDBRET ctdbResetRecord(CTHANDLE Handle)
Description
ctdbResetRecord() resets the record buffer to its original state. Handle [in] the record handle.
Returns
ctdbResetRecord() returns CTDBRET_OK if successful, or the c-tree Plus error code on failure.
See also
ctdbResetAll(), ctdbClearRecord()
www.faircom.com
All Rights Reserved
595
ctdbRestoreSavePoint
Restore a transaction save point.
Declaration
CTDBRET ctdbRestoreSavePoint(CTHANDLE Handle, NINT SavePoint)
Description
ctdbRestoreSavePoint() restores a transaction save point. Handle [in] the session handle. SavePoint [in] the save point number returned by ctdbSetSavePoint(). SavePoint can be set to -1 to back up to most current save point, can be set to -2 to back up one more, -3 more....etc. If SavePoint is 0, the most current save point is restored.
Returns
ctdbRestoreSavePoint() returns CTDBRET_OK if successful, or the c-tree Plus error code on failure.
See also
ctdbBegin(), ctdbCommit(), ctdbAbort(), ctdbSetSavePoint()
FairCom Corporation
596
ctdbSeekRecord
Make the record pointed by offset as the current record and read the record.
Declaration
CTDBRET ctdbSeekRecord(CTHANDLE Handle, CTOFFSET offset)
Description
ctdbSeekRecord() makes the record pointed by offset as the current record and read the record. Handle [in] the record handle. offset [in] the record offset.
Returns
ctdbSeekRecord() returns CTDBRET_OK on success, or a c-treeDB C API error code on failure
See also
ctdbSetRecordPos(), ctdbSetRecordOffset(), ctdbGetRecordPos()
www.faircom.com
All Rights Reserved
597
ctdbSetAutoCommit
Declaration
CTDBRET ctdbDECL ctdbSetAutoCommit(CTHANDLE Handle, CTBOOL flag);
Description
ctdbSetAutoCommit() sets the c-treeDB auto commit mode. The auto commit of transactions are invoked automatically when records are added or updated by a ctdbWriteRecord() call. Automatic transactions may increase performance by reducing network traffic for single record updates since this is equivalent of performing the following functions:
ctdbBegin(); if (ctdbWriteRecord() == CTDBRET_OK) ctdbCommit(); else ctdbAbort();
Handle is a session handle. flag indicates if auto commit mode should be enabled or not. The following applies when an automatic transaction is performed: 1. An automatic transaction will only free locks acquired by the ctdbWriteRecord() function. 2. If an automatic transaction is aborted because of errors detected by ctdbWriteRecord(), all locks acquired by ctdbWriteRecord() are released. 3. If locks are active, by calling ctdbLock() function, an automatic transaction will not release any locks when it commits or aborts the ctdbWriteRecord() operation. 4. If OPS_UNLOCK_UPD is on, both commits and aborts on automatic transactions release only locks obtained within trans and/or locks on records updated within transaction, regardless if the c-treeDB session lock state is active or not.
Return Values
Value 0 Symbolic Constant Explanation No Error
CTDBRET_OK
See Also
ctdbGetAutoCommit() ctdbSetOperationState() ctdbGetOperationState()
FairCom Corporation
598
ctdbSetBatch
Performs operations on a group of records.
DECLARATION
CTDBRET ctdbDECL ctdbSetBatch(CTHANDLE Handle, CTBATCH_MODE mode, VRLEN targetLen, VRLEN bufferLen);
DESCRIPTION
ctdbSetBatch() attempts to initiate a specified operation on a group of records with keys matching a partial key value, an index range expression, or the entire table by physical order. Handle parameter must be a record handle associated with an opened table. The mode parameter specifies which batch operation is to take place. You must choose at least one of the mandatory modes. You may or one or more of the optional mode to specify further parameters for the batch operation. Please refer to the description of the modes below. targetLen specifies the number of significant bytes of the partial target key when the batch mode is CTBATCH_GET or CTBATCH_DEL. bufferLen is the size of the buffer used internally by c-treeDB code to handle batch operations. A zero value for this parameter indicates the default value size should be used. The default buffer size is calculated as the size of the fixed portion of the record multiplied by 128. You must specify one of the following Mandatory modes when calling the ctdbSetBatch() function or the CTRecord:SetBatch() method:
MODE Description Retrieve a group of related records by partial key Retrieve a group of related records based on an index range expression Retrieve records from a table in physical order. The starting record for the batch retrieval may be specified. Delete a group of related records by partial key Insert a group of records
The following modes are optional and can be OR-ed to the mandatory mode to specify other details on how the batch operation is to be performed.
Mode Description Process records with a greater than or equal key match with the target key. When this mode is specified, the number of matched records is not readily available. ctdbBatchLocked() and CTRecord::BatchLocked returns a value one greater than ctdbBatchLoaded() to indicate there may be more records to process.This mode is applicable only with CTBATCH_GET and CTBATCH_DEL modes and can not be used with CTBATCH_LKEY. Process records that have a less than or equal key match with the target key.This mode is applicable only with CTBATCH_GET and CTBATCH_DEL modes and can not be used with CTBATCH_GKEY.
CTBATCH_GKEY
CTBATCH_LKEY
www.faircom.com
All Rights Reserved
599
Mode
Description Verify that the keys in the index match the values in the key fields of the record. Keep all records locked after ...EndBatch() is called. Without this mode, all records locks are released when ...EndBatch() is called. This option is only in effect when used with CTBATCH_LOCK_READ or CTBATCH_LOCK_WRITE. Place a read lock on each record that matches the partial key. Place a write lock on each record that matches the partial key. Convert a CTBATCH_LOCK_READ or CTBATCH_LOCK_WRITE to blocking read and blocking write locks, respectively. Implement an alternative locking strategy: only locks the record during the record read; original locking strategy keeps locks on during entire batch processing.
CTBATCH_VERIFY CTBATCH_LOCK_KEEP
CTBATCH_COMPLETE
...SetBatch() returns a success code only if all matching records are successfully locked. You must specify either CTBATCH_LOCK_READ or CTBATCH_LOCK_WRITE.
FairCom Corporation
600
1. Establish an index range by calling the ctdbRecordRangeOn() function or the CTRecord::RangeOn() method. 2. Call the ctdbSetBatch() function or the CTRecord::SetBatch() method with CTBATCH_RANGE mode to start a new record retrieval batch operation. 3. If the ctdbSetBatch() function returns with no errors, continue to call the ctdbNextBatch() function repeatedly until all related records are retrieved. ctdbNextBatch() returns BTMT_ERR (428) to indicate no more records are available. With the c-treeDB C++ API call the CTRecord::NextBatch() method repeatedly until all related records are retrieved. CTRecord::NextBatch() returns false to indicate no more records are available. 4. When you are done with the batch records, call the ctdbEndBatch() function or the CTRecord::EndBatch() method to terminate the batch operation. 5. Call the ctdbRecordRangeOff() function or the CTRecord::RangeOff() method to terminate index range operations.
www.faircom.com
All Rights Reserved
601
RETURNS
Value 0 Symbolic Constant CTDBRET_OK Explanation No error occurred.
See Appendix A for a complete listing of valid c-tree Plus error values.
EXAMPLE
void GetInvoiceItems(CTHANDLE hRecord, NINT Invoice) { NINT count = 0; /* set the partial target key */ ctdbClearRecord(hRecord); ctdbSetFieldAsSigned(hRecord, 0, Invoice); /* set the batch operation */ if (ctdbSetBatch(hRecord, CTBATCH_GET, sizeof(Invoice), 0) == CTDBRET_OK) { /* retrieve records */ while (ctdbNextBatch(hRecord) == CTDBRET_OK) count++; /* terminate batch operations */ ctdbEndBatch(hRecord); } printf("%d records found\n", count); }
FairCom Corporation
602
SEE ALSO
ctdbBatchLoaded(), ctdbBatchLocked(), ctdbBatchMode(), ctdbBatchTotal(), ctdbEndBatch(), ctdbInsertBatch(), ctdbIsBatchActive(), ctdbNextBatch()
www.faircom.com
All Rights Reserved
603
ctdbSetCallback
Establishes a callback function.
Declaration
CTDBRET ctdbSetCallback(CTHANDLE Handle, CTDB_CALLBACK_TYPE CallBackType,ctdbCallbackFunction CallBackFunc);
Description
ctdbSetCallback() establishes a new callback function to receive calls for a given callback type. Handle can be any valid c-treeDB session, database, table or record handle. CallBackType is one of the following callback types from the table below. CallBackFunc is an address to a callback function.
Callback Symbolic Constant Explanation Called after a successful session logon. Called before a session logout. Called after a successful database connect. Called a database disconnect. Called after c-tree ISAM table open, but before any other table callbacks. This callback can be used to indicate that the table is open and ready for operations. Called before the table is closed. Called after the table open code loads the DODA. This callback can be used to change the contents of the DODA before the c-treeDB field handles are created based on the DODA information and the index and index segment handles are created based on the IFIL information. Called after the table open code load the schema information. This callback can be used to modify the contents of the schema information before the c-treeDB field handles are created based on the DODA information and the index and index segment handles are created based on the IFIL information. Called during the table open operation to allow the customization of c-treeDBs extended field information. Called during the table open operation to allow the customization of the length of the fixed portion of the record. Called during a c-treeDB alter table operation to allow the indication if alter table operations are allowed or not for a particular table. Called during an alter table full rebuild loop to indicate a percentage progress of the rebuild process. Called to indicate that a record handle is about to become active or an alter table was performed and the record need to be re-initialized.
CTDB_ON_TABLE_CLOSE CTDB_ON_TABLE_GET_DODA
CTDB_ON_TABLE_GET_SCHEMA
CTDB_ON_TABLE_REBUILD CTDB_ON_RECORD_INIT
FairCom Corporation
604
Explanation Called to indicate that the record handle is about to become inactive. The record handle is being released or the table is closing. Called before a record read operation. Called after a record read operation. Called before c-tree Plus BuildKey function is called.
CTDB_ON_RECORD_RESET
Called before a record write or record update. Called after a record write or record update.
You need to register your callback functions before they are invoked by c-treeDB. A callback function is registered by calling the ctdbSetCallback() function and passing the appropriate c-treeDB handle, the callback function type and the address of a function to receive the callback calls. You can register any of the defined callback functions using the session handle and every time a database, table or record handle is allocated, they will automatically inherit their callbacks from the session handle. Conversely if you register callbacks using a database handle, every time a table or a record handle is allocated they will automatically inherit their callbacks from the database handle. Record handles will also inherit any callbacks registered with the table handle.
Return
Value 0 Symbolic Constant CTDBRET_OK Explanation No error occurred.
See Appendix A for a complete listing of valid c-tree Plus error values.
Example
/* allocate a new session handle */ CTHANDLE hSession = ctdbAllocSession(CTSESSION_CTREE); /* set table open callback */ if (ctdbSetCallback(hSession, CTDB_ON_TABLE_OPEN, OnTableOpen) != CTDBRET_OK) printf("ctdbSetCallback failed\n");
See Also
ctdbClearAllCallback(), ctdbClearCallback(), ctdbGetCallback()
www.faircom.com
All Rights Reserved
605
ctdbSetCurrentNodeName
Set the client-side node name.
Declaration
CTDBRET ctdbSetCurrentNodeName(CTHANDLE Handle, pTEXT NodeName);
Description
When monitoring c-tree Server attached users, well written c-treeDB client applications should register their workstation (node) name using the standard c-tree SETNODE() (SetNodeName() ) function call. ctdbSetCurrentNodeName() set a client-side node name. Handle is a session handle and NodeName is an string specifying the node name. The specified node name appears in the ctadmn utility under the option for list clients. ctdbSetCurrentNodeName() must be called after a successful logon. This functionality is available only with the c-tree Server. A call to ctdbSetCurrentNodeName() on non-server environment will always return CTDBRET_OK and the node name is ignored.
Return
Value 0 Symbolic Constant CTDBRET_OK Explanation
See "c-treeDB Errors and Return Values" for a complete listing of valid c-treeDB error codes and return values.
Example
/* set the c-tree Server node name for this workstation */ if (ctdbSetCurrentNodeName(AnyHandle, "This is my node") != CTDBRET_OK) printf("ctdbSetCurrrentNodeName() failed\n");
See also
ctdbSetDefaultIndex(), ctdbBuildTargetKey()
FairCom Corporation
606
ctdbSetDatabaseExclusive
Sets or clears the database exclusive flag.
Declaration
CTDBRET ctdbSetDatabaseExclusive(CTHANDLE Handle, CTBOOL flag);
Description
ctdbSetDatabaseExclusive() sets or clears the database exclusive flag. If a database exclusive flag is set, only one connection will be allowed on this database. Set the database exclusive flag after allocating the database handle, and before performing a connect. Setting the database exclusive flag after a database is connected will not have any effect during the current connection. Handle is a database handle and flag will set or clear the database exclusive flag.
Return
Value 0 Symbolic Constant CTDBRET_OK Explanation No error occurred.
See Appendix A for a complete listing of valid c-tree Plus error values.
Example
/* perform an exclusive logon and connect */ CTHANDLE hSession = ctdbAllocSession(CTSESSION_CTDB); CTHANDLE hDatabase = ctdbAllocDatabase(hSession); if (hSession) { ctdbSetSessionExclusive(hSession, YES); if (ctdbLogon(hSession, "FAIRCOM", "ADMIN", "ADMIN") != CTDBRET_OK) printf("ctdbLogon failed\n"); else { ctdbSetDatabaseExclusive(hDatabase, YES); if (ctdbConnect(hDatabase, "MyData") != CTDBRET_OK) printf("ctdbConnect failed\n"); } } ctdbFreeDatabase(hDatabase); ctdbFreeSession(hSession);
See Also
ctdbSetSessionExclusive(), ctdbIsSessionExclusive(), ctdbIsDatabaseExclusive()
www.faircom.com
All Rights Reserved
607
ctdbSetDefaultIndex
Set the number of the new default index.
Declaration
CTDBRET ctdbSetDefaultIndex(CTHANDLE Handle, NINT indexno)
Description
ctdbSetDefaultIndex() sets the number of the new default index. Use ctdbGetDefaultIndex() to retrieve the table default index. Initially, the default index is the first index created during the table definition. If not disabled during the table creation, two default indices are created during the table definition, besides the indices defined by the user. These indices may be used to sort the table, and they are: ROWID - this unique index represents the ordering of the table by input order. To set this index as the default, the Index parameter should be set to CTDB_ROWID_IDXNO; RECBYT - this index represents the offset of the record inside the table. It is used internally to improve space management, and may be used to sort the table by physical order. To set this index as the default, the Index parameter should be set to CTDB_RECBYT_IDXNO. See the discussion on "Hidden fields") regarding these two indices. Use ctdbSetDefaultIndexByName() to set the table default index by name. Handle [in] the record handle. Index [in] the index number to be set as default.
Returns
ctdbSetDefaultIndex() returns CTDBRET_OK on success, or c-treeDB C API error code on failure.
See also
ctdbAllocRecord(), ctdbSetTableDefaultIndexExtentSize(), ctdbGetDefaultIndex(), ctdbSetDefaultIndexByName()
FairCom Corporation
608
ctdbSetDefaultIndexByName
Set the default index by its name
Declaration
CTDBRET ctdbSetDefaultIndexByName(CTHANDLE Handle, pTEXT name)
Description
ctdbSetDefaultIndexByName() sets the default index by its name. See the discussion on the default index presented in the ctdbSetDefaultIndex() function. Use ctdbGetDefaultIndexName() to retrieve the table default index name. Use ctdbSetDefaultIndex() to set the table default index by number. Handle [in] the record handle. name [in] the index name to be set as default.
Returns
ctdbSetDefaultIndexByName() returns CTDBRET_OK on success, or c-treeDB C API error code on failure.
See also
ctdbAllocRecord(), ctdbGetDefaultIndexName(), ctdbSetDefaultIndex()
www.faircom.com
All Rights Reserved
609
ctdbSetDefDateType
Set the default date type.
Declaration
CTDBRET ctdbSetDefDateType(CTHANDLE Handle, CTDATE_TYPE DateType)
Description
ctdbSetDefDateType() sets the default date type for the present session. Initially, the default is CTDATE_MDCY, indicating month, day, century, year (4 digits for the year). The possible date types are given in "c-treeDB definitions".. Use ctdbGetDefDateType() to retrieve the default date type. Handle [in] any c-treeDB Handle. DateType [in] a valid date type. Valid types are listed in "c-treeDB definitions"..
Returns
ctdbSetDefDateType() returns CTDBRET_OK on success, or c-treeDB C API error code on failure.
See also
ctdbGetDefDateType()
FairCom Corporation
610
ctdbSetDefFloatFormat
Set the default floating point format string
Declaration
CTDBRET ctdbSetDefFloatFormat(CTHANDLE Handle, pTEXT format)
Description
ctdbSetDefFloatFormat() sets the default floating point format string. Handle [in] any c-treeDB Handle. format [in] the string format to be used by sprintf() or sscanf().
Returns
ctdbSetDefFloatFormat() returns CTDBRET_OK on success, or c-treeDB C API error on failure.
See also
ctdbGetDefFloatFormat()
www.faircom.com
All Rights Reserved
611
ctdbSetDefTimeType
Set the default time type.
Declaration
CTDBRET ctdbSetDefTimeType(CTHANDLE Handle, CTTIME_TYPE TimeType)
Description
ctdbSetDefTimeType() sets the default time type for the present session. Initially, the default is CTTIME_HMP, indicating hour, minute and am/pm. The possible time types are given in "c-treeDB definitions".. Use ctdbGetDefTimeType() to retrieve the default time type. Handle [in] any c-treeDB Handle. TimeType [in] a valid time type. Valid types are listed in "c-treeDB definitions"..
Returns
ctdbSetDefTimeType() returns CTDBRET_OK on success, or c-treeDB C API error on failure.
See also
ctdbGetDefTimeType()
FairCom Corporation
612
ctdbSetEditedRecord
Set the record changed flag.
Declaration
CTDBRET ctdbSetNewRecord(CTHANDLE Handle, CTBOOL flag)
Description
ctdbSetEditedRecord() sets the the record changed flag. Handle [in] the Session Handle. flag [in] record changed flag value.
Returns
ctdbSetEditedRecord() returns CTDBRET_OK on success, or c-treeDB C API error on failure.
See also
ctdbSetNewRecord()
www.faircom.com
All Rights Reserved
613
ctdbSetError
Set the error code.
Declaration
CTDBRET ctdbSetError(CTHANDLE Handle, CTDBRET ErrorCode)
Description
ctdbSetError() sets the error code. Handle should be any Handle inside the Session (session handle, database handle, table handle, record handle, index handle, field handle, or segment handle). ErrorCode should be any valid c-treeDB C API error code.
Returns
ctdbSetError() returns CTDBRET_OK if successful, or NULL on failure.
See also
ctdbGetError(), ctdbClearError()
FairCom Corporation
614
ctdbSetFieldAsBigint
Set field as big integer value.
Declaration
CTDBRET ctdbSetFieldAsBigint(CTHANDLE Handle, NINT FieldNbr, CTBIGINT Value)
Description
ctdbSetFieldAsBigint() sets a field as big integer. Use ctdbGetFieldAsBigint() to retrieve field as a big integer value. Handle [in] the record handle. FieldNbr [in] the field number to be set. To retrieve the field number given the field name, use ctdbGetFieldNumberByName(). Value [in] the big integer value to set to the field.
Returns
ctdbSetFieldAsBigint() returns CTDBRET_OK if successful, or the c-tree Plus error code on failure.
See also
ctdbAllocRecord(), ctdbSetFieldAsBool(), ctdbSetFieldAsSigned(), ctdbSetFieldAsUnsigned(), ctdbSetFieldAsDate(), ctdbSetFieldAsTime(), ctdbSetFieldAsMoney(), ctdbSetFieldAsFloat(), ctdbSetFieldAsDateTime(), ctdbSetFieldAsString(), ctdbGetFieldAsBigint(), ctdbGetFieldNumberByName()
www.faircom.com
All Rights Reserved
615
ctdbSetFieldAsBinary
Set field as binary value.
Declaration
CTDBRET ctdbSetFieldAsBinary(CTHANDLE Handle, NINT FieldNbr, pVOID pValue, VRLEN size)
Description
ctdbSetFieldAsBinary() sets a field as binary. Use ctdbGetFieldAsBinary() to retrieve field as a binary value. Handle [in] the record handle. FieldNbr [in] the field number to be set. To retrieve the field number given the field name, use ctdbGetFieldNumberByName(). pValue [in] the pointer to the binary value to set to the field. size [in] pValue size in bytes.
Returns
ctdbSetFieldAsBinary() returns CTDBRET_OK if successful, or the c-tree Plus error code on failure.
See also
ctdbAllocRecord(), ctdbSetFieldAsBool(), ctdbSetFieldAsSigned(), ctdbSetFieldAsUnsigned(), ctdbSetFieldAsDate(), ctdbSetFieldAsTime(), ctdbSetFieldAsMoney(), ctdbSetFieldAsFloat(), ctdbSetFieldAsDateTime(), ctdbSetFieldAsString(), ctdbGetFieldAsBinary(), ctdbGetFieldNumberByName()
FairCom Corporation
616
ctdbSetFieldAsBlob
Set field as CTBLOB type value.
Declaration
CTDBRET ctdbSetFieldAsBlob(CTHANDLE Handle, NINT FieldNbr, pCTBLOB pValue)
Description
ctdbSetFieldAsBlob() sets a field as CTBLOB type value. Use ctdbGetFieldAsBlob() to retrieve field as CTBLOB. Handle [in] the record handle. FieldNbr [in] the field number to be set. To retrieve the field number given the field name, use ctdbGetFieldNumberByName(). pValue [in] the pointer to the CTBLOB value to set to the field.
Returns
ctdbSetFieldAsBlob() returns CTDBRET_OK if successful, or the c-tree Plus error code on failure.
See also
ctdbAllocRecord(), ctdbSetFieldAsBool(), ctdbSetFieldAsSigned(), ctdbSetFieldAsUnsigned(), ctdbSetFieldAsDate(), ctdbSetFieldAsTime(), ctdbSetFieldAsMoney(), ctdbSetFieldAsFloat(), ctdbSetFieldAsDateTime(), ctdbSetFieldAsString(), ctdbGetFieldAsBlob()
www.faircom.com
All Rights Reserved
617
ctdbSetFieldAsBool
Set field as CTBOOL type value.
Declaration
CTDBRET ctdbSetFieldAsBool(CTHANDLE Handle, NINT FieldNbr, CTBOOL Value)
Description
ctdbSetFieldAsBool() sets a field as CTBOOL type value. Use ctdbGetFieldAsBool() to retrieve field as CTBOOL. Handle [in] the record handle. FieldNbr [in] the field number to be set. To retrieve the field number given the field name, use ctdbGetFieldNumberByName(). Value [in] the CTBOOL value to set to the field.
Returns
ctdbSetFieldAsBool() returns CTDBRET_OK if successful, or the c-tree Plus error code on failure.
See also
ctdbAllocRecord(), ctdbSetFieldAsSigned(), ctdbSetFieldAsUnsigned(), ctdbSetFieldAsDate(), ctdbSetFieldAsTime(), ctdbSetFieldAsMoney(), ctdbSetFieldAsFloat(), ctdbSetFieldAsDateTime(), ctdbSetFieldAsString(), ctdbGetFieldAsBool(), ctdbGetFieldNumber()
FairCom Corporation
618
ctdbSetFieldAsCurrency
Set field as a currency value.
Declaration
CTDBRET ctdbSetFieldAsCurrency(CTHANDLE Handle, NINT FieldNbr, CTCURRENCY Value)
Description
ctdbSetFieldAsCurrency() sets a field as currency value. Use ctdbGetFieldAsCurrency() to retrieve field as a currency value. Handle [in] the record handle. FieldNbr [in] the field number to be set. To retrieve the field number given the field name, use ctdbGetFieldNumberByName(). Value [in] the pointer to the currency value.
Returns
ctdbSetFieldAsCurrency() returns CTDBRET_OK if successful, or the c-tree Plus error code on failure.
See also
ctdbAllocRecord(), ctdbSetFieldAsBool(), ctdbSetFieldAsSigned(), ctdbSetFieldAsUnsigned(), ctdbSetFieldAsTime(), ctdbSetFieldAsMoney(), ctdbSetFieldAsFloat(), ctdbSetFieldAsDateTime(), ctdbSetFieldAsString(), ctdbSetFieldAsBlob(), ctdbGetFieldNumberByName(), ctdbGetFieldAsCurrency()
www.faircom.com
All Rights Reserved
619
ctdbSetFieldAsDate
Set field as CTDATE type value.
Declaration
CTDBRET ctdbSetFieldAsDate(CTHANDLE Handle, NINT FieldNbr, CTDATE Value)
Description
ctdbSetFieldAsDate() sets a field as CTDATE type value. Use ctdbGetFieldAsDate() to retrieve field as CTDATE. Handle [in] the record handle. FieldNbr [in] the field number to be set. To retrieve the field number given the field name, use ctdbGetFieldNumberByName(). Value [in] the CTDATE value to set to the field.
Returns
ctdbSetFieldAsDate() returns CTDBRET_OK if successful, or the c-tree Plus error code on failure.
See also
ctdbAllocRecord(), ctdbSetFieldAsBool(), ctdbSetFieldAsSigned(), ctdbSetFieldAsUnsigned(), ctdbSetFieldAsTime(), ctdbSetFieldAsMoney(), ctdbSetFieldAsFloat(), ctdbSetFieldAsDateTime(), ctdbSetFieldAsString(), ctdbSetFieldAsBlob(), ctdbGetFieldAsDate(), ctdbGetFieldNumberByName()
FairCom Corporation
620
ctdbSetFieldAsDateTime
Set field as CTDATETIME type value.
Declaration
CTDBRET ctdbSetFieldAsDateTime(CTHANDLE Handle, NINT FieldNbr, CTDATETIME value)
Description
ctdbSetFieldAsDateTime() sets a field as CTDATETIME type value. Use ctdbGetFieldAsDateTime() to retrieve field as CTDATETIME. Handle [in] the record handle. FieldNbr [in] the field number to be set. To retrieve the field number given the field name, use ctdbGetFieldNumberByName(). Value [in] the CTDATETIME value to set to the field.
Returns
ctdbSetFieldAsDateTime() returns CTDBRET_OK if successful, or the c-tree Plus error code on failure.
See also
ctdbAllocRecord(), ctdbSetFieldAsBool(), ctdbSetFieldAsSigned(), ctdbSetFieldAsUnsigned(), ctdbSetFieldAsDate(), ctdbSetFieldAsTime(), ctdbSetFieldAsMoney(), ctdbSetFieldAsFloat(), ctdbSetFieldAsString(), ctdbSetFieldAsBlob(), ctdbGetFieldAsDateTime(), ctdbGetFieldNumber()
www.faircom.com
All Rights Reserved
621
ctdbSetFieldAsFloat
Set field as CTFLOAT type value.
Declaration
CTDBRET ctdbSetFieldAsFloat(CTHANDLE Handle, NINT FieldNbr, CTFLOAT Value)
Description
ctdbSetFieldAsFloat() sets a field as CTFLOAT type value. Use ctdbGetFieldAsFloat() to retrieve field as CTFLOAT. Handle [in] the record handle. FieldNbr [in] the field number to be set. To retrieve the field number given the field name, use ctdbGetFieldNumberByName(). Value [in] the CTFLOAT value to set to the field.
Returns
ctdbSetFieldAsFloat returns CTDBRET_OK if successful, or the c-tree Plus error code on failure.
See also
ctdbAllocRecord(), ctdbSetFieldAsBool(), ctdbSetFieldAsSigned(), ctdbSetFieldAsUnsigned(), ctdbSetFieldAsDate(), ctdbSetFieldAsTime(), ctdbSetFieldAsMoney(), ctdbSetFieldAsDateTime(), ctdbSetFieldAsString(), ctdbSetFieldAsBlob(), ctdbGetFieldAsFloat(), ctdbGetFieldNumber()
FairCom Corporation
622
ctdbSetFieldAsMoney
Set field as CTMONEY type value.
Declaration
CTDBRET ctdbSetFieldAsMoney(CTHANDLE Handle, NINT FieldNbr, CTMONEY Value)
Description
ctdbSetFieldAsMoney() sets a field as CTMONEY type value. Use ctdbGetFieldAsMoney() to retrieve field as CTMONEY. Handle [in] the record handle. FieldNbr [in] the field number to be set. To retrieve the field number given the field name, use ctdbGetFieldNumberByName(). Value [in] the CTMONEY value to set to the field.
Returns
ctdbSetFieldAsMoney() returns CTDBRET_OK if successful, or the c-tree Plus error code on failure.
See also
ctdbAllocRecord(), ctdbSetFieldAsBool(), ctdbSetFieldAsSigned(), ctdbSetFieldAsUnsigned(), ctdbSetFieldAsDate(), ctdbSetFieldAsTime(), ctdbSetFieldAsFloat(), ctdbSetFieldAsDateTime(), ctdbSetFieldAsString(), ctdbSetFieldAsBlob(), ctdbGetFieldAsMoney(), ctdbGetFieldNumber()
www.faircom.com
All Rights Reserved
623
ctdbSetFieldAsNumber
Set field as a number value.
Declaration
CTDBRET ctdbSetFieldAsNumber(CTHANDLE Handle, NINT FieldNbr, pCTNUMBER pValue)
Description
ctdbSetFieldAsNumber() set field as number. Use ctdbGetFieldAsNumber() to retrieve field as a number value. Handle [in] the record handle. FieldNbr [in] the field number to be set. To retrieve the field number given the field name, use ctdbGetFieldNumberByName(). pValue [in] the pointer to the number value to set to the field.
Returns
ctdbSetFieldAsNumber() returns CTDBRET_OK if successful, or the c-tree Plus error code on failure.
See also
ctdbAllocRecord(), ctdbSetFieldAsBool(), ctdbSetFieldAsSigned(), ctdbSetFieldAsUnsigned(), ctdbSetFieldAsDate(), ctdbSetFieldAsTime(), ctdbSetFieldAsFloat(), ctdbSetFieldAsDateTime(), ctdbSetFieldAsString(), ctdbSetFieldAsBlob(), ctdbGetFieldAsNumber()
FairCom Corporation
624
ctdbSetFieldAsSigned
Set field as CTSIGNED type value.
Declaration
CTDBRET ctdbSetFieldAsSigned(CTHANDLE Handle, NINT FieldNbr, CTSIGNED Value)
Description
ctdbSetFieldAsSigned() sets a field as CTSIGNED type value. Use ctdbGetFieldAsSigned() to retrieve field as CTSIGNED. Handle [in] the record handle. FieldNbr [in] the field number to be set. To retrieve the field number given the field name, use ctdbGetFieldNumberByName(). Value [in] the CTSIGNED value to set to the field.
Returns
ctdbSetFieldAsSigned() returns CTDBRET_OK if successful, or the c-tree Plus error code on failure.
See also
ctdbAllocRecord(), ctdbSetFieldAsBool(), ctdbSetFieldAsUnsigned(), ctdbSetFieldAsDate(), ctdbSetFieldAsTime(), ctdbSetFieldAsMoney(), ctdbSetFieldAsFloat(), ctdbSetFieldAsDateTime(), ctdbSetFieldAsString(), ctdbSetFieldAsBlob(), ctdbGetFieldAsSigned(), ctdbGetFieldNumber()
www.faircom.com
All Rights Reserved
625
ctdbSetFieldAsString
Set field as CTSTRING type value.
Declaration
CTDBRET ctdbSetFieldAsString(CTHANDLE Handle, NINT FieldNbr, CTSTRING Value)
Description
ctdbSetFieldAsString() sets a field as CTSTRING type value. To set a CT_BOOL field, the value being set must be equal to TRUE or FALSE, case insensitive, otherwise, the function will return CTDBRET_CANTCONVERT (4042). Use ctdbGetFieldAsString() to retrieve field as CTSTRING. Handle [in] the record handle. FieldNbr [in] the field number to be set. To retrieve the field number given the field name, use ctdbGetFieldNumberByName(). Value [in] the CTSTRING value to set to the field.
Returns
ctdbSetFieldAsString() returns CTDBRET_OK if successful, or the c-tree Plus error code on failure. Error CTDBRET_CANTCONVERT (4042) indicate Value can't be converted to the specified field type.
See also
ctdbAllocRecord(), ctdbSetFieldAsBool(), ctdbSetFieldAsSigned(), ctdbSetFieldAsUnsigned(), ctdbSetFieldAsDate(), ctdbSetFieldAsTime(), ctdbSetFieldAsMoney(), ctdbSetFieldAsFloat(), ctdbSetFieldAsDateTime(), ctdbSetFieldAsBlob(), ctdbGetFieldAsString(), ctdbGetFieldNumber()
FairCom Corporation
626
ctdbSetFieldAsTime
Set field as CTTIME type value.
Declaration
CTDBRET ctdbSetFieldAsTime(CTHANDLE Handle, NINT FieldNbr, CTTIME Value)
Description
ctdbSetFieldAsTime() sets a field as CTTIME type value. Use ctdbGetFieldAsTime() to retrieve field as CTTIME. The default time format to set a time field is CTTIME_HMP (HH:MM am/pm). To modify it, use ctdbSetDefTimeType(). Handle [in] the record handle. FieldNbr [in] the field number to be set. To retrieve the field number given the field name, use ctdbGetFieldNumberByName(). Value [in] the CTTIME value to set to the field.
Returns
ctdbSetFieldAsTime() returns CTDBRET_OK if successful, or the c-tree Plus error code on failure.
See also
ctdbAllocRecord(), ctdbSetFieldAsBool(), ctdbSetFieldAsSigned(), ctdbSetFieldAsUnsigned(), ctdbSetFieldAsDate(), ctdbSetFieldAsMoney(), ctdbSetFieldAsFloat(), ctdbSetFieldAsDateTime(), ctdbSetFieldAsString(), ctdbSetFieldAsBlob(), ctdbGetFieldAsTime(), ctdbGetFieldNumber(), ctdbSetDefTimeType()
www.faircom.com
All Rights Reserved
627
ctdbSetFieldAsUnsigned
Set field as CTUNSIGNED type value.
Declaration
CTDBRET ctdbSetFieldAsUnsigned(CTHANDLE Handle, NINT FieldNbr, CTUNSIGNED Value)
Description
ctdbSetFieldAsUnsigned() sets a field as CTUNSIGNED type value. Use ctdbGetFieldAsUnsigned() to retrieve field as CTUNSIGNED. Handle [in] the record handle. FieldNbr [in] the field number to be set. To retrieve the field number given the field name, use ctdbGetFieldNumberByName(). Value [in] the CTUNSIGNED value to set to the field.
Returns
ctdbSetFieldAsUnsigned() returns CTDBRET_OK if successful, or the c-tree Plus error code on failure.
See also
ctdbAllocRecord(), ctdbSetFieldAsBool(), ctdbSetFieldAsSigned(), ctdbSetFieldAsDate(), ctdbSetFieldAsTime(), ctdbSetFieldAsMoney(), ctdbSetFieldAsFloat(), ctdbSetFieldAsDateTime(), ctdbSetFieldAsString(), ctdbSetFieldAsBlob(), ctdbGetFieldAsUnsigned(), ctdbGetFieldNumber()
FairCom Corporation
628
ctdbSetFieldAsUTF16
Sets the field with a Unicode UTF-16 string.
DECLARATION
CTDBRET ctdbSetFieldAsUTF16(CTHANDLE Handle, NINT FieldNbr, pWCHAR pValue);
DESCRIPTION
ctdbSetFieldAsUTF16() sets the field with a UNICODE UTF-16 string. If the underlying field type is not one of the UNICODE field types, the UTF-16 string is converted to the appropriate type before the data is stores in the field. Handle is a record handle. FieldNbr is the field number. pValue is the wide (UTF-16) string buffer.
RETURN
Value 0 Symbolic Constant CTDBRET_OK Explanation No error occurred.
See Appendix A for a complete listing of valid c-tree Plus error values.
EXAMPLE
CTDBRET AddData(CTHANDLE hRecord, pTEXT str, NINT val) { CTDBRET eRet; WCHAR WStr[32]; if ((eRet = ctdbClearRecord(hRecord)) != CTDBRET_OK) { printf("ctdbClearRecord failed with error %d", eRet); goto Exit; } if ((eRet = (CTDBRET)ctdb_u8TOu16(str, WStr, sizeof(WStr))) != CTDBRET_OK) { printf("ctdb_u8TOu16 failed with error %d", eRet); goto Exit; } if ((eRet = ctdbSetFieldAsUTF16(hRecord, 0, WStr)) != CTDBRET_OK) { printf("ctdbSetFieldAsUTF16 failed with error %d", eRet); goto Exit; } if ((eRet = ctdbSetFieldAsSigned(hRecord, 1, (CTSIGNED)val)) != CTDBRET_OK) { printf("ctdbSetFieldAsSigned failed with error %d", eRet); goto Exit; } if ((eRet = ctdbWriteRecord(hRecord)) != CTDBRET_OK) { printf("ctdbWriteRecord failed with error %d", eRet); goto Exit; } Exit: return eRet; }
www.faircom.com
All Rights Reserved
629
SEE ALSO
ctdbGetFieldAsUTF16()
FairCom Corporation
630
ctdbSetFieldDefaultDateTimeType
Sets the default field value date and time type.
DECLARATION
CTDBRET ctdbSetFieldDefaultDateTimeType(CTHANDLE Handle, CTDATE_TYPE dateType, CTTIME_TYPE timeType);
DESCRIPTION
Sets the default field value date and time type to be used when converting CT_DATE, CT_TIME and CT_TIMES string values. By default the date type is CTDATE_MDCY and the time type is CTTIME_HMS. Use this function to modify the default values. ctdbSetFieldDefaultDateTimeType() modifies both the date and time types. If you wish to change only the default date time, but keep the current time type, use the following example:
ctdbSetFieldDefaultDateTimeType(hField, CTDATE_YMD, ctdbGetFieldDefaultTimeType(hField));
You can use the same approach to change only the time type, keeping the current date type:
ctdbSetFieldDefaultDateTimeType(hField,ctdbGetFieldDefaultDateType(hField), CTIME_HMP);
Handle must be a field handle. dateType is a date type format to be used for converting values between dates and strings. The possible values are:
Value 1 2 3 4 5 6 Symbolic Constant Explanation Date format is mm/dd/ccyy Date format is mm/dd/yy Date format is dd/mm/ccyy Date format is dd/mm/yy Date format is ccyymmdd Date format is yymmdd
timeType is the time type to be used for converting values between time and strings. The possible values are:
Value 1 2 3 4 5 Symbolic Constant Explanation Time format is hh:mm:ss am|pm Time format is hh:mm am|pm Time format is hh:mm:ss (24 hour) Time format is hh:mm (24 hour) Time format is hhmm (military)
RETURN
Value 0 Symbolic Constant CTDBRET_OK Explanation No error occurred.
See Appendix A for a complete listing of valid c-tree Plus error values.
www.faircom.com
All Rights Reserved
631
EXAMPLE
/* set the field default date and time types */ hField = ctdbGetField(hTable, 5); if (hField) if (ctdbSetFieldDefaultDateTimeType(hField, CTDATE_DMY, CTIME_HMP)) printf("ctdbSetFieldDefaultDateTimeType failed\n");
SEE ALSO
ctdbSetFieldDefaultValue(), ctdbGetFieldDefaultValue(), ctdbClearFieldDefaultValue(), ctdbIsFieldDefaultValueSet(), ctdbClearAllFieldDefaultValue(), ctdbGetFieldDefaultDateType(), ctdbGetFieldDefaultTimeType()
FairCom Corporation
632
ctdbSetFieldDefaultValue
Sets the field default value.
DECLARATION
CTDBRET ctdbSetFieldDefaultValue(CTHANDLE Handle, pTEXT value, VRLEN length)
DESCRIPTION
The default value of a field is used during an alter table operation when a full table rebuild is performed. During a full alter table rebuild, and after the old record buffer data is moved to the new record buffer, the new record buffer is scanned and if a NULL field is found and that NULL field has a default value, the default value is copied to the field buffer. The field default value is kept as a string representation of the data. It is recommended that numeric data should be converted to string using one of the rich set of c-treeDB data conversion functions. Date values should be converted to string using the default date type value. The default date type value can be retrieved by calling ctdbGetFieldDefaultDateType() function. By default, the date type is CTDATE_MDCY. Time values should be converted to string using the default time type value. The default time type value can be retrieved by calling ctdbGetFieldDefaultTimeType() function. By default, the time type is CTTIME_HMS. Time stamp values should be converted to string using the default date type and time type values as described above. Handle must be a c-treeDB field handle. value is a string with the default value. No checks are made to ensure the default value matches the correct field type. The caller is responsible for passing the appropriate value. length correspond to the length of value parameter. You must pass a proper length of the string.
RETURN
Value 0 Symbolic Constant CTDBRET_OK Explanation No error occurred.
See Appendix A for a complete listing of valid c-tree Plus error values.
EXAMPLE
/* set the default value for country - field #5 */ hField = ctdbGetField(hTable, 5); if (hField) if (ctdbSetFieldDefaultValue(hField, "USA", 3) != CTDBRET_OK) printf("ctdbSetFieldDefaultValue failed\n");
SEE ALSO
ctdbGetFieldDefaultValue(), ctdbClearFieldDefaultValue(), ctdbIsFieldDefaultValueSet(), ctdbClearAllFieldDefaultValue(), ctdbSetFieldDefaultDateTimeType(), ctdbGetFieldDefaultDateType(), ctdbGetFieldDefaultTimeType()
www.faircom.com
All Rights Reserved
633
ctdbSetFieldLength
Set the field length
Declaration
VRLEN ctdbSetFieldLength(CTHANDLE Handle, VRLEN len)
Description
ctdbSetFieldLength() sets the field length. Use ctdbGetFieldLength() to retrieve the field length. Handle [in] the Field Handle. len [in] the field length.
Returns
ctdbSetFieldLength() returns CTDBRET_OK on success, or a c-treeDB C API error code on failure.
See also
ctdbGetFieldLength()
FairCom Corporation
634
ctdbSetFieldName
Change the field name
Declaration
CTDBRET ctdbSetFieldName(CTHANDLE Handle, pTEXT name)
Description
ctdbSetFieldName() changes the field name. Use ctdbGetFieldName() to retrieve the field name. Handle [in] the Field Handle. name [in] the new field name.
Returns
ctdbSetFieldName() returns CTDBRET_OK on success, or a c-treeDB C API error code on failure.
See also
ctdbGetFieldName()
www.faircom.com
All Rights Reserved
635
ctdbSetFieldNullFlag
Set the field null flag.
Declaration
CTDBRET ctdbSetFieldNullFlag(CTHANDLE Handle, CTBOOL flag)
Description
ctdbSetFieldNullFlag() sets the field null flag. Handle [in] the Field Handle. flag [in] the null flag value.
Returns
ctdbSetFieldNullFlag() returns CTDBRET_OK on success, or a c-treeDB C API error code on failure.
See also
ctdbGetFieldNullFlag()
FairCom Corporation
636
ctdbSetFieldPrecision
Set the field precision.
Declaration
CTDBRET ctdbSetFieldPrecision(CTHANDLE Handle, NINT fprec)
Description
ctdbSetFieldPrecision() sets the field precision (maximum number of digits). Handle [in] the Field Handle. fprec [in] the field precision.
Returns
ctdbSetFieldPrecision() returns CTDBRET_OK on success, or a c-treeDB C API error code on failure.
See also
ctdbGetFieldPrecision()
www.faircom.com
All Rights Reserved
637
ctdbSetFieldProperties
Set field properties such as name, type and length.
Declaration
CTDBRET ctdbSetFieldProperties(CTHANDLE Handle, pTEXT FieldName, CTDBTYPE Type, VRLEN Length)
Description
ctdbSetFieldProperties() sets field properties such as name, type and length. Use ctdbGetFieldProperties() to retrieve the field properties. Handle [in] the Field Handle. FieldName [in] the field name. Type [in] the field type. Length [in] the field length.
Returns
ctdbSetFieldProperties() returns CTDBRET_OK on success, or a c-treeDB C API error code on failure.
See also
ctdbAllocTable(), ctdbGetFieldProperties()
FairCom Corporation
638
ctdbSetFieldScale
Set the field scale.
Declaration
CTDBRET ctdbSetFieldScale(CTHANDLE Handle, NINT fscale)
Description
ctdbSetFieldScale() sets the field scale (the number of digits to the right of the decimal point). Handle [in] the Field Handle. scale [in] the field scale.
Returns
ctdbSetFieldScale() returns CTDBRET_OK on success, or a c-treeDB C API error code on failure.
See also
ctdbGetFieldScale()
www.faircom.com
All Rights Reserved
639
ctdbSetFieldType
Sets the field type
Declaration
CTDBTYPE ctdbSetFieldType(CTHANDLE Handle)
Description
ctdbSetFieldType() sets the field type. Use ctdbGetFieldType() to retrieve the field type. Handle [in] the Field Handle.
Returns
ctdbSetFieldType() returns CTDBRET_OK on success, or a c-treeDB C API error code on failure.
See also
ctdbGetFieldType()
FairCom Corporation
640
ctdbSetIndexDuplicateFlag
Set the allow duplicate flag for this index.
Declaration
CTDBRET ctdbSetIndexDuplicateFlag(CTHANDLE Handle, CTBOOL DupFlag)
Description
ctdbSetIndexDuplicateFlag() sets the allow duplicate key flag for this index. Use ctdbGetIndexDuplicateFlag() to retrieve the allow duplicate key flag for the desired index. Handle [in] the index handle. DupFlag [in] the flag to indicate if duplicates are allowed.
Returns
ctdbSetIndexDuplicateFlag() returns CTDBRET_OK on success, or a c-treeDB C API error code on failure.
See also
ctdbAllocIndex(), ctdbGetIndexDuplicateFlag()
www.faircom.com
All Rights Reserved
641
ctdbSetIndexEmptyChar
Set the empty char property for the index
Declaration
CTDBRET ctdbSetIndexEmptyChar(CTHANDLE Handle, NINT EmptyChar)
Description
ctdbSetIndexEmptyChar() sets the empty char property for this index. Use ctdbGetIndexEmptyChar() to retrieve the empty char property for this index. The empty char property is expressed as the decimal equivalent of the ASCII table. For instance, an ASCII space is specified a value of 32, and NULL byte is specified as 0. Handle [in] the index handle. EmptyChar [in] the empty char value.
Returns
ctdbSetIndexEmptyChar() returns CTDBRET_OK on success, or c-treeDB C API error on failure.
See also
ctdbAllocIndex(), ctdbGetIndexEmptyChar()
FairCom Corporation
642
ctdbSetIndexExtension
Set table index file name extension
Declaration
CTDBRET ctdbSetIndexExtension(CTHANDLE Handle, pTEXT ext)
Description
ctdbSetIndexExtension() sets the index table file name extension. The default value for the index extension is .idx. To retrieve the index table file name extension, use ctdbGetIndexExtension(). Handle [in] the Table Handle. exit [in] the index table file name extension.
Returns
ctdbSetIndexExtension() returns CTDBRET_OK on success, or c-treeDB C API error on failure.
See also
ctdbAllocTable(), ctdbGetIndexExtension()
www.faircom.com
All Rights Reserved
643
ctdbSetIndexFileName
Specify the Physical index file name.
Declaration
CTDBRET ctdbSetIndexFilename(CTHANDLE Handle, pTEXT path, pTEXT filename);
Description
Handle is an index handle returned by ctdbAddIndex() or ctdbGetIndex() calls. path specifies the directory location of the index file. A NULL value for path indicates that the index file is to be located in the same directory as the data file. filename specifies the name of the index file. If filename is NULL, this index is to be a member of the previous index file. If the filename of all index files are NULL, then all indices will be placed in one physical index file located in the same directory as the data file, and the index file name is the same as the data file name, with the current index file extension. An application can change the current index file extension by calling ctdbSetIndexExtension().
Return
Value 0 Symbolic Constant CTDBRET_OK Explanation
c-tree Plus Programmer's Reference Guide for a complete listing of valid c-tree Plus error values.
Example
CTHANDLE hTable = ctdbAllocTable(hDatabase); CTHANDLE hIndex; ctdbAddField(hTable, "name", CT_FSTRING, 20); ctdbAddField(hTable, "age", CT_INT2); hIndex = ctdbAddIndex(hTable, "index1", CTINDEX_FIXED, NO, NO); ctdbSetIndexFilename(hIndex, NULL, "myindex1"); ctdbAddSegmentByName(hTable, 0, "name", CTSEG_SCHSEG); ctdbAddIndex(hTable, "index2", CTINDEX_FIXED, NO, NO); ctdbAddSegmentByName(hTable, 1, "age", CTSEG_SCHSEG); hIndex = ctdbAddIndex(hTable, "index3", CTINDEX_FIXED, NO, NO); ctdbSetIndexFilename(hIndex, NULL, "myindex2"); ctdbAddSegmentByName(hTable, 2, "name", CTSEG_SCHSEG); ctdbAddSegmentByName(hTable, 2, "age", CTSEG_SCHSEG); if (ctdbCreateTable(hTable, "mytable", CTCREATE_NORMAL) != CTDBRET_OK) printf("ctdbCreateTable failed with code %d\n", ctdbGetError(hTable));
See also
ctdbGetIndexFileName(), ctdbSetIndexExtension(), ctdbAddIndex(), ctdbGetIndex()
FairCom Corporation
644
ctdbSetIndexKeyType
Set the index key type.
Declaration
CTDBRET ctdbSetIndexKeyType(CTHANDLE Handle, CTDBKEY KeyType)
Description
ctdbSetIndexKeyType() sets the key type for this index. Use ctdbAddIndex() to add an index to a table. Use ctdbGetIndexKeyType() to retrieve the Index key type. The valid key types are listed in "c-treeDB definitions".. Handle [in] the index handle. KeyType [in] the key type. See the allowed values in "c-treeDB definitions".. Valid keytype values are: CTINDEX_FIXED: Fixed length key CTINDEX_LEADING: Leading character compression CTINDEX_PADDING: Padding compression CTINDEX_LEADPAD: Leading and padding compression
Returns
ctdbSetIndexKeyType() returns CTDBRET_OK on success, or c-treeDB C API error on failure.
See also
ctdbAllocIndex(), ctdbGetIndexKeyType()
www.faircom.com
All Rights Reserved
645
ctdbSetIndexKSeg
Establishes an index-wide extended key segment definition.
DECLARATION
CTDBRET ctdbSetIndexKSeg(CTHANDLE Handle, pctKSEGDEF pKSeg);
DESCRIPTION
ctdbSetIndexKSeg() establishes an index-wide extended key segment definition. Handle must be an index handle and pKSeg is a pointer to an extended key segment definition structure with the extended key definition.
RETURN
Value 0 Symbolic Constant CTDBRET_OK Explanation No error occurred.
See Appendix A for a complete listing of valid c-tree Plus error values.
EXAMPLE
ctKSEGDEF kseg; kseg.kseg_ssiz = ctKSEG_SSIZ_COMPUTED; kseg.kseg_type = ctKSEG_TYPE_UNICODE; kseg.kseg_styp = ctKSEG_STYP_UTF16; kseg.kseg_comp = ctKSEG_COMPU_S_DEFAULT | ctKSEG_COMPU_N_NONE; kseg.kseg_desc = "en_US" if ((eRet = ctdbSetIndexKSeg(hIndex, &kseg)) != CTDBRET_OK) printf(ctdbSetIndexKSeg failed with error %d\n, eRet);
SEE ALSO
ctdbSetTableKSeg(), ctdbGetTableKSeg(), ctdbGetIndexKSeg(), ctdbSetSegmentKSeg(), ctdbGetSegmentKSeg(), ctdbSetKSegDefaults()
FairCom Corporation
646
ctdbSetIndexName
Change the index name.
Declaration
CTDBRET ctdbSetIndexName(CTHANDLE Handle, pTEXT IndexName)
Description
ctdbSetIndexName() changes the index name. The index name can only be changed before the table is created. ctdbSetIndexName() will fail if the table is active. Handle [in] the index handle. IndexName [in] the new index name.
Returns
ctdbSetIndexName() returns CTDBRET_OK on success, or c-treeDB C API error on failure.
See also
ctdbCreateTable(), ctdbAddIndex()
www.faircom.com
All Rights Reserved
647
ctdbSetIndexNullFlag
Set the null key flag for this index.
Declaration
CTDBRET ctdbSetIndexNullFlag(CTHANDLE Handle, CTBOOL NullFlag)
Description
ctdbSetIndexNullFlag() sets the null key flag for this index. Use ctdbGetIndexNullFlag() to retrieve the null key flag for the desired index. Handle [in] the index handle. NullFlag [in] the null key flag for this index.
Returns
ctdbSetIndexNullFlag() returns CTDBRET_OK on success, or c-treeDB C API error on failure.
See also
ctdbAllocIndex(), ctdbGetIndexNullFlag()
FairCom Corporation
648
ctdbSetIndexTemporaryFlag
Set the temporary flag for this index
Declaration
CTDBRET ctdbSetIndexTemporaryFlag(CTHANDLE Handle, CTBOOL TempFlag)
Description
ctdbSetIndexTemporaryFlag() sets the temporary flag for this index. Use ctdbGetIndexTemporaryFlag() to retrieve the flag that indicates this index as temporary. Handle [in] the index handle. TempFlag [in] the temporary index flag.
Returns
ctdbSetIndexTemporaryFlag() returns CTDBRET_OK on success, or c-treeDB C API error on failure.
See also
ctdbAllocIndex(), ctdbGetIndexTemporaryFlag()
www.faircom.com
All Rights Reserved
649
ctdbSetKeepLock
Sets the current keep lock mode when a transaction is committed or aborted.
DECLARATION
CTDBRET ctdbSetKeepLock(CTHANDLE Handle, CTKEEP_MODE mode);
DESCRIPTION
When a transaction is terminated by calling either the ctdbCommit() or ctdbAbort() function, all locks are automatically freed, including the locks acquired outside the transaction. An application might want to control which locks are kept when the transaction ends. To support this ability, c-treeDB introduced a function to control how locks are handled when a transaction terminates. By default, the c-treeDB begin transaction function, ctdbBegin(), will begin a transaction by invoking c-trees TRANBEG() function with the ctTRNLOG and ctENABLE_BLK modes set. If the TRANBEG() function succeeds, c-treeDBs ctdbBegin() function automatically calls LKISAM() to suspend locks enabled by TRANBEG(), allowing users to enable any locks they wish: read locks, write locks, blocking or non-blocking. In this case, the c-treeDB commit or abort transaction functions, ctdbCommit() and ctdbAbort(), call the appropriate c-tree ISAM functions to terminate the transaction and free all locks. ctdbSetKeepLock() sets the extended keep lock mode applied when an active transaction is commited or aborted by calling ctdbCommit() or ctdbAbort(). Handle is a session handle and the keep lock mode is one of the following pre-defined constants:
Value 0 1 Symbolic Constant Explanation Release all locks. Clear LKISAM state. This is the default mode. Keep all locks acquired before and during transaction. The LKISAM state is not cleared. Release only locks obtained within transaction and/or locks on records updated within transaction. The LKISAM state is not cleared. Unconditionally keep all locks acquired before transaction began. Free locks obtained within the transaction. The LKISAM state is not cleared.
CTKEEP_OUTALL
RETURN
Value 0 Symbolic Constant CTDBRET_OK Explanation No error occurred.
See Appendix A for a complete listing of valid c-tree Plus error values.
EXAMPLE
/* set the keep lock */ if (ctdbSetKeepLock(hSession, CTKEEP_LOCK) != CTDBRET_OK) printf("ctdbSetKeepLock failed\n"); /* begin the transaction */ ctdbBegin(hSession); /* do some operations and commit transaction */ ctdbCommit(hSession);
FairCom Corporation
650
SEE ALSO
ctdbAbort, ctdbBegin(), ctdbCommit(), ctdbGetKeepLock()
www.faircom.com
All Rights Reserved
651
ctdbSetKSegDefaults
Sets the system-wide default values for the extended key segment definition.
DECLARATION
CTDBRET ctdbSetKSegDefaults(pctKSEGDEF pKSeg);
DESCRIPTION
Sets the system-wide default values for the extended key segment definition. pKSeg is a pointer to an extended key segment definition structure which will receive the definition. The default values are: kseg_ssiz = ctKSEG_SSIZ_COMPUTED; kseg_type = ctKSEG_TYPE_UNICODE; kseg_styp = ctKSEG_STYP_UTF16; kseg_comp = ctKSEG_COMPU_S_DEFAULT | ctKSEG_COMPU_N_NONE; kseg_desc = "en_US"
RETURN
Value 0 Symbolic Constant CTDBRET_OK Explanation No error occurred.
See Appendix A for a complete listing of valid c-tree Plus error values.
EXAMPLE
ctKSEGDEF kseg; if ((eRet = ctdbSetKSegDefaults(&kseg)) != CTDBRET_OK) printf(ctdbSetKSegDefaults failed with error %d\n, eRet);
SEE ALSO
ctdbSetTableKSeg(), ctdbGetTableKSeg(), ctdbSetIndexKSeg(), ctdbGetIndexKSeg(), ctdbSetSegmentKSeg(), ctdbGetSegmentKSeg()
FairCom Corporation
652
ctdbSetLocalTag
Sets the localTag pointer.
DECLARATION
CTDBRET ctdbSetLocalTag(CTHANDLE Handle, pVOID pTag);
DESCRIPTION
The local tag pointer, pTag, is a place holder for data storage specific to each callback type implementation. A callback function implementation may use this tag to store local data. The localTag pointer is available for c-treeDB session, database, table and record handles, and it is initialized with NULL when the handle is allocated.
RETURN
Value 0 Symbolic Constant CTDBRET_OK Explanation No error occurred.
See Appendix A for a complete listing of valid c-tree Plus error values.
EXAMPLE
if (ctdbSetLocalTag(Handle, pSession->onAlloc(1000))) printf("ctdbSetLocalTag failed\n");
SEE ALSO
ctdbGetHandleType(), ctdbGetLocalTag()
www.faircom.com
All Rights Reserved
653
ctdbSetLogonOnly
Set the session logon only flag.
Declaration
CTDBRET ctdbSetLogonOnly(CTHANDLE Handle, CTBOOL flag)
Description
ctdbSetLogonOnly() sets the session logon only flag. This flag, when set to YES before the session Logon, will prevent the session from using the session dictionary. If the session dictionary may not be used, the database dictionary cannot be used. With this, any information related to databases or tables cannot be use, but the tables can yet be opened or created using the session handle, as can be seen in the example below. To retrieve the flag, use ctdbGetLogonOnly(). Handle [in] the Sesion Handle. flag [in] logon only flag value.
Returns
ctdbSetLogonOnly() returns CTDBRET_OK on success, or c-treeDB C API error on failure.
Example
CTSESSION_TYPE ctdbsess=CTSESSION_CTDB; CTHANDLE hSession = ctdbAllocSession(ctdbsess); CTHANDLE hTable = ctdbAllocTable(hSession); CTDBRET err; err = ctdbSetLogonOnly(hSession, YES); err = ctdbLogon(hSession, "FAIRCOMS", "ADMIN", "ADMIN"); pMyField1 = ctdbAddField(pMyTable, "Name" , CT_FSTRING,32); pMyField2 = ctdbAddField(pMyTable, "Balance", CT_SFLOAT, 4); pMyIndex = ctdbAddIndex(pMyTable, "iName", CTINDEX_FIXED,NO,NO); pMyIseg = ctdbAddSegment(pMyIndex, pMyField1, 2); RetVal = ctdbCreateTable(pMyTable,"Table1",CTCREATE_NORMAL); err = ctdbLogout(hSession); ctdbFreeTable(hTable); ctdbFreeSession(hSession);
See also
ctdbGetLogonOnly(), ctdbLogon()
FairCom Corporation
654
ctdbSetNewRecord
Set the new record flag.
Declaration
CTDBRET ctdbSetNewRecord(CTHANDLE Handle, CTBOOL flag)
Description
ctdbSetNewRecord() sets the new record flag. Handle [in] the Sesion Handle. flag [in] new record flag value.
Returns
ctdbSetNewRecord() returns CTDBRET_OK on success, or c-treeDB C API error on failure.
See also
ctdbSetEditedRecord()
www.faircom.com
All Rights Reserved
655
ctdbSetOperationState
Declaration
CTDBRET ctdbDECL ctdbSetOperationState(CTHANDLE Handle, CTOPS_MODE mode, CTOPS_STATE state);
Description
ctdbSetOperationState() sets the c-tree operation modes for special performance-related functionality and test operational states for critical events. Handle is a session handle. mode uses a combination of the following values:
Operations Mode Description Enable automatic, low level, blocking read locks on each record access that does not already have a lock. Lock next fetch only. Automatic unlock on add. Automatic unlock on rewrite. (OPS_UNLOCK_ADD | OPS_UNLOCK_RWT) Blocking lock on next fetch only. Toggle function monitor. (Server) Toggle lock monitor. (Server) Toggle memory track monitor. (Server) Dont continue if mirror or primary fails. (Server) A primary or mirror has been shutdown. Memory swapping active. Automatic ISAM transactions. Auto commit on swap occurred. Changes GetSerialNbr() operation. Defer file closes or deletes during transactions. Change all CT_STRING fields having a non-zero field length in the fixed length portion of the record buffer to CT_FSTRING fields. (Client) Set sysiocod on disk reads and writes.
OPS_READLOCK OPS_LOCKON_GET OPS_UNLOCK_ADD OPS_UNLOCK_RWT OPS_UNLOCK_UPD OPS_LOCKON_BLK OPS_FUNCTION_MON OPS_LOCK_MON OPS_TRACK_MON OPS_MIRROR_NOSWITCH OPS_MIRROR_TRM OPS_MEMORY_SWP OPS_AUTOISAM_TRN OPS_COMMIT_SWP OPS_SERIAL_UPD OPS_DEFER_CLOSE OPS_CONV_STRING
OPS_DISK_IO
FairCom Corporation
656
Return Values
Value 0 Symbolic Constant Explanation No error occurred.
CTDBRET_OK
See Also
ctdbGetOperationState() ctdbGetAutoCommit() ctdbSetAutoCommit()
www.faircom.com
All Rights Reserved
657
ctdbSetPadChar
Set the table pad and field delimiter characters.
Declaration
CTDBRET ctdbSetPadChar(CTHANDLE Handle, pTEXT pPadChar, pTEXT pDmlChar)
Description
ctdbSetPadChar() sets the table pad and field delimiter characters. These characters are used to pad fixed string fields (CT_FSTRING) to allow proper target key formation. Handle [in] the Table Handle. padchar [in] the pad character dmlchar [in] the field delimiter character
Returns
ctdbSetPadChar() returns CTDBRET_OK on success, or c-treeDB C API error code on failure.
See also
ctdbGetPadChar(), ctdbUpdatePadChar()
FairCom Corporation
658
ctdbSetPathPrefix
Set the client-side path prefix.
Declaration
CTDBRET ctdbSetPathPrefix(CTHANDLE hSession, pTEXT pathPrefix);
Description
A path prefix can be set anytime after the session handle is allocated. If a path prefix is set before a session logon, the new path prefix will affect the location of the session dictionary file. If a path prefix is set after a session logon, but before a database connect, then the path prefix affects only the database dictionary and any tables that are manipulated during that session. A path prefix can be removed at any time by setting a NULL value for the path prefix. You can use ctdbGetPathPrefix() to check if a path prefix is set or not. If ctdbGetPathPrefix() returns NULL, then no path prefix is set.
Return
Value 0 Symbolic Constant CTDBRET_OK Explanation
See "c-treeDB Errors and Return Values" for a complete listing of valid c-treeDB error codes and return values.
Example
/* set the current path prefix */ if (ctdbSetPathPrefix(AnyHandle, "c:\myDirectory") != CTDBRET_OK) printf("ctdbSetPathPrefix() failed\n"); /* clear the current path prefix */ if (ctdbSetPathPrefix(AnyHandle, NULL) != CTDBRET_OK) printf("ctdbSetPathPrefix() failed\n");
See also
ctdbGetPathPrefix()
www.faircom.com
All Rights Reserved
659
ctdbSetRecordBuffer
Set the record buffer with an user supplied data.
Declaration
CTDBRET ctdbSetRecordBuffer(CTHANDLE Handle, pVOID pBuffer, VRLEN reclen, CTRECBUF_MODE mode)
Description
ctdbSetRecordBuffer() sets the record buffer with an user supplied data. The record buffer NEW and MODIFIED flags are set to YES. After a call to ctdbSetRecordBuffer(), a call to ctdbWriteRecord() will add a new record to the record's table. Handle [in] the record handle. pBuffer [in] the pointer to a user buffer containing the record data. If the record buffer is NULL, the record is set to automatic. reclen [in] the length in bytes of the user record buffer mode [in] the mode of operation. Valid values are given in the table below.
Mode Explanation This is the default mode for the record buffer operation. The record manager will allocate or reallocate the record buffer as needed to hold the record data. The user is responsible for supplying a record buffer large enough to handle any record data. If a record operation is attempted and the record buffer is not long enough to hold the data, an CTDBRET_INVRECBUF is returned to indicate that the record buffer is not large enough. OR this mode in to indicate that the record manager is not supposed to update the internal control structures of the record buffer.
CTRECBUF_AUTO CTRECBUF_STATIC
CTRECBUF_RAW
Returns
ctdbSetRecordBuffer() returns CTDBRET_OK on success, or a c-treeDB C API error code on failure. The error CTDBRET_INVRECBUF (4063) means that the buffer is not large enough to hold the data. Increase the buffer or use the mode CTRECBUF_AUTO.
See also
ctdbWriteRecord(), ctdbSetRecordPos(), ctdbSetRecordOffset()
FairCom Corporation
660
ctdbSetRecordOffset
Update the record offset.
Declaration
CTDBRET ctdbSetRecordOffset(CTHANDLE Handle, CTOFFSET offset)
Description
ctdbSetRecordOffset() updates the record offset. The current record pointer is not moved and no record data is updated. Handle [in] the record handle. offset [in] the new record byte offset.
Returns
ctdbSetRecordOffset() returns CTDBRET_OK on success, or a c-treeDB C API error code on failure
See also
ctdbSetRecordPos(), ctdbSeekRecord(), ctdbGetRecordPos(), ctdbSetRecordBuffer()
www.faircom.com
All Rights Reserved
661
ctdbSetRecordPos
Set the current record offset position.
Declaration
CTDBRET ctdbSetRecordPos(CTHANDLE Handle, CTOFFSET offset)
Description
ctdbSetRecordPos() sets the current record position. The record buffer is not updated. Follow the ctdbSetRecordPos() with a call to ctdbReadRecord() to update the record buffer. Handle [in] the record handle. offset [in] the current record offset position.
Returns
ctdbSetRecordPos() returns CTDBRET_OK on success, or a c-treeDB C API error code on failure
See also
ctdbSetRecordOffset(), ctdbReadRecord(), ctdbSeekRecord(), ctdbGetRecordPos(), ctdbSetRecordBuffer()
FairCom Corporation
662
ctdbRenameTable
Declaration
ctdbRenameTable(CTHANDLE Handle, pTEXT oldname, pTEXT newname);
Description
Handle a database handle newname a string containing the original table name newname a string containing the new table name
Return Values
Value 0 4012 4022 Symbolic Constant CTDBRET_OK Explanation No Error. Database not active. Tablename already exists in database.
CTDBRET_NOTACTIVE CTDBRET_TABLEEXIST
See Also
www.faircom.com
All Rights Reserved
663
ctdbSetResourceData
Set the resource data..
DECLARATION
CTDBRET ctdbDECL ctdbSetResourceData(CTHANDLE resource, pVOID data, VRLEN size);
DESCRIPTION
Set the resource data. The internal resource buffer is resized and the resource data is copied. If the resource data parameter is NULL, the internal resource data buffer is released. resource is a handle allocated with ctdbAllocHandle(). data is a pointer to resource data. If data is NULL the internal resource data buffer is cleared. size indicate the number of bytes pointed by data.
RETURN
ctdbSetResourceData() return CTDBRET_OK on success.
EXAMPLE
CTDBRET ReadMyResource(CTHANDLE Handle, ULONG type, ULONG number, ppVOID data, pVRLEN size) { CTDBRET eRet; CTHANDLE hRes = ctdbAllocResource(Handle, type, number, NULL); /* check the resource handle allocation */ if (hRes == NULL) { eRet = ctdbGetError(Handle); goto Exit; } /* get the resource */ if ((eRet = ctdbFindResource(hRes, type, number, NO)) != CTDBRET_OK) goto Exit; /* allocate a buffer large enough for the resource data */ *size = ctdbGetResourceDataLength(hRes); if (*size > 0) { *data = (pVOID)malloc(*size); if (*data == NULL) { eRet = CTDBRET_NOMEMORY; goto Exit; } memcpy(*data, ctdbGetResourceData(hRes), *size); } Exit: if (hRes) ctdbFreeResource(hRes); return eRet; }
SEE ALSO
ctdbAllocResource, ctdbFreeResource, ctdbAddResource, ctdbDeleteResource, ctdbUpdateResource, ctdbFirstResource, ctdbNextResource, ctdbFindResource, ctdbFindResourceByName, ctdbGetResourceType, ctdbSetResourceType, ctdbGetResourceNumber, ctdbSetResourceNumber, ctdbGetResourceName, ctdbSetResourceName, ctdbGetResourceDataLength, ctdbGetResourceData, ctdbIsResourceLocked, ctdbUnlockResource
FairCom Corporation
664
ctdbSetResourceName
Set the resource name.
DECLARATION
CTDBRET ctdbDECL ctdbSetResourceName(CTHANDLE resource, pTEXT name);
DSCRIPTION
Set the resource name. resource is a handle allocated by ctdbAllocHandle(). name is a resource name. A NULL value is acceptable to clear the current resource name.
RETURN
ctdbSetResourceName() returns CTDBRET_OK on success
EXAMPLE
if (ctdbGetResourceName(hRes) != NULL) ctdbSetResourceName(hRes, NULL);
SEE ALSO
ctdbAllocResource, ctdbFreeResource, ctdbAddResource, ctdbDeleteResource, ctdbUpdateResource, ctdbFirstResource, ctdbNextResource, ctdbFindResource, ctdbFindResourceByName, ctdbGetResourceType, ctdbSetResourceType, ctdbGetResourceNumber, ctdbSetResourceNumber, ctdbGetResourceName, ctdbGetResourceDataLength, ctdbGetResourceData, ctdbSetResourceData, ctdbIsResourceLocked, ctdbUnlockResource
www.faircom.com
All Rights Reserved
665
ctdbSetResourceNumber
Set a resource number.
DECLARATION
CTDBRET ctdbDECL ctdbSetResourceNumber(CTHANDLE resource, ULONG number);
DESCRIPTION
Sets a resource number. resource is a handle allocated by ctdbAllocResource() and number is a value representing a resource number.
RETURN
ctdbSetResourceNumber() returns CTDBRET_OK on success.
EXAMPLE
if (ctdbGetResourceNumber(hRes) != number) ctdbSetResourceNumber(hRes, number);
SEE ALSO
ctdbAllocResource, ctdbFreeResource, ctdbAddResource, ctdbDeleteResource, ctdbUpdateResource, ctdbFirstResource, ctdbNextResource, ctdbFindResource, ctdbFindResourceByName, ctdbGetResourceType, ctdbSetResourceType, ctdbGetResourceNumber, ctdbGetResourceName, ctdbSetResourceName, ctdbGetResourceDataLength, ctdbGetResourceData, ctdbSetResourceData, ctdbIsResourceLocked, ctdbUnlockResource
FairCom Corporation
666
ctdbSetResourceType
Set the resource type.
DECLARATION
CTDBRET ctdbDECL ctdbSetResourceType(CTHANDLE resource, ULONG type);
DESCRIPTION
Set the resource type. resource is a handle allocated by ctdbAllocResource() and type is a number representing the resource type.
RETURN
ctdbSetResourceType() returns CTDBRET_OK on success.
EXAMPLE
if (ctdbGetResourceType(hRes) != type) ctdbSetResourceType(hRes, type);
SEE ALSO
ctdbAllocResource, ctdbFreeResource, ctdbAddResource, ctdbDeleteResource, ctdbUpdateResource, ctdbFirstResource, ctdbNextResource, ctdbFindResource, ctdbFindResourceByName, ctdbGetResourceType, ctdbGetResourceNumber, ctdbSetResourceNumber, ctdbGetResourceName, ctdbSetResourceName, ctdbGetResourceDataLength, ctdbGetResourceData, ctdbSetResourceData, ctdbIsResourceLocked, ctdbUnlockResource
www.faircom.com
All Rights Reserved
667
ctdbSetSavePoint
Establish a transaction save point.
Declaration
NINT ctdbSetSavePoint(CTHANDLE Handle)
Description
ctdbSetSavePoint() establishes a transaction save point. Handle [in] the session handle.
Returns
ctdbSetSavePoint() returns the save point number, or 0 on failure.
See also
ctdbBegin(), ctdbCommit(), ctdbAbort(), ctdbRestoreSavePoint()
FairCom Corporation
668
ctdbSetSegmentKSeg
Establishes a segment extended key definition.
DECLARATION
CTDBRET ctdbSetSegmentKSeg(CTHANDLE Handle, pctKSEGDEF pKSeg);
DESCRIPTION
ctdbSetSegmentKSeg() establishes a segment extended key segment definition. Handle must be a segment handle and pKSeg is a pointer to an extended key segment definition structure with the extended key definition.
RETURN
Value 0 Symbolic Constant CTDBRET_OK Explanation No error occurred.
See Appendix A for a complete listing of valid c-tree Plus error values.
EXAMPLE
ctKSEGDEF kseg; kseg.kseg_ssiz = ctKSEG_SSIZ_COMPUTED; kseg.kseg_type = ctKSEG_TYPE_UNICODE; kseg.kseg_styp = ctKSEG_STYP_UTF16; kseg.kseg_comp = ctKSEG_COMPU_S_DEFAULT | ctKSEG_COMPU_N_NONE; kseg.kseg_desc = "en_US" if ((eRet = ctdbSetSegmentKSeg(hIndex, &kseg)) != CTDBRET_OK) printf(ctdbSetSegmentKSeg failed with error %d\n, eRet);
SEE ALSO
ctdbSetTableKSeg(), ctdbGetTableKSeg(), ctdbSetIndexKSeg(), ctdbGetIndexKSeg(), ctdbGetSegmentKSeg(), ctdbSetKSegDefaults()
www.faircom.com
All Rights Reserved
669
ctdbSetSegmentMode
Set the segment mode.
Declaration
CTDBRET ctdbSetSegmentMode(CTHANDLE Handle, CTSEG_MODE SegMode)
Description
ctdbSetSegmentMode() sets the segment mode. When the table is created, the segment mode is defined with the segments. If this information has to be changed later, ctdbSetSegmentMode() may be used. In this case, ctdbAlterTable() must be called after that to modify the table structure. Use ctdbGetSegmentMode() to retrieve the segment mode. Handle [in] the Segment Handle. SegMode [in] one of the valid segment modes, presented in "c-treeDB definitions"..
Returns
ctdbSetSegmentMode() returns CTDBRET_OK on success, or c-treeDB C API error on failure.
Example
seg = ctdbGetSegmentMode(hSegment); if (seg == CTSEG_SCHSEG) { err = ctdbSetSegmentMode(hSegment, CTSEG_USCHSEG); err = ctdbAlterTable(hTable); }
See also
ctdbAllocSegment(), ctdbGetSegmentMode(), ctdbAlterTable()
FairCom Corporation
670
ctdbSetSessionParams
Set the session parameter based on the parameter type.
Declaration
CTDBRET ctdbSetSessionParams(CTHANDLE Handle, CTSESSION_PARAM ParamType, NINT value)
Description
ctdbSetSessionParams() sets the session parameter based on the parameter type. It is necessary to set parameters before logging on to the server with ctdbLogon(). Handle [in] the session handle. ParamType [in] the parameter type. Allowed values are: CT_BUFS: the number of index file buffers, minimum 3 CT_FILS: initial block of file structures. CT_SECT: the number of node sectors. Minimum of one required. sect multiplied by 128 equals the index node size. CT_DBUFS: the number of buffers for data files I/O CT_USERPROF: is the user profile mask, and accepts the following values: USERPRF_CLRCHK - instructs single-user TRANPROC applications to remove S*.FCS and L*.FCS files upon a successful application shutdown. The c-tree Plus checkpoint code determines at the time of a final checkpoint if there are no pending transactions or file opens, and if this user profile bit has been turned on. If so, the S*.FCS and L*.FCS files are deleted. However, if the application is causing log files to be saved (very unusual for a single-user application), then the files are not cleared. The USERPRF_CLRCHK option is off by default. USERPRF_LOCLIB - specifies this instance of c-tree Plus is to be directed to a local database. Applicable only to client/server when using Local Library Support. USERPRF_NDATA - enable the manual mode of UNIFRMAT support. Enabling the manual record transformation mode would only be desirable when performing custom record level byte flipping or the record structures contain no numeric data (i.e., LONG, FLOAT, . . .). A side benefit of enabling this manual mode is the virtual elimination of Server DODA requests, thereby reducing network traffic by one function call per file open. USERPRF_NTKEY - disables the automatic TransformKey() feature. See the TransformKey() function description for more information. USERPRF_PTHTMP - changes GetCtTempFileName() from its default operation of returning a temporary file name to specifying a directory name where temporary files are to reside. USERPRF_SAVENV - enable the automatic SAVENV feature. See the Begin() function description for more information. To use more than one value, OR the values together. Leave CT_USERPROF set to zero to accept the defaults. value is the numeric value to be attributed to the parameter specified by ParamType.
Returns
ctdbSetSessionParams() returns c-tree Plus error code on failure, or CTDBRET_OK on success.
www.faircom.com
All Rights Reserved
671
Example
CTSESSION_TYPE ctdbsess=CTSESSION_CTDB; CTHANDLE hSession = ctdbAllocSession(ctdbsess); CTDBRET err; NINT ret, newbuf; err = ctdbLogon(hSession, "FAIRCOMS", "ADMIN", "ADMIN"); ret = ctdbGetSessionParams(hSession, CT_BUFS); newbuf = ret + 2; err = ctdbSetSessionParams(hSession, CT_BUFS, newbuf);
See also
ctdbGetSessionParams(), ctdbAllocSession()
FairCom Corporation
672
ctdbSetSessionPath
Set the default session path.
Declaration
CTDBRET ctdbSetSessionPath(CTHANDLE Handle, pTEXT Path)
Description
ctdbSetSessionPath() sets the default session path, where the session dictionary is located or will be created. Subsequent calls to functions like ctdbLogon() will use the session dictionary located in this path. Handle [in] the session handle. Path [in] the pointer to the new default session path.
Returns
ctdbSetSessionPath() returns CTDBRET_OK if successful, or the c-tree Plus error code on failure.
Example
ctdbSetSessionPath(handle, c:\mySession); eRet = ctdbLogon(handle, "FAIRCOMS", "ADMIN", "ADMIN");
See also
ctdbGetSessionPath(), ctdbLogon(), ctdbCreateSession()
www.faircom.com
All Rights Reserved
673
ctdbSetSessionExclusive
Sets or clears the session exclusive flag.
DECLARATION
CTDBRET ctdbSetSessionExclusive(CTHANDLE Handle, CTBOOL flag);
DESCRIPTION
ctdbSetSessionExclusive() sets or clears the session exclusive flag. If a session exclusive flag is set, only one CTSESSION_CTDB or CTSESSION_SQL session will be allowed. Set the session exclusive flag after allocating the session handle, but before performing a logon. Setting the session exclusive flag after a session logon is performed will not have any effect during the current session. Handle is a session handle. If flag is YES, this will set the exclusive flag, while NO will clear the exclusive flag.
RETURN
Value 0 Symbolic Constant CTDBRET_OK Explanation No error occurred.
See Appendix A for a complete listing of valid c-tree Plus error values.
EXAMPLE
/* perform an exclusive logon */ CTHANDLE hSession = ctdbAllocSession(CTSESSION_CTDB); if (hSession) { ctdbSetSessionExclusive(hSession, YES); if (ctdbLogon(hSession, "FAIRCOM", "ADMIN", "ADMIN") != CTDBRET_OK) printf("ctdbLogon failed\n"); } ctdbFreeSession(hSession);
SEE ALSO
ctdbIsSessionExclusive(), ctdbSetDatabaseExclusive(), ctdbIsDatabaseExclusives()
FairCom Corporation
674
ctdbSetSessionType
Change the session type.
Declaration
CTDBRET ctdbSetSessionType(CTHANDLE Handle, CTSESSION_TYPE SessionType)
Description
ctdbSetSessionType() changes the session type. The session type is initially set when ctdbAllocSession() is called to allocate a new session handle. ctdbSetSessionType() allow users to change the session type after it has been allocated. Handle [in] the session handle. SessionType [in] the new session type. The valid types are CTSESSION_CTDB, CTSESSION_CTREE, or CTSESSION_SQL
Returns
ctdbSetSessionType() returns CTDBRET_OK if successful, or the c-tree Plus error code on failure.
See also
ctdbGetSessionType()
www.faircom.com
All Rights Reserved
675
ctdbSetTableDefaultDataExtentSize
Set table default data extent size.
Declaration
CTDBRET ctdbSetTableDefaultDataExtentSize(CTHANDLE Handle, NINT size)
Description
ctdbSetTableDefaultDataExtentSize() sets the table default data extent size. Use ctdbSetTableDefaultIndexExtentSize() to set the table default index extend size. Use ctdbGetTableDefaultDataExtentSize() to retrieve the table default data extent size. Handle [in] the Table Handle. size [in] the extent size.
Returns
ctdbSetTableDefaultDataExtentSize() returns CTDBRET_OK on success, or c-treeDB C API error code on failure.
See also
ctdbAllocTable(), ctdbSetTableDefaultIndexExtentSize(), ctdbGetTableDefaultDataExtentSize()
FairCom Corporation
676
ctdbSetTableDefaultIndexExtentSize
Set the table default index extent size
Declaration
CTDBRET ctdbSetTableDefaultIndexExtentSize(CTHANDLE Handle, NINT size)
Description
ctdbSetTableDefaultIndexExtentSize() sets the table default index extent size. Use ctdbSetTableDefaultDataExtentSize() to set the table default data extend size. Use ctdbGetTableDefaultIndexExtentSize() to retrieve the table default index extent size. Use ctdbSetDefaultIndex() to set the table default index. Handle [in] the Table Handle. size [in] the size to be extent.
Returns
ctdbSetTableDefaultIndexExtentSize() returns CTDBRET_OK on success, or c-treeDB C API error code on failure.
See also
ctdbAllocTable(), ctdbSetTableDefaultDataExtentSize(), ctdbSetDefaultIndex(), ctdbGetTableDefaultIndexExtentSize()
www.faircom.com
All Rights Reserved
677
ctdbSetTableExtension
Set a new table extension
Declaration
CTDBRET ctdbSetTableExtension(CTHANDLE Handle, pTEXT fExt)
Description
ctdbSetTableExtension() sets a new table extension. Use ctdbGetTableExtension() to retrieve the table extension. Handle [in] the Table Handle. fExt [in] the new table extension.
Returns
ctdbSetTableExtension() returns CTDBRET_OK on success, or c-treeDB C API error code on failure.
See also
ctdbAllocTable(), ctdbGetTableExtension()
FairCom Corporation
678
ctdbSetTableGroupid
Set the table group ID.
Declaration
CTDBRET ctdbSetTableGroupid(CTHANDLE Handle, pTEXT groupid)
Description
ctdbSetTableGroupid() sets the table group ID. To retrieve the table group ID, use ctdbGetTableGroupid(). Handle [in] the Table Handle. groupid [in] the table group id. If groupid is NULL, no action is taken.
Returns
ctdbSetTableGroupid() returns CTDBRET_OK on success, or c-treeDB C API error on failure.
See also
ctdbAllocTable(), ctdbGetTableGroupid()
www.faircom.com
All Rights Reserved
679
ctdbSetTableKSeg
Establishes a table wide extended key segment definition.
DECLARATION
CTDBRET ctdbSetTableKSeg (CTHANDLE Handle, pctKSEGDEF pKSeg);
DESCRIPTION
ctdbSetTableKSeg() establishes a table wide extended key segment definition. Handle must be a c-treeDB table handle. pKSeg is a pointer to an extended key segment definition structure with the extended key definition.
RETURN
Value 0 Symbolic Constant CTDBRET_OK Explanation No error occurred.
See Appendix A for a complete listing of valid c-tree Plus error values.
EXAMPLE
ctKSEGDEF kseg; kseg.kseg_ssiz = ctKSEG_SSIZ_COMPUTED; kseg.kseg_type = ctKSEG_TYPE_UNICODE; kseg.kseg_styp = ctKSEG_STYP_UTF16; kseg.kseg_comp = ctKSEG_COMPU_S_DEFAULT | ctKSEG_COMPU_N_NONE; kseg.kseg_desc = "en_US" if ((eRet = ctdbSetTableKSeg(hTable, &kseg)) != CTDBRET_OK) printf(ctdbSetTableKSeg failed with error %d\n, eRet);
SEE ALSO
ctdbGetTableKSeg(), ctdbSetIndexKSeg(), ctdbGetIndexKSeg(), ctdbSetSegmentKSeg(), ctdbGetSegmentKSeg(), ctdbSetKSegDefaults()
FairCom Corporation
680
ctdbSetTablePassword
Set the table password.
Declaration
CTDBRET ctdbSetTablePassword(CTHANDLE Handle, pTEXT password)
Description
ctdbSetTablePassword() sets the table password. To retrieve the table password, use ctdbGetTablePassword(). Handle [in] the Table Handle. Password [in] the table password.
Returns
ctdbSetTablePassword() returns CTDBRET_OK on success, or c-treeDB C API error on failure.
See also
ctdbAllocTable(), ctdbGetTablePassword()
www.faircom.com
All Rights Reserved
681
ctdbSetTablePath
Set a new table path
Declaration
CTDBRET ctdbSetTablePath(CTHANDLE Handle, pTEXT Path)
Description
ctdbSetTablePath() Sets a new Table Path. Set the table path before the table is created, otherwise it will created in the default (server or application) directory. After the table creation, the table path is stored in the database dictionary and the user does not need to know it in order to open the table. If, for any reason, it is needed to retrieve the table path, use ctdbGetTablePath(). Handle [in] the Table Handle. Path [in] the Table Path.
Returns
ctdbSetTablePath() returns CTDBRET_OK on success, or c-treeDB C API error code on failure.
Example
ctdbSetTablePath(hTable, C:\mydatabase); eRet = ctdbCreateTable(hTable, table_name, CTCREATE_NORMAL);
See also
ctdbGetTablePath(), ctdbCreateTable()
FairCom Corporation
682
ctdbSetTablePermission
Set table permission mask.
Declaration
CTDBRET ctdbSetTablePermission(CTHANDLE Handle, LONG permmask)
Description
ctdbSetTablePermission() sets the table permission mask. To retrieve the table permission mask, use ctdbGetTablePermission(). Handle [in] the Table Handle. permmask [in] the Table Permission mask. The valid values for permmask are presented in "c-treeDB definitions"..
Returns
ctdbSetTablePermission() returns CTDBRET_OK on success, or c-treeDB C API error on failure.
See also
ctdbAllocTable(), ctdbGetTablePermission()
www.faircom.com
All Rights Reserved
683
ctdbSetTableOwner
Declaration
CTDBRET ctdbSetTableOwner(CTHANDLE Handle, pTEXT owner);
Description
Sets the table owner. You should set the table owner before the table is created to allow the proper c-tree security setting to take place. Handle is a table handle allocated by ctdbAllocTable(). owner is a string with the table owner name. owner can be NULL, in which case the table owner name will be cleared.
Return Values
ctdbSetTableOwner() returns CTDBRET_OK on success.
See Also
ctdbGetTableOwner()
FairCom Corporation
684
ctdbSetTransactionMode
Declaration
CTDBRET ctdbDECL ctdbSetTransactionMode(CTHANDLE Handle, CTBEGIN_MODE mode);
Description
Handle is a session handle. mode is a combination of possible mode values:
CTBEGIN_MODE Symbolic Constant Description No begin transaction mode set. Default mode apply. Transaction atomicity only. Auto-recovery is not available. Mutually exclusive with CTBEGIN_TRNLOG. Full transaction processing functionality including auto-recovery. Mutually exclusive to CTBEGIN_PREIMG. This is the default begin transaction mode. Defer begin transaction until update. Automatically invokes savepoints after each successful record or resource update.
CTBEGIN_DEFER CTBEGIN_AUTOSAVE
This mode will be OR-ed in to form the transaction mode used when a c-tree transaction is started. If the transaction mode is CTBEGIN_NONE, the ctTRNLOG mode is used to start a new transaction.
Return Values
Value 0 Symbolic Constant NO_ERROR Explanation Successful operation.
See Also
ctdbGetTransactionMode()
www.faircom.com
All Rights Reserved
685
ctdbSetUserTag
Set the user tag.
Declaration
CTDBRET ctdbSetUserTag(CTHANDLE Handle, pVOID tagptr)
Description
ctdbSetUserTag() sets the user tag. Handle [in] any c-treeDB SDK Handle. tagptr [in] the pointer associated with the value to be set to the user tag.
Returns
ctdbSetUserTag() returns CTDBRET_OK on success, or c-treeDB C API error on failure.
See also
ctdbGetUserTag()
FairCom Corporation
686
ctdbStringToBigInt
Convert a string to a big integer value.
Declaration
CTDBRET ctdbStringToBigInt(pTEXT pStr, pCTBIGINT pValue)
Description
ctdbStringToBigInt() converts a string to a big integer value. A big integer is an 8 bytes integer value. Use ctdbBigIntToString() to convert from a big integer to a string. pStr [in] the string value. pValue [out] the big integer value (8 bytes signed integer).
Returns
ctdbStringToBigInt() returns CTDBRET_OK on success, or c-treeDB C API error on failure. The possible error associated with ctdbStringToBigInt() is: CTDBRET_NULARG (4007): Null argument not valid in pValue
See also
ctdbBigIntToString()
www.faircom.com
All Rights Reserved
687
ctdbStringToCurrency
Convert a string value to a CTCURRENCY value.
Declaration
CTDBRET ctdbStringToCurrency(pTEXT pStr, pCTCURRENCY pCurrency)
Description
ctdbStringToCurrency() converts a string value to a CTCURRENCY (8 bytes signed integer) value. Use ctdbCurrencyToString() to convert from a CTCURRENCY value to a string. pStr [in] the string value. pCurrency [out] the CTCURRENCY value (8 bytes integer).
Returns
ctdbStringToCurrency() returns CTDBRET_OK on success, or c-treeDB C API error on failure. The possible error associated with ctdbStringToCurrency() is: CTDBRET_NULARG (4007): Null argument not valid in pStr
See also
ctdbCurrencyToString()
FairCom Corporation
688
ctdbStringToDate
Convert a date in string format to CTDATE packed format.
Declaration
CTDBRET ctdbStringToDate(pTEXT pStr, CTDATE_TYPE DateType, pCTDATE pDate)
Description
ctdbStringToDate() converts a date in string format to CTDATE packed format. Use ctdbDateToString() to convert a packed CTDATE into a string. pStr [in] the pointer to the string. DateType [in] the date type. Valid types are listed in "c-treeDB definitions".. pDate [out] the pointer to date that will result from the conversion.
Returns
ctdbStringToDate() returns CTDBRET_OK on success, or c-treeDB C error on failure. The possible errors associated with ctdbStringToDate() are: CTDBRET_NULARG (4007): Null argument not valid in pStr CTDBRET_NOMEMORY (4001): Not enough memory CTDBRET_INVFORMAT (4028): Invalid format in DateType CTDBRET_INVDATE (4029): Invalid packed CTDATE
See also
ctdbStringToTime(), ctdbDateToString()
www.faircom.com
All Rights Reserved
689
ctdbStringToDateTime
Convert a date in string format into a packed CTDATETIME.
Declaration
CTDBRET ctdbStringToDateTime(pTEXT pStr, pCTDATETIME pDateTime, CTDATE_TYPE DateType, CTTIME_TYPE TimeType)
Description
ctdbStringToDateTime() converts a packed CTDATETIME into a string. The date is converted to string based on the DateType parameter, and the time is converted to string based on the TimeType parameter. pStr [in] a pointer to the string with the date and time value. pDateTime [out] Pointer to a CTDATETIME type value to received the converted string date and time DateType [in] the date type. Valid types are listed "c-treeDB definitions".. TimeType [in] the time type. Valid types are listed in "c-treeDB definitions"..
Returns
ctdbStringToDateTime() returns CTDBRET_OK on success, or c-treeDB C error on failure. The possible errors associated with ctdbStringToDateTime() are: CTDBRET_NULARG (4007): Null argument not valid in pStr CTDBRET_INVDATE (4029): Invalid format in DateType CTDBRET_INVTYPE (4019): Invalid type in DateType or TimeType CTDBRET_ARGSMALL (4006): Buffer is too small (increase size)
See also
ctdbDateTimeToString(), ctdbStringToTime(), ctdbStringToDate()
FairCom Corporation
690
ctdbStringToMoney
Convert a string value to a CTMONEY type value.
Declaration
CTDBRET ctdbStringToMoney(pTEXT pStr, pCTMONEY pMoney)
Description
ctdbStringToMoney() converts from a string to CTMONEY. Use ctdbMoneyToString() to converts a CTMONEY value to a string. pStr [in] the pointer to the string. pMoney [out] the pointer to a CTMONEY type value.
Returns
ctdbStringToMoney() returns CTDBRET_OK on success, or c-treeDB C API error on failure. The possible errors associated with ctdbStringToMoney() are: CTDBRET_NULARG (4007): Null argument not valid in pStr CTDBRET_OVERFLOW (4038): Operation caused overflow
See also
ctdbMoneyToString()
www.faircom.com
All Rights Reserved
691
ctdbStringToNumber
Convert a CTNUMBER type value to a string.
Declaration
CTDBRET ctdbStringToNumber(pTEXT pStr, pCTNUMBER pNumber)
Description
ctdbStringToNumber() converts a string to a CTNUMBER. Use ctdbNumberToString() to convert from CTNUMBER to a string. pStr [in] the pointer to the string that will result from the conversion. pNumber [out] pointer to CTNUMBER.
Returns
ctdbStringToNumber() returns CTDBRET_OK on success, or c-treeDB C API error on failure. The possible errors associated with ctdbStringToNumber() are: CTDBRET_NULARG (4007): Null argument not valid in pStr CTDBRET_OVERFLOW (4038): Operation caused overflow
See also
ctdbNumberToString()
FairCom Corporation
692
ctdbStringToTime
Convert a time in string format to CTTIME packed format.
Declaration
CTDBRET ctdbStringToTime(pTEXT pStr, CTTIME_TYPE TimeType, pCTTIME pTime)
Description
ctdbStringToTime() converts a time in string format to CTTIME packed format. Use ctdbTimeToString() to convert a packed CTTIME into a string. pStr [in] the pointer to the string. TimeType [in] the time types. Valid types described in "c-treeDB definitions".. pTime [out] the pointer to a CTTIME value that will result from the conversion.
Returns
ctdbStringToTime() returns CTDBRET_OK on success, or c-treeDB C error on failure. The possible errors associated with ctdbStringToTime() are: CTDBRET_NULARG (4007): Null argument not valid in pStr CTDBRET_NOMEMORY (4001): Not enough memory CTDBRET_INVFORMAT (4028): Invalid format in TimeType CTDBRET_INVTIME (4033): Invalid packed CTTIME
See also
ctdbTimeToString()
www.faircom.com
All Rights Reserved
693
ctdbSwitchContext
Force an ISAM context switch.
Declaration
CTDBRET ctdbSwitchContext(CTHANDLE Handle)
Description
Force a switch to the c-tree Plus ISAM context indicated by the record handle. Each record handle has its own c-tree ISAM context id. When most c-treeDB record handling functions are called, they automatically perform a c-tree ISAM context switch. ctdbSwitchContext() may be useful before calling specific c-tree ISAM or low level calls to make sure the correct ISAM context is active before making those calls. Handle is a record handle. The handle must be a record handle. No other type of c-treeDB handle is acceptable.
Return
Value 0
c-tree Plus Programmer's Reference Guide for a complete listing of valid c-tree Plus error values.
Example
/* force a context switch */ if (ctdbSwitchContext(hRecord) != CTDBRET_OK) printf("ctdbSwitchContext failed\n"); /* call ResetRecord */ if (ResetRecord((COUNT)ctdbGetDatno(hRecord), SWTCURI)) printf("ResetRecord failed\n");
See also
ctdbSwitchInstance(), ctdbGetDatno(), ctdbGetIdxno(), ctdbGetIdxnoByName(), ctdbGetIdxnoByNumber()
FairCom Corporation
694
ctdbSwitchInstance
Force a c-tree Plus instance switch.
Declaration
CTDBRET ctdbSwitchInstance(CTHANDLE Handle)
Description
Force a switch to the c-tree Plus instance indicated by the Session handle. Each session handle has its unique c-tree instance id. When most c-treeDB C functions are called, they automatically perform a c-tree instance switch. ctdbSwitchInstance() may be useful before calling specific c-tree ISAM or low level calls to make sure the correct instance is active before making those calls. Handle is a Session handle. You can pass any c-treeDB handle to ctdbSwitchInstance().
Return
Value 0 Symbolic Constant CTDBRET_OK Explanation Successful function.
See "c-treeDB Errors and Return Values" for a complete listing of valid c-treeDB error codes and return values.
Example
/* declare and allocate the remote and local session handles */ CTHANDLE hRemote = ctdbAllocSession(CTSESSION_CTREE); CTHANDLE hLocal = ctdbAllocSession(CTSESSION_CTREE); /* logon to c-tree server using the remote session handle */ if (ctdbLogon(hRemove, "FAIRCOMS", "ADMIN", "ADMIN") != CTDBRET_OK) printf("Remote ctdbLogon failed\n"); /* logon to local session using the local session handle */ if (ctdbLogon(hLocal, "local", "ADMIN", "ADMIN) != CTDBRET_OK) printf("Local ctdbLogon failed\n"); /* perform a c-tree instance switch and call CtreeUserOperation function */ if (ctdbSwitchInstance(hRemote) != CTDBRET_OK) printf("ctdbSwitchInstance failed\n"); CtreeUserOperation("!mkdir faircom", buffer, sizeof(buffer);
See also
ctdbSwitchContext(), ctdbGetDatno(), ctdbGetIdxno(), ctdbGetIdxnoByName(), ctdbGetIdxnoByNumber()
www.faircom.com
All Rights Reserved
695
ctdbSystemFilterOff
Deletes a permanent system-wide record filter..
DECLARATION
CTDBRET ctdbDECL ctdbSystemFilterOff(CTHANDLE Handle, CTSYSFILTER mode);
DESCRIPTION
Deletes a permanent system-wide record filter. The table must be opened exclusive and the user must have file definition permission for the table. Handle is a table handle or any c-treeDB handle that can produce a table handle, such as a record, field, index or segment handle. For the parameter mode you must specify one of the following:
Permanent Filter Symbolic Constant Explanation Indicates you are deleting a system-wide read record filter. Indicates you are deleting a system-wide write record filter.
Indicates you are deleting both a system-wide read record filter and a system-wide write record filter.
RETURN
Value 0 Symbolic Constant CTDBRET_OK Explanation No error occurred.
See Appendix A for a complete listing of valid c-tree Plus error values.
EXAMPLE
/* delete a system wide filter */ if (ctdbSystemFilterOff(hTable, CTSYSFILTER_READ | CTSYSFILTER_WRITE)) != CTDBRET_OK) printf("ctdbSystemFilterOff failed\n");
SEE ALSO
ctdbSystemFilterOn()
FairCom Corporation
696
ctdbSystemFilterOn
Establishes a permanent system-wide data record filter.
DECLARATION
CTDBRET ctdbDECL ctdbSystemFilterOn(CTHANDLE Handle, CTSYSFILTER mode);
DESCRIPTION
Establishes a permanent system-wide data record filter, i.e,. the filter applies to all users, read and/or write record filter. Depending on the server file security setting, the table must be opened exclusive and the user must have file definition permission for the table. A table may have at most one read and one write system wide filter. A write filter will be called when data records are added, updated or deleted. Once a read or a write filter is established, it can only be deleted by calling the function ctdbSystemFilterOff(). Handle is a table handle or any c-treeDB handle that can produce a table handle, such as a record, field, index or segment handle. For the mode parameter, you must specify one of the following:
Permanent Filter Symbolic Constant Explanation Indicates you are setting a system-wide read record filter. Indicates you are setting a system-wide write record filter. Indicates you are setting both a system-wide read record filter and a system-wide write record filter.
System-wide filters must be callback filters. The actual callback evaluation takes place in a new callback function ctfiltercb_rowl() located in module ctclbk.c. There different levels of security settings when users modify data file definition resources such as IFIL and DODA. The c-tree Server can be configured for three different levels of data file resource security:
FILEDEF_SECURITY_LEVEL Explanation Lowest security setting. There is no protection as any user may add or delete data file definition resources. This setting may be used to keep the c-tree Server data compatible with legacy applications. Default security setting. Any user may add or delete data file definition resources, but the file must be opened exclusive. This default setting may be enough to keep the c-tree Server data compatible with most legacy applications. Highest security setting. A user must have file definition permission before a definition resource is added or deleted. The file must be opened exclusive. This setting is appropriate for applications that require the highest level of security and may cause compatibility problems with existing legacy applications.
LOW
MEDIUM
HIGH
RETURN
Value 0 Symbolic Constant CTDBRET_OK Explanation No error occurred.
See Appendix A for a complete listing of valid c-tree Plus error values.
www.faircom.com
All Rights Reserved
697
EXAMPLE
/* establish a new system wide filter */ if (ctdbSystemFilterOn(hTable, CTSYSFILTER_READ | CTSYSFILTER_WRITE)) != CTDBRET_OK) printf("ctdbSystemFilterOn failed\n");
SEE ALSO
ctdbSystemFilterOff()
FairCom Corporation
698
ctdbTimeCheck
Check if the given time is valid.
Declaration
CTDBRET ctdbTimeCheck(NINT hour, NINT minute, NINT second)
Description
ctdbTimeCheck() checks to see if the given time is valid. To check if the date is valid, use ctdbDateCheck(). hour is the hour, and it is supposed to be in the range 0 hour 23 minute minute 59 59 minute is the minute, and it is supposed to be in the range 0 second is the second, and it is supposed to be in the range 0
Returns
ctdbTimeCheck() returns CTDBRET_OK on success, or c-treeDB C API error code on failure. The possible errors associated with ctdbTimeCheck() are: CTDBRET_INVHOUR (4034): Invalid hour CTDBRET_INVMINUTE (4035): Invalid minute CTDBRET_INVSECOND (4036): Invalid second
See also
ctdbDateCheck()
www.faircom.com
All Rights Reserved
699
ctdbTimePack
Pack a time in the form hour:minute:second into a CTTIME form.
Declaration
CTDBRET ctdbTimePack(pCTTIME pTime, NINT hour, NINT minute, NINT second)
Description
ctdbTimePack() pack a time in the form hour:minute:second into a CTTIME form. pTime [out] the packed time. hour [in] the hour. minute [in] the minute. second [in] the second
Returns
ctdbTimePack() returns CTDBRET_OK on success, or c-treeDB C API error on failure.
See also
ctdbTimeUnpack(), ctdbDateTimePack()
FairCom Corporation
700
ctdbTimeToString
Convert a packed CTTIME into a string.
Declaration
CTDBRET ctdbTimeToString(CTTIME Time, CTTIME_TYPE TimeType, pTEXT pStr, VRLEN size)
Description
ctdbTimeToString() converts a packed CTTIME into a string. To convert a packed CTTIME to seconds, use ctdbTimeToSeconds(). Use ctdbStringToTime() to convert from a string to CTTIME. Use ctdbDateToString() to convert a packed CTDATE into a string. Time [in] the time, in CTTIME format. TimeType [in] the time type. Valid types are listed in "c-treeDB definitions".. pStr [out] the pointer to the string that will result from the conversion. size [in] the buffer size of the string.
Returns
ctdbTimeToString() returns CTDBRET_OK on success, or c-treeDB C API error on failure. The possible errors associated with ctdbTimeToString() are: CTDBRET_NULARG (4007): Null argument not valid in pStr CTDBRET_INVFORMAT (4028): Invalid format in TimeType CTDBRET_ARGSMALL (4006): Buffer is too small (increase size)
See also
ctdbTimeToSeconds(), ctdbStringToTime(), ctdbDateToString(), ctdbDateTimeToString()
www.faircom.com
All Rights Reserved
701
ctdbTimeUnpack
Unpack a CTTIME time into the form hour:minute:second.
Declaration
CTDBRET ctdbTimeUnpack(CTDATE Date, pNINT pyear, pNINT pmonth, pNINT pday)
Description
ctdbTimeUnpack() unpack a CTDATE date into the form day, month and year. Time [in] the packed date. phour [out] the hour. pminute [out] the minute psecond [out] the second
Returns
ctdbTimeUnpack() returns CTDBRET_OK on success, or c-treeDB C API error on failure.
See also
ctdbTimePack()
FairCom Corporation
702
ctdbUnlock
Releases all session-wide locks
Declaration
CTDBRET ctdbUnlock(CTHANDLE Handle)
Description
ctdbUnlock() releases all locks obtained with ctdbLock(). This is the same as calling ctdbLock() with the lock mode CTLOCK_FREE. To release locks in records obtained with ctdbLockRecord(), use ctdbUnlockRecord(). Handle [in] a Session or any other Handle. Notice that, if called inside a transaction, this free operation will result in the suspension of the locks, and not in their release. The locks will only be released when the transaction is finished with a call to ctdbCommit() or ctdbAbort(). If the locks are suspended, it means that new records read will not be locked. To restore the suspended locks, use ctdbLock() with one of the READ or WRITE lock modes (or the RESTORE options). If, for any special reason, the unused locks from a particular table must be released inside a transaction, ctdbUnlockTable() may be used. Unused locks are records that where locked but not updated/deleted/added.
Returns
ctdbUnlock() returns CTDBRET_OK on success, or c-treeDB C API error code on failure.
Example
if (ctdbIsLockActive(pSession)) ctdbUnlock(pSession);
See also
ctdbLock(), ctdbIsLockActive(), ctdbGetLockMode(), ctdbUnlockRecord(), ctdbUnlockTable()
www.faircom.com
All Rights Reserved
703
ctdbUnlockRecord
Unlock the current record.
Declaration
CTDBRET ctdbUnlockRecord(CTHANDLE Handle)
Description
ctdbUnlockRecord() unlocks the current record, provided the lock was obtained with ctdbLockRecord(). Use ctdbUnlockTable() to unlock all record locks obtained with ctdbLockRecord() within a given table. Handle [in] the record handle.
Returns
ctdbUnlockRecord() returns CTDBRET_OK on success, or c-treeDB C API error code on failure.
See also
ctdbLockRecord(), ctdbUnlock()
FairCom Corporation
704
ctdbUnlockResource
Release any locks held by resource.
DECLARATION
CTDBRET ctdbDECL ctdbUnlockResource(CTHANDLE resource);
DESCRIPTION
Unlocks a resource. The resource is only unlocked if it was previously locked by ctdbFirstResource(), ctdbNextResource(), ctdbFindResource() or ctdbFindResourceByName(). resource is a handle allocated by ctdbAllocHandle.
RETURN
ctdbUlnlockResource() returns CTDBRET_OK on success.
EXAMPLE
if (ctdbIsResourceLocked(hRes)) ctdbUnlockResource(hRes);
SEE ALSO
ctdbAllocResource, ctdbFreeResource, ctdbAddResource, ctdbDeleteResource, ctdbUpdateResource, ctdbFirstResource, ctdbNextResource, ctdbFindResource, ctdbFindResourceByName, ctdbGetResourceType, ctdbSetResourceType, ctdbGetResourceNumber, ctdbSetResourceNumber, ctdbGetResourceName, ctdbSetResourceName, ctdbGetResourceDataLength, ctdbGetResourceData, ctdbSetResourceData, ctdbIsResourceLocked
www.faircom.com
All Rights Reserved
705
ctdbUnlockTable
Releases all record locks associated with a table.
Declaration
CTDBRET ctdbUnlockTable(CTHANDLE Handle)
Description
ctdbUnlockTable() releases all locks associated with the specified table. ctdbUnlockTable() will unlock all table records obtained either with calls to ctdbLock() or to ctdbLockRecord(). Handle [in] the Table, Record, Field, Index or Segment Handle. If ctdbUnlockTable() is used inside a transaction, the lock mode is changed to CTLOCK_SUSPEND, and new locks are not acquired until a new call to ctdbLock() or to ctdbLockRecord() restore the locks. All unused locks from this particular table are released. Unused locks are records that where locked but not updated/deleted/added.
Returns
ctdbUnlockTable() returns CTDBRET_OK on success, or c-treeDB C API error code on failure.
See also
ctdbLockRecord(), ctdbUnlockRecord()
FairCom Corporation
706
ctdbUpdateCndxIndex
Add, change or delete the conditional expression associated with an index, given by number.
Declaration
CTDBRET ctdbUpdateCndxIndex(CTHANDLE Handle, NINT indexnbr, pTEXT cndexpr)
Description
ctdbUpdateCndxIndex() adds, changes or deletes the conditional expression associated with an index. After the conditional expression is successfully associated with the index, the index data is automatically rebuilt. To retrieve the conditional expression, use ctdbGetCndxIndex() or ctdbGetCndxIndexByName(). Handle [in] the Table Handle. indexnbr [in] the index number. cndexpr [in] string containing the conditional expression.
Returns
ctdbUpdateCndxIndex() returns CTDBRET_OK on success, or c-treeDB C API error code on failure.
See also
ctdbUpdateCndxIndexByName(), ctdbGetCndxIndex(), ctdbGetCndxIndexByName(), ctdbGetCndxIndexLength(), ctdbGetCndxIndexLengthByName()
www.faircom.com
All Rights Reserved
707
ctdbUpdateCndxIndexByName
Add, change or delete the conditional expression associated with an index, given by name.
Declaration
CTDBRET ctdbUpdateCndxIndexByName(CTHANDLE Handle, pTEXT indexname, pTEXT cndexpr)
Description
ctdbUpdateCndxIndexByName() adds, changes or deletes the conditional expression associated with an index, given by name. After the conditional expression is successfully associated with the index, the index data is automatically rebuilt. To retrieve the conditional expression, use ctdbGetCndxIndex() or ctdbGetCndxIndexByName(). Handle [in] the Table Handle. indexname [in] the index name. cndexpr [in] string containing the conditional expression.
Returns
ctdbUpdateCndxIndexByName() returns CTDBRET_OK on success, or c-treeDB C API error code on failure.
See also
ctdbUpdateCndxIndex(), ctdbGetCndxIndex(), ctdbGetCndxIndexByName(), ctdbGetCndxIndexLength(), ctdbGetCndxIndexLengthByName()
FairCom Corporation
708
ctdbUpdateCreateMode
Update the table create mode.
Declaration
CTDBRET ctdbUpdateCreateMode(CTHANDLE Handle, CTCREATE_MODE mode)
Description
ctdbUpdateCreateMode() updates the table create mode. ctdbUpdateCreateMode() changes critical file mode attributes, such as the level of transaction control. No check is made to determine if the mode change will damage data. No check is made if the new mode is valid. Note: Use this function with caution, as data may be lost. For instance, changing a data file from transaction processing to no transaction processing make automatic recovery unavailable. Handle [in] the Table Handle. mode [in] the new table create mode. It must be perfectly formed, as it will replace the current table create mode. Use the function ctdbGetTableCreateMode() to retrieve the current create mode and apply the changes on a fully qualified create mode. Update only the following create table modes: CTCREATE_PREIMG CTCREATE_TRNLOG CTCREATE_WRITETHRU CTCREATE_CHECKLOCK CTCREATE_CHECKREAD CTCREATE_HUGEFILE
Returns
ctdbUpdateCreateMode() returns CTDBRET_OK on success, or c-treeDB C API error code on failure.
See also
ctdbCreateTable()
www.faircom.com
All Rights Reserved
709
ctdbUpdatePadChar
Update the table pad and delimiter character resource.
Declaration
CTDBRET ctdbUpdatePadChar(CTHANDLE Handle, NINT padchar, NINT dmlchar, CTBOOL rebuild)
Description
ctdbUpdatePadChar() updates the table pad and delimiter character resource. The table must be opened exclusive to allow update of the resource. Handle [in] the Table Handle. padchar [in] the pad character dmlchar [in] the field delimiter character. rebuild [in] indicate if the table should be rebuilt. If rebuild is set to YES, every record is read and the fixed string fields (CT_FSTRING) are padded according to new padding strategy. Notice that this feature is not implemented yet, and no rebuild is done.
Returns
ctdbUpdatePadChar() returns CTDBRET_OK on success, or c-treeDB C API error code on failure.
See also
ctdbSetPadChar(), ctdbGetPadChar()
FairCom Corporation
710
ctdbUpdateResource
Update the contents of an existing resource.
DECLARATION
CTDBRET ctdbDECL ctdbUpdateResource(CTHANDLE resource, pVOID data, VRLEN size);
DESCRIPTION
ctdbUpdateResource() update an existing resource. You must call ctdbAllocResource() with specific resource type and number that will uniquely identify the resource being updated. resource is a handle allocated by ctdbAllocResource(). The Resource data 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. size indicate the number of bytes occupied by data.
RETURN
ctdbUpdateResource() returns CTDBRET_OK on success.
EXAMPLE
CTDBRET UpdateMyResource(CTHANDLE Handle, ULONG type, ULONG number, pTEXT name, pVOID data, VRLEN size) { CTDBRET Retval; CTHANDLE hRes = ctdbAllocResource(Handle, type, number, name); if (hRes) { if ((Retval = ctdbUpdateResource(hRes, data, size)) != CTDBRET_OK) printf("ctdbUpdateResource failed with error %d\n", Retval); ctdbFreeResource(hRes); } else { printf("Failed to allocate resource handle\n"); Retval = CTDBRET_NOMEMORY; } return Retval; }
SEE ALSO
ctdbAllocResource, ctdbFreeResource, ctdbAddResource, ctdbDeleteResource, ctdbFirstResource, ctdbNextResource, ctdbFindResource, ctdbFindResourceByName, ctdbGetResourceType, ctdbSetResourceType, ctdbGetResourceNumber, ctdbSetResourceNumber, ctdbGetResourceName, ctdbSetResourceName, ctdbGetResourceDataLength, ctdbGetResourceData, ctdbSetResourceData, ctdbIsResourceLocked, ctdbUnlockResource
www.faircom.com
All Rights Reserved
711
ctdbWriteRecord
Add a new record or update an existing record.
Declaration
CTDBRET ctdbWriteRecord(CTHANDLE Handle)
Description
ctdbWriteRecord() adds a new record or update an existing record. Use ctdbSetRecordBuffer() or the ctdbSetFieldAs() functions to set the buffer before writing the record. Handle [in] the record handle.
Returns
ctdbWriteRecord() returns CTDBRET_OK if successful, or the c-tree Plus error code on failure.
See also
ctdbAllocRecord(), ctdbReadRecord(), ctdbDeleteRecord(), ctdbSetRecordBuffer(), ctdbGetErrorIndex()
FairCom Corporation
712
ctdb_u16TOu8
Converts a UTF-16 string to a UTF-8 encoding.
DECLARATION
NINT ctu16TOu8(pWCHAR u16str, pTEXT u8str, NINT u8size);
DESCRIPTION
ctdb_u16TOu8() converts a UTF-16 encoded string to a UTF-8 Unicode string. The input strings are assumed to be terminated by the nul character. All output buffer sizes are specified in bytes.
RETURN
Value 0 153 446 Symbolic Constant NO_ERROR VBSZ_ERR BMOD_ERR Explanation No error occurred. Output buffer too small. Bad key segment mode.
See Appendix "c-tree Plus Error Codes" in the c-tree Plus Programmer's Reference Guide for a complete listing of valid c-tree Plus error values.
EXAMPLE
TEXT buffer[512]; switch (ctdb_u16TOu8(tableName, buffer, sizeof(buffer)) { case CTDBRET_OK: { printf("UTF-16 to UTF-8 conversion ok\n"); break; } case VBSZ_ERR: { printf("Conversion buffer is too small\n"); break; } case BMOD_ERR: { printf("Problem occurred during conversion\n"); break; } default: { printf("Unknown error code\n"); break; } }
SEE ALSO
ctdb_u8TOu16
www.faircom.com
All Rights Reserved
713
ctdb_u8TOu16
Converts an ASCII or UTF-8 encoded string to a UTF-16 string.
DECLARATION
NINT ctdb_u8TOu16(pTEXT u8str, pWCHAR u16str, NINT u16size);
DESCRIPTION
ctdb_u8TOu16() converts an ASCII or UTF-8 encoded string to a UTF-16 Unicode string. The input strings are assumed to be terminated by a NULL character. All output buffer sizes are specified in bytes.
RETURN
Value 0 153 446 Symbolic Constant Explanation No error occurred. Output buffer too small. Bad key segment mode.
See Appendix A for a complete listing of valid c-tree Plus error values.
EXAMPLE
WCHAR buffer[256]; switch (ctdb_u8TOu16("tablename", buffer, sizeof(buffer)) { case CTDBRET_OK: { printf("UTF-8 to UTF-16 conversion ok\n"); break; } case VBSZ_ERR: { printf("Conversion buffer is too small\n"); break; } case BMOD_ERR: { printf("Problem occurred during conversion\n"); break; } default: { printf("Unknown error code\n"); break; } }
SEE ALSO
ctdb_u16TOu8()
FairCom Corporation
714
Appendix A.
Please note that several of these error codes are not really errors, but rather indicators of an unsuccessful operation. For example, KDUP_ERR (2) occurs if you attempt to add an existing entry to an index that does not support duplicate key values. This is not an error, but a situation to which your application program must be prepared to react.
Value 0 2 3 4 Symbolic Constant NO_ERROR Explanation Successful operation. Key value already exists in index. Could not delete target key value since recbyt does not match associated data record position in index. Could not find target key value in index. No deletion performed. May indicate improper use of buffers during ReWriteRecord() Cannot call DeleteKeyBlind() with an index that supports duplicate keys.
5 6 7 -8
-9 10 11
12
13
FUNK_ERR
OpenIFile() cannot determine type of file. Version 3.3 files must be rebuilt
before using .
www.faircom.com
All Rights Reserved
715
Value 14
Symbolic Constant
Explanation File appears corrupt at open. This occurs if a file is updated; and the disk protocol is set at NOTFORCE; and CloseIFile() is not executed. Rebuild file. Data file has been compacted, but not rebuilt. Rebuild data file, but do not force rebuild. Could not create index file. Either no space is available on disk or filnam points to improper name. Could not create data file. Either no space is available on disk or filnam points to improper name. Tried to create existing index file. Tried to create existing data file. Key length too large for node size. There must be room for at least 3 key values per node. The node size is given by sect * 128 where sect is 3rd parameter. Cannot create data file with record length smaller than 5.
FCRP_ERR
15
16 17 18 19 20
21 22
DREC_ERR FNUM_ERR
filno out of range: 0 <= filno < fils, where fils is 2nd parameter. This error
may occur if c-tree Plus has not been initialized.
23 24 25 26 27 28 29 30
Illegal index member number. Could not close file. Usually indicates that memory is clobbered. Bad link in deleted node list. Rebuild file. File number (datno, keyno, or filno) is not in use. Data record position before 1st actual data record
recbyt exceeds logical end of file. If recbyt is correct, then data file header record may be incorrect. If so, rebuild data file.
Next record in delete chain of a fixed-length data file does not have 1st byte set to 0xff. Data file header record may be corrupt; if so, rebuild data file. Or C255 constant is incorrect: see ctcmpl.h.
31
DELFLG_ERR
32 33 34
recptr is NULL.
Could not find correct predecessor node. Should not show up in a single user system. Indicates that an index insertion was interrupted before completion. Rebuild index.
FairCom Corporation
716
Value 35
Symbolic Constant
Explanation
SEEK_ERR
lseek() failed in function ctio() (ctclib.c). Possible causes are: out of disk space, corrupted record position in file, or corrupted file descriptor.
Read failed in function ctio() (ctclib.c). Possible cause: corrupted data record position in file. Write failed in function ctio(). See 35 above. Could not convert a virtually opened file to an actually opened file. This might occur if your application uses up some file descriptors after a virtual file has been automatically closed. You can protect against this by lowering the MAXVFIL parameter in ctoptn.h.
36
37 38
39 40
FULL_ERR KSIZ_ERR
The 4-byte data record position (or node position) address space has been exhausted.
sect * 128 (where sect is 3rd InitCTree() parameter) was larger when index
was created. Buffers are too small for nodes.
41 42 43 44 45 46 47 48
UDLK_ERR DLOK_ERR FVER_ERR OSRL_ERR KLEN_ERR FUSE_ERR FINT_ERR FMOD_ERR FSAV_ERR LNOD_ERR UNOD_ERR
Could not unlock data record. If dummy lock file is in use, be sure it has a file mode of 3. Could not obtain data record lock. In a DOS system, be sure that the network is up or share is loaded. Current configuration parameters are inconsistent with the configuration parameters at the time of file creation. Data file serial number overflow. Index key length exceeds MAXLEN parameter. Change MAXLEN in ctoptn.h and recompile c-tree Plus. File number is already in use c-tree Plus has not been initialized A function has been called for the wrong type of file: e.g., a variable-length function is called for a fixed-length data file. Could not write file directory updates to disk during file extension. Could not lock index file node. Could not unlock index file node. If a dummy lock file is in use, be sure it has a file mode of 3. Variable-length and/or floating point keys disabled in ctoptn.h. The files file mode is inconsistent with the compile time options selected in ctoptn.h. Attempt to write a read only file.
49 50 51
52 53 54
www.faircom.com
All Rights Reserved
717
Value 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
Symbolic Constant
Explanation File deletion failed. File must be opened exclusive for delete. Proper lock is not held (ctCHECKLOCK/READ).
DLTF_ERR DLTP_ERR DADV_ERR KLOD_ERR KLOR_ERR KFRC_ERR CTNL_ERR LERR_ERR RSER_ERR RLEN_ERR RMEM_ERR RCHK_ERR RENF_ERR LALC_ERR BNOD_ERR TEXS_ERR TNON_ERR TSHD_ERR TLOG_ERR TRAC_ERR TROW_ERR TBAD_ERR TRNM_ERR TABN_ERR FLOG_ERR BKEY_ERR ATRN_ERR UALC_ERR IALC_ERR
LoadKey() called with incorrect key number. You cannot continue. LoadKey() called with key out of order. You may skip this key and
continue. Percent out of range. NULL file control block detected during I/O. File must be opened exclusively. Start file/log file serial number error. Checkpoint past end of log file. Not enough memory during transaction processing. Log file entry failed to find checkpoint. Could not rename file. Could not allocate memory for control list. Node does not belong to index. Transaction already pending. No active transaction. No space for shadow buffer.
FairCom Corporation
718
Symbolic Constant
Explanation Maximum users exceeded. Attempt to reduce write lock to read lock after update. Dead lock detected. System is busy: files in use. Linked list memory allocation error. Memory allocation during tran processing. Could not create queue. Queue write error. Queue memory error during write. Queue read error. Pending error: cannot save or commit tran. Could not start task. Start-file/log open error. Bad user handle. Bad transaction mode. transaction type / mode conflict. No current ISAM record for data file isam_fil. Could not satisfy ISAM search request for index isam_fil. The following 4 items are the most 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 Programmers Guide. Not calling TransformKey() on target. Refer to TransformKey in the Function Reference Guide Improper segment mode. Review Key Segment Modes in the c-tree Plus Programmers Guide.
MUSR_ERR LUPD_ERR DEAD_ERR QIET_ERR LMEM_ERR TMEM_ERR NQUE_ERR QWRT_ERR QMRT_ERR QRED_ERR PNDG_ERR STSK_ERR LOPN_ERR SUSR_ERR BTMD_ERR TTYP_ERR ICUR_ERR INOT_ERR
102
INOD_ERR
ISAM parameter file does not exist. Be sure that filnam parameter points to correct name. isam_fil value is undefined. Could not read ISAM parameter file Initialization record. isam_fil is undefined. Be sure that parameter file is not empty, and that the correct short integer input conversion character has been specified in ctoptn.h.
103
IGIN_ERR
www.faircom.com
All Rights Reserved
719
Value 104
Symbolic Constant
Explanation Number of files opened exceeds fils parameter at initialization. Increase fils. Optionally change ctMAXFIL in ctoptn.h. isam_fil is undefined. Could not undo a rejected ISAM update. Data file must be rebuilt. (During the rebuild, look for records with rejected duplicate key values.) Could not read ISAM parameter file Data File Description record for isam_fil. Be sure parameter file is consistent with RTREE setting in ctoptn.h. Too many indices for data file number isam_fil in ISAM parameter file. Change MAX_DAT_KEY in ctoptn.h.
IFIL_ERR
105
IUND_ERR IDRI_ERR
106
keyno for index file member out of sequence. keyno must equal host index file keyno plus member number.
Too many key segments defined in ISAM parameter file for index number isam_fil. Change MAX_KEY_SEG in ctoptn.h. Be sure that parameter file is consistent with RTREE setting in ctoptn.h. Could not read ISAM parameter file Key Segment Description record for index number isam_fil. Could not read ISAM parameter file Index File Description record. isam_fil indicates the relative index number for an unspecified data file. (ctENABLE) found pending locks. No space left in c-tree Pluss internal lock list. 1st byte of fixed-length data record found by ISAM routine equals delete flag. Sum of key segment lengths does not match key length for index number isam_fil. Bad mode parameter. Could not read ISAM parameter file Index Member record. NextInSet or PreviousInSet called with a keyno that does not match keyno in last call to FirstInSet or . FirstInSet called for numeric key type. Not enough dynamic memory for record buffer in ctrbld.c. Tried to update data with ctISAMKBUFhdr on. Attempt to change between fixed and variable-length records during rebuild. Once a data file is created, its record length characteristic cannot be changed. A variable-length data record is not preceded by a valid record mark. The file is apparently corrupted. Number of indices in index file does not match IFIL structure in call to OpenIFile() or the parameter file specified by .
FairCom Corporation
110 111 112 113 114 115 116 117 118 119 120 121 122
ISRC_ERR IKRI_ERR IPND_ERR INOL_ERR IRED_ERR ISLN_ERR IMOD_ERR IMRI_ERR SKEY_ERR SKTY_ERR RRLN_ERR KBUF_ERR RMOD_ERR
123 124
RVHD_ERR INIX_ERR
720
Symbolic Constant
Explanation c-tree Plus is already initialized via a previous call to , , , or . Bad directory path get. Could not send request. SeeClient/Server VDP Errors in the c-tree Plus Programmers Reference Guide for more information. Could not receive answer. See Client/Server VDP Errors for more information. c-tree Plus not initialized. NULL file name pointer in . File name length exceeds message size. No room for application message buffer. Could not identify Server. Could not get Servers message id. Could not allocate application id. Could not get application message status. Could not set application message size. Could not get rid of application message. Badly formed file name. Variable record length exceeds 65,529 bytes. Required message size exceeds maximum. Application MAXLEN > Servers MAXLEN ctoptn.h. Communications handler not installed. Application could not id output queue. No message space. Was login ok? Could not update available space information in variable-length data file. Record pointed to by available space information is not marked deleted in variable-length data file. Attempt to write a variable-length record into a file position which is too small for the record. Variable-length passed to AddVRecord() is less than minimum record length established at file creation. Server is shutting down. Could not shut down; transactions pending. Could not extend logfile.
IINT_ERR ABDR_ERR ARQS_ERR ARSP_ERR NINT_ERR AFNM_ERR AFLN_ERR ASPC_ERR ASKY_ERR ASID_ERR AAID_ERR AMST_ERR AMQZ_ERR AMRD_ERR ABNM_ERR VMAX_ERR AMSG_ERR SMXL_ERR SHND_ERR QMEM_ERR ALOG_ERR VDLK_ERR VDLFLG_ERR VLEN_ERR VRLN_ERR SHUT_ERR STRN_ERR LEXT_ERR
128
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
www.faircom.com
All Rights Reserved
721
Value 153 154 155 156 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
Symbolic Constant
Explanation Buffer in call to ReReadVRecord() is too small for the variable-length record. Attempt to read (R) a zero length record from a variable-length data file. Native system failure. Timeout error.
VBSZ_ERR VRCL_ERR SYST_ERR NTIM_ERR VFLG_ERR VPNT_ERR ITIM_ERR SINA_ERR SGON_ERR SFRE_ERR SFIL_ERR SNFB_ERR SNMC_ERR SRQS_ERR SRSP_ERR TCRE_ERR SFUN_ERR SMSG_ERR SSPC_ERR SSKY_ERR SSID_ERR SAMS_ERR SMST_ERR SMQZ_ERR SINM_ERR SOUT_ERR IKRU_ERR IKMU_ERR IKSR_ERR IDRU_ERR
FairCom Corporation
722
Value 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 400 401 402 403 404 405 406 407
Symbolic Constant
Explanation Multiple set buffer space already allocated. Not enough dynamic memory for multiple sets. Set number out of range in . Null buffer pointer in r-tree. Null target buffer pointer in r-tree. JOINS_TO skip condition in r-tree. JOINS_TO error condition in r-tree. JOINS_TO null fill condition in r-tree. IS_DETAIL_FOR skip condition in r-tree. IS_DETAIL_FOR error condition in r-tree. IS_DETAIL_FOR null fill condition in r-tree. Could not get dynamic memory for r-tree data field symbolic names. Exceeded RETRY_LIMIT on error 160 in r-tree. Could not get memory for IFIL block. Improper IFIL block. Key segment refers to schema but no schema is defined. Resource already enabled. Resources not enabled File must be exclusive to enable resource. Empty resource id. Output buffer to small. Resource id already added. Bad resource search mode. Attempt to get non-resource info. Can occur on fixed-length file with numeric value in first position. See IMPORTANT - Data Record Delete Flag for more information. Resource not found. User not active. Not a superfile. Attempt to create open superfile member. Superfile host not opened. Cannot nest superfiles.
ISDP_ERR ISAL_ERR ISNM_ERR IRBF_ERR ITBF_ERR IJSK_ERR IJER_ERR IJNL_ERR IDSK_ERR IDER_ERR IDNL_ERR IDMU_ERR ITML_ERR IMEM_ERR BIFL_ERR NSCH_ERR RCRE_ERR RNON_ERR RXCL_ERR RZRO_ERR RBUF_ERR RDUP_ERR RCSE_ERR RRED_ERR
www.faircom.com
All Rights Reserved
723
Value 415 416 417 418 419 420 421 422 423 424 425
Symbolic Constant
Explanation Illegal AddKey() to superfile. Illegal to superfile. Superfile created with different index node size. Superfile created with maximum name length exceeding current maximum. Host superfile does not support recovery. Key update with pending transaction. Filter not supported. Probably an invalid value in mode parameter of . Function not supported. Probably an invalid value in mode parameter of . Incomplete batch. You specified BAT_COMPLETE in a DoBatch() call. Add list error. Internal processing problem. May be a memory overwrite. Batch already in progress. You made a call to DoBatch() to open a new batch before you have completed the prior one. Make a call with a mode of BAT_CAN first. No batch active. You are calling DoBatch() with a mode of BAT_CAN or BAT_NXT. Status info already returned. You are making two consecutive DoBatch() calls looking just for status information. No more info.
SADD_ERR SDEL_ERR SPAG_ERR SNAM_ERR SRCV_ERR TPND_ERR BTFL_ERR BTFN_ERR BTIC_ERR BTAD_ERR BTIP_ERR
426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
BTNO_ERR BTST_ERR BTMT_ERR BTBZ_ERR BTRQ_ERR LAGR_ERR FLEN_ERR SSCH_ERR DLEN_ERR FMEM_ERR DNUM_ERR DADR_ERR DZRO_ERR DCNV_ERR DDDM_ERR DMEM_ERR DAVL_ERR
bufsiz is too small for a single record. You need a larger buffer for this file.
request is a NULL pointer. Aggregate/serialization lock denied. Fixed-length string requires len in DODA. Segment definition inconsistent with schema. Very long def block not supported. File def memory error. Bad def number.
FairCom Corporation
724
Value 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 498 499
Symbolic Constant
Explanation File length discrepancy. Could not create file during dump recovery. Not enough data to assemble key. Invalid key mode. You must be the owner of this file. File definition permission denied. ADMIN has opened file. Cannot delete file. Invalid user id when logging on Server. Invalid password when logging on Server. Server could not process user/acct info. Invalid Server name. Service not supported. Using an option unavailable to this library. User does not belong to group. Group access denied. File password invalid. Write permission not granted. Delete permission denied Resource not enabled. Bad permission flag. No superfile directory found during CTSBLD() processing. File does not have unique Server/File number. ISAM level logon not performed. Incremental Index: dnumidx < 1. Incremental Index: dfilno not an ISAM file. Incremental Index: aidxnam NULL for 1st. Incremental Index: active tran not allowed. Negative I/O request. Guest logons disabled. Old log file found during log create. Mismatch between recovery log and file id.
DSIZ_ERR DCRE_ERR SDAT_ERR BMOD_ERR BOWN_ERR DEFP_ERR DADM_ERR LUID_ERR LPWD_ERR LSRV_ERR NSRV_ERR NSUP_ERR SGRP_ERR SACS_ERR SPWD_ERR SWRT_ERR SDLT_ERR SRES_ERR SPER_ERR SHDR_ERR UQID_ERR IISM_ERR IINI_ERR IIDT_ERR IINM_ERR IITR_ERR NGIO_ERR LGST_ERR NLOG_ERR FIDD_ERR
www.faircom.com
All Rights Reserved
725
Value 500 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519
Symbolic Constant
SRFL_ERR SRIO_ERR SRIN_ERR DSRV_ERR RFCK_ERR ILOP_ERR DLOP_ERR SBLF_ERR CQUE_ERR OIFL_ERR GNUL_ERR GNOT_ERR GEXS_ERR IEOF_ERR
Could not open save/restore file. Could not process save/restore file. Save/restore inconsistency. Duplicate Server. Active chkpnt at start of roll-forward. Index nodes form illegal loop: rebuild. Data file loop detected.
Attempt to update index with inconsistent transaction number. If encountered, compact and rebuild the file to resolve the error. Could not allocate memory for the Streettalk login message buffer. Userid in InitISAM() does not match current login id. Index must be rebuilt. See CTSTATUS.FCS. Key segment length error. System checkpoints terminated. Client does not match server. Index reorg entry error.
FairCom Corporation
726
Value 532 533 534 535 536 537 538 -539 540 541 542 543 544 545 546 547 548 549 550
Symbolic Constant
Explanation
ASAV_ERR MTRN_ERR OTRN_ERR REGC_ERR AREG_ERR TCOL_ERR PIOT_ERR BFIL_COD PNUL_ERR LWRT_ERR MCRE_ERR MOPN_ERR MCLS_ERR MDLT_ERR MWRT_ERR MSAV_ERR MRED_ERR MHDR_ERR MSKP_ERR MNOT_ERR MSEG_ERR FBEG_ERR
www.faircom.com
All Rights Reserved
727
Value 554
Symbolic Constant
Explanation Inconsistent SerialNum defn info. It is inappropriate (regardless of partitioned files or not) to use PRMIIDX to add indices that use SRLSEG if SRGSEG based indices do not already exist. First, a SRLSEG index requires space in the data record. Second, none of the existing records would have SRLSEG data already in place, even if space had been reserved. ISRL_ERR (554) is returned when PRMIIDX attempts to add indices with SRLSEG when SRLSEG has not already been used.
ISRL_ERR
555 556 557 558 559 560 561 562 563 570 571 572 573 574 575 576 -587 588 589 590 591 592 593 -594
PREA_ERR PWRT_ERR CWRT_ERR PSAV_ERR CSAV_ERR SMON_ERR DDMP_BEG DDMP_END DDMP_ERR RCL1_ERR RCL2_ERR RCL3_ERR RCL4_ERR RCL5_ERR RCL6_ERR RCL7_ERR CPND_COD CPND_ERR LADM_ERR NCON_ERR OCON_ERR ECON_ERR XUSR_ERR XUSR_COD
Could not read primary files, so it is switching to mirrored files. Could not write primary files, so it is switching to mirrored files. Could not write mirror files, so it is suspending mirrored files. Could not save primary files, so it is switching to mirrored files. Could not save mirror files, so it is suspending mirrored files. Only one of each monitor at a time. SYSMON: dynamic dump begins. SYSMON: dynamic dump ends. SYSMON: dynamic dump ends (errors). Incomplete compression. Index rebuild required. Incomplete compression and index rebuild required. Primary/mirror files out-of-syncronization. Copy good file over bad. Incomplete compression and primary/mirror files out-of-syncronization. Index rebuild required and primary/mirror files out-of-syncronization. Incomplete compression and index rebuild required and primary/mirror files out-of-syncronization. Close/delete deferred: pending transaction. Attempt to close or delete file with pending transaction. Member of ADMIN group required. Could not find ISAM context ID. Old context ID. Call . Context ID exists. Non-ADMIN user blocked from log on. Users in SEC_BLOCK class logged on.
FairCom Corporation
728
Value 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623
Symbolic Constant
Explanation varlen too small in . Missing information. Could not initialize expression. Could not evaluate conditional expression. Dynamic Dump extent error. No more client threads.
CLEN_ERR CMIS_ERR CINI_ERR CVAL_ERR DEXT_ERR CTHD_ERR VRFY_ERR CMEM_ERR FLEX_ERR FINC_ERR KSRL_ERR DCOD_ERR RCOD_ERR IAIX_ERR LTPW_ERR HNUL_ERR HLOG_ERR HSTR_ERR HONE_ERR HMAP_ERR HIDX_ERR HACT_ERR HNOT_ERR HENT_ERR HZRO_ERR HSIZ_ERR HTYP_ERR HMID_ERR HMEM_ERR
www.faircom.com
All Rights Reserved
729
Symbolic Constant
Explanation Net change only applies to specific match of key or record position. Must specify exactly one matching criteria: ctHISTpos or ctHISTkey or one or both of ctHISTuser and ctHISTnode. Encountered an UNDTRAN (undo committed transaction) going forward. Must completely restart this set of history calls (i.e. repeat the first search call and subsequent search calls: the undone transaction will be ignored). Unknown type of request. Must specify filno. Could not initialize internal file ID: preserve files and contact FairCom. Unexpected length in log entry. Could not get ctSS_LOCK on file User lost locks found on close NULL plen (pointer to size). Negative length specified. Could not create thread synchronization object. Thread synchronization object get failed. Thread synchronization object rel failed. Queue message truncated to fit. Semaphore must be initialized with count > 0. Semaphore already initialized. Thread synchronization object cls failed. Must use exact file name. Accessing a file pending delete Reversible TRANDEP delete File number changed after deferred close. Superfile member/host TRANDEP specification conflict No support beyond 2 GB No support beyond 4 GB Duplicate keys purged and logged. Could not process duplicate key log. Duplicate keys rejected and listed. Attempt to exceed mapped lock limit.
627 628 629 630 631 -632 633 634 635 636 637 638 639 640 641 642 643 -644 645 646 -647 -648 650 651 652 653
HUNK_ERR HFIL_ERR HTFL_ERR HUNX_ERR SSLO_ERR LLOK_COD NPLN_ERR NLEN_ERR TSYC_ERR TSYF_ERR TSYR_ERR TQUE_ERR TZRO_ERR TINT_ERR TSYX_ERR EXCT_ERR DPND_ERR RDEL_COD CHGF_ERR SDEP_ERR E2GB_COD E4GB_COD DUPJ_ERR DUPX_ERR DUPL_ERR MAPL_ERR
FairCom Corporation
730
Value 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684
Symbolic Constant
Explanation Record length too long for log size. Could not reopen using freopen(). Transaction log header is bad. Could not create copy file. Could not write copy file. Could not read entire original file. Rebuild complete, but failed mirror copy. Failed process duplicate log and copy mirror. Duplicate key purged, but could not copy mirror. Duplicate key rejected, but could not copy mirror. Primary log (or start) file failed. Mirrored log (or start) file failed. incompatible log format attempt to exceed max file size large page size not a multiple of 16K inconsistent XCREblk node sectors too small for huge file non-zero high long with non-huge file inconsistency: file attr & sys version extended header bad signature additional file segments needed file segments not supported could not open segment cannot directly operate on seg def bad file segment name bad file segment size could not create file segment could not process segment header seg resource cannot move seg update invalid, see CTSTATUS.FCS segment update already in progress
TLNG_ERR FREO_ERR LHDR_ERR CPYF_ERR CPYW_ERR CPYR_ERR CPYB_ERR CPYX_ERR CPYJ_ERR CPYL_ERR LPRI_ERR LMIR_ERR LFRM_ERR MAXZ_ERR LRGN_ERR XCRE_ERR HMIN_ERR XOVR_ERR HDR8_ERR SIG8_ERR SEGM_ERR SEGS_ERR SEGO_ERR SEGD_ERR SEGN_ERR SEGZ_ERR SEGC_ERR SEGH_ERR SEGL_ERR SEGU_ERR SEGX_ERR
www.faircom.com
All Rights Reserved
731
Value 685 686 687 688 689 690 691 692 693 694 695 696 697 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717
Symbolic Constant
Explanation i/o on segmented file terminated segment definition too large unexpected value during recovery pending segment mismatch 1st & 2nd headers out of sync bad request header CheckSum bad response header CheckSum bad request (to server) CRC bad response (from server) CRC no Unicode support could not get work buffer for blk I/O
SEGF_ERR SEGR_ERR SEGQ_ERR SEGP_ERR SEQ8_ERR CREQ_ERR CRSP_ERR CRCQ_ERR CRCP_ERR NUNC_ERR BSPC_ERR SEGK_ERR DSPC_ERR OSEG_ERR CSEG_ERR ASEG_ERR HSEG_ERR SSEG_ERR DSEG_ERR NSEG_ERR USEG_ERR MBSP_ERR MBNM_ERR MBFM_ERR DIDX_ERR PLOW_ERR PHST_ERR PMBR_ERR PNOT_ERR PXPR_ERR POVR_ERR
FairCom Corporation
732
Value 718 719 720 721 722 723 724 725 -726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748
Symbolic Constant
Explanation partition member in use partition member pending purge partition member purged partition member archived bad partition host list must retry operation bad current ISAM position for host
PUSD_ERR PPND_ERR PPRG_ERR PARC_ERR PLST_ERR PTRY_ERR PCRP_ERR PVRN_ERR PPRG_COD PFMD_ERR PSUP_ERR PUNQ_ERR PHGH_ERR PRIK_ERR UMOD_ERR PMOP_ERR EXTH_ERR CUNF_ERR AOVR_ERR PMTC_ERR MINT_ERR FFLT_ERR DDCR_ERR DDDR_ERR S6BT_ERR SFHI_ERR FREL_ERR R6BT_ERR ACHN_ERR RSYN_ERR REXT_ERR
www.faircom.com
All Rights Reserved
733
Value 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779
Symbolic Constant
Explanation bad parameter value different ICU version, rebuild index checkpoint memory inconsistency more than one log set in transaction cannot RST/CLR past special savepoint only Q creator can perform operation a system queue is required server is not activated must uninit c-tree (STPUSR) only notifications to queue wrong queue instance SYSMON interrupted / cancelled no active SYSMON no range defined for index segment out of range range defined but no FRS/LST RNG comm I/O has been blocked-ctcomioblk has been set by user insufficient file handles and could not find file to close for virtual processing fixed length record offset not aligned commit lock error: make sure record update performed with lock unexpected CMTLOK unlock failure: call FairCom cannot turn off file's tran support in middle of transaction if file updated compatibility option not enabled platform does not support compatibility option superfile host & member must have same REPLICATION attribute superfile members must all be closed no UNQKEY support for REPLICATION operation not supported for SUPERFILES cannot unregister another client's replication instance the specified replication instance name is not registered the specified replication instance name is already registered
PBAD_ERR ICUV_ERR CHKM_ERR LSET_ERR SPCL_ERR QOWN_ERR SQUE_ERR NACT_ERR STPU_ERR QNOT_ERR QUIN_ERR XMON_ERR NMON_ERR NRNG_ERR ORNG_COD CRNG_ERR CIOB_ERR VCLS_ERR FALG_ERR CMLK_ERR CULK_ERR XTRN_ERR COMP_ERR PLAT_ERR SREP_ERR SMEM_ERR UNQK_ERR SUPR_ERR REPU_ERR REPI_ERR REPR_ERR
FairCom Corporation
734
Value 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 -795 796 797 798 799 800 801 802 803 804 805 806 807 808 809
Symbolic Constant
Explanation cannot attach to replication instance with active connection this replication connection already has a registered instance name decompression error: unexpected output length incremental index: cannot add permanent indices while temporary indices exist LDAP initialization failed error connecting to LDAP server error binding to LDAP server LDAP user authentication failed error checking user's LDAP groups member of c-tree login group required strict serializer must be in transaction to access record strict serializer cannot keep locks external server shutdown disabled partial record rewrite has keys spanning partial record and remaining region of record Tried to update data with missing key buffer contents recursive ctptsema() call for open or create file copy failed immediate dump restore failed file is blocked, retry later file block cleared: close/reopen file
REPA_ERR REPC_ERR UCMP_ERR IITI_ERR LDPI_ERR LDPC_ERR LDPB_ERR LDPA_ERR LDPG_ERR LGRP_ERR LSST_ERR LSSK_ERR XSHT_ERR PKSP_ERR XBUF_ERR VTSM_COD FCPY_ERR DRST_ERR FBLK_ERR FBLK_RDO TDEP_ERR FBLK_PND FBLK_SUP LNEW_ERR SETO_ERR MSTK_ERR KCON_ERR MSTK_COD TRQS_ERR TRSP_ERR
www.faircom.com
All Rights Reserved
735
Value 810 811 812 813 814 815 816 817 818 819 820 821 822 -823 824 825 826 827 -828 -829 830 831 -832 833 834
Symbolic Constant
Explanation status log write failure update only from internal API unexpected zero node size in header unexpected state for user block obj thread did not have ctFBactive set
SLOG_ERR IAPI_ERR ZRCZ_ERR UBLK_ERR FBLK_ACT FBLK_NTF QTUQ_ERR QTAB_ERR QTFB_ERR QTBB_ERR QTBK_PND MLAB_ERR MLHG_ERR TRAB_COD MIMP_ERR QTOP_ERR QBAD_ERR UTIM_OUT ICUV_COD ICUV_REB TTAB_ERR TTHG_ERR ITMP_COD XNOD_ERR XCON_ERR
sysiocod value when KDUP_ERR occurs on a temporary index and error is ignored.
FairCom Corporation
736
Value 838 839 -840 841 842 843 844 845 846 847
Symbolic Constant
Explanation
sysiocod when read only, admin open request blocked by on the fly CLNIDXX.
www.faircom.com
All Rights Reserved
737
Appendix B.
Value 0 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027
This table lists the possible c-treeDB errors that may be encountered during the usage of c-treeDB.
Symbolic Constant CTDBRET_OK
CTDBRET_BASE CTDBRET_NOMEMORY CTDBRET_NULHANDLE CTDBRET_NOTSESSION CTDBRET_INVARG CTDBRET_INDEXRANGE CTDBRET_ARGSMALL CTDBRET_NULARG CTDBRET_ARGNUL CTDBRET_NOTOPEN CTDBRET_NOTDATABASE CTDBRET_ISACTIVE CTDBRET_NOTACTIVE CTDBRET_NOTTABLE CTDBRET_NOSUCHFIELD CTDBRET_CANTDELETE CTDBRET_FIELDEXIST CTDBRET_NOTFIELD CTDBRET_NOTINDEX CTDBRET_INVTYPE CTDBRET_NOTSEGMENT CTDBRET_DATABASEEXIST CTDBRET_TABLEEXIST CTDBRET_NOSUCHTABLE CTDBRET_NOTRECORD CTDBRET_INTERNAL CTDBRET_INVFIND CTDBRET_NODATA
www.faircom.com
All Rights Reserved
739
Value 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058
Symbolic Constant
Explanation Invalid date or time format Invalid date Invalid date day Invalid date month Invalid date year Invalid packed CTTIME Invalid hour Invalid minute Invalid second Invalid morning/evening indicator. Operation causes Overflow Operation causes Underflow Division by zero error Invalid DateTime Cant perform type conversion Argument is too big Path does not exist Unknown index number Not found Invalid segment mode Table has no indices Invalid segment number Invalid ISAM context handle Index name already in use Partial field data read Invalid index name Feature not supported Invalid lock mode Record not locked Record is not locked for writes Dictionary handle not allocated
CTDBRET_INVFORMAT CTDBRET_INVDATE CTDBRET_INVDAY CTDBRET_INVMONTH CTDBRET_INVYEAR CTDBRET_INVTIME CTDBRET_INVHOUR CTDBRET_INVMINUTE CTDBRET_INVSECOND CTDBRET_INVAMPM CTDBRET_OVERFLOW CTDBRET_UNDERFLOW CTDBRET_DIVBYZERO CTDBRET_INVDATETIME CTDBRET_CANTCONVERT CTDBRET_TOOBIG CTDBRET_NOSUCHPATH CTDBRET_NOSUCHINDEX CTDBRET_NOTFOUND CTDBRET_INVSEGMODE CTDBRET_NOINDEX CTDBRET_NOSUCHSEGMENT CTDBRET_INVICON CTDBRET_INDEXEXIST CTDBRET_MOREDATA CTDBRET_NOINDEXNAME CTDBRET_NOTSUPPORTED CTDBRET_INVLOCKMODE CTDBRET_NOLOCK CTDBRET_NOWRITELOCK CTDBRET_NOTDICT
FairCom Corporation
740
Value 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088
Symbolic Constant
Explanation Not yet implemented Invalid number Invalid number precision Invalid number scale Record buffer not large enough recbyt index cannot be deleted rowid index cannot be deleted Table has no rowid index Cannot create a file (dupdb) Cannot copy a file (dupdb) Cannot restore lock Invalid isolation level Conditional expression evaluates to false Conditional expression parser error Invalid type mixup Unknown field name Internal yacc error Memory allocation failed Stack overflow Stack underflow Invalid execution node Division by zero No record schema No record buffer Not enough data Invalid session type Invalid alter table action Records are different Invalid operator Table was open read only
CTDBRET_NOTYET CTDBRET_INVNUMBER CTDBRET_INVPREC CTDBRET_INVSCALE CTDBRET_INVRECBUF CTDBRET_CANTDELRECBYT CTDBRET_CANTDELROWID CTDBRET_NOROWID CTDBRET_CANCREATE CTDBRET_CANTCOPY CTDBRET_NOTSUSPENDED CTDBRET_INVISOLEVEL CTDBRET_CNDXFALSE CTDBRET_CNDXSYNTAX CTDBRET_CONDXTYPE CTDBRET_CNDXFIELD CTDBRET_CNDXINTERNAL CTDBRET_CNDXMEMORY CTDBRET_CNDXOVERFLOW CTDBRET_CNDXUNDERFLOW CTDBRET_CNDXEXEC CTDBRET_CNDXDIVISION CTDBRET_CNDXNOSCHEMA CTDBRET_CNDXNORECBUF CTDBRET_CNDXSDAT CTDBRET_INVSESSIONTYPE CTDBRET_INVALTERACTION CTDBRET_DIFFERENT CTDBRET_INVOPERATOR CTDBRET_READONLY
www.faircom.com
All Rights Reserved
741
Index
A
Atomicity............................................................... 138 Automatic recovery .............................................. 139
B
Bigint data type .................................................... 134 Boolean data type ................................................ 131 BuildKey ............................................................... 166
C
Compatibility......................................................... 183 c-tree Plus ISAM .............................................. 183 c-treeSQL......................................................... 183 field mapping with SQL .................................... 183 low-level data files............................................ 183 Count data type.................................................... 131 CTDB_DATABASE_CONNECT .......................... 152 CTDB_DATABASE_DISCONNECT .................... 152 CTDB_ON_DATABASE_CONNECT................... 154 CTDB_ON_DATABASE_DISCONNECT............. 154 CTDB_ON_RECORD_AFTER_BUILD_KEY152, 166 CTDB_ON_RECORD_AFTER_READ ........ 152, 164 CTDB_ON_RECORD_AFTER_WRITE....... 152, 168 CTDB_ON_RECORD_BEFORE_BUILD_KEY .. 152, 165 CTDB_ON_RECORD_BEFORE_READ ..... 152, 163 CTDB_ON_RECORD_BEFORE_WRITE.... 152, 167 CTDB_ON_RECORD_INIT ......................... 152, 162 CTDB_ON_RECORD_RESET .................... 152, 163 CTDB_ON_SESSION_LOGON................... 152, 153 CTDB_ON_SESSION_LOGOUT................. 152, 153 CTDB_ON_TABLE_ALTER......................... 152, 160 CTDB_ON_TABLE_CLOSE ........................ 152, 157 CTDB_ON_TABLE_GET_DODA................. 152, 158 CTDB_ON_TABLE_GET_EXT_INFO ......... 152, 159 CTDB_ON_TABLE_GET_RECLEN ............ 152, 159 CTDB_ON_TABLE_GET_SCHEMA ........... 152, 157 CTDB_ON_TABLE_OPEN .......................... 152, 155 CTDB_ON_TABLE_REBUILD..................... 152, 161 ctdbClearAllCallback ............................................ 170 ctdbClearCallback ................................................ 170 ctdbConnect ......................................................... 154 ctdbGetCallback................................................... 170 ctdbGetRebuildProgress...................................... 161 ctdbLogon ............................................................ 153 ctdbOpenTable..................................................... 155 ctdbsdk.h and c-treeDB return codes .................. 152 ctdbSetCallback ................................................... 170 ctdbUNICODE...................................................... 172 c-treeDB callbacks CTDB_DATABASE_CONNECT .................. 152
www.faircom.com
All Rights Reserved
CTDB_DATABASE_DISCONNECT ............ 152 CTDB_ON_DATABASE_CONNECT ........... 154 CTDB_ON_DATABASE_DISCONNECT ..... 154 CTDB_ON_RECORD_AFTER_BUILD_KEY .......................................................... 152, 166 CTDB_ON_RECORD_AFTER_READ. 152, 164 CTDB_ON_RECORD_AFTER_WRITE152, 168 CTDB_ON_RECORD_BEFORE_BUILD_KEY .......................................................... 152, 165 CTDB_ON_RECORD_BEFORE_READ..... 152, 163 CTDB_ON_RECORD_BEFORE_WRITE... 152, 167 CTDB_ON_RECORD_INIT.................. 152, 162 CTDB_ON_RECORD_RESET ............ 152, 163 CTDB_ON_SESSION_LOGON ........... 152, 153 CTDB_ON_SESSION_LOGOUT......... 152, 153 CTDB_ON_TABLE_ALTER ................. 152, 160 CTDB_ON_TABLE_CLOSE ................ 152, 157 CTDB_ON_TABLE_GET_DODA......... 152, 158 CTDB_ON_TABLE_GET_EXT_INFO . 152, 159 CTDB_ON_TABLE_GET_RECLEN..... 152, 159 CTDB_ON_TABLE_GET_SCHEMA.... 152, 157 CTDB_ON_TABLE_OPEN .................. 152, 155 CTDB_ON_TABLE_REBUILD ............. 152, 161 memory allocation concerns ........................ 170 CTSEG_UNCSEG ........................................... 177 functions ctdb_u16TOu8.............................................. 172 ctdb_u8Tou16 .............................................. 172 ctdbGetFieldAsUTF16.................................. 174 ctdbGetIndexKSeg ....................................... 180 ctdbGetSegmentKSeg ................................. 180 ctdbGetTableKSeg ....................................... 180 ctdbSetFieldAsUTF16 .................................. 175 ctdbSetIndexKSeg........................................ 180 ctdbSetKSegDefaults ................................... 180 ctdbSetSegmentKSeg .................................. 180 ctdbSetTableKSeg ....................................... 180 introduction........................................................... 1 overview ............................................................... 1 reading UTF-16 field data ................................ 174 Unicode ctdbUNICODE support ................................. 172 Writing UTF-16 Field Data ............................... 175 ctUNICODE .......................................................... 172 Currency data type ............................................... 136
D
Data definition ........................................................... 199 manipulation ..................................................... 200 structure ........................................................... 202 types................................................................. 200 Data integrity ........................................................ 138 atomicity ........................................................... 138
743
automatic recovery........................................... 139 create table for transaction processing ............ 139 free locks.......................................................... 141 free locks with table ......................................... 142 lock ................................................................... 140 lock modes ....................................................... 141 save points ....................................................... 140 start lock........................................................... 140 start transaction................................................ 139 terminating transaction..................................... 139 transactions...................................................... 138 Data types ............................................................ 131 boolean ............................................................ 131 count ................................................................ 131 double .............................................................. 131 float .................................................................. 131 long .................................................................. 131 nint ................................................................... 131 scalar................................................................ 131 signed............................................................... 131 text ................................................................... 131 ucount .............................................................. 131 uint ................................................................... 131 ulong ................................................................ 131 unsigned........................................................... 131 utext ................................................................. 131 Databases .............................................................. 59 add ..................................................................... 65 add table under transaction control.................... 76 adding existing table .......................................... 76 allocate handle ................................................... 73 connect............................................................... 73 create ................................................................. 65 create table ........................................................ 75 create table under transaction control ............... 75 delete ................................................................. 65 delete table......................................................... 77 delete table under transaction control................ 77 dictionary............................................................ 79 drop .................................................................... 65 drop table ........................................................... 76 drop table under transaction control .................. 76 find ..................................................................... 66 find active ........................................................... 67 find active by UID ............................................... 67 find active table .................................................. 78 find active table by UID ...................................... 79 find by UID ......................................................... 67 find table............................................................. 78 find table by UID................................................. 79 first ..................................................................... 65 first active ........................................................... 66 first active table .................................................. 78 first table............................................................. 77 manage .............................................................. 64
manage tables.................................................... 75 name .................................................................. 74 next..................................................................... 66 next active .......................................................... 66 next active table ................................................. 78 next table............................................................ 77 path .................................................................... 74 properties ........................................................... 74 table count.......................................................... 74 table UID ............................................................ 79 UID ..................................................................... 67 work with ............................................................ 73 Default date formats............................................... 69 Definitions c-treeDB ............................................................. 83 field types ........................................................... 83 find modes........................................................ 109 index types ....................................................... 192 record lock modes ............................................ 193 segment modes.................................................. 88 session wide lock mode ................................... 193 table create mode ............................................ 195 table open mode .............................................. 197 table permissions ............................................. 198 Double data type .................................................. 131
E
Errors c-tree Plus ........................................................ 715 c-treeDB ........................................................... 739 handling.............................................................. 68
F
Fields...................................................................... 59 add ..................................................................... 82 delete.................................................................. 82 delete flag........................................................... 86 hidden................................................................. 86 insert................................................................... 82 null flag ............................................................... 86 rowid................................................................... 86 types................................................................... 83 Files session dictionary layout .................................... 72 Find modes........................................................... 109 Float data type...................................................... 131 Float formats .......................................................... 69 Formats .................................................................. 69 default date......................................................... 69 float..................................................................... 69 time..................................................................... 69 functions c-tree Plus BuildKey ....................................................... 166 c-treeDB ctdb_u16TO8................................................ 172
FairCom Corporation
744
ctdb_u8TO16 ............................................... 172 ctdbClearAllCallback .................................... 170 ctdbClearCallback ........................................ 170 ctdbConnect ................................................. 154 ctdbGetCallback........................................... 170 ctdbGetFieldAsUTF16.................................. 174 ctdbGetIndexKSeg ....................................... 180 ctdbGetRebuildProgress .............................. 161 ctdbGetSegmentKSeg ................................. 180 ctdbLogon .................................................... 153 ctdbOpenTable............................................. 155 ctdbSetCallback ........................................... 170 ctdbSetFieldAsUTF16 .................................. 175 ctdbSetKSegDefaults ................................... 180 ctdbSetSegmentKSeg.................................. 180 ctdbSetTableKSeg ....................................... 180 Functions descriptions ...................................................... 205 session ............................................................... 68
CTBIGINT......................................................... 134 CTCURRENCY ................................................ 136 CTMONEY ....................................................... 135 CTNUMBER ..................................................... 137
P
Password session ............................................................... 63 Permission table.................................................................. 198 table mask ........................................................ 102
R
Records .................................................................. 59 actual field length ............................................. 126 add ................................................................... 127 allocate handle ................................................. 104 automatic data type conversion ....................... 125 build target key ................................................. 109 check field length ............................................. 127 check if locked.................................................. 130 clear buffer ....................................................... 127 clear field .......................................................... 127 count................................................................. 130 create set.......................................................... 110 default index ..................................................... 106 defined field size .............................................. 126 delete................................................................ 129 demote locks .................................................... 131 edit flag............................................................. 129 field address in buffer....................................... 126 field offset in buffer........................................... 127 filters................................................................. 111 find.................................................................... 108 find by ROWID ................................................. 110 find by target key.............................................. 109 find modes........................................................ 109 first.................................................................... 107 free ................................................................... 105 last.................................................................... 107 lock ................................................................... 130 lock modes ....................................................... 193 new flag ............................................................ 129 next................................................................... 107 null field support ............................................... 126 offset................................................................. 129 previous............................................................ 107 properties ......................................................... 129 read field data to buffer .................................... 123 release handle.................................................. 105 reset ................................................................. 105 ROWID ............................................................. 130 seek.................................................................. 108 select RECBYT index....................................... 106 select ROWID index ......................................... 107 sets................................................................... 110
H
Hidden fields .......................................................... 86
I
ICU International Components for Unicode ......... 173 Index ...................................................................... 59 add ..................................................................... 87 delete ................................................................. 87 RECBYT............................................................. 90 ROWID............................................................... 89 types................................................................. 192 Initialization .......................................................... 199 ISO 10646-1 2000 ................................................................. 171 ISO/IEC 10646-1.................................................. 171
L
Locks.................................................................... 140 free ................................................................... 141 free with table................................................... 142 modes .............................................................. 141 record ............................................................... 130 record, mode .................................................... 193 session wide....................................................... 69 session wide, mode ......................................... 193 start .................................................................. 140 Long data type ..................................................... 131
M
Money data type................................................... 135 mtmake Unicode option ................................................. 172
N
Nint data type ....................................................... 131 Number data type................................................. 137 Numeric data type
www.faircom.com
All Rights Reserved
745
share context.................................................... 104 terminate set .................................................... 110 update .............................................................. 128 use field names ................................................ 127 user managed buffers ...................................... 105 write field data to buffer.................................... 123 Recovery automatic.......................................................... 139 RFC 2871............................................................. 171 RFC 3629............................................................. 171
data manipulation ............................................. 200 data structure ................................................... 202 data types......................................................... 200 initialization....................................................... 199 transaction processing ..................................... 199 utilty .................................................................. 204
T
Tables..................................................................... 59 add fields ...................................................... 82, 95 add index................................................ 87, 95, 99 allocate ............................................................... 81 allocate without database support...................... 81 alter .................................................................... 95 change default properties................................... 90 close ................................................................... 95 create ................................................................. 90 create mode ..................................................... 195 create under transaction control......................... 92 data file extent size .......................................... 101 delete fields .................................................. 82, 95 delete index ............................................ 87, 95, 99 drop .................................................................... 76 edit fields ............................................................ 95 edit index ............................................................ 95 field padding ..................................................... 103 field type ............................................................. 83 file extension .................................................... 101 file extension, index.......................................... 101 find active ........................................................... 78 first...................................................................... 77 fixed length records ............................................ 85 force index rebuild .............................................. 99 force rebuild...................................................... 100 free locks .......................................................... 142 group ID............................................................ 102 hidden fields ....................................................... 86 index file extent size ......................................... 101 insert fields ................................................... 82, 95 name ................................................................ 101 next..................................................................... 77 number of fields................................................ 103 number of indices ............................................. 103 open ................................................................... 93 open mode ....................................................... 197 open with password ........................................... 94 password .......................................................... 101 path .................................................................. 101 permission ........................................................ 198 permission mask .............................................. 102 properties ......................................................... 101 RECBYT index ................................................... 90 ROWID index ..................................................... 89 segment modes.................................................. 88 UID ..................................................................... 79 update create mode ......................................... 103
FairCom Corporation
S
Scalar data types ................................................. 131 Segment................................................................. 59 modes ................................................................ 88 Sessions................................................................. 59 active property.................................................... 64 add existing database ........................................ 65 allocate handle ................................................... 60 create new database.......................................... 65 create new dictionary ......................................... 61 database UID ..................................................... 67 default date formats ........................................... 69 delete database.................................................. 65 dictionary file layout ........................................... 72 drop database .................................................... 65 error handling ..................................................... 68 find active database ........................................... 67 find active database by UID ............................... 67 find database...................................................... 66 find database by UID ......................................... 67 first active database ........................................... 66 first database...................................................... 65 float formats ....................................................... 69 functions............................................................. 68 lock ..................................................................... 69 lock mode......................................................... 193 logon .................................................................. 62 logout ................................................................. 62 managing databases.......................................... 64 next active database .......................................... 66 next database..................................................... 66 no dictionary....................................................... 71 password properties........................................... 63 path property ...................................................... 64 properties ........................................................... 63 server properties ................................................ 63 time formats ....................................................... 69 transaction processing ....................................... 68 user defined tags................................................ 70 user name properties ......................................... 63 work without dictionary support.......................... 71 working with ....................................................... 60 Signed data type .................................................. 131 Summary.............................................................. 199 data definition................................................... 199
746
variable length records....................................... 85 working with ....................................................... 80 Tags user defined ....................................................... 70 Text data type ...................................................... 131 Time formats .......................................................... 69 Transaction processing create table ...................................................... 139 session ............................................................... 68 summary .......................................................... 199 terminate .......................................................... 140 Transactions......................................................... 138
U
Ucount data type .................................................. 131 Uint data type ....................................................... 131 Ulong data type .................................................... 131 Unicode ................................................................ 172 Creating Key Segments ................................... 176 c-treeDB ctdbGetFieldAsUTF16.................................. 174 ctdbGetSegmentKSeg ................................. 180 ctdbGetTableKSeg....................................... 180 ctdbSetIndexKSeg ....................................... 180 ctdbSetKSegDefaults ................................... 180 ctdbSetSegmentKSeg.................................. 180 ctdbSetTableKSeg ....................................... 180 Extended Key Segment Definition ................... 180 fields CT_2UNICODE............................................ 177 CT_F2UNICODE.......................................... 177 CT_FUNICODE............................................ 177 CT_UNICODE.............................................. 177 International Components for Unicode (ICU)... 173 ISO 10646-1 2000 ............................................................. 171 ISO/IEC 10646-1.............................................. 171 mtmake options................................................ 172 Reading UTF-16 Field Data ............................. 174 RFC 2871......................................................... 171 RFC 3629......................................................... 171 UTF-16 ............................................................. 171 UTF-16 Field Types CT_2UNICODE............................................ 173 CT_F2UNICODE.......................................... 173 CT_FUNICODE............................................ 173 CT_UNICODE.............................................. 173 UTF-8 ............................................................... 171 Writing UTF-16 Field Data ............................... 175 Unsigned data type .............................................. 131 Utext data type ..................................................... 131 UTF-16 ................................................................. 173 Utility .................................................................... 204
www.faircom.com
All Rights Reserved
747