Professional Documents
Culture Documents
Guia Oficial N°07. Vel30RM
Guia Oficial N°07. Vel30RM
Reference Manual
20-7203-1001
Trademarks
Centura, the Centura logo, Centura net.db, Centura Web Developer, Gupta, the Gupta
logo, Gupta Powered, the Gupta Powered logo, Fast Facts, Object Nationalizer, Quest,
QuickObjects, SQL/API, SQLBase, SQLBase Exchange, SQLConsole, SQLGateway,
SQLHost, SQLNetwork, SQLRouter, SQLTalk, and Team Object Manager, RDM, ROM,
and Velocis are trademarks of Centura Software Corporation and may be registered in the
United States of America and/or other countries. SQLWindows is a registered trademark
and TeamWindows, ReportWindows and EditWindows are trademarks exclusively used
and licensed by Centura Software Corporation.
Adobe is a trademark of Adobe Systems, Incorporated.
IBM, OS/2, NetBIOS, and AIX are registered trademarks of International Business
Machines Corporation.
UNIX is a registered trademark licensed exclusively by The Open Group.
SCO UNIX is a trademark of Santa Cruz Operation, Incorporated.
Microsoft is a registered trademark, and DOS, Windows, Windows NT, and Windows 95
are trademarks, of Microsoft Corporation.
Java and Solaris are trademarks of Sun Microsystems, Incorporated.
Microsoft, Internet Explorer, Internet Information Server, DOS, Win 32, Windows,
Windows NT, Windows 95 and Visual Basic are either registered trademarks or
trademarks of Microsoft Corporation in the United States of America and/or other
countries.
Novell is a registered trademark, and NetWare is a trademark, of Novell Incorporated.
All other product or service names mentioned herein are trademarks or registered
trademarks of their respective owners.
Copyright
Copyright 1999 by Centura Software Corporation. All rights reserved.
Velocis 3.0 Installation and Administration Guide
20-7301-1002
November 1999
Contents
Chapter 1 Introduction
1.1 Velocis Documentation................................................................................................ 1-1
1.1.1 About This Manual................................................................................................. 1-1
1.1.2 About the Function References in this Manual................................................... 1-3
1.1.3 Related Velocis Documents ................................................................................... 1-4
1.1.4 Document Conventions ......................................................................................... 1-5
1.2 Other Helpful Resources ............................................................................................. 1-5
Chapter 2 Velocis Utilities
admin................................................................................................................................... 2-2
dbcheck................................................................................................................................ 2-3
dbdefrag .............................................................................................................................. 2-5
dbfix ..................................................................................................................................... 2-7
dbimp................................................................................................................................... 2-9
dbreplay ............................................................................................................................ 2-13
dbstat ................................................................................................................................. 2-15
dchain ................................................................................................................................ 2-17
ddlproc .............................................................................................................................. 2-19
instodbc ............................................................................................................................. 2-22
instrds ................................................................................................................................ 2-23
keybuild............................................................................................................................. 2-24
prdbd ................................................................................................................................. 2-26
rds....................................................................................................................................... 2-27
rdsadm............................................................................................................................... 2-28
rsql...................................................................................................................................... 2-29
sddlp .................................................................................................................................. 2-37
vping .................................................................................................................................. 2-39
Chapter 3 SQL Decimal Value Manipulation Functions (BCD Prefix)
BCDAdd .............................................................................................................................. 3-2
BCDAllocEnv...................................................................................................................... 3-3
BCDAllocZBuf .................................................................................................................... 3-4
BCDCompare...................................................................................................................... 3-5
BCDDivide .......................................................................................................................... 3-6
BCDFreeEnv ....................................................................................................................... 3-7
BCDFreeZBuf...................................................................................................................... 3-8
BCDMultiply....................................................................................................................... 3-9
BCDPack............................................................................................................................ 3-10
BCDStatus ......................................................................................................................... 3-11
Contents i
BCDSubtract ..................................................................................................................... 3-12
BCDUnpack ...................................................................................................................... 3-13
Chapter 4 Dictionary Access API Functions (c_ Prefix)
(Alphabetical listing by function name).......................................................................... 4-2
Chapter 5 Customized Comparison Function Module Functions
(cmp Prefix)
cmpDescribeFcns................................................................................................................ 5-2
cmpFunction ....................................................................................................................... 5-4
cmpShutdown .................................................................................................................... 5-6
Chapter 6 Core API Functions (d_ Prefix)
(Alphabetical listing by function name).......................................................................... 6-2
Chapter 7 Extension Module Functions (em_ and Mod Prefix)
em_attach ............................................................................................................................ 7-2
em_call................................................................................................................................. 7-4
em_detach ........................................................................................................................... 7-7
em_getContext.................................................................................................................... 7-9
em_getHandle .................................................................................................................. 7-11
em_load ............................................................................................................................. 7-12
em_unload ........................................................................................................................ 7-14
ModCleanup ..................................................................................................................... 7-15
ModDescribeFcns............................................................................................................. 7-16
ModFunction .................................................................................................................... 7-18
ModInit.............................................................................................................................. 7-20
Chapter 8 Import and Export Filter Module Functions (ief Prefix)
iefCheck............................................................................................................................... 8-2
iefCleanup ........................................................................................................................... 8-4
iefDescribeFcns................................................................................................................... 8-5
iefFetch ................................................................................................................................ 8-7
iefInit.................................................................................................................................... 8-9
iefStore............................................................................................................................... 8-12
Chapter 9 Parameter List Functions (pl_ Prefix)
pl_alloc................................................................................................................................. 9-2
pl_count............................................................................................................................... 9-4
pl_del ................................................................................................................................... 9-5
pl_free .................................................................................................................................. 9-6
pl_get ................................................................................................................................... 9-8
pl_peek .............................................................................................................................. 9-10
Contents iii
Chapter 17 Server Extension Toolkit Functions (C++ API)
17.1 Class Reference ........................................................................................................... 17-1
class DataDescriptor : public SeBase ............................................................................. 17-1
Constructor and Destructor ...................................................................................... 17-2
Member Functions...................................................................................................... 17-2
class ParmReceive : public SeBase ................................................................................. 17-4
Operators..................................................................................................................... 17-4
Member Functions...................................................................................................... 17-6
class ParmSend : public SeBase...................................................................................... 17-9
Operators..................................................................................................................... 17-9
Member Functions.................................................................................................... 17-10
class SeBase ..................................................................................................................... 17-12
Constructor and Destructor .................................................................................... 17-13
Operators................................................................................................................... 17-13
Member Functions.................................................................................................... 17-14
class ServerExtension : public SeBase.......................................................................... 17-17
Constructor and Destructor .................................................................................... 17-17
Member Functions.................................................................................................... 17-19
17.2 Macro Reference ....................................................................................................... 17-26
Macros ............................................................................................................................. 17-26
BEGIN_RPC_MAP ................................................................................................... 17-26
CREATE_EXPORTS ................................................................................................. 17-26
DECLARE_RPC_MAP............................................................................................. 17-29
END_RPC_MAP....................................................................................................... 17-29
ON_RPC .................................................................................................................... 17-29
Chapter 18 Velocis Data Types
18.1 Low-Level Database Programming ......................................................................... 18-1
18.2 SQL Programming ..................................................................................................... 18-3
18.3 Compound Velocis Data Types ................................................................................ 18-8
(Alphabetical listing by type name)............................................................................... 18-8
Chapter 19 Return Codes and Error Messages
19.1 Standard Return Codes ............................................................................................. 19-1
19.2 SQL-Specific Return Codes ..................................................................................... 19-25
19.2.1 General Codes Returned by SQL Functions................................................. 19-25
19.2.2 Detailed Codes Retrieved by the SQLError Function................................. 19-26
19.2.3 Codes Returned by SQL Value Manipulation Functions ........................... 19-48
19.3 Error Messages Returned by the sddlp Utility..................................................... 19-49
Contents v
Chapter 1
Introduction
This book is the reference manual for Centura Velocis Database Server. It provides
complete descriptions of all Velocis utilities, functions, complex data types, and return
codes. Information on use of the functions and utilities can be found in the Velocis User’s
Guide.
Introduction 1-1
Chapter 7, "Extension Module Functions," describes the functions that provide access
between Velocis client applications and extension modules, which reside on the Velocis
server. These functions begin with an em_ prefix. The chapter also describes the
functions that you can use in an extension module to extend server capabilities. These
functions begin with a Mod prefix and appear after the em_ function summaries.
Chapter 8, "Import and Export Filter Module Functions," describes the functions that you
can use in an extension module to create filters for use in transferring data between
Velocis SQL databases and outside resources. These functions begin with an ief prefix.
Chapter 9, "Parameter List Functions," describes the functions that are used to package
the data sent between Velocis client applications and Velocis server extension modules.
These functions begin with a pl_ prefix.
Chapter 10, "Engine Resource Manager Functions," contains descriptions of functions that
begin with an rm_ prefix. Your extension module can call these functions for use in
resource management.
Chapter 11, "Administration API Functions," contains descriptions of the functions that
begin with an s_ prefix. Your application can call these functions for server
administration tasks, but they are most often accessed by the system administrator
through the Velocis administration utilities.
Chapter 12, "SQL API Functions," describes the functions that begin with an SQL prefix.
Your application calls them for communication with the Velocis SQL support module.
The functions provide full relational access to the server engine and database. Additional
Velocis SQL functions are provided in Chapters 3, 13, and 16.
Chapter 13, "SQL UDF Support Functions," contains descriptions of the Velocis SQL
user-defined support functions, represented with a SYS prefix. Your server-based UDF
or import/export filter module can call these functions to extend the functionality of the
server.
Chapter 14, "UDF Module Functions," describes the functions that you can use in a UDF
module to extend server functionality. The function names begin with a udf prefix,
which you can replace with a module-specific prefix.
Chapter 15, "UDP Module Functions," describes the functions used in a user-defined
procedure module. The function names begin with a udp prefix, which you can replace
with a module-specific prefix.
Chapter 16, "SQL Date/Time Manipulation Functions," contains descriptions of the
Velocis SQL date/time manipulation functions, which begin with a VAL prefix.
Introduction 1-3
After the Currency Changes section, the function reference presents the Locking
Requirements section, which lists locking requirements for any function that accesses the
database. If your application has opened the database in a nonshared mode, locking is
not required.
The next section of the function reference is See Also, which lists related functions,
complex data types, etc.
For many of the functions in this manual, an Example section is included. An example
illustrates how the application calls the function, but not necessarily how the application
uses it. For examples showing application use of Velocis API functions, see the Velocis
User’s Guide.
Note: The trademarked name of this product is Velocis Database Server and is reflected in
the actual titles of the manuals. For ease of reference within the manuals, the simpler
form of Velocis is used.
Velocis system components are furnished on a CD. The CD includes a readme.txt file
that contains the release notes for your particular operating environment. Be sure to read
this file carefully. It provides detailed information about:
• Recent changes to the system that are not documented in the current manuals.
• Issues specific to your particular operating system or compiler.
Convention Description
Introduction 1-5
Access the collection by going to the CD, navigating to the Book Set folder, and
opening the PDF file listed in that directory.
• Worldwide Web
The Centura Worldwide Web home page is located at http://www.centurasoft.com.
The Centura web server provides access to a wealth of information about Centura
products and services.
Command admin
Syntax
Command None
Options
Description The admin utility invokes Velocis Administrator, which performs
most system administration operations necessary for configuration,
testing, and maintenance of Velocis. With this utility, you can view,
create, modify, or delete server objects (such as users, databases,
database devices, and extension modules). You can also use the
utility to modify velocis.ini configuration parameters.
The utility makes use of the administration API functions detailed in
Chapter 11 of this manual. See Chapter 5 of the Velocis
Installation/Administration Guide for instructions on running this
utility. Alternatively, you can write your own system
administration code, making calls directly to the administration API
(s_ functions).
Command dbcheck [-? | -h] [-a] [-b ["bname[;bname]..."]] [-f file] [-i secs]
Syntax [-k ["kname[;kname]..."]] [-L "serverID;userID;password"] [-m type]
[-p pages] [-q] [-r ["rname[;rname]..."]] [-s ["sname[;sname]..."]]
dbname
Description This utility examines the consistency of the files in the physical
database specified by dbname. For this purpose, it calls the
s_dbcheckBegin function. The utility translates the command
options into the function parameters. The recIDs, setIDs, keyfldIDs,
and blobfldIDs parameters are formed from the names directly
specified in the command line (explicitly or implicitly) and from the
names in the file that is specified in the -f option. Duplicate
specifications of the same element are accepted.
After starting the consistency checking process (and until its
termination), the utility fetches the next portion of the user report
after every secs seconds and puts it into the standard output file.
The utility displays progress by polling the status of the running
dbrepair operation. Status is polled by one or more calls to
s_dbrGetStatus.
Command dbdefrag [-? | -h] [-a] [-b ["bname[;bname]..."]] [-f file] [-i secs]
Syntax [-L "serverID;userID;password"] [-m type] [-n] [-p pages] [-q]
[-r ["rname[;rname]..."]] dbname
Description This utility compresses files in the dbname database by using the
s_dbdefragBegin function. The utility extracts the parameters for
the call from the values of the command options. The recIDs and
blobfldIDs parameters are formed from the names directly specified
in the command line (explicitly or implicitly) and from the names in
the file that is specified in the -f option. Duplicate specifications of
the same element are accepted.
After starting the consistency checking process (and until its
termination), the utility fetches the next portion of the user report
after every secs seconds and puts it into the standard output file.
The utility displays progress by polling the status of the running
dbrepair operation. Status is polled by one or more calls to
s_dbrGetStatus.
Command dbfix [-? | -h] [-a] [-b ["bname[;bname]..."]] [-d dumpfile] [-f file]
Syntax [-i secs] [-k ["kname[;kname]..."]] [-L "serverID;userID;password"]
[-m type] [-n] [-p pages] [-r ["rname[;rname]..."]]
[-s ["sname[;sname]..."]] dbname
Description This utility performs the consistency check of the dbname database
and repairs the database if corruption is detected. The utility
accomplishes this by a call of the s_dbfixBegin function. The utility
extracts the parameters for the call from the values of the command
options. The recIDs, setIDs, keyfldIDs, and blobfldIDs parameters are
formed from the names directly specified in the command line
(explicitly or implicitly) and from the names in the file that is
specified in the -f option. Duplicate specifications of the same
element are accepted.
After starting the consistency checking process (and until its
termination), the utility fetches the next portion of the user report
after every secs seconds and puts it into the standard output file.
The utility displays progress by polling the status of the running
dbrepair operation. Status is polled by one or more calls to
s_dbrGetStatus.
Command dbimp [-? | -h] [-e "ch"] [-L "serverID;userID;password"] [-n] [-s "ch"]
Syntax impspec
Description This utility imports data to a Velocis database from ASCII text files
according to commands contained in an import specification file,
impspec. It logs in to the server and opens the database in exclusive
mode with no transactions ("xn"). Refer to Chapter 9 of the Velocis
User’s Guide for complete information.
The dbimp error message format, which is shown below, can be
interpreted by some text editors.
filename line col : message
Language dbname The name of the database that is the target of the
Parameters import. The database must be initialized and
registered in the catalog.
input_file The full name, optionally including a full path, of an
ASCII (the default) or Unicode text file to be used as
input. The name of the file must be enclosed in
quotation marks. An input file may be opened
more than once during an import.
recname A record type as defined in the DDL schema for the
database.
fldnum An integer that identifies a field within the input
file. The first input field is number 1, the second is
2, etc.
fldname A field type as defined in the DDL schema for the
database, within the record type created by the
record statement that encloses this statement.
setname A set type as defined in the DDL schema for the
database.
Example From tims.imp, the database import file for the example
tims database:
database tims;
foreach "author.txt" {
record author {
create on 1;
field name = 3;
}
}
foreach "info.txt" {
record info {
create on 1;
field id_code = 4;
field info_title = 5;
field publisher = 6;
field pub_date = 7;
field info_type = 8;
}
record author {
find on 2;
}
connect has_published;
}
foreach "text.txt" {
record text {
field line = 3;
}
record info {
find on 2;
}
connect abstract;
}
foreach "key_word.txt" {
record key_word {
create on 1;
field word = 2;
}
}
foreach "intersct.txt" {
record intersect {
field int_type = 4;
}
record info {
find on 3;
}
record key_word {
find on 2;
}
connect info_to_key;
connect key_to_info;
}
end;
Command dbreplay [-? | -h] [-b] [-c] [-L "user;pw"] [-n] [-q]
Syntax [-s "mm/dd/yyyy hh:mm:ss"] [-v] [logfilename]
Description This utility is used to reprocess all committed transactions that were
recorded in change log files after a server backup. It performs what
is called roll-forward recovery. The utility must be executed
immediately after a server backup has been restored.
Roll-forward recovery works in conjunction with hot backup mode.
After the server is placed into hot backup mode (using an
administrative utility), all database files should be backed up. If a
roll-forward recovery becomes necessary, the dbreplay utility must
be used.
This utility runs in a standalone (non-server) mode, and the server
cannot be running when you use this utility. To perform the
recovery, database files that were backed up must be restored to
their original positions. Log files which were created when hot
backup mode was entered need to be present. Then run this utility.
Command dbstat [-? | -h] [-b num] [-k num] [-L "serverID;userID;password"]
Syntax [-nb] [-nd] [-nk] [-v] [dbname]
Command dchain [-? | -h] [-a] [-b ["bname[;bname]..."]] [-f file] [-i secs]
Syntax [-k ["kname[;kname]..."]] [-L "serverID;userID;password"] [-m type]
[-n] [-p pages] [-r ["rname[;rname]..."]] dbname
Description This utility rebuilds delete chains in the dbname database by calling
the s_dchainBegin function. The utility extracts the parameters for
the call from the values of the command options. The recIDs,
keyfldIDs, and blobfldIDs parameters are formed from the names
directly specified in the command line (explicitly or implicitly) and
from the names in the file that is specified in the -f option.
Duplicate specifications of the same element are accepted.
After starting the consistency checking process and until its
termination, the utility fetches the next portion of the user report
after every secs seconds and puts it into the standard output file.
The utility displays progress by polling the status of the running
dbrepair operation. Status is polled by one or more calls to
s_dbrGetStatus.
-L "serverID;userID;password"
Specifies the user login information. If this option is
omitted, the utility looks for the information in the
RDSLOGIN environment variable. Then, if the
variable is undefined, the utility prompts you for
the login information.
-r Displays a file structure report in standard output
(stdout). See Chapter 5 of the Velocis User’s Guide.
-s Turns off case sensitivity. The utility defaults to
case sensitivity.
-t device Specifies the device on which to place the dictionary
file. If this option is not specified, the user’s default
device is used.
allocation field 13
amount field 20
balance field 14
budget record 7 10 24
cat_desc field 12
check record 7 16 25
check_date field 918
check_no field 917
code field 811
paid_to field 19
transactions set 22
Description The ddlproc utility compiles the schema contained in the text file
ddlfile. It generates a database dictionary file (<dbname>.dbd) to
run on the server in a default device, or in the device specified for
the -t option. The processor also generates a C database header file
named <dbname>.h.
The ddlproc utility reports any processing errors to standard output
in the following format, which some text editors interpret.
filename line col : message
ddlproc The following are ddlproc keywords. Note that they are not case-
Keywords sensitive.
asc desc long records
ascending descending member set
blob_id double next sets
by file nocase short
char first opt static
compound float optional struct
contains int order timestamp
data key owner unique
database last readonly unsigned
db_addr local record wchar
Command instodbc [-? | -h] [-a] [-d database [database] ...] [-f] [-q] [-s] [-u]
Syntax binpath servername
Description A system administrator can use this utility to add the Velocis ODBC
driver and a data source to an existing ODBC installation. The
utility enables the ODBC driver manager. The use of this utility is
illustrated in the Velocis Installation and Administration Guide.
Example For the command line below, instodbc creates a driver with the
name "Velocis" and a data source named "Velocis VEL3". The 32-bit
ODBC Administrator Data Sources screen will display a "Velocis
VEL3(Velocis)" entry.
instodbc c:\velocis\bin VEL3
Example
instrds -s VEL3 c:\velocis\bin\rds.exe c:\velocis\catalog
Command keybuild [-? | -h] [-f file] [-i secs] [-k ["kname[;kname]..."]]
Syntax [-L "serverID;userID;password"] [-m type] [-p pages] dbname
Description This utility rebuilds indexes in the dbname database by calling the
s_keybuildBegin function. The utility extracts the parameters for
the call from the values of the command options. The keyfldIDs
parameter is formed from the names directly specified in the
command line (explicitly or implicitly) and from the names in the
Description This utility displays the contents of the database dictionary (.dbd)
file for the dbname database. It reports the default database page
size and each entry in the file table, record table, field table, set table,
member table, sort field table, and key table that constitutes the
internal form of the database dictionary. This report is written to
standard output (stdout) and can be redirected as desired.
The utility normally prints symbolic names wherever possible. If
you want the record, set, and field numbers only, use the -c option.
Command rds [-c path] [-d [-ph | -pi | -pn]] [-r threads] [servername]
Syntax
Description A system administrator can use this utility to put the database
server into operation. You can operate the server in the background
by using the -d option, with the ability to set the level of process
priority. If you are running the Velocis server on Windows NT, you
can install and run Velocis as a Windows NT service by using the
instrds utility.
Command rsql [-? | -h] [-c num] [-e] [-H num] [-l num] [-n] [-o output_file]
Syntax [-s num] [-w num] [startup [arg]...]
Once you have started rsql, you can enter utility commands or
Velocis SQL statements at the prompt ("1 rsql>"). Each statement is
terminated by a semicolon (";") at the end of the line. You can enter
multi-line statements by pressing <Enter> at the end of each line.
An example of a multi-line statement is shown below.
1 rsql> select sale_name, sum(amount), max(amount), min(amount), avg(amount)
1+ rsql> from path salesperson to customer to sales_order
1+ rsql> group by sale_name;
The rsql Utility The rsql utility has a set of commands to select and edit previously
Commands entered Velocis SQL statements, open and close connections to
Velocis servers, control use of statement handles, read and store
statements in text files, etc. These commands are listed in the table
below. Each rsql utility command begins with a special character in
the first column of the entered statement and is terminated by
pressing the <Enter> key. Only Velocis SQL statements are
remembered in the statement history list. Utility commands are not
remembered.
The "@" command searches down the list for a statement that
matches the specified text pattern with the wild card characters "*"
(match zero or more characters) and "?" (match any single
character). The search starts from the current statement and
Example
1 rsql> .t
*** table mode is off
1 rsql> select * from salesperson;
SALE_ID: BNF
SALE_NAME: Flores, Bob
COMMISSION: 0.135000
REGION: 0
OFFICE: 1
MGR_ID: **NULL**
2 rsql> .n
SALE_ID: JBW
SALE_NAME: Warner, John
COMMISSION: 0.115000
REGION: 1
OFFICE: 1
MGR_ID: **NULL**
2 rsql> .f getcursor
*** cursor = SQL_CUR_3_1
2 rsql> .h 2
*** using statement handle 2 of connection 1
2 rsql> update salesperson set commission = 0.10
2 rsql+ >where current of sql_cur_3_1;
*** 1 rows affected
3 rsql> commit;
Command sddlp [-? | -h] [-b] [-c] [-d "ddlproc_opts"] [-f] [-i] [-k]
Syntax [-L "serverID;userID;password"] [-n] [-o] [-p] [-R] [-r] [-u] [-w]
ddlfile
Description The sddlp utility compiles a text file containing a Velocis SQL DDL
database schema. Compilation generates the corresponding Core
DDL schema and automatically invokes the internal ddlproc
program to compile the Core schema for use under Velocis.
The utility reports errors in the schema on the standard error stream
(stderr). It only updates the system catalog when it encounters no
errors and the -p option has not been specified.
Note: Full ANSI 1989 SQL referential integrity checking requires the
existence of every row referenced by each foreign key in the
database. To enforce this integrity condition in the processing of a
delete statement, Velocis SQL maintains a reference count data field
in each Velocis record type that is referenced by a foreign key.
Velocis then allows deletions of referenced rows when the reference
count is zero. Extra overhead is incurred to maintain these reference
counts.
Command vping [-? | -h] [-c Packets] [-i TestTime] [-s PacketSize] [-w WaitTime]
Syntax [servername]
Some BCD functions involve converting BCD values to and from character strings. The
character string buffers must be large enough to contain the entire decimal value.
Therefore, the number of bytes to allocate to a string buffer should be at least the
maximum allowable precision of the allocated BCD handle, plus three (for the sign,
decimal point, and null-terminating character).
Description This function allocates a BCD environment handle to use for other
BCD functions. To allocate the BCD environment handle, your
application must specify the maximum precision and scale for the
BCD values that it is manipulating. These values can be set to
anything you want. However, to directly store (through the Core
API) any BCD values in the database, the maximum precision and
scale specified in this function must match the values specified in
Velocis SQL.
Description This function allocates a packed decimal buffer with a size indicated
by the prec parameter. Packed decimals store two digits of data to a
byte, plus three additional bytes for the scale, precision, and flags.
You can use the BCDZLEN(precision) macro to calculate the size, in
bytes, of a packed decimal buffer.
Example
#include "velocis.h"
#include "sqlrds.h"
BCD_Z *pBcd;
...
/* Pack commission value, note the 0 len argument can be used when
the BCD_Z * value was allocated using BCDAllocZBuf.
*/
BCDPack(hBcd, "0.025", 4, 3, pBcd, 0);
Description This function divides the left operand decimal string by the right
decimal string. It then writes the resulting decimal string to a
character array.
Example
#include "velocis.h"
#include "sqlrds.h"
BCD_Z *pBcd;
...
/* Pack commission value, note the 0 len argument can be used when
the BCD_Z * value was allocated using BCDAllocZBuf.
*/
BCDPack(hBcd, "0.025", 4, 3, pBcd, 0);
Description This function multiplies two decimal strings and stores the resulting
decimal string in a character array.
Description This function converts a numeric character string into a decimal that
is in the internal BCD format of SQL for storage (through the Core
API) in a particular column of the database.
Extremely Important: The precision and scale used in the
conversion must match the declared precision and scale for the
database column. You can obtain this information for any database
column by calling the SQLColumns function.
Description This function checks the status of a decimal value for overflow and
loss of precision.
Description This function subtracts the right decimal string from the left decimal
string, and stores the resulting numeric string in a character array.
Description This function converts a decimal value from the internal BCD
format of Velocis SQL to a character string.
Note: You can use the d_dict function to access the database dictionary, but it always
generates a call to the server. The c_ functions are more efficient, because they cache any
requested data, and they only make calls to the server when it is necessary. You can also
use the prdbd utility to print the contents of the database dictionary.
A database dictionary contains an information table for each of these categories: files,
sets, set members, records, compound keys, fields (which also include compound keys),
and sort fields (fields that are referenced in an order by clause in a set definition). For
each table, there is an entry for each database item of that category, which contains the
details for that item. (To get the number of items of a certain category, use the
appropriate c_size_* function.) When the database schema is processed, the database
dictionary is created and stored in a server file that is named after the database and has a
.dbd suffix.
When using many of the c_ functions and all Core API (d_) functions that take
parameters for these database items, the indexed form of the item must be used. An
indexed category of database items is numbered sequentially from 0 to the number of
items that are in the category. Because offsets may be used in the database header file
constant defintions, you can obtain the index number from the constants for sets,
records, and fields by using the c_st_idx, c_rt_idx, and c_fd_idx functions, respectively.
Note: File indexes are identical to their constant definitions in the database header file,
so a conversion function is not necessary. Indexes for compound keys, set members, and
sort fields are not used in Core API functions.
When you have finished using these functions, call c_freedict to free the cached database
tables and perform other cleanup.
Description This function retrieves a dimension for the field element represented
by the fd_number and dim_elem parameters. Every field can have up
to three dimensions. If a field has no dimensions, all elements are
zero.
Parameters fd_number [Input] The field table index for the field (see
c_fd_idx).
hDb [Input] The database handle.
Description This function retrieves field attribute flags associated with the
specified field. Possible values of flags are:
SORTFLD Field is used in by clause of a set specification
STRUCTFLD Field is a member of a structure field
UNSIGNEDFLD Field is unsigned
STATIC Field is static
COMKEYED Field is included in a compound key
Description This function retrieves a key field type. Possible values are:
NOKEY Not a key field
DUPLICATES A non-unique key field (duplicates allowed)
UNIQUE A unique key field
Description This function retrieves the file table entry for the key file containing
the specified field. If fd_number does not specify a key field, the
function returns a value of -1.
Description This function retrieves the prefix number of the specified key. A
key prefix is used in key files to distinguish between two different
keys in the same key file. If fd_number does not specify a key field,
the function returns a value of -1.
Description This function retrieves the length, in bytes, of the specified field.
The length is the total length of the field, even if the field is grouped
or dimensioned.
c_fd_rec Get the record table entry of the record containing the specified field
Description This function retrieves the record table index for the record
containing the specified field.
Description This function retrieves the size, in bytes, of the specified field.
Description This function retrieves the type of the specified field. Possible
values are:
CHARACTER Character
SHORTINT Short integer
REGINT Integer
LONGINT Long integer
FLOAT Floating point
DOUBLE Double floating point
DBADDR Database address
GROUPED Grouped
COMKEY Compound key
Description This function frees the cached tables for the specified database. Call
this function when you are finished using the dictionary access
functions.
Description This function retrieves a file name for the specified file.
Description This function retrieves the number of record slots per page for the
specified file.
Database pages are divided into slots, where each slot contains one
record. If there are records of different sizes in the data file, the slot
size must be large enough to accommodate the size of the largest
record.
Description This function retrieves the file type for the specified file. The
possible types are:
DATA Data file
KEY Key file
BLOB BLOB file
Description This function retrieves the field table index of a field contained in a
compound key.
Description This function retrieves the field table index for the specified
compound key.
Return Values The field table index for the compound key
Description This function retrieves the offset to the start of field data in the
specified compound key.
Description This function retrieves the record table index for the specified
member.
c_mt_sort_fld Get the table entry for the first sort field
Description This function retrieves the sort field table index for the first sort
field.
Description This function retrieves the total number of sort field table entries for
the specified member.
Description This function retrieves the length, in bytes, of the specified record.
Description This function retrieves the total number of fields contained in the
specified record. Use the returned value in a loop in conjunction
with c_rt_fields to loop over all the field entries for a record.
Compound key definitions follow the field definitions in the field
table, for a given record. This value is -1 if the record is a system
record.
Description This function retrieves the index of the first field in the field table for
the specified record.
Description This function retrieves the file table index for the file containing the
specified record.
Description This function retrieves flags associated with the specified record.
The possible flag settings are STATIC and COMKEYED.
Parameters rec [Input] The record type from a database header file.
Description This function converts the specified record type to a record table
index.
Description This function retrieves the field table index for a field used in a
sorted set.
Description This function retrieves the size of a field table, listing references to
fields of records included in the database. The ddlproc utility uses
this size to determine table numbering when it creates the field table
and stores it in the database dictionary file.
Description This function retrieves the size of a file table, listing references to
files included in the database. The ddlproc utility uses this size to
determine table numbering when it creates the file table and stores
it in the database dictionary file.
Description This function retrieves the size of a compound key table, listing
references to compound keys used in the database. The ddlproc
utility uses this size to determine table numbering when it creates
the compound key table and stores it in the database dictionary file.
Description This function retrieves the size of a set member table, listing
references to member records of sets used in the database. The
ddlproc utility uses this size to determine table numbering when it
creates the set member table and stores it in the database dictionary
file.
Description This function retrieves the size of a record table, listing references to
records in the database. The ddlproc utility uses this size to
determine table numbering when it creates the record table and
stores it in the database dictionary file.
Description This function retrieves the size of a sort table, listing references to
fields used to order a set member. The ddlproc utility uses this size
to determine table numbering when it creates the sort table and
stores it in the database dictionary file.
Description This function retrieves the size of a set table, listing references to sets
in the database. The ddlproc utility uses this size to determine table
numbering when it creates the set table and stores it in the database
dictionary file.
Description This function retrieves flags associated with the specified set table.
There are currently no used values for this variable.
Description This function converts the set type for the specified set to a set table
index.
c_st_members Get the member table index for the first set member
Description This function retrieves the member table index for the first member
record in the specified set. Use this value in conjunction with
c_st_memtot to set up a loop that retrieves all member table entries
for a given set.
Description This function retrieves the ordering method for the specified set.
The function returns one of these values:
FIRST Order first
LAST Order last
ASCENDING Order ascending
DESCENDING Order descending
NEXT Order next
Description This function retrieves the record table index for the owner record
of the specified set.
The function address member of the structure is a pointer to the function that you
implement to create the comparison routine. Use the cmpFunction function interface to
create this function.
For more information about these functions, see Chapter 9 of the Velocis User's Guide.
Description Velocis loads the user comparison shared library and calls the
cmpDescribeFcns function when the server is started. As with the
ModDescribeFcns function in extension modules, this function
returns the names of the customized comparison routines and the
addresses of their respective comparison functions. You must
implement every function listed in the comparison function table.
Any attempt to open a database that references missing comparison
routines (that is, routines not returned from cmpDescribeFcns) will
fail, and an explanatory error message will be displayed.
The format of the comparison function load table is specified by the
following type definitions:
/* Comparison Function Load Table */
typedef struct cmploadtable {
char cmpName[33]; /* name of comparison routine */
CMPFUNCTION *cmpFunction; /* address of compare function */
} CMPLOADTABLE;
You must define this function in the usercmp.c module file. The
data types and constants used in usercmp.c are declared in the
usercmp.h header file.
Example
/* table of customized comparison functions */
static CMPLOADTABLE CmpFcnTable[] = {
/* cmpName cmpFunction */
/* --------- ----------- */
{ "cmpSoundex", cmpSoundex }
};
/* ==================================================================
Called once to initialize module. Called during Server startup.
*/
void REXTERNAL cmpDescribeFcns(
unsigned short *NumFcns, /* out: num. of fcns in module */
CMPLOADTABLE **cmpLoadTable, /* out: addr of CmpFcnTable */
char **descr) /* out: description string */
{
*NumFcns = sizeof(CmpFcnTable)/sizeof(CmpFcnTable[0]);
*cmpLoadTable = CmpFcnTable;
*fcn_descr = "Sample of customized comparison function";
}
Example
#define SNDXLEN 4
/* ==================================================================
Soundex conversion routine.
*/
static void GenSoundex(
const char *name, /* in: pointer to name string */
const char *code) /* out: pointer to result code */
{
static short soundex_code[26] = {
/* a b c d e f g h i j k l m n o p q r s t u v w x y z */
0,1,2,3,0,1,2,0,0,2,2,4,5,5,0,1,2,6,2,3,0,1,0,2,0,2
};
char c;
short l, thisCode, lastCode;
GenSoundex(leftVal, lSndx);
GenSoundex(rightVal, rSndx);
return (short) memcmp(lSndx, rSndx, SNDXLEN);
}
Parameters None
Description Velocis calls this function when the Velocis server shuts down. You
can define this function to perform any necessary cleanup
operations. Typically, no cleanup will be required.
You must define this function in the usercmp.c module file.
Note: These functions were formerly referred to as the runtime API functions.
Description This function deletes BLOB data associated with the specified BLOB
ID field of the current record. The function sets the contents of field
to NULL_BLOB.
Currency None
Changes
Currency None
Changes
Locking None
Requirements
Syntax short d_blobread (long field, void *buf, long len, long *size,
RDM_DB hDb)
Description This function reads data into a buffer from the position of the
specified BLOB data in the current record. If the call to this function
is the first BLOB data operation for the current record, the function
reads from the start of the BLOB data. If d_blobseek has been
called to set the current position for field, reading will commence
from there. Otherwise, it reads from the point where the last read
stopped. The d_blobtell function may be used to determine the
current position.
If the BLOB data is shorter than the amount indicated in the len
parameter, the function writes the actual number of bytes it has read
to the size parameter. Following a successful call to d_blobread, the
current position in the record is advanced by size bytes.
The d_blobread function returns S_BADBLOB if Velocis indicates
that the BLOB data is corrupted. The function returns
S_NOTFOUND when it is called for the first time after it has
encountered data that is shorter than the specified length. Then, for
the next call after d_blobread returns S_NOTFOUND, the function
reads from the start of the indicated BLOB data.
Currency None
Changes
Locking If dirty reads are not enabled, a read lock on the current record.
Requirements
Description This function adjusts the current byte offset in BLOB data according
to the specified point of origin. If the origin parameter is set to
B_START, the offset must be greater than or equal to zero and
d_blobseek sets the position from the start of the BLOB data. If
origin contains B_CURRENT, d_blobseek sets the position to offset
bytes from the current position. Finally, if origin contains B_END,
the offset must be less than or equal to zero, and d_blobseek sets
the position from the end of the BLOB data. The d_blobseek
function returns S_BLOBPOS if the offset sets the position beyond
the boundaries of the BLOB data.
Currency None
Changes
Locking If dirty reads are not enabled, a read lock on the current record.
Requirements
Description This function retrieves the size of the specified BLOB data associated
with the indicated field identifier (field) in the current record.
Currency None
Changes
Locking If dirty reads are not enabled, a read lock on the current record.
Requirements
Description This function retrieves the current byte offset position from the start
of the BLOB data associated with the specified field identifier (field)
in the current record.
The current byte offset is affected by the d_blobread, d_blobseek,
and d_blobwrite functions.
Currency None
Changes
Locking If dirty reads are not enabled, a read lock on the current record.
Requirements
Syntax short d_blobwrite (long field, void *buf, long size, RDM_DB hDb)
Description This function writes BLOB data from the indicated buffer, starting at
the current position of the specified BLOB in the current record. If
the application is calling d_blobwrite as the first operation for the
current record, the function begins the write at the start of the BLOB
data. If the value stored in field is NULL_BLOB, the function creates
the BLOB.
Currency None
Changes
Currency None
Changes
Locking None
Requirements
Description This function closes all databases that have been opened in a server
session. If a transaction is active, the function aborts it (see
d_trabort). The user remains logged into the server and can issue
subsequent d_open calls.
Currency Once the database has been closed, the currency (current record,
Changes owner, and members of a set) is no longer relevant or accessible.
Example
main()
{
/* A Velocis Database Server application program */
...
s_login("dbServer","myname","secret",&hSess);
d_open("tims", "s", hSess, &hDb);
d_close(hSess);
s_logout(hSess);
}
Parameters set [Input] The set type that includes the member
record.
hDb [Input] The database handle.
Description This function frees the record instance lock on the current member
of the specified set. You must establish a valid owner and member
for the set before the application can call this function.
The S_TRFREE error code is returned if the application tries to free a
read lock within a transaction but has not enabled the freeing of
read locks (see d_rdlockmodes). The d_cmfree function returns
S_NOTLOCKED if the application tries to free a record with no
record instance locks.
Currency None
Changes
Locking None
Requirements
Example
... /* Do a safe read of all members of set*/
d_setro(SET1, hDb);
d_cslock(SET1, "r", hDb);
for (stat = d_findfm(SET1, hDb); stat == S_OKAY;
stat = d_findnm(SET1, hDb) ) {
d_cmlock(SET1, "r", hDb);
d_recread(REC1, &rec1, hDb);
...
d_cmfree(SET1, hDb);
}
Parameters set [Input] The set type that includes the member
record.
ltype [Input] The lock type indicator. To apply a read
lock, specify "r". To apply a write lock, specify "w".
hDb [Input] The database handle.
Description This function requests a record instance lock of the specified type for
the current member of the indicated set. You must establish a valid
owner and member for the set before the application can call
d_cmlock.
Note that locking a set member only allows access to the member
record. The application must separately lock the owner if it needs to
access the owner. It must also separately lock the set if it needs to
access the set connection.
Your application can upgrade or downgrade an existing lock.
However, it cannot downgrade a write lock within a transaction.
Currency None
Changes
Locking None
Requirements
Example
... /* Update member with new value */
d_cslock(SET1, "r", hDb);
d_findfm(SET1, hDb);
d_trbegin("upd", hSess);
d_cmlock(SET1, "r", hDb);
d_recread(REC1, rec1, hDb);
...
d_cmlock(SET1, "w", hDb);
d_recwrite(REC1, &rec1, hDb);
d_trend(hSess);
Parameters set [Input] The set that includes the member record.
cmtype [Output] A pointer to the record type.
hDb [Input] The database handle.
Description This function retrieves the record type for the current member
record in the specified set. The d_cmtype function is particularly
useful in determining the current member record type of a multi-
member set.
Currency None
Changes
Example
short rtype; /* Record type */
long fld; /* Field type */
char txt[80]; /* Comment text */
...
d_cmtype(COMMENTS, &rtype, hDb);
switch ( rtype ) {
case TEXT30:
fld = T30_LINE;
break;
case TEXT55:
fld = T55_LINE;
break;
case TEXT80:
fld = T80_LINE;
}
d_csmread(COMMENTS, fld, txt, hDb);
Description This function frees the record instance lock on the current owner of
the specified set. You must establish a valid owner for the set before
the application can call d_cofree.
Currency None
Changes
Locking None
Requirements
Example
/* Read owner of a set */
d_colock(SET1, "r", hDb);
d_csoread(SET1, FLD1, &fld1, hDb);
d_cofree(SET1, hDb);
Parameters set [Input] The set type that includes the owner record.
ltype [Input] The lock type indicator. To apply a read
lock, specify "r".To apply a write lock, specify "w".
hDb [Input] The database handle.
Description This function requests a record instance lock of the specified type for
the current member of the indicated set. You must establish a valid
owner for the set before the application can call d_colock.
Note that locking a set owner only allows access to the owner
record. The application must separately lock the members if it
needs to access them. It must also separately lock the set if it needs
to access the set connection.
Your application can upgrade or downgrade an existing lock.
However, it cannot downgrade a write lock within a transaction.
Currency None
Changes
Locking None
Requirements
Description This function connects the current record to the current owner of the
specified set. The record is placed in the set in the order specified in
the schema for the database. Upon successful completion of
d_connect, the connected record becomes the current member of the
specified set.
Example
struct info irec; /* Tech. info record */
...
/* Make author record current owner of has_published */
d_setor(HAS_PUBLISHED, hDb);
...
/* Create new info record */
if ( d_fillnew(INFO, &irec, hDb) == S_OKAY ) {
/* Connect new info record to has_published set */
d_connect(HAS_PUBLISHED, hDb);
}
Description This function retrieves the record type for the current owner record
in the specified set.
Currency None
Changes
Locking This function does not require locks. However, if there is no lock on
Requirements the record, there is no guarantee that another user will not modify
or delete this record.
Example
short rtype;
...
/* Check consistency of database */
d_cotype(HAS_PUBLISHED, &rtype, hDb);
if ( rtype != AUTHOR )
pr_dberror();
Description This function frees the record instance lock on the current record.
You must establish a valid current record before the application can
call d_crfree.
The d_crfree function returns S_TRFREE if the application attempts
to free a write lock within a transaction. The application receives the
same error if it attempts to free a read lock within a transaction, but
has not enabled the freeing of read locks (see d_rdlockmodes). The
d_crfree function returns an S_NOLOCK error code if the
application attempts to free a record that has no record instance
lock.
Currency None
Changes
Locking None
Requirements
Example
/* Display record on screen */
...
d_keyfind(key1, usrval, hDb);
d_crlock("r", hDb);
...
... /* Display field */
...
d_crfree(hDb);
Description This function retrieves the database address of the current record
and copies the address into the location specified by dba. If the
current record is null (NULL_DBA), the d_crget function returns
S_NOCR and sets the dba parameter to NULL_DBA. Use the
d_crget function with the d_crset function to save and restore the
current record.
Currency None
Changes
Locking None
Requirements
Example
DB_ADDR save_dba;
...
/* Save current record for later retrieval */
d_crget(&save_dba, hDb);
...
/* Later, retrieve saved record */
d_crset(&save_dba, hDb);
d_recread(REC1, &irec, hDb);
Description This function requests a record instance lock of the specified type for
the current record. You must establish a valid current record before
the application can use d_crlock.
Your application can upgrade or downgrade an existing lock.
However, it cannot downgrade a write lock within a transaction.
Currency None
Changes
Locking None
Requirements
Example
/* Display record on screen */
...
d_keyfind(key1, usrval, hDb);
d_crlock("r", hDb);
...
... /* Display field */
...
d_crfree(hDb);
Parameters field [Input] The field type to read from the current
record.
data [Output] A pointer to the field contents.
hDb [Input] The database handle.
Description This function copies the contents of the specified field from the
current record to the area indicated by the data parameter. If field
specifies an array, d_crread reads the entire array (elements of an
array cannot be read individually). In the case of BLOB data, this
function retrieves the BLOB ID, a long integer that indicates the
page number in the BLOB ID file where the BLOB data begins.
Note: You must be sure that the data area is at least as long as the
field. A good practice is to use the defined constants from the
header file that is generated by the ddlproc utility (for example,
"char name[SIZEOF_NAME];").
Currency None
Changes
Locking If dirty reads are not enabled, the current record requires a lock.
Requirements
Example
char name[SIZEOF_NAME]; /* Author name */
...
/* Find author of info record */
d_findco(HAS_PUBLISHED, hDb);
d_crread(NAME, name, hDb);
Description This function sets the current record to the database address
specified by dba. Use the d_crset function in conjunction with the
d_crget function to save and restore the current record.
Locking None
Requirements
Example
DB_ADDR save_dba;
...
/* Save current record for later retrieval */
d_crget(&save_dba, hDb);
...
/* Later, retrieve saved record */
d_crset(&save_dba, hDb);
d_recread(REC1, &irec, hDb);
Parameters set [Input] The set that includes the current record.
ltype [Input] The lock type indicator. To apply a read
lock, specify "r". To apply a write lock, specify "w".
hDb [Input] The database handle.
Description This function requests a set instance lock of the specified type based
on the current member record of the specified set, instead of the
owner record. You must establish a valid current record before
your application can call d_crslock.
This function allows safe "upward navigation" from a member to its
owner. This single function performs the equivalent of d_setmr
followed by d_colock. The d_crslock function is required in this
situation because a d_setmr requires a set instance lock.
If the record is not currently connected to an instance of set type set,
d_crslock returns S_EOS. If the request is for a lock that is identical
to the existing set instance lock, d_crslock ignores the request and
returns S_OKAY.
Note that locking the set instance only allows access to the set
connection. The application must separately lock the owner if it
needs to access this record. It must separately lock the set members
if it needs to access them.
Your application can upgrade or downgrade an existing lock.
However, it cannot downgrade a write lock within a transaction.
Currency None
Changes
Locking None
Requirements
Example
d_crslock (SET1, "r", hDb); /* Safely find owner of current record */
d_findco (SET1, hDb)
Description This function retrieves the record type of the current record and
writes the type in the location indicated by the crtype parameter.
Currency None
Changes
Locking This function does not require locks. However, if there is no lock on
Requirements the specified record, there is no guarantee that another user will not
modify or delete the record.
Example
SHORT rtype;
...
d_crtype(&rtype, hDb);
if ( rtype == AUTHOR )
pr_author();
else if ( rtype == INFO )
pr_info();
Parameters field [Input] The field type within the current record.
data [Input] A pointer to the value to write for the
specified field.
hDb [Input] The database handle.
Description This function writes the value specified by the data parameter to the
indicated field in the current record. If field indicates a key field,
d_crwrite automatically updates the key. If field indicates a sort
field of a set arranged in ascending or descending order, the
d_crwrite function automatically adjusts the position of the record
in the set to reflect the order indicated. (In this case, a set instance or
set type lock is required.) If field indicates an array field, d_crwrite
writes the entire array (elements of an array cannot be written
individually).
Your application cannot use the d_crwrite function to modify a
compound key field, but you may modify the component fields of a
compound key. When a component field is modified, the key is
repositioned. If you intend to modify more than one component
field of the same compound key, it may be more efficient to use
d_recwrite, because the key will be repositioned only once.
The application cannot use the d_crwrite function to modify a BLOB
ID field. If the function is called for this type of data, it returns
S_BLOBUPD.
Note: You must be sure that the data area is at least as long as the
field. A good practice is to use the defined constants from the
header file that is generated by the ddlproc utility (for example,
"char name[SIZEOF_NAME];").
Currency None
Changes
Locking Write lock on the current record. If the specified field is used as a
Requirements sort field in a set, and it is being changed, a write lock is required on
the set as well.
Example
/* Change info record id_code*/
chg_id(char *old_id, char *new_id)
{
if ((stat = d_keyfind(ID_CODE, old_id, hDb)) == S_OKAY )
d_crwrite(ID_CODE, new_id, hDb);
else if ( stat == S_NOTFOUND )
printf("id_code %s not found\n", old_id);
return;
}
Parameters set [Input] The set type on which to free the lock.
hDb [Input] The database handle.
Description This function frees the set instance lock on the specified set. You
must establish a valid owner for the set before the application can
call d_csfree.
The d_csfree function returns S_TRFREE if the application attempts
to free a write lock within a transaction. The same error code is
returned if the application tries to free a read lock within a
transaction but has not enabled the freeing of read locks (see
d_rdlockmodes). The d_csfree function returns an S_NOLOCK
code if your application attempts to free a set that has no set
instance locks.
Currency None
Changes
Locking None
Requirements
Example
/* Safely navigate a set */
d_setor(SET1, hDb);
d_cslock(SET1, "r", hDb);
for (stat = d_findfm(SET1, hDb); stat == S_OKAY;
stat = d_findnm(SET1, hDb))
{ ... }
d_csfree(SET1, hDb);
Description This function requests a set instance lock of the specified type for the
current set. You must establish a valid current owner for the set
before the application can call d_cslock.
Note that locking a set only allows access to the set connection. The
application must separately lock the owner if it needs to access the
owner’s contents. It must also separately lock the set members if it
needs to access them.
Your application can upgrade or downgrade an existing lock.
However, it cannot downgrade a write lock within a transaction.
Currency None
Changes
Locking None
Requirements
Example
/* Safely navigate a set */
d_setor(SET1, hDb);
d_cslock(SET1, "r", hDb);
for (stat = d_findfm(SET1, hDb); stat == S_OKAY;
stat = d_findnm(SET1, hDb))
{
...
}
d_csfree(SET1, hDb);
Description This function retrieves the database address of the current member
of the specified set and copies the address into the location specified
by dba. If the current member is null (NULL_DBA), the d_csmget
function returns S_NOCM and sets the dba parameter to
NULL_DBA. Your application uses the d_csmget function with the
d_csmset function to save and restore the current member of a set.
Currency None
Changes
Locking None
Requirements
Example
/* Print key words for info record */
DB_ADDR dba;
...
/* Save current member of key_to_info set in
case info record was retrieved from a key word scan */
d_csmget(KEY_TO_INFO, &dba, hDb);
... /* Print key words thru info_to_key */
/* Restore current member */
d_csmset(KEY_TO_INFO, &dba, hDb);
Syntax short d_csmread (short set, long field, void *data, RDM_DB hDb)
Description This function copies the contents of field from the current member of
the specified set and places it in the area indicated by the data
parameter. The amount of data read is determined by the dictionary
length. If the field is an array field, the d_csmread function reads
the entire array (elements of an array cannot be read individually).
Note: You must be sure that the data area is at least as long as the
field. A good practice is to use the defined constants from the
header file that is generated by the ddlproc utility (for example,
"char name[SIZEOF_NAME];").
Currency None
Changes
Locking If dirty reads are not enabled, a lock is required on the current
Requirements member of the indicated set.
Example
char name[32]; /* Author name /
...
/* Print all authors in the database */
for ( stat = d_findfm(AUTHOR_LIST, hDb); stat == S_OKAY;
stat = d_findnm(AUTHOR_LIST, hDb) ) {
d_csmread(AUTHOR_LIST, NAME, name, hDb);
printf("%s\n", name);
}
Description This function sets the database address of the current member of the
specified set to the value specified by dba. It also sets the current
owner of the set to the record that owns the current member. Use
this function with d_csmget to save and restore the current member
of a set. You can also use d_csmset with d_crget or d_csoget.
Normally, a set instance lock is required before this function is
called (unless dirty reading is enabled). If the set is not locked and
the owner is not known, use d_crslock.
Example
/* Print key words for info record */
DB_ADDR dba;
...
/* Save current member of key_to_info set
in case info record was retrieved from a key word scan */
d_csmget(KEY_TO_INFO, &dba, hDb);
... /* Print key words thru info_to_key */
/* Restore current member */
d_csmset(KEY_TO_INFO, &dba, hDb);
Syntax short d_csmwrite (short set, long field, void *data, RDM_DB hDb)
Description This function writes the value specified by the data parameter to the
indicated field in the current member of the specified set. If field
indicates a key field, d_csmwrite automatically updates the key. If
field indicates a sort field of a set arranged in ascending or
descending order, the d_csmwrite function automatically adjusts
the position of the record in the set to reflect the order indicated. If
field indicates an array field, d_csmwrite writes the entire array
(elements of an array cannot be written individually).
Your application cannot use the d_csmwrite function to modify a
compound key field, but you may modify the component fields of a
compound key. When a component field is modified, the key is
repositioned. If you intend to modify more than one component
field of the same compound key, it may be more efficient to use
d_recwrite, because the key will be repositioned only once.
The application cannot use the d_csmwrite function to modify a
BLOB ID field. If the function is called for this type of data, it
returns S_BLOBUPD. Use d_blobdelete or d_blobwrite instead.
Note: You must be sure that the data area is at least as long as the
field. A good practice is to use the defined constants from the
header file that is generated by the ddlproc utility (for example,
"char name[SIZEOF_NAME];").
Currency None
Changes
Locking Write lock on the current member of the specified set. If the field
Requirements being updated is also used in a sort by clause for a sorted set, the set
must also be write-locked.
Example
char name[SIZEOF_NAME]; /* Author name */
...
/* Change author "Worth" to "Wirth" */
for ( stat = d_findfm(AUTHOR_LIST, hDb); stat == S_OKAY;
stat = d_findnm(AUTHOR_LIST, hDb) ) {
d_csmread(AUTHOR_LIST, NAME, name, hDb);
if ( strcmp(name, "Worth") == 0 )
d_csmwrite(AUTHOR_LIST, NAME, "Wirth", hDb);
}
Description This function retrieves the database address of the current owner of
the specified set and copies the address into the location specified by
dba. If the current owner is null (NULL_DBA), the function returns
S_NOCO and sets the dba parameter to NULL_DBA. Use this
function with the d_csoset function to save and restore the current
owner of a set.
Currency None
Changes
Locking None
Requirements
Example
DB_ADDR dba;
...
/* Save current author on stack for later processing */
d_csoget(HAS_PUBLISHED, &dba, hDb);
...
/* Restore saved author as owner of has_published */
d_csoset(HAS_PUBLISHED, &dba, hDb)
Syntax short d_csoread (short set, long field, void *data, RDM_DB hDb)
Description This function copies the contents of field from the current owner of
the specified set and places it in the area indicated by the data
parameter. The amount of data read is determined by the dictionary
length. If the field is an array field, the d_csoread function reads the
entire array (elements of an array cannot be read individually).
Note: You must be sure that the data area is at least as long as the
field. A good practice is to use the defined constants from the
header file that is generated by the ddlproc utility (for example,
"char name[SIZEOF_NAME];").
Currency None
Changes
Locking If dirty reads are not enabled, a lock is required on the current
Requirements owner of the specified set.
Example
char name[SIZEOF_NAME]; /* Author name /
...
/* Print author name associated with info record */
d_csoread(HAS_PUBLISHED, NAME, name, hDb);
printf("author: %s\n", name);
Parameters set [Input] The set containing the current owner record.
dba [Input] A pointer to the value to which to set the
database address.
hDb [Input] The database handle.
Description This function sets the database address of the current owner of the
specified set to the value specified by dba. It also sets the current
member of the set to NULL. If the current owner is null
(NULL_DBA), the function sets the current owner and current
member of the set to NULL_DBA. Use this function with d_csoget
to save and restore the current owner of a set.
Locking None
Requirements
Example
DB_ADDR dba;
...
/* Save current author on stack for later processing */
d_csoget(HAS_PUBLISHED, &dba, hDb);
...
/* Restore saved author as owner of has_published */
d_csoset(HAS_PUBLISHED, &dba, hDb);
Syntax short d_csowrite (short set, long field, void *data, RDM_DB hDb)
Description This function writes the value specified by the data parameter to the
indicated field in the current owner of the specified set. If field
indicates a key field, d_csowrite automatically updates the key. If
field indicates a sort field of a set arranged in ascending or
descending order, the d_csowrite function automatically adjusts the
position of the record in the set to reflect the order indicated. If field
indicates an array field, d_csowrite writes the entire array (elements
of an array cannot be written individually).
Your application cannot use the d_csowrite function to modify a
compound key field, but you may modify the component fields of a
compound key. When a component field is modified, the key is
repositioned. If you intend to modify more than one component
field of the same compound key, it may be more efficient to use
d_recwrite, because the key will be repositioned only once.
The application cannot use the d_csowrite function to modify a
BLOB ID field. If the function is called for this type of data, it
returns S_BLOBUPD.
Note: You must be sure that the data area is at least as long as the
field. A good practice is to use the defined constants from the
header file that is generated by the ddlproc utility (for example,
"char name[SIZEOF_NAME];").
Currency None
Changes
Locking Write lock on the current owner of set. If the field being updated is
Requirements also used in a sort by clause for a sorted set, the set must also be
write-locked.
Example
/* Change author to "Wirth, N." */
d_csowrite(HAS_PUBLISHED, NAME, "Wirth, N.", hDb);
d_curkey Set the key position for keys in the current record
Description This function sets the current key stack position for every key in the
current record from the field values in the current record. Thus, a
subsequent d_keynext call for any of these key fields will return the
next key value (either the next instance of a duplicate, or the next
higher value).
Currency None
Changes
Locking None. However, since the record is not locked, the application
Requirements might get an S_DELETED error, indicating that the record
containing these keys (the current record) has been deleted by
another user.
Example
char sea_zip[6], cust_zip[6];
char id[4];
...
/* Locate some customers with same zip code as "SEA" */
if ( d_keyfind(CUST_ID, "SEA", hDb) == S_OKAY ) {
d_crread(ZIP_CODE, &sea_zip, hDb);
d_curkey(hDb);
while ( d_keynext(ZIP_CODE, hDb) == S_OKAY ) {
d_crread(ZIP_CODE, &cust_zip, hDb);
if ( strcmp(sea_zip, cust_zip) ! = 0)
break;
d_crread(CUST_ID, id, hDb);
printf("cust_id = %s\n", cust_id);
}
}
Description This function frees the record instance lock on a record with the
database address specified in the dba parameter. The d_dbafree
function returns S_TRFREE if the application attempts to free a
write lock within a transaction. The application receives the same
error if the application attempts to free a read lock within a
transaction, but has not enabled the freeing of read locks (see
d_rdlockmodes). The d_dbafree function returns an S_NOLOCK
error code if the application attempts to free a record that has no
record instance locks.
Currency None
Changes
Locking None
Requirements
Example
/* Free lock on previously saved and locked record */
...
d_crlock("r", hDb);
d_crget(&savedba, hDb);
...
d_dbafree(savedba, hDb);
Description This function requests a record instance lock of the specified type for
the record with the specified database address (dba parameter).
Your application can upgrade or downgrade an existing lock.
However, it cannot downgrade a write lock within a transaction.
Currency None
Changes
Locking None
Requirements
Example
DB_ADDR lockarry[MAXLOCKS]
...
.... /* Setup lockarray */
...
/* Step through array and lock records */
...
for (i = 0; i < max; i++)
d_dbalock(lockarray[i], "r", hDb);
Description This function extracts the file number and slot number from the
specified database address. When finished processing, the function
writes the file number and the slot number for use by your
application. The Velocis User’s Guide explains the use of
d_decode_dba in Chapter 9.
Currency None
Changes
Locking None
Requirements
Example
DB_ADDR dba; /* Database address of current record */
short file; /* File number */
long slot; /* Slot number */
...
/* Record to be displayed is current record */
d_crget(&dba, hDb);
d_decode_dba(dba, &file, &slot);
printf("id number: %d-%Id\n", file, slot);
Description This function deletes the current record from the database. All keys
associated with the record are removed from their respective key
files. Then the record is marked as deleted and placed on the delete
chain for the file in which it resides. Before calling the d_delete
function, the application must have removed the record from all sets
of which it is an owner or a member.
Example
/* Disconnect and delete abstract */
d_setom(ABSTRACT, HAS_PUBLISHED, hDb);
while ( d_findfm(ABSTRACT, hDb) == S_OKAY ) {
d_discon(ABSTRACT, hDb);
d_delete(hDb);
}
Syntax short d_dict (short item, short element, void *values, char objname[],
RDM_DB hDb)
Currency None
Changes
Locking None
Requirements
Parameters nset [Input] The set type from which to disconnect the
current member.
hDb [Input] The database handle.
Description This function disconnects the current member record from the
specified set. The disconnected record becomes the current record,
and the next member of the set becomes the new current member.
The d_discon function returns S_EOS when it has disconnected the
last set member (that is, the one at the end of the set).
Example
/* Disconnect and delete abstract */
d_setom(ABSTRACT, HAS_PUBLISHED, hDb);
while ( d_findfm(ABSTRACT, hDb) == S_OKAY ) {
d_discon(ABSTRACT, hDb);
d_delete(hDb);
}
Description This function disconnects all members from the sets owned by the
current record. It also disconnects the current record from all sets of
which it is a member. Then d_disdel deletes the current record.
Write locks are required on all affected sets and the current record.
Locking Write lock on all sets to which the current record is connected (is a
Requirements member or owner), and write lock on the current record. The
function automatically frees the record instance lock when it deletes
the current record. If transactions are being used, the record
instance lock is held until the end of transactions. Otherwise, it is
freed immediately.
Example
/* Disconnect and delete abstract */
d_setom(ABSTRACT, HAS_PUBLISHED, hDb);
while ( d_findfm(ABSTRACT, hDb) == S_OKAY )
d_disdel(hDb);
Description This function forms a database address from the specified file
number and slot number. The use of d_encode_dba is explained in
Chapter 9 of the Velocis User’s Guide.
Currency None
Changes
Locking None
Requirements
Example
DB_ADDR dba; /* Database address */
short file; /* File number */
long slot; /* Slot number */
struct record rec; /* Record buffer */
...
/* Extract file number of slot number from id number string */
/* Display record */
...
Currency None
Changes
Locking None
Requirements
Example
char errbuf[80];
...
if ((stat = d_grplock(glock, numglock, hSess) != S_OKAY) {
d_errinfo(errbuf, sizeof(errbuf), hSess);
printf("d_grplock failed: %s\n", errbuf);
}
Description This function creates a new record occurrence of the specified type
(nrec) in the database and fills it with the data pointed to by recval. If
the record contains key fields, the d_fillnew function automatically
inserts them in the correct key files. If any key field is unique and
the data in the field is not unique, the function returns
S_DUPLICATE and fails to create the record. If record type nrec
contains BLOB fields, each BLOB ID field must contain zero
(NULL_BLOB). BLOB contents may be written to the BLOB ID
fields following the creation of the record.
The d_fillnew function does not make any set connections or create
optional key fields. Your application can only create optional key
fields by calling d_keystore.
Example
struct info irec;
...
d_trbegin("ins", hSess);
/* Create new tech info record */
if(d_fillnew(INFO, &irec, hDb) == S_DUPLICATE)
printf("duplicate id_code: %s\n", irec.id_code);
else {
... /* Connect to appropriate sets */
}
d_trend(hSess);
Description This function finds the owner of the current record in the specified
set (nset). The function sets the current owner of the set to the
record found. The function sets the current member of the set from
the current record. The current record is then set to the new current
owner.
Locking If dirty reads are not enabled, the set must be locked.
Requirements
Example
/* Print key words associated with tech. info */
while ( d_findnm(INFO_TO_KEY, hDb) == S_OKAY ) {
d_findco(KEY_TO_INFO, hDb);
d_crread(WORD, key, hDb);
printf("%s\n", key);
}
Description This function finds the first member of the specified set (nset). The
d_findfm function sets the current member of the set and the
current record to the found record. The function returns S_EOS if it
finds no members for the set.
Locking If dirty reads are not enabled, the specified set must be locked.
Requirements
Example
char name[32]; /* Author name */
...
/* Print author list in ascending order */
for ( stat = d_findfm(AUTHOR_LIST, hDb); stat == S_OKAY;
stat = d_findnm(AUTHOR_LIST, hDb) ) {
d_crread(NAME, name, hDb);
printf("author: %s\n", name);
}
Description This function finds the last member of the specified set (nset). The
d_findlm function sets the current member of the set and the
current record to the found record. The function returns S_EOS if it
finds no members for the set. See the description of d_findpm.
Locking If dirty reads are not enabled, the specified set must be locked.
Requirements
Example
char name[32]; /* Author name */
...
/* Print author list in descending order */
for ( stat = d_findlm(AUTHOR_LIST, hDb); stat == S_OKAY;
stat = d_findpm(AUTHOR_LIST, hDb) ) {
d_crread(NAME, name, hDb);
printf("author: %s\n", name);
}
Description This function finds the next member of the specified set (nset). The
d_findnm function sets the current member of the set and the
current record to the found record. The function returns S_EOS if it
does not find a next member. If there is no current member of the
specified set, d_findnm behaves like d_findfm.
Locking If dirty reads are not enabled, the specified set must be locked.
Requirements
Example
char name[32]; /* Author name */
...
/* Print author list in ascending order */
for ( stat = d_findfm(AUTHOR_LIST, hDb); stat == S_OKAY;
stat = d_findnm(AUTHOR_LIST, hDb) ) {
d_crread(NAME, name, hDb);
printf("author: %s\n", name);
}
Description This function finds the previous member of the specified set (nset).
The d_findpm function sets the current member of the set and the
current record to the found record. The function returns S_EOS if it
does not find a previous member. If there is no current member of a
set, d_findpm behaves like d_findlm.
Locking If dirty reads are not enabled, the specified set must be locked.
Requirements
Example
char name[32]; /* Author name */
...
/* Print author list in descending order */
for ( stat = d_findlm(AUTHOR_LIST, hDb); stat == S_OKAY;
stat = d_findpm(AUTHOR_LIST, hDb) ) {
d_crread(NAME, name, hDb);
printf("author: %s\n", name);
}
Syntax short d_fldcmp (long field_id, const void *value1, const void *value2,
short *result, RDM_DB hDb)
Description This function compares two values stored in the field identified by
field_id. The result of the comparison returned is identical to that
obtained by the runtime while performing operations such as
building index trees, performing SQL queries where the order is
specified, etc. This function aids custom sorting within client
applications and extension modules, while remaining consistent
with sorting performed by the server runtime.
If field_id identifies a character or Unicode field, Velocis compares
the values according to the Locale or country table settings, if any.
Example
char str1[] = "Warren, Anita";
char str2[] = "warren, anita";
short cmpres;
d_getDD Get the RPC parameter data descriptor for a field or record type
Currency None
Changes
Locking None
Requirements
Example
/* ===================================================================
Envelope function for d_recread
*/
short REXTERNAL Ed_recread(
PL_DATADESC *inParms,
PL_DATADESC *outParms)
{
short rc;
short fcnRet;
size_t length;
short count;
short rec;
RDM_DB hDb;
PL_ITEM *pSI;
char *data;
char *funcName = "d_recread";
return fcnRet;
}
(continued)
(continued)
/* ===================================================================
Envelope function for d_keyread
*/
short REXTERNAL Ed_keyread(
PL_DATADESC *inParms,
PL_DATADESC *outParms)
{
short rc;
short fcnRet;
size_t length;
short count;
long field;
RDM_DB hDb;
PL_ITEM *pSI;
char *key_val;
char *funcName = "d_keyread";
if (count == 1)
rc = pl_put(outParms, pSI->type, PL_FLAG_FREE, key_val, length);
else
rc = pl_putStruct(outParms, pSI, PL_FLAG_FREE, key_val, 0);
if (rc != S_OKAY)
return ModRPCError(funcName, 2, rc);
return fcnRet;
}
Description This function allows the application to make multiple lock requests
with one call. Any number and kind of locks can be requested. The
application can use this function to minimize, or even eliminate,
deadlock potential. If d_grplock cannot grant any of the lock
requests, it grants none of them.
You must correctly establish the currency (current record, owner,
and members of a set) for any lock request that depends on
currency. An existing lock can be upgraded or downgraded,
although a write lock cannot be downgraded within a transaction.
Currency None
Changes
Locking None
Requirements
Example
GROUPLOCK glock[3];
...
/* Lock the first 3 members of set */
d_setor(SET1, hDb);
stat = d_findfm(SET1, hDb);
for (i = 0; stat == S_OKAY && i < 3; i++) {
glock[i].ftype = DBALOCK;
glock[i].lmode = ’r’;
d_crget(&dba, hDb);
glock[i].dba = dba;
glock[i].hdb = hDb;
stat = d_findnm(SET1, hDb);
}
d_grplock(glock, 3, hSess);
Description This function closes one database, selected by its database handle
(hDb). If a transaction is active when the application calls d_iclose,
the transaction is aborted. If only one database has been opened in
the same session as hDb, this function behaves like d_close.
Currency None
Changes
Locking None
Requirements
Example
d_open("sales", "s", hSess, &hSales);
d_iopen("invntory", "s", hSess, &hInv);
...
/* Eliminate sales and add payroll */
d_iclose(hSales);
d_iopen("payroll", "s", hSess, &hPay);
/* Close all databases */
d_close(hSess);
Description This function opens the specified database (dbname) with the type of
database access indicated by the openmode parameter. Your
application calls this function to open additional databases after
opening the first database in a call to d_open. If no databases are
already open within session hSess, this function works like d_open.
Locking None
Requirements
Example
d_open("sales", "s", hSess, &hSales);
d_iopen("invntory", "s", hSess, &hInv);
...
/* Eliminate sales and add payroll */
d_iclose(hSales);
d_iopen("payroll", "s", hSess, &hPay);
/* Close all databases */
d_close(hSess);
Note: If the current record is not of a legal member record type for
the indicated set, d_ismember calls dberr with the S_INVMEM
error code.
Currency None
Changes
Example
/* Annual corporate awards */
while ( d_keynext(EMPLOYEE_ID, hDb) == S_OKAY ) {
if ( d_ismember(DIVISION_MANAGER, hDb) == S_OKAY ) {
/* Award large dividend */
...
}
else if ( d_ismember(DEPT_MANAGER, hDb) == S_OKAY ) {
/* Award raise */
...
}
else {
/* Give commendation */
...
}
}
Description This function determines whether the current record has any
members connected to it through the specified set. If the function
finds that the record is an owner of one or more members, the
function returns S_OKAY. If the record is an owner of an empty set,
the d_isowner function returns S_EOS.
Note: If the current record is not of a legal owner record type for the
specified set, d_isowner calls the application error handler function,
specified by d_set_dberr, with the S_INVOWN error code.
Currency None
Changes
Locking This function does not require locks. However, it might read old
Requirements data if the specified set is not locked.
Example
if ( d_isowner(ALTERNATE_SET_1, hDb) == S_OKAY ) {
/* Process set 1 records */
...
}
else if ( d_isowner(ALTERNATE_SET_2, hDb) == S_OKAY ) {
/* Process set 2 records */
...
}
else if ( d_isowner(ALTERNATE_SET_3, hDb) == S_OKAY ) {
/* Process set 3 records */
...
}
Description This function deletes the key entry associated with the specified
optional key field in the current record.
Currency None
Changes
Example
if ( d_keyfind(EMP_ID, "8505", 4, hDb) ) == S_OKAY ) {
/* Upgrade employee to manager */
d_keydel(EMP_ID, hDb);
d_keystore(MGR_ID, hDb);
}
Parameters field [Input] The key field for which to set search
direction.
dir [Input] A flag indicating the direction of the search.
To search forward, specify 0. To search backward,
specify 1.
hDb [Input] The database handle.
Description This function sets the direction for all subsequent key searching and
navigation for the specified key. If the dir parameter is zero, key
search and navigation functions behave normally. However, if the
dir parameter is 1, the normal behavior of the search and navigation
functions changes.
The Navigation Function Changes section below describes the
changes that take place in the navigation functions when the search
direction is 1. Note especially the change in behavior of d_keyfind
and d_pkeyfind. The primary purpose of d_keydir is to make
d_keyfind and d_pkeyfind navigate to the last of a group of
duplicate keys, to make it easy to scan a key in reverse order.
Currency None
Changes
Locking None
Requirements
Example
/* Scan a key find in reverse order */
d_keydir(NAME, 1, hDb);
for (rv = d_keyfrst(NAME, hDb); rv == S_OKAY;
rv = d_keynext (NAME, hDb)) {
... /* Here if another key has been found */
}
Description This function determines whether the key for an optional key field
in the current record is stored. The d_keyexist function returns
S_OKAY if the key is stored. If the key is not stored, the function
returns S_NOTFOUND.
Currency None
Changes
Locking If dirty reads are not enabled, the current record must be locked.
Requirements
Example
if ( d_keyexist(EMP_ID, hDb) == S_NOTFOUND ) {
/* Store employee id */
d_keystore(EMP_ID, hDb);
}
Syntax short d_keyfind (long field, const void *fldval, RDM_DB hDb)
Description This function finds a record occurrence based on the specified key
(fldval parameter). Regardless of whether the function finds the key,
the key stack remains positioned so that a subsequent d_keynext (or
d_keyprev) call will retrieve the record with the next higher (or
lower) key value. If the value of fldval is NULL, the d_keyfind
function positions the key stack at the beginning so that d_keynext
will return the first key on file.
Locking None. However, if the record is not locked, your application might
Requirements receive an S_DELETED error code when it later attempts to read the
record found by d_keyfind. Also, another application might change
the record so that its key field no longer matches the value specified
to d_keyfind.
Example
char id[16];
...
/* Display all database related info records
(those for which id begins with "db") */
d_keyfind(ID_CODE, "db", hDb); /* Position to start of "db"s */
do {
d_keyread(id, hDb);
if ( strncmp(id, "db", 2) )
break; /* No more "db"s */
d_recread(REC1, &irec, hDb);
... /* Print info records contents */
} while ( d_keynext(ID_CODE, hDb) == S_OKAY);
d_keyfrst Find the record associated with the first occurrence of a key
Description This function finds the record occurrence associated with the first
occurrence of the specified key (field parameter).
Locking None. However, if the record is not locked, your application might
Requirements receive S_DELETED when it later attempts to read the record found
by d_keyfrst. This code indicates that another application deleted
the record.
Example
/* Display all info records in id_code order */
for ( stat = d_keyfrst(ID_CODE, hDb); stat == S_OKAY;
stat = d_keynext(ID_CODE, hDb) ) {
d_recread(REC1, &irec, hDb);
... /* Print info record contents */
}
d_keylast Find the record associated with the last occurrence of a key
Parameters field [Input] The key field type for which to search.
hDb [Input] The database handle.
Description This function finds the record occurrence associated with the last
occurrence of the specified key (field parameter).
Locking None. However, if the record is not locked, your application might
Requirements receive S_DELETED when it later attempts to read the record found
by d_keylast. This code indicates that another application deleted
the record.
Example
/* Display all info records in reverse id_code order */
for ( stat = d_keylast(ID_CODE, hDb); stat == S_OKAY;
stat = d_keyprev(ID_CODE, hDb) ) {
d_recread(REC1, &irec, hDb);
... /* Print info record contents */
}
Description This function finds the record occurrence associated with the next
occurrence of the specified key (field parameter). The d_keynext
function returns S_NOTFOUND if it finds no more keys. Because
Velocis keeps track of the relative position of each key field in a key
stack, the application can intersperse d_keynext calls for multiple
key fields.
Note: The first call to d_keynext (or the first call after a return of
S_NOTFOUND) finds the first key on file.
Locking None. However, if the record is not locked, your application might
Requirements receive S_DELETED when it later attempts to read the record found
by d_keynext. This code indicates that another application has
deleted the record.
Example
/* Display all info records in id_code order */
for ( stat = d_keyfrst(ID_CODE, hDb); stat == S_OKAY;
stat = d_keynext(ID_CODE, hDb) ) {
d_recread(REC1, &irec, hDb);
... /* Print info record contents */
}
Description This function finds the record occurrence associated with the
previous occurrence of the specified key (field parameter). The
d_keyprev function returns S_NOTFOUND if it finds no more keys.
Because Velocis keeps track of the relative position of each key field
in a key stack, the application can intersperse d_keyprev calls for
multiple key fields.
Note: The first call to d_keyprev (or the first call after a return of
S_NOTFOUND) finds the last key on file.
Locking None. However, if the record is not locked, your application might
Requirements receive an S_DELETED error code when it later attempts to read the
record found by d_keyprev. This code indicates that another
application has deleted the record.
Example
/* Display all info records in reverse id_code order */
while ( d_keyprev(ID_CODE, hDb) == S_OKAY ) {
d_recread(REC1, &irec, hDb);
... /* Print info record contents */
}
Parameters field [Input] The key field type for which to read the
state.
buf [Output] A pointer to the key state information.
hDb [Input] The database handle.
Description This function copies state information for the position of the
specified key into the buffer indicated by buf. Your application uses
the d_keyrdstate function with d_keyszstate and d_keywrstate to
save and restore the current position of a key in a key file.
Currency None
Changes
Locking None
Requirements
Example
void *buf; /* Buffer to hold state information */
unsigned short bufLen; /* Size of buffer needed to hold this key’s
state information */
...
d_keyszstate(ID_CODE, &bufLen, hDb); /* Get required buffer size */
buf = rm_getMemory(bufLen, 0); /* Allocate a buffer */
d_keyrdstate(ID_CODE, buf, hDb); /* Save key state in buffer */
... /* Do some other processing */
d_keywrstate(ID_CODE, buf, hDb); /* Restore key state */
Description This function reads the value of the last key found by a key retrieval
function. The application can use the d_keyread function to check
the value of a key without having to read its associated record.
Thus, a list of key values can be produced without reading the data
file by using a combination of the d_keyfrst, d_keynext, and
d_keyread functions.
Currency None
Changes
Locking None. However, if the record is not locked, the application might
Requirements receive the S_DELETED error code, indicating that another
application deleted the record. Another application might also
change the key fields of the current record.
Example
char id[16]:
...
d_keyfind(ID_CODE, "db", hDb); /* Position to start of "db"s */
while ( d_keynext(ID_CODE, hDb) == S_OKAY ) {
d_keyread(ID_CODE, id, hDb);
if ( strncmp(id, "db", 2) ) ! = 0)
break; /* No more "db"s */
d_recread(REC1, &irec, hDb);
... /* Print info record contents */
}
Parameters field [Input] The optional key field type for which to
store a value.
hDb [Input] The database handle.
Description This function creates a key entry from the data contained in the
current record for the specified optional key (field parameter). Your
application can only call the d_keystore function after the record is
created. Once the application stores an optional key, the key is
automatically modified any time its field contents are modified (for
example, by d_recwrite).
Currency None
Changes
Example
/* Batch load key for daily stock tracking record */
for ( stat = d_recfrst(STOCK, hDb); stat == S_OKAY;
stat = d_recnext(STOCK, hDb) )
d_keystore(ID_CODE, hDb);
Syntax short d_keyszstate (long field, unsigned short *pSize, RDM_DB hDb)
Parameters field [Input] The key field type for which to get the state
size.
pSize [Output] A pointer to the size, in bytes, of the buffer
to store key state information.
hDb [Input] The database handle.
Description This function retrieves the size of a buffer to store state information
for the specified key field, regardless of the key state. The retrieved
size does not change during execution of the application. Your
application uses the d_keyszstate function with d_keyrdstate and
d_keywrstate to save and restore the state of a key file.
Currency None
Changes
Locking None
Requirements
Example
void *buf; /* Buffer to hold state information */
unsigned short bufLen; /* Size of buffer needed to hold
this key’s state information */
...
d_keyszstate(ID_CODE, &bufLen, hDb); /* Get required buffer size */
buf = rm_getMemory(bufLen, 0); /* Allocate a buffer */
d_keyrdstate(ID_CODE, buf, hDb); /* Save key state in buffer */
... /* Do some other processing */
d_keywrstate(ID_CODE, buf, hDb); /* Restore key state */
Parameters field [Input] The key field type for which to restore the
state.
buf [Input] A pointer to a buffer that contains key state
information, as obtained using the d_keyrdstate
function.
hDb [Input] The database handle.
Description This function restores the key state information from the buffer
indicated by buf. Your application uses the d_keywrstate function
with d_keyszstate and d_keyrdstate to save and restore the state of
the key file.
Locking None
Requirements
Example
void *buf; /* Buffer to hold state information */
unsigned short bufLen; /* Size of buffer needed to hold
this key’s state information */
...
d_keyszstate(ID_CODE, &bufLen, hDb); /* Get required buffer size */
buf = rm_getMemory(bufLen, 0); /* Allocate a buffer */
d_keyrdstate(ID_CODE, buf, hDb); /* Save key state in buffer */
... /* Do some other processing */
d_keywrstate(ID_CODE, buf, hDb); /* Restore key state */
Description This function creates a new record occurrence of the specified type
(nrec). If the record contains key fields, the application must first
call d_setkey to set up those field’s values. The d_makenew
function automatically stores the key fields in the key file and in the
record. If any key field is unique and the data in the field is not
unique, d_makenew returns S_DUPLICATE and fails to create the
record.
Your application cannot call d_makenew to create records that
contain compound keys. For these, the application must use
d_fillnew.
Example
/* Create intersection record */
d_makenew(INTERSECT, hDb);
d_connect(KEY_TO_INFO, hDb);
d_connect(INFO_TO_KEY, hDb);
Description This function retrieves a member count for the specified current set.
Currency None
Changes
Locking If dirty reads are not enabled, the set must be locked.
Requirements
Example
char name[32]; /* Author name */
long num; /* Number of pubs. */
...
/* Print list of authors with total number of
associated publications in database */
for ( stat = d_findfm(AUTHOR_LIST, hDb); stat == S_OKAY;
stat = d_findnm(AUTHOR_LIST, hDb) ) {
d_crread(NAME, name, hDb);
d_setor(HAS_PUBLISHED, hDb);
d_members(HAS_PUBLISHED, &num, hDb);
printf("author %s has %ld publications on file\n", name, num);
}
d_nullset Set the SQL null value flag for a data field in the current record
Syntax short d_nullset (long field, void *bitmap, short isnull, RDM_DB hDb)
Parameters field [Input] The identifier of the field for which to set
the null value flag.
bitmap [Input] A pointer to the sysnulls_ field value for the
current record. If you have not previously read this
value, specify NULL; the function will
automatically read in the current value.
isnull [Input] The null flag. Specify TRUE (1) to set the
field to null or FALSE (0) to set the field to non-null.
hDb [Input] The database handle.
Description This function is used to set the SQL null indicator bit associated with
the specified field in the sysnulls_ field of the current record.
If you have previously read the current record (e.g., d_recread) or
the sysnulls_ field (e.g., d_crread), you can pass a pointer to the
sysnulls_ value by using the bitmap parameter. If bitmap is NULL,
the value of sysnulls_ will automatically be read from the current
record by d_nullset.
An SQL null value is controlled by the bit in the sysnulls_ data field
corresponding to the data field specified by field. When the field is
null, the bit will be on (1), and the value of field will be set to either
the minimum possible value (for scalar numeric types) or all zeros
(for all other types). When the field is not null, the bit will be off (0).
A TRUE (1 or nonzero) value for the isnull parameter will set field to
null. A FALSE (0) value for isnull will set field to non-null.
For more information about how SQL null values are implemented
in the Core DDL associated with an SQL database, see Chapter 6 of
the Velocis User’s Guide.
Currency None
Changes
Example
#include "velocis.h"
...
/* scan through all salespersons */
for ( stat = d_recfrst(SALESPERSON, hSales);
stat == S_OKAY; stat = d_recnext(hSales) ) {
d_crget(&curdba, hSales);
if ( !DB_ADDR_EQ(curdba, vpdba) ) {
d_nulltest(SALESPERSON_MGR_ID, NULL, &is_null, hSales);
if ( is_null ) {
/* connect to manages */
d_connect(MANAGES, hSales);
d_nulltest Read the SQL null value flag for a data field in the current record
Parameters field [Input] The identifier of the field for which to read
the null value flag.
bitmap [Input] A pointer to the sysnulls_ field value for the
current record. If you have not previously read this
value, specify NULL; the function will
automatically read in the current value.
pIsnull [Output] A pointer to a short variable that will
contain TRUE (1) if field is null or FALSE (0) if field
is not null.
hDb [Input] The database handle.
Description This function is used to read from the sysnulls_ field of the current
record the SQL null indicator bit associated with the specified field.
If you have previously read the current record (e.g., d_recread) or
the sysnulls_ field (e.g., d_crread), you can pass a pointer to the
sysnulls_ value using the bitmap parameter. If bitmap is NULL, the
current value of sysnulls_ will automatically be read from the
current record by d_nullset.
An SQL null value is controlled by the bit in the sysnulls_ data field
corresponding to the data field specified by field. When the field is
null, the bit will be on (1), and the value of field will be set to either
the minimum possible value (for scalar numeric types) or all zeros
(for all other types). When the field is not null, the bit will be off (0).
The current null indicator bit value (1 or 0) is returned in the short
variable pointed to by pIsnull.
For more information about how SQL null values are implemented
in the Core DDL associated with an SQL database, see Chapter 6 of
the Velocis User’s Guide.
Currency None
Changes
Locking If dirty reads are not enabled, the current record requires a lock.
Requirements
Example
#include "velocis.h"
...
/* scan through all salespersons */
for ( stat = d_recfrst(SALESPERSON, hSales);
stat == S_OKAY; stat = d_recnext(hSales) ) {
d_crget(&curdba, hSales);
if ( !DB_ADDR_EQ(curdba, vpdba) ) {
d_nulltest(SALESPERSON_MGR_ID, NULL, &is_null, hSales);
if ( is_null ) {
/* connect to manages */
d_connect(MANAGES, hSales);
Note: If you use SQL databases, calling the d_open function can
inadvertently end all active transactions in those databases, because
the function closes all databases before opening a database. To
avoid this problem, use the d_iopen function.
Locking None
Requirements
Example
stat = d_open("tims", "x", srv, &hDb);
if (stat ==S_UNAVAIL) {
user_message("database unavailable");
terminate();
}
Description This function finds a record occurrence based on the specified key
(field parameter). The area to search is restricted to the specified
fields and characters of the last considered value of the key (that is,
the last field of the key, unless restricted using nFields). The
d_pkeyfind function with nFields equal to zero and partialStrLen
equal to zero is equivalent to d_keyfind.
Regardless of whether d_pkeyfind finds the record it seeks, the key
stack remains positioned so that a subsequent call to d_keynext (or
d_keyprev, d_pkeynext, or d_pkeyprev) retrieves the record with
the next higher (or lower) key value. If field is set to NULL, the
d_pkeyfind function positions the key stack at the beginning so that
d_keynext will retrieve the first key on file.
Locking None. However, if the record is not locked, your application might
Requirements receive an S_DELETED error code when it later attempts to read the
record found by d_pkeyfind. Another application can also change
the record so that its key field no longer matches the value specified
to d_pkeyfind.
Example
/* Given a compound key on last and first name, find all records
matching R Miller (for example Ralph Miller, Rich Miller). */
struct name_index NI;
strcpy(NI.last_name, "Miller");
strcpy(NI.first_name, "R");
for (rv = d_pkeyfind(NAME_INDEX, 2, 1, &NI, hDb); rv == S_OKAY;
rv = d_pkeynext(NAME_INDEX, 2, 1, &NI, hDb)) {
... /* Process this "R Miller" record */
}
d_pkeynext Find the record occurrence associated with the next key
Parameters field [Input] The key field type for which to search.
nFields [Input] The number of fields. If this parameter is
set to zero, the function searches all fields. If this
parameter specifies a non-zero value, the function
uses only the number of fields indicated. This
parameter applies only to compound keys.
partialStrLen [Input] The partial string length, in bytes. If this
parameter specifes a non-zero value, the function
uses only this many characters of the last field being
considered (depending on nFields above).
fldval [Input] A pointer to the data to be searched.
hDb [Input] The database handle.
Description This function finds the record occurrence associated with the next
occurrence of the specified key (field parameter). The d_pkeynext
function with nFields equal to zero and partialStrLen equal to zero is
equivalent to d_keynext.
The d_pkeynext function returns S_NOTFOUND if it finds no more
keys or a key that is greater than the key specified by fldval (as
restricted by nFields and partialStrLen). Because Velocis keeps track
of the relative position of each key field in a key stack, the
application can intersperse d_pkeynext and d_keynext calls for
multiple key fields.
Locking None. However, if the record is not locked, your application might
Requirements receive an S_DELETED error code when it later attempts to read the
Example
/* Given a compound key on last and first name, find all records
matching R Miller (for example Ralph Miller, Rich Miller). */
struct name_index NI;
strcpy(NI.last_name, "Miller");
strcpy(NI.first_name, "R");
for (rv = d_pkeyfind(NAME_INDEX, 2, 1, &NI, hDb); rv == S_OKAY;
rv = d_pkeynext(NAME_INDEX, 2, 1, &NI, hDb)) {
... /* Process this "R Miller" record */
}
d_pkeyprev Find the record occurrence associated with the previous key
Parameters field [Input] The field type of the key field for which the
previous key will be found.
nFields [Input] The number of fields. If this parameter has
a value of zero, the function searches all fields. If
this parameter specifies a non-zero value, the
function uses only the number of fields indicated.
This parameter applies only to compound keys.
partialStrLen [Input] The partial string length. If this parameter
specifes a non-zero value, the function uses only
this many characters of the last field being
considered (depending on nFields above).
fldval [Input] A pointer to the data to be searched.
hDb [Input] The database handle.
Description This function finds the record occurrence associated with the
previous occurrence of the specified key (field parameter). The
d_pkeyprev function with nFields equal to zero and partialStrLen
equal to zero is equivalent to d_keyprev.
The d_pkeyprev function returns S_NOTFOUND if it finds no more
keys, or a key whose value is less than that specified by fldval (as
restricted by nFields and partialStrLen). Because Velocis keeps track
of the relative position of each key field in a key stack, the
application can interleave d_pkeyprev and d_keyprev calls for
multiple key fields.
Locking None. However, if the record is not locked, your application might
Requirements receive an S_DELETED error code when it later attempts to read the
record found by d_pkeyprev. This code indicates that another
application has deleted the record. Also, another application might
change the record so that its key field no longer matches the value
specified to d_pkeyprev.
Example
/* Given a key on NUMBER (a ’short’), print all records with
NUMBER> = 25, in order of highest to lowest number. */
short minToPrint = 25;
for (rv = d_keylast(NUMBER hDb); rv == S_OKAY;
rv = d_pkeyprev(NUMBER, 0, 0, (void *)&minToPrint, hDb)) {
d_recread(...); /* Read this record */
... /* ... and print it */
}
Description This function copies the contents of the currency table to the buffer
pointed to by currbuff. It writes the size of the currency table buffer
to the currsize parameter, which must not be NULL. If currbuff is set
to NULL, or buflen is set to zero, d_rdcurr writes no currency
information and places in currsize the size, in bytes, of the buffer
required to store the currency. Your application can use this
information in allocating buffer for subsequent calls to d_rdcurr. If
buflen is non-zero, but less than the currency size, d_rdcurr writes
the required size in currsize and returns an S_BUFLEN error code
without writing to currbuff.
The currency table is returned as an array of DB_ADDRs. The first
in the table is the current record, followed by the current set owners,
and then the current set members. If the application knows the
number of sets in the database, the length of curbuff can be
calculated as:
buflen = ((numSets * 2) + 1) * sizeof(DB_ADDR)
Currency None
Changes
Locking None
Requirements
Example
DB_ADDR ctab[128]; /*Save currency table*/
short csize; /*Size of saved currency table*/
...
d_rdcurr(ctab, sizeof(ctab), &csize, hDb); /*Save currency tables*/
... /*Do other processing*/
d_wrcurr(ctab, sizeof(ctab), hDb); /*Restore currency tables*/
Description This function sets the current level of transaction isolation for multi-
user database environments. In a call to this function, the
application enables dirty reads and freeable read locks within a
transaction. The d_rdlockmodes function returns S_ILLMODE if
the application attempts to loosen transaction isolation (for example,
enable dirty reads) while a transaction is active. See Chapter 3 of the
Velocis User’s Guide for more about transaction isolation in
multi-user database environments.
Currency None
Changes
Locking None
Requirements
Example
/* Configure this instance to permit dirty reads */
d_rdlockmodes(1, 0, hSess);
...
/* Now configure for dirty reads and
freeable read locks within transaction */
d_rdlockmodes(1, 1, hSess);
...
/* Now go back to highest (default) level of isolation */
d_rdlockmodes(0, 0, hSess);
Description This function finds the first record occurrence of the specified record
type (rec) in the related data file. The d_recfrst function searches
records in database address order, skipping any deleted records or
records of a different type. Thus, this function retrieves the record
occurrence with the lowest database address. Your application uses
this function with the d_recnext and d_recprev functions to provide
sequential record access capability.
Note: If the data file contains multiple record types, or large blocks
of deleted records, the d_recfrst function might require substantial
amounts of time to scan the file until it finds a record of type rec.
Locking None. However, if the record is not locked, your application might
Requirements receive an S_DELETED error code when it attempts a subsequent
read operation. This code indicates another application deleted the
record.
Example
int info_total;
Description This function finds the last record occurrence of the specified record
type (rec) in the related data file. The d_reclast function searches
records in database address order, skipping any deleted records or
records of a different type. Thus, this function retrieves the record
occurrence with the highest database address. Your application
uses this function with the d_recprev and d_recnext functions to
provide sequential record access capability.
Note: If the data file contains multiple record types, or large blocks
of deleted records, the d_reclast function might require substantial
amounts of time to scan the file until it finds a record of type rec.
Locking None. However, if the record is not locked, your application might
Requirements receive an S_DELETED error code when it attempts a subsequent
read operation. This code indicates another application deleted the
record.
Example
int info_total;
d_recnext Find the next record occurrence of the current record type
Description This function finds the next occurrence of the record with the same
type (rec) that was found with a previous call to d_recfrst, d_reclast,
d_recprev, or d_recset. The d_reclast function searches records in
database address order, skipping any deleted records or records of a
different type. The function returns S_NOTFOUND when it finds
no more records. It provides sequential record access capability.
Note: If the data file contains multiple record types, or large blocks
of deleted records, the d_recnext function might require substantial
amounts of time to scan the file until it finds a record of type rec.
Locking None. However, if the record is not locked, your application might
Requirements receive an S_DELETED error code when it attempts a subsequent
read operation. This code indicates another application deleted the
record.
Example
int info_total;
d_recprev Find the previous record occurrence of the current record type
Description This function finds the previous occurrence of the record with the
same type record (rec) found with a previous call to d_recnext,
d_reclast, d_recfrst, or d_recset. The d_recprev function retrieves
records in descending database address order, skipping any deleted
records or records of a different type. The function returns
S_NOTFOUND when it finds no more records. It provides
sequential record access capability.
Note: If the data file contains multiple record types, or large blocks
of deleted records, the d_recprev function might require substantial
amounts of time to scan the file until it finds a record of type rec.
Locking None. However, if the record is not locked, your application might
Requirements receive an S_DELETED error code when it attempts a subsequent
read operation. This code indicates another application deleted the
record.
Example
int info_total;
/* Compute total number of info records in database */
for (info_total = 0, stat = d_reclast(INFO, hDb);
stat == S_OKAY; stat = d_recprev(hDb))
++info_total;
printf("Total of %d info records in database\n", info_total);
Description This function verifies that the current record is of type rec. It then
copies the contents of the current record into the data area pointed
to by data. The rec parameter is used for validation of the type of the
current record, and it does not imply that Velocis supports a current
of record type. There is only one current record.
Note: You must be sure that the data area is at least as long as the
record. A good practice is to use the structure definitions from the
header generated by ddlproc (for example, "struct info infoData;").
Currency None
Changes
Locking If dirty reads are not enabled, a lock is required for the current
Requirements record.
Example
struct info irec;
...
/* Display all info records in id_code order */
for ( stat = d_keyfrst(ID_CODE, hDb); stat == S_OKAY;
stat = d_keynext(ID_CODE, hDb) ) {
d_recread(INFO, &irec, hDb);
... /* Print info record contents */
}
Description This function verifies that the current record is of type rec and sets
the current scan position to the position of the current record. Your
application uses d_recset to establish the current position for
sequential record access scans from the current record, via
d_recnext or d_recprev. The function enables sequential scans
regardless of how the current record was established.
Currency None
Changes
Locking None
Requirements
Example
/* Scan sequentially from key, starting with key */
d_keyfind(INFO_TYPE,&info_key, hDb);
for (stat = d_recset(INFO, hDb); stat == S_OKAY;stat = d_recnext(hDb))
{
d_recread(INFO, &info, hDb);
print_record(&info);
}
d_recsetat Set the record type and database address to reflect the current
record
Description This function is the same as d_recset except that dba is used instead
of the current record.
Currency None
Changes
Locking None
Requirements
d_recseqno Get the next file sequence number for the specified record type
Syntax short d_recseqno (short rec, unsigned long *pSeqno, RDM_DB hDb)
Syntax short d_rectot (short rec, unsigned long *pTot, RDM_DB hDb)
Currency None
Changes
Example
unsigned long total;
...
d_rectot(CUSTOMER, &total, hDb);
printf("there are %lu customers in the database\n", total);
Description This function copies the data from the location pointed to by data
into the current record. The write operation automatically updates
key fields and sorted sets with sort fields contained in the current
record. However, when multiple fields in the record are used as
sort fields in the same set, your application obtains better results if it
calls d_discon to disconnect the current record from all sorted sets
before calling d_recwrite. After the call to d_recwrite, the
application should reconnect the record with the sets by calling
d_connect.
The application cannot use the d_recwrite function to modify a
BLOB field. If the function is called for this type of data, it returns
S_BLOBUPD.
Note: You must be sure that the data area is at least as long as the
record. A good practice is to use the structure definitions from the
header generated by ddlproc (for example, "struct info infoData;").
Currency None
Changes
Locking Write lock on the current record. If the function modifies a field
Requirements used in a sort by clause for a sorted set, the set must also be write-
locked.
Example
/* Modify info record */
mod_info(id)
char *id; /* id code of info rec to modify */
{
if ( stat = d_keyfind(ID_CODE, id, hDb) == S_OKAY ) {
d_recread(REC1, &irec, hDb);
if ( edit_info(&irec) ) { /* User edits info data */
d_recwrite(REC1, &irec, hDb); /* Okay to update */
}
else
... /* Edit canceled */
}
else if ( stat == S_NOTFOUND )
usermsg("id code not found");
}
Description This function frees all instance and table locks for your application.
The function returns S_TRFREE if the application tries to illegally
free locks within a transaction. It is always illegal to free write locks
within a transaction. If the application has not enabled the freeing
of read locks, it is also illegal to free read locks within a transaction.
Currency None
Changes
Locking None
Requirements
Example
/* Freeing locks in no-trans application */
d_open("dbase1", "sn", hSess); /* Open db in shared, no-trans mode */
...
d_crlock("r", hDb);
d_crslock(SET1, "w", hDb);
d_dbalock(savedba, "r", hDb);
d_stlock(SET2, "w", hDb);
...
d_release(RWLOCKS, hSess); /* Free all locks */
Description This function resets the error handler stack to place the error
handling function specified by func at the top of the stack. Before
calling d_reset_dberr, your application must provide the name of its
error handler in a call to d_set_dberr.
In effect, d_reset_dberr pops the error handler stack until the
application error handler is uncovered. If it does not find the error
handler specified by the application on the stack, the function
returns S_NODBERR and leaves the error handler stack unchanged.
Currency None
Changes
Locking None
Requirements
Parameters rec [Input] The record type for which to free locks.
hDb [Input] The database handle.
Description This function frees the record type lock on the specified record type.
The d_rtfree function returns S_TRFREE if the application attempts
to free a write lock within a transaction. The same error code is
returned if the application tries to free a read lock within a
transaction, but has not enabled the freeing of read locks (see
d_rdlockmodes). The d_rtfree function returns an S_NOTLOCKED
error code if the application attempts to free a record that has no
record type locks.
Currency None
Changes
Locking None
Requirements
Example
d_open("dbase2", "sn", hSess);
...
/* Allow app to update any record for REC1 */
d_rtlock(REC1, "w", hDb);
...
d_recwrite(REC1, val1, hDb);
d_recwrite(REC1, val2, hDb);
...
d_delete(hDb);
d_rtfree(REC1, hDb);
Description This function requests a record type lock of the type specified by rec.
If the d_rtlock function finds the requested lock identical to the
existing lock for the record, it ignores the application request and
returns S_OKAY.
Once the application locks a record type, all instances of the record
are implicitly given the same kind of lock. Thus the application can
freely access the record instances without setting up record instance
locks. Note that locking the record type does not provide any access
to set connections. The application must separately lock the set
(instance or type).
Currency None
Changes
Locking None
Requirements
Example
d_open("dbase2", "sn", hSess);
...
/* Allow app to update any record for REC1 */
d_rtlock(REC1, "w", hDb);
...
d_recwrite(REC1, val1, ...);
d_recwrite(REC1, val2, ...);
...
d_delete(hDb);
d_rtfree(REC1, hDb);
Description This function sets the default application error handler function
(func parameter) that Velocis can call when it detects an error while
processing a Core API (d_) function. The specified error handler
supersedes the current error handler or the default error handler
dberr. In effect, the previous error handler is "pushed" into the
stack by the new error handler. See Chapter 7 of the Velocis User’s
Guide for help in writing an error handler for your application.
Currency None
Changes
Locking None
Requirements
FARPROC fp;
fp = MakeProcInstance((FARPROC)MyDberr, hInstance);
d_set_dberr((ERRORPROC)fp, NULL, hSess);
Non-Windows
#include "rds.h"
Description This function sets the specified key field to the value specified by
fldvalue. Your application must call this function for each key field
in a record that will subsequently be created by a call to
d_makenew. Velocis can then create the keys during preparation of
the record by d_makenew.
Currency None
Changes
Locking None
Requirements
Example
/* Create a new info record */
d_setkey(ID_CODE, "db022", hDb);
d_makenew(INFO);
d_setmm Set the current member from the current member of another set
Parameters sett [Input] The set type to which the function assigns
the current member from sets.
sets [Input] The set type containing the current member
to assign.
hDb [Input] The database handle.
Description This function assigns the current member of sets as the current
member of sett. The current member of sets must be a legal member
of sett and must be connected to a sett occurrence. The new current
owner of sett is obtained from the new current member of sett.
Locking If dirty reads are not enabled, sett must be locked. Your application
Requirements can use the d_crslock function to lock the set.
Example
/* Print key words associated with tech. info */
while ( d_findnm(INFO_TO_KEY, hDb) == S_OKAY ) {
d_setmm(KEY_TO_INFO, INFO_TO_KEY, hDb);
d_csoread(INFO_TO_KEY, WORD, key, hDb);
printf("%s\n", key);
}
Parameters setm [Input] The set type to which this function assigns a
new current member.
seto [Input] The set type containing the current owner to
assign as current member of setm.
hDb [Input] The database handle.
Description This function assigns the current owner of seto as the current
member of setm. The current owner of seto must be a legal member
of setm and must be connected to a setm occurrence. The new
current owner of setm is obtained from the new current member of
setm.
Locking If dirty reads are not enabled, setm must be locked. Your application
Requirements can use the d_crslock function to lock the set.
Example
long count;
...
/* Delete author, if he has no pubs. */
d_members(HAS_PUBLISHED, &count, hDb);
if ( count == 0L ) {
d_setmo(AUTHOR_LIST, HAS_PUBLISHED, hDb);
d_discon(AUTHOR_LIST, hDb);
d_delete(hDb);
}
Parameters set [Input] The set type for which this function assigns
the current member from the current record.
hDb [Input] The database handle.
Description This function assigns the current member of set from the current
record. The current record must be a legal member of set and must
be connected to a set occurrence. The new current owner of set is
obtained from the new current member of set.
Locking If dirty reads are not enabled, set must be locked. Your application
Requirements can use the d_crslock function to lock the set.
Example
/* Disconnect and delete intersect and (possibly) key word */
d_setom(INFO_TO_KEY, HAS_PUBLISHED, hDb);
while ( d_findnm(INFO_TO_KEY, hDb) == S_OKAY ) {
d_discon(INFO_TO_KEY, hDb);
d_setmr(KEY_TO_INFO, hDb);
d_discon(KEY_TO_INFO, hDb);
d_delete(hDb);
d_members(KEY_TO_INFO, &count, hDb);
if ( count == 0L ) {
/* Delete key word */
d_setro(KEY_TO_INFO, hDb);
d_delete(hDb);
}
}
Parameters nseto [Input] The set type for which this function assigns
the current owner from the current member of
nsetm.
nsetm [Input] The set type containing the current member
to assign as current owner of nseto.
hDb [Input] The database handle.
Description This function assigns the current member of nsetm as the current
owner of nseto. The current member of nsetm must be a legal owner
of nseto. The d_setom function sets the current member of nseto to
NULL_DBA.
Locking None
Requirements
Example
/* Disconnect and delete intersect and (possibly) key word */
d_setom(INFO_TO_KEY, HAS_PUBLISHED, hDb);
while ( d_findnm(INFO_TO_KEY, hDb) == S_OKAY ) {
d_discon(INFO_TO_KEY, hDb);
d_setmr(KEY_TO_INFO, hDb);
d_discon(KEY_TO_INFO, hDb);
d_delete(hDb);
d_members(KEY_TO_INFO, &count, hDb);
if ( count == 0L ) {
/* Delete key word */
d_setro(KEY_TO_INFO, hDb);
d_delete(hDb);
}
}
d_setoo Set the current owner from the current owner of another set
Parameters nsett [Input] The set type for which this function assigns
the current owner from the current owner of nsets.
nsets [Input] The set type that contains the current owner
to assign as the current owner of nsett.
hDb [Input] The database handle.
Description This function assigns the current owner of nsets as the current owner
of nsett. The current owner of nsets must be a legal owner of nsett.
The d_setoo function sets the current member of nsett to
NULL_DBA.
Locking None
Requirements
Example
/* Make curr_member of AUTHOR_LIST null */
d_setoo(AUTHOR_LIST, AUTHOR_LIST, hDb);
Parameters nset [Input] The set type for which this function assigns
the current record as current owner.
hDb [Input] The database handle.
Description This function assigns the current record as the current owner of nset.
The current record must be a legal owner of nset. The d_setor
function sets the current member of nset to NULL_DBA.
Locking None
Requirements
Example
/* List "database technology" publications */
if (d_keyfind(KEYWORD, "database technology", hDb) == S_OKAY) {
d_setor(KEY_TO_INFO, hDb);
while ( d_findnm(KEY_TO_INFO, hDb) == S_OKAY ) {
d_findco(INFO_TO_KEY, hDb);
d_recread(REC1, &irec, hDb);
pr_info();
}
Parameters set [Input] The set type for which this function assigns
the current member as the current record.
hDb Input] The database handle.
Description This function assigns the current member of set as the current
record.
Locking None
Requirements
Example
d_setrm(HAS PUBLISHED, hDb);
pr_info(); /* Print info record */
Parameters set [Input] The set type whose current owner will be
assigned as current record.
hDb [Input] The database handle.
Description This function assigns the current record from the current owner of
set.
Locking None
Requirements
Example
/* Disconnect and delete intersect and (possibly) key word */
d_setom(INFO_TO_KEY, HAS_PUBLISHED, hDb);
while ( d_findnm(INFO_TO_KEY, hDb) == S_OKAY ) {
d_discon(INFO_TO_KEY, hDb);
d_setmr(KEY_TO_INFO, hDb);
d_discon(KEY_TO_INFO, hDb);
d_delete(hDb);
d_members(KEY_TO_INFO, &count, hDb);
if ( count == 0L ) {
/* Delete key word */
d_setro(KEY_TO_INFO, hDb);
d_delete(hDb);
}
}
Description This function returns a list of locks (of locktype) within a database. If
more than one owner for a lock (actualelem > 1) exists, you can call
d_showOwners to retrieve the list of all users with this lock.
Description This function returns a list of all owners of a particular lock type
(locktype) within a database. It is useful if there are locks with more
than one owner, since d_showLocks can only retrieve one owner
per lock.
Description This function frees the set type lock on the specified set. The
d_stfree function returns S_TRFREE if the application attempts to
free a write lock within a transaction. The same error code returns if
the application tries to free a read lock within a transaction, but has
not enabled the freeing of read locks (see d_rdlockmodes). The
d_stfree function returns an S_NOTLOCKED error code if the
application attempts to free a set for which it has no set type locks.
Currency None
Changes
Locking None
Requirements
Example
d_open("dbase4", "sn", hSess);
...
/* Allow app to freely modify any set connect in SET1 */
d_stlock(SET1, "w", hDb);
...
d_discon(SET1, hDb);
...
d_connect(SET1, hDb);
...
d_stfree(SET1, hDb);
Description This function requests a set type lock for the specified set. If the
d_stlock function finds that the requested lock is identical to the
existing lock for the set type, it ignores the application request and
returns S_OKAY.
Once the application locks a set type, all instances of the set are
implicitly given the same kind of lock. Thus the application can
freely access the set instances without setting up set instance locks.
Note that locking the set type does not provide any access to the
contents of records that are owners or members of the set. The
application must separately lock the records (instance or type).
Currency None
Changes
Locking None
Requirements
Example
d_open("dbase4", "sn", hSess);
...
/* Allow app to freely modify any set connect in SET1 */
d_stlock(SET1, "w", hDb);
...
d_discon(SET1, hDb);
...
d_connect(SET1, hDb);
...
d_stfree(SET1, hDb);
Description The d_taskinfo function returns information about each session that
is currently logged into the Velocis server. The session handle for
the task is returned in sessHandle. The task information is returned
in the TASK_INFO structure pointed to by taskinfo. Of the
information in this structure, only the name of the logged-in user is
useful to an application program. This user name is stored in the
TASK_INFO structure’s usname field (a character array with a length
of USERNAMELEN bytes).
Description This function sets the timeout period for pending lock requests for
your application. The lock request functions return S_UNAVAIL
when a timeout occurs.
Your application must call d_timeout after calling d_open. Since
timeouts are the only means of detecting potential deadlock
situations, the application should take care in turning off a timeout.
Currency None
Changes
Locking None
Requirements
Example
d_open("tims", "s");
d_timeout(30, hSess); /* Set a 30 second timeout value */
Locking None
Requirements
Example
d_trbegin("orderentry", hSess);
... /* Enter customer info */
... /* Enter order info */
... /* Check inventory */
if ( items_requested > items_available ) {
d_trabort(hSess);
... /* Inform user */
}
else {
... /* Complete update */
d_trend(hSess);
}
Currency None
Changes
Locking None
Requirements
Example
/* If a transaction has not been started, begin one now.
Otherwise, "nest" within the caller’s transaction. */
short inTrans;
d_tractive(&inTrans, hSess);
if (!inTrans)
d_trbegin("orderentry");
Note: If you want to modify both SQL and Core databases in the
same transaction, we recommend that you use the SQLTransact
function instead and make the changes to the SQL database before
changing the Core database. The transaction will be committed
upon the next call to SQLTransact.
Currency None
Changes
Locking None
Requirements
Example
char tr_id[25]; /* Transaction id string */
int tr_tot = 0; /* Total number of transactions */
...
sprintf(tr_id, "tr# %4d", ++tr_tot);
d_trbegin(tr_id, hSess);
... /* 1.Enter cust info, 2.Enter order info, 3.Check inventory */
if ( items_requested > items_available ) {
d_trabort(hSess);
... /* inform user */
}
else {
... /* Complete update */
d_trend(hSess);
}
Currency None
Changes
Locking None
Requirements
Example
d_trbegin("orderentry");
... /* Enter order info */
d_trend(hSess);
Description This function marks the specified position within the current
transaction. Later, your application can roll back (via d_trrollback)
to this point in the transaction. The application uses d_trmark and
d_trrollback to discard portions of a transaction without
terminating the transaction or discarding locks.
Currency None
Changes
Locking None
Requirements
Example
d_trbegin("rollback", hSess);
...
d_trmark("mark1", hSess); /* 1st mark */
...
d_trmark("mark2", hSess); /* 2nd mark */
...
d_trrollback("mark2", hSess); /* Rollback to mark2 */
...
d_trmark("mark3", hSess); /* 3rd mark */
...
d_trrollback("mark1", hSess); /* Rollback to mark1
(mark3 wiped out as well) */
...
d_trrollback("missing", hSess); /* Undo all work */
Locking None
Requirements
Example
d_trbegin("rollback", hSess);
...
d_trmark("mark1", hSess); /* 1st mark */
...
d_trmark("mark2", hSess); /* 2nd mark */
...
d_trrollback("mark2", hSess); /* Rollback to mark2 */
...
d_trmark("mark3", hSess); /* 3rd mark */
...
d_trrollback("mark1", hSess); /* Rollback to mark1
(mark3 wiped out as well) */
...
d_trrollback("missing", hSess); /* Undo all work */
Description This function removes the specified error handler function (func)
from the top of the error handler stack. If d_unset_dberr does not
find the function on the stack, it returns S_NODBERR and leaves the
error handler stack unchanged.
Currency None
Changes
Locking None
Requirements
Description This function restores the currency tables from currbuff. The length
of the buffer, indicated by buflen, must be large enough to store the
entire currency. If the buffer length is too small, d_wrcurr returns
S_BUFLEN and makes no change to the currency.
Note: Your application can use the d_wrcurr function with d_rdcurr
to save and restore the state of a database currency.
Locking None
Requirements
Example
DB_ADDR ctab[128]; /* Save currency table */
short csize; /* Size of saved currency table */
...
d_rdcurr(&ctab, sizeof(ctab), &csize, hDb); /* Save currency tables */
... /* Do some other processing */
d_wrcurr(ctab, sizeof(ctab), hDb); /* Restore currency tables */
The fcn member of the structure is a pointer to one of your extension module functions.
Each extension module function declaration must conform to the ModFunction function
prototype. The id member is the function identifier number, which must be a unique
positive integer; typically, it starts at 0 and increases incrementally in the load table.
No additional header files (other than velocis.h) need to be included to use these
functions. When declaring and defining the Mod functions, however, you have to
include the REXTERNAL macro between the function type and the function name.
For more information about the em_ and Mod functions, see Chapter 11 of the Velocis
User's Guide.
Example
#include "velocis.h"
...
short emh;
short stat;
Example
From the application header file included in both the client program and the
extension module:
...
#define TXCLIENTINIT 0
#define TXRESET 1
#define TXTRANSACTION 2
#define TXREPORT 3
#define TXCLIENTCLOSE 4
...
stop = clock();
return( tracking ? stop-start : 0 );
}
Example
From the client application program:
/* =====================================================================
Closes & logs out, frees RPC stuff, and all that clean up work.
*/
void tx_close( void )
{
PL_DATADESC *sessParm;
short stat, rc;
if ( stat == S_OKAY ) {
em_detach( hEM, hSess );
em_unload( hEM, hSess );
s_logout( hSess );
}
}
d_unset_dberr(ReportError, hSess);
rm_freeMemory(*context, 0);
*context = NULL;
return S_OKAY;
}
Description This function returns the location of a pointer to the session's task
context maintained by the Velocis server. It is called from an
extension module function and/or the ModInit and ModCleanup
functions.
Each extension module has a separate entry in a session's task
context that can be used to store a pointer to any user-allocated
context buffer. The extension module can use the context buffer to
store data that must persist between multiple calls to the extension
module. Using the buffer also allows you to write an extension
module that is re-entrant.
After initial allocation of the user context buffer, store the pointer to
the allocated buffer in the location pointed to by the return value of
em_getContext. To retrieve the buffer, use em_getContext in
subsequent calls to the extension module.
Note: The initial allocation of a user context buffer is normally
performed in the extension module by the ModInit function. The
buffer is normally freed by the ModCleanup function.
Return Values A pointer to the session's context pointer for this extension module
Example
/* Data specific to each client caller */
typedef struct {
... /* contains "global" data used by EM for a particular session */
RDM_DB hDb;
} GLOBALS;
...
/* =====================================================================
Initialization for EM. Called by Velocis for each client on em_attach
*/
short REXTERNAL ModInit( RDM_SESS hSess )
{
short stat;
void **context;
GLOBALS *ctx;
/* =====================================================================
When a client logs out, free this client's context data.
*/
short REXTERNAL ModCleanup( RDM_SESS hSess )
{
void **context;
GLOBALS *ctx;
d_iclose(ctx->hDb);
rm_freeMemory(ctx, 0);
*context = NULL;
return S_OKAY;
}
Description This function can be called from an extension module to obtain its
own handle.
Example
#include "velocis.h"
...
short emh;
short stat;
Example
RDM_SESS hSess;
short emHandle;
Return Values This function may return any of the Velocis error codes, which
becomes the return value of em_detach.
Example
short REXTERNAL ModCleanup (
RDM_SESS hSess)
{
void **context;
GLOBALS *ctx;
d_iclose(ctx->hDb);
rm_freeMemory(ctx, 0);
*context = NULL;
return S_OKAY;
}
Example
short hMyApp = 0;
static char modDescr[] = "MyApp extensions V3.0";
static EMLOADTABLE emTable[] = {
{ MA_Add, 0 }
{ MA_Delete, 1 }
{ MA_Update, 2 }
{ MA_Read, 3 }
};
if (fcn_descr)
*fcn_descr = modDescr;
return;
}
Example
/* ===================================================================
Envelope function for fetchBlock function
*/
short REXTERNAL EfetchBlock(
PL_DATADESC *pInParms,
PL_DATADESC *pOutParms )
{
short rv;
/* input arguments */
short bufsize;
RDM_SESS hSess;
/* output argument */
short nbytes;
void *buf;
Return Values This function returns any of the Velocis error codes, which becomes
the return value of em_attach.
Example
typedef struct {
short rec_type;
short rec_size;
short last_stat;
RDM_DB hDb;
} CTX;
...
/* =================================================================
Module initialization (per em_attach)
*/
short REXTERNAL ModInit(
RDM_SESS hSess )
{
void **ctxPtrPtr = em_getContext(hSess, ModHandle);
return S_OKAY;
}
When declaring and defining these functions, you must add the REXTERNAL macro
between the function return type and the function name.
Parameters hSys [Input] The SQL system handle associated with the
statement invoking the filter.
numArgs [Input] The number of arguments or elements in the
args array.
args [Input] A pointer to an array of VALUE entries, one
for each specified filter argument.
error [Output] A pointer to a VALUE variable to contain
error information when an error is detected.
Example
/* =====================================================================
Type-checking for (up to) one date argument
*/
short REXTERNAL bbCheck (
HSYS hSys, /* in: system handle */
short noargs, /* in: number of arguments to function */
VALUE *args, /* in: array of arguments */
VALUE *error) /* out: container for error value */
{
short status = SQL_SUCCESS;
Parameters hSys [Input] The SQL system handle associated with the
statement that is invoking the filter.
ctxp [Input] A pointer to the IEF statement context
pointer.
Example
/* =====================================================================
Filter cleanup
*/
void REXTERNAL bbCleanup (
HSYS hSys, /* in: system handle */
void **cxtp) /* in: statement context pointer */
{
BB_CTX *ctx = *cxtp;
RM_MEMTAG mTag;
SYSMemoryTag(hSys, &mTag);
rm_freeMemory(ctx->webpg, mTag);
rm_freeMemory(ctx, mTag);
*cxtp = NULL;
}
iefDescribeFcns Describe the import or export filters defined in this IEF module
Example
#include "sqlrds.h"
#include "sqlsys.h"
IEFCHECK uniCheck;
IEFFETCH uniFetch;
IEFSTORE uniStore;
IEFINIT uniInit;
IEFCLEANUP uniCleanup;
/* =====================================================================
Ascii/Unicode file import/export filters
*/
void REXTERNAL iefDescribeFcns (
unsigned short *NumFltrs, /* out: number of filters in module */
IEFLOADTABLE **pIEFLoadTable, /* out: points to IefTable above */
char **modDesc) /* out: optional description string */
{
*NumFltrs = sizeof(IefTable)/sizeof(IEFLOADTABLE);
*pIEFLoadTable = IefTable;
*modDescr = "built-in ascii/unicode file filters";
}
Syntax short REXTERNAL iefFetch (HSYS hSys, void **cxtp, short numVals,
VALUE *vals, VALUE *error)
Parameters hSys [Input] The SQL system handle associated with the
statement that is invoking the filter.
ctxp [Input] A pointer to IEF statement context pointer.
numVals [Input] The number of column values or elements
in the vals array.
vals [Input/Output] A pointer to an array of VALUE
entries, one for each column value to be returned.
error [Output] A pointer to a variable containing
iefFetch, error information when an error is
detected.
Example
/* =====================================================================
Import filter
*/
short REXTERNAL bbFetch (
HSYS hSys, /* in: system handle */
void **cxtp, /* in: statement context pointer */
short novals, /* in: number of values to fetch */
VALUE *vals, /* in: array of value containers */
VALUE *error) /* out: container for error value */
{
BB_CTX *ctx = *cxtp;
short status = SQL_SUCCESS;
vals[0].vt.tsv.date = ctx->game_date;
status = FetchNextGame(ctx);
if ( status == SQL_SUCCESS ) {
vals[1].vt.cv = ctx->visitor;
vals[2].vt.cv = ctx->home;
vals[3].vt.sv = ctx->v_runs;
vals[4].vt.sv = ctx->h_runs;
}
return status;
}
Syntax short REXTERNAL iefInit (HSYS hSys, void **cxtp, short type,
short numArgs, VALUE *args, short numVals,
VALUE_DESCR *vdescr, VALUE *error)
Parameters hSys [Input] The SQL system handle associated with the
statement invoking the filter.
ctxp [Input] A pointer to the IEF statement context
pointer.
type [Input] Identifies the filter type (SQL_IMPORT or
SQL_EXPORT).
numArgs [Input] The number of arguments or elements in
args array.
args [Input] A pointer to an array of VALUE entries, one
for each specified filter argument.
numVals [Input] The number of column description entries in
the vdescr array.
vdescr [Input] A pointer to an array of column description
entries.
error [Output] A pointer to a VALUE variable containing
error information when an error is detected.
Example
/* =====================================================================
Filter initialization
*/
short REXTERNAL bbInit (
HSYS hSys, /* in: system handle */
void **cxtp, /* in: statement context pointer */
short type, /* in: SQL_IMPORT / SQL_EXPORT */
short noargs, /* in: number of arguments to function */
VALUE *args, /* in: array of arguments */
short *novals, /* in/out: number of value */
VALUE_DESCR **vdescr, /* in/out: value description array */
VALUE *error) /* out: container for error value */
{
RDM_DB hDb;
RM_MEMTAG mTag;
BB_CTX *ctx;
char uri[30];
DATE_STRUCT dsv;
short status = SQL_SUCCESS;
SYSMemoryTag(hSys, &mTag);
Syntax short REXTERNAL iefStore (HSYS hSys, void **cxtp, short numVals,
VALUE *vals, VALUE *error)
Parameters hSys [Input] The SQL system handle associated with the
statement invoking the filter.
ctxp [Input] A pointer to IEF statement context pointer.
numVals [Input] The number of column values to store.
vals [Input/Output] A pointer to an array of VALUE
entries, one for each column value to be stored.
error [Output] A pointer to a VALUE variable containing
error information when an error is detected.
Example
/* =====================================================================
ASCII Export filter
*/
short REXTERNAL ascStore (
HSYS hSys, /* in: system handle */
void **cxtp, /* in: statement context pointer */
short novals, /* in: number of values to store */
VALUE *vals, /* in: array of value containers */
VALUE *error) /* out: container for error value */
{
while (*cp) {
if ( *cp == '"' || *cp == '\\' )
PutChar('\\', ctx);
PutChar(*cp++, ctx);
}
if (quote)
PutChar('"', ctx);
if (i < novals - 1)
PutChar(ctx->delim, ctx);
}
PutChar('\n', ctx);
return SQL_SUCCESS;
}
Parameters None
Return Values A pointer to the structure containing the allocated parameter list
(NULL if not enough memory to allocate)
Example
#include "velocis.h"
#include "tims.h"
...
/* Now place the AUTHOR record into the input parameter list */
pl_put(inParm, PL_ASCIZ, 0, (void *)author.name, 0);
Description This function returns the total number of parameters in the specified
parameter list.
Description This function deletes the current data item in a parameter list. The
current data item is normally the most recently added parameter,
but you can use pl_seek to make another item the current one.
Example
#include "velocis.h"
#include "tims.h"
short con_author (
author Author, /* Author to create and connect */
char *prev_author, /* Will hold previous author name */
short hSvc, /* Extension module handle */
RDM_DB hDb, /* Database handle of tims */
RDM_SESS hSess) /* Our session with the server */
{
/* Example assumes extension module has been loaded and attached */
PL_DATADESC *inParm; /* I/P Parm list */
PL_DATADESC *outParm; /* O/P Parm List */
char *pPrev; /* ptr to prev author in PL packet */
short retcode; /* Return status from extension module */
short stat; /* Return code from rpc calls */
inParm = pl_alloc();
pl_put(inParm, PL_ULONG, 0, &hDb, 0);
pl_put(inParm, PL_ASCIZ, 0, Author.name, 0);
stat = em_call(hSvc, CON_AUTH, inParm, &outParm, &retcode, hSess);
pl_free(outParm);
return 0;
}
Example
#include "velocis.h"
#include "tims.h"
Description This function extracts information about the next parameter in the
specified parameter list without actually retrieving the parameter
itself.
The function retrieves three things associated with the parameter
item: an indicator of the data type, the values of the data modifier
flags, and a size value, in bytes. If the parameter is opaque, the size
returned is the amount of bytes in the data. If the parameter is an
Example
/* ====================================================================
Envelope function for d_crwrite
*/
short REXTERNAL Ed_crwrite(
PL_DATADESC *inParms,
PL_DATADESC *outParms)
{
short rc;
long *data;
unsigned short flags;
long field;
RDM_DB hDb;
PL_DATATYPE type;
char *funcName = "d_crwrite";
UNREF_PARM(outParms)
Example
DB_ADDR dba;
short set;
char flags[2], msg[20];
RDM_SESS hSess;
strcpy(msg, "Update");
...
Example
#include "velocis.h"
#include "tims.h"
short con_author (
author Author, /* Author to create and connect */
char *prev_author, /* Will hold previous author name */
short hSvc, /* Extension module handle */
RDM_DB hDb, /* Database handle of tims */
RDM_SESS hSess) /* Our session with the server */
{
/* Example assumes extension module has been loaded and attached */
PL_DATADESC *inParm; /* I/P Parm list */
PL_DATADESC *outParm; /* O/P Parm List */
short retcode; /* Return status from extension module */
short stat; /* Return code from rpc calls */
inParm = pl_alloc();
pl_put(inParm, PL_ULONG, 0, &hDb, 0);
pl_put(inParm, PL_ASCIZ, 0, Author.name, 0);
stat = em_call(hSvc, CON_AUTH, inParm, &outParm, &retcode, hSess);
pl_get(outParm, prev_author);
pl_free(outParm);
return 0;
}
typedef struct {
unsigned long size;
PL_DATATYPE type;
unsigned short flags;
} PL_ITEM;
Note: The flags and elems parameters in this function apply to the
entire structure being placed in the parameter list. As to their
counterparts in the PL_ITEM structure, the flags and size fields, each
field applies only to its specific item in the PL_ITEM structure
element.
The array of PL_ITEM structures must contain entries for each field
of the structure that is being placed in the parameter list, in the
order in which the fields are declared. Items that are themselves
structures are indicated by the PL_STRUCT data type indicator.
(Structures can be nested within other structures in the parameter
item.) The first and last entries in the array of data items must have
the type field equal to PL_STRUCT. The first entry must have a flags
field in which PL_FLAG_OPEN is set, and the last entry must have a
flags field in which PL_FLAG_CLOSE is set. The items that
constitute the structure are specified between these two entries.
Note: The data type indicator PL_STRUCT and the data modifier
flags PL_FLAG_OPEN and PL_FLAG_CLOSE can only be specified
within a PL_ITEM structure. They cannot be specified directly as
arguments in pl_putStruct or any other parameter list function.
Example
struct userinf {
char username[SIZEOF_USERNAME];
char userpass[SIZEOF_USERPASS];
char userpriv;
};
typedef struct {
struct userinf us;
char usdevice[SIZEOF_DEVNAME];
} USERINF_CHG;
PL_ITEM userinf_chg_items[8] = {
{0, PL_STRUCT, PL_FLAG_OPEN}, /*start USERINF_CHG */
{0, PL_STRUCT, PL_FLAG_OPEN}, /*start struct userinf*/
{SIZEOF_USERNAME, PL_CHAR, PL_FLAG_ARRAY},
{SIZEOF_USERPASS, PL_CHAR, PL_FLAG_ARRAY},
{0, PL_CHAR, 0},
{0, PL_STRUCT, PL_FLAG_CLOSE},/*end struct userinf*/
{SIZEOF_DEVNAME, PL_CHAR, PL_FLAG_ARRAY},
{0, PL_STRUCT, PL_FLAG_CLOSE} /*end USERINF_CHG*/
};
Example
typedef struct {
PL_DATAVAL type;
void *data;
} PARM_INFO;
inParm = pl_alloc();
while (parmInfo[i].data) {
pl_put(inParm, parmInfo[i].type, 0, parmInfo[i].data, 0);
i++;
}
pl_seek(inParm, 0, SEEK_SET);
pl_put(inParm, PL_SHORT, 0, &i, 0);
return retcode;
}
Table 10-1. Locations Where Certain Resource Manager Functions Can Be Called
Callable Functions From the Server Only Callable Functions From both Client and Server
rm_allocPool rm_resetTag rm_cExtendMemory rm_fileStreamPuts
rm_allocTag rm_sleep rm_cGetMemory rm_fileStreamRewind
rm_cleanup rm_startup rm_extendMemory rm_fileSync
rm_createTag rm_syncCreate rm_fileClose rm_fileValidate
rm_filePrintf rm_syncDelete rm_fileCopy rm_fileWrite
rm_fileSeekRead rm_syncDisableQ rm_fileLength rm_freeMemory
rm_fileSeekWrite rm_syncEnableQ rm_fileMove rm_getenv
rm_freeTagMemory rm_syncEnterExcl rm_fileOpen rm_getLocalEnv
rm_getFromPool rm_syncExitExcl rm_filePosition rm_getMemory
rm_log rm_syncReceiveQ rm_fileRead rm_iniGet
rm_memoryAllocated rm_syncResume rm_fileRemove rm_iniGetPrivate
rm_memoryAvail rm_syncSendQ rm_fileRename rm_iniSet
rm_putInPool rm_syncStart rm_fileSeek rm_iniSetPrivate
rm_queueCreate rm_syncWait rm_fileStreamClose rm_putLocalEnv
rm_queueDelete rm_syncWaitQ rm_fileStreamGetLine rm_Strdup
rm_queuePurge rm_threadBegin rm_fileStreamGets rm_zFreeMemory
rm_queueRead rm_threadEnd rm_fileStreamOpen
rm_queueWrite rm_zFreePool
For more information about these functions, see Chapter 4 of the Velocis User’s Guide.
Example
#include "velocis.h"
RM_POOL *qPool;
...
Example
short REXTERNAL ModInit (
RDM_SESS hSess) /* in: RDM session id */
{
void **context;
EM_CONTEXT *ctx;
rm_cExtendMemory Extend or reallocate a memory block, and clear the new portion
Example
/* add new column reference entry */
if ( sdp->nocolrefs == sdp->maxcolrefs ) {
sdp->maxcolrefs += cr_chunk;
newsize = sdp->maxcolrefs*sizeof(CRL_ENTRY);
sdp->crbuf = rm_cExtendMemory(sdp->crbuf, newsize, psp->compiletag);
}
Example
sqlCtx = rm_cGetMemory(sizeof(SQLCTXT), userTag);
Parameters None
Description This function is used to clean up all operational data and shut down
the resource manager. Call the function only if rm_startup has been
called to initiate the resource manager interface. You should instead
use the administration API functions s_startup and s_terminate to
start and shut down the Velocis database engine (which includes
that interface). Use of rm_startup and rm_cleanup are confined to
applications that only use the resource manager functions.
Example
#include "velocis.h"
...
main()
{
...
/* startup Velocis resource manager */
stat = rm_startup(NULL, MessageConsole, LOG_ERROR|LOG_WARN|LOG_INFO);
rm_cleanup();
}
Parameters name [Input] The name of the tag. This name is used to
report any errors for the tag. If you do not need a
name for the tag, specify NULL.
limit [Input] The maximum amount of memory that can
be allocated. For no limit (other than the system
physical limit), specify 0.
errloc [Input] The jump buffer of an out-of-memory
handler. To have the memory allocation functions
simply return NULL for out-of-memory situations,
specify NULL.
fcnAddr [Input] The address of the memory-finding function,
which tries to make extra memory available if the
first allocation attempt fails. To bypass this feature,
specify NULL; otherwise, the function must have
the following prototype:
void REXTERNAL MemoryFindingFunctionName
(RM_MEMTAG MemoryTag,
size_t AmountOfMemoryRequested);
segsize [Input] The size, in bytes, of the memory allocation
segment. To use the default value (8,192), specify 0.
flags [Input] The serialized (one at a time) allocation flag.
If threads are allowed to allocate and to free
memory at the same time, you must specify
RM_USESEM to provide mutual exclusion;
otherwise, you may specify RM_NOSEM.
Example
/* Free up memory by swapping statement code to disk */
void REXTERNAL SwapStmt(
RM_MEMTAG tag,
size_t size)
{
while ( size > 0 ) {
/* find least recently used statement */
...
/* save to swap file */
...
/* free statement buffer */
...
size -= /* buffer length */
}
}
...
jmp_buf memjmp;
RM_MEMTAG compileTag;
if ( setjmp(memjmp) ) {
/* free any previously allocated memory and return error */
rm_freeTagMemory(compileTag, 1);
return errSRVMEMORY;
}
...
compileTag = rm_createTag("compile", 0, memjmp, SwapStmt, 0, RM_NOSEM);
Example
/* add new column reference entry */
if ( sdp->nocolrefs == sdp->maxcolrefs ) {
sdp->maxcolrefs += cr_chunk;
newsize = sdp->maxcolrefs*sizeof(CRL_ENTRY);
sdp->crbuf = rm_extendMemory(sdp->crbuf, newsize, psp->compiletag);
}
Description This function closes the resource manager file associated with the
specified file handle.
Example
RM_PFILE dbdFile;
...
rm_fileClose(dbdFile);
Description This function will create a new file in the path identified by destName
and copy the contents of the file at srcName into it.
The file paths must be in the local operating system’s format. They
may be absolute or relative paths.
Example
unsigned long filelen;
...
/* get length of file */
filelen = rm_fileLength(hInFile);
Description This function will attempt to rename a file from srcName to destName.
If that fails, srcFile will be copied to destFile and srcFile will be
removed.
Parameters name [Input] The file name, including the directory path.
oflags [Input] A bit map of file open characteristics.
Specify a combination of either O_BINARY or
O_TEXT, one of O_RDONLY, O_RDWR, or
O_WRONLY (O_RDONLY is the default), and any
combination of O_APPEND, O_CREATE, and
O_TRUNC. These flags are described below.
O_BINARY
Binary file. No interpretation is performed.
O_TEXT
Text file. The end-of-file marker is <Ctrl+D> (UNIX)
or <Ctrl+Z>+<Enter> (Windows).
O_RDONLY
Read-only mode. Write requests result in errors.
O_RDWR
Read/write mode.
O_WRONLY
Write-only mode.
O_APPEND
Append mode. New writes are added to the end of
the file.
O_CREAT
Create mode. A new file is created. If the file already
exists and O_TRUNC and O_APPEND are not
specified, an error is returned.
O_TRUNC
Truncate mode. Implies O_CREAT.
xflags [Input] A bit map of extended characteristics of
resource manager file operation. Specify any
combination of these flags:
RM_DIRECTIO
Causes file writes to be immediately written to disk.
RM_EXIT_ON_FAIL
Ends the program in the event of a file error.
RM_FPRINTF
Uses rm_filePrintf to write to the file.
RM_NOGROW
Ignores the creation and extension lengths (crelen and
extlen), increases the file size only when data is
appended to it, and increases it only by the length of
the data added. This flag is generally used with
RM_FPRINTF.
RM_NOSYNC
Allows the file to be available to multiple threads, but
does no synchronization itself. This flag assumes that
the user is doing whatever synchronization is
necessary.
RM_SHARE
Makes the file available to multiple threads.
RM_STICKY
Forces the resource manager to keep this file open.
Under certain circumstances, the resource manager
may close files to free up file handles. When the file is
needed again, it is reopened. This flag makes sure
that the resource manager does not close the file until
rm_fileClose is called.
crelen [Input] The amount of memory, in bytes, allocated
for the file when it is created.
extlen [Input] The amount of memory, in bytes, to extend
the file whenever a write beyond the end of the file
occurs.
Description This function opens a file. A Velocis resource manager (RM) file
handle pointer is returned. If the file cannot be opened, NULL is
returned.
If the file is to be used by more than one thread, you must specify
RM_SHARE or RM_NOSYNC in the extended characteristics
parameter (xflags). You should only use rm_fileSeekRead and
rm_fileSeekWrite to perform the I/O operations on shared files. If
you call rm_fileSeek, rm_fileRead, or rm_fileWrite on a shared file,
a warning message will be reported to the Velocis message log.
Example
RM_PFILE hInFile, hOutFile;
...
/* open files */
hInFile = rm_fileOpen(inFileName, O_RDONLY|O_BINARY, RM_SHARE, 0, 0);
hOutFile = rm_fileOpen(outFileName, O_CREAT|O_RDWR|O_BINARY,
RM_SHARE|RM_DIRECTIO, 0, 0);
if ( ! hInFile || !hOutFile )
printf("Unable to open files\n");
Description This function returns the current position of the file (the position
where the next read or write would occur).
Return Values The file position (the number of bytes from the beginning of the file);
if the handle is invalid, 0 is returned
Description This function writes the text formatted by the format printf specifier
to the file. The resource manager file must be a file opened (using
rm_fileOpen) with the RM_FPRINTF attribute specified. Any
variables referenced in the format specifier must be listed following
the format string in the order in which they are referenced. Any
standard printf format specification may be used.
Example
RM_PFILE traceFile;
...
traceFile = rm_fileOpen("c:\debug\trace.out", O_TEXT|O_RDWR, RM_FPRINTF);
...
rm_filePrintf(traceFile, "MyFunction(%s, %ld)\n", dbname, seqno);
Description This function reads a block of bytes from the current position in a file
into a specified buffer. This function should not be used with files
that are shared between multiple threads. A warning message will
be written to the Velocis message log whenever rm_fileRead is
called with a file that was opened with the RM_SHARE attribute.
The conflict occurs because, in the time between the call to
rm_fileSeek and the subsequent call to rm_fileRead, another thread
could have issued a call to rm_fileSeek, changing the file position.
Use rm_fileSeekRead for shared, multi-threaded file access.
The function returns the number of bytes actually read. The end of
the file is detected when the return value is less than the specified
length.
Example
unsigned long filelen;
RM_PFILE hFile;
char buf[4096];
unsigned int len, bufsize;
...
hFile = rm_fileOpen("somefile.xyz", O_BINARY|O_RDONLY, 0, 0, 0);
if ( !hFile ) {
printf("unable to open file\n");
exit(1);
}
/* sequentially read through file */
for (filelen = rm_fileLength(hFile); filelen > 0; filelen -= bufsize ) {
bufsize = filelen > 4096 ? 4096 : filelen;
len = rm_fileRead(hFile, buf, bufsize);
if ( len != bufsize ) {
printf("error reading file!\n");
break;
}
}
...
Description This function deletes a file. If the file resides in the current working
directory, you need to specify only a base file name. Otherwise, the
full path name is required.
Example
char filename[500];
...
printf("enter fully-qualified name of file to be deleted: ");
gets(filename);
if ( rm_fileRemove(filename) )
printf("unable to delete file %s\n", filename);
Description This function renames a file. If the file resides in the current working
directory, you need to specify only a base file name. Otherwise, the
full path name is required.
Example
char oldName[500], newName[500];
Description This function sets the position of a file to the specified address. The
address is the byte offset from the beginning of the file. This
function should not be used with files shared between multiple
threads. A warning message will be written to the Velocis message
log whenever rm_fileSeek is called for a file opened with the
RM_SHARE attribute. The conflict occurs because, in the time
between the call to rm_fileSeek and the subsequent call to
rm_fileRead or rm_fileSeekWrite, another thread could have issued
a call to rm_fileSeek, changing the file position. Use
rm_fileSeekRead or rm_fileSeekWrite for shared, multi-threaded
file access.
Example
RM_PFILE datFile;
char reply[81], buf[1024];
unsigned long addr, len;
...
datFile = rm_fileOpen(filename, O_BINARY|O_RDONLY, 0, 0, 0);
...
while ( printf("enter file offset: ", gets(reply) ) {
addr = (unsigned long)atol(reply);
rm_fileSeek(datFile, addr);
len = rm_fileRead(datFile, buf, 1024);
dump_file(buf, len);
}
Example
while ( ! end_of_dump ) {
rm_queueRead(dumpQueue, &pMsg,NULL, &end_of_dump, RM_INDEFINITE_WAIT);
if ( pMsg ) {
/* read block to be dumped */
len=rm_fileSeekRead(hInFile,pMsg->startpos,inBuff, pMsg->blocklen);
if ( len != pMsg->blocklen )
rm_log(LOG_ERROR, "error reading input file");
else
DumpBlock(inBuff, pMsg->startpos, pMsg->blocklen, outBuff);
Description This function writes a block of bytes from a buffer into a resource
manager file, beginning at the specified byte offset position. If your
writes are asynchronous, ensure that all writes have finished by
calling the file synchronization function (rm_fileSync) after
completing all of the required writes. You cannot reuse the buffer
until the write is completed.
Example
/* =====================================================================
Dump block to hex output file
*/
static void DumpBlock(
unsigned char *i_buf,
unsigned long i_pos,
size_t i_len,
char *o_buf)
{
unsigned long o_pos = 77*(i_pos/16);
size_t o_len = 77*(i_len/16);
...
while ( i_len > 0 ) {
... /* format hex dump of block */
}
rm_fileSeekWrite(hOutFile, o_pos, o_buf, o_len, 1);
}
Description This function closes the streaming file represented by rmf. Allocated
memory is released.
Description This function reads any number of characters from the file
represented by rmf and points *buf to the allocated space. A line is
defined as all characters from the current position in the stream to
and including the first newline character.
The line must be freed by using rm_freeMemory and the default tag
(0 or NULL).
Return Values The pointer to the line, or NULL if an error has occurred or if an end-
of-file has been reached
Description This function reads up through the first newline character or to len-1
characters, whichever is shorter. The resulting line will always be
null-terminated.
Return Values A pointer to the line, or NULL if an error has occurred or if an end-
of-file has been reached
Description This function opens the file named by fname. It may be an absolute
or relative page. The mode flags are passed into the ANSI standard
open function and must be defined in fcntl.h. Flags such as
O_CREAT and O_RDWR are commonly used.
A file opened by this function must be used by the other
rm_fileStream* functions. These functions implement a streaming
buffer on top of the rm_file* functions.
Within an extension module, these functions should be used instead
of the standard C/C++ open/close/read/write functions, because
Velocis needs to remain in control of the number of OS file handles
that are open at once.
The return value from this function is a handle to other functions. It
is a pointer to a structure that keeps stream information and a buffer.
You must use rm_fileStreamClose to properly close the file and free
the memory that has been allocated.
Description This function writes one line to a streaming file. It must be a null-
terminated string. The ending null-byte will be changed to a
newline character before the string is written.
Description This function commits all writes on a resource manager file to disk.
All pending writes issued by the calling thread are guaranteed to be
on the disk once the function has returned.
Note: This function must be called from each thread that has issued
asynchronous write calls (see rm_fileSeekWrite).
Example
rm_fileSync(hOutFile);
Description This function looks for the named file on the local file system. The
path to the file may be absolute or relative.
Description This function writes a certain number of bytes to the current position
in a file from a specified buffer. It returns the number of bytes
actually written. An error is detected when the return value is less
than the specified length.
Do not use this function with files shared between multiple threads.
Use rm_fileSeekWrite for shared, multi-threaded file access.
Example
unsigned long filelen;
RM_PFILE hInFile, hOutFile;
char buf[4096];
unsigned int len, bufsize;
...
hInFile = rm_fileOpen(inFileName, O_BINARY|O_RDONLY, 0, 0, 0);
hOutFIle = rm_fileOpen(outFileName, O_CREAT|O_BINARY|O_WRONLY, 0, 0, 0);
Description This function frees a block of memory. The pointer specified must
point to a block of memory previously allocated under the specified
tag. If the pointer was not previously allocated under that tag, an
error message is logged, and the function returns without freeing the
block.
Example
char *tempBuf;
rm_freeMemory(tempBuf, compileTag);
Description This function frees all of the memory that was allocated under a
memory tag. It also allows you to specify whether to free the tag or
leave it for future memory allocations.
Example
jmp_buf memjmp;
if ( setjmp(memjmp) ) {
/* free any previously allocated memory and return error */
rm_freeTagMemory(compileTag, 0);
return errSRVMEMORY;
}
rm_resetTag(memjmp, compileTag);
Description This function returns the definition string for the environment
variable specified. If the environment variable is not defined, the
function returns NULL. An environment variable can be set either in
the system environment or in the [ENVIRONMENT] section of
velocis.ini.
Example
char *catpath;
...
catpath = rm_getenv("CATPATH");
Description This function fetches the next available buffer from the buffer pool.
If there are no buffers in the pool, a new buffer is allocated. If the
static_size flag was 0 in the rm_allocPool call creating the pool, and
the first available buffer is smaller than the specified buffer size, the
buffer will be expanded to the specified size. The size of the
returned buffer will always be at least bufsize in length.
If there is insufficient memory available, the action taken will be the
same as what was specified for the memory tag passed into
rm_allocPool. Buffer pools are most efficient when the sizes of the
buffers are equal, since this reduces the amount of memory
allocation calls required.
Example
Main Thread
/* send dump messages to threads */
for (pos = 0; filelen > 0; pos += buffSize) {
pMsg = rm_getFromPool(sizeof(DUMPMSG), qPool);
pMsg->startpos = pos;
pMsg->blocklen = filelen >= buffSize ? buffSize : filelen;
rm_queueWrite(dumpQueue, pMsg, sizeof(DUMPMSG), 0, 0);
filelen -= buffSize;
}
Dump Thread
while ( ! end_of_dump ) {
rm_queueRead(dumpQueue, &pMsg,NULL, &end_of_dump, RM_INDEFINITE_WAIT);
if ( pMsg ) {
...
Description This function searches through the local Velocis environment for a
variable with name varname.
See rm_getenv for a description of how local Velocis variables are
loaded into the environment.
Example
char *inBuff;
char *outBuff;
...
Syntax short rm_iniGet (char *section, char *entry, char *buffer, short length,
short flag)
Description This function retrieves the setting for a server configuration variable
into an output string. To do this, the function passes all its
parameters to the rm_iniGetPrivate function and supplies the
velocis.ini file name as the last parameter.
Example
rm_log(LOG_INFO, "Dump complete: %ld %d-byte blocks written to file %s.",
blockCount, buffSize, outFileName);
Description This function returns the total number of bytes that have been
allocated to a tag.
Description This function returns the number of bytes that may still be allocated
to a tag. If no limit has been specified, then -1 will be returned.
To set a limit on the memory used by a tag, the rm_createTag
function must be used.
Return Values The number of bytes available, or -1 if no limit has been specified
Description This function puts a buffer into the buffer pool. The buffer must
have been returned from a previous call to rm_getFromPool or have
been allocated using the memory tag specified in the rm_allocPool
call that created the pool.
Example
Main Thread
/* send dump messages to threads */
for (pos = 0; filelen > 0; pos += buffSize) {
pMsg = rm_getFromPool(sizeof(DUMPMSG), qPool);
pMsg->startpos = pos;
pMsg->blocklen = filelen >= buffSize ? buffSize : filelen;
rm_queueWrite(dumpQueue, pMsg, sizeof(DUMPMSG), 0, 0);
filelen -= buffSize;
}
Dump Thread
while ( ! end_of_dump ) {
rm_queueRead(dumpQueue, &pMsg,NULL, &end_of_dump, RM_INDEFINITE_WAIT);
if ( pMsg ) {
...
/* free queue message */
rm_putInPool(pMsg, qPool);
}
Description This function parses sp to obtain a variable name and variable value.
The form of the string must be:
name=value
The name may be used in rm_getLocalEnv or rm_getenv to find the
value.
Parameters name [Input] The name of the queue to create. This name
is reported in any error messages generated.
Example
short dumpQueue;
...
/* Create message queue for sending dump instructions to threads */
dumpQueue = rm_queueCreate("dumpQueue");
Description This function deletes a queue and any messages that are currently on
the queue.
Example
short dumpQueue;
...
rm_queueDelete(dumpQueue);
Description This function looks for all messages matching a message identifier
and removes them from a queue. If the message identifier is equal to
-1, the function removes all messages from the queue.
Example
/* forced system shutdown, purge and delete queue */
rm_queuePurge(dioQueue, -1);
rm_queueDelete(dioQueue);
Description This function reads a message from a specified queue. Once the
message has been read, the function stores a pointer to the message
buffer, the size of the buffer, and the message identifier. Note that
the pointer returned by rm_queueRead is identical to the pointer
passed into rm_queueWrite by the sending thread.
If no message is available on the queue, the call will suspend until
either a message is sent or the maximum wait time has elapsed. A
status of RM_TIMEOUT is returned if the function returns and there
are no messages available.
Example
/* process cache manager request messages */
for ( msgCount = 0; ; ++msgCount ) {
rm_queueRead( dioQueue, &pMsg, NULL, &msgid, RM_INDEFINITE_WAIT );
switch ( msgid ) {
case DIO_GET:
... /* get request cache page */
...
}
Description This function places a message of specified length into a queue. The
message can be placed at the beginning or at the end of the queue.
You may include an identifier number with the message.
Example
/* session thread’s request to cache manager to read a page */
rm_syncStart(pMsg->dioSem);
Description This function modifies the location of the out-of-memory error jump
buffer. The errloc parameter is the value of a C jump buffer, which
you establish by calling setjmp. Control will be passed to that
location (via a call to longjmp) when there is not enough memory to
satisfy an allocation request (for example, a call to rm_getMemory)
on the tag. An errloc value of NULL indicates that NULL will be
returned by memory allocation functions when there is insufficient
memory.
Example
jmp_buf memjmp;
if ( setjmp(memjmp) ) {
/* free any previously allocated memory and return error */
rm_freeTagMemory(compileTag, 0);
return errSRVMEMORY;
}
rm_resetTag(memjmp, compileTag);
Description This function causes the executing thread to suspend (allowing other
threads to run), until at least the specified period of time has elapsed.
The function is typically used by a thread waiting for some activity
to be completed.
Example
while ( ! done ) {
/* check it once each second */
rm_sleep(1000);
}
rm_startup Start the Velocis resource manager (in lieu of the Velocis database
engine)
Description This function starts the Velocis resource manager. Use this function
only when your application will not be using any of the Velocis
database functions.
The function for handling log messages can have any valid function
name. It requires three parameters: an indicator of the type of action
being taken, an indicator of the type of message, and the message
string itself. The action type indicator can be one of the following
values:
Example
#include "velocis.h"
switch ( fcn ) {
case RDSLOG_OPEN:
errlog = fopen("velocis.log", "w");
break;
case RDSLOG_MESSAGE:
if ( type == LOG_ERROR ) {
/* make sure this gets noticed */
fprintf(errlog, "******* ERROR! ******* ");
printf("******* ERROR! ******* ");
}
fprintf(errlog, "%s\n", msg);
printf("%s\n", msg);
break;
case RDSLOG_CLOSE:
fclose(errlog);
break;
}
}
Example
RM_SEM mSem, eSem, qSem;
...
mSem = rm_syncCreate("task table", RM_MUTEX_SEM, RM_SHAREABLE);
eSem = rm_syncCreate("chkpt done", RM_EVENT_SEM, RM_EXCLUSIVE);
qSem = rm_syncCreate("log cycle", RM_QUIES_SEM, RM_EXCLUSIVE);
Example
rm_syncDelete(mSem);
rm_syncDelete(eSem);
rm_syncDelete(qSem);
Example
Writer Thread
/* prevent new readers from gaining access */
rm_syncDisableQ(qSem);
/* wait for all current readers to exit */
rm_syncWaitQ(qSem, RM_INDEFINITE_WAIT);
Reader Thread
/* gain access to shared data */
rm_syncReceiveQ(qSem);
Description This function is called from the writer thread to enable reader access
to the shared data controlled by a quiescent semaphore. The writer
thread calls this function after it has completed making the needed
changes to the shared data.
Reader threads must call rm_syncReceiveQ to receive access
permission to the semaphore. These threads are left hanging,
however, if the semaphore is in a disabled state. The
rm_syncEnableQ function releases these threads, allowing access
from the threads to occur.
Example
Writer Thread
/* prevent new readers from gaining access */
rm_syncDisableQ(qSem);
/* wait for all current readers to exit */
rm_syncWaitQ(qSem, RM_INDEFINITE_WAIT);
Reader Thread
/* gain access to shared data */
rm_syncReceiveQ(qSem);
Example
/* update count of dumped blocks */
rm_syncEnterExcl(countSem);
++blockCount;
rm_syncExitExcl(countSem);
Example
/* update count of dumped blocks */
rm_syncEnterExcl(countSem);
++blockCount;
rm_syncExitExcl(countSem);
Description This function is called by a reader thread to gain access to the shared
data controlled by a quiescent semaphore. If the semaphore is
disabled (that is, a writer thread currently has access), the calling
thread will be suspended until the semaphore is re-enabled. After
the function returns, the thread may access (safely read but not
safely modify) the shared data. The thread then calls
rm_syncSendQ to signal that it has completed its access.
Example
Writer Thread
/* prevent new readers from gaining access */
rm_syncDisableQ(qSem);
/* wait for all current readers to exit */
rm_syncWaitQ(qSem, RM_INDEFINITE_WAIT);
Reader Thread
/* gain access to shared data */
rm_syncReceiveQ(qSem);
Description This function sets the state of an event semaphore to signalled. All
threads that are hanging on a call to rm_syncWait will be released.
Example
/* =====================================================================
Example thread
*/
static void RTHREAD Example(void *pTestQueue)
{
short testQueue;
RM_SEM doneSem;
void *pMsg;
unsigned long msgCount;
rm_syncResume(doneSem);
if ( ! pMsg )
break;
}
rm_threadEnd();
}
rm_syncWait(pMsg->dioSem, RM_INDEFINITE_WAIT);
Description This function is called by a reader thread when it has completed its
access to the shared data controlled by the quiescent semaphore. It
sends its exit notification status to the semaphore. If this is the only
reader thread and the semaphore is disabled, the writer thread
hanging on a call to rm_syncWaitQ will be released.
Example
Writer Thread
/* prevent new readers from gaining access */
rm_syncDisableQ(qSem);
/* wait for all current readers to exit */
rm_syncWaitQ(qSem, RM_INDEFINITE_WAIT);
Reader Thread
/* gain access to shared data */
rm_syncReceiveQ(qSem);
Description This function starts an event by placing the event semaphore into a
non-signalled state. This means that any other thread calling
rm_syncWait will hang until some thread calls rm_syncResume.
Example
/* session thread’s request to cache manager to read a page */
rm_syncStart(pMsg->dioSem);
Description This function waits for the event semaphore to be signalled. If the
semaphore is already in a signalled state, the function returns
immediately. The semaphore remains signalled until some thread
calls rm_syncStart. Calling rm_syncResume signals the semaphore.
If the semaphore is not signalled, the calling thread will wait,
pausing up to the amount of time specified in the rm_syncWait call.
(If RM_INDEFINITE_WAIT is specified, the thread will wait
indefinitely.) If a timeout occurs, the function returns
RM_TIMEOUT.
Example
/* session thread’s request to cache manager to read a page */
rm_syncStart(pMsg->dioSem);
Description This function is called by a writer thread to wait for all currently
executing reader threads to complete. This function can be called
when the quiescent semaphore is not yet disabled. In that case, no
new rm_syncReceiveQ calls are blocked, but if the number of
readers drops to zero, the quiescent semaphore automatically
becomes disabled, and the call to rm_syncWaitQ returns.
Example
Writer Thread
/* prevent new readers from gaining access */
rm_syncDisableQ(qSem);
/* wait for all current readers to exit */
rm_syncWaitQ(qSem, RM_INDEFINITE_WAIT);
Reader Thread
/* gain access to shared data */
rm_syncReceiveQ(qSem);
Description This function can be used to launch a new thread. Your use of this
function is platform-independent and allows you to develop Velocis
application servers that are independent of platform.
The size of the stack allocated for the thread is typically a multiple of
1,024 bytes. (Velocis assigns a stack size of "2048 * sizeof(int)".) Be
careful to assign an ample amount, because a stack overwrite can
cause the server to fail with a general protection fault.
The thread priority values only affect scheduling behavior on
operating systems that support thread priorities, such as Windows.
Unless special requirements indicate otherwise, it is recommended
that you use normal priority (RM_THREAD_NORMAL).
Example
/* =====================================================================
Example thread
*/
static void RTHREAD Example(void *pTestQueue)
{
short testQueue;
RM_SEM doneSem;
void *pMsg;
unsigned long msgCount;
rm_syncResume(doneSem);
if ( ! pMsg )
break;
}
rm_threadEnd();
}
/* =====================================================================
Multi-threaded Velocis Standalone Test Program
*/
void main()
{
...
Parameters None
Example
/* =====================================================================
Example thread
*/
static void RTHREAD Example(void *pTestQueue)
{
short testQueue;
RM_SEM doneSem;
void *pMsg;
unsigned long msgCount;
rm_syncResume(doneSem);
if ( ! pMsg )
break;
}
rm_threadEnd();
}
Description This function frees all of the buffers contained in the buffer pool.
Any control information is also freed. The function sets the pool
handle to NULL.
Example
RM_POOL *qPool;
...
/* free the message pool */
rm_zFreePool(&qPool);
Description The s_backupAttach function moves the server from persistent hot
backup mode to regular hot backup mode. Only after a successful
call to this function can hot backup mode be terminated in the
normal way (through s_backupEnd or s_logout). (Alternatively, a
single function call to s_backupKill can end persistent hot backup
mode.)
The hBackup session handle must identify an internal session created
by an earlier call to s_backupDetach. The s_backupAttach function
transfers the internal session’s backup status to the session identified
by hSess, which can be different than the session handle passed
earlier to s_backupDetach. The session can then terminate hot
backup mode as if it had previously called s_backupBegin only.
s_backupCacheGet Get the maximum number of hot file index pages for caching
Description This function retrieves the current value that specifies the maximum
number of hot file index pages that the Velocis server will cache
during hot backup.
s_backupCacheSet Set the maximum number of hot file index pages for caching
Description This function allows you to change, before starting hot backup, the
size of the cache for the hot file index pages. Velocis allocates and
caches this amount in memory at the start of backup mode. If this
function is not called, Velocis uses the value of the
HotIndexCachePages configuration parameter in velocis.ini. To
retrieve the current cache size, use the s_backupCacheGet function.
Description This function ends hot backup mode. If the flush flag is set, this
function calls s_backupFlush to flush the hot file. If the flush flag is
not set, the modified pages stored in the hot file will be written
gradually to the database files and removed from the hot file, as
they are read during normal server operation. Note that if multiple
clients have called s_backupBegin, all of them have to call
s_backupEnd before the backup mode is terminated.
Description This function flushes all changes made during the most recent
backup from the hot file to the database files. It can only be called
outside of backup mode (that is, after s_backupEnd has been
called).
Calling s_backupFlush is optional, because Velocis gradually writes
hot file changes back to the database files as they are accessed from
the hot file after the latest backup. However, calling this function
returns the system to normal operational mode as soon as possible.
Note that s_backupFlush forces the hot pages to migrate by reading
all hot pages into the database files and marking them as modified.
Velocis then uses its normal checkpoint process to write the hot
pages back to the database files.
Description This function adds the specified database to the system catalog. It
also registers the data and key files that belong to the database,
which is required before any application can access the database.
must call the s_dbrEnd function to make the session available for
the next dbrepair operation.
You can limit the check if you specify particular database elements
in the null-terminated arrays recIDs, setIDs, keyfldIDs, and blobfldIDs.
If these are not NULL, only records, sets, keys, and BLOBs of the
types specified in these parameters will be checked for consistency.
The consistency check performs the following:
• Validates the database address and type for each record of the
specified record types
• Checks the integrity of the delete chains
• Checks the integrity of sets
• Checks the integrity of BLOBs
• Checks for consistency between keys and their corresponding
field values in records
The database checking procedure scans the specified database to be
sure the record headers (containing the record ID, database address,
etc.) are valid, the key files are correct and are consistent with the
data files, and the set linkages and BLOB linkages are valid. During
its scan, the procedure validates the position of each record
occurrence and verifies the integrity of the delete chains. The set
consistency cannot be ascertained without record type and delete
chain validation. Therefore, the owner and the member records of
the checked sets are always verified for consistency, even if their
types are not explicitly specified in recIDs. The procedure reports
each inconsistency with a message indicating the nature of the
inconsistency and the file and location of the offending record, key,
or BLOB. It also can report some statistics on the scanned files. The
output is the user report sent to the output file specified by filename
on the user device. The system report is printed in the system log.
If DBR_QUICKCHECK is specified, the check operation is
performed in quick mode. In this mode, the check procedure does
not traverse sets for details of the corruption. Instead, for each set
type, it adds the member count in each owner record and counts the
total number of non-orphan member records. In a consistent
database, the totals must match. If a database is corrupted, there is a
good chance of a mismatch, and the utility reports an error. This
mode significantly reduces set verification time and is designed for
routine consistency checking, but it does not guarantee 100%
detection of all possible database corruption.
Parameters dbname [Input] The name of the database whose files are to
be compressed.
options [Input] The option flags. This parameter is a bit
map of the following values:
DBR_REPORT_SUMMARY
Sends only a summary report to the output file.
Otherwise, sends extra statistical information.
DBR_SYSLOG_SUMMARY
Sends nothing to the system log except internal
error messages. Otherwise, reports on the start
and termination of the major steps of the
compression process.
DBR_SIMULATE
Produces only a report of the modifications
necessary to compress the specified files,
without performing the modifications.
DBR_IGNORE_DBA
Instructs the module to ignore defined fields of
type DB_ADDR. Use this mode when these
fields contain references to records in other
databases.
recIDs [Input] A pointer to a null-terminated array of
record type IDs. Only the database files containing
the records of the specified types are to be
compressed. The last element of the array must be
NULL_RECID. If your application passes NULL in
this parameter, all data files in the database will be
compressed. If, in this parameter, your application
passes a pointer to an array containing only the
terminating element, no data files are compressed.
blobfldIDs [Input] A pointer to a null-terminated array of
BLOB field IDs. These IDs specify which BLOB files
will be compressed. If the ID of a BLOB field is
encountered in the array, the BLOB file containing
BLOBs for this field will be compressed. The last
Description This function opens the dbname database in exclusive mode and
compresses the database by removing the delete chain slots from the
data files and BLOB files. The function is executed asynchronously;
it returns immediately after the repairing process has started.
You can obtain information on the current status of the compression
process by calling the s_dbrGetStatus function. You can abort this
process at any time with a call to the s_dbrEnd function. If the
process has already terminated, you must call s_dbrEnd to make the
session available for the next dbrepair operation.
Normally, whenever a record is deleted from the database, it is
marked for reuse and put on the delete chain, but not physically
removed from the file. The database file compression procedure
moves records from the end of the file into the places occupied by
the deleted records, adjusting all pointers referring to the moved
records. It leaves no unused slots between valid records in the file.
A similar technique is used for BLOB files. By default, the operation
adjusts all values of type DB_ADDR in the database that refer to
moved records. However, if some record fields of type DB_ADDR
are considered database addresses in another database, you should
use the DBR_IGNORE_DBA option.
Description This function removes the specified database from the system
catalog. Note that the function does not delete the associated
database files.
the array, the key file containing keys for this field
will be repaired. The last element of the array must
be NULL_FLDID. If your application passes NULL
in this parameter, all key files in the database will
be repaired. If, in this parameter, your application
passes a pointer to an array containing only the
terminating element, no keys will be repaired.
blobfldIDs [Input] A pointer to a null-terminated array of
BLOB field IDs. These IDs specify which BLOB files
are to be repaired. If the ID of a BLOB field is
encountered in the array, then the BLOB file
containing BLOBs for this field will be repaired.
The last element of the array must be
NULL_FLDID. If your application passes NULL in
this parameter, all BLOB files in the database will be
repaired. If, in this parameter, your application
passes a pointer to an array containing only the
terminating element, no BLOBs will be repaired.
cachepages [Input] The number of pages to be allocated in the
internal dbrepair cache for the operation. The
default is 64.
dumpname [Input] The name of the file on the user device
containing the dump of the corrupted records that
were removed from the database by the
s_dbfixBegin function. If your application passes
NULL in this parameter, no dump of the removed
records is produced.
filename [Input] The name of the file where the report
containing the results of the database consistency
check and the description of the database repairs is
to be sent. If your application passes NULL in this
parameter, no user report is produced.
hSess [Input] The session handle.
Description This function opens the dbname database in exclusive mode and
performs the following actions:
• Runs the full consistency check of the database (equivalent to
dbcheck) to obtain detailed information on all cases of the
database’s corruption.
Parameters dbname [Input] The name of the database for which this
function retrieves a definition.
dbase [Output] A pointer to the DBD_DBF structure
containing the database definition.
hSess [Input] The session handle.
Description This function causes the server to initialize the specified registered
database. It first tries to open the database in exclusive access mode.
If this action is successful, the function calls s_dbInitfile to initialize
the data and key files associated with the database.
The s_dbInit function returns S_BUACTIVE if it is called during hot
backup mode. (In previous versions of Velocis, database files could
be changed whenever Velocis was in backup mode.)
Description This function causes the server to initialize the specified database
file. Because this function initializes only one file, use s_dbInit if
you want initialize an entire database.
Description This function ends the dbrepair operation started in the session by
any of the following operations: s_dbcheckBegin, s_dbfixBegin,
s_keybuildBegin, s_dbdefragBegin, or s_dchainBegin. If the
operation is still in progress, the s_dbrEnd call aborts it. The
function closes the database processed in the operation and makes
the session handle available for new dbrepair operations.
Description This function returns in the status structure the details of the current
status of the active dbrepair operation started in the session (with
hSess) by any of the following functions: s_dbcheckBegin,
s_dbfixBegin, s_keybuildBegin, s_dbdefragBegin, or
s_dchainBegin. The structure is defined as follows:
typedef struct _DBR_STATUS {
short terminated; /* contains 0 if the process is in
progress, 1 if completed normally, 2 if
terminated prematurely. Negative value
indicates an error and contains the
error code */
char fname[FILELEN]; /* contains name of the file currently
being processed */
unsigned long items; /* number of the file items
(records/nodes/pages) already processed */
short passno; /* number of the pass of the file currently
being executed */
unsigned long errors; /* number of errors found in the database */
} DBR_STATUS;
Description This function checks the physical allocation of records, indexes, and
blobs in database files. It determines the number of items per
database page for each database file and the amount of unused
space per file based on slack space between the record/slot sizes
and the slot/page sizes.
To implement the dbstat utility, s_dbstat loads and attaches the
internal extension module that performs the analysis. It also
detaches and unloads the module when it is finished processing.
Return Values S_OKAY S_PRIV
Description This function adds a user to the access list for the specified database,
which has previously been designated "private" (see s_dbAdd).
Only users connected to the database access list can open the
database. All database users have a default of read access
(permaccess = 0) to the database, but only one user can be designated
as the owner of the database (ownerdb = 1).
Description This function removes a user from the database access list for the
indicated database.
Description This function retrieves a database access record for the specified
user (user). The dbaccrec structure has two short integer fields,
permaccess and ownerdb, containing the values specified in the
s_dbUserAdd function call.
Parameters dbname [Input] The name of the database whose files are to
be processed for delete chain repair.
options [Input] The option flags. This parameter is a bit
map of the following values:
DBR_REPORT_SUMMARY
Sends only a summary report to the output file.
Otherwise, sends additional statistical
information.
DBR_SIMULATE
Produces only a report of the modifications
necessary to repair the delete chains of the
specified files without actually performing these
modifications.
DBR_SYSLOG_SUMMARY
Sends nothing to the system log except internal
error messages. Otherwise, reports on the start
and termination of the major steps of the delete
chain repair process.
recIDs [Input] A pointer to a null-terminated array of
record type IDs. Only the delete chains of the data
files containing the records of the specified types
will be repaired. The last element of the array must
be NULL_RECID. If your application passes NULL
in this parameter, delete chains in all the data files
will be repaired. If, in this parameter, your
application passes a pointer to an array containing
only the terminating element, no delete chains in
the data files will be repaired.
keyfldIDs [Input] A pointer to a null-terminated array of key
field IDs. These IDs specify the key files where the
delete chains are to be repaired. If the ID of a key
field is encountered in the array, then the delete
chain of the key file containing that key will be
repaired. The last element of the array must be
NULL_FLDID. If your application passes NULL in
Description This function opens the dbname database in exclusive mode and
rebuilds delete chains in the database files. The function is executed
asynchronously; it returns immediately after the repairing process
has started.
You can obtain information on the current status of the delete chain
rebuilding process by calling the s_dbrGetStatus function. You can
abort this process at any time with a call to the s_dbrEnd function.
If the process has already terminated, you have to call the s_dbrEnd
function to make the session available for the next dbrepair
operation.
The delete chain rebuilding procedure creates a new chain by
connecting all records marked as deleted in the order of their
database addresses. The main purpose is to ensure that all records
Description This function adds (registers) a single device in the system catalog.
Devices are used to provide logical names for locations of files.
Description This function adds (registers) a logical device in the system catalog.
If the fCdrom parameter is set to TRUE, the device is read-only (for
example, a CD-ROM device).
Description This function removes the definition of a device from the system
catalog. The function can only delete the device definition if it has
no associated items (for example, database files or extension
modules) connected to it. To disconnect associated items, the
application should use s_dbDel, s_userDel, and s_emDel.
Description This function retrieves the definition of the specified device from the
system catalog.
Description This function retrieves the definition of the specified logical device
from the system catalog.
Description This function changes the physical path associated with the
specified logical database device. Your application cannot use this
function to change the device name in the system catalog. To do
this, the application should call s_devDel to delete the device, then
add the new name with a call to s_devAdd.
Description This function changes the physical path associated with the
specified logical device. Your application cannot use this function to
change the device name in the system catalog. To do this, the
application should call s_devDel to delete the device, then add the
new name with a call to s_devAddEx.
Description This function changes the device designated for the extension
module. Note that your application cannot call s_emModify to
change the extension module name. To make a name change, you
must first delete the extension module with a call to s_emDel and
then add it back with a new name (via s_emAdd).
Parameters None
Description This function shuts down the Velocis remote procedure call (RPC)
and network control processor (NCP) subsystems. You must call
this function from your application server before calling
s_terminate, which shuts down the Velocis database engine.
Example
#include "velocis.h"
...
s_endRPCThreads();
s_terminate();
...
Description This function returns the error message associated with the specified
Velocis error code. The location of the error code’s description is
returned by the errbuf parameter.
Parameters basedev [Input] The name of the device containing the base
file.
basefile [Input] The name of the base file.
extdev [Input] The name of the device on which to store
the extension file.
extfile [Input] The name of the extension file to add.
hSess [Input] The session handle.
Description This function adds an extension file to the specified base file, which
is contained on the Velocis device basedev. The new file will be
named extfile and will be located on the device extdev. The extension
file will be created once the base file has grown to the size equal to
its maximum file size limit. You can change the default base file size
limit as well as the extension file size limit by calling function
s_fileSetSizes.
Parameters basedev [Input] The name of the device containing the base
file.
basefile [Input] The name of the base file.
extno [Input] The extension file number. Use 0 to specify
the base file.
pFileinfo [Output] A pointer to the FILEINFO structure that
contains the base/extension file parameters.
hSess [Input] The session handle.
Description This function moves the specified file (either a base file or an
extension file) from its current device to the new one.
Description This function receives the specified file from the server database
device. The function places the retrieved file in the current
directory of the application, unless a path is also specified in the
filename.
Description This function sends the specified file to the server database device.
The function retrieves the file to be sent from the current directory
of the application, unless a path is also specified in the filename.
Parameters basedev [Input] The name of the device containing the base
file.
basefile [Input] The name of the base file.
extno [Input] The extension file number. Use 0 to specify
the base file.
maxsize [Input] The new maximum size of the extension file.
cresize [Input] The new creation size of the extension file.
extsize [Input] The new extension size of the extension file.
hSess [Input] The session handle.
Parameters basedev [Input] The name of the device containing the base
file.
basefile [Input] The name of the base file.
noexts [Output] A pointer to the total number of extension
files.
maxsize [Output] A pointer to the maximum size, in bytes,
of the base file plus the extension files.
totsize [Output] A pointer to the current allocated size, in
bytes, of the base file plus the extension files.
hSess [Input] The session handle.
Description This function returns the total number of extension files that were
attached to basefile on device basedev. It also returns the maximum
size and the total space used (in bytes) on basedev by basefile and its
extension files. The values that are returned in totused and maxsize
are exact double values (an 8-byte double has 15 significant digits).
NULL values can be specified for any of the output arguments.
Description This function retrieves the minimum amount of free disk space that
is currently available and the name of the device that has the least
space. When more than one Velocis device is located on the same
physical device, all the devices have the same amount of free disk
space available at any time.
The s_getDiskFreeSpace function returns S_OKAY if the amount of
free disk space is above the minimum threshold. The function
returns S_NOSPACE if the amount of available disk space on a
Velocis device has fallen below the minimum threshold and the
server is now in read-only mode. In this case, s_getDiskFreeSpace
writes the amount of disk space below the threshold in the pAvail
parameter.
If the server has been in read-only mode (out of disk space) when
the application calls s_getDiskFreeSpace, but all Velocis devices are
currently above the minimum threshold, the server re-enables
updates. For example, the application might call
s_getDiskFreeSpace if it has just freed some disk space.
Description This function retrieves the number of minutes of inactivity that the
server allows on a client connection before assuming it is dead and
disconnecting it. This value is used whenever the server is unable to
detect a dead client. By default, Velocis does not timeout a
connection. See s_setTimeout for details on setting a timeout limit.
Syntax short s_iniGet (char *section, char *entry, char *buffer, short length,
short flag, RDM_SESS hSess)
Description This function opens the dbname database in exclusive mode and
rebuilds indexes contained in the database key files. The function is
Description This function sends the message to the server’s (or application
server’s) log function. The default log function writes the specified
message to the console and the system log (RDS.log).
Description This function logs into the server through the Core API
(d_ functions). Note that user names and passwords are case-
sensitive. When the login is complete, s_login returns the session
handle for the application to use in subsequent calls. Connection
aliases must be defined in the connect.ini file on the client machine.
See Chapter 2 of the Velocis Installation and Administration Guide.
Description This function logs out the application from the server associated
with the session indicated by the hSess parameter. The hSess server
handle will no longer be valid (that is, it can no longer be used to
access the server).
If the hSess session holds active transactions or open databases, they
will be cleaned up. Uncommitted transactions will be aborted.
Syntax short s_ping (char *server, unsigned long count, unsigned long pktsz,
pPING_CALLBACK pingBack, void *ptr)
Parameters minFree [Input] A new value, in bytes, for the minimum free
disk space threshold. The default is 5 MB.
hSess [Input] The session handle.
Description This function dynamically sets the minimum amount of free disk
space threshold value. If the amount of available disk space for any
device falls below the server-wide threshold set in this parameter,
Velocis enters read-only mode. In this mode, Velocis returns
S_NOSPACE from all database create, modify, and delete function
calls.
The free disk space threshold set by your application must be large
enough to accommodate the largest checkpoint. If the threshold is
too low for a checkpoint to occur, the server shuts down. To find
out the current free disk space threshold value, your application can
call s_getDiskFreeSpace.
As an alternative to calling s_setMinFreeSpace in your application,
if you have administrative privileges, you can change the free disk
space threshold through admin or rdsadm. Procedures for doing
this are provided in the Velocis Installation and Administration Guide.
Note: All Velocis devices that are stored on the same physical
device have the same amount of free space available at any time.
s_setTimeout Set the total amount of inactive time allowed on a connection before
the server assumes that the client has disconnected
Description This function sets the number of minutes of inactivity that the server
allows on a client connection before disconnecting it. ("Inactivity" is
the total time elapsed since the server received a message from the
client.) By default, the server waits until the network informs it of a
client disconnection. If you want to set the timeout with this
function, you must call s_login before calling s_setTimeout. (If
multiple sessions are started, a separate timeout may be established
for each.)
Velocis depends on the network transport layer to inform the server
of a client disconnection (because of premature exit, power loss, or
abnormal termination). Under some circumstances, the transport
fails to inform the Velocis server, and although the client program
no longer exists, the server still maintains a session for the client.
Velocis does not automatically specify a timeout limit, so there are
no default restrictions on inactive time. To set a default value, you
may add a parameter to the connect.ini file used by the client. In
the [Configuration] section, add the following:
[Configuration]
ClientTimeout=XX
Syntax short s_showDbFiles (char *dbname, short pos, unsigned long nelems,
void *buf, unsigned long buflen, unsigned long *actualelem,
RDM_SESS hSess)
Description This function retrieves the names of files and devices that are
associated with the database dbname. If the value of actualelem is
equal to the value of nelems, indicating that there is more
information to gather, your application needs to make additional
calls to retrieve all the information. For each of these follow-up
calls, the application needs to set pos to FETCHNEXT.
Example
FILEDEV dbarrayfiles[50];
void *buf;
Syntax short s_showDbs (short pos, unsigned long nelems, void *buf,
unsigned long buflen, unsigned long *actualelem,
RDM_SESS hSess)
Example
void *buf;
char dbarray[50][SIZEOF_DBNAME];
/* Can hold up to 50 database names */
Example
void *buf;
char *dbname = "tims";
char userarray[50][SIZEOF_USERNAME]; /* Can hold up to 50 users */
Syntax short s_showDevs (short pos, unsigned long nelems, void *buf,
unsigned long buflen, unsigned long *actualelem,
RDM_SESS hSess)
Description This function retrieves the names of registered devices in the system
catalog. If the value of actualelem is equal to the value of nelems,
indicating that there is more information to gather, your application
needs to make several calls to retrieve all the information. On these
follow-up calls, the application should set pos to FETCHNEXT.
Example
void *buf;
char devarray[50][SIZEOF_DEVNAME]; /* Holds up to 50 device names */
Syntax short s_showEms (short pos, unsigned long nelems, void *buf,
unsigned long buflen, unsigned long *actualelem,
RDM_SESS hSess)
Example
void *buf;
char extmodarray[50][SIZEOF_EMNAME];
/* Can hold up to 50 extension module names */
Example
void *buf;
char dbarray[50][SIZEOF_DBNAME];
/* Can hold up to 50 database names */
Syntax short s_showUsers (short pos, unsigned long nelems, void *buf,
unsigned long buflen, unsigned long *actualelem,
RDM_SESS hSess)
Description This function retrieves the names of database users registered in the
system catalog. If the number of elements retrieved matches the
number requested, there is more information to gather, and your
application needs to make additional calls (with pos set to
FETCHNEXT) to retrieve the remaining information.
Example
void *buf;
char userarray[50][SIZEOF_USERNAME]; /* Holds up to 50 user names */
s_startRPCThreads Start the Velocis RPC/NCP subsystem and initiate session threads
Description This function is called from an application server to start the Velocis
remote procedure call (RPC) and network control processor (NCP)
subsystems. This allows standard Velocis client programs,
including third-party ODBC tools that use the Velocis ODBC driver,
to access the Velocis database controlled by your application server.
Velocis maintains a pool of threads to process calls from the user
login sessions. There can be many more user sessions than session
threads. You need to specify the number of session threads in the
pool.
The function can be passed a pointer to a shutdown flag, which
Velocis sets to 1 when a system shutdown has been requested. A
system shutdown is requested when some administrative user has
called the s_shutdown function or used the shutdown command on
the admin or rdsadm utility. Initialize the flag to 0 before calling
s_startRPCThreads. Specifying NULL for the shutdown flag will
disable the s_shutdown function and the shutdown commands in
the admin and rdsadm utilities.
Example
#include "velocis.h"
...
s_endRPCThreads();
...
Description This function starts the Velocis database engine. It must be the first
Velocis function called from a server-based application program
that uses Velocis (that is, the application server). It is not necessary
to call this function from a standard Velocis client-based program.
An alternative directory path for the Velocis catalog may be
specified.
You may choose to have a custom function to handle Velocis log
messages. The custom function requires three things: an indicator
for the type of action being done, indicators for the types of
Example
#include "velocis.h"
switch ( fcn ) {
case RDSLOG_OPEN:
errlog = fopen("velocis.log", "w");
break;
case RDSLOG_MESSAGE:
if ( type == LOG_ERROR ) {
/* make sure this gets noticed */
fprintf(errlog, "******* ERROR! ******* ");
printf("******* ERROR! ******* ");
}
fprintf(errlog, "%s\n", msg);
printf("%s\n", msg);
break;
case RDSLOG_CLOSE:
fclose(errlog);
break;
}
}
Database STAT_PGZERO_READ
Statistics Total number of times Velocis performed a page zero read from a
database file.
STAT_PGZERO_WRITE
Total number of times Velocis performed a page zero write to a
database file.
STAT_OPEN_DB_TABLES
Total number of times a database open required a database
dictionary read from disk.
STAT_CLOSE_DB_TABLES
Total number of times a database dictionary was removed from
memory. This counter is incremented when all users of the database
have called d_close and the table can be removed from Velocis
memory.
STAT_OPEN_DBS
Total number of times Velocis performed a database open.
STAT_CLOSE_DBS
Total number of times Velocis performed a database close.
Locking STAT_GROUP_LOCK_REQ
Statistics Total number of lock requests Velocis serviced. This counter is
incremented when Velocis receives a lock request, whether it was
granted, blocked, timed out, or a Velocis error occurred.
STAT_GROUP_LOCK_BLOCKED
Total number of lock requests blocked because of an incompatible
lock.
STAT_GROUP_LOCK_TIMEOUT
Total number of times a lock timed out because of an incompatible
lock.
STAT_INST_READ_LOCKS
Total number of times an instance read lock is granted.
STAT_TABLE_READ_LOCKS
Total number of times a table read lock is granted.
STAT_INST_WRITE_LOCKS
Total number of times an instance write lock is granted.
STAT_TABLE_WRITE_LOCKS
Total number of times a table write lock is granted.
STAT_FREED_LOCKS
Total number of successful requests to free instance and table locks.
Transaction STAT_TRBEGINS
Statistics Total number of times a database transaction began. This counter is
incremented after every successful d_trbegin call to an open
database.
STAT_TRENDS
Total number of times a database transaction ended. This counter is
incremented after every successful d_trend call to an open database.
STAT_TRABORTS
Total number of times a transaction aborted. This counter is
Remote STAT_REQUESTS
Procedure Call Total number of client RPC calls serviced by the server.
(RPC) Statistics
STAT_LOGINS
Total number of times the server processed a login.
STAT_LOGOUTS
Total number of times the server processed a logout. This counter is
increased when a successful client logout is serviced by Velocis.
STAT_CLIENT_ABORTS
Total number of times Velocis aborted a client session. For every
session abort, a logout will be automatically performed by Velocis,
hence the STAT_LOGOUTS total is also incremented.
Miscellaneous STAT_D_FCN_CALLS
Statistics Total number of d_ function calls. This counter is increased each
time a d_ function call is made to Velocis by a client or by a Velocis
extension module.
STAT_DBERRS
Total number of database errors. This counter is increased each time
a database error occurs.
STAT_NORM_REQUESTS
Total number of normal RPC requests. This counter is increased
each time Velocis receives a normal RPC request that is serviced by
a normal Velocis thread.
STAT_PRI_REQUESTS
Total number of priority RPC requests. This counter is increased
each time Velocis receives a priority RPC request that is serviced by
a priority Velocis thread.
Example
long stats[N_STATS];
long totalTx = 0;
Parameters None
Description This function shuts down the Velocis database engine. If you have
previously called s_startRPCThreads, you must first call
s_endRPCThreads before calling s_terminate.
Example
#include "velocis.h"
...
s_endRPCThreads();
s_terminate();
}
Description This function adds a user to the system catalog, using information
from the USERINF_CHG structure. Your application must have
previously called s_devAdd to register the home database device
for the user.
Description This function removes a database user from the system catalog. The
user is then blocked from accessing the server or its databases.
Parameters username [Input] The name of the user from whom to retrieve
information.
user [Output] A pointer to the USERINF_CHG structure
containing the retrieved user information.
hSess [Input] The session handle.
Description This function retrieves the definition for the specified database user
from the system catalog.
Description This function modifies the user definition for the specified user. It
changes the password, database access privileges, or default user
device in the system catalog.
Description This function retrieves the version string of the server. If you set the
session handle to NO_SESS, the function retrieves the version string
from the client side shared library. An application can use this
information to check whether there is a need to upgrade the
database software.
Example
/* Get Velocis Client and Server library versions. */
#include <stdio.h>
#include "velocis.h"
void main(void)
{
short sStatus = 0;
RDM_SESS hSess = 0;
char *szVersion = NULL;
/* ----------------------------------------------------------
** Get and display Client libraries version.
** ---------------------------------------------------------- */
sStatus = s_version( &szVersion, NO_SESS );
printf( "Client libraries version (%s) status = %d\n",
szVersion, sStatus );
/* ----------------------------------------------------------
** Login to Velocis.
** Get and display Server libraries version.
** ---------------------------------------------------------- */
sStatus = s_login( "RDS", "admin", "secret", &hSess );
if ( S_OKAY != sStatus )
{
printf( "Failed to log into server RDS, error: %hd\n", sStatus );
return;
}
s_logout( hSess );
}
Description This function allocates a new environment handle and initializes the
Velocis SQL API. Only one environment handle is used by each
application. Each environment handle can support multiple
connections. The function returns SQL_ERROR if the server does
not have enough memory for the connection handle.
Your application must call SQLAllocEnv before invoking
SQLAllocConnect. Only one call to SQLAllocEnv needs to be
made within a single application.
Description This function allocates and initializes a new SQL statement handle
for the processing of Velocis SQL statements on the specified server.
The function returns SQL_ERROR only when the server does not
have enough memory for the SQL connection handle.
An application may use an unrestricted number of SQL statement
handles, but it is good practice to conserve server memory by
limiting the number of active handles.
Description This function binds a host variable to a result column value. Your
application must call this function before calling SQLFetch or
SQLExtendedFetch to retrieve select statement processing results.
The application can also call SQLBindCol between fetch calls to
rebind a column to another host variable.
After binding the result column values to host variables (when your
application calls SQLFetch or SQLExtendedFetch), the results
obtained are automatically written to the bound host variables. If a
bound variable is too small to contain an entire result column value,
SQLFetch or SQLExtendedFetch writes a truncated value to the
bound variable (buf) of SQLBindCol. The fetch function truncates
the value of buf to (bufLen-1), sets outLen to the true length of the
result, and returns SQL_SUCCESS_WITH_INFO. The offending
columns are those that have outLen greater than or equal to bufLen.
Velocis uses 6-byte database addresses. As in previous versions of
Velocis, you can fetch a rowid-type column by binding the rowid
column to an integer variable. However, to retrieve the entire 6-byte
database address (including the two-byte file number), you must
use a different C bind type, SQL_C_DBADDR. The default bind
type for rowid columns and all other bind types (for example,
SQL_C_CHAR and SQL_C_LONG) returns only the slot
information (the normal row identifier) when performed on a rowid
column. If you need to retrieve the complete address (for instance,
for Core API operations), bind the column to a DB_ADDR-type
variable with the SQL_C_DBADDR bind type. The
SQL_C_DBADDR C type also works with SQLGetData.
The SQLBindCol function supports bookmarks. To bind a
bookmark, specify SQL_C_BOOKMARK in the host variable data
type (ctype) parameter, and specify 0 in the column number (col).
The buffer length parameter (buflen) is ignored for bookmarks. The
buffer parameter (buf) must include an array of longs, with the
number of array elements matching the size of the rowset. After
calling SQLExtendedFetch, this array stores the bookmarks for the
rows in the current rowset.
Description This function cancels the processing of the specified SQL statement.
It has the same effect as the SQL_CLOSE option of the SQLFreeStmt
function. It is typically used with select statements to terminate
processing before reaching the end of the result set.
If you call this function to cancel a statement that still requires data
completion (for instance, while the statement requires data for
SQL_DATA_AT_EXEC parameters), Velocis rolls back the current
transaction only if it is in auto commit mode. If in manual commit
mode (Velocis’s default mode), Velocis simply cancels the statement
and relies on you to roll back if you so choose.
Note: This is not standard ODBC behavior. Velocis does this
because it cannot easily roll back SQL operations to a mark, and
because ODBC does not clearly define how to handle a canceled
operation in manual commit mode (although rolling back would be
the logical handling).
Therefore, if Velocis is in manual commit mode, you cannot simply
re-execute a statement that has been canceled, as ODBC specifies.
Instead, you must first abort or commit the transaction to clear the
canceled state, then re-execute the statement. Thus, in manual
commit mode, Velocis requires you to specify how to handle a
canceled statement (abort or commit) before you can re-execute the
statement. Again, this is a Velocis-specific behavior.
Description This function generates a result set of data describing the c_data
column or group of columns. The data from this result set can then
be retrieved using SQLFetch or SQLExtendedFetch. Search
patterns cannot be used on the names for the table qualifier, table, or
column. The function generates a row for the c_data column itself,
with an additional row for each subcolumn of the c_data column, if
any. The result set contains the following columns:
Description This function obtains information about the specified column from
the result set of the specified select statement. From the attr
parameter, the function determines the attribute for which to return
information. It then obtains the descriptor information and writes it
either to the buf parameter or the descr parameter.
This function only retrieves information for one attribute. Your
application must repeat the call as necessary to retrieve data for all
attributes of interest.
SQL_COLUMN_COUNT
Sets descr to the number of columns in the result set. This value is
also obtained from SQLNumResultCols. The colno argument is
ignored.
SQL_COLUMN_DISPLAY_SIZE
Sets descr to the maximum number of characters needed when the
column value is converted to type SQL_C_CHAR.
SQL_COLUMN_LABEL
Returns in buf the column label or title. If there is no label or title,
the column name is returned.
SQL_COLUMN_LENGTH
Sets descr to the length, in bytes, of the column value for the default
(SQL_C_DEFAULT) elementary data type of the result. This length
is the actual number of bytes that can be copied into the
application’s result column buffer.
SQL_COLUMN_MONEY
Sets descr to FALSE (0). Velocis SQL does not have a money-based
data type.
SQL_COLUMN_NAME
Returns in buf the name of the column. If the column contains an
unaliased expression, the expression text is written.
Note: In Velocis, both SQL_COLUMN_NAME and
SQL_COLUMN_LABEL return the same information. This behavior
is not compliant with ODBC. In ODBC, using
SQL_COLUMN_LABEL returns a heading, or a column name if
there is no heading. Using SQL_COLUMN_NAME in ODBC
always returns the column name, regardless of whether a column
heading exists.
SQL_COLUMN_NULLABLE
Sets descr to the null state of the column. This attribute type
indicates whether the column is "nullable" (that is, can contain a
NULL value). The possible attribute values are SQL_NO_NULLS
(cannot contain nulls), SQL_NULLABLE (can contain nulls), and
SQL_NULLABLE_UNKNOWN (the function cannot determine
whether null values are allowed).
SQL_COLUMN_OWNER_NAME
Returns a blank string. A value for this attribute type cannot be
determined.
SQL_COLUMN_PRECISION
Sets descr to the column precision.
SQL_COLUMN_QUALIFIER_NAME
Returns a blank string. A value cannot be determined for this
attribute type.
SQL_COLUMN_SCALE
Sets descr to the column scale for data types that allow scale to be
specified.
SQL_COLUMN_SEARCHABLE
Determines whether the column can be used for a search. There are
four different levels of searching in descr:
SQL_SEARCHABLE
Column is fully searchable.
SQL_ALL_EXCEPT_LIKE
Column can be used in any where clause comparison except like.
SQL_LIKE_ONLY
Column can only be used in a like comparison.
SQL_UNSEARCHABLE
Column cannot be used in any search.
In Velocis, char and varchar types are SQL_SEARCHABLE, BLOB
types are SQL_UNSEARCHABLE, and all remaining supported
types are SQL_ALL_EXCEPT_LIKE.
SQL_COLUMN_TABLE_NAME
Sets descr to the table name for the column. If the table name cannot
be retrieved, a blank string is returned.
SQL_COLUMN_TYPE
Sets descr to the data type of the result column. Possible data types
are described in Chapter 18.
SQL_COLUMN_TYPE_NAME
Returns in buf the data type for the column result (for example, char,
integer, etc.).
SQL_COLUMN_UNSIGNED
Sets descr to FALSE (0). Velocis SQL does not support unsigned
data types.
SQL_COLUMN_UPDATABLE
Sets descr to an indicator of whether the column’s data type supports
updates and, if the statement accesses a view, whether the view is
updateable. The possible values for this attribute are
SQL_ATTR_READONLY (the column is not updateable),
SQL_ATTR_WRITE (the column is updateable), and
SQL_ATTR_READWRITE_UNKNOWN (the column’s updateable
status is not known).
Parameters hstmt [Input] The handle for the SQL statement that
referencesthe table.
tblname [Input] The name of the database table. If
correlation names have been specified for the tables
listed in the from clause of the referencing select
statement, you must specify the correlation name.
dba [Input] The database address to convert.
rowid [Output] A pointer to the row identifier ("rowid").
Description This function converts the specified database address to the rowid
for a row in the corresponding database table. The function returns
SQL_ERROR if the database address is not valid for the specified
table or the specified table is not referenced in the given SQL
statement.
Note: This function is only needed in applications that call both the
Velocis SQL API and the Velocis Core APIs.
Description This function retrieves the handle that Velocis uses to represent the
specified database. Your application can later use this handle in
calls to the Velocis Core APIs (bypassing Velocis SQL) to access
database information.
Description This function determines the type of SQL statement associated with
the specified statement handle (hstmt). The statement type
indicators that can be returned in the type parameter are listed
below, along with the SQL statement types they represent. See
Chapter 4 of the Velocis Language Guide for definitions of these
statements.
Description This function disconnects the application from the Velocis SQL
support module associated with the specified connection handle
(hdbc). If successful, the function automatically frees all SQL
statement handles allocated for the connection on a successful
SQLDisconnect call. If there are any active transactions (in other
words, transactions that have not yet been committed or rolled
back) at the time of disconnection, SQLDisconnect returns an
appropriate SQL_ERROR code and the connection remains open.
SQL_DRIVER_COMPLETE_REQUIRED
Operates similarly to SQL_DRIVER_COMPLETE
except that any unneeded fields within the dialog
box are deactivated.
Description This ODBC level 1 function connects your application to the Velocis
SQL support module. This function allows your application to
specify any combination of connection parameters (server name,
user name, and password) with the ODBC driver, prompting the
user for any unspecified values. The corresponding non-ODBC
connection function (SQLConnect) must have all parameters
furnished at the same time to perform a connection. Refer to the
Microsoft ODBC SDK Programmer’s Reference for ODBC-specific
details of SQLDriverConnect.
Description This function is called by your application after another Velocis SQL
API function returns the standard code SQL_ERROR or
SQL_SUCCESS_WITH_INFO (described in Chapter 19). The
function examines the standard error/status code and writes both
the standard SAG/ODBC code and the Velocis SQL-specific code
that explains it. If required, it also copies the explanatory message
text to the errMsg parameter.
For each active connection or active SQL statement, the SQL server
maintains only the error/status information associated with the
most recent function call. If your application does not call SQLError
before the next function call for a given connection or statement, the
previous error/status information is lost.
Description This function compiles and executes the specified Velocis SQL
statement. To include embedded parameter references in the SQL
string, call SQLBindParameter as often as needed to assign values
to the parameters in the order of their arrangement in the statement
string. Each parameter reference must be assigned a value before
your application can call SQLExecDirect.
Description This function executes the specified statement, which has already
been prepared by SQLPrepare. Any parameter markers contained
in the statement must have been bound to host program variable
values through prior calls to SQLBindParameter. These values
remain in effect until the statement is completely processed (or a call
to SQLFreeStmt has aborted statement execution). Your application
can then assign new values to the statement parameters and recall
SQLExecute for the new parameter set.
SQL_FETCH_PREV or SQL_FETCH_PRIOR
Fetches the previous result rowset. If the cursor is
positioned after the end of the result set, the result is
the same as SQL_FETCH_LAST.
SQL_FETCH_RELATIVE
Fetches the rowset that is rowNum rows from the
current row position.
Examples:
If rowNum is -10, Velocis fetches the rowset
starting 10 rows before the beginning of the
current rowset. Thus, if the current rowset
starts with row 50, this operation will fetch the
rowset starting at row 40.
If rowNum is 30, Velocis fetches the rowset
starting 30 rows after the start of the current
rowset. Thus, if the current rowset starts at row
50, this operation will fetches the rowset starting
at row 80.
If rowNum is zero, the driver retrieves the
current rowset again.
If the cursor is positioned before the start of the
result set and rowNum is positive, or if the
cursor is positioned after the end of the result
set and rowNum is negative, this operation acts
like SQL_FETCH_ABSOLUTE.
rowNum [Input] The rowset to fetch. This parameter is only
used with static cursors if fetchType is
SQL_FETCH_ABSOLUTE,
SQL_FETCH_RELATIVE, or
SQL_FETCH_BOOKMARK (see above). This
option is not used with forward-only cursors.
actualRows [Output] A pointer to the number of rows fetched.
rowStatArray [Output] A pointer to an array showing the status of
each result set row. Element values are:
SQL_ROW_ADDED
The row was added.
SQL_ROW_DELETED
The row was deleted.
SQL_ROW_ERROR
The row was successfully fetched, but one or more
columns had a truncation error. All other errors
terminate the result set, so no results are retrieved.
SQL_ROW_NOROW
No row was fetched for this row set entry (that is,
Description This ODBC level 2 function extends the basic fetch capabilities
provided by SQLFetch. It implements a forward-only (that is,
nonscrollable), block mode, read-only cursor that allows the
retrieval of multiple select statement result rows using a single RPC.
The maximum number of rows that can be retrieved in a single call
to SQLExtendedFetch (that is, the size of the result set) is specified
in an earlier call to the SQLSetScrollOptions function. The default
number of rows is 1.
The SQLExtendedFetch function automatically writes column
values for each fetched row to host variables bound through prior
calls to SQLBindCol. SQLExtendedFetch returns
SQL_NO_DATA_FOUND when it finds no more rows in the result
set. Refer to the Microsoft ODBC SDK Programmer’s Reference for
ODBC-specific details of SQLExtendedFetch.
For errors encountered during the fetch operation, the function
writes SQL_ROW_ERROR to the rows involved (rowStatArray
parameter). The function returns SQL_SUCCESS_WITH_INFO
when one or more rows in the retrieved result set have a data
truncation error (errCHTRUNC).
If a timeout occurs when SQLExtendedFetch has retrieved at least
one row and tries to fetch another row that is locked, the function
returns SQL_SUCCESS or SQL_SUCCESS_WITH_INFO. It sets
actualRows to the number of rows actually fetched (which is less
than the result set size). On the next call to SQLExtendedFetch, the
first row retrieved is the row for which the timeout has occurred. If
that row is still locked, SQLExtendedFetch returns SQL_ERROR
(errTIMEOUT). The application can call SQLExtendedFetch as
needed until it succeeds in retrieving the locked row.
If static cursors are activated, SQLExtendedFetch fetches any
rowset within the result set. Fetched rows are cached on the client
side for easy re-fetching. Because rows are fetched when requested,
exercise caution with the SQL_FETCH_LAST option, and with the
SQL_FETCH_ABSOLUTE option when it has a negative rowNum
value. Both options require Velocis to fetch the entire result set to
the client side before returning the requested rowset. If the result
set is large, this can take some time. Once cached, however, the
rows can be retrieved quickly without calling the server again.
See your ODBC manual if you require more detail on how
SQLExtendedFetch works with static cursors.
SQLFetch Get the next row from a result set for a select statement
Description This function retrieves the next row of a result for the specified
select statement. If the columns of the result set were already
bound to host variables in calls to SQLBindCol, SQLFetch
automatically writes column values for the fetched row to the host
variables. If the columns are unbound, the application can call
SQLGetData to retrieve the column values for the fetched row. The
SQLFetch function returns SQL_SUCCESS_WITH_INFO if one or
more of the host variables bound to column values are not large
enough to hold entire column values.
Description This ODBC Level 2 function returns information about foreign keys
in the specified tables. It returns a result set based on one of the
following sets of results.
Description This function frees all memory associated with the specified
environment handle. Before calling this function, your application
must call SQLFreeConnect to release all allocated connection
handles. After SQLFreeEnv returns, your application cannot call
any other Velocis SQL functions except SQLAllocEnv.
Description This function ends the processing associated with the specified SQL
statement.
Description This ODBC level 1 function retrieves the current setting for the
specified connection option. The list of valid connection options is
given in the next section. Some options in SQLGetStmtOption can
also be sent to this function. Refer to the Microsoft ODBC SDK
Programmer’s Reference for ODBC-specific details of
SQLGetConnectOption.
Connection You can request the types of connection options (option parameter)
Option Type indicated by the defined constants shown below. Each option
Indicators description outlines the kinds of settings that the option can contain
(data parameter).
SQL_ACCESS_MODE
Retrieves an integer that indicates whether the Velocis connection is
read only or read/write. It returns SQL_MODE_READ_ONLY if
the connection is read only and SQL_MODE_READ_WRITE if the
connection is read/write.
SQL_AUTOCOMMIT
Retrieves a 32-bit integer indicating the transaction commit state.
Possible values are:
SQL_AUTOCOMMIT_OFF
Specifies that the application issue commits. This is the default value.
Note that it is different from the ODBC-specified default. The default
can, however, be changed through the ODBC administrator utility or
in the odbc.ini file.
SQL_AUTOCOMMIT_ON
Specifies that Velocis automatically issue a transaction commit after
each statement.
SQL_LOGIN_TIMEOUT
Retrieves an integer that indicates the time, in seconds, that Velocis
waits for a login request to complete before returning to the
application. The default is 15 seconds.
SQL_OPT_TRACE
Retrieves a 32-bit integer that indicates whether the ODBC Driver
Manager traces ODBC functions. If SQL_OPT_TRACE_ON is the
value, the driver manager writes each ODBC call to a trace file. If
this value is SQL_OPT_TRACE_OFF, the driver manager does not
perform a write for each ODBC call. This option does nothing if the
application is linked directly to Velocis; it only works if the
application is linked to the ODBC library and calls Velocis through
the ODBC Driver Manager. This standard ODBC option is only for
client platforms that have DLL support (such as Windows).
SQL_TXN_ISOLATION
Retrieves a 32-bit integer indicating the transaction isolation mode.
Possible values are:
SQL_TXN_READ_UNCOMMITTED
Indicates the transaction isolation mode is at the lowest level and that
"dirty read" mode is in effect, which allows unlocked reading of data.
SQL_TXN_READ_COMMITTED
Indicates that transaction isolation mode is on and cursor stability
mode, which allows read repeatability, is off. Changes are invisible
until the transaction is committed. Only the current row is locked.
SQL_TXN_REPEATABLE_READ
Indicates that both transaction isolation mode and cursor stability
mode are in effect. Changes are not visible until the transaction is
committed. All accessed rows remain locked until the transaction
ends. This is the highest level of isolation.
SQL_TXN_REPEATABLE_UNCOMMITTED
Indicates the "dirty read mode" is in effect, but cursor stability mode is
enforced inside the transaction.
SQL_OPT_VENDOR
Retrieves a null-terminated string identifying the vendor name
encoded in error messages provided by SQLError. The default
string for this option is "Centura".
Description This function retrieves the current cursor name for the specified
SQL statement. The application can then use this cursor in a call to
SQLExecute to process positioned update and delete statements
using a separate statement handle.
For SQLGetCursorName to operate properly, the Velocis SQL
statement indicated by hstmt must correspond to a select statement
that does not contain a group by or order by clause. The statement
must have a valid cursor name.
If the application has issued a prior call to SQLSetCursorName for
the given statement, SQLGetCursorName writes the same cursor
name. If SQLSetCursorName has not been called,
SQLGetCursorName writes a Velocis-generated cursor name of the
form SQL_CUR_connection_server, resulting from a prior call to
SQLExecute. In this name, connection represents the integer the
server has assigned to the connection and server represents the
integer the server has assigned to the SQL statement handle. An
example of a Velocis-generated cursor name is
SQL_CUR_0005_0003.
data for unbound columns beyond the last bound column. Refer to
the Microsoft ODBC SDK Programmer’s Reference for ODBC-specific
details of SQLGetData.
The SQLGetData function can alternatively be used with
SQLExtendedFetch (with static cursors only) instead of SQLFetch.
To fetch the data for a particular row in a rowset, first retrieve a
rowset (using SQLExtendedFetch), then position to a row within
that rowset (using SQLSetPos). The data can then be retrieved
using SQLGetData. If SQLSetPos is not called, the data for the first
row in the rowset is retrieved.
To retrieve a bookmark, specify SQL_C_BOOKMARK as the host
variable data type (cnvType) of the parameter, and specify 0 as the
column number (colNum). The buffer length parameter (buflen) is
ignored for bookmarks. The bookmark is returned into a four-byte
integer buffer.
Additional fetching information about this function can be seen
through the following example. Suppose the following sequence of
function calls is performed:
SQLGetData(colNum=n)
SQLGetData(colNum=m)
SQLGetData(colNum=n)
The final call to SQLGetData retrieves data from the start of the nth
column. Any offset in the column data due to earlier calls to
SQLGetData for that column is no longer valid. Velocis starts
fetching where it left off, not from the beginning.
Since Velocis uses 6-byte database addresses, a special bind type
(SQL_C_DBADDR) must be used to retrieve the entire 6-byte
address. See SQLBindCol for information about this new bind
type.
With BLOB data types, it is possible to call SQLGetData multiple
times to retrieve all the data in parts. Each call retrieves the number
of bytes specified in outBuffLen into outBuff. The next call retrieves
data starting where the previous call ended. When there are no
more bytes to retrieve, SQLGetData returns
SQL_NO_DATA_FOUND. For types other than
SQL_LONGVARCHAR and SQL_LONGVARBINARY, multiple
calls to SQLGetData return SQL_NO_DATA_FOUND on the
second and all subsequent calls.
Description This ODBC level 1 function retrieves data indicating if Velocis SQL
supports the specified ODBC function. The function writes a single
UWORD variable if function is an SQL_API_* constant.
Alternatively, if function is SQL_API_ALL_FUNCTIONS, the
function writes a 100-element UWORD array. Your application can
index each array element by the appropriate SQL_API_* constant to
determine if Velocis SQL supports a given function. Refer to the
Microsoft ODBC SDK Programmer’s Reference for more details of
SQLGetFunctions.
SQLGetStmtOption Get the current setting for a Velocis SQL statement option
Description This ODBC level 1 function retrieves the current setting of the
specified SQL statement option. Refer to the Microsoft ODBC SDK
Programmer’s Reference for details about the use of
SQLGetStmtOption.
SQL_CURSOR_TYPE
Specifies the type of cursor to use for the SQL statement. Velocis
supports two settings for this option:
SQL_CURSOR_FORWARD_ONLY (forward-only cursors, the
default) and SQL_CURSOR_STATIC (for static cursors).
SQL_FETCH_CHUNKSIZE
Sets size for a chunk of rows. The chunk size (default 100)
determines the maximum number of rows fetched from the server,
per network call, on a FETCH_LAST or a high absolute fetch. This
value is used to optimize data retrieval by reducing the number of
network calls necessary to retrieve the requested rows. It is only
used when more than a single rowset must be fetched from the
server to meet the request. Therefore, SQL_FETCH_LAST, or
SQL_FETCH_ABSOLUTE with a rownum value much higher than
the highest row currently cached, will use this value.
SQL_FETCH_NEXT, which only fetches the next rowset, will not
use the value.
Examples:
Suppose no rows have been fetched, the rowset size is 10, the chunk
size is 100, and the user requests the rowset starting at row 50. Velocis
fetches into the cache all rows between 1 and 59 (the last row in the
requested rowset) in one call, as opposed to making 6 calls, fetching 10
rows (the rowset size) each time.
As another example, suppose the same user requested the last rowset
instead, and the total result set size is 200. In this case, the user wants
the rowset starting at row 191 and ending at 200 (the last row). Velocis
will fetch the intervening rows into the cache first, so it will make three
network calls, the first to fetch rows 1-100, the next to fetch 101-200,
and the third to confirm there are no more rows to fetch. If the chunk
size were instead 50, then five calls would be necessary to fetch the
same data.
The chunk size sets the maximum number of rows that Velocis fetches
in this manner. If the rowset size is larger than this value, Velocis
fetches the number of rows equal to the rowset size, regardless of the
chunk size. Although a large chunk size causes fewer network calls to
fetch result data, it also results in more client side memory usage.
Velocis also uses the chunk size to determine the number of rows
kept in memory by the client side cache. Velocis will keep in
memory the quantity of rows equal to the chunk size, the rowset
size, or 100, whichever is largest.
SQL_FETCH_MAXBLOB
Sets the maximum number of bytes to return from an unbound
BLOB. (If a BLOB field is bound, Velocis ignores this setting.) By
using this Velocis-specific option, you can retrieve bytes (using
SQLGetData) from an unbound BLOB without being required to re-
execute the query. The default is zero, which means that Velocis
does not return any bytes from BLOBs that are not bound. All
unbound BLOBs in the query use this value; you are not allowed to
set different values for different BLOBs in the same query.
When using static cursors, Velocis normally restricts you to fetching
only bound BLOBs. When you use static cursors, Velocis, by
default, fetches BLOB field data only if the BLOB field has been
bound. If no BLOB data is fetched, then the BLOB data from that
field cannot be accessed until you re-execute the query.
SQL_FETCH_USECHUNK
Determines whether to do "fetch ahead" operations. If this option is
set to 1, Velocis uses the chunk size (set with
SQL_FETCH_CHUNKSIZE) as the maximum number of rows to
retrieve, even if a smaller fetch could retrieve the desired rows. If
this option is set to 0, chunks are only used in fetching as outlined in
the SQL_FETCH_CHUNKSIZE option above.
Normally, an SQL_FETCH_NEXT operation fetches from the server
only the next rowset. Therefore, repeatedly calling FETCH_NEXT
with a small rowset size can generate needless network traffic.
However, with SQL_FETCH_USECHUNK set, using FETCH_NEXT
once returns from the server a quantity of rows less than or equal to
the chunk size (that is, a chunk of rows). The remaining calls using
FETCH_NEXT retrieve data from the client side cache, rather than
generating more network traffic. This can significantly increase
performance.
Example:
The user has a rowset size of 10, a chunk size of 100, and is fetching the
data using FETCH_NEXT. Normally, this action would generate a
network call with each call to SQLExtendedFetch; each call would
return 10 rows from the server. However, with the
SQL_FETCH_USECHUNK option set, the first call fetches a chunk of
rows (100) from the server. The next nine FETCH_NEXT calls will
fetch the data not from the server, but from the client side cache, which
is much faster. Since the rows will probably be stored in memory,
performance will be further enhanced by eliminating the need to
access them from the client-side disk cache.
SQLGetTypeInfo Get the Velocis SQL characteristics for ODBC data types
Description This ODBC level 1 function retrieves a result set describing Velocis
SQL-specific characteristics of the specified ODBC data type(s). If
the sqlType parameter corresponds to one data type, the result set
consists of a single row. If the function retrieves no rows, the
specified type is not supported by Velocis. If the value of sqlType is
SQL_ALL_TYPES, the function retrieves one row for each
supported type. Refer to the Microsoft ODBC SDK Programmer’s
Reference for details of SQLGetTypeInfo and a description of the
result set.
Parameters thisHdbc [Input] The SQL connection handle for the session
within which this function is being called.
thatHdbc [Input] The SQL connection handle of the session
with the statement to be killed.
Example
/* Separate thread function */
void KillThread(void *pHdbc)
{
RETCODE stat;
HDBC thisHdbc, thatHdbc;
WaitForButtonClick();
SQLAllocConnect(henv, &thisHdbc);
stat = SQLConnect(thisHdbc, server, SQL_NTS, user,
SQL_NTS, password, SQL_NTS);
if ( stat == SQL_SUCCESS ) {
SQLKill(thisHdbc, thatHdbc);
SQLDisconnect(thisHdbc);
SQLFreeConnect(thisHdbc);
}
}
Description This function retrieves the number of columns in the result set for
the specified select statement. Your application must call
SQLPrepare (or SQLExecDirect) before issuing a call to
SQLNumResultCols.
Description This function compiles the specified Velocis SQL statement, which is
subsequently executed in a call to SQLExecute. If SQLPrepare finds
errors in the statement that it is processing, it returns SQL_ERROR.
The Velocis SQL statement processed by SQLPrepare can include
embedded host variable references or parameter markers. Each
parameter marker must be encoded as a literal "?". After
SQLPrepare finishes, your application can change a parameter
marker before calling SQLExecute by simply changing the value of
the host variables. The application can also change the host variable
for a parameter by calling SQLBindParameter before the next
SQLExecute call.
Description This ODBC Level 2 function returns a result set for the table
specified in szTabName that names the primary key columns of that
table. One row is returned for each column that is part of the
primary key. This function only returns information for one table at
a time, and no wildcards are allowed in szTabName. The function
only returns primary key information, not unique (non-primary)
key information. Refer to the Microsoft ODBC SDK Programmer’s
Reference for ODBC-specific operational details about this function.
Description This ODBC level 2 function produces a result set describing the
stored procedures available on the Velocis server. The function
provides all stored procedure names that match the specified search
pattern (procName) in a result set, with one row for each stored
procedure and columns ordered by PROCEDURE_NAME (see the
table below). If procName is NULL, SQLProcedures provides the
names of all stored procedures. Your application can then retrieve
the result set by calling SQLFetch or SQLExtendedFetch. For
details of SQLProcedures, refer to the Microsoft ODBC SDK
Programmer’s Reference.
Parameters hstmt [Input] The handle for the SQL statement that
references the table.
tblname [Input] The table name. If correlation names have
been used for the tables listed in the from clause of
the referencing select statement, you must specify
the correlation name.
dba [Output] A pointer to the database address.
Description This function retrieves the database address of the current row of
the specified table, if the table is referenced in the specified SQL
statement. If the statement is insert, it must have been executed
prior to your application’s call to SQLRowDba. If the statement is
select, update, or delete, it must have been positioned before your
application calls SQLRowDba. If the statement is select, it must
also not contain an order by or a group by clause. The function
returns SQL_ERROR if the given SQL statement does not reference
the specified table.
Parameters hstmt [Input] The handle for the SQL statement that
references the table.
tblname [Input] The table name. If correlation names were
used for the tables listed in the from clause of the
referencing select statement, you must specify the
correlation name.
pRowid [Output] A pointer to the row identifier.
Description This function retrieves the identifier of the current row from the
given table being accessed by the specified SQL statement. If the
statement is insert, it must have been executed prior to your
application’s call to SQLRowId. If the statement is select, update,
or delete, it must have been positioned before your application calls
SQLRowId. If the statement is select, it must also not contain an
order by or a group by clause. The function returns SQL_ERROR if
the specified table is not referenced in the SQL statement.
This function is useful when using primary keys of the rowid type.
For example, after your application executes an insert statement to
insert a row in a table with a primary key of the rowid type, a call to
SQLRowId will retrieve the identifier of the inserted row. Your
application can then specify this row identifier in any insert
statements using foreign keys that reference the table containing the
row.
SQLRowIdToDba Convert the identifier of table row to the database address of the
row
Parameters hstmt [Input] The handle for the SQL statement that
references the table.
tblname [Input] The table name. If correlation names have
been used for the tables listed in the from clause of
the referencing select statement, you must specify
the correlation name.
rowid [Input] A pointer to the row identifier.
dba [Output] A pointer to the database address.
Description This function converts a row identifier to the database address for
the row. If the statement that references the specified table is insert,
it must have been executed prior to your application’s call to
SQLRowIdToDba. If the statement is select, update, or delete, it
must have been positioned before your application calls
SQLRowIdToDba. The function returns SQL_ERROR if the
database address is not valid for the specified table or if the
specified table is not referenced in the given SQL statement.
Description This function retrieves the Velocis session handle associated with
the specified server connection handle (hdbc). Your application
needs the session handle to call extension modules located on the
server side of Velocis. The application also uses the session handle
in calling Velocis Runtime API functions.
The session ID is used with the em_call function to call a Velocis
extension module from a client application.
Description This function sets the specified c_data column to the indicated
values. The application uses SQLAllocCData to allocate hCData, a
parameter that contains information about the c_data column, such
as member column sizes and types. Use this function to set the data
values inside the handle. See SQLAllocCData for more details.
Description This ODBC level 1 function sets the specified connection option to a
new value (toValue). For details of SQLSetConnectOption, refer to
the Microsoft ODBC SDK Programmer’s Reference.
Description This function sets a user-defined cursor name (cursor) for the
specified SQL statement. The application can then use the cursor to
process positioned update and delete statements in calls to
SQLExecute with a separate SQL statement handle.
For SQLSetCursorName to operate properly, the Velocis SQL
statement indicated by hstmt must correspond to a select statement
that does not contain a group by or order by clause.
Description This function sets the value of a host variable reference or parameter
marker embedded in the hstmt statement. While SQLSetParam is
left in Velocis for backward compatibility, new users should use the
SQLBindParameter function.
Description This ODBC Level 2 function positions the current row within a
rowset. Once positioned, SQLGetData can be called on the current
row to retrieve its data, thus allowing SQLGetData functionality
within a multi-row rowset. Before calling SQLSetPos, the user must
set the statement to use static cursors, execute a query, and use
SQLExtendedFetch (not SQLFetch) to fetch at least one rowset. The
function returns an error if row is less than 1 or greater than the
number of rows in the current rowset. The SQLSetPos function also
returns an error if the cursor is positioned either before the
beginning or after the end of the result set. After calling
SQLExtendedFetch, the current row is set to the first row in the
current rowset.
Description This ODBC level 2 function sets scroll options for select statements
with the specified handle. While this function is left in Velocis for
backward compatibility, it has been superseded by the
SQLSetStmtOption function.
The SQLSetScrollOptions function supports both forward-only (the
default) and static cursors. You can change the cursor type by using
the SQL_SCROLL_FORWARD_ONLY and SQL_SCROLL_STATIC
options, respectively, in the SQLSetStmtOption function.
Changing the cursor type requires a call to this function before the
statement has been prepared. In Velocis 2.0 and earlier, this
function could be called anytime, as it set the rowset size only.
However, the cursor type can only be set before the statement is
prepared, hence this new requirement.
Description This ODBC level 1 function sets the value of the option associated
with the specified statement. Refer to the Microsoft ODBC SDK
Programmer’s Reference for details about the use of
SQLSetStmtOption.
Normally, Velocis returns the data type of rowid columns as
SQL_INTEGER (from functions such as SQLDescribeCol,
SQLColAttributes, and SQLColumns). This is because the ODBC
specification does not clearly specify how a third-party ODBC
application handles a driver-specific type in a data source.
However, if an application is directly linked with Velocis, Velocis
can return the rowid column’s type as SQL_ROWID. To activate
this feature, call SQLSetStmtOption with the
SQL_ACTUAL_TYPES option and an option setting parameter of
TRUE. To turn off this feature, repeat that function call, but instead
use an option setting parameter of FALSE (the default setting). Do
not set this option if you are connecting to Velocis through ODBC.
SQLShowPlan Show the execution plan chosen by the optimizer for a query
Description This function sets up a result set containing information about the
execution plan the optimizer has picked for the query specified by
hQuery. There is one row for each table in hQuery, specifying the
method Velocis uses to access the data. The columns of the result
set are shown below.
SQLSpecialColumns Prepare a result set from columns that uniquely identify and access
rows
SQL_SCOPE_SESSION
Specifies that column values uniquely identifying
each row be valid for the entire session.
nullable [Input] The null state indicator for a column. If the
column cannot contain nulls, specify
SQL_NO_NULLS; otherwise, specify
SQL_NULLABLE.
Description This ODBC level 1 function sets up a result set for the specified SQL
statement. The function forms the set from table columns that
uniquely identify and access rows in the same table. The table to be
processed by SQLSpecialColumns is specified through the
database name (tabQual or tabOwner) and the table name (tabName).
Refer to the Microsoft ODBC SDK Programmer’s Reference for ODBC-
specific operational details about SQLSpecialColumns.
The function places in the result set all special columns that match
the specified search pattern for all three parameters. If
SQLSpecialColumns finds no columns that can be used to uniquely
identify table rows, it returns SQL_NO_DATA_FOUND.
Each row of the set contains information about one of the columns
(see the table below). Your application can obtain these rows by
calling SQLFetch or SQLExtendedFetch.
Result set rows have a scope that is at least as restrictive as that
specified in the scope parameter. As defined for Velocis SQL
applications, all special columns support a scope of
SQL_SCOPE_CURROW. Sometimes the actual scope may be larger,
but SQLSpecialColumns cannot determine this because the Velocis
SQL user can change operational characteristics dynamically. For
example, if cursor stability mode (read repeatability) is turned on,
SQL_SCOPE_TRANSACTION is the type of scope used. If the
database has been opened in exclusive access mode, the type of
scope is SQL_SCOPE_SESSION.
SQLStatistics Prepare a result set containing statistics about a table and its indexes
Description This ODBC level 1 function produces a result set for the specified
SQL statement. The function forms the set from the tables contained
in the specified database. Refer to the Microsoft ODBC SDK
Programmer’s Reference for ODBC-specific operational details about
SQLTables.
The SQLTables function associates tables with the tabQual and
tabName parameters, each of which can contain a search pattern.
The function places in the result set all tables that match the
specified search pattern for these parameters. If SQLTables finds
no tables, it returns SQL_NO_DATA_FOUND.
In the result set, the tables are ordered by TABLE_TYPE,
TABLE_QUALIFIER, and TABLE_NAME. Each row of the set
contains information about one of the tables (see the table below).
Your application can obtain these rows by calling SQLFetch or
SQLExtendedFetch.
Parameters hMod [Input] The handle for the UDP module defining
the trigger function.
hSess [Input] The handle for the session with which the
trigger function is associated.
name [Input] The name of the transaction trigger function.
Trigger [Input] A pointer to the trigger function. The
function must have this prototype:
void REXTERNAL TransactionTriggerFunction
(short OperationTypeIndicator,
char *TransactionIdentifierString,
char *TriggerName, void *TriggerContextPointer)
ptr [Input] A pointer to a user-maintained context
passed to the trigger function. It can be set to
NULL.
mode [Input] The indicator for the calling frequency
mode. To have the trigger called any time commit
or rollback occurs in the session, specify
SYS_COMMIT_EVERY. To have it called only once,
when the next transaction commit or rollback
occurs, specify SYS_COMMIT_ONCE.
Example For the sample function definition below, the trigger function is
called every time a transaction event occurs. In a separate
transaction log database, this trigger writes all transaction events
occurring during the user’s connections. The transaction trigger has
its own connection for this database, so commits to the log database
will not be recorded in the log database.
If type is SYS_MARK, or if type is SYS_ROLLBACK to a mark, the
function saves the action that has occurred in the trigger’s memory
context for later addition into the transaction log database.
If type is SYS_COMMIT, or if type is SYS_ROLLBACK and no marks
are present, the transaction trigger actually puts the actions that
have occurred into the transaction log database. It first loops
through the actions that are stored in its private context, adding
each of them as a new record in the log, then it adds the commit or
rollback action as a log entry. Then this information is committed to
the transaction log database.
if ( type == SYS_REMOVE ) {
rm_freeTagMemory (ctx->mTag, 1);
ctx->mTag = NULL;
SQLFreeStmt(ctx->hStmt, SQL_DROP);
SQLDisconnect(ctx->hDbc);
SQLFreeConnect(ctx->hDbc);
SQLFreeEnv(ctx->hEnv);
rm_freeMemory(ctx, 0);
} else {
if (type == SYS_MARK ||
(type == SYS_ROLLBACK && IsAMark(ctx->act_list, label))) {
/* Record the event, but don’t commit it yet
** It will be committed to the log when a commit
** or rollback occurs...*/
lap = rm_getMemory(sizeof(LOG_ACTION), ctx->mTag);
if ( lap ) {
lap->type = type;
lap->next = ctx->act_list;
lap->prev = NULL;
if (ctx->act_list) ctx->act_list->prev = lap;
lap->label = label ? rm_Strdup(label, ctx->mTag) : NULL;
ctx->act_list = lap;
}
} else if (type == SYS_COMMIT || type == SYS_ROLLBACK) {
if (ctx->act_list) { /* Process stored actions (if any) */
/* Find first event (it’s last in the list) */
for (lap = ctx->act_list; lap->next; lap = lap->next) ;
for (lgp = lap; lgp; lgp = lgp->prev) {
switch (lgp->type) {
case SYS_MARK:
strcpy(ctx->action, "mark"); break;
case SYS_ROLLBACK:
strcpy(ctx->action, "rollback to mk"); break;
}
strcpy(ctx->label, lgp->label);
SQLExecute(ctx->hStmt);
}
ctx->act_list = NULL;
rm_freeTagMemory(ctx->mTag, 0);
}
switch (type) {
case SYS_COMMIT: strcpy(ctx->action, "commit"); break;
case SYS_ROLLBACK: strcpy(ctx->action, "rollback"); break;
}
strcpy(ctx->label, label);
SQLExecute(ctx->hStmt);
SQLTransact(ctx->hEnv, ctx->hDbc, SQL_COMMIT);
}
}
return;
}
The mark finding function (IsAMark) and the action and context
structures (log_action and log_ctx, respectively) are defined in the
following example.
/* ====================================================================
Invalid data type conversion
*/
long REXTERNAL BadConvert(HENV henv, HDBC hdbc, HSTMT hstmt, long code)
{
/* My error message is better */
printf("**** A type conversion specified in SQLBindCol or "
"SQLBindParameter call is not valid.\n");
return code;
}
...
Parameters hSys [Input] The handle for the Velocis SQL support module.
tblname [Input] The name of the database table. This name must
be the correlation name, if correlation names have been
specified for the tables listed in the from clause of the
referencing select statement.
dba [Input] The database address to convert.
pRowID [Output] A pointer to the row identifier.
Description This function is called from a server-side UDF module to convert the
specified database address to the identifier for a row in the
corresponding database table. The function returns SQL_ERROR if
the database address is not valid for the specified table, or if the
specified table is not referenced in the SQL statement that
corresponds to the handle for the Velocis SQL support module.
Parameters hSys [Input] The handle for the Velocis SQL support module.
dbname [Input] The database name. Your application must have
already opened the database during server connection,
either implicitly or explicitly (for example, using the
open statement).
phDb [Output] A pointer to the database handle.
Parameters hSys [Input] The handle for the Velocis SQL support module.
pStype [Output] A pointer to the statement type, defined as a
manifest constant declared in the standard Velocis SQL
header file sqlrds.h. Possible values are:
sqlDELETE Deletes a row or rows from a table.
sqlINSERT Inserts a row into a table.
sqlSELECT Implements a select statement.
sqlUPDATE Implements an update statement.
Parameters hSys [Input] The handle for the Velocis SQL support module.
pudftag [Output] A pointer to the memory allocation tag.
Parameters hSys [Input] The handle for the Velocis SQL support module.
tblname [Input] The table name. This name must be the
correlation name, if correlation names have been
specified for the tables listed in the from clause of the
referencing select statement.
dbap [Output] A pointer to the database address of the current
row.
Description This function retrieves the database address of the current row of a
table, if the table is referenced in the SQL statement specified by the
handle for the Velocis SQL support module. The function returns
SQL_ERROR if the SQL statement does not reference the specified
table.
Parameters hSys [Input] The handle for the Velocis SQL support module.
tblname [Input] The table name. This name must be the
correlation name, if correlation names have been
specified for the tables listed in the from clause of the
referencing select statement.
pRowid [Output] A pointer to the row identifier.
Description This function retrieves the identifier of the current row from the
given table, which is accessed by the SQL statement associated with
the handle for the Velocis SQL support module. It is called from a
server-side UDF module. The function returns SQL_ERROR if the
specified table is not referenced in the SQL statement.
This function is useful when using primary keys of the rowid type.
For example, after your application executes an insert statement to
insert a row in a table with a primary key of the rowid type, a call to
SQLRowId will retrieve the identifier of the inserted row. Your
application can then specify this row identifier in any insert
statement using foreign keys that reference the table containing the
row.
SYSRowIdToDba Convert the identifier of a table row to the database address of the
row
Parameters hSys [Input] The handle for the Velocis SQL support module.
tblname [Input] The table name. This name must be the
correlation name, if correlation names have been
specified for the tables listed in the from clause of the
referencing select statement.
rowid [Input] A pointer to the row identifier.
dbap [Output] A pointer to the database address.
Parameters hSys [Input] The handle for the Velocis SQL support module.
hSess [Output] A pointer to the session handle corresponding
to the server connection.
Syntax short SYSValAdd (HSYS hSys, const VALUE *lv, const VALUE *rv,
VALUE *result)
Parameters hSys [Input] The handle for the Velocis SQL support module.
lv [Input] A pointer to the left operand. This parameter
must contain a valid numeric SQL value. Possible value
types are SQL_SMALLINT, SQL_INTEGER, SQL_REAL,
SQL_FLOAT, SQL_DECIMAL, and SQL_DOUBLE.
rv [Input] A pointer to the right operand. This parameter
must also contain a valid numeric SQL value, as
described for the lv parameter.
result [Output] A pointer to the result of the addition.
Description This function is called from a server-side UDF module to add two
numeric SQL values (lv + rv). The function uses mixed-mode
arithmetic following standard Velocis SQL rules.
Note: Velocis defines the SYSVal* functions for use with scalar and
aggregate UDFs that might need to perform calculations on mixed-
mode numeric values.
Parameters hSys [Input] The handle for the Velocis SQL support module.
lv [Input/Output] A pointer to the location of the SQL
value. This parameter must contain a valid numeric SQL
value. Possible value types are SQL_SMALLINT,
SQL_INTEGER, SQL_REAL, SQL_FLOAT,
SQL_DECIMAL, and SQL_DOUBLE.
Description This function is called from a server-side UDF module to change the
sign of the specified numeric SQL value. The function uses mixed-
mode arithmetic following standard Velocis SQL rules.
Note: Velocis defines the SYSVal* functions for use with scalar and
aggregate UDFs that might need to perform calculations on mixed-
mode numeric values.
Parameters hSys [Input] The handle for the Velocis SQL support module.
lv [Input] A pointer to the left numeric value. This
parameter must contain a valid numeric SQL value.
Possible value types are SQL_SMALLINT,
SQL_INTEGER, SQL_REAL, SQL_FLOAT,
SQL_DECIMAL, and SQL_DOUBLE.
rv [Input] A pointer to the right numeric value. This
parameter must also contain a valid numeric SQL value,
as described for the lv parameter.
Note: Velocis defines the SYSVal* functions for use with scalar and
aggregate UDFs that might need to perform calculations on mixed-
mode numeric values.
Parameters hSys [Input] The handle for the Velocis SQL support module.
rtype [Input] The data type. This parameter must contain a
valid SQL data type. These are SQL_SMALLINT,
SQL_INTEGER, SQL_REAL, SQL_FLOAT,
SQL_DECIMAL, and SQL_DOUBLE.
lv [Input/Output] A pointer to the location of the numeric
value.
Note: Velocis defines the SYSVal* functions for use with scalar and
aggregate UDFs that might need to perform calculations on mixed-
mode numeric values.
Syntax short SYSValDiv (HSYS hSys, const VALUE *lv, const VALUE *rv,
VALUE *result)
Parameters hSys [Input] The handle for the Velocis SQL support module.
lv [Input] A pointer to the left value (numerator). This
parameter must contain a value with a valid SQL data
type. Possible value types are SQL_SMALLINT,
SQL_INTEGER, SQL_REAL, SQL_FLOAT,
SQL_DECIMAL, and SQL_DOUBLE.
rv [Input] A pointer to the right value (denominator). This
parameter must also contain a value with a valid SQL
data type, as defined for the lv parameter.
result [Output] A pointer to the result of the division.
Description This function is called from a server-side UDF module to divide one
numeric SQL value by another (lv / rv). The function uses mixed-
mode arithmetic following standard Velocis SQL rules.
Note: Velocis defines the SYSVal* functions for use with scalar and
aggregate UDFs that might need to perform calculations on mixed-
mode numeric values.
Syntax short SYSValMult (HSYS hSys, const VALUE *lv, const VALUE *rv,
VALUE *result)
Parameters hSys [Input] The handle for the Velocis SQL support module.
lv [Input] A pointer to the left value. This parameter must
contain a value with a valid SQL data type. Possible
value types are SQL_SMALLINT, SQL_INTEGER,
SQL_REAL, SQL_FLOAT, SQL_DECIMAL, and
SQL_DOUBLE.
rv [Input] A pointer to the right value. This parameter
must also contain a value with a valid SQL data type, as
defined for the lv parameter.
result [Output] A pointer to the result of the multiplication.
Note: Velocis defines the SYSVal* functions for use with scalar and
aggregate UDFs that might need to perform calculations on mixed-
mode numeric values.
Syntax short SYSValSub (HSYS hSys, const VALUE *lv, const VALUE *rv,
VALUE *result)
Parameters hSys [Input] The handle for the Velocis SQL support module.
lv [Input] A pointer to the left value. This parameter must
contain a value with a valid SQL data type. Possible
value types are SQL_SMALLINT, SQL_INTEGER,
SQL_REAL, SQL_FLOAT, SQL_DECIMAL, and
SQL_DOUBLE.
rv [Input] A pointer to the right value. This parameter
must also contain a value with a valid SQL data type, as
defined for the lv parameter.
result [Output] A pointer to the result of the subtraction.
Note: Velocis defines the SYSVal* functions for use with scalar and
aggregate UDFs that might need to perform calculations on mixed-
mode numeric values.
Parameters hSys [Input] The system handle used by the SQL support
module to identify and maintain the context of the
executing statement.
noargs [Input] The number of parameters in the UDF.
args [Input] A pointer to an array of VALUE structures
containing the UDF parameters.
result [Output] A pointer to a VALUE structure
containing the result of the type checking operation.
The result is either a detailed error message or one
of the Velocis SQL data types listed in Chapter 18.
len [Output] A pointer to the length, in bytes, of the
result information. If there are no UDF parameters,
this parameter is ignored.
Example
short REXTERNAL CntCheck (
HSYS hSys, /* in: system handle */
short noargs, /* in: number of arguments to function */
const VALUE *args, /* in: array of arguments */
VALUE *result, /* out: result value */
short *len) /* out: max length result string */
{
short status = SQL_SUCCESS;
UNREF_PARM(hSys)
UNREF_PARM(args)
UNREF_PARM(len);
if (noargs != 1) {
result->type = SQL_CHAR;
result->vt.cv = "only 1 argument expression is allowed";
status = SQL_ERROR;
}
else
result->type = SQL_INTEGER;
return status;
}
Parameters hSys [Input] The system handle used by the SQL support
module to identify and maintain the context of the
executing statement.
ctxp [Input] A pointer to the Velocis SQL statement
context pointer.
UNREF_PARM(hSys)
rm_freeMemory(cnt, cnt->mTag);
*cxtp = NULL;
}
Description This function describes the entry point functions for a UDF module.
It must be included (exactly as named) in each UDF module DLL.
When you compile the first Velocis SQL statement referencing one
of the UDF module functions, the SQL support module calls
udfDescribeFcns. The function returns in UDFLoadTable a pointer
to a function description table containing all entry point
information. In addition, the function can return an optional
module description string to be displayed on the Velocis system
console indicating the UDF module DLL has been loaded.
The UDF load table must specify the name of the UDF and the
address of at least two functions, udfFunc and udfCheck. In
addition, the UDF load table entry can optionally contain the
addresses of the udfInit and udfCleanup functions. For an
aggregate UDF, the table entry must include the address of the
udfReset function.
/*===============================================================
User function description, called when statement is prepared
===============================================================*/
void REXTERNAL udfDescribeFcns (
unsigned short *NumFcns, /* out: num. of functions in module */
PUDFLOADTABLE *UDFLoadTable, /* out: points to UdfTable above */
char **fcn_descr) /* out: optional description string */
{
*NumFcns = RLEN(UdfTable);
*UDFLoadTable = UdfTable;
*fcn_descr = "Sample of SQL user-defined functions";
}
Syntax short REXTERNAL udfFunc (HSYS hSys, void **ctxp, short noargs,
const VALUE *args, VALUE *result)
Parameters hSys [Input] The system handle used by the SQL support
module to identify and maintain the context of the
executing statement.
ctxp [Input] A pointer to the Velocis SQL statement
context pointer.
noargs [Input] The number of parameters in the UDF.
args [Input] A pointer to an array of VALUE structures
containing the UDF parameters.
result [Output] A pointer to a VALUE structure
containing its processing result.
Description This function performs the actual processing for a particular UDF.
The actual function name can be any valid C function name and
must be assigned to the udfFunc entry in the UDF load table
returned by the udfDescribeFcns function.
If the function succeeds, it returns SQL_SUCCESS and puts the
result into the result parameter. Even if the UDF is an aggregate
function, your udfFunc function should always return a running
result every time it is called, because the UDF cannot determine
which call will be the final one of the aggregate calculation. If the
function fails, it should return SQL_ERROR and put a descriptive
error string into the result parameter.
When a scalar UDF is referenced in a where clause, you need to be
sure to check for NULL arguments (a NULL argument will have
type SQL_NULL) and return SQL_NULL as the result type. This is
because the SQL query processing will pre-evaluate expressions
(that is, before all column values have been read) to avoid reading
unnecessary rows. NULLs are passed for column values that have
not yet been read.
The Example section below illustrates an example count aggregate
function.
UNREF_PARM(hSys)
UNREF_PARM(noargs)
result->type = SQL_INTEGER;
if (args[0].type != SQL_NULL)
result->vt.lv = ++cnt->count;
else
result->vt.lv = cnt->count;
return SQL_SUCCESS;
}
Parameters hSys [Input] The system handle used by the SQL support
module to identify and maintain the context of the
executing statement.
ctxp [Input] A pointer to the statement context pointer
associated with the system handle.
Example
short REXTERNAL CntInit (
HSYS hSys, /* in: system handle */
void **cxtp) /* in: statement context pointer */
{
COUNT_CTX *cnt;
RM_MEMTAG mTag;
SYSMemoryTag(hSys, &mTag);
cnt = *cxtp = rm_getMemory(sizeof(COUNT_CTX), mTag);
cnt->mTag = mTag;
cnt->count = 0L;
return SQL_SUCCESS;
}
typedef struct {
RM_MEMTAG mTag;
long count;
} COUNT_CTX;
udfReset Reset the running values for the last aggregate function
Parameters hSys [Input] The system handle used by the SQL support
module to identify and maintain the context of the
executing statement.
ctxp [Input] A pointer to the statement context pointer.
Description This function is called by Velocis SQL for an aggregate UDF to reset
the running values for the current aggregate when the grouping
value changes. The actual function name can be any valid C
function name and must be assigned to the udfReset entry in the
UDF load table.
Example
short REXTERNAL CntReset (
HSYS hSys, /* in: system handle */
void **cxtp) /* in: statement context pointer */
{
COUNT_CTX *cnt = *cxtp;
UNREF_PARM(hSys)
cnt->count = 0L;
return SQL_SUCCESS;
}
Example
short REXTERNAL timsCheck (
short noargs, /* in: number of arguments passed */
const short *types, /* in: type of each argmt, types[noargs-1] */
VALUE *err) /* out: container for error messages */
{
short arg;
err->type = SQL_CHAR;
err->vt.cv = "tims_data requires char arguments only";
Description This function is called by Velocis SQL when the execute statement is
closed for the UDP module. The actual function name can be any
valid C function name and must be assigned to the udpCleanup
entry in the UDP load table. It cleans up by closing and freeing
statement handles, terminating connections, dropping temporary
tables, etc. It also allows you to free any memory allocated in the
initial call to your udpInit function, or any memory allocated
during processing.
Example
void REXTERNAL timsCleanup (
void **ctxp, /* in: statement udp_ctx pointer */
RM_MEMTAG mTag) /* memory tag for rm_ memory calls */
{
UDP_CTX *ctx = *ctxp;
SQLFreeStmt(ctx->hStmt, SQL_CLOSE);
SQLExecDirect(ctx->hStmt, "drop table timstab", SQL_NTS);
SQLFreeStmt(ctx->hStmt, SQL_DROP);
SQLDisconnect(ctx->hDbc);
SQLFreeConnect(ctx->hDbc);
SQLFreeEnv(ctx->hEnv);
d_close(ctx->hDb);
d_closetask(ctx->hSess);
rm_freeMemory(ctx, mTag);
return;
}
Description This function describes all of the UDPs and their function entry
points for a UDP module. You must include it (exactly as named) in
each of your UDP modules.
When you compile the first SQL statement referencing the UDP,
Velocis SQL calls udpDescribeFcns. This function must return the
number of UDPs contained in the module and the function
description table containing all entry point information. In addition,
the function can return an optional module description string to be
displayed on the Velocis system console indicating the UDP DLL
has been loaded.
Each entry in the UDP load table array must specify the name of a
UDP and the addresses of up to five processing functions that
implement that UDP, including udpCheck, udpCleanup,
udpExecute, udpInit, and udpMoreResults. Each UDP must at
least include a udpExecute function. The other processing functions
are optional.
Example
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
/* ----------------------------------------------------------
List of functions in module, called when module is loaded
-------------------------------------------------------------*/
Description This function is called by Velocis SQL to obtain the first result set
from the UDP. It is invoked when SQLExecute processes the
execute statement for the named UDP. The actual function name
can be any valid C function name and must be assigned to the
udpExecute entry in the UDP load table.
Your udpExecute function can be defined to perform a variety of
tasks, such as SQL commands, runtime operations, administrative
functions, etc. When processing is complete, if the procedure
returns a result set, your function will need to execute a select
statement and return the handle of the select statement in phStmt so
that ensuing calls to SQLFetch or SQLExtendFetch can retrieve the
results.
If an error occurs, the function will need to return SQL_ERROR and
an error string in the err parameter. Otherwise, the function should
return SQL_SUCCESS.
The statement context pointer, ctxp, points to a pointer variable that
is maintained in the SQL statement context. This pointer allows you
to allocate and store UDP-specific context information. Your
udpInit function would typically be used to allocate the context,
udpExecute (and udpMoreResults) would use the context, and
Example
short REXTERNAL timsExecute (
void **ctxp, /* in: proc context pointer */
short noargs, /* in: number of arguments to procedure */
VALUE *args, /* in: array of arguments */
RM_MEMTAG mTag, /* in: memory tag for rm_ memory calls*/
HSTMT *phStmt, /* out: hstmt for result set */
VALUE *err) /* out: container for error messages */
{
static char errmsg[65];
char author[32];
struct info ir;
short stat, arg;
char *author_arg = args->vt.cv;
UDP_CTX *ctx = *ctxp;
RDM_DB hdb = ctx->hDb;
HSTMT hstmt = ctx->hStmt;
/* extract data from tims database & insert into SQL table */
d_setoo(AUTHOR_LIST, AUTHOR_LIST, hdb);
(continued)
(continued)
for ( ; ; ) {
while ( (stat = d_findnm(AUTHOR_LIST, hdb)) == S_OKAY ) {
d_recread(AUTHOR, author, hdb);
for ( arg = 0; arg < noargs; ++arg) {
/* check for author in argument list */
char *aname = args[arg].vt.cv;
if ( strncmp(author, aname, strlen(aname)) == 0 )
break;
}
if ( noargs == 0 || arg < noargs )
break;
}
if ( stat != S_OKAY )
break;
d_setor(HAS_PUBLISHED, hdb);
while ( (stat = d_findnm(HAS_PUBLISHED, hdb)) == S_OKAY ) {
d_recread(INFO, &ir, hdb);
SQLExecute(hstmt);
}
}
SQLFreeStmt(hstmt, SQL_RESET_PARAMS);
return SQL_SUCCESS;
}
Syntax short REXTERNAL udpInit (void **ctxp, short noargs, VALUE *args,
RDM_SESS hSess, RM_MEMTAG mTag, VALUE *err)
Example
short REXTERNAL timsInit (
void **ctxp, /* in: proc context pointer */
short noargs, /* in: number of arguments pased */
VALUE *args, /* in: arguments, args[noargs-1] */
RDM_SESS hSess, /* in: current session id */
RM_MEMTAG mTag, /* in: memory tag for rm_ memory calls */
VALUE *err) /* out: container for error messages */
{
short stat;
/* open TIMS w/separate RDS task, allows dirty reads w/in trans */
d_opentask("", &ctx->hSess);
stat = d_open("tims", "s", ctx->hSess, &ctx->hDb);
if ( stat != S_OKAY ) {
err->type = SQL_CHAR;
err->vt.cv = "unable to open TIMS";
d_closetask(ctx->hSess);
rm_freeMemory(ctx, mTag);
return SQL_ERROR;
}
*ctxp = ctx;
return SQL_SUCCESS;
}
Description This function is called by Velocis SQL to obtain the next result set
for the specified UDP. It is invoked each time your application calls
SQLMoreResults on the execute statement handle that
referencesthe UDP. The actual function name can be any valid C
function name and must be assigned to the udpCleanup entry in the
UDP load table.
If there are no more result sets, your udpMoreResults function
should return SQL_NO_DATA_FOUND. If there is no more than
one result set returned by your UDP, you do not need to have a
udpMoreResults function (just set the UDP load table entry for it to
NULL).
The statement context pointer, ctxp, points to a pointer variable that
is maintained in the SQL statement context. This pointer allows you
to allocate and store UDP-specific context information. Your
udpInit function would typically be used to allocate the context,
udpMoreResults (and udpExecute) would use the context, and
udpCleanup would free it. In the example below, the context is
used to store statement and database handles that were assigned in
the udpInit function.
Example
short REXTERNAL timsMoreResults (
void **ctxp, /* in: proc context pointer */
short noargs, /* in: number of arguments to procedure */
VALUE *args, /* in: array of arguments */
RM_MEMTAG mTag, /* in: memory tag for rm_ memory calls */
HSTMT *phStmt, /* out: hstmt for result set */
VALUE *err) /* out: container for error messages */
{
UDP_CTX *ctx = *ctxp;
if ( ctx->finished )
return SQL_NO_DATA_FOUND;
ctx->finished = 1;
SQLFreeStmt(ctx->hStmt, SQL_CLOSE);
SQLExecDirect(ctx->hStmt,
"select count(*) 'TOTAL ROWS FOUND' from timstab",
SQL_NTS);
*phStmt = ctx->hStmt;
return SQL_SUCCESS;
}
Description This function converts an ODBC date value into an internal Velocis
date.
Description This function converts an ODBC time value into an internal Velocis
time.
VALUnpackDate Convert an internal Velocis date value to the standard ODBC format
Description This function converts a Velocis date from its internal format to the
standard ODBC format.
VALUnpackTime Convert an internal Velocis time value to the standard ODBC format
Description This function converts a Velocis time from its internal format to the
standard ODBC format.
Description This function converts a Velocis timestamp from its internal format
to the standard ODBC format.
DataDescriptor::DataDescription
Public DataDescription (short nInitSize = 0)
Remarks This is the default constructor of the data definition array. You can
specify the initial size of the data definition array by passing
nInitSize. The default initial size is 0.
DataDescriptor::~DataDescription
Public ~DataDescription ()
Remarks This destructor frees memory allocated for the data definition array.
Member Functions
DataDescriptor::Begin
Public void Begin (unsigned short nStructSize,
unsigned short nArraySize = 0)
Remarks This method inserts a logical start item into the definition of a
structure or an array of structures. For an array of structures, the
size of the array must be supplied in nArraySize. If a structure being
defined contains nested structures, the definition sequence must call
Begin every time a nested structure begins.
See Also DataDescriptor::End
DataDescriptor::End
Public void End ()
Remarks This method inserts a logical end item into the definition of a
structure or array of structures. The method automatically
determines whether it needs to put an end to the entire definition or
just to a nested structure definition. The number of End calls must
match the number of Begin calls in your structure definition. To
end the entire definition, the PL_FLAG_CLOSE data modifier flag is
added to the closing element.
See Also DataDescriptor::Begin
DataDescriptor::IsEmpty
Public T_F IsEmpty ()
Remarks This method returns TRUE if the structure has not been built yet;
FALSE otherwise.
Operators
ParmReceive::operator >>
Public ParmReceive& operator >> (char *ps)
ParmReceive& operator >> (type& value)
ParmReceive& operator >> (ParmReceive& (*func)(ParmReceive&))
type:
[unsigned] {char | int | long | short}
| double | float | signed char
Parameters ps A pointer to a character array or a character string.
value The reference to a scalar value.
func A pointer to a function that takes a stream as an
argument and returns a stream as a result.
Remarks This operator retrieves a scalar value from the parameter list and
assigns it to the variable, if the type of data in the parameter list
matches that of the variable. For data to be retrieved successfully,
they must be sent by the remote process in a typesafe manner. The
only exception is when the operator is used with a character pointer,
because it accepts both character arrays (PL_CHAR) and null-
terminated character strings (PL_ASCIZ). In Table 17-2 below, the
correlation is shown between the C++ integral types and the DPL
(Data Portability Layer) types, as defined in the Velocis library. To
retrieve a structure or an array, a corresponding Get method must
be used.
When reading a text string from the input stream, you have to make
sure that your character array has enough space to accommodate the
received data. If you are not sure about the size of the string in the
stream, the GetNextSize method should be used first.
If the operator is used with a function pointer, any function of the
ParmReceive object can be used with the operator as long as it
returns a ParmReceive object. This may be handy when the user
designs such a function. (Currently, no functions of that type are
included in the ParmReceive class.)
See Also ParmReceive::Get, ParmReceive::GetNextSize,
ParmSend::operator <<, ServerExtension::Rpc
Example
short MyServerExtension::XFunction(short *sOut, long *lOut, float *fOut)
{
short nRet;
ParmSend Input(XFUNCTION, GetSession());
ParmReceive Output;
ParmReceive::Get
Public SeStatus Get (type *pValue, short nSize = 0)
SeStatus Get (void *pValue, short nSize = 0, short nStructSize = 0)
type:
[unsigned] {char | int | long | short}
| double | float | signed char
Parameters pValue A pointer to the address where the data is copied.
nSize The expected size of the data; this value is ignored if
0 is specified.
Remarks Call this method to retrieve a structure or an array of scalar values.
To read an array successfully, use the proper version of the Get
method. The method actually copies data from the parameter list to
the address pointed to by pValue only if their type in the list is
consistent with that of the argument. That is, the remote process
must send an array of the exact same type that is being expected.
(The only exceptions are for the char and unsigned char pointer
types, which accept both null-terminated character strings and
character arrays.) This guarantees that data sent by the remote
process as a character string, using << (char *), will be correctly
received by the local process with Get (char *). If a non-zero value
of nSize (the expected size of data) is specified, it is used for
additional data size validation. If nSize does not match that in the
parameter list, the InvalidSize error code is returned.
To retrieve a structure, an array of structures, or opaque data, use
the version of the method that takes a generic pointer (void *)
parameter. If nSize is provided, the additional size validation is
performed by comparing this value with the one in the descriptor
associated with the data element in the stream. By default, the size
of the data in the descriptor is used.
Always make sure that the destination structure or array has
enough room to accept the data from the stream. For opaque data
and character strings, it is recommended that GetNextSize be called
first, to inspect the size of incoming data. For structures, you can
use the sizeof function within nSize to insure safety.
This method returns the status code of the most recent operation.
ParmReceive::GetNextSize
Public unsigned short GetNextSize ()
Remarks Call this method to get the size, in bytes, of the next value in the
input stream.
See Also ParmReceive::GetNextType
ParmReceive::GetNextType
Public unsigned short GetNextType ()
Remarks Call this method to inspect the type of the next value in the input
stream. This method should be used when the type of data in the
input stream is unknown.
See Also ParmReceive::GetNextSize
ParmReceive::GetSize
Public unsigned short GetSize ()
Remarks Call this method to get the size, in bytes, of the current value in the
input stream.
See Also ParmReceive::GetType
ParmReceive::NoData
Public T_F NoData ()
Remarks Call this method to detect the end of data condition in the input
stream. It returns TRUE if the "end of data" condition is reported by
the communication layer with the S_RPCENDOFPARMS error code.
Operators
ParmSend::operator <<
Public ParmSend& operator << (char *ps)
ParmSend& operator << (type& value)
ParmSend& operator << (ParmSend& (*func)(ParmSend&))
type:
[unsigned] {char | int | long | short}
| double | float | signed char
Parameters ps A pointer to a character array or a null-terminated
character string.
value A reference to scalar value.
func A pointer to a function that takes a stream as an
argument and returns a stream as a result.
Remarks This operator places a value in the output parameter list and assigns
a DPL type to it according to the variable’s type. For data to be read
successfully by the remote process, they should be retrieved by the
operator >> (its counterpart) or by the Get method with the same
type of argument. (For example, short and unsigned short integers
are considered different types, which results in the InvalidData
error code.) Table 17-2 shows the correlation between C++ integral
types and the DPL types defined in Velocis library.
The third version of the operator shown allows any method of the
output stream object to be used with the operator as long as it
returns an output stream object. This may be convenient if the user
needs to design such a method. (Currently, no methods of that type
are included in the ParmSend class.)
This operator returns the status code of the most recent operation.
Note: The Put family of methods can be used instead to perform the
same operation.
Member Functions
ParmSend::Put
Public SeStatus ParmSend::Put (type *pValue, short nSize = 0)
SeStatus ParmSend::Put (void *pValue, PL_ITEM *pItemDesc,
short nSize = 0)
type:
[unsigned] {char | int | long | short}
| double | float | signed char
Parameters pValue A pointer to the data item to be sent.
pItemDesc (Second version—for structure or opaque data only)
The DPL description of a structure, if the data is a
structure; if the data is opaque, specify NULL.
nSize The size of the array, structure, or opaque data. If 0
is specified, the item is considered a scalar value.
Remarks There are two forms of the ParmSend::Put method. The first
version shown is used to store a scalar value or an array of scalar
values, while the second version is used to store structure or opaque
data.
• Call the first form of this method to store a single scalar value or
an array of scalar values. The data items stored by the Put
method should be retrieved by a corresponding Get method.
Although scalar values stored by the Put method can also be
Input.Put(sData, nInSize);
nAvg = Rpc(Input, Output);
}
return nAvg;
}
SeBase::SeBase
Protected SeBase (T_F bServer = FALSE)
Remarks This is a standard constructor. As a protected method, it enforces
subclassing. The default value of bServer is FALSE. From the client
side, it is called with no arguments, while on the server side, TRUE
is passed explicitly.
See Also SeBase::~SeBase
SeBase::~SeBase
Public virtual ~SeBase ()
Remarks This method is a standard destructor. Because it is a virtual method,
C++ ensures the destructor of the topmost derived class is called
first.
See Also SeBase::SeBase
Operators
SeBase::operator new
Public operator new (size_t nSize, short nMemTag = 0)
Remarks This operator performs an optimized memory allocation of nSize
bytes using rm_getMemory, defined in the Velocis library. The
default version of the operator is available for allocating both the
client and server-side objects. On the server side, you can also
specify a memory tag ID (nMemTag). The memory tag is internally
generated by rm_allocTag and can be obtained by calling the
GetMemoryTag member method. With tagged memory allocations,
you can guarantee that all objects allocated with the tag will be
properly cleaned up simply by freeing the tag.
If you should override this operator in your class, you must also
override the delete operator. On the server side, make sure your
overloaded operator uses rm_getMemory to perform allocation.
When using this operator, make sure that the class inherited from
SeBase comes first in the multiple inheritance declarations. If this is
SeBase::operator delete
Public operator delete (void *p)
Remarks This operator frees memory by calling rm_freeMemory and passing
the memory buffer pointer (p). On the server side, the operator
deletes the objects using the same tag as the new operator.
If you should override this operator in your class, you must also
override the new operator. On the server side, make sure you are
using rm_freeMemory to do the cleanup.
When using this operator, make sure that the class inherited from
SeBase comes first in the multiple inheritance declarations. To
obtain the memory tag ID, the operator casts the memory pointer to
SeBase, which only works if SeBase is the first base class.
Member Functions
SeBase::AllocateNewTag
Protected short AllocateNewTag ()
Remarks This method calls rm_allocTag to retrieve the value of the new
memory tag ID.
SeBase::FreeMemory
Protected void FreeMemory (void *ptr, short nTag)
Remarks This method calls rm_freeMemory (ptr, nTag), where ptr is a pointer
to the memory block to be freed, and nTag is the memory tag ID
where the memory block has been allocated.
SeBase::GetContext
Protected void **GetContext (RDM_SESS hSess, short hEM)
Remarks This method calls em_getContext (hSess, hEM), where hSess is the
session handle, and hEM is the extension module handle. It returns
a reference to the context pointer. This method can be used to get
access to the ServerExtension-derived object, which has been
created by ModInit.
SeBase::GetErrorCode
Public short GetErrorCode ()
Remarks This method retrieves the S_ return code from the most recent RPC
call. The purpose of this is to retrieve more detailed information
about the cause of a failure when GetStatus returns the RPCError
status.
SeBase::GetMemory
Protected void *GetMemory (size_t nLen, short nTag)
Remarks This method calls rm_getMemory (nLen, nTag), where nLen is the
size of the memory block, and nTag is the memory tag ID where the
memory block is allocated. It returns a pointer to the allocated
memory block.
SeBase::GetMemoryTag
Public short GetMemoryTag ()
Remarks Call this method to get the object’s memory tag ID. If you allocate
objects using this memory tag, they are guaranteed to be cleaned up
when the object itself is deleted at session’s end.
SeBase::IsServer
Protected short IsServer ()
Remarks This method can be used in a derived class to query if the execution
is being conducted on the server side or the client side. It is
instrumental for implementing polymorphic methods that behave
differently on different sides of the connection. The method returns
TRUE if the method was created on the server side (in the extension)
and FALSE if it is was created on the client side.
SeBase::LogWrite
Protected void LogWrite (char *str)
Remarks This method calls rm_systemLogWrite (char *format, ...). The
method writes a string (str) to the server console and to the log file
(RDS.log). Contrary to its native counterpart, it does not format the
output and only accepts a character string.
SeBase::Okay
Public T_F Okay ()
Remarks Call this method whenever you want to check if the most recent
operation was successful. It returns TRUE if the most recent
operation was successful, FALSE otherwise.
ServerExtension::ServerExtension
Public [default] ServerExtension ()
[client] ServerExtension (char *strModuleName, RDM_SESS hSess)
[server] ServerExtension (RDM_SESS hSess, short hEM)
Remarks There are 3 versions of the ServerExtension constructor: a default
constructor without parameters, a client-side constructor that passes
Member Functions
ServerExtension::Attach
Public T_F Attach (char *strModuleName)
Remarks This method is a client-side wrapper for em_attach; it has no effect if
it is called on the server side. It explicitly attaches the extension
module by name (strModuleName). Before the module can be
attached, it must be loaded into the server’s memory using the Load
method. The handle to the module is stored within the object and
can be retrieved by calling GetHandle. If FALSE is returned, you
should check the error code with GetErrorCode to determine the
cause of the failure. In most cases, it is not necessary to call this
method since it is called implicitly by the constructor.
See Also SeBase::GetErrorCode, ServerExtension::Detach,
ServerExtension::GetHandle, ServerExtension::Load
ServerExtension::GetDescription
Public static char *GetDescription () const
Remarks This server-side method retrieves a pointer to a static string. This
static method is called by the extension module to obtain the
description string of the module. By default, the string "A
C++ server extension" is returned. You can overload this method if
you want a different string to appear on the Velocis server console
when the module is loaded.
ServerExtension::GetHandle
Public short GetHandle ()
Remarks This method returns the extension module handle. On the client
side, the handle is returned by em_load in the object constructor.
On the server side, the handle is set in ModDescribeFcns.
ServerExtension::GetSession
Public RDM_SESS GetSession ()
Remarks This method retrieves the session handle.
See Also CREATE_EXPORTS (macro)
Note: Right after it is loaded, the extension module will call the
OnLoad static method.
ServerExtension::OnLoad
Public static void OnLoad ()
Remarks This server-side method is only called once (by ModDescribeFcns)
when the extension module is being loaded into memory. This
allows you to include certain "on-load" actions in the extension
module code. It is a static method, because at loading time, no
object of type ServerExtension exists. Therefore, only static data or
methods can be accessed within your OnLoad method. Any global
calculations that are shared by some or all extension functions
should be done here. For example, this is an obvious place for
building structure definitions, since they only need to be created
once.
Note: This is not a virtual method, but once overloaded, it acts like
one, since ModDescribeFcns (which is compiled as part of the
CREATE_EXPORTS macro) uses the user-defined class to invoke it.
#define XEXP 1
#define XLOG 2
#define XSIN 3
#define XCABS 4
BEGIN_RPC_MAP(MathServer, ServerExtension)
ON_RPC(XCABS, XCabs)
ON_RPC(XEXP, XExp)
ON_RPC(XLOG, XLog)
ON_RPC(XSIN, XSin)
...
END_RPC_MAP()
protected:
DataDescriptor m_ComplexDesc;
public:
Xmath(RDM_SESS hSess); //constructor
double Xexp(double);
double Xlog(double);
double XSin(double);
double Xcabs(struct _complex *);
...
};
(continued)
ServerExtension::SetSession
Public void SetSession (RDM_SESS hSess)
void SetSession (HDBC hDbc)
Remarks The first version of this method is provided to explicitly set the
session handle (hSess) in the object. The second version is a helper
method that sets the session handle in the object from the SQL
connection handle (hDbc). This version is provided for the cases
where a mixture of SQL and d_ APIs are used in the program.
See Also ServerExtension::GetSession
Note: The Velocis extension module standard API does not provide
an entry point for unloading, so this event cannot be custom
processed on the server.
Macros
BEGIN_RPC_MAP
Syntax BEGIN_RPC_MAP (theClass, baseClass)
Fields theClass The derived class for which the message map is
defined.
baseClass The immediate parent class.
Remarks Use this macro as the opening bracket of the message map definition
for your server envelope object. The map has to be defined once in
one of the source (.cpp) files. Each entry in the map must be defined
using the ON_RPC macro.
See Also END_RPC_MAP, ON_RPC
CREATE_EXPORTS
Syntax CREATE_EXPORTS (theUserDefinedClass)
Remarks This macro must be called once in any of the source files (.cpp) that
implement the extension classes. It creates definitions for the
exported functions ModDescribeFcns, ModInit and ModCleanup
in a standard extension module. The macro parameter
(theUserDefinedClass) is the user-defined envelope class derived from
ServerExtension. An object of this type will be instantiated by
ModInit, and a pointer to it will be stored in the session context.
Therefore, each session contains its own unique object of type
theUserDefinedClass. Since this type is required to instantiate the
object, the standard export functions cannot be precompiled and a
macro must be used to generate them.
END_RPC_MAP
Syntax END_RPC_MAP ()
Remarks Use this macro as the closing bracket of the message map for your
server envelope object.
See Also BEGIN_RPC_MAP, ON_RPC
ON_RPC
Syntax ON_RPC (MessId, Func)
Remarks Use this macro to define a message map entry for your envelope
class. The macro fields specify the message ID (MessId) and the
name of a member method of the derived class that was specified in
the BEGIN_RPC_MAP macro (Func). There must be one entry for
each message type receivable from the client, unless the entry is
defined in the parent class.
See Also BEGIN_RPC_MAP, END_RPC_MAP
Example
class MyEnvelope : public ServerExtension {
...
DECLARE_RPC_MAP();
};
BEGIN_RPC_MAP(MyEnvelope, SetverEnvelope)
ON_RPC(MESS1, emFunction1)
ON_RPC(MESS2, emFunction2)
END_RPC_MAP()
Constant Description
DB_ADDR_SIZE Use when the size of a database address variable is needed. Same
as sizeof(DB_ADDR).
LITERAL_NULL_DBA Use when statically initializing database address fields in a
structure, such as a GROUPLOCK variable.
NULL_DBA Use to assign a null database address value to a DB_ADDR
variable in an assignment statement.
Macro Description
DB_ADDR_EQ(dba1, dba2) Returns 1 (true) if two database address (DB_ADDR) variables are
equal.
DB_ADDR_ISNULL(dba) Returns 1 (true) if a database address is null.
MAKE_SESS(hDb) Returns the session ID that is contained in the specified RDM_DB
value.
Also provided are additional, Velocis-specific types (Table 18-5) for use with the SQL
support functions (i.e., the BCD, VAL, and SYS function APIs).
The following three tables list the standard ODBC/SQL data type definitions. Table 18-6
lists the standard SQL data types. Use of these definitions requires that you include the
sql.h header file.
Table 18-7 lists the extended SQL data types. To use these types in addition to the
standard SQL data types, include the sqlext.h header file.
Velocis-specific data types are listed in Table 18-8. These data types, the standard SQL
data types, and the extended SQL data types are made available when you include the
sqlrds.h header file.
Velocis supports all ODBC-specified data type conversions. This includes conversion
into a character string for any data type, and the usual conversions between numeric
Description This structure defines a date, consisting of the month, day, and year.
You use a C variable of DATE_STRUCT type to hold SQL date
values as a bound column result or parameter value.
Description This structure contains the name of the database device in which the
data dictionary (.dbd) file is stored and information about the
database name.
Fields fname The name of a data file, key file, or BLOB file.
fdevice The name of the device on which the the file in
fname is stored.
Description This structure provides the name of the file device for the database
dictionary.
Description This structure contains lock request information for use by the
d_grplock function in making multiple lock requests for your
application.
Description The pl_putStruct function uses arrays of this structure to define the
fields that make up a structure parameter. Structures can be nested
within a structure parameter.
The data type, which is specified in the type field, must be equal to
one of the enumerated values described in the table below. The
table lists the data type indicators, their equivalent C data types, and
their descriptions. Although equivalent data types for C are shown,
the conversion mechanism works for any variety of languages (for
example, SQL, Core DDL, Pascal, etc.).
Fields hour The hour of the day. Possible values are 0 (12 am)
to 23 (11 pm).
minute The minute of the hour. Possible values are 0 to 59.
second The second of the minute. Possible values are 0 to
59.
Description This structure defines a time, consisting of the hour, minute, and
second. You use a C variable of TIME_STRUCT type to hold SQL
time values as a bound column result or parameter value.
Fields username The name of the user. This name must be unique.
userpass The user password.
userpriv The database access privilege for the user. Possible
values are:
0 Normal user
1 Administrative user
Description This structure defines a parameter of a UDF or UDP. The type field
holds the parameter type, while the parameter value is placed in one
of the fields of the vt union, depending on the data type.
The rest of this section lists the standard Velocis return codes, sorted by name (as defined
in rdserrs.h). Each description includes the return code, its numerical value, a message
string, and a description of the status or error. For ways to correct the errors, see
Chapter 13 in the Velocis User’s Guide.
SQL_ERROR -1
An SQL error was detected.
The application has generated an SQL error. Check SQLError for more
specific failure information (see section 19.2.2).
SQL_INVALID_HANDLE -2
Null statement or connection handle.
A function has failed due to an invalid environment, connection, or
statement handle. This code only results from a programming error. No
further information is available from SQLError.
SQL_NEED_DATA 99
SQLExecute has encountered an execution-time parameter.
In a call to SQLExecute or SQLExecDirect, there were
SQL_DATA_AT_EXEC parameters specified for the statement being
executed. The application now needs to send the data using
SQLParamData and SQLPutData.
SQL_NO_DATA_FOUND 100
No data found.
The SQLFetch function has returned all rows from the result table.
SQL_SUCCESS 0
Success.
The function has been completed successfully.
The remainder of this section lists the SQLError codes, sorted by Velocis numerical code.
Each description includes:
• Velocis SQL numeric code (for example, 1002).
• Velocis SQL constant name for the error (for example, errCHTRUNC).
• The ODBC/SAG code for the error (for example, 01004 for errCHTRUNC). Some of
the ODBC codes are not unique due to their lack of specificity. In contrast, the Velocis
SQL-specific codes are more specific. For example, Velocis SQL provides a number of
syntax error codes that parallel the ODBC code for all syntax errors (37000).
’(’ expected.
You must enclose a check clause in parentheses.
Bad function table entry for function udfname in UDF DLL: <dllname>.
The function table entry for function "udfname" in the UDF DLL
("dllname") has a null address for the type checking function. See the
definition of udfCheck.
c_data columns not allowed in check() clause: <name>.
You cannot reference columns of c_data type in a check clause.
c_data columns not allowed in create join: <name>.
You cannot reference columns of c_data type in a create join statement.
c_data columns not allowed in foreign key: <name>.
You cannot reference columns of c_data type in a foreign key.
c_data columns not allowed in index: <name>.
You cannot reference columns of c_data type in an index.
c_data columns not allowed in primary/unique key: <name>.
You cannot reference columns of c_data type in a primary or unique key.
c_data is non-standard.