P@4 W! McGraw-HillEnterprise
Computing Series DB2 Universal Database Developer’s Guide for Call Level Interface by Sanders ISBN 0-07-134572-8 Enterprise Java Developer’s Guideby Narayanan/Liu ISBN 0-07-134673-2 Web Warehousing and Knowledge Management by Mattison ISBN 0-07-0041103-4 ODBC 3.5 Developer’s Guide by Sanders ISBN 0-07-058087-1 Data Warehousing, Data Mining & OLAP by BersodSmith ISBN 0-07-006272-2 Data Stores, Data Warehousing and the Zachman fiamework by Inman ISBN 0-07-031429-2
Copyright 82000 by The McGraw-Hill Companies, Inc. All Rights Reserved. Printed in the United States of America. Exceptas permitted under the United States Copyright Act of 1976,no part of this publication maybe reproduced or distributed in any form or by any means, or stored in a database or retrieval system, without the prior written permission of the publisher.
l 2 3 4 5 6 7 8 9 0 AGMIAGM 9 0 4 3 2 1 0 9 Pm 0-07-135390-9 Part Of ISBN 0-07-135392-5 The sponsoring editor for this book was Simon Yates, and the production supervisor was Clare Stanley. It was set in Century Schoolbook by D&G Limited, LLC. Printed and bound by QuebecorlMartinsburg. Throughout this book, trademarked names are used. Rather than puta trademark symbol after every occurrenceof a trademarked name, we used the names in aneditorial fashion only, and t o the benefit of the trademark owner, with no intention of infringement of the trademark. Where such designations appear in this book, they have beenprinted with initial caps. ~
Information contained in this work has been obtained by The McGraw-Hill Companies,Inc. ("McGraw-Hill") from sources believed to be reliable. However, neither McGraw-Hill nor its authors guarantees the accuracy or completeness of any information published herein and neither McGraw-Hill nor itaauthors shall be responsible for any errors, omissions, or damages arising out of use of this information. This work is publishedwith the understanding that McGraw-Hill and its authors are supplying information but are not attempting to renderengineering or otherprofessionalservices. If such services are required, the assistance of an appropriate professional should be sought.
f4
This book is printed on recycled, acid-free paper containing a minimum of 60% recycled de-inked fiber.
project of‘this ma ~fferentpeople, I cont~butions :
niver-
rmation about u
as one o
ost of all, I would like to th
*
“scenesautho~zers t
l!M!
IDEDICATION To my son, Tyler Mamk43anders.
CONTENTS xv
Foreword
xvii
Introduction Part 1
Basic Database Concepts
1
Chapter 1
DB2 Database Architecture
3
The Relational Database Relational Database Objects Databases Table Spaces Tables Indexes Views Packages (Access Plans) Triggers Aliases Event Monitors Schemas System Catalog views Recovery Log Files and the Recovery History File Configuration Files DB2 Database Directories Physical DatabaseDirectory Volume Directory System Directory Workstation Directory Database Connection Services Directory
Chapter2DatabaseConsistencyMechanisms What Is Data Consistency7 Transactions Concurrency and Ransaction Isolation Levels Repeatable Read Read Stability Cursor Stability Uncommitted Read Specifying the Isolation Level Locking Lock Attributes Lock States
4 4 5 5 7 10 12 13 13 14 14 14 15 16 17 17 18 19 19 20 20
23 24 24 25 27 28 28 28 29 29 30 30
Contents Locks and Application Performance mansaction Logging
32 38
Part 2
Application Development Fundamentals
Chapter 3
Getting Started with Dl32 Application Development 45
43
What Is a DB2 Database Application? Designing a DB2 Database Application Elements of a DE2 Database Application High-Level Programming Language SOL Statements CL1 Function Calls API Function Calls Establishing the DB2 Database Application Development Environment Establishing the D62 Database Application Testing Environment Creating a Testing Database Creating Testing Tables and views Generating Test Data Managing Transactions Creating and Preparing Source Code Files
46 46 48 49 49 51 52
Writing API Applications
61
The Basic Structure of an API SourceE-Code File Types of API Function Calls API Naming Conventions API Data Structures Error Handling Evaluating Return Codes Evaluating SOLCA Return Codes Evaluating SOLSTATES Creating Executable Applications Running, Testing, and Debugging API Applications
62 62 66 67 70 70 70 71 71 71
Part 3
Appllcatlon Programming Interface ( N I ) Functions
75
Chapter 5
Program Preparation and General Programming APls
77
Embedded SOL Application Preparation Exception, Signal, and Interrupt Handlers Pointer Manipulation and MemoryCopy Functions
78 79 79
Chapter 4
55 56 56 56 57 57 58
Contents Specifying Connection Accounting Strings Evaluating SQLCA Return Codesand SQWATE Values PRECOMPILE PROGRAM BIND REBIND GET INSTANCE INSTALL SIGNAL HANDLER INTERRUPT GET ADDRESS COPY MEMORY DEREFERENCE ADDRESS SET ACCOUNTING STRING GETERRORMESSAGE GETSQLSTATEMESSAGE GET AUTHORIZATIONS Chapter 6
79 81 82 99 103 107 109 112 116 117 118 119 122 125 128
DB2Database ManagerControl and Database
Control APls
133
The DB2 Database Manager Sewer Processes Creating and Deleting DB2 Databases Starting and Stopping DB2 Databases Retrieving and Setting Other Connection Setting Values Controlling DB2 Database Manager Connection Instances The DB2 Database Manager and DB2 Database Control Functions START DATABASE MANAGER START DATABASE MANAGER STOPDATABASEMANAGER FORCE APPLICATION CREATEDATABASE DROP DATABASE ACTIVATEDATABASE DEACTIVATE DATABASE ATTACH AlTACH AND CHANGE PASSWORD DETACH QUERY CLIENT SET CLIENT QUERY CLIENT INFORMATION SET CLIENT INFORMATION
134 134 134 135 135 135 136 137 142 146 150 159 160 163 165 169 173 174 179 180 185
Contents Chapter 7
Chapter 8
DB2 Database Manager and Database Configuration APls
187
Configuring D62 D62 Database Manager Configuration Parameters D62 Database Configuration Parameters The D62 Database Manager and Database Configuration Functions Get Database ManagerConfiguration Get Database ManagerConfiguration Get Database ManagerConfiguration Defaults UPDATE DATABASE MANAGER CONFIGURATION RESET DATABASE MANAGER CONFIGURATION GET DATABASE CONFIGURATION GET DATABASE CONFIGURATION DEFAULTS UPDATE DATABASE CONFIGURATION RESET DATABASE CONFIGURATION
189 190 191 204 207 212 213 225 228 233
Database, Node, and DCS Directory Management APls
235
D62 Directories The System Database Directory Volume Directories The Workstation (Node) Directory The Database ConnectionServices (DCS) Directory RegisteringIDeregistering D62 Database Servers with NetWare The D62 Database, Node, and DCS Directory Management Functions CATALOG DATABASE CATALOG DATABASE UNCATALOG DATABASE CHANGE DATABASE COMMENT OPEN DATABASE DIRECTORY SCAN GET NEXT DATABASEDIRECTORY ENTRY CLOSE DATABASE DIRECTORY SCAN CATALOG NODE UNCATALOG NODE OPEN NODE DIRECTORY S C A N GET NEXT NODE DIRECTORY ENTRY CLOSE NODE DIRECTORY SCAN CATALOG DCS DATABASE UNCATALOGDCSDATABASE OPEN DCS DIRECTORY S C A N GET DCS DIRECTORY ENTRIES
188 188 189
236 236 236 237 237 237 238 239 240 244 247 250 253 255 256 262 264 267 269 270 273 276 278
Contents 280 28 1 28 1 286
GET DCS DIRECTORY ENTRYFOR DATABASE CLOSE DCS DIRECTORY SCAN REGISTER DEREGISTER
Chapter 9
Table and Table Space Management
APls
289
Table Spaces and Table Space Containers Reorganizing Table Data Updating Table Statistics The D62 Table and Table Space Management Functions OPEN TABLESPACE QUERY OPEN TABLESPACE QUERY FETCH TABLESPACE QUERY CLOSE TABLESPACE OUERY TABLESPACE QUERY SINGLE TABLESPACE QUERY GET TABLESPACE STATISTICS OPEN TABLESPACE CONTAINER QUERY FETCH TABLESPACE CONTAINER QUERY CLOSE TABLESPACE CONTAINER QUERY TABLESPACE CONTAINER QUERY FREE MEMORY REORGANIZE TABLE RUN STATISTICS
Chapter 10
290 290 29 1 29 1 292 293 296 300 300 304 307 310 314 316 316 320 320 324
APls
329
Database Migration Recovering from an "Inconsistent" State Creating Backup Images Restoring Datbase and Table Spaces from Backup Images Performing Redirected Restore Operations Using Roll-Forward Recovery Recovery History Files The D62 Database Migration And Disaster Recovery Functions MIGRATE DATABASE MIGRATE DATABASE RESTART DATABASE BACKUP DATABASE RESTORE DATABASE RECONCILE SET TABLESPACE CONTAINERS ROLLFORWARD DATABASE
330 330 33 1
DatabaseMigrationandDisasterRecovery
332 332 333 333 335 336 337 339 342 351 36 1 365 372
Contents
Chapter 1 1
Chapter 12
Chapter 13
ASYNCHRONOUS READ LOG OPEN RECOVERY HISTORY FILE S C A N GET NEXT RECOVERY HISTORY FILE ENTRY CLOSE RECOVERY HISTORY FILE S C A N UPDATE RECOVERY HISTORY FILE PRUNE RECOVERY HISTORY FILE
387 394 399 404 405 409
DataHandling APls
41 5
Exporting Data Importing Data Loading Data Supported Export, Import, and Load File Formats The DE2 Data Handling Functions EXPORT IMPORT LOAD LOAD QUERY QUIESCE TABLESPACES FOR TABLE
41 6 41 6 41 7 41 9 420 42 1 430 446 464 466
D62DatabasePartitionManagementFunctions
47 1
Nodegroups.And Data Partitioning V p e s Of Parallelism V 0 Parallelism Query Parallelism Enabling Query Parallelism Enabling Data Partitioning The DE2 Database Partition Management Functions ADD NODE DROP NODE VERIFY CREATE DATABASE AT NODE DROP DATABASE AT NODE SET RUNTIME DEGREE GET TABLE PARTITIONING INFORMATION GET ROW PARTITIONING NUMBER REDISTRIBUTE NODEGROUP
472 472 473 473 475 475 476 477 480 482 485 487 490 494 500
Database Monitor and lndoubt lkansaction Processing APls
505
The DB2 Database System Monitor Database System Monitor Switches When Counting Starts Retrieving Snapshot Monitor Data
506
506 507 508
Contents Working with Multiple Databases How the WePhaseCommit Process Works Recovering from Errors Encountered While Using WePhase Commits Manually Resolving lndoubt ltansactions Wo-Phase Commit Processing Using an XA-Compliant lkansaction Manager The DB2 Database Monitor and lndoubt ltansaction Processing Functions GETNPDATE MONITOR SWITCHES RESET MONITOR ESTIMATE DATABASE SYSTEM MONITOR BUFFER SIZE GET SNAPSHOT LIST DRDA INDOUBT TRANSACTIONS LIST INDOUBT TRANSACTIONS COMMIT AN INDOUBT TRANSACllON ROLLBACK AN INDOUBT TRANSACTION FORGET TRANSACTION STATUS
509 509
Thread Context Management Functions
553
Contexts The DB2 Thread Context Management Functions SET APPLICATION CONTEXT TYPE CREATE AND ATTACH TO AN APPLICATION CONTEXT DETACH AND DESTROY APPLICATION CONTEXT ATTACH TO CONTEXT DETACH FROM CONTEXT GET CURRENT CONTEXT INTERRUPT CONTEXT
554 554 555 559 562 566 567 568 572
Chapter 14
51 1 512 514 515 516 52 1 524 527 536 540 545 548 552
Appendix A ODBC Scalar Functions
577
Reference Appendix B SQLSTATE
58 1
Appendix C How theExampleProgramsWereDeveloped
61 5
Bibliography
627
Index
627
API Index
639
This Page Intentionally Left Blank
m
P4 FOREWORD Relational database technology wasinvented in IBM research more than 20 years ago. In 1983, IBM shipped the firstversion of DB2 for MVS. In 1997,IBM delivered its flagship relational technology onthe AS/400 and OS/2. As we enter the21st century, IBM has continued to extend its award winning database technology with additional function and support for additional platforms. Today, DB2 Universal Database is the most modern database on the planet, supporting the world’s most popular system platforms (IBM OS/390, IBM OS/400, IBM RS/6000, IBM OS/2, Sun Solaris, HP-UX, Microsoft , Windows NT, SCO Openserver, and Linux). DB2 Universal Database, whichk t shipped in 1997,has evolved to meet the rapidfire changes within corporations around the world. Traditional companiesare transforming their core business processes around the Internet. New e-companiesare being formed, and a new generation of Web-based applications are being written.You might ask, ‘What is an e-business anyway?” e-business is buying and selling on the Internet. e-business is being open 24hours-a-day, sevendays-a-week, without having to be there at the company e-business is about reaching new customers, and e-business means working togetherin different ways. Some have said that e-business changes everything-or does it? e-business demands highly scalable, available, secure, and reliable systems. e-business demands industrial strength database technology-the kind that DB2 has delivered to more than 40 million users over the last15 years. IBM’s DB2 Universal Database team has been hard at work delivering enhancementsto DB2 Universal Databaseto make it the foundation for e-business. Today, users can accessDB2 Universal Database from the Web. Application developerscan write DB2 applications and stored procedures using Java or JDBC. Database administrators can administer DB2 databases from Web browsers, and DB2 is themost highly scalable, available, robust database in the world. e-business poses a number of new requirements on the database, as well-access from any type of device. New, pervasive devices will be used to access DB2 databases. e-businesses will have a growing need to leverage informationand knowledge, which will drive business intelligenceand knowledge-based applications whichrequire support formulti-terabyte databases to grow to petabytes. These applications will require advanced analytical functions to be supported in the database engine. They will also require access to rich content-documents, images, text, video, and spatial data. DB2 Universal Database has been extendedto deliver this rich contenttoday. The next millenniumwill bring withit enormous change. The next millennium also will bring with it incredible opportunityfor information technology professionalsand those who support database systems. The new economy will be based on information exchange, and database professionalswill be the stewards of this critical corporateasset. I encourage you to take advantage of the opportunity that Roger Sanders is providing to learn more aboutDB2 Universal Database.I also encourageyou to obtain a certification in DB2 Universal Database. Your time will be well spent. DB2 Universal Databaseis the foundation for e-business for thousands of companies today,and we have only begun. Janet Perna General Manager,Data Management Solutions IBM Corporation
This Page Intentionally Left Blank
m m INTRODUCTION DB2 Universal Databaseis a robust database management systemthat is designed to be used fora variety of purposes in a variety of operating system environments. DB2 Universal Databaseis not a new product; it has existed in some formor another since 1989. The earliest version was called Database Manager,and that version was bundled with OS12 in a product calledOS12 Extended Edition.This product wasIBM’s first attempt to put its popular Database 2 product (which had been available forMVS operating systems onIBM mainframes since 1983) on a PC. Through the years, IBM’s PC versionof DB2has matured to the point wherethe program is now one ofthe most powerhl database products available fora wide variety of platforms. DB2 Universal Database provides a rich set of programming interfaces (Structured Query Language, a Call-Level Interface, and numerous Application ProgrammingInterface function calls) that can be used to develop severalMerent kinds of applications. “his book, one of a seriea of books that describe eachof these programming iuterfacesin detail, is designed to provide you with a conceptual overviewof DB2 Universal Database-as well as a comprehensive referencethat m e r s DB2 Universal Database’s Application Programming Interface.
m
BW Why I Wrote This Book Although DB2 Universal Database has been available since 1989, only a handful of books have beenwritten about the product. And,as theDB2 product evolved, manyof the books that were written were not revisedto reflect the differences in theproduct. Eventually, they went outof print. By 1993, whenthe DB2/2 GA product was released (with DB2/6000 followingshortly after), no book existed that focused on DB2 application development. Robert Orfali and Dan Harkey’s ClientlServer Programming with OS12 2.1 contained four chapters covering the Extended Services 1.0 database manager and later DB2/2. However, because this book addressed clientlserver programming rather thanDB2 application programming,its information aboutDB2 was limited.This situation meant that IBM’s product manuals and online help werethe only resources available to application developers writing applications for DB2/2. In thesummer of 1992, while developing a specialized DB2 application(then called the Extended Services 1.0 Database Manager) that used manyof DB2’sAppZicationProgramming Interface (API) calls, I discovered how lacking (particularly in the areaof examples) someof the IBM manuals for this product really were. Becausethere were no other reference books available, I had to spend a considerable amount of trial-anderror programming to complete my DB2 application.I immediately saw the need fora good DB2programming reference guide. This inspiration ultimately led to the writing of myfirst book, The Developer’s Handbook to DB2 for Common Servers. Since that book was written,DB2 has undergone two more revisions,and several new features have been added to an already rich application development toolset. As I began revising my original book, I discovered that it would be impossible toput a thorough reference forthis toolset in a single book. My editor, Simon Yates, decided to do the next best thing: to put this information in a series of books, where each book addressed a specific aspectof DB2 Universal Database’s rich development toolset.
Introduction
F!FW Who I s This Book For? This book is for anyone whois interested increating DB2 Universal Database applications usingDB2's Administrative Application Programming Interfaces (APIs).The book is written primarily fordatabase application programmersand analysts who are familiar with DB2 and are designing and/or coding software applicationsthat performone or more DB2 administrative tasks. Experienced C/C++ programmers with little experience developingDB2 database applications will benefit most from the material covered in this book. Experienced DB2 A P I application developers whoare familiar with earlier versions of the DB2 product will also benefit from this book, because the book describes in detail new features that areonly availablein the latest release of DB2Universal Database. In either case, this book is meant to be a single resource that provides you with almost everythingyou needto know in order to design and develop DB2database applications usingDB2 APIs. To get the most out of this book, you should have a working knowledge of the C++ programming language. An understanding of relational database concepts and Structured Query Language (SQW will also be helpful, although not crucial.
How This Book I s Organized T h i s book is divided into three major parts. Part 1discusses basic relational database
concepts. Before you can successfully develop a DB2API application, youmust fist have a good understanding of DB2's underlying database architecture and data consistency mechanisms. Two chapters in this section are designed to provide youwith that understanding: Chapter 1and Chapter 2. Chapter 1explains relationaldatabase concepts and describes the components #of a DB2 Universal Database. This chapter also describesthe internal file structures used by DB2 fordata and database object storage. Chapter 2 discusses the mechanisms that DB2 provides formaintaining data integrity, These mechanisms include transactions, isolation levels, row- and table-level locking, and transaction logging. Together,these two chapters laythe groundwork forthe restof this book. Part 2 discusses DB2 application development fundamentals. Once you have a good understanding of DB2'sunderlying database architecture and consistency mechanisms, you also need to understand general database application developmentas it applies to DB2. The two chapters in this section, Chapters 3 and 4, describe the different typesof applications that can be developed for DB2and provide you with an understanding of the methods usedto develop applications using DB2 APIs. Chapter 3 discusses the application development processas it applies to DB2. This chapter describes basic DB2 application design and identifies the main elements 'of a DB2 application. The chapter also explains how the database application development and testing environment are established before the application development process begins.
Introduction Chapter 4 explains how to write Application ProgrammingInterface ( N I ) applications and identifies the main components of a API application. This chapter also describes the steps you must taket o convert A P I application source-code files into executable programs. Part 3 contains information about each DB2 A P I function that can be used in an application. This section is designed to be a detailed A P I function reference. The ten chapters in this section groupthe API functions according to their functionality. Chapter 5 examines the basic set of DB2 APIs that are used to prepare and bind embedded SQL applications, along with the APIs that aretypically usedin all DB2 A P I applications. This chapter also contains a detailed reference section that covers each program preparation and general application development A P I function provided by DB2. Each A P I function describedin this chapter is accompanied bya Visual C++ example that illustrateshow to code the A P I in an application program. Chapter 6 shows how an application canstart, stop, andto a certain extent, control the DB2 Database Manager background server processes. This chapter also contains a detailed reference section that covers each A P I function that can be used to interact with the DB2 Database Manager. Each API function describedin this chapter is accompanied by a Visual C++ example that illustrates how to code the A P I in an application program. Chapter 7 describes how DB2 uses configuration filesto manage system resources. This chapter also contains a detailed reference section that covers each A P I fundion that can be used t o view, modi^, or reset DB2 Database Manager and DB2 database configuration files. Each A P I function described in this chapter is accompanied by a Visual C++ example that illustrates how to code the A P I in an application program. Chapter 8 examines the sub-directories that DB2 uses to keep track of databases, remote workstations (nodes), and DRDA servers. This chapter also containsa detailed reference section that covers eachA P I function that can be used to scan and retrieve entries stored in the database, node, and DCS sub-diredories. Each API function described in thischapter is accompanied by a Visual C++ example that illustrateshow to code the API in anapplication program. Chapter 9 shows how DB2 database tables can be stored in different table spaces, and how data stored in tables can be reorganized so faster access plans can be generated. This chapter also containsa detailed reference sectionthat covers eachA P I function that can be used to manage tables and table spaces. EachA P I function described in this chapter is accompanied by a Visual C++ example that illustrates how to code the API in an application program. Chapter 10 examines the mechanisms that DB2 provides for migrating, backing up, restarting, and restoring databases. This chapter also containsa detailed reference section that covers eachAPI function that can be used to migrate, backup,restart, restore, and perform a roll-forward recoveryon a DB2 database. Each API function described in thischapter is accompanied by a Visual C++ example that illustrates how to code the A P I in an application program.
iI I
I
" . " I
n
,
Introduction
l
Chapter 11shows how data stored in a database table can be exported to an external file, and how data stored in external files can be imported or bulk-loaded into database tables.T h i s chapter also contains a detailed reference section that covers each API function that can be used to move data between a database and one or more external files. EachAPI function describedin this chapter is accompanied bya VisualC++ example that illustrates how to code the API in anapplication program. Chapter 12 looks at database partitioning and node (workstation) management in an multi-partitioned database environment. This chapter also contains a detailed reference sectionthat covers each API function that can be used to manage database nodes and obtain partitioning information. Each API function described in this chapter is accompanied bya Visual C++ example that illustrates how t o code the API in anapplication program. Chapter 13 examines the database activity monitorand two-phase commit processing. This chapter also contains a detailed reference sectionthat covers each API function that can be used to monitor database activity and manually process indoubt transactions that were created when acritical error occurred during two-phase commit processing. EachA P I function describedin this chapter i s accompanied bya Visual C++ example that illustrates how to code the API in an application program. Chapter 14 describes the mechanisms usedby DB2 to work with threads in multithreaded applications.T h i s chapter also contains a detailed reference section that covers each API function that can be used to manage thread contexts. EachAPI function described in this chapter is accompanied by a Visual C++ example that illustrates how to code the CL1 API in an application program.
NOTE: The concepts covered in Chapters 1 3 are repeated in each book in this series. If you have another book in thisseries and are already familiar with thisinformation, you may want to skip these three chapters.
m
larrnsrl About the Examples The example programs provided are an essential part of this book; therefore, it is imperative that they are accurate. To make the use of each DB2 API function call clear, I included onlythe requiredoverhead in each exampleand provided limited emr-checking. I have also tried to design the example programsso they verifythat theAFT function call being demonstrated actually executed as expected. Forinstance,an example programillustrating database cofiguration file modification mightretrieve and display a value before and afterthe modification, to verify that the API function used to modify the data worked COlTeCtly I compiled and tested almost all of the examples in this book with Visual C++ 6.0, running against the SAMPLE database that isprovided with DB2 Universal Database, Version 5.2. AppendixC showsthe steps I used to create the testenvironment and the steps I used to reproduce and test all of the examples providedin t h i s book.
Introduction
m m Feedback and Source Code on theCD I have tried to make sure that all the information and examples providedin thisbook are accurate; however, I am not perfect. If you happen to find a problemwith some of the information in this book or with one of the example programs, please send me the correction so I can makethe appropriate changes in futureprintings. In addition, I welcome any comments you might haveabout this book. The best way to communicatewith me is via e - m d a r-bean8ere~indepring.com. t As mentioned earlier, all the example programs provided in this book have been tested for accuracy: Thus, ifyou type them in exactly as they appear in the book, they should compile and execute successfully.To help you avoid all that typing, electronic copies of these programs have been provided on the CD accompanyingthis book.
Limits of Liability and Warranty Disclaimer
,
Both the publisher and I have used our best efforts in preparing the material in this book. These efforts include obtaining technical information from IBM,as well as developing and testing the example programsto determine their effectiveness and accuracy. We make no warranty of any kind, expressed or implied, with regard to the documentation and example programs provided in this book. We shall not be liable in any event for incidental or consequential damages in connection with or arising out of the furnishing, performance,or use of either this documentation or these example programs.
This Page Intentionally Left Blank
This Page Intentionally Left Blank
DB2 Databbase Architectu[re 2 applications, you Before you begin developing DB2 databasc need to understand the underlying architecture of DB2 Uniuersal Database (UDB), Version 5.2. T h i s cha]pter is designed to introduce you t o the architecture used byDI32 UDB. T h i s chapter begins with a descriptionof the relational Idatabase model and its data-handlingoperations. This i s followed. by an introduction to the dataobjects and support objects that mlake up a DB2 database. Finally, the directory, subdirectory,and :lile-naming conventions used by DB2 forstoring these data a n dIsystem objects are discussed. Let’s begin by defining a relational database man- I agement system.
; l
4
Concepts Database Part 1: Basic
.
The Relational Database DB2 UDB, Version 5.2, is a 32-bit relational database management system. relational A database management system is a database management system that is designed around a set of powerful mathematical conceptsknown as relational algebra. The first relational database model was introduced in theearly 1970s by Mr. E. F. Codd at the IBM San Jose Research Center. This model is based on the following operationsthat are identified in relational algebra: SELECTION-This operation selects one or more records froma table based on a specified condition. PROJECTION-This operation returns a column or columns froma table based on. some condition. JOIN-This operation enables you to paste two or more tables together. Each table must have acommon column beforea JOIN operation can work. UNION-This operation combines two like tables to produce set a of all records found in both tables. Eachtable must have compatible columns before a UNION operation can work.In other words, each field in the first table must match each field in the second table. Essentially, a UNIONof two tables is the same as the mathematical additionof two tables. DIFFERENCE-This operation tells you which recordsare unique to one table when two tablesare compared. Again, each table musthave identical columns before a DIFFERENCE operation can work. Essentially, a DIFFERENCE of two tablesis the same as the mathematical subtractionof two tables. INTERSECTION-This operation tells you which recordsare common to twoor more tables whenthey are compared. This operation involves performingthe UNION and DIFFERENCE operations twice. PRODUCT-This operation combines two dissimilar tables to producea set of all records foundin both tables. Essentially,a PRODUCT oftwo tables is the same as the mathematical multiplication of two tables. The PRODUCT operation can often produce unwanted side effects, however, requiring you to use the PROJECTION operation to clean them up.
As you can see, in a relational database data is perceived to existin one or more twodimensional tables. These tablesare made up of rows and columns, where each record (row) is divided into fields (columns) that contain individual pieces of information. Although data is not actually stored this way, visualizing the data aas collectionof twodimensional tables makesit easier to describe data needs in easy-to-understand terms.
M
pmsll
Relational Database Objects A relationaldatabase system is more than justa collection of two-dimensional tables. Additional objects existthat aid in data storage and retrieval, database structure control, and database disaster recoveW. In general, objects are defined as items about which DB2 retains information. With DB2, two basic types of objects exist: data objects and support objects.
Chapter 1:DB2 Database Architecture Data objects are the database objects that are used to store and manipulate data. Data objects also control how user data (and some system data) is organized. Data objects include B Databases
U Table Spaces U Tables
U User-Defined Data Types (UDTs) B User-Defined Functions (UDFs) B Check Constraints
U Indexes U Views U Packages (accessplans)
Triggers B Aliases B Event Monitors
Databases A database is simply a set of all DB2-related objects. When you create a DB2 database, you are establishing an administrative entity that provides an underlying structure for an eventual collection of tables, views, associated indexes, etc.-as well as the table spaces in which these items exist. Figure 1-1 illustrates a simple database object. The database structure also includes items such as system catalogs, transaction recovery logs, and disk storage directories. Data (or user) objeds arealways accessed from within the underlying structure of a database.
Table Spaces A table space logically groups (or partitions) data objects such as tables, views, and indexes basedon their datatypes. Upto three tablespaces can be usedper table. Typically, the first table space is used for table data(by default),while a second table space is used as a temporary storage area for Structured Q u e y Langzuzge (SQL) operations (such as sorting, reorganizing tables, joining tables, and creating indexes). The third table space is typically used forlarge object (LOB) fields. Table spacesare designed to provide a levelof indirectionbetween user tables and the database in which they exist. Two basic types of table spaces exist database managed spaces (DMSs) and system managed spaces (SMSs). For SMS-managed spaces, each storage space is a directory that is managed by the operating system's file manager system. For DMS-managed spaces, eachstorage space is either a fixed-size, pre-allocated fileor a specific physical device (such as a disk) that i s managed by the DB2 Database Manager.As mentioned earlier,table spaces can also allocate storage areas for LOBsand can control the device, file, or directory where both LOBs and table data aret o be stored.Table spaces can span
Part 1: Basic Database Concepts DATABASE
Figure 1-1 Database object and its related data objects multiple physical disk drives, and their size can be extended at any time (stopping and restarting the databasei s not necessary). Figure1-2 illustrates how you can use table spaces to direct a database object to store ita table data on one physical disk drive-and store the table’s corresponding indexes on another physical disk drive.
Chapter 1: DB2 Database Architecture
1
PHYSICAL DISK DRIVE 1
-
DATABASE
U B
I
P
TABLESPACE
'
7
PHYSICAL DISK DRIVE L
l
rr INDEXES
-
A
TABLESPACE
Figure 1-2 Using table spaces to separate the physical storage of tables and indexes
NOTE: You should recognize that the table space concept implemented by DB2 Universal Database is differenth m the table space concept used byDB2 for OSI390.
Tables The table is the most fundamentaldata object of a DB2 database. All user datais stored in and retrieved from one or more tables in a database. Two types of tables can exist in a DB2 database: base tables and result tables. Tables that are created by the user to store user data are known as base tables. Temporary tables that are created (and deleted)by DB2 fiom oneor more base tables to satisfythe result of a query are known as result tables. Each table contains an unordered collection of rows, and a k e d number of columns. "he definitionof the columns in the table makes up the table structure, and therows contain the actual table data. The storage representation of a row is called a record, and the storage representation of a column is called a field. At eachintersection of a row and column in a database tableis a specific data item calleda value. Figure 1 3 shows the structure of a simple database table.
l II
1
k"l 8
L " . .. -.
I
."
! : .
Concepts P Database art 1: Basic
,
.
DATABASE TABLE A
-
051061
061061
1009
DAY HEPBURN ROBINSON HOLDEN
1010
CRAWFORD
1004 1005 1006
RECORD (ROW)
Figure 1-3
COOPER BOGART BACALL
1003
1007 1008
101151 11118C 091101 1 m r 031021
~~
Simple database table
DATA TYPES Each columnin a table is assigned a specificdata type during it$creation. This action ensures that only data of the correct type is stored in the table's columns. The following data types are available in DB2: SMALLIN!I"A small integer is a binary integer with a precisionof 15 bits. The range of a small integer i s -32,768 to +32,767. INTEGER (INT)-An integer is a large binary integer with a precision of 31 bits. The range of an integer is -2,147,483,648 to +2,147,483,647. BIGINT-A big integer is a large binary integer with a precisionof 63 bits. F'LOAT (REAL)-A single-precision, floating-point numberis a 32-bit approximation of a real number. Therange of a single-precision, floating-point number is 10.0, to 10.0 E+38. DOUBLE-A double-precision, floating-pointnumber is a 64-bit approximation of a real number. The number can be zero or can range from -1.79769E"308to -2.225E-307 and 2.225E307 to 1.79769E+308. DECIMAL (DEC, NUMERIC, NUM)-A decimal value is a packed decimalnumber with an implicit decimal point. The position of the decimal pointis determined by the precision and scale of the number. Therange of a decimalvariable or the
Chapter 1:Architecture DB2 Database
.
9 ~~
numbers in a decimal columnis -n to +n, where the absolute valueof n is the largest number that can be represented with the applicable precisionand scale. CHARACTER (CHAR)-A character string isa sequence of bytes. Thelength of the string is thenumber of bytes in thesequence and must be between 1and 254. VARCHAR-A varying-length character string isa sequence of bytes in varying lengths, up to 4,000 bytes. LONG VARCHAR-A long, varying-lengthcharacter string is a sequence of bytes in varying lengths, up to 32,700 bytes. GRAPHIC-A graphic string isa sequence of bytes that represents double-byte character data. The length of the stringis the number of double-byte characters in the sequence and must be between 1and 127. VARGWHIC-A varying-length graphicstring is a sequence of bytes in varying lengths, up t o 2,000 double-bytecharacters. LONG VARGRAPHIC-A long, varying-length graphicstring isa sequence of bytes in varying lengths, up t o 16,350 double-bytecharacters. BLOB-A binary large object sting is a varying-length string, measured in bytes, that can be up to 2GB (2,147,483,647 bytes) long. A BLOB is primarily intended to hold nontraditional data, such as pictures, voice, and mixed media. BLOBScan also hold structured data for user-defined typesand functions. CLOB-A character large object string is a varying-length string measured in bytes that can be up to 2GB long. A CLOB can store large, single-byte character strings or multibyte, character-baseddata, such as documents written with a single character set. DBCLOB-A double-byte character large object string is a varying-length string of double-byte characters that can be up to 1,073,741,823 characters long. A DBCLOB can store large, double-byte, character-baseddata, such as documents written with a single character set. A DBCLOBis considered to be a graphic sting. DATE-A date is a three-part value (year, month, and day) designating a calendar date. The range of the year part is0001 to 9999, the range of the month part isone to 12, and the range of the day part isone to n (28,29,30, or 31),where n depends on the month and whether the year value corresponds to a leap year. TIME-A time is a three-part value (hour,minutes, and seconds) designating a time of day under a 24-hour clock. The range of the hour part is zero to 24, the range of the minutes part is0 to 59, and the range of the seconds part isalso 0 to 59. Ifthe hour part is setto 24, the minutes and seconds must be 0. TIMESTAMP-A timestamp is a seven-part value (year, month, day, hour, minutes, seconds, and microseconds) that designates a calendar date and time-of-day under a 24-hour clock. The ranges for each part are thesame as defined for the previous two data types, whilethe range for the fractional specification of microseconds is 0 to 999,999. DISTINCT W E - A distinct type is a user-defined data type that shares its internal representation (source type) with one of the previous data types-but is considered
Part 1: Basic Database Concepts to be a separate, incompatible type for most SQL operations.For example, a user can definean AUDIO data type for referencingexternal .WAV files that use the BLOB data type for their internalsource type.Distinct types do not automaticay acquire the functions and operators of their source types, becausethese items might no longer be meaningful. However, user-defined functions and operators can be created and applied to distinct types to replace this lost functionality. For more informationabout DB2 data types, refer to the IBM DB2 Universal Database SQL Reference, Version5.2 product manual.
CHECK CONSTRAINTS When youcreate or alter a table, you can alsoestablish restrictions on data entry for one or more columns in the table. These restrictions, known as check constraints, exist to ensure that none of the dataentered (or changed) in a table violates predefined conditions. Three types of check constraints exist, as shown in thefollowing list Unique Constraint-A rule that prevents duplicate values from beingstored in one or more columnswithin a table Referential Constraint-A rule that ensures that values stored in one or more columns in a table can be foundin a column of another table n b l e Check Constraint-A rule that sets restrictions on all data thatis added to a specific table The conditions defined fora check constraint cannot contain any SQL queries, and they cannot refer to columns within another table. Tables can be defined with or without check constraints, and check constraints can definemultiple restrictions on the data in a table. Check constraints are defined in the CREATE TABLE and ALTER TABLE SQL statements. If you define a check constraint in the ALTER TABLE SQL statement for a table that already contains data, theexisting data will usually be checkedagainst the new condition before the ALTER TABLE statement can be successfully completed. You can, however, placethe table in a check-pending state with the SET CONSTRAINTS SQL statement, whichenables the ALTER TABLE SQL statement to execute without checking existing data. If you place a table in a check-pending state, you must execute the SET CONSTRAINTS SQL statement again after the table has been altered to check the existing data and return the table t o a normal state.
Indexes An in&x is an ordered set of pointers to the rows of a base table. Each index is based on the values of data in one or more columns(refer to the definition of key, later in this section), and more than one index can be defined for a table. An index uses a balanced binary tree (a hierarchical data structure in which each elementhas at most one predecessor but can have many successors)to order the values of key columns in a table. When you indexa table by oneor more of its columns, DB2can accessdata directly and more efficiently because the index is ordered by the columns to be retrieved. Also, because an index is stored separately from its associated table, the index providesa way to define keysoutside of the table definition. Once youcreate an index, the DB2 Data-
Chapter 1:DB2 Database Architecture base Manager automatically builds the appropriate binary tree structureand maintains that structure. Figure 1-4 shows a simple table and its corresponding index. DB2 uses indexes t o quickly locate specific rows (records) in a table. If youcreate an index of frequently uged columnsin a table, you will see improved performanceon row access and updates. A unique index(refer to the following paragraph) helps maintain data integrity by ensuring that each rowof data ina table is unique. Indexesalso provide greater concurrency when more than one transaction accesses the same table. Because row retrieval is faster, locks do not last as long. These benefits, however,are not without a price. Indexesincrease actual disk-space requirements and cause a slight decrease in performance whenever an indexed table's data is updated, because all indexes defined forthe table must also be updated. A key is a column (or set of columns) in a table or index that is used to identify or access a particular row (or rows) of data. A key that i s composed of more than one column is called a composite K e y . A column can be part of several composite keys.A key that i s defined in such a way that thekey identifies a single row of.data within a table is called a unique key. A unique key that i s part of the definition of a table is called a primary key. A table can haveonly oneprimary key, and the columns of a primary key cannot contain null (missing) values.A key that references (or points to) a primary key in another table is called a foreign key. A foreign keyestablishes a referential link to a primary key, and the columns defined in each key must match. In Figure 1-4, the EMPID columnis the primary key for Table A.
INDFXA
ROW 1 ROW 2 ROW 3 ROW 4 ROW 5 ROW 6 ROW 7 ROW 8 ROW 9 ROW 10 ROW 11
Figure 1-4 Simple database table and its corresponding index, where the EMPID column is the primary key
i
I
12
i j ,
.
'
:
I .
Part 1: Basic Database Concepts
Views A view is an alternative way of representing data that exists in one or more tables. Essentially, a view is a named specificationof a result table. The specificationis a predefined data selection that occurs whenever the view is referenced in an SQL statement. For this reason, you can picture a view as having columns and rows, just like a base table. In fact, a view can be usedjust like a base table in most cases. Althougha view looks likea base table, a view does not existas a table in physical storage-so a view does not contain data. Instead, a view refers to data stored in other base tables. (Although a view might referto another view, the reference is ultimately to data stored in one or more base tables.) Figure 1-5 illustrates the relationship between two base tables and a view. TABLE B
TABLEA
VIEW A
Figure 1-5 In this figure, a view is created from two separate tables. Because the
EMPID column is commonin both tables, the EMPID column joins the tables to create a single view.
Chapter 1:DB2 Database Architecture A view can include any numberof columns from one or more base tables. A view can also include any numberof columns from other views, so a view can be a combination of columns from both viewsand tables. When the column of a view comes from a column of a base table, that column inherits anyconstraints that apply to the column of the base table. For example, if a view includesa column that is a unique key for its base table, operations performed against that view are subject to the same constraint as operations performed against the underlying base -table.
Packages (Access Plans) A package(or access plan) is an object.that contains control structures (known as sections) that areused to execute SQL statements. If an application program intends to access a database using static SQL,the application developermust embed the appropriate SQL statements in the program source code. When the program source code is converted to an executable object(static SQL)or executed (dynamicSQL),the strategy for executing each embedded SQL statement is stored in a package as a single section. Each section is the bound (or operational) form of the embedded SQL statement, and this form contains information such as which index to use and how to use the index. When developing DB2 UDB database applications, you shouldhide package creation from users whenever possible. Packages and binding are discussed in more detail in Chapter 3, “Getting Started with DB2 Application Development.”
Triggers A trigger is a set of actions that are automatically executed (or triggered) when an INSERT, UPDATE, or DELETE SQL statement is executed against a specified table. Whenever the appropriateSQL statement is executed, the trigger is activated-and a set of predefined actionsbegin execution.You can use triggers along with foreign keys(referential constraints) and check constraints to enforce data integrity rules. You can also usetriggers to apply updates to other tables in the database, to automatically generate and/or transform values for inserted or updated rows, and to invoke userdefined functions. When creating a trigger, in order to determine whenthe trigger should beactivated, you must firstdefine and then lateruse the following criteria: Subject table-The table for whichthe trigger is defined Trigger event-A specific SQL operation that updates the subject table (could be an INSERT, UPDATE, or DELETE operation) Activation time-Indicates whether the trigger should be activated before or aRer the trigger event is performed on the subject table Set ofaffected rows-The rows of the subject table on which the INSERT, UPDATE, or DELETE SQL operation is performed Trigger granularity-Defines whether the actions of the trigger will be performed once forthe whole SQL operation or once for eachof the rows in the setof affected rows
Part 1: Basic Database Concepts Wggered action-Triggered action is an optional search condition and a set of SQL statements that are to be executed wheneverthe trigger is activated. The triggered action is executed only ifthe search condition evaluates to TRUE. At times, triggered actions might need to refer to the original values in the set of affected rows. "his reference can be made with transition variables and/or transition tables. Transition variables are temporary storage variables that use the names of the columns in the subject table and are qualified by a specified name that identifies whether the reference is t o the old value (prior t o the SQL operation) or the new value (after the SQL operation). Transition tables also use the names of the columns of the subject table, but they have a specifiedname that enables the complete set of affected rows to be treated as a single table.As with transition variables, transition tables can be defined for both the old values and the new values. Multiple triggers can be specified for a single table. The order in which the triggers are activated is based on the order in which they were created, so the most recently created trigger will be the last trigger to be activated. Activating a trigger that executes SQL statements may causeother triggers to be activated (or even the same trigger to be reactivated). "his event is referred to as trigger cascading.When trigger cascading occurs, referential integrity delete rules can also be activated, thus a single operation can significantly change a database. Therefore, whenever you create a trigger, make sure to thoroughly examinethe effects that thetrigger's operationwill have on all other triggers and referential constraints defined forthe database.
Aliases An alias isan alternate name for a table or view. Aliases can be referenced in the same way the original table or view is referenced. An alias can also bean alternatename for another alias. This process of aliases referring to each other is known as aliaschaining. Becausealiases are publicly referenced names, no special authority or privilege is needed to use them-unlike tables and views.
Event Monitors An event monitor observes each event that happens to another specified object' and records all selected events to either a named pipe or to an external file. Essentially, event monitorsare "tracking" devicesthat inform other applications (either via named pipes or files) whenever specified event conditions occur. Event monitors allow you to obseme the events that take place in a database whenever database applications are executing against it. Once defined, event monitors can automatically be started each time a database is opened.
Schemas All data objects are organized (bythe database administrator) into schemas, which provide a logical classificationof the objects in the database. Object names consistof two parts. The fist (leftmost) part iscalled the qualifier, or schema, and the second (right-
Chapter 1:DB2 Database Architecture most) part iscalled the simple (or unqualified)name. Syntactically, these two parts are concatenated as a single string of characters separated by a period. Whenan object such as a table space, table, index, view, alias, user-defined data type, user-defined function, package, event monitor,or trigger is created, that object is assigned to an appropriate schema basedon its name. Figure1-6 illustrates how a table is assigned to a particular schema during the table creation process. NOTE: If no schema is specified when an object is created, the DB2 Database Manager
uses the creator’s userID as the default schema. This section completes the discussion of data objects. Now let’s examine DB2 support objects. Support objects are database objects that contain descriptionsof all objects in the database, provide transaction and failure support, and control system resource usage. Support objects include the following items: H System catalog tabledviews
Log files and the Recovery History file DB2 Database Manager configuration fdes H Database configuration fdes
System Catalog Views DB2 creates and maintains a set of views and base tables for each database created. These views and base tables are collectively known as the system catalog.The system PAYROLL
(SCHEMA) DATABASE
“CREATE TABLE PAYROLL.STAFF”
Figure 1-6 Implementing schemas with the CREATE SOL statement
Part 1: Basic Database Concepts catalog consistsof tables that contain accurate descriptions of all objeds in the database
at all W.DB2 automatically updates the system catalogtables in response to SQL data definition statements, environment routines,and certain utility routines. “he catalog viewsare similar to any other database views, with the exception that they cannot be explicitlycreated, updated (withthe exception of some specific updateable views), or dropped. You can retrieve data in the catalog viewsin thesame way that you retrieve data from any other view in thedatabase. For a completelisting of the DB2 catalog views, refer to the IBM DB2 Universal Database SQL Reference, Version 5.2product manual.
Recovery Log Files and the Recovery HistoryFile Database recovery logfiles keep arunning record of all changes madeto tables in a database, and these files serve two important purposes. First, they provide necessary support for transaction processing. Becausean independent record of all database changes is written to the recovery log files, the sequence of changes making up a transaction can be removed from the database if the transaction is rolled back. Second, recovery log files ensure that a system power outageor application error will not leavethe database in an inconsistent state. In the event of a failure, the changes that have been made,but that have not been made permanent (committed)are rolled back.Furthermore, all committed transactions, which might not have been physically written t o disk, are redone. Database recovery loggingis always active and cannot be deactivated. These actions ensure that theintegrity of the database is always maintained. You can also keep additional recovery log files to provide forward recovery in the event of disk (media)failure. The roll-forward database recovery utility uses these additional database recovery logs, called archived logs, to enable adatabase to be rebuilt to a specific point in time. In addition to using the information in the active database recovery logto rebuild adatabase, archived logsare used to reapply previous changes. For roll-forward database recovery to work correctly,you are required to have both a previous backup versionof the database and a recovery log containing changes made to the database since that backup was made.The following list describes the types of database recovery logsthat can exist: Active log files-Active log files contain information for transactions whose changes have notyet been written to the database files. Active log files contain information necessary to roll backany active transaction not committed during normal processing. Active log files also contain transactions that arecommitted but are not yet physicallywritten from memory(bufferpool) to disk (database files). Online archived log files-An activity parallel to logging exists that automatically dumps the active transaction log fileto an archive log file whenevertransaction activity ceases, when the active log file is closed, or when the active log file gets full. An archived logis said to be “online” whenthe archived log is stored in the database log path directory. Ofline archived log files-Archived log filescan be stored in locations other than the database log path directory.An archived log fileis said to be “offline” when it is not stored in the database log path directory.
Chapter 1:DB2 Database Architecture " I
\%
'
..
NOTE: If an online archived logfile does not contain anyactive transactions, thi file will be overwritten the next time an archive log file is generated. On the other h a n d , if an archived log file contains active transactions,the file will not be overwritten by other active transaction log dumps until all active transactions storedin the file have been made p e m n e n t . If youdelete an active log file, the database becomes unusable and must be restored before the database can be used again. Ifyou delete an archived log file(either online or offline) roll-forward recovery will only be possible up to the point in time coveredby the log filethat was written to before the deleted log file was created. The recovery history file contains a summary of the backup informationthat is used to recover part or all of the database to a s@c point in time. A recovery history fileis automatically mated when a database is created, andthe file is automatically updated whenever the database is backed up, restored, or populated withthe LOAD operation.
Configuration Files Similar t o all computer software applications, DB2 UDB uses system resources both when it is installed and when it is running. In most cases,run time resource management (RAM and shared control blocks, for example) are managed by the operating system (OS). If, however,an application is greedy for system resources, problems can occur for boththe application and for other concurrently running applications. DB2 provides two sets of configuration parametersthat can be used to control its consumption of system resources. Oneset of parameters that is used for the DB2 Database Manager itself exists in a DB2 Database Manager configuration file. This file contains values that are to be used to control resource usage when creating databases (database code page, collating sequence, and DB2 release level, for example). This file also controls system resources that are used by all database applications(astotal shared RAM, for example). A second set of parameters exists for each DB2database mated and is stored in a database configuration file. This file contains parameter values that are used to indicate the current state of the database (backup pending flag, database consistency orflag, roll-forward pending flag, for example) and parameter values that d e h e the amount of system resources the database can use (buffer pool size, database logging, or sort memory size, for example). A database configuration file exists for each database, so a changeto one database codguration does not havea corresponding effect on other databases.By fme-tuning thesetwo configuration files, you can tailor DB2 for optimum performance in any numberof OS environments. For more information about DB2 configuration parameters, file referto the IBA4 DB2 Universal Database Administration Guide, Version 5.2 product manual.
DB2 Database Directories DB2 UDBuses a set of directories forestablishingan environment, storing data objeds, and enabling data access to both localand other remote workstations (nodes)and databases. Theset of directories usedby DB2 contain the following items:
H One or more physicaldatabase directories One or more volume diredories
!
j
L "
18__
Part 1: Basic Database Concepts A system directory A workstation (node) directory A database connection services directory These directories define the overall DB2 Database Manager operating environment. Figure 1-7 illustrates DB2's directory structure.
SYSTEM DIRECTORY
I 1 WORKSTATION VOLUME
PHYSICAL, DATABASE DIRECTORIES
Figure 1-7
DATABASE DIRECTORY
CONNECTION DIRECTORY SERVICES DIRECTORY
D625 directory structure
Physical Database Directory Each time a database is created, the DB2 Database Manager creates aseparate subdirectory in which to store control files (such as log header files)and to allocate containers in which default table spaces are stored. Objects associated withthe database are usually storedin the database subdirectory,but they can be stored in other various locations -including system devices. All database subdirectories are created withinthe instance defined in the DB2INSTANCE environment variableor within the instance to which the user application has been explicitlyattached.The naming scheme used forDB2 a instance or UNM Platforms is inrrtall-patb/$DB2INSTANCE/NODgnnnn.The naming scheme used on Intel platforms is drive_Ietter:\$DB2INSTANCE\NODEnnnn.In both cases, NODEis the node identifier in a partitioned database environment whereNODEOOOOis the first node, NoDEoool is the second node,and so on. The naming scheme fordatabase subdirectories created within an instance is sQLoOoOl through s ~ ~ n n n nwhere n, the number for pllpnn increases each time a new database is created. For example,directory sQLoooo1 contains all objects associated with the first database created, S Q L O O O Ocon~
Chapter 1: DB2 Database Architecture tains all objects forthe second database created, and so on. DB2 automatically creates and maintains these subdirectories.
Volume Directory In addition to physical database directories, a volume directory existson every logical disk drive available (on a single workstation)that contains oneor more DB2 databases. This directory contains one entry for eachdatabase that is physically stored on that particular logical disk drive, The volume directory is automatically created when the first database is created on the logical disk drive, and DB2 updates its contents each time a database creation or deletion event occurs. Each entry in the volume directorycontains the following information: W The database name, as provided with the CREATE DATABASE command
The database alias name (which is the same as thedatabase name) W The database comment, as provided with the CREATE DATABASE command
The name of the root directoryin which the database exists The productname and release number associatedwith the database Other system information, including the code page the database was created under and entry type (whichis always HOME) W The actual number of volume database directories that exist on the workstation, which is the number of logical disk drives on that workstation that contain oneor more DB2 databases
System Directory The systemdatabase directory is themaster directory fora DB2 workstation.This directory contains one entry for each local and remote cataloged database that can be accessed by the DB2 Database Manager froma particular workstation. Databases are implicitly cataloged when the CREATE DATABASE command or API function is issued and can also be explicitly cataloged withthe CATALOG DATABASE command or API function. The system directory existson the logical disk drive wherethe DB2 product software is installed. Each entry in thesystem directory containsthe following information: W The database name provided with the CREATE DATABASE or CATALOG DATABASE
command or API function W The database alias name (which is usually the same as the database name) W The database comment, as provided with the CREATE DATABASE or CATALOG
command or API function The logicaldisk drive on which the database exists, if it is local The nodename on whichthe database exists, ifit is remote Other system information, including where validation of authentication names (user IDS)and passwords will be performed DATABASE
i i
1 i
20
r"l I
/
ParConcepts t Database 1: Basic
i ' ,
Workstation Directory The workstation or node directory contains oneentry for each remotedatabase server workstation that can be accessed. The workstation directory alsoexists on the logical disk drive wherethe DB2 product softwareis installed. Entries in the workstation directory are used in conjunction withentries in the system directoryto make connectiuns to remote DB2 UDBdatabase servers. Entries in the workstation directoryare also used in conjunction with entries in thedatabase connection services directoryto make connections to hosts (OSl390, AS1400,etc.) database servers. Each entry in the workstation directory containsthe following information: B The nodename of the remote server workstation wherea DB2 database exists B The node name comment
B The protocolthat will be used to communicate with the remote server workstation B The typeof security checking that will be performed bythe remote server
workstation W The hostnameor address of the remote server H The servicename or port number for the remote server
DatabaseConnectionServicesDirectory
,
A database connection services directory onlyexists if the DB2 Connect producthas been installed on the workstation. This directory exists on the logical disk drive where the DB2 Connect product software is installed. The database connection services directory contains one entry for each host (OS1390, ASl400, etc.) database that DB2 can access via the distributed relational database architecture (DRDA) services. Eachentry in theconnection services directorycontains the following information: B The localdatabase name W The target database name
W The database comment W The applicationrequester library file that executes the DRDA protocolto
communicate with the host database B The user-defined nameor nickname forthe remote server database B The database system usedon the remote server workstation
B Other system information, includinga defaults override parameter string that defines SQLCODE mapping requirements, date and time formatting to use, etc.
\*
!
j
Chapter 1: DB2 Database Architecture
4
e
NOTE: l b avoid potential problems, do not create directories that use the same naming scheme as the physical database directories, and do not manipulate the volume, system, node, and databaseconnection services directories that have been created by DB2.
The goal ofthis chapter is to provide youwith an overview of the underlying architecture of a DB2 Universal Database (UDB), Version 5.2 database. You should now understand therelational database model and be familiarwith the followingdata objects and support objects: W Data objects W Databases W Table spaces W Tables W User-Defined Data Types (UDTs)
W User-Deiined Functions (UDFs) W Check constraints W Indexes W Views
.
W Packages (access plans)
W Triggers
m Aliases
W Event monitors W Support objects W System catalog views W Recovery log filesand the Recovery History file
W DB2 Database Manager configuration file W Database configuration files
Finally, you should beaware of how DB2UDB creates and uses the follofigdirectories and subdiredories on your storage media: W Physical database directories W Volume diredories
W System directory W Workstation diredory
Database Connection Services directory
!
1
I
A j ;
22. j j
PartDatabase 1: Concepts Basic You should be comfortablewith these basic DB2 database concepts before you begin your database application design work (and especially before youactually begin writing the source code for yourapplication).The next chapter continues to present these concepts bydiscussingthe database consistency mechanismsavailable in DB2 Universal Database, Version 5.2.
Consistency Mechanisms Once you understand the underlying architecture of DB2 Universal Database, you should become familiar with the mechanisms DB2 uses to provide and maintain dataconsistency. T h i s chapter is designed t o introduce you to the concepts of data consistency and to the threemechanisms DB2 uses to enforce consistency: transactions, locking, and transaction logging. The first part of this chapter defines database consistency and examines some of the requirements a database management system must meet to provide and maintain consistency. This part is followed bya close lookat the heartof all data manipulation: the transaction. Next, DB2’s lockingmechanism is described and how that mechanism is used by multiple transactions working concurrently to maintain data integrityis discussed.Finally, this chapter concludes with a discussion of transaction logging and the datarecovery process used by DB2 to restore data consistancyif application or system failure
I"1 2 4
j i,
Part 1: Basic Database Concepts
What I s Data Consistency? The best way to define data consistency is by example. Suppose your company o wa chain of restaurants, and you have adatabase designed to keep track of supplies stored in each of those restaurants. To facilitate the supplies purchasing process, your dahbase contains an inventory table for each restaurant in thechain. Whenever supplies are received or used by a restaurant, theinventory table for that restaurant is updated. Now, suppose some bottles of ketchup are physically moved from one restaurant to another. The ketchup bottle count value in the donating restaurant's inventory table needs to be lowered, and the ketchup bottle count value in the receiving restaurant's inventory table needs to be raised to accurately represent this inventory move. Ifa user lowers the ketchup bottle count from the donating restaurant's inventory table but fails to raise the ketchup bottle countin thereceiving restaurant's inventory table, the data has become inconsistent. Now, the total ketchup bottle count for the entire chain of restaurants i s incorrect. Data can become inconsistent if auser fails to make all necessary changes(as in the previous example), if the system crashes while the user is in the middle of making changes, or if an application accessingdata stops prematurely for some reason. Inconsistency can also occur when several users are accessing the same data at the same time. For example, oneuser might read another user's changes before the data has been properly updated and take some inappropriate action-or make an incorrect change based on the premature data values read. To properly maintain data consistency, solutionsmust be provided forthe followkg questions: How can you maintain generic consistencyof data if you donot know what each individual data owner or user wants? ! How can YOU keep a single application from accidentally destroying data consistency?
m How can you ensure that multiple applications accessingthe same data a t the same time will not destroydata consistency?
If the system fails while a database is inuse, how can the database be return4 to a consistentstate? DB2 provides solutionsto these questions with its transaction support, locking, and logging mechanisms.
"R P M Transactions A trunsaction, or a unit of work, is a recoverable sequenceof one or more SQL operations grouped together as a single unit within an application process. Theinitiation and termination of a transaction define the points of data consistencywithin an applicationprocess. Either all SQL operations within a transaction are applied to the datasource, or the effects of all SQL operations within a transaction are completely "undone."
l
!
'Chapter 2: Database Consistency Mechanisms
i
" .
25 " "
I
i
Transactions and commitment control are relational database concepts that have been around forquite some time. They provide the capability to commit or recover from pending changes madeto a database in order to enforce data consistency and integrity. With embedded SQL applications, transactions are automatically initiated when the application process is started. With OpenDatabase Connectivity (ODBC) and Call-Level Interface (CLI), transactions are implicitly started whenever the application begins working witha data source. Regardless of how transactions are initiated, they are terminated when they are either committed or rolled back. Whena transaction is committed, all changes madeto the datasource sincethe transaction was initiated are made permanent.When a transaction is rolled back,all changes madeto the datasource sincethe transaction was initiated are removed, and the.data in the data source is returned to its previous state (before the transaction began). In either case, the data source is guaranteed to be in a consistent state atthe completion of each transaction. A commit or roll back operation only affectsthe datachanges madewithin the transaction they end. As long as data changesremainuncommitted, other application processes are usually unable to see them,and they can be removed with the roll back operation. However, once data changes are committed, they become accessibleto other application processesand can no longer be removed bya roll back operation. A database application program can do all of its work in a single transaction or spread its work overseveral sequential transactions. Data used within a transaction is protected from being changed or seen by other transactions through various isolation levels. Transactions provide generic database consistency by ensuring that changes become permanent only when youissue a COMMITSQL statement or via APIcalls defined within a Transaction Manager.Your responsibility, however,is to ensure that the sequence of SQL operations in each transaction results in a consistent database. DB2 then ensures that each transaction is eithercompleted (committed)or removed (rolled back) as a single unit of work. If a failure occurs before the transaction is complete, DB2 will back out all uncommitted changes to restore the database consistency that DB2 assumes existed whenthe transaction was initiated. Figure 2-1 shows the effectsof both a successful transaction and a transaction that failed.
lwl l eal H Concurrency and Transaction
Isolation Levels So far, we have only lookedat transactions from a single-user data source point-of-view. With single-userdata sources, each transactionoccurs serially anddoes not haveto contend with interferencefrom other transactions. With multi-user data sources, however, transactions can occur simultaneously, and each transactionhas the potential to interfere with another transaction. Transactions that have the potential of interfering withone another are said to be interleaved,or parallel, transactions. Transactions that runisolated from each otherare said to be seriulizable, which means that the results of running them
Part 1: Basic Database Concepts A SUCCESSFUL. TRANSACTION Locks are acquired at theStart of the
START TRANSACTION
Transaction.
SQL COMMAND SQL COMMAND
When theCO" IT SQL statementis executed, all changesare made permanent.
SQL COMMAND
corn END TRANSACTION
U
Locks are released at the End of the Transaction.
AN UNSUCCESSFUL TRANSACTION
START TRANSACTION COMMAND SQL
rlr
Locks are acquired at the Start of the
Transaction.
- I
occurs, the When an Error Condition R0 LLBACK SQL statementis executed and a llchanges made to the database are removed.
ROLLBACK Locks are released at the End of the Transaction.
END TRANSACTION
U Figure 2-1 Events thattake place during the executionof a successful andan unsuccessful transaction
simultaneously are the same as the results of running them one right after another (serially). Ideally,all transactions should be serializable. So why should transactions be serializable? Consider the following problem. Suppose a salesman is entering orders on a database system at the same time a clerkis sending out bills. Now, suppose the salesman enters an order from Company X but does not commit the order (the salesman is still talking to the representative from CompanyX). While the salesman is on the phone, the clerk queriesthe database for alist of all outstanding orders, seesthe order for Company X,and sends Company X a bill. Now, suppose the representative from CompanyX decides to cancel the order. Thesalesman rolls back the transaction, because the representative changed his mind and the order information was never committed. A week later, Company X receives a bill forpart a it never ordered. If the salesman's transaction and the clerk's transaction had been isolated from each other (serialized),this problem would never have occurred. Either thesalesman's transaction would have finished before the clerk's transaction started, or the clerk's
Chapter 2: Database Consistency Mechanisms
27
transaction would have Gnished before the salesman's transaction started. In either case, CompanyX would not have receiveda bill. When transactions are not isolated from each other in multi-user environments, the following three types of events (or phenomena) can occuras aresulk H Dirty reads-This event occurs whena transaction reads data that has not
yet been committed.For example: Transaction1changes a row of data, and Transaction 2 reads the changed row before Transaction 1commits the change. If Transaction 1rolls backthe change, then Transaction 2 will have readdata that is considered never to have existed. H Nonrepeatable reads-This event occurs when a transaction reads the same row of data twice but receives differentdata values each time.For example: Transaction 1reads a row of data, and Transaction 2 changes or deletes that row and commitsthe change. If Transaction1attempts to reread the row, Transaction 1retrieves different data values (ifthe row was updated) or discovers that the row no longer exists (if the row was deleted). H Phantoms-This event occurs whena row of data matches a search criteria but
initially is not seen.For example: Transaction1reads a setof rows that satisfy some search criteria, and Transaction2 inserts anew row matching Transaction l's search criteria. If Transaction 1re-executes the query statement that produced the original set of rows, a different set of rows will beretrieved. Maintaining database consistency and data integrity while enablingmore than one application to access the same data at the same time is known as concurrency. DB2 enforces concurrency by using fourdifferent transaction isolation levels.An isolation level determines how data islocked or isolated from other processes whilethe data i s being accessed.DB2 supports the following isolation levels: H Repeatable read H Read stability H Cursor stability H Uncommitted read
Repeatable Read The repeatable read isolation level locks all the rows an application retrieves within a single transaction.If youuse the repeatable read isolation level, SELECT SQL statements issued multiple times withinthe same transaction will yield the same result. A transaction running under the repeatable read isolation level retrieve can and operateon the same rows as many timesas needed until thetransaction completes. However,no other transactions can update, delete, or insert arow (which would affect the result table being accessed) until the isolating transaction terminates. Transactions running under the repeatable read isolation level cannot see uncommitted changes of other transactions. The repeatable read isolation level does not allow phantom rows to be seen.
Part 1: Basic Database Concepts
Read Stability The read stability isolation level locks only those rows that an application retrieves within a transaction. This feature ensures that any row read by a transaction is not changed by other transactions until the transaction holding the lock is terminated. Unfortunately, if a transaction using the read stability isolation level issues the same query more than once, the transaction can retrieve new rowsthat were entered by other transactions that now meet the search criteria. T h i s event occurs because the read stability isolation levelensures that all data retrieved remains unchanged until thetime that thetransaction sees the data,even when temporary tables or row blocking is used. Thus, the read stability isolation level allows phantom rows to be seen and non-repeatable reads to occur.
Cursor Stability The cursor stability isolation level locks any row being accessed bya transaction, as long as thecursor is positioned on that row. This lock remains in effect until thenext row is retrieved (fetched)-or until the transaction is terminated. If a transaction running under the cursor stability isolation levelhas retrieved a row froma table, no other transactions can update or delete that row as long as the cursor is positioned on that row. Additionally, ifa transaction running under the cursor stability isolation level changes the row it retrieved, no other application can update or delete that row until the isolating transaction is terminated. When a transaction has locked a row with the cursor stability isolation level,other transactions can insert, delete, or change rows on either side of the locked row-as long as the locked row is not accessed via an index. Therefore, the same SELECT SQL statement issued twice within a single transaction might not always yieldthe same results. Transactions running under the cursor stability isolation level cannot see uncommitted changes made by other transactions. With the cursor stability isolation level, both nonrepeatable reads and phantom reads are possible.
Uncommitted Read The uncommitted red isolation level allows a transaction to accessuncommitted changes madeby other transactions (in either the same or in different applications).A transaction running under the uncommitted read isolation level does not lock other applications outof the row it is reading-unless another transaction attempts to drop or alter thetable. If a transaction running under the uncommitted read isolation level accesses a read-only cursor,the transaction can access most uncommitted changes made by other transactions. The transaction cannot access tables, views, and indexes that are being created or dropped by other transactions, however, until those transactions are complete. All other changes madeby other transactions can be read before they are committed or rolled back.If a transaction running under the uncommitted read isolation level accesses an updateable cursor,the transaction will behaveas if the cursor stability isolation level were in effect. With the uncommitted read isolation level, both noyepeatable reads and phantom reads are possible.
Ff !
II
!
Chapter 2: Database Consistency Mechanisms R
Table 2-1 shows the four transaction isolation levels that are supported by DB2 Universal Database,as well as the types of phenomena that can occurwhen each one is used. Table 2-1 Transaction isolation levels supportedby DB2 and the phenomena that can occur when each is used m”Tr”.:,
UncommittedYes Read
Dirty R
,., ;,. e
~
,, .:
”
a
,.,,
*.
,
:;,
> “
d
,
,
,
m
.>
m
,
.
..
.~
s
Yes
No
Yes
Read Stability
No
No
Yes
Repeatable Read
No
No
No
Cursor Stability
,I
P
Yes
Specifying the Isolation Level You specify the isolation level foran embedded SQL application either at precompile time or when bindingthe application to a database. In most cases,you set theisolation level for embedded SQL applications with the ISOLATION option of the command line processor PREP or BIND commands. In other cases, you can set an embedded SQL application’s isolation levelby using the PREP or BIND API functions. The isolation level for a CL1 application is setby CL1statement handle attributes. The default isolation level used for all applicationsis thecursor stability isolation level.
Locking Along with isolation levels,DB2 uses locks to provide concurrency controland to control data access. A lock is a mechanism that associates a data resource with a single transaction, with the purpose of controlling how other transactions interact with that resource whilethe resource is associated withthe transaction that acquired the lock. The transaction with whichthe resource is associated is said to “hold”or “own” the lock. When a data resource in the database is accessed by a transaction, that resource is locked according to the previously specified isolation level. This lock prevents other transactions from accessing the resource in a way that would interfere with the owning transaction. Once the owning transaction is terminated (either committed or rolled back), changes madeto the resource are either made permanent or are removed, and the dataresource is unlocked so it can be used by other transactions. Figure 2-2 illustrates theprinciples of data resource locking. If one transactiontries to access a data resource in a way that is incompatible witha lock held by another transaction,that transaction must wait until the owning transaction has ended. This situationis known as a lock wait.When this event occurs, the transadion attempting to access the re9ourcesimply stops execution untilthe owning transaction has terminated and the incompatible lock is released. Locks are automatically provided by DB2 foreach transaction, so applicationsdo notneed to explicitlyrequest data r e s o wlocks.
Part 1: Basic Database Concepts
I
TRANSACTION2
c
I H-
STARTTRANSACTION
SQL C O M M A N D SQL C O M M A N D SQL C O M M A N D COMMIT
END TRANSACTION
Figure 2-2 DB2 prevents uncontrolled concurrent table accessby using locks. In this example, Transaction 1 has locked tableh and Transaction2 must wait until the lock is released before it can execute.
Lock Attributes All locks used by DB2have the following basicattributes: Object-The object attribute identifies the data resource beinglocked. Tablesare the only data resource objectsthat can be explicitly lockedby an application. DB2 can set locks on other types of resources, suchas rows, tables, etc., but these locks are used for internal purposes only Size--The size attribute specifies the physical sizeof the portion of the dataresource that is being locked.A lock does not always have to control an entire data resource. For example, rather than giving an application exclusive control over an entire table, DB2 can only givethe lock exclusive control over the row that needs to be changed. Duration-The duration attribute specifies the length of time a lock is held. The isolation levels described earlier control the duration of a lock. Mode-The mode attribute specifies the type of access permitted forthe lock owner, as well as thetype of access permittedfor concurrent users of the locked data resource. Mode is sometimes referredto as the “state”of the lock.
Lock States As a transaction performs its operations, DB2 automatically acquireslocks on the data resources it references. These locksare placed on a table, a row (or multiple rows),or both a table and a row (or rows). The only object a transaction can explicitly acquirea lock for is a table, and a transaction can only changethe stateof row locks by issuing
Chapter 2: Database Consistency Mechanisms
,
I
,
j
31
i
l
a COMMIT or a ROLLBACK SQL statement. The locksthat areplaced on a data resource by a transaction can have oneof the following states: Next Key Share (NS)-If a lock is set in the Next Key Share state, thelock owner and all concurrent transactions can read-but cannot change-data in the locked row. Only individual rows can be lockedin the Next KeyShare state. This lock is acquired in place of a Share lock on data thatis read using the read stability or cursor stability transaction isolation level. Share @)--If a lock is set in the Share state,the lock ownerand anyother concurrent transactions can read-but cannot change-data in the locked table or row. As long as a table is not Share locked, individual rows in that table can be Share locked. If, however, a table is Share locked, no rowShare locks can be set in thattable by the lock owner. Ifeither a table or a row is Share locked, other concurrent transactions can read the data, but they cannot change the data. Update (u)-If a lock is set in the Update state, the lock owner can update data in the locked data table. Furthermore, the Update operation automatically acquires Exclusive lockson the rows it updates. Other concurrent transactions can readbut not update-data in the locked table. Next Key Exclusive m - I f a lock is set in the Next Key Exclusivestate, the lock owner can read-but not change-the locked row. Only individual rows can be locked in theNext Key Exclusivestate. This lock is acquired on the next row in a table when a row is deleted fromor inserted into the index fora table. Next Key Weak Exclusive W ) - I f a lock is set in the Next Key Weak Exclusivestate, the lock owner can read-but not change-the locked row. Only individual rows can be lockedin the Next Key Weak Exclusivestate. This lock is acquired on the next row in a table when a row is inserted into the index of a non-catalog table. Exclusive K L " f a table or row lock is set in the Exclusive state, the lock owner can both read andchange data in the locked table, but only transactions using the uncommitted read isolation level can access the locked table or row(s). Exclusive locks are best used with data resources that areto be manipulated withthe INSERT, UPDATE, and/or DELETE SQL statements. Weak Exclusive W)-If a lock is set in the Weak Exclusivestate, thelock owner can read andchange the locked row. Onlyindividual rows can be lockedin the Weak Exclusive state. This lock is acquired on a row whenthe row is inserted into a noncatalog table. Super Exclusive @)-If a lock is set in the Super Exclusivestate, the lock owner can alter a table, drop a table, create an index, or drop an index. T h i s lock is automatically acquired on a table whenever a transaction performs any oneof these operations. No other concurrent transactions can read or update the table until this lock is removed.
In addition to these eight primary locks, there are four more special locksthat are only used on tables. They are called intention locks and are used to signify that rows
L??-: I
i l
I
PartDatabase 1: Concepts Basic
!
within the table may eventually become locked. These locksare always placed on the table before any rows within the tableare locked. Intention locks can have one of the following states: Intent None 0 - I f an intention lock is set in the Intent None state, thelock owner can read data in the locked data table, including uncommitteddata, butcannot change this data.In this mode, no row locks are acquired by the lock owner,so other concurrent transactions can read and change data in the table. Intent Share (IS)-If an intention lock is set in the Intent Share state, lock the owner can readdata in thelocked data table but cannot changethe data.Again, because the lock owner does notacquire row locks, other concurrent transactions can both read and change data in thetable. When a transaction owns an Intent Sharelock on a table, the transaction acquires a Sharelock on each row it reads. T h i s intention lock is acquired whena transaction does not conveythe intentto update any rows in thetable. Intent Exclusive (nrs-If an intention lock is set in the Intent Exclusive state, thelock owner and any other concurrent transactions can read and change data in the locked table. When the lock ownerreads data from the datatable, the lock owner acquires a Sharelock on each row it reads and an Update and Exclusive lock on each row it updates. Other concurrent transactions can bothread and update the locked table. This intent lock is acquired whena transaction conveys the intentto update rows in the table. The SELECT FOR UPDATE,UPDATE T ERE, and INSERT SQL statements convey the intentto update. Share with Intent Exclusive (SIx)-If an intention lock is set in the Share with Intent Exclusive state, thelock ownercan bothread and change data in the locked table. The lock owneracquires Exclusive lockson the rows it updates but not on the rows it reads, so other concurrent transactions can readbut not update data in the locked table.
As a transaction performs its operations, DB2 automatically acquires appropriate locks as dataobjects are referenced. Figure2-3 illustrates thelogic DB2 uses to determine the type of lock to acquire on a referenced data object.
Locks and Application Performance When developing DB2applications,you must be aware of several factors concerningthe uses of locks and the effect they have on the performance of an application. The following factors can affect application performance: W Concurrency versus lock size
H Deadlocks W Lock compatibility W Lock conversion
H Lock escalation
Chapter 2: Database Consistency Mechanisms
SQL COMMAND I
INDEX SCAN
TABLE SCAN
Nh+l
ACQUIRE UPDATE
INTENT SHARE (IS) LOCK TABLE LOCK TABLE LOCK TABLE LOCK TABLE
ACQUIRE
ACQUIRE SHARE (S) LOCKS ON ALL REFERENCED ROWS
INTENDED ?
INTENTEXCLUSIVE (JX)
EXCLUSIVE ( X ) OR
ACQUIRE ACQUIRE UPDATE
INTENDED ? ACQUIRE
SHARE (S)
EXCLUSIVE (X)
NO LOCKS ACQUIRED ON REFERENCED ROWS
SHARE (S) LOCKS ON ALL REFERENCED ROWS
Figure 2-3 Logic usedby DB2 to determine which type of lock(s) to acquire
CONCURRENCY VERSUS LOCK SIZE As long as multiple transactions access tables for the purpose of reading data, concurrency should be only aminor concern. What becomes moreof an issue is the situation in which at least one transaction writes to a table. Unlessan appropriate index is defined on a table, there is almost no concurrent write accessto that table. Concurrentupdates are only possible with Intent Share or Intent Exclusive locks. Ifno index exists forthe locked table, the entire table must be scanned forthe appropriate data MW (table scan). In thiscase, the transaction must hold either a Share or an Exclusive lock on the table. Simply creating indexeson all tables does not guarantee concurrency.DB2's optimizer decides for you whether indexes are used in processing yourSQL statements, so even if you have defined indexes, the optimizer mightchoose to perfom a table scan for any of several reasons: No index is defined for yoursearch criteria (WHEREclause). The index key must match the columns usedin theWHERE clause in order forthe optimizer t o use the index to help locate the desired rows. If you chooseto optimize for high concurrency, makesure your table design includesa primary key for eachtable that will be updated. These primary keys shouldthen be used wheneverthese tables are referenced with an UPDATE SQL statement. Direct access might be faster thanvia an index. Thetable must be large enough so the optimizer thinks it is worthwhile to take theextra step of going through the index, rather than justsearching all the rows in thetable. For example, the optimizer would probablynot use any index definedon a table with only four rows of data.
M l j
I l."
i
34 .
!
Part 1: Basic Database Concepts
, ;
"!
W A large number of row lockswill be acquired. If many rows in a table will be
accessed by a transaction, the optimizer willprobably acquire a table lock. Any time one transaction holds a lockon a table or row, other transactions might be denied access until the owner transaction has terminated. To optimize for maximum concurrency, a small, row-level lock is usually better than a large table lock. Because locks require storage space (to keep) and processing time (to manage), you can minimize both of these factors by using one large lock-rather than many small ones.
DEADLOCKS When two or more transactions are contending for locks, a situation
known as a dedZock can occur. Consider the following example. Transaction1 locks "able A with an Exclusive lock, and Transaction 2 locks "able B with an Exclusive lock. Now, suppose Transaction1 attempts to lock "able B with an Exclusive lock, and Transaction 2 attempts to lock "able A with an Exclusive lock. Both transactions will be suspended
until their second lock request is granted. Because neither lock request can be granted until one ofthe transactions performs aCOMMITor ROLLBACK operation-and because,neither transaction can perform a COMMIT or ROLLBACK operation becausethey are both !suspended (waitingon locks)-a deadlock situation has occurred. figure 2-4 illustrates this scenario.
Transaction 1 is waiting for Transaction 2 to release its lock on TableB.
I
I TRANSACTION 2
I PTART TRANCAf'TlfJN Transaction 2 is waiting for Transaction 1 to release its lock on TableA.
END TRANSACTION
Figure 2 4
Deadlock cycle between two transactions
l
1 ;
Chapter 2: Database Consistency Mechanisms
i 35 1 " A
A deadlockis more preciselyreferred to as a "deadlock cycle," becausethe transactions involved in a deadlock forma circle of wait states. Each transaction in the circle is waiting for a lock held by one of the other transactions in the circle. Whena deadlock cycle occurs,all the transactions involved in thedeadlock willwait indefinitely-unless an outside agent performs some actionto end the deadlock cycle. Becauseof this, DB2 contains an asynchronous system background process associated with each active database that is responsible for finding and resolving deadlocks in the locking subsystem. "his background process is called the deudZock detector. When a database becomes active, the deadlock detector is started as partof the process that initializes the database for use. The deadlock detectorstays "asleep" most of the time but "wakes up" at preset intervals to look for the presence of deadlocks between transactions using the database. Normally, the deadlock detectorsees that there areno deadlockson the database and goes back to sleep. If, however, the deadlock detector discoversa deadlock on the database, the detector selects one of the transactions in thecycle to roll back and terminate. The transaction that is rolled back receivesan SQL error code, and all of its locks are released. The remainingtransaction can then proceed, because the deadlock cycle is broken. The possibilityexists (although unlikely) that more than one deadlock cycle exists on a database. If this is the case, the detector willfind each remainingcycle and terminate one of the offending transactions in thesame manneruntil alldeadlock cycles are broken. Because at least two transactions are involved in a deadlock cycle, you might assume that two data objects are always involved in the deadlock. " h i s is not true. A certain type of deadlock, known as a conversion deadlock, can occur on a single data object. A conversion deadlock occurs when two or more transactions already hold compatible locks on an object, and theneach transaction requests new, incompatible lock modeson that same object. A conversiondeadlock usually occurs between two transactions searching for rows via an index (index scan). Using an index scan, each transaction acquires Share andExclusive locks on rows. When eachtransaction has readthe same row and then attemptsto update that row, a conversion deadlocksituation occurs. Application designersneed to watch out for deadlock scenarios when designing highconcurrency applicationsthat aret o be run by multiple concurrent users. In situations where the same set of rows will likely beread and thenupdated by multiple copies of the same application program,that program should be designedto roll back and retry any transactions that might be terminated as a result of a deadlock situation. As a general rule, the shorter the transaction, the less likely the transaction will be to get into a deadlock cycle.Setting the proper interval for the deadlock detector (in the database configuration file)is also necessary to ensure good concurrent application performance. An interval that is too short will cause unnecessary overhead,and an interval that is too long will enable a deadlock cycleto delay a process for an unacceptable amount of time. You must balancethe possible delaysin resolving deadlocks withthe overhead of detecting the possible delays.
LOCK C0"PATIBILITY
If the state of onelockplaced on a data resource enables another lock to be placedon the same resource,the two locks (or states)are said to be Compatible. Whenever one transaction holds a lock on a data resource and a second transaction requests a lock onthe same resource,DB2 examines the two lockstates
36
I 1
Part 1: Basic Database Concepts to determine whether they are compatible. If the locks are compatible, the lock is granted to the second transaction (aslong as no other transaction is waiting forthe data resource). Ifthe locks are incompatible, however,the second transaction must wait until the first transaction releases its lock. (In fact, the second transaction must lwait until all existing incompatible locksare released.) Table2-2 shows a lock compatibility matrix that identifies whichlocks are compatible and which are not.
Table 2-2 Lockcompatibilitymatrix
none none
IN
IS
NS
S
IX
SIX
U
Nx
NW
X
W
Z
X
YES YES YES YES YES YES YES YES YES YES YES YES YES YES YES YES YES YES YES YES YES YES ' NO YES YES YES YES YES YES YES YES NO NO NO NO NO YES YES YES NO NO YES YES YES NO NO NO YES YES YES YES YES YES YES NO NO YES NO NO NO NO NO YES YES YES NO NO YES NO NO NO NO NO NO NO YES YES YES NO NO NO NO NO NO NO NO NO NO YES YES YES YES YES NO NO NO NO NO NO NO NO YES YES NO YES NO NO NO NO NO NO NO NO NO YES YES NO YES NO NO NO NO NO NO NO YES NO YES YES NO NO NO NO NO NO NO NO NO NO NO
W
YES YES
Z
YES
IN IS
NS S IX SIX
U Nx
NW
YES
YES YES
NO
NO
NO
NO
NO
NO
NO
NO
YES
NO
NO NO
NO
NO
NO
NO
NO
NO
NO
NO
NO
NO NO
Adapted fromIBM DB2 Universal Database Embedded SQL Programming Guide, page 143. YES
NO
Locks are compatible, therefore the lock requested is granted Locks are not compatible; therefore,the requesting transaction must wait for the held lock to be released or fora timeout to occur.
LockTyps IN Intent None IS Intent Share
NS Next Key S
IX SIX
Update
U NX NW X
Share Share Intent Exclusive ShareWith Intent Exclusive Next Key Exclusive NextKeyWeakExclusive Exclusive
Weak Exclusive W Z Exclusive Super
Chapter 2: Database Consistency Mechanisms
LOCK CONVERSION
When a transaction accesses a data resource on which the transaction already holds a lock-and the mode of access requires a more restrictive lock than the one the transaction already holds-the state of the lock is changed to the more restrictive state. The operationof changing the state of a lock already held to a more restrictive state iscalled a loch conversion.Lock conversion occurs because a transaction can only hold one lock on a data resource at a time. The conversion case for row locks is simple. A conversion only occurs ifan Exclusive lock is needed and a Share or Update lock is held. More distinct lock conversions exist fortables than for rows.In most cases, conversions result in the requested lock state becoming the new state of the lock currently held whenever the requested state is the higher state. IntentExclusive and Share locks, however, are special cases, because neither is considered to be more restrictive than the other, If one of these locks is held and the other is requested, the resulting conversion is to a Share with Intent Exclusive lock. Lock conversion can cause lockstoonly increase restriction. Once a lock has been converted,the lock stays at the highest level obtained until thetransaction is terminated.
LOCK ESCALATION All locks require space for storage, and because this space is finite, DB2 limits the amount of space the system can use for locks. Furthermore, a limit is placed on the space eachtransaction can use forits own locks. A process known as lock escalation occurs when too many record locks are issued in the database and one of these space limitations is exceeded. Lock escalation is theprocess of converting several locks on individual rows in a table into a single, table-level lock. When a transaction requests a lock after the lock spaceis full,one of its tables is selected-and lock escalation takes place t o create space in thelock list data structure. If enough spaceis not freed,another table is selected for escalation, and so on, until enough spacehas been freed for the transaction to continue. If there is still not enough spacein the lock list after all the transaction's tables have been escalated,the transaction is asked to either commit or roll back all changes made sinceits initiation (i.e., the transaction receives aq SQL error code, and the transaction is terminated). An important point to remember is that anattempted escalation only occursto the transaction that encounters a limit. T h i s situation happens because,in most cases,the lock storage space willbe filled whenthat transaction reaches its own transaction lock limit. If the system storage lock spacelimit is reached, however, a transaction that does not hold many locks might try to escalate, fail, and then be terminated. This event means that offending transactions holding many locks overa long period of time can cause other transactions to'terminate prematurely. If escalation becomes objectionable, there aretwo ways t o solve the problem: Increase the number of locks enabledin thedatabase configuration file (witha corresponding increasein memory). T h i s solution mightbe the best if concurrent access to the table by other processes is important. A point of diminishing returns exists on index access and record locking, even when concurrency is theprimary concern. The overheadof obtaining record-level locks can impose more delays to other pnjcesses, which negatesthe benefits of concurrent accessto the table. Locate and adjust theoffending transaction(s1, which might be the one(s) terminating prematurely, and explicitly issue LOCK TABLE SQL statements within
Part 1: Basic Database Concepts the transaction(s1. Thischoice might be the best if memory sizeis crucial, or if an extremely high percentageof rows are being locked. W Change the degree of transaction isolation being used. m Increase the frequency of commit operations.
Transaction Logging Transaction logging is simply a method of keeping track of what changes have been made to a database. Every change made to a row of data ina database table is recorded in theactive log fileas anindividual log record. Each log record enables DB2 to either remove or apply the data change to the database. To fully understand transaction logging operations,you should know what the transaction log contains, how transaction logging works, how the transaction log gets synchronized, and how to manage log file space.
HOW TRANSACTION LOGGINGWO= Each changeto a row in a table is made with an INSERT, UPDATE, or DELETE SQL statement. If you use the INSERT SQL statement, a transaction record containingthe new row is writtento the log file. If you use the UPDATE SQL statement, transaction records containingthe old row information and the new row information are written to the log file (two separate records are written). If you use the DELETE SQL statement, a transaction record containingthe old row information is written to the log file. These types of transaction log records make up the majority of the records in the transaction log file.Other transaction records alsoexist, which indicate whether a ROLLBACK or a COMMIT SQL statement was usedto end a transaction. These records end a sequence of data log recordsfor a single transaction. Whenever a ROLLBACK or a COMMIT log record is written, the record is immediately forced out to the active log file. This action ensures that all the log records of a completed transaction are in the log file and will not belost due to a system failure. Because more than one transaction might be using a database at any given time,the active log file containsthe changes madeby multiple transactions. To keep everythingstraight in the log, each log record contains an identifier of the transaction that created the record. In addition, all the log records fora single transaction are chained together. Once a transaction is committed, all log records for that transaction are no longer needed (&er all changes madeby that transaction are physically written to the disk). If a ROLLBACK occurs, DB2 processes each log record written by the transaction in reverse order and backs out all changes made. Both "before" and "after" image UPDATE records are writtento the log filefor this reason.
LOG FILEAND DATABASE SYNCHRONIZATION DB2 can maintain consistency only by keeping the log file and database synchronized. This synchronization is achieved with a write-ahead logging technique. When a transaction changes a row in a table, that change is actually made in a memory buffer contained in the database buffer pool and is writtento the disk later. As a result, themost current data changes made to a working database are in the buffer pool, not on the disk. Write-ahead logging
P Chapter 2: Database Consistency Mechanisms
,
'
I
i
31
I
preserves consistency bywriting the log recordof a row change to the disk beforethe change itself is written from the memory bufferto the disk. Log records are written to disk whenever atransaction terminates-or whenever the buffer pool manager writes the memory bufferto the disk database. If the system crashes,the log file and database will no longer be synchronized.Fortunately, the log filecontains a recordof every uncommitted change made to the database, becausethe log recordof the change is forced to disk before the actual change is written. T h i s event enablesthe recovery processto restore the database to a consistent state. The recovery processis discussed in more detail in the Database Recovery section later in this chapter.
MANAGINGLOG F'ILE SPACE It wasmentioned earlier that DB2 writes records sequentially to the log filein order to support transactions. Because the log file grows until thefile is reset, if nolimits were imposed onthe log file size,all free space on the system disk would eventuallybecome full of logrecords. DB2's LogManager controls the size of the log file,and whenever possible,the Log Manager resets the log to an empty state. The growthof the log is controlled by the initial size of the primary log files, the size limit for each secondary log and file,the number of primary and secondary log files being used. When the primary log fileis filled, the Log Manager allocates space for a secondary log file,and the overflow is stored in that secondary file. Whenever the primary log file becomesempty due t o transaction inactivity (i.e., no transactions have uncommitted records in the log), the primary log fileis reset and any secondary log filesthat have been allocated are released. If atransaction r u n s out of log space, either because the maximum primary log file size was reached and a secondary file was not used, or because there was too little disk space to allocate the next secondary log file, a roll back occurs and the transaction is terminated. Regardless of cause, this process continuesuntil the log's inactive state is reached and the log i s reset to its minimum size. If two or more continuously overlappingtransactions (e.g., high volume and high activity rate) arerunning, the primary log file might never reset. be Continuously overlapping transactions are not likely,but they can happen when two or more transactions starting at close intervals use the same database. When designing adatabase system in which the transaction arrival rate is high, you should increase the log file size to reduce the probability of transactions being rolled back due to insufficient logfile space. You can also prevent the primary log file from beingreset if a lengthy transaction (one that causes manylog records to be written before they are committed)is running. But first, you must consider how these transactions are used, as well as the amount of log file space needed to support them, when designing the database system. If other transactions are &g concurrently with a lengthy transaction, the log file space requirement will increase.A lengthy transaction should probablyrun by itself, and the transaction should probably openthe database for exclusive usageand fill up the log file before committing its changes.Any transaction that never ends execution (i.e., never performs a ROLLBACK or COMMIT) is a faulty application, because the transaction will eventually cause itselfand possibly other transactions to fail.
Part 1: Basic Database Concepts DATABASE RECOVERY Database recovery is the process of returning the data in a database to a consistent state aftera system failure (such as a power failure in' the middle of a work.session) occurs. If a DB2 database is active when a system failure occurs,that database is left in an inconsistent state until the database is accessed again. At that time, a special recovery processis executed that restores the database to a new, consistent state. This new, consistent state isdefined by the transaction boundaries of any applicationsthat were usingthe database when the system failure occurred. This recovery process is made possible by the database log file (see Recovery Log File in Chapter 1,"DB2 Database Architecture"). Becausethe log file contains botha "before" and "after" imageof every change madeto a row, all transaction records stored in the log file canbe either removed from or added to the database as necessaq. DB2 determines whetherdatabase recovery is needed by examining the recovery log file the firsttime a database is opened after a system failure occurs. Ifthe log file shows that the database was notshut down normally,the disk imageof the database could be inconsistent. That's because changes made by completedtransactions (still in the memory buffers) might have been lost. To restore the database to a consistent state, DB2 does the following actions: Any change madeby a transaction that was in flight (had not been committed or rolled back)is removed from the database. DB2 works backwardthrough the log file; ifan uncommitted changeis found, the record is restored to the "before" image retrieved fromthe log file. Any change madeby a committed transaction that isnot found in the database is written to the database. As DB2 scans the log file, any committed log records found that arenot in thedatabase are written to the database. W If a transaction was in the process of being rolled back,the roll back operation is completed so that all changes madeto the databaseby that transaction are removed. Because DB2 knows that changes are only consistent whenthey are explicitly committed, all work done by in-flight transactions is considered inconsistentand must be backed out of the database to preserve database consistency. As described previously, during the recovery process DB2 must scan the log file to restore the databaseto a consistent state. While scanning the log file, DB2 reads, the database to determine whether the database contains the committed or uncommitted changes. If the log file is large, you could spend quite a while scanningthe whole log and reading associated rows from the database. Fortunately, scanningthe whole logis usually unnecessary, becausethe actions recordedat the beginning of the log file have been in thelog file longerthan the other actions. "he chance is greater, then, that their transactions have been completed and that the data has already been written to the database; therefore, no recovery actions are required for the log records generated by these transactions. If some way existedto skip theselog recordsduring the m v e r y process, the length of time necessaryto recover the entire database could be shortened.This is the purpose of the soft checkpoint,which establishes a pointer in the log at which to begin database recov-
Chapter 2: Database Consistency Mechanisms
,
I
I
,
1
l
i
,
j
"
41
1I
I
ery. All log file records recorded before this checkpoint are the result of completed transactions, and their changes have already been written to the database. A soft checkpoint is most useful when log files are large, becausethe checkpoint can reduce the number of log records that are examined during database recovery; the more o h n the soft checkpoint is updated, the faster the database can be recovered.
S U R l R l A R Y m m I m I
I I I
You will find it extremely important to understand the mechanisms DB2 uses to ensure database consistency before designing yourdatabase application. Unfortunately, this aspect is one of the more complicated topics of database application design."his chapter was designed to provide you with an overview of the database consistency mechanisms found in DB2 Universal Database, Version 5.2. You should now know what database consistency is and how to maintain it. You should also be familiar with transactions and how your application uses them tomaintain data integrity. Furthermore, you should be familiar with the following transaction isolation levels: H Repeatable read
W Read stability W Cursor stability W Uncommitted read You should also understand the following lock attributes: M Object W
Size
W Duration
W Mode
And you shouldunderstand the difference betweenthe following lockstates:
W Intent None (IN) W Intent Share (IS) M Next Key Share (NS) W Share (S) W Intent Exclusive (IX) W Share with Intent Exclusive (SIX) W Update (U) M Next Key Exclusive(NX) W Next Key Weak Exclusive(NW) W Exclusive (X)
F
I
" " L
42
Concepts PDatabase art 1: Basic R Weak Exclusive (W) R Super Exclusive (Z)
You should also be familiar with lock size, deadlocks, lock compatibility, lock conversion, and lock escalation.Finally, you should beaware of howtransaction logging works and how transaction logsare used to restore database consistency in theevent of a system failure. As you build your database application, you will need to understand most of the information coveredin this chapter. Incorporatingthis information in your application during the design and development process will help you catch and hopefully avoid potential problemsin your application design.
This Page Intentionally Left Blank
Appllcatlo Development The DB2 database application development process begins with the application designand continues with the actual source code development. This chapter is designed to introduce you to the elements that can be usedto drive your application's design. The first part of this chapter defines a simple application program and explains how a DB2 database application differs.This is followed by a n introduction to the four main elements that are used to develop DB2 applications. Next, directions for establishing a DB2 database application development and testing environment are discussed. Finally, a brief overview of transaction management and source code creation and preparation is provided. We will begin by answering the question, 'What is a DB2 datal:base application?"
efore i d e n t i ~ n gthe basic elements of a 2 database application, let’s examine the basic elements of a simple application. Most simple applications contain five essential parts: Logic (decision control)
ory (data storage and retrieval) thmetic (calculation) ~ n p uis t defined as the way an application receives the information it needs in order to produce solutions for the problems that it was designed to solve. Once input has been received, logic takes over and determines what information should be placed in or taken out of memory (data storage) and what ~ ~ i t ~ m eoperations tic should be pe~ormed.Nondatabase applications use ~ n c t i o n supplied s by the operkting system to store data in (and retrieve data from) simple, b ~ e - o ~ e n t files. e d Once the application has produced a solution to the problem that it was designed to solve, it provides approp~ateoutput of either an answer or a specific action.
method of data storage/ret~evaland ating system file input / o u ~ p (UO) u~ i more than just data storage and retmeva control (logic); thanks to the non~rocedural
3-1 illustrates the es abase application pro
ow can the f ~ c t i o n adependencies l in the database be isolated?
can have DI32 atements with
etti
nt has been ~ ~ e p ~the ~ ~pplic~tion e d , desi conside~~tions should include the followin saction definitions
G
in the ~ ~ p ~ i c a t i o ~
~ocessc
n. ~ p ~ l i c a ~ i o n
Chapter 3: Getting Started with DB2 Application Development
High-Level Programming Language A high-level programming language provides the framework within which all SQL statements, CL1function calls,and API calls are contained. This framework enablesyou to control the sequence of your application's tasks (logic) and provides a way for your application t o collect user input and produce appropriate output. A high-level programming language also enables you to use operating system calls and DB2 application elements (SQL statements, CL1 function calls, and API calls) within the same application program.In essence, the high-level programming language can take care of everything except data storage and retrieval. By combining OS calls and DB2 elements, you can develop DB2 database applications that incorporate OS-specific file U0 for referencingexternal data files.You can also use the high-level programming languageto incorporate Presentation Manager functions, User Interface class library routines, and/or Microsoft Founclation Class ( W C ) library routines in the application for both collectinguser inputand displaying application output. Additionally, by building a DB2 database application with a high-level language, you can exploitthe capabilities of the computer hardware to enhance application performance (i.e., optimizing for high-level processors such as the Pentium I11 processor) and simplify user interaction (i.e., using special YO devices suchas light pens and scanners).DB2 Universal Database,Version 5.2, providessupport for the following high-level languages:
mc R c++ R COBOL
m FORTRAN m mxx n Visual BASIC (through the DB2 Stored Procedure Builder)
SQL Statements SQL is a standardized language that is used to define, store, manipulate, and retrieve data in a relational database management system. SQL statements are executed by DB2, not by the operating system. Because SQLis nonprocedural by design, it is not an actual programming language;therefore, mostdatabase applicationsare a combination of the decision and sequence controlof a high-level programming language and the data storage, manipulation, and retrieval capabilities of SQL statements. Two types of SQL statements can be embedded in an application program: static SQL statements and dynamic SQL statements. Each has its advantages and disadvantages.
STATIC SQL A static SQL statement is an SQL statement that is hard-coded in an application program when a source codefde is written. Because high-level programming language compilers cannot interpret SQL statements, all source code files containing static SQL statements must be processed by an SQL precompiler before they can be compiled. Likewise, DB2 cannot work directly with high-level programming language
l
Ii
P Part 2 Application Development Fundamentals variables. Instead, DB2 must work with host variables that are deflned in a special place within an embedded SQL source code file (so the SQL precompiler can recognize them). The SQL precompiler is responsible for translating all SQL statements found in asourcecodefile into their appropriate host-languagefunctioncalls and for converting the actual SQL statements into host-language comments. The SQL precompiler is also responsible forevaluating the declared data types of host variables and determining which data conversion methodsto use when movingdata to-and-from the database. Additionally, the SQL precompiler performserror checkingon each coded SQL statement and ensures that appropriate host-variable data types are used for their respective table column values. Static SQL has one distinct advantage over dynamic SQL. Because the structure of the SQL statements used is lmown at precompile time,the work of analyzing the statement and creating a package containing data access a planis done duringthe development phase. Thus, static SQL executes quickly, because its operational form already existsthe in database at application run time. The down sideto this property is that all static SQL statements mustbe prepared (i.e., their access planmust be stored in the database) before they can be executed,and they cannotbe altered at run time. Becauseof this characteristic, if an application uses static SQL,its operational package(s1 must be "bound" to each database the application will work with before the static SQL statements can be executed.
NOTE: Because static SQL applications require prior knowledge of database, table, schema, and field names, changes made to these objects after the application is developed could produce undesirableresults.
DYNAMIC SQL Although static SQL statements are fairly easy t o use, they are limited because their format must be known in advance by the precompiler, and they can onlyuse host variables.A dynamic SQL statement does not have a precoded, fixed format, so the data objects the statement uses can change eachtime the statement is executed. This feature is useful for an application that has an SQL requirement in which the format and syntax of the SQL statement is not known at the time the source code is written. Dynamic SQL statements do not haveto be precompiled(although the overhead for dynamic SQL statements sometimes has to) and bound to the database they will access. Instead, they are combined with high-level programming language statements to produce an executable program,and all binding takes place at run time, rather thanduring compilation. Because dynamic SQL statements are dynamically created accordingto the flow of application logic at execution time, theyare more powerful than static SQL statements. Unfortunately, dynamicSQL statements are also more complicatedto implement. Additionally, because dynamic SQL statements must be prepared at applicationrun time, most will execute more slowly than their equivalent static SQL counterparts However, because dynamic SQL statements use the most current database statistics during execution, there are some casesin which a dynamicSQL statement will execute faster than anequivalent static SQL statement. Dynamic SQL statements also enable the optimizer to see the real values of arguments,so they are not confinedto the use of host variables.Figure 3-2 shows how both static SQL and dynamicSQL applications interact with aDB2 database.
F I
Chapter 3: Getting Started with DB2 Application Development
,
:
51
STATIC SQL APPLICATIONS DATABASE
APPLICATION CONTAINING STATIC SQL STATEMENTS
The operational form of static SQL statements are stored as packages in the database. to access table Applications containing static SQL statements use these packages data at application runtime. DYNAMIC SQL APPLICATIONS DATABASE
APPLICATION CONTAINING DYNAMIC SQL STATEMENTS
The operational form of dynamic SQL statements are automatically created at application run time. Temporary access plans, generated when dynamic SQL statements are prepared, are then used to access table data.
Figure 3-2 How SOL applications interact witha D62 database
CL1 Function Calls DB2’s Call Level Interface (CLI) is a collection of API function calls that were developed specifically for database access. To understand the call level interface, you need to understand the basis of DB2’s CL1 and how it compares with existing, callable, SQL interfaces. In the early 199Os, the WOpen Companyand the SQLAccess Group (SAG),now a part of WOpen,jointly developed a standard specification for a callable SQL interface called the XIOpen Call-Level Interface, or X/Open CLI.The god of the WOpen CL1 was to increase the portability of
52
1 :
i :
Part 2: Application Development Fundamentals database applications by enabling them to become independent of any one database management system’s programming interface. Most of the WOpen CL1 specifications were later accepted as part of a new IS0 CL1internationalstandard. DB2’s CL1is based on this IS0 CL1 standard interface specification. In 1992, Microsoft Corporation developed a callable SQL interface, ODBC, for ‘the MicrosoR Windows operating system. ODBC is based on the WOpen CL1 standards specification but provides extended functions that support additional capability. The ODBC specification also defines an operating environment where database-specific ODBC drivers are dynamically loaded (basedon the database name provided with’the connection request)at application run time by an ODBC Driver Manager.This Driver Manager providesa central pointof control for each datasource-specific library (driver) that implements ODBC function calls and interactswith a specific database management system (DBMS). Byusing drivers,an application can be linked directlyto a single ODBC driver library,rather thanto each DBMS itself. Whenthe application runs, the ODBC Driver Manager mediatesits function calls and ensures that they are directed to the appropriate driver. Figure3-3 shows how CL1 applicationsinteract with a DB2 database via the ODBC Driver Manager and the DB2 CL1driver. Applications that incorporate DB2’sCL1 are linked directly to the DB2CL1 load library. TheDB2 CL1load library canthen be loaded as an ODBC driver byany ODBC Driver Manageror it can be used independently. DB2’s CLI provides support forall ODBC 3X Level 1fundions except SQLBulkoperationeO;all ODBC Level 2 functions except SQmrivere( ) ; some WOpen CL1 functions,and some DB2-specific functions. The CL1 specifications defined for ISO, WOpen, ODBC, and DB2 are continually evolving in a coop erative mannerto produce new functionsthat provide additional capabilities. The important difference between embedded dynamic SQL statements and CL1function calls lies in how the actual SQL statements are invoked. With dynamic SQL,an application prepares and executes SQL for a single DBMS-in this case, DB2. For a dynamic SQL application to work with a different DBMS, the application would have to be precompiledand recompiled forthat DBMS. With CLI,an application uses procedure calls at execution time to perform SQL operations. BecauseCL1 applications do not have to be precompiled, they can be executed on a variety of database systems without undergoing any alteration.
API Function Calls Application Programming Interface (API)function callsare a collectionof DB2 productspecific function callsthat provide services otherthan the data storage, manipulation, and retrieval servicesthat are provided by SQLstatements and CL1function calls.API calls are embedded within a high-level programming languageand operate in a fashion similar to other host-language function calls. Each API function has both a call and a return interface, and the calling applicationmust wait until a requested API function completes beforeit can continue. The services provided by DB2 API function callscan be divided intothe following categories: W Database manager control APIs
Database manager configuration APIs
: i 53
Chapter 3: Getting Started with DB2 Application Development
I
APPLICATION
r-
S DB2 CL1
r RETURN
CALL
ODBC DRNER MANAGER
DB2 ODBC DRIVER
S t
TEMPORARY
TABLES
ACCESS PLAN
RETURN
W DATABASE Figure 3-3 How CU applications interact witha DB2 database
H Database controlAPIs W Database configurationAPIs
H Database directory managementAPIs W Clienthemer directory managementAPIs
H Node managementAPIs W Network support APIs H Backuphecovery APIs
t
" I
I
j
P!
1 54 l
Part 2: Application Development Fundamentals m Operational utility APIs Database monitoring APIs Data utility APIs General application programmingAPIs Application preparation APIs W Remote server APIs Table space managementAPIs Transaction APIs Miscellaneous APIs
An application can use APIs to access DB2facilities that arenot available via SQL statements or CL1 function calls.In addition,you can write applications containingonly APIs that will perform the following functions: I Manipulate the DB2 environment by cataloging and uncataloging databases and workstations (nodes), by scanning system database andworkstation'directories, and by creating, deleting, and migrating databases Perform routine database maintenance by backing up and restoring databasesand by exporting data to and importing data from external data files Manipulate the DB2 database manager configuration fileand other DB2 database configuration files Perform specific clientkerner operations I Provide a run-time interface for precompiled SQL statements Precompile embedded SQL applications m Bulk loadtables by importing data from external data files Figure 3-4 illustrates how an application containing the BACKUP A P I interacts with the DB2 Database Managert o back up a DB2 database.
-
BACKUP API APPLICATION
APPLICATION CONTAINING THE BACKUP
A P I FUNCTION CALL
CALL 4
+
R E m
PERFORM BACKUP OPERATION
Figure 3 4 How a BACKUP MI call is processed by'DB2
DATABASE
a
Chapter 3: Getting Started with DB2 Application Development
FM M Establishing the DB2 Database Application Development Environment Before you can begin developing DB2 database applications, you must establish the appropriate application developmentioperating system environment by performing the following steps:
1. Install the appropriate DB2 Universal Database software product on the workstation that will be used for application development.the If application will be developedin a client-server environment, youmust installthe DB2 Universal Database server softwareon the workstation that will act as the server and install the appropriate DB2 Universal DatabaseClient Application Enabler (CAE) software on all client workstations.You also must install a communication protocolthat is common to both client and server workstations. 2. Install and properly configurethe DB2 Universal DatabaseSoftware Developer's Kit (SDK) softwareon all workstations that will be used for application development. 3. Install andproperly configurea high-level language compileron all workstations that will be usedfor application development. 4. Make sure you can establish a connection to the appropriate databaseb). For additional information on how to accomplish these tasks, refer to the installation documentation for DB2 Universal Database, DB2 Universal Database SDK, the compiler being used,and theappropriate communications package. You can develop DB2 database applications on any workstation that has theDB2 SDK installed. You can run DB2 database applications either at a DB2 server workstation or on any clientworkstation thathasthe appropriate DB2 CAE software installed. You can even develop applications in such a way that one part of the application r u n s on the client workstationand another part r u n s on the server workstation. When a DB2 database application is divided across workstations in this manner, the part thatresides on the server workstation is known as a stored procedure. To precompile, compile,and link DB2 database applications, your environment paths need to be properly set. If you follow the installation instructions that come with the DB2 Universal Database SDK and the supported high-level language compiler, your environment should automatically support application development. If, however, after installing the DB2 Universal DatabaseSDK and your high-level language compiler you are unable to precompile, compile, and link your application, check the environment paths andmake sure they point to the correct drivesand directories.
Nom: Altbugh environment paths are usually set appropriately during the installation process, the compilerldevelopment interface being usedmay require that these paths are explicitly provided.
'
i
i 56
I
Part 2: Application Development Fundamentals
PM W4 Establishing the DB2 Database
Application Testing Environment As with anyother application, the best way to ensure that a DB2 database application performs as expected is t o thoroughly test it.You must perform this testing during both the actual development of the application and a h r the application coding phasehas been completed. To thoroughly test your application,establish an appropriate testing environment that includes the following items:
A testing database Appropriate testing tables Valid test data
Creating a Testing Database If your application creates, alters, or drops tables, views, indexes, or any other data objects, you shouldcreate a temporary database for testing purposes. If your application inserts, updates, or deletes data from tables and views, you shouldalso use a testing database t o prevent your application from corrupting production-level data while it is being tested. You can create a testing database in any of the following ways: By writing a small application that calls the CREATE DATABASE API call, either with a high-level programming language (such as C) or as a command file withREXX H By issuing the CREATE DATABASE command from the DB2 command-line processor By backing up theproduction database and restoring it on a dedicated application development and/ortesting workstation
Creating Testing Tables and Views To determine which testing tables and views you will need in the test database, you must first analyze the data needs of the application (or part of the application) being tested. You can performthis analysis by preparing a listof all data needed by the application and then describing how each data item in the list going is to be accessed. When the analysis is complete, youcan construct the testtables and views that arenecessary for testing theapplication in any of the following ways:
H By writing a small application in a high-level programming languagethat executes the CREATE TABLE or CREATE VIEW SQL statement and creates all necessarytables and views. (This application could be the same applicationthat creates the testing database-provided static SQL is not used.) By issuing the CREATE TABLE or CREATE VIEW SQL statement from the DB2 command-line processor
Chapter 3: Getting Startedwith DB2 Application Development W By backing upthe production database and restoring it on a dedicated application development andor testing workstation If youare developing the database schema alongwith the application, you may need to refme the definitions of the test tables repeatedly throughout the development process. Data objects such as tables and views usually cannotbe created and accessed within the same database application, because the DB2 Database Manager cannot bind SQL statements to data objects that do not exist. To make the process of creating and changing data objects less time-consuming, and to avoid this type of binding problem, you can create a separate application that constructs all necessary data objects as you are developing the main application.When the main application developmentis complete, you can then use the application that creates the data objects to construct production databases. If appropriate, this application can then be incorporated into the main application’sinstallation program.
Generating Test Data The data an application uses during testing should represent all possible data input conditions. Ifthe application is designed to check the validity of input data, the test data should include both valid and invalid data. This feature isnecessary to verify that the valid data is processed appropriately-and the invalid data is deteded and handled correctly. You can insert test datainto tables in any of the following ways:
W By writing a small application that executes the INSERT SQL statement. This statement will insert one or more rows into the specified table each time the statement is issued. W By writing a small application that executes the INSERT SELECT SQL statement. This statement will obtain data from an existing table and insert the data into the specified table each time the statementis issued. W By writing a small application that calls the IMPORT API. You can use this A P I to load large amounts of new or existing data, or you can use this API in conjunction with the EXPORT API to duplicate oneor more tables that have already been populated in a production database. By writing a small application that calls the LOAD API. You can alsouse this API to bulk loadlarge amounts of new or existing data into a database. W By backing up theproduction database and restoring it on a dedicated application development and/or testing workstation.
...
U Managing Transactions You might recallin Chapter 2, “Database Consistency Mechanisms,” that transactions were described as the basic buildingblocks that DB2 uses to maintain database consistency.All data storage, manipulation,and retrieval must be performed within one or
I
58 i
I "
Part 2: Application Development Fundamentals
more transactions, and any application that successfully connects to a database aukmatically initiates atransaction.The application, therefore, must end the transaction by issuing either a COMMIT or a ROLLBACK SQL statement (or by callingthe SQL EnaTrane ( ) CL1 function), or by disconnecting from the database (which causes the DB2 Database Manager to automatically performa COMMIToperation).
NOTE: You should not disconnect froma database and allow the DB2 Database Manager to automaticallyend the transaction, because somedatabase management systems behave differentlythan others (for example, DB21400 will performa ROLLBACK instead of a COMMIT). The'comIT SQL statement makes all changes in the transaction permanent, while the ROLLBACK SQL statement removes all these changes from the database. Once a transaction has ended, all locks held bythe transaction are freed-and another transaction can access the previously lockeddata. (Refer to Chapter 2,"DatabaseConsistency Mechanisms," for more information.) Applications should be developed in such a way that they end transactions on a timely basis, so other applications (or other transactions within the same application) are not denied accessto necessary data resources for long periodsof time. Applications should also be developed in such a way that their transactions do not inadvertently cause deadlocksituations to occur. During the execution of an application program, you can issue explicit COMMIT or ROLLBACK SQL statements to ensure that transactions are terminated on a timely basis. Keep in mind, however,that once a COMMIT or ROLLBXCK SQL statement has been issued, its processing cannot be stopped-and its effects cannot easily be reversed.
m
FM Creating and Preparing
Source Code Files The high-level programming languagestatements in in application program are usually written to a standard ASCII text file, known as a source code file, which can be edited with any text or source code editor. The source code files must have the proper file extension for the host language in which the code is written (i.e., C source files have a .C extension, and COBOL source files havea .COB extension)for the high-level language compilerto know what to do with them. If your application is writtenin an interpreted language suchas RE- you can execute the application directly from the operating system command prompt byentering the program name after connecting to the required database. Applications written in interpreted host languages do not need to be precompiled, compiled, or linked. Howevbr, if your application waswritten in a compiled host language such as C, you must perform additional steps to build your application. Beforeyou can compile your program, you must precompile it if it contains embedded SQL. Simply stated,precompilingis the process of converting embedded SQL statements into DB2 run-timeAPI calls that a host compiler can process. The SQL callsare then stored in a package, in a bind file,or in
R Chapter 3: Getting Started with DB2 Application Development
l 4
both, depending uponthe precompiler options specified.After the progr&n is precompiled, compiled,and linked, the program must thenbe bound to the test or the production database. Binding is the process of creating a package from the source codeor bind file and storing the package in the database for later use. If your application accesses more than one database, and if it contains embedded SQL,it must be bound to each database used beforeit can be executed. Precompilingand binding are only required if the source files contain embedded SQLstatements; if they contain only CL1 function calls and/or API calls, precompilingand binding are not necessary.
S U M R l A R Y " I I " m m The goalof this chapter was to provide youwith an overview of the DB2 database application development process. You should now understand what a DB2 database application is, and you should be familiar with some of the issues that affect database appliation design. You should also be familiar with the following application development building blocks: R A high-level programminglanguage
m m
SQL statements CL1 function calls API calls
You should alsobe able to establish a DB2 database application development environment and create testing databases, testing tables, and test data. Finally, you should have someunderstanding about the way source code files are created and converted into executable programs.Chapter 4 continues to present DB2 database application development fundamentals by focusing on the development of CL1applications forDB2 Universal Database, Version 5.2.
This Page Intentionally Left Blank
Writing AY1 'I. A
DB2 Universal Database application programming interface (API) calls are a set of functions that are not part of the standard SQL sublanguage nor the Call-Level Interface (CLI) routines. Where SQL and CLI are used to add, modify, and retrieve data h m a database,API calls provide an interface to the DB2 Database Manager. API calls are o h n included in embedded SQLor CL1 applications to provide additionalfunctionality that i s not covered by SQL or CL1 (for example,starting and stopping DB2's Database Manager).You can develop completeAPI applications that control database environments, modify database con@urations, and perform administrative tasks. API applications can also be used to fine-tune database performance and perform routine database maintenance.
162 I
: :
L'
Part 2: Application Development Fundamentals
This chapter begins by describing the basic structure of an A P I database application source-code file. Then,the types of A P I calls available withDB2, their naming conventions, and the special data structuressome A P I calls use is discussed. Next information on how to evaluate API return codes and display error messages is provided. Finally, this chapter concludes witha brief discussionon using the compiler and linker to convert an A P I application source-code fileto an executable program.
m
BM The Basic Structure of an API Source-
Code File An A P I application program source-code file can be dividedinto two main parts: the header and the body. The header contains, amongother things, the host-language compiler preprocessor statements that are used to merge the contents of the appropriate DB2 A P I header file(s) with the host-language source-code file. These header files contain theA P I function prototype definitions and the structuretemplates for the special data structuresthat are required by some ofthe APIs. The body contains the local v&able declarationstatements, the variable assignment statements, and one or more A P I function calls. Thebody also contains additional processing statements and error-handling statements that may be required in order for the application to perform the desired task. The sampleC programminglanguage source code in Figure 4-1 illustrates these two parts, along with some of the C language statements that might be found in them.
m
BW Types of API Function Calls DB2's rich set of A P I function callscan be dividedinto the following categories: N Database Manager ControlAPIs N Database Manager ConfigurationAPIs N Database Control APIs N Database ConfigurationAPIs N Database Directory ManagementAPIs N ClientBerner Directory ManagementAPIs
Node Management APIs N Network Support APIs
Chapter 4 Writing API Applications API SOURCE CODE FRAMEWORK
P Include Appropriate Header Files*/ #include estdio.h> #include estdlib.h> #include <string.h> m
#include 4qljra.b #include <sqljacb.h> #include <sqlenv.h> P Declare Function Prototypes*I int main(int argc, char *argv U);
r HEADER
Y
P Declare
Procedure*I int main(int argc, char *argvO) { P Declare Local Variables*I struct sqledinfo *pDB-Dirlnfo= NULL; unsigned short usHandle = 0; unsigned short usDBCount= 0; structsqlcasqlRetCode; m
PGet The Database Directory Information *I sqledosd(0, &usHandle, &usDBCount, &sqlRetCode);
*I PScan The Dlrectory Buffer And Print Info for (; usDBCount !=O; usDBCount-) sqledgne(usHandle, &pDB-Dirlnfo, &sqlRetCode) printf("%.8s\t", pDB-Dirlnfo->alias); printf("%.8s\t", pDB-Dirlnfo->alias); printf("%.30s\n", pDB-Dirlnfo->comment); }
P Free Resources (Directory Info Buffer) */ sqledcls (usHandle, &sqlRetCode); m
P ReturnTo The Operating System*I
1
return((int) sqlRetCode.sqlcode);
Figure 4-1
Parts of an API sourcecode file.
H Backup/RecoveryAPIs H Operational Utility APIs H Database MonitoringAPIs
Data UtilityAPIs H General Application Programming APIs H Application PreparationAPIs
Remote Server Connection APIs
BODY
[ j
64 I j
Part 2 Application DevelopmentFundamentals Table Space ManagementAPIs W Transaction APIs
Miscellaneous APIs Each API function call falls into one of these categories accordingto its functionality. Thef o l l o d g describes eachof these categories in more detail.
DATABASE MANAGER CONTROLAPIs. Database Manager control APIs are a set of functions that start and stop the DB2 Database Manager background process. This background process must be running before any application can gain accessto a DB2 database.
DATABASE W A G E R CONFIGURATION "1s.
The Database Manager configuration APIs are a set of functions that can be used to retrieve, change, or reset the information stored in the DB2 Database Manager configuration file. The DB2 Database Manager configuration file contains configuration parameters that affect the overall performanceof DB2's Database Manager and its global resources. These APIs are rarely used in embedded SQL or CL1 application programs;only API application programs that provide some type of generalized database utilitieshave a use for these functions.
DATABASE CONTROL APIs. Database control APIs are a set of functions that can be used to create new databases, drop (delete)or migrate existing databases, and restart DB2 databases that were not stopped correctly (for example, databases that were open whena system failure occurred).
DATABASE CONFIGURATIONAPIs. Every database has its o w n configuration filethat is automatically created when the CREATE DATABA8E API call (or command) is executed. Database configuration APIs are a set of functions that can be used to retrieve, change,or reset the information stored in these database configuration files. Each database configuration file contains configuration parameters that deet the performance of an individual database and its resource requirements. These APIs are rarely used in embedded SQL or CL1 application programs;only API application programsthat provide sometype of generalized database utilities have a use for these functions.
DATABASE DIRECTORY MANAGEMENT APIs. Database directory management APIs are a set of functions that can be usedto catalog and uncatalog databases, change database comments (descriptions), and view the entriesstored in theDB2 database directory.
CLIENT/SERVERDIRECTORYMANAGEMENT APIs. Client'Server directory managementAPIs are a set of functions that can be used to catalog and uncatalog databases that are accessed via DB2 Connect. These APIs can also view the entries stored in the DB2 DCS directory. NODE MANAGENIENT APIs. Node management APIs are a set of functions that can be used to catalog and uncatalog remote workstations, and view the entriesstored in the DB2 workstation directory.
Chapter 4: Writing API Applications NETWORK SUPPORT APIs. Network support APIs are a set of functions that can be usedto register and deregister a DB2 database server workstation's address in the NetWare bindery (on the network server).
BACKUP/RECOVERY APIs. Backup/Recovery APIs are a set of functions that can be used t o back up and restore databases, perform roll-forward recoverieson databases, and view the entries stored in a DB2 database recovery history file. Everydatabase has its own recovery file, which is automatically created when the CREATE DATABASE AF'I call (or command) is executed. Once created, this history file is automatically updated whenever the database or its table space(s) are backed up or restored. The recovery history file can be used t o reset the database to the stateit was in at any specific point intime.
OPERATIONAL UTILITY APIs. Operational utility APIs are a set of functions that can be usedto change lockstates on table spaces, reorganizethe datain database tables, update statistics on database tables, and force all users off a database (i.e., break all connections to a database). DATABASE MONITORINGAPIs. Database monitoring APIsare a set of functions that can beused database.
to collect information about the current state
of a DB2
DATA UTILITY APIs. Data utility APIsme a set of functionsthat can be usedto import data from and export data to various external file formats. GENERALAPPLICATION PROGRAMMING APIs. General application programming M I S are a set of functions that can be usedin conjunction with embedded SQL statements, CL1 function calls, and/or other API function calls to develop robust database application programs. These APIs perform suchtasks as retieving SQL and API error messages, retrieving SQLSTATE values, installing signal and interrupt handlers, and copying and freeing memory buffers used byother APIs. APPLICATION PREPARATION APIs. Application preparation APIs are a set of functions that can be used t o precompile, bind,and rebind embedded SQL source-code files.
REMOTE SERVER CONNECTION APIs. Remote server connection APIs are a set of functions that can be usedto attach to and detach from workstations (nodes) at which instance-levelfunctions are executed. Thesefunctions essentially establish (and remove) a logical instance attachment to a specified workstation and s t a r t (or end) a physical communications connection to that workstation.
TABLE SPACE MANAGEMENT APIs. Table space management APIs are a set of functions that can be usedto create new table spaces and retieve information about existing table spaces.
TRANSACTIONAPIs. Transaction APIs are a set of functions that allow two-phase commit-compliant applications to execute problem-solving functions on transactions that are tying up systemresources(otherwise known as in doubt transactions).
166
11
Part 2 Application Development Fundamentals For DB2, these resources include lockson tables andindexes, log space, and transaction storage memory. Transaction APIs are used in applications that need to query, commit, roll back,or cancel in-doubttransactions. You can cancel indoubt transactions by removing log recordsand releasing log pages associatedwith the transaction.
MISCELLANEOUS H I S . Miscellaneous APIs are a set of functions that do ‘not fall into any of the categories previously .listed. Some of these functions canbe used to retrieve user authorization information, set and retieve settings for connections made by application processes,and provide accounting informationto DRDA servers.
API Naming Conventions Although most embedded SQL statements and CL1 functions are endowed with lbng and descriptive names,most DB2’s API functions do not follow this pattern. Instead, many A P I function names creatively packas much information as possible into eight characters. The conventions used by DB2for naming most A P I functions are as follows: U Each A P I name begins with the letterssql. H The fourth character in each API name denotes the functional area to which the A P I call belongs: -e forC-specificenvironmentservices. -U forC-specificgeneral utilities. -f forC-specificconfigurationservices. a forC-speciscapplicationservices. -m -b
forC-specificmonitorservices. for C-specific table and table-space query services.
forC-specific SQLSTATE services. for a generic (language-independent) versionof the above services. U The last four characters describe the function. As you might imagine,this fourletter limitation results insome strange abbreviations. -0
-g
t6
*4
NOTE: In later versions of DB2 Universal Database,there is m limitation on the length of API functionnames. However, thefirstfourcharacters continue following these naming conventions.
There is a C-language versionof each A P I function that has been optimized forthe C/C++ programming language. Thereis also a language-independent generic version that corresponds to almost every C-languageA P I function available.If you are developing an A P I application program withC or C++, you should use the C-language specific version of the A P I function. However, if you are developing an API application program with another programming language, suchas COBOL, REXX,or FORTRAN, you must use the generic A P I functions instead of their C-language counterparts.
Chapter 4: Writing A P I Applications
IIAPI Data Structures ORen API application source-code files must contain declarationstatements that create special data structure variables. These special data structure variables are used to either provide input information to or obtain return information fromspecific API functions. Table 4-1 lists the names of the data structure templates that are stored in theDB2 API header files, alongwith brief descriptionsof what each data structure is used for. A P I data structure templates are made available to C and C++ applications when the appropriate compiler preprocessor statements (#include aamzm.z.h>) are placed in the header portion of the source-code file. Once the structure templates are made available to the source-code file,a corresponding structure variable must be declared and initialized before it can be used in anA P I function call.In addition to MI-specific structure templates, every source-code that file contains oneor more A P I calls must, at a minimum,declare a variable of the SQLCA data structure type.This variable is used by almost everyAPI function to return statusinformation to the calling application after the API call completes execution. Table 4-1
Data Structures Used by DBZS A P I Functions
rfwd_input
Passes information neededfor a roll forward recovery operationto the ROLLFORWARD DATABASE U I .
rfwd-output
Returns information generated by a roll forward recovery operationto an application program.
aql-authorieatione
Returns user authorization information to an application program.
eql-dir-entry
Transfers Database Connection Services directory information between an application programand DB2.
eqla-flaginfo
Holds flagger information.
eqlb-flagmsge
Holds flagger messages.
eqlb-tbegtate
Returns table space statistics information to an application program.
SQLB-TBSCONTQRY-DATA
Returns table space container data to an application program.
SQLB-TBSQRY-DATA
Returns table space data to an application program.
SQLB-QUESCER-DATA
Holds table space quescer information.
eqlca
Returns error and warning information to an application program.
eqlchar
Transfers variable length data between an application programand DB2.
sqlda
Transfers collections of data between an application program and DB2.
eqldcol
k
eqle-admoptione
Pasees tabel space information to the ADD
eqle-client-info
Transfers client information betweenan application program and DB2.
eqle-conn-setting
Specifies connection setting types Crype 1or Type 2) and values.
eqlepode-appc
Passes information for catalogingAFTC nodes to the CATALOQ NODE API.
s column informationto the IMPORT and EXPORT "Is. NODE API.
1
A Part 2: Application Development Fundamentals
sqle-node-appn
Passes information for catalogingAPPN nodes to the CATAGOG NODE API.
eqle-node-cpic
Passes information for cataloging CPIC nodes to the CATALOGNODE API.
eqle-node-ipxepx
Passes information for catalogingIpx/spxnodes to the CATALOG NODE
API. eqle-node-local
Passes information for cataloging LOCAL nodes to the CATALOG NODE
API. eqle-node-netb
Passes information for cataloging NetBIOS nodes to the CATALOG NobE API.
eqle-node-npipe
Passes information for catalogingnamed pipes to the CATALOG NODE API.
eqle-node-struct
Passes information for cataloging all nodes to the CATALOGNODE API.
eqle-node-tcpip
Passes information for cataloging TCP/IP nodes to the CATALOG NOD& API .
eqle-reg-nwbindery
Passes information for registering or deregisterhg the DB2 server idfrom the bindery onthe NetWare file server.
eqle-start-options
Passes start-up option infromationto the START API.
eqleabcountryinfo
Transfers country information between an application program and DB2.
eqledbaeec
Passes creation parameters to the CREATE DATABASEAPI.
SQLETSDESC
Passes table space description informationto the CREATE DATABASE API.
SQLETSCDESC
Passes table space container description informationto the CREATE DATABASE API.
eqleabetopopt
Passes stop information to the STOP DATABASE MANAaER API.
sqledinfo
Returns database directory information about a singleentry in the system or localdatabase directory to an application program.
eqleninfo
Returns node directory information about a singleentry in the node directory to an application program.
eqlfupa
Passes database and Database Manager co&guration file information between an application programand DB2.
sqh-collected
Transfers Database System Monitorcolledion count informationbetween an application program and DB2.
eqh-recording-group
Transfers Database System Monitor monitor group information between an application programand DB2.
eqlaQtimestamlY
Holds Database System Monitor monitorgroup timestamp information.
DATABASE MANAQER
Chapter 4: Writing API Applications Table 4-1
Data Structures Used by DBZS MI Functions (Continued)
S U h
Sends database system monitor requests from an application programto
DB2. eq&obj-etruct
Sends database system monitor requests from an application programto DB2.
SUlopt eqloptheader BqlOptiOllS
Passes bind options information to the BIND API and precompile options information to the PRECOMPILE PRAPI.
SQLU-LSN
Transfers log sequencenumber information between an application program and DB2.
eqlu-media-list sqlu-rnedialiet-target eqlu-media-entry sqlu-vendor . aqlu-location-entry
Holds a list of target media (BACKUP) or source media (RESTORE) for a backup image.
SQLU-RLOG-INFO
Transfers log status information between an application programand DB2.
eqlu-tableepace-bkret-list eqlu-tablespace-entry
Passes a list of table-space namea to an application program.
eqluexpt-out
Returns information generated by an export to an application program.
eqluhinfo eqluht e9 Elqluhaam
Passes information fromthe recovery history f l e to an application Program.
epluimpt-in
Passes information needed for an import operation to the IMPORTAPI. Returns information generated by an import operation to an application
epluimpt-out
Prngram. eqluload-in
Passesinformation needed for a bulk load operation to the LOAD API.
sizluload-out
Returns information generated by a bulk load operationto an application Prngram. Passes new logfle directory information to the ROLLFORWARD DATABASE API.
eplurf-newloppath eplurfjnfo
&turnsinformation generated by a rollforwad database operation to an application program.
splupi eqlpart-key
Transfers partitioning information between an application programand
SQIIXA-RECOVER
Provides a list of indoubt transactions to an application program.
SQLXA-XID
Used to identify atransaction to an application program.
DB2.
1 7_"0
l
1
Part 2 Application Development Fundamentals
II RM Error Handling You have already seen that error handling is an important part of every DB2 embedded SQL and CL1 database application."he same holdstrue for DB2 APIapplications. Whenever an A P I call is executed, status information is returned to the calling application by the following: The API functionreturn code "he SQLCA data structurevariable Like embedded SQL and CL1 applications, the best way to handle error conditions is with a common error-handling routine.
Evaluating Return Codes Whenever an API function call is executed, a special value,known as a return code, is returned to the calling application.A common error-handling routine should first determine whetheror not an error or warning conditionhas occurred by checking this return code value. If the error-handling routine discovers that anerror or warning has occurred, it should examinethe SQL codethat is also returned and process the error accordingly At a minimum, an error-handling routine should notify users that anerror or warning has occurred -and provide enough informationso the problem can be corrected.
Evaluating SQLCA Return Codes It was mentioned earlier that each API application must declare a variable of 'the SQLCA data structuretype. Wheneveran API functionis invoked froman application program, the address of this variable is always passed as an output parameter value. This variable is then used by DB2 to store status information when the API function completes execution. If an error or warning conditionoccurs during the execution of an API function call, an errorreturn-code valueis returned to the calling applicationand additional information aboutthe warning or error isplaced in theSQLCA data structurevariable. To save space,this information is stored in theform of a coded number. However, you can invoke the QET ERROR MESSAQE AF'I, using this data structurevariable, to translate the coded number into a more meaningful description, which can then be used to correct the problem. Incorporating the GET ERROR MESSAQE API call into your API application during the development phase will helpyou quicklydetermine when there is problem a in the way an API call was invoked. Incorporating the QET ERROR MESSAQE API call into your A P I application will also let theuser know whya particularAPI function failedat application run time.
Chapter 4: Writing API Applications
Evaluating SQLSTATEs If an error or warning condition occursduring the execution of an API function c a l l , a standardized error-code value is also placed in the SQLCAdata structurevariable. Like the SQLCA return-code value, the SQLSTATE information is stored in the form of a coded number. You can use the GET SQLSTATE API to translate this coded number into a more meaningful error-message description.
m
111 Creating Executable Applications Once youhave written your API application s o d e file(s), youmust convert them into an executable DB2 database application program. Thesteps used in this process are: 1. Compile the source-code files to create object modules. 2. Link the object modulesto create an executable program.
After you havewritten an API source-codefile, you must compile it with a high-level language compiler (suchas TrisualAge C++, Visual C++, and Borland C/C++).highThe level language compiler converts the source-code fileinto an object modulethat is then used bythe linker to create the executable program. The linker combines specified object modules, high-level language libraries,and DB2 libraries to produce an executable application (providedno errors or unresolved external references occur).For most operating systems, the executable application can be either an executable load module (.m) a shared library or a dynamic linklibrary (.DLL). Figure4-2 illustrates the process of converting an A P I application source-code fileto an executable application.
!!!!!l b Running, Testing, and Debugging API
Applications Once your application program has been successfully compiled and linked, you canrun the program and determine whetheror not it performs as expected. You should be able to run your DB2 APIapplicationprogram as you would any other application program on your particular operating system. If problems occur, you canthe dofollowing to help test and debug yourcode: M When compilingand linking, specifythe proper compiler and linker options so the
executable program canbe used with a symbolic debugger(usually provided with the high-level language compiler). M Make full use of the QET ERROR MESSAGE and QET SQLSTATE API function calls. Display all error message and returncodes generated whenever an API function call fails.
Part 2: Application Development Fundamentals SOURCE F'ILE
SOURCE F'ILES
WITHOUT
CONTAINING
A P I FUNCTION CALLS
API FUNCTION CALLS
a
a
A P I SPECIFIC IEADER FILES I
l \
l
HIGH-LEVEL LANGUAGE COMPILER
OBJECT
FILES
OBJECT LIBRARIES
F'ILES
HIGH-LEVEL LANGUAGE LINKER
l EXECUTABLE PROGRAM
CALL
DB2 DATABASE MANAGER
Figure 4 2 Processfor convertingA P I sourcecode files into executable DB2 application programs.
NOTE:Because some APIs require a database connection before theycan be executed, consider creating a temporary database to use while testing yourAPI application to avoid inadvertently corrupting a production database.
Chapter 4: Writing API Applications
s
m
Y
u
"
"
n
u
m
"he goal of this chapter was to provide you with an overview of how application programming interface (-1) application source-code filesare structured and to describe the processes involvedin converting A P I application source-code filesinto executable database application programs. You should knowthat A P I functions are divided according to their functionality,into the following groups: M Database Manager ControlAPIs M Database Manager ConfigurationAPIs
M Database Control APIs
W Database ConfigurationAPIs M Database Directory ManagementAPIs W ClientBerver Directory Management APIs M Node Directory Management APIs W Network Support APIs M BackupmecoveryAPIs M Operational Utility APIs M Database Monitoring APIs W Data Utility APIs General Application ProgrammingAPIs M Application Preparation APIs W Remote Server ConnectionAPIs Table Space ManagementAPIs M Transaction APIs M MiscellaneousAPIs You should alsobe familiar with the API routine naming conventions usedby IBM and thespecial data structuresthat many of the DB2 APIs require. You should know how to detect errors by evaluating the A P I return codes and how to translate SQLCAcoded values into useful error messages with the QEI ERROR MESSAQE A P I function call. You should also befamiliar with the two-step processthat is used t o convert DB2 A P I source-code filesto executable database applications: M Compiling M Linking
Finally,you should know howto run,test, and debug yourDB2 API database application onceit has been compiledand linked.
This Page Intentionally Left Blank
This Page Intentionally Left Blank
Program .. =paration:2nd General Yrogramming APIS J
Before most DB2 applicationscan be compiled and executed, they must be prepared by the SQL precompiler, andthe packages produced must be bound to one or more databasea This chapter is designed to introduce youto the set of DB2 API functions that are used to prepare applications and bind packages to DB2 databases and to the set of DB2 API functionsthat perform general tasks in an application program. The first part of this chapter providesa general discussion about embeddedSQL application preparation.Then, the functions that areused to handle exceptions,signals, and interrupts are described.Next,information about accounting strings and the function used to set them is provided. This is followed bya brief rlinmnninn nf t.heminter mnninnlntinn nnd m m r m o w w
e sectionmpare applicaided.
L 78 " __ j :
j
Part 3: Application Programming InterfaceFunctions
M F 4 Embedded SQL Application Preparation As discussed in Chapter 4, embedded SQL source-code files must always be precompiled. The precompile process converts a source-code file with embedded SQL statements into a high-level language source-code file that is made up entirely of high-level language statements. This process is important, because the high-level languagecompiler cannot interpret SQL statements, so it cannot create the appropriate object code files that are used by the linker to produce an executable program. The precompile process alsocreates a corresponding packagethat contains, amongother things, one or more data access plans.Data access plans contain informationabout how the SQL statements in thesource-code fileare to be processed by DB2at application run time. Normally, the SQL precompiler is invoked fromeither the DB2 command-line processor or from a batch or make utility file. There may betimes, however, when the SQL precompiler needs to be invoked from an application program (for example, when an embedded SQL source-code fileis provided for a portable application and theapplication's installation program needs to precompile it in order to produce the corresponding execution package). In these cases, you can use the PRECOMPILE PROGRAMfunction t o invoke the DB2 SQL precompiler. When an embedded SQL source-code file is precompiled, the corresponding execution package produced can either be stored in a database immediately or written to an external bind fileand bound to the database later (theprocess of storing this package in the appropriate database is known as binding).By default, packages are automatically bound to the database used for precompiling during the precompile process. By specifying the appropriateprecompiler options, however, you can to elect store this package in a separate file and perform the binding process at a later time. Just as the SQL precompiler is normally invoked fromeither theDB2 command-line processoror from a batch or make utility file, the DB2 bind utility is normally invokedin the same manner. There may be times, however, when you need to invoke the bind utility from an application program (for example, whena bind file is provided for a portable application and the application's installation program needsto bind it t o the databasethat the application willrun against).You can usethe BIND function to invoke the DB2 bind utility for cases suchas these. When producing execution packages for embeddedSQL applications, the SQL precompiler determines the best access plan to use by evaluating the data objects available at package creation time. As more data objects, suchas indexes, are added to the database, older packages needto be rebound so they can take advantage of new data objecta (and possibly produce more efficientdata access plans). Ifthe bind files associated with an application are available, you can rebind older packages by re-invoking the DB2 bind utility. Ifthe bind filesare no longer available, you can still rebind existing packages by using the REBIND function. Whenthe REBIND function is invoked, the specifiedpackage is recreated from the SQL statements that were stored in the SYSCAT.STATEMENTS system catalogtable when the package wasfirst created.
j I
j
Chapter 5: Program Preparation and GeneralProgramming M I S
i 71
,
_
"
t
Exception, Signal, and Interrupt Handlers A DB2 database application programmust be able to shut down gracefully whenever an exception, signal, or interrupt occurs. Typically, this process is done through an exception, signal,or interrupt handler routine. "he INSTALL SIGNAL HANDLER function can be usedto iristall a default exception, signal, or interrupt handler routine in all DB2 applications. If this function is called before any other API functions or SQL statements are executed, any DB2 operationsthat are currently in progress will be ended gracefully whenever an exception, signal, or interrupt occurs (normally, a ROLLBACK SQL statement isexecuted in order t o avoid the riskof inconsistent data). The default exception, signal, or interrupt handler is adequate for most simple, singletask applications. However, your if application programis a multithread or multiprocess application,you might wantto provide a customized exception,signal, or interrupt handler. Ifthis situation is thecase, the INTERRUPT function shouldbe called from each custom exception, signal, or interrupt handler routine to ensure that all DB2 operations currently in progress are ended gracefullyThis API function notifies DB2 that a termination has been requested. DB2 then examines which, ifany, database operation is in progress and takes appropriate action to cleanly terminate that operation. Some database operations, suchas the COMMIT and the ROLLBACK SQL statement, cannot be terminated and are allowed to complete, becausetheir completion is necessary to maintain consistent data. ~~
~~
NOTE: SQL statements other than COMMIT and ROLLBACK should never be placed in
customized exception, signal, and interrupt handlerroutines.
Pointer Manipulation and Memory Copy Functions Because many DB2 API functions use pointers foreither inputor output parameters, some type of pointer manipulation is often required whenAPI functions are included in application programs. Some host languages, such as C and C++, support pointer manipulation and provide memory copy functions. Other host languages, such as FORTRAN and COBOL, do not. "he QET ADDRJWS, COPY MEMORY,and DEREFERENCE ADDRESS functions are designed to provide pointer manipulation and memory copy functions for applications that are written in host languages that do not inherently provide this functionality.
Specifying Connection Accounting Strings DB2 database applications designedto runin a distributed environment might need to connect to and retrieve data from a Distributed Relational Database Architecture (DRDA)application server (such as DB2 forOS/390). DRDA servers often use a process
Part 3: Application Programming Interface Functions known as chargeback accountingto charge customers for their use of system resources. By using the SET ACCOUNTING STRING function, applications running on a DB2 Universal Database workstation(using DB2 Connect)canpasschargebackaccounting information directly to a DRDA server when a connection is established. Accounting strings typically contain56 bytes of system-generated data and up to 199 bytesof usersupplied data (suffix). Table 5-1 shows the fields and format of a typical accounting string. The followingis an example accountingstring: X’3C8SQL050200S/2 CHlOEXCA
ETPDDCZ
x’05‘DEPTl
The SET ACCOUNTING STRING functioncombines system-generated data with a suffix,which is provided as one of its inputparameters, t o produce the accounting string that is to be sent to the specified server at the next connect request. Therefore, an application should call this function before attempting to connect to a DRDA application server.An application can also call this function any time it needs to change the accounting string (for example,to send a different string when a connection is made t o a different DRDA database). If the SET ACCOUNTING STRING function is not called before a connection to a DRDA application server is made, the value stored in the DB~ACCOUNT environment variable will be usedas thedefault. Ifno value exists for the DB~ACCOUNT environment variable,the value of the dfi-amount-str DB2 Database Managerconfiguration parameter will be used. Table 5-1 AccountingString Fields
acct-str-len
1
A hexadecimal value representing theoverall length of the accounting string minus1. For example, this valuewould be Ox3C for a string containing61 characters.
client-prdid
8
The product ID of the client’s DB2 Client Application Enabler software. For example, the product ID for the DB2 Universal Database, Version 5.2 Client Application Enabler is ”SQL05020.”
clientglatform
18
The platform(or operating system)on which the client application runs;for example, “OS/2,” “AE,“ “DOS,” or “Windows.”
client-appl-name
20
The first 20 characters of the application name; for example,
client-authid
8
The authorizationID used to precompile and bind the applica. tion; for example, “ETPDDGZ.”
sm-len
1
A hexadecimal value representingthe overall length of the usersupplied suffix string. This field should be set to Ox00 if no mersupplied suffix string i s provided.
suffix
199
The user-suppliedsuffix string. This string can be a value specified by an application, the value of the DB2ACCOUNT environment variable, the value of the dfi-account-str DB2 Database Manager configuration parameter, or a null string.
“CH14EX6A.”
Adapted fromIBM’s DB2 Connect Users Guio!e,Table 6, p. 74.
,
#
Chapter 5: Program Preparation and General ProgrammingAPIs
i
:
l
,
".
1 1 81
i
Evaluating SQLCA Return Codes and SQLSTATE Values Most DB2 API functions require a pointer to a SQL Communications Area (SQLCA) data structurevariable as anoutput parameter.When an API functionor an embedded SQL statement completes execution, this variable contains error, warning, or status information.To save on space, this information i s stored in theform of a coded number. If the QET ERROR MESSAGE function is executed and the SQLCA data structurevariable returned from another API function is provided as input, the coded number will be translated into more meaningfulerror message text. Standardized error code values or SQLSTATEs are also stored in the SQLCA data structure variable. Like the SQLCA return code value, the SQLSTATE information is stored in the form of a coded number. You can use the GET SQLSTATE MXSSAGE function to translate this coded number into more meaningful error message text. By including either (or both) of these API functions in your DB2 database applications,you can return meaningful error and warning information to the end user whenever error and/or warning conditions occur. The Program Preparation And General Application Programming Functions Table 5-2 lists the DB2 API functions that used prepare applications, bind packagesto a r e ,
Table 5-2 Program Preparationand General ProgrammingM I S
PRECOMPILE PROGRAM
Preprocesses a source-code filethat contains embedded SQLstatements and or an generates acorresponding package that i s stored in either the database external file..
BIND
Prepares theSQL statements stored in a bind file and generates acorresponding package that is stored in the database.
REBIND
Recreates a package that is already storedin a database without using an external bind file. Retrieves the current valueof the DB2INSTANCE environment variable.
QET INSTANCE INSTALL
SIQNAL
signal handler in aDB2 database application HANDLER Installs the default interrupt
'INTERRUPT
Program. Safely stops execution of the current database request.
GET ADDRESS
Stores the addressof one variable in another variable.
'COPY
Copies data from one memorystorage areato another.
MEMORY
DEREFERENCE
ADDRESS
SET
ACCOUNTING
STRINQ
QET
ERROR
QET
SQLSTATE
GET
AUTHORIZATIONS
MESSAGE MESSAQE
Copies data from a buffer defined by a pointerto a variablethat is directly accessible by an application. Specifies accounting information that is to be sent to Distributed Relational Database Architecture (DFLDA) servers along with connect requests. Retrieves the message text associated with an SQL CommunicationsArea error code from a special DB2 error message file. Retrieves the message text associated with a SQLSTATE value from a special DB2 error message file. Retrieves the authorizations that have been granted to the currentuser.
Part 3: Application Programming Interface Functions DB2 databases, and perform general tasks in an application program. Eachof these functions are described in detail in theremainder of this chapter.
PRECOMPILE PROGRAM Purpose
syntax
The PRECOMPILE PRWRAMfunction is used to precompile (preprocess)an application program source-code filethat contains embedded SQL statements. eqlaprep (char
SQL--1-FN SQL-I-RC
char etructeqlopt structeqlca
Parameters
*ProgramName, *M#gFileName, *PrepOptiona, *SPLcA);
PmgramName
A pointer to a location in memory wherethe name of the source-
MsgFilelvame
code file to be precompiledis stored. A pointer t o a location in memory wherethe name of the fde or device that all error, warning,and informational messages generated are to be written to is stored.
PrepOptions
A pointer to a sqlopt structure that contains the precompiler options
SQLCA
A pointer to alocation in memorywherea SQL Communications Area (SQLCA)data structurevariable is stored. This variable
(if any) that should be used when precompiling the source-code file.
returns either status information (ifthe function executed successfully)or error information (ifthe function failed)to the calling application.
Includes
#include<sql.h>
Description
The PRECOMPILE PRWRAMfunction is used to precompile (preprocess)an application program source-code filethat contains embedded SQL statements. When a sourcecode file containing embedded SQL statements is precompiled, a modified sourcefile containing host language function calls for each SQL statement used is produced, and by default, a package forthe SQL statements coded in thefile is created and bound to the database to which a connectionhas been established. The name of the package to be created is, by default, the same as the firsteight characters of the source-code file name (minus the file extensionand converted to uppercase) from whichthe package was generated. However, you can overwrite bind filenames and package names by using the SQL-BINILOPT and the SQL-PKQ-OPT options whenthis function is called. A special structure (sqlopt) is used to pass different precompile optionsto the SQL precompiler whenthis function is called. Thesqlopt structure isdefined in sql.h as follows:
Chapter 5: Program Preparationand General ProgrammingAPIs struct sqlopt {
structeqloptheaderheader; etruct sqloptione option[l];
/* /* /*
A
*/
PrecompileDind optionsheader
*/
An array of PrecompileDind
*/
options
1;
T h i s structure is composed of two or more additional structures: one sqloptheader
structure and one or more sqloptions structures. The sqloptheader structure is defined in sql.h as follows: struct sqloptheader (
unsigned long allocated;
unsigned long used;
/* Number of q l o p t i o n e structuree that* / /* have been allocated (the number of */ /* elements i n the array specified in */ /* the option parameter of the */ /* sqlopt structure) */ /* The actual numberof Bt?lOptiOnS */
/* /* /*
structures used (the actual number of type and Val option pairs eupplied)
*/
*/
*/
The sqloptwns structure is defined in sq1.h as follows: struct sqloptions
I unsigned long type; unsigned long Val; 1;
/ * Precompile/Bind option type /* Precompile/Bind option value
*/
*/
Table 53 lists thevalues that can be used for the type and ual fields of the sqloptions structure, as well as a description about what each typelval option causes the SQL precompiler (or the DB2 Bind utility) to do. The PRECOMPILE PROGRAM function executesunder the currenttransaction (which was initiated by a connection to a database), and upon completion,it automatically issues either a C O ~ orT a ROLLBACK SQL statement to terminate thetransaction.
Comments
The MsgFileName parameter can contain the path and name of an operating system fileor a standard device (such as standarderror or standard out). If the MsgFileName parameter contains the pathand name of a file that already exists, the existing filewill be overwritten whenthis function is executed. Ifthis parameter contains the pathand name of a file that does notexist, a new file will be created.
I
i
p
Part 3: Application Programming Interface Functions
Table 5-3 Values Precompile/Bind and Options
b
No
Specifies that thepackage doesnot already exist and is to be created.
SQL-ACTION-REPLACE
No
Specifies that thepackage exists and is to be replaced.This value is the default valuefor the SOL-ACTION-OPT option.
NULL
Yes
Indicates that no bind file is to be generated by the precompiler. This option can only be used withthe SQL precompiler.
sqlchur structure value
Yes
Indicates that a bind file with the specified name is to be generated by the precompiler. "his option , can only be used withthe SQL precompiler.
Yes
Specifies that row blocking should be performedfor read-only cursors, cursors not specified 88 FOR UPDATE OF, and cursors for which no static DELETE WHERE CURRENT OF statements are executed. In this case, ambiguousm o r s are treated asread-only cursors.
SQL-BL-NO
Yes
Specifies that row blockingis not to be performed for cursors. In this case, ambiguouscursors are treated asupdateable cursors.
SQL-BL-UNAMEIO
Yes
Specifies that row blockingshould be performed for read-only cursom, cursors notspecified as FOR UPDATE OF, m o r s for which no static DELETE WIIERE CURRENT OF statements areexecuted, and cursors that do not havedynamic statements associated with them. In this case, ambiguouscursors are treated as updateable cursors.
SQL-CCSIW-OPT
unsigned long integer value
No
Specifies the coded character set identifier that is to be used for double-byte characters in character column definitions specified in CREATE TABLE and ALTER TABLE SQL Statements.
SQL-CCSIDM-OPT
unsigned long integer value
No
Specifies the coded character set identifier that isto be used for
SQL-ACTION-ADD SQL-ACTION-OPT
SQL-BIND-OPT
SQL-BL-ALL SQL-BLOCK-OPT
Chapter 5: Program Preparation and GeneralProgramming APIs
.~
,...,,,,.
.--
"~
ecompilelBind Option
~
"
Value
85
: ." . .
1
Currently Supported Description mixed-byte characters in character column definitions specified in CREATE TABLEmdALTER TABLE
SQL statements. SQL-CCSIDS-OPT
unsigned long integer value
No
Specifies the coded character set identifier that is to be used for singlebyte charactersin character column definitions specified in CREATE TABLEadALTER TABLE
SQL statements. SQL-CHARSUB-BIT SOL-CHARSUB-OPT
SQL-CHARSUB-DEFAULT
No
Specifies that theFOR BIT DATA SQL character subtypeis to be used in all new character column definitions specified in CREATE TABLE and ALTER TABLE SQL statements (unless otherwise explicitly specified).
No
Specifies that thetarget systemdefined default character subtype is to be used in all new character column definitions specified in CREATE TABLEmdALTER TABLE
SQL statements (unless otherwise explicitly specified).This value i s the default valuefor the SQL-CHARSUB-OPT option.
No
Specifies that theFOR MIXED DATA SQL character subtypeis to be usedin all new character col-
umn definitions specified in TABLE and ALTER TABLE SQL statements (unless otherwise explicitly specified). SQL-CHARSUB-SBCS
SQL-CNCTLREQD-NO SQL-CNULREQD-OPT
SQL-CNULREQD-YJW
No
Specifies that the FOR SBCS DATA SQL character subtypeis to be used in all new character column definitions specified in CREATE TABLE and ALTER TABLE SQL statements (unless otherwise explicitly specified).
No
Specifies that c/c++ NULL terminated strings are not NULL terminated if truncation occurs.
No
Specifies that c/c++ NULL terminated strings are padded with blanks and always includea
1 I
" "
,
'
86 I '
Part 3 Application Programming Interface Functions
"
NULL-terminated character, even when if truncation occurs. SQL-COLLECTION-OPT
sqlchar structure value
Yes
Specities an eight-charactercollection identifier that is to be assigned to the package being created. If no collection identifieris specified, the authorization ID of the user executing the PRECOMPILE PROGM or BIND function will be used.
SQLCONNECT-2
Yes
Specifies that CONNECT Sf& statements are to be processed as Type 2 connects.
Yes
Specifies that CONNECT SQL statements are to be processedas Type 1 Connects.
Yes
Specifies that CONNECT SQL statements are to be processedas Type 2 Connects.
Yes
Specifies that a date and timeformat that is associated withthe country code of the database is to be used for date and timevalues.
SQL DATETIME-EUR
Yes
Specifies that theB M standard for European date and timefor-, mat is tobe used for date and time values.
SQL-DATETIME-IS0
Yes
Specities that theInternational Standards Organization W O ) date and time formatis to be used for date and timevalues.
SQL-DATETIME-JIS
Yes
Specifies that the Japanese Industrial Standard date and time format is to be used for date and time values.
SQLL~IATETIKE-LOC
Yes
Specifies that thelocaldate and time formatthat is associated with the country code of the database is to be used fordate andtime values.
SQL-DATETIMB-USA
Yes
Specifies that theIBM standard for the United Statesof America date and time format is to be used for date and timevalues.
SQL-CONNECT-1 SQL-CONNECT-OPT
SQL-CONNECT-2
SQL-DATETIME-OPT DATETIME-DEF SQL
-15
:
Chapter 5: Program Preparation and General ProgrammingAPIs
" "
87 1 .. 1
No
Specifies that 15-digit precisionis to be used in decimal arithmetic operations.
No
Specifies that 31-digit precision is to be used in decimal arithmetic operations.
No
Specifies that a comma is to be used as a decimal point indicator in decimal and floating point literals.
SQL-DECDEL-PERIOD
No
Specifies that a period is to be used as a decimal pointindicator in decimal andfloating point literals.
SQL-DEFERRED-PREPARE-NO
Yes
Specifies that PREPARE SQL statements are to be executedat the time theyare issued.
SQL-DEFERRED-PREPARE-YES
Yes
Specifies that theexecution of PREPARE SQL statements is to be deferred untila corresponding OPEN, DESCRIBE, or EXECUTE statement i s issued.
SQL-DEC-OPT
SQL-DEC-31
SQL-DECDEL-COBIWL SQL-DECDEL-OPT
SQL-DEFERRED-PREPARE-OPT
i.
SQL-DEFERRED-PREPARE~L Yes
Specifies that all PREPARE SQL Statements (otherthan PREPARE INTO statements which contain parameter markers) areto be executed at thetime theyare issued.
If a PREPARE SQL statement uses an INTO clause to return information to an SQL DescriptorArea (SQLDA) data structurevariable, the application must not reference the content of the SQLDA variable until the OPEN, DESCRIBE,or EXECUTE SQL statement has been executed. SQL-DEGREE-ANY SQL-DEGREE-OPT
unsigned long integer between 2 and 32767
Yes
Specifies that queries are to be executed using any degree of I/O parallel processing.
Yes
Specifies the degree of parallel I/O processing that is to be used when executing queries.
Part 3: Application Programming Interface Functions Table 5-3 Precornpile/Bind Options and Values (Continued) ";";S
f
i
z
x
,, .;mm < ,'I../
m
d
Option
.. ~
~
. *_
~
~
Value
w
a
-
-
~
CuiTently supported Description
SQL-DEGREE-1
Yes
~
D
?":
Specifies that I/O parallel processing cannot be used to execute SQL queries. This value is the default value for the SQL-DEGREE-OPT
option. Yes
SpecSes thatall database connections are to be disconnected when a COMMIT SQL statement is executed.
SQL-DISCONNECT-EXPL
Yes
Specifies that only database connections that have beenexplicitly marked for release by the RELEASE SQL statement areto be disconnected when a COMMIT SQL statement is executed.
SQL-DISCONNECT-COND
Yes
Specifies that only database connections that have beenexplicitly marked for release by the RELEASE SQL statement or that do not have any cursom that were defined as WITH HOLD open are t0 be disconnected when aCOMMIT SQL statement is executed.
SQL-DYNAMICRULES-BIND
No
Specifies that thepackage owner is to be used as the authorization identifier when executingdynamic SQL statements.
SQL-DYNAMICRULES-DEFINE
NO
Specifies that thedefiner of a userdefined function or stored procedure is to be used as theauthorization identifier when executing dynamic SQL Statementsin the user-defined function or stored procedure.
SQL-DYNAMICRULES-INVOKE
NO
Specifies that the invoker of a user-defined function or stored procedure is to be used as the authorization identifier when executing dynamicSQL statements in theuser-defined functionor stored procedure.
SQL-DYNAMICRULES-NJN
No
Specifies that theauthorization ID of the user executingthe package is to be used as the authorization identifier when executing dynamic SQL statements.
SQL-EXPLAINSL
Yes
Specifies that Explain tablesare to
SQL-DISCONNECT-OPT SQL-DISCONNECT_ADTO
SQL-EXPLAIN-OPT
Chapter 5: Program Preparation and General ProgrammingAPIs Table 5-3 Precompile/Bind Options and Values (Continued) Preco&pilmind Option
Value
c;urrently Supported Deecription be populated with information about the access plans chosen for each eligible static SQL statement a t precompile time and with each dynamic SQLstatement at application run time.
SQL-EXPLSNAP-OPT
No
Specifies that Explain tablesare to be populated with information about the access plans chosen for each SQL statement in the package.
SQL-EXPLAIN-NO
No
Specifies that Explain information about the access plans chosen for each SQLstatement in the package is not to be stored in the Explain tables.
SQL-EXPLSNAP-NO
No
Specifies that anExplain snapshot will not be written to the Explain tables for each eligible static SQL statement in the package.
SQL-EXPLSNAP-YES
No
Specifies that an Explain snapshot is to be written to the Explain tables for each eligible static SQL statement in the package.
SQL-EXPLSNAP-ALL
No
Specifies that anExplain snapshot is to be written to the Explain tables for each eligiblestatic SQL statement in the package, and that Explain snapshot information is also to be gathered for eligible dynamic SQLStatements at application runtime-even if the CURRENT EXPLAIN
SNAPSHOT
register is set to NO. SQL-FLAQ-OPT
SQL-SQL92E-SYNTAX
Yes
Specifies that SQL statements are to be checked against ISO/ANSI SQL92 standards, andall deviations are to be reported.
Yes
Specifies that SQL statements are to be checked against MVS DB2 Version 2.3 SQLsyntax, andall deviations are to be reported.
Yes
Specifies that all SQL statements are to be checked against M V S DB2 Version3.1 SQL syntax, and all deviations are to be reported.
I
90
Table 5-3
Part 3: Application Programming Interface Functions Precompile/BindOptions and Values(Continued) -.h._,,.. ., .... !... , ? \ z %.c. Curwntly
v-. P r m
.i:.2
i I
,
,
,
.I
Option
v
y
Supported Description SQL-MVSDBSV41-SYNTAX
Yes
Specifies that SQL statements are to be checked against MVS DB2 Version 4.1 SQL syntax, and all deviations are to be reported.
SQL-FUNCTION-PATH
sqlchar structure value
No
Specifies the function path to be used when resolving user-defined distinct datatypes and functions referenced in staticSQL statements.
SQL-GENERIC-OPT
sqlchar structure value
Yes
Provides a means of passing new bind options (as a single string)to target DRDA databases.
SQL-QRANT-GROUP-OPT
sqlchar structure value
Yes
Specifies that theEXECUTE and BIND authorizations are to be granted to a specific user ID. This option can only be used withthe DB2 Bind utility.
sqlchar structure value
Yes
Specifies that theEXECUTE and BIND authorizations are to be granted to a specified user ID or group ID (the groupID specified can be PUBLIC). This option can be usedonly with the DB2 Bind utility.
SQL-QRANT-USELOPT
sqlchar structure value
Yes
S p e d e s t h athe t EXECUTE and BIND authorizations are to be granted to a specific user ID.This option can only beused withthe DB2 Bind utility.
SQL-INSERT-OPT
SQL-INSERT-BUF
Yes
Specifies that insert operations performed by an application should be buffered.
SQL-INSERT-DEF
Yes
Specifies that insert operations performed by an application should not be buffered.
SQL-RE?D-STAB
Yes
Specifies that theRead Stability isolation level should be used to isolate the effects of other executing applicationsh m the application usingthis package.
SQL-NO-COMMIT
No
Specifies that commitment control is not to be used by this package
SQL-CURSOR-STAB
Yes
Specifies that the Cursor Stability isolation level should be used to
I
p”1 l
Chapter 5: Program Preparation and General Programming M I S
~
j ’.
li
91.“_I 1 . ”.
Table 5-3 Precornpile/Bind Options and Values (Continued)
isolate the effects of other executing applicationsfrom the application using thispackage. SQL-REP”
SQL-LEVEL-OPT
value structure sqlchar
SQL-LINE-MACROS
SQL-OPTIMIZE SQL-OPTIM-OPT
SQL-WNT-OPTIMIZE
SQL-OWNER-OPT
value structure sqlchar
Yes
Specifies that theRepeatable Read isolation level shouldbe used to isolate the effects of other executing applicationsfrom the application using thispackage.
Yes
Specifies that theUncommitted Read isolation level should be used to isolate the effects of other executing applicationsfrom the application usingthis package.
No
Specifies the level consistency token that a module stored in a package is to use. “his token verifies that therequesting application and the database package are synchronized. This option can only be used withthe SQL precompiler.
Yes
Specifies that thegeneration of #line macros in themodified C/C++ file produced are to be s u p pressed.
Yes
Specifies that #line macros are to be embeddedin the modified WC++ file produced.
Yes
Specifies that theprecompiler is to optimize the initialization of internal SQLDA variables that areused when host variablesare referenced in embedded SQLstatements.
Yes
Specifies that theprecompiler is not to optimize the initialization of internal SQLDA variables that are used when host variablesare referenced in embedded SQL statements.
No
Specifies an eight-character authorization ID that identifies the package owner.By default, the authorization ID of the userperforming the precompile or bind process is used to identify the package owner.
Table 5-3 PrecompileIBind Options and Values (Continued) 4.
l\ U L L
Yes
Specifies that a package is not to be created. This option can only be used with the SQL precompiler.
sqlchar structure value
Yes
Specifies the name of the package that is to be created. If a package name is not specified, the package name is the uppercase nameof the source-code file being precompiled (truncated to eight characters and minus the extension)."his option can only be used withthe SQL precompiler.
SQL-PREP-OUTPUT-OPT
sqlchar structure value
Yes
Specifies the name of the modified source-code filethat is produced by the precompiler.
SQL-QWMIIFIER-OPT
sqlchur structure value
No
Spedies animplicit qualifiername that is to used for all unqualified table names, views, indexes, and aliases contained in thepackage. By default, the authorizationID of the user performing the precompile o r bind processis used as the implicit qualSer.
SQL-QUERYOPT-OPT
SOL-QUERYOPT-0 SQL-QUERYOPT-1 SQL-QUERYOPT-2 SQL-QUERYOPT-3 SQL-QUERYOPT-5 SQL-QUERYOPT-7 SQL-QUERYOPT-9
No
Specifies the level of optimization to use whenprecompiling the static SQL statements contained in the package. The defaultoptimiaation level is SQL-QUERYOPT-5.
SQL-RELEASE-OPT
SQL-RELEASE-COMMIT
No
Specifies that resources acquired for dynamic SQLstatements are to be released at each COMMIT point. This value is the default valuefor the SQL-RELEASE-OPT option.
SQL-RELEASE-DEALLOCATE
No
Specifies that resources acquired for dynamic SQLStatements are to be released whenthe application terminates.
structure sqlchur value
No
Identifies a specific versionof a package to replace whenthe SQL-ACTION-REPLACE value is specified forthe SQL-ACTION-OPT option. "his option can only be used with theDB2 Bind utility.
SQL-REPLVER-OPT
Chapter 5: Program Preparation and General ProgrammingAPIs Table 5-3 Precompile/Bind Options and Values (Continued)
Description
Option SQL-RETAIN-NO SQL-RETAIN-OPT
SQL-RETAIN-YES
No
Specifies that EXEXUTE authorizations are not to be preserved when apackage is replaced. "his option canonly be used withthe DB2 Bind utility.
No
Specifies that MECUTE authorizations are to be preserved when a package is replaced. This option can only be used withthe DB2 Bind utility.This value is the default valuefor SQL-RETAIN-OPT.
SQL-RULES-OPT
SQL-S?iA-OPT
SQL-SQLERROR-OPT
SQL-RULES-DB2
Yes
Specifies that theCONNECT SQL statement canbe used to switch between established connections.
SQL-RULES-STD
Yes
Specifies that theCONNECT SQL statement canonly be usedto establish new connections.
SQL-SAA-NO
Yes
Specifies that themodified FORTRAN source-code file produced by the precompiler is inconsistent with the SAA definition.
SQL-BAA-YFS
Yes
Specifies that themodified FORTRAN source-code file produced by the precompiler is consistent with the SAA definition.
SQL-SQLERROR-CHECK
Yes
Specifies that thetarget system is to perform syntax and semantic checks on the SQL statements being boundto the database. If an error is encountered, apackage will not be created.
SQL-SQLERROR-CONTINUE
No
Specifies that thetarget system is to perform syntax and semantic checks on the SQL statements being bound to the database. If an error is encountered, a package will still be created.
No
Specifies that theprecompiler is to perform syntax and semantic checks on the SQL statements being precompiled. Ifan error is encountered, a package or a bind file will not be created. This value is thedefault valuefor the
1 94
Part 3 Application Programming Interface Functions
mently
BPlorted
Description SQL-SQLERROR-OPT option.
SQL-SQLonuW OPT
SQL-SQLWARN-NO
No
Specifies that warning messages will not be returned from the SQL precompiler.
SQL-SQLWARN-YFS
No
Specifies that warning messages will be returned from the SQL precompiler. This value is the default vdue for the SQL-SQLWARN-OPT option.
Yes
Specifies that theIBM DB2 rules apply for both the syntax and semantics of static anddynamio SQL statements coded in an application.
SQL-MIA-COMP
Yes
Specifies that theISO/ANSI SQL92 rules applyfor both the syntax and semanticsof static and dynamic SQL statements coded in an application (SQLCA variables are used for error reporting).
SQL-SQL92E-COMP
Yes
Specifies that theISO/ANSI SQL92 rules apply for both the syntax and semanticsof static and dynamic SQLstatements coded in an application (SQLCODE and SQLSTATE variables are used for error reporting).
No
Specifies that anapostrophe is to be used as the string delimiter within SQL statements.
No
Specifies that double quotation marks are to be used as the string delimiter withinSQL statements.
Yes
Specifies that a one-phase commit is to be used to commit the work done by each database in multiple database transactions.
SQL-SYNC-TWOPHASE
Yes
Specifies that a TransactionManager is to be used to perform two-phase commitsto commit the work done byeach databasein multiple database transactions
SQL-SYNC-NONE
Yes
Specifies that no Transaction Manager is to be used to perform two-
SQL-STANDARDS-OPT SQL-SAA-COMP
SQL-STRDEL-APOSTROPHE SQL-STRDEL-OPT
SQL-STRDEL-QUOTE
SQL-SYNCPOINT-OPT SQL-SYNC-ONEPHASE
,
Chapter 5: Program Preparation and General Programming
APIs
I
: I
1- 5 .
" "
1
Table 5-3 Precompile/Bind Options and Values (Continued) "~<"-.xcwm#7xe"
Currently Supported Description
Option
phase commits, and that single updater-multiple reader operations are not enforced. SQL-NO-SYNTAX-CHECK
Yes
Specifies that theprecompiler is to create a package or bind file along with a modified source codefde, rather thanperforming SQL syntax checking only.
SQL-SYNTAX-CHECK
Yes
Specifies that only SQL syntax checking is to be performed bythe precompiler. No package or bind file is to be generated. Instructs theprecompiler to produce modified source codethat is tailored to a specific compiler(on the currentplatform).
SQL-TARET-OPT
sqlchar structure value
SQL-TEXT-OPT
sqlchur structure value
No
Specifies a description that is to be assigned to the package. The description canbe up to 255 characters long.
SQL-VALIDATE-OPT
SQL-VALIDATE-BIND
No
Specifies that authorization validation is to be performed by the DB2 Database Managerat precompilel bind time.
SQL-VALIDATE-Rm
No
Specifies that authorization validation is performed bythe DB2 Database Managerat application run time. "his value is the default value for the SQL-VALIDATE-OPT option.
SQL-VERSION-OPT
sqlchar structure value
No
Specifies the Version identifier for a package. "his option can only be used withthe SQL precompiler.
SQL-WCIShR-OPT
SQL-WCHF&-CONVERT
Yes
Specifies that datastored in host variables that were declared using the wchar-t base typeare to be converted to DBCS format, using the ANSI Cfunction wcstombs ( ) (output DBCS data is converted to wchar-t format usingthe ANSI C function mbstowcs ( ) 1.
Yes
Specifies that datastored in host variables that were declared using the wchar-t base typeare not to be convertedto DBCS format (and vice-versa). This means that data
Table 5-3 Precompile/Bind Options and Values (Continued)
stored in wchar-t format cannot be passed to the DB2 Database Manager.
Notes: Whensqlchar structure option values are specified, the sqlopt.sqloptiomva1 field must contain a pointer to a valid sqkhur structure. This structure contains a character string that specifies the option value to be set, along with the length of the character string. In most cases, if an unsupported option is specified, the option will be ignored and a warning will be returned by the SQL precompiler or the DB2 bind utility. Adapted from IBM's DB2 Universal Database A P Z Reference,Table 4, pages 21 to 24 and Table 5, pages 14 and 16,and thePRECOMPILE PROGRAM and BIND commands documentation in IBM's DB2 Universal Database
Command Reference, pages 305 to 324 and 98 to 110.
H The SQL precompiler expects the following high-levellanguage source-code file
extensions: .sqc Capplications .sqx C++applications .sqC C++ applications (UNIX) .sqb COBOL applications .sqf FORTRAN applications When the SQL-TARGET-OPT option is used, the inputfile does not haveto use one' of these predefined extensions. The precompile processstops whenever afatal error occurs or whenever moretlian 100 general errors occur. If the precompile process stops,DB2 will attempt to close all opened filesand the package being produced will be discarded.
Authorization Only users with System Administrator (SYSADM) authority, Database Administrator (DBADM) authority, BINDADD authority (if the package that will begenerated does not exist),or BIND authority (if the package that will begenerated already exists) are allowed to execute this function. The user also needsall authorizations that arerequired to compile any static SQL Statements coded in thespecified source-code file. Authorization privileges that have been granted t o groups and to PUBLIC are not used when authorization checking is performed forstatic SQL statements. 1
Chapter 5: ProgramPreparation and GeneralProgramming APIs
!
1
i 971
NOTE:If a user has SYSADM authority but not explicit authority to complete the bind process, the DB2 Database Manager will automatically give the user explicit DBADM authority. See Also
Example
BIND
The following C++ program illustrates how to use the PRECOMPILE P R O O R Afunction ~~ to precompile an embedded SQL source-code file:
/* /* NAME: /* PURPOSE: /* /* PROQRAM /* /*
CHSEX1.SQC Illuetrate How To Use The Following DB2 API Function In A C++ Program:
*/ PRECOMPILE
*/ */
*/ */ */ */
// Include The Appropriate Header Files #include <windows.h> #include
#include <sqlutil.h> #include <sql.h>
/ / Define The API-Claee Claes claea API-Claes
c / / Attributes public: struct sqlca sqlca;
1;
/ / operatione public : long Precompileprogram( ;
/ / Define The Precompileprogram0 Member
Function
long API_Clase::PrecompileProgram()
c / / Declare The LocalMemory Variables etruct sqlopt StlVCt BglOptiOnS struct eqlchar char int
*Prepoptiona; *optionePtr; *BindFile; Stringtll]; Buff Size}
/ / Store The Bina File Name In A SQLCHAR Structure strcpy(String, "EXAMPLE.BND"); BindFile = (struct eqlchar *) malloc (strlen(String) + eizeof(etruct eqlchar)); BindFile->length P strlen(String); stmcpy(BindPile->data, String, strlen(String));
Part 3: Application Programming Interface Functions / / Allocate And InitializeThe Precompiler Optione Structure Buffsize = eizeof(etruct eqlopt) + eizeof(etruct eqloptheader) (2 eizeof(etruct eq1optione))t PrepOptione (etruct eqlopt *) malloc(Buff8ize)t PrepOptione->header.allocated = 2; PrepOptione->header.ueed I l;
-
+
/ / Precompile The Specified Source Code File eqlaprep(*'EXAHPLE.SQCn, uPREPINFO.DATn, PrepOptione, breqlca)) / / If The Source Code File Wae Succeeefully Precompiled, Dieplay / / A Succeee Meeeage if (eqlca.eplcode == SQL-RC-OK) {
1
1
tout << umtAMPLE.SQC ham been precompiled. Checkthe file cout (< uPREPINFO.DAT for" << end11 cout c < Uadditional information.tr edl)
/ / Return TheSQLCA Return return(eqlca.eqlcode)t
CodeTo The
Calling
Function
/*
/* /*
*/ */
The Main Function
*/
int main( ) t / / Declare The Local M e n s o r y Variables rc long m SQL-RC-OKI atructeqlcaeqlcat
/ / COMeCt To The SAMPLE Databaee TO SAMPLE USER ueerID EXEC SQL CONNECT
USINQ
/ / Precompile An Embedded SQL (.SW) Program rc = Example.Preco~ileProgramOt
/ / Ieeue A Rollback To Free EXEC SQL ROLLBACK)
All
Locke
/ / Dieconnect From The SAMPLE Databaee EXEC SQL DISCONNECT CDRRENT)
1
/ / Return To The return(rc) I
Operating
Syetem
paasword)
Chapter 5: Program Preparation and General ProgrammingAPIs
BIND Purpose
The BIND function is used to invoke the bind utility, which prepares the SQL statements stored in a bind filethat was generated by the SQL precompiler and creates a corresponding packagethat is stored in the database. SQL-API-RC SQL-API-FN
eqlabndx (char char e t a c t eqlopt e t r u c t eqlca
Paraketern
BindFileName
MsgFileName
BindOptions
SQLCA
*BindFileName, *MEgFileName, *BinUOptionrr, *SPLCA);
A pointer to a location in memory where the name of the bind file (or the name of a file containinga list of bind files)to be bound to the currentconnected database is stored. A pointer to a location in memory where the name of the file or device that all error, warning,and informational messages generated are to be written to is stored. A pointer to a sqlopt structure that contains the bind options (if any) that should be used when the specified bind file(s)are bound to the current connected database. A pointer to a location in memorywhere a SQL Communications Area (SQLCA)data structurevariable is stored. This variable returns either statusinformation (if the function executed successfully) or error information (ifthe function failed)to the calling application.
Includes
,#include <eql.h>
Dedption
The BIND function is used to invoke the bind utility, which prepares the SQL statements stored in a bind filethat was generated by the SQL precompiler and creates a corresponding packagethat is stored in thedatabase. Binding canbe performed as partof the precompile processor as a separate process at a later timthis function is only used when bindingis performed as a separate process. A special structure (sqlopt) is used to pass different bind options to the bind utility when this function is called. Referto the PRECOMPILE PROGRAM function for a detailed description of the sqlopt structure and for more information about the bind options that areavailable. The BIND function executesunder the currenttransaction (which wasinitiated by a connection to a database) and, upon completion,it automatically issues either a COMMIT or a ROLLBACK SQL statement to terminate the current transaction.
Comments
H The MsgFileName parameter can contain the path and name of an operating
system fileor a standard device (suchas standard erroror standard out). H If the MsgFileName parameter contains the path andname of a file that already exists, the existing filewill be overwritten whenthis function is executed. Ifthis
Part 3: Application Programming Interface Functions parameter contains the pathand name of a filethat does notexist, a new filewill be created. W The bindutility expects all bind filesto have the extension .bnd. U The BindFileName parameter can contain the name of a specific bind fileor the name of a filethat contains a list of bind file names; If the name of a file containing alist of bind filenames is specified,it must be precededwith the at symbol (Q,and the file itself must have the extension .lst. For example, a fully qualified bindlist file name on Windows NT might be C : \@all. let. W Path specifications can be supplied with bind file names in a bind list file. Ifthe bind list file contains two or more bind file names,all but the lastbind file name should be followed bya plus sign (+). The bind filepaths and names can be placed on one or more lines in thebind list file. For example, on Windows NT, a bind list file mightcontain the following list: mybindl .bnh+mybind2. C:mybind3.bnd+ mybind4.bnd
bnd+
U By default, the name of the package t o be created by this function is the same ,as
the fist eight characters of the source-code filename (minus the file extensionand converted to uppercase) that was usedto generate the bind file. However, you can overwrite bind file names and package names by using the SQL-BIND-OPT and SQL-PKQ-OPT options with the PRECOMPILE PROGRAM function. W The bind process stops whenever fatal a error occurs or whenever morethan 100 general errors occur. If the bind process stops,DB2 will attempt to close all opened files and the package($ being produced will be discarded. m In a multi-node database environment, this function can be called from any node listed in thedb2nodes.cfg configuration file. The node that this function is called from automaticallyupdates the database catalog on the catalog node,and the changes are visible to all nodes.
Connection
This function can only be called if a connection to a database exists.
Requirements
Authorization Only users with System Administrator (SYSADM) authority, Database Administrator (DBADM) authority, BINDADD authority (if the package that will be generated does not exist), or BIND authority (if the package that will begenerated already exists) are allowed to execute this function call. The user also needsall authorizations required to compile any static SQL statements coded in thespecified source-code file. Authorization privileges that have been granted to groups and to PUBLIC are not used whenauthorization checking is performed forstatic SQL statements.
Chapter 5: Program Preparation and General Programming APIs NOTE:If a user has SYSADM authority but not explicit authority to complete the bind process, the DB2Database Manager will automatically givethe user explicit DBADM authority. see Also
Example
PRECOMPILE
PROORAM
The following C++ program illustrates how to use the BIND function to bind the contents of an external bindfile to the current connected database:
/*
/*
/* /* /* /* /*
NAME:
CHSEX2.SQC PURPOSE: Illustrate How To Use The Following DB2 API Function In A C++ Programs BIND
*/
/*
*/
/ / Include The Appropriate Header Files #include <windows.h> #include #include <sqlutil.h> #include <sql.h> / / Define The API-Class Class class API-Class i / / Attributes public : struct sqlca sqlca;
1;
*/ */ */ */ */ */
/ / Operations public : long BindProgram();
/ / Define The BindProgram() Member Function long API_Class::BindProgram()
c / / Declare The Local Memory Variables *BindOptions; sqlopt struct struct sqloptions *OptionsPtr; struct sqlchar *Collection; String[14] char 8 Buff int Size; / / Store The Collection Name In A SQLCHAR Structure strcpy(String, UBINDSAMPD); Collection = (struct sqlchar* ) malloc (strlen(String) + sizeof(struct sqlchar)); Collection->length P strlen(8tring); etrncpy(Col1ection->data, String, strlen(String));
!
102
j
Part 3: Application Programming Interface Functions
:
/ / Allocate And Initialize The;Bind Options Structure Buffsize = sizeof(8truct sqlopt) + sizeof(struct sqloptheader) + (2 * sizeof (struct sqloptions) ); BindOptions = (struct sqlopt *) malloc(BuffSize); BindOptions->header.allocated = 2; BindOgtions->header.used = 1;
Optionsptr = (struct sqloptions *) BindOptions->option; OptionsPtr->type = SQL-COLLECTION-OPT; OptionsPtr->val = (unsigned long) Collection; / / Bind The Specified Bind FileTo The SAMPLE Database sqlabnclx("EXZ4MPLE.BND", "BINDINFO.DAT", BindOptions, brsqlca) ; / / If The Bind FileWas Successfully BoundTo The / / Database, Display A Success Message if (sglca.sqlcode == SQL-RC-OK)
SAMPLE
{
tout *< "EXAMPLE.BND has been bound to the SAMPLEdatabase. cout *< '#Check the file" endl; cout (( **BINDIQO.DAT for additional information." *< endl;
m;
1 / / Return TheSQLCA Return return(sqlca.aqlcode);
codeTO The Calling
Function
1
Function
/* /*
*/
*/ */
The Main
/*
int main( ) {
/ / Declare The Local Memory rclong a SQL-RC-OK; structsplcasqlca;
Variables
/ / Create An Instance Of The MI-Class Class API-ClassExample; / / Connect To The SAMPLE Database EXEC SQL CONNECT TO SAMPLE USER
userID
/ / Bind An Existing Bind FileTo The rc = Example. BindProgram ();
SAMPLE
/ / Issue A Rollback To Free All Locks EXEC SQL ROLLBACK; / / Disconnect From The SAMPLE Database EXEC SQL DISCONNECT CURRENT; / / Return To The return(rc);
1
Operating
System
USINQ
password;
Database
p?
i
i
I !
Chapter 5: Program Preparation and General Programming M I S
pqm REBIND
103 1
Purpose
The REBIND function is used to recreate a package that is already stored in the database without using a corresponding bind file.
syntax
SQL-API-RC SQL-API-FN
Parameters
Sqlarbnd (char structsqlca void
*PackageUame,
*SPLcA, *Reserved);
PackageName
A pointer to a location in memory where the name (qualified or unqualified) of the package to be rebound is stored.
SQLCA
A pointer to a location in memory where a SQLCommunications Area (SQLCA)data structurevariable is stored. This variable returns either status information (ifthe function executed successfully) or error information (ifthe function failed) to the calling application. A pointer that is currently reserved for later use. For now, this parameter must always be set to NULL.
Reserved
Includes
#include <sql.h>
Description
The REBIND function is used t o re-create a package that is already stored in the database without using a corresponding bind file. When this function is executed, the DB2 Database Managerrecreates the package from the SQL statements stored in the SYSCAT.STATEMENTSsystem catalog table. The REBIND function provides a user or an application with the following capabilities: H A quick wayto recreate a package whenthe original bind fileis not available (which enables a user to take advantage of changes in thesystem).For example, if an index is created for a table, you can use the REBIND function to recreate the package so SQL statements in theapplication cantake advantage of the new index. Likewise, you canuse this function to recreate packages after the RUN STATISTICS function is executed, so all access plans generated for the packages can take advantage of the new statistical information. The ability to recreate inoperative packages. A packageis marked inoperative (the VALID column of the SYSCAT.PACKAGES system catalogtable is set to "X") when a function instance that the package dependson is dropped. Inoperative packages must be explicitly reboundto a database with either the bind or rebind utility before they can be used byany applicationthat references them. Control overthe process of rebinding of invalid packages. Invalid packages are automatically (or implicitly) rebound bythe DB2 Database Manager whenthey are executed. This process can result ina noticeable delayin theexecution of the first SQL statement that requests an invalid package. A moredesirable method might be to explicitly rebind invalid packages, rather thanallow DB2 to implicitly rebind them, in order to eliminate this initial delay and to trap and process unexpected SQL error messages (which might be returned if the implicit rebindfails). For
Part 3: Application Programming Interface Functions example, whenan earlier version DB2 database is migrated, all packages stored’in that database are invalidated by the migration process.This process might affect a large number of packages, so you might want to explicitly rebindall the invalid packages at one time.
Comments
W If the package name specified in the PackageName parameter is not explicitly
unqualified, it is implicitly qualifiedby the current authorization ID. Note that this default qualifier mightbe different fromthe authorization ID that was used when the package was originally bound to the database. W The bind optionsthat were specified when a package was originally created and bound to the database are reused whenthe package is rebound. W This function does not automatically commit or roll backthe current transaction after the rebind has occurred. Instead, the user must explicitly commitor roll back the transaction. This action allowsthe user to update different table statistics and then rebind the package to see what, if anything, changes. This action also allows a single transaction to perform multiple rebind operations. W During the rebind process,an exclusive lockis acquired and held on a package’s record in theSYSIBM.SYSPLAN system table. Therefore, ifthe rebind utility attempts to rebind a packagethat is in use by another application, the utility must wait until thetransaction that is using the package ends (so the utility can acquire the appropriate exclusive lock). W The rebind process will stop if afatal or general error occurs. If the rebind process stops beforethe specified packageis re-created, the corresponding packagewill be left in itsoriginal state. W The rebindutility will repopulate the Explain tables for packagesthat were created with the SQL-EXPLSNAP-OPT precompilehind optionset to SQL-EXPLUN-YBS or SQL-EXPLAIN-ALL when this function is called. However,the Explain facilityM11 use the Explain tables of the user requesting the REBIND operation, notthe Explain tables of the user who performedthe original bind operation. W The REBIND function is supported by DB2 Connect. W Explicit rebindingcan be done with the BIND function, the REBIND function, or the db2rbindtool (refer to the IBM DB2 Universal Database Command Reference for more information aboutthe db2rbind tool). Because boththe BIND and REBIND functions can explicitly rebind a package to a database, the choice of which function to use depends on the circumstances. Sincethe performance of the REBIND function is significantly better than thatof the BIND fundion, use the REBIND function whenever the situation does not specifically require the use of the BIND function. TheBIND function (and not the REBIND function) must be used to explicitly rebind a package when: W The embedded SQL application program has been modified (when SQL
statements have been added or deleted, or when the package does not match the executable program image). You want to modify any of the bind optionsas partof the rebind process.
C
Chapter 5: Program Preparation and General Programming M I S
I 105
The REBIND function does not allow the user to specify bind options. The package does notcurrently exist in thedatabase. You want to detect all general bind errors. The REBIND function only returns the firsterror it detects (and then ends),whereas the BIND function returns the first100 errors it encounters during the binding process.
Connection This function can only be called if a connection to a database exists. Requirements Authorization Only users with System Administrator(SYSADM) authority, Database Administrator (DBADM) authority, or BIND authority for the package t o be rebound can execute this function call.
NOTE: The authorization ID stored in the BOUNDBY column of the SYSIBMSYSPLAN system table, which is the authorization ID of the most recentbinder of the package, is used as the binder authorizationID for the rebind operationand as the default schema for all table references in the package.
See Also
BIND,RUN STATISTICS
Example
The followingC++ program illustrates how to use the REBIND function t o rebind a package that already exists in the currentconnected database: ~
/* /* /*
/* /* /*
NAME:
CH5EX3 PURPOSE: Illustrate How To Use The Following DB2 API Function In A C++ Program:
~~
*/ */
*/
*/ */ */
REBIND
/*
*/
/ / Include The Appropriate #include <windows.h> #incluBe #include #include <sql.h> / / Define The API-Class Class class API-Class {
/ / Attributes public : struct sqlca sqlca; / / Operations
Heaaer
Files
Part 3 Application Programming Interface Functions public : long long
DiepPkgTimeetamp ( Rebind ();
;
1; / / Define The DispPkgTimestamp( ) Member ::DiepPkgTimeetamp ( ) long API-Claee
Function
{
/ / Declare The SQL Host M e m o r y Variables EXEC SQL BEGIN DECLARE SECTION; char PackageName 91 ; char BindTime [ 3 0I ; EXEC SQL END DECLARE SECTION; / / Retrieve A Record From The SYSIBM.SYSPLAN Table EXEC SQL SELECTNAME, CHAR(LAST-BIND-TIME) INTO :PackageName, :BindTime FROM SYSIBM.SYSPLAN m R E NAME 'EXAMPLE' AND BOUNDBY = 'USERID' ; 5
/ / Print The Information Retrieved , if (eqlca.sqlcode == SQL-RC-OK) {
tout << "Package Name : cout.width(14); cout.setf(ios::left); cout (< PackageName (< ULast Bound :
'' << BindTime
*(
endl;
1 / / Return The SQLCA Return return(eqlca.eglcode);
Code To The
Calling
Function
1 / / Define The Rebind0 Member Function long API-Clase::Rebind() {
/ / Rebind lime Specified Package eplarbnd ("EXAMPLE", Grsqlca, NULL) ; / / If The Bind File Was Succesefully / / Succeee Meaeage
if (eqlca.sqlcode == SQL-RC-OK) cout <<. "The EXAMPLE package / / Return The SQLCA Return return(sqlca.eqlcode);
Code
Rebound, Dieplay A
hae To
been rebound." << endl; The
Calling
Function
1
Main
/* /* /*
*/ The
int main() {
*/ */
Chapter 5: Program Preparation and General ProgrammingAPIs / / Declare The Local Memory Variable0 rc long = SQL-RC-OK; etruct eqlca eqlca; / / Create An Inetance Of The API-Clam Claee API-ClaeeExample; / / Connect To The SAMPLE Database TO SAMPLE USER ueerID EXEC SQL CONNECT
/ / Retrieve And Dieplay The Timeetamp / / It Ie Rebound rc = Example.DiepPkgTimeetamp();
-
/ / Bind An gxieting Bind rc Example.Rebind( ) ;
FileTo The
USINQ
For
The
SAMPLE
paeeword; Package
Before
Databaee
/ / Retrieve And Dieplay The Timeetamp ForThe Package After / / It Ie Rebound (The Timeetamp Should Be Different)
rc
I
Example.DiepPkgTimeetamp() ;
/ / Ieeue A Rollback To Free EXEC SQL ROLLBACK;
All
Locke
/ / Dieconnect From The SAMPLE Databaee EXEC SQLDISCONNEK!T CURRENT;
1
/ / Return To The return(rc) ;
Operating
Syetem
purpose
The QET INSTANCE functionis used to retrieve the current value of the DB2INSTANCE environment variable.
syntax
SQL-API-RC SQL-API-FN eqlegine
Parametera
Instance
SQLCA
Includes
#include <eqlenv.h>
(char etruct eqlca
*Instance, *SQLCA);
A pointer to a location in memory where this function is to store the current DB2 Database Manager instancename (the current value of the DBXNSTANCE environment variable). A pointerto alocation in memory where a SQLCommunications Area (SQLCA) data structure vaiiable is stored. This variable returns either status information (ifthe function executed successfully) or error information (ifthe functionfailed) to the calling application.
Part 3: Application Programming Interface Functions Description
The GET INSTANCE function is used to retrieve the current value of the DB~INSTANCE environment variable.This value usually identifies the instance-level nodeto which the application is currently attached.
Comments
The bufferin which this function is to store the DB2 Database Manager instance name (the Instance parameter) must be at least eight bytes long. W The valuein theDB~INSTANCEenvironment variable is not necessarilythe DB2 Database Manager instance to whichthe application is currently attached. To identify the DB2 Database Manager instance to which an application is currently attached, call the ATTACH function with all parameters except the SQLCA parameter set t o NULL.
Connection This function can be called at any time; a connection to a DB2 Database Manager Requirements instance or to a DB2 database does not haveto be established first. Authorization No authorization is required to executethis function call. Example
Thefollowing C++ program illustrates how to use the GET INSTANCE function to obtain the current value of the DB~INSTANCEenvironment variable:
/*
/*
/* /*
*/ CH5EXQ.CPP NAME: PURPOSE: Illustrate How To Use The Following DB2 API Function In A C++ Program:
*/ */ */
/*
/* /* /*
*/ */ */
GET INSTANCE
*/
/ / Include The Appropriate #include <windows.h> #include #include <sqlenv.h> #include <sql.h>
Header
Files
/ / Define The API-Class Class class API-Class
i / / Attributes public : struct sqlca sqlca; / / Operations public: long GetInstanceOi >t
/ / Define The &tInstanceO Member Function long API-Class: :&tInstance()
i / / Declare
The
LocalMemory Variables
Chapter 5: Program Preparationand General ProgrammingAPIs char Inetance [91; / / Obtain The Current / / Variable
Value Of The DB2INSTANCE Environment
eqlegine(Inetance, &sulcal; Instance[B] m 0; / / If The Current ValueOf The DB2INSTANCE / / Wae Obtained, DieplayIt
if (eqlca.sqlcde
I=
Environment Variable
SQL-RC-OK)
{
>
tout << "Current value of the DB2INSTANCE environment U ; cout << "variable : << Instance << endl;
*/ */
/* Function
/*
The Main
int main0 {
/ / Declare The LocalMemory Variables long rc I SQL-RC-OK; / / Create An Instance Of The API-Claee Claee API-ClaeeExample;
/ / Get The Current Value Of The DBaINSTANCE Environment Variable rc = Example.QetInetance();
1
/ / Return To The Operating return )(rc ;
Syetem
IMQ P W INSTALL SIGNAL HANDLER Purpose
The INSTALL SIQNAL HANDLER functionis used to installthedefaultinterruptsignal handler providedwith DB2.
syntax
SQL-API-RC SQL-API-FN sqleieig (etruct eqlca
Parametem
SQLCA
*SQLCA);
A pointer to alocation in memorywhere a SQL Communications Area data structure variablei s stored. "his variable returns either status information (if the functionexecuted successfully)or error information (if the function failed) to the calling application.
j 110 i
1 :
Part 3 Application Programming Interface Functions
'
Includes
#include <sqlenv.h>
Description
"he INSTALL SIQNAL HANDLER function is used to install thedefault interrupt signal handler that is provided withthe DB2 Software Development Kit (SDK). Whenthe default interrupt signal handler detects an interrupt signal (usudly Ctrl-C and/or Ctrl-Break), it resets thesignal and callsthe INTERRUPT function to gracefully stop the processing of the currentdatabase request. If an application has not installed an interrupt signal handler and an interrupt signal i s received, the application will beterminated. This function provides simple interrupt signal handling and should always be usedif an application does not have extensive interrupt handling requirements.
Comments
B If an application requires a more elaborate interrupt handling scheme, you can
develop a signal handling routine that resets thesignal, callsthe INTERRUPT function, and then performs additionaltasks. B You must call this API function beforethe default interrupt signal handler will function properly. B This function cannotbe used in applications that run on the Windows or Windows N" operating system.
Connection This function canbe called at any time;a connection to a DB2 Database Manager Requirements instance or to a DB2 database does not haveto be established first. Authorization No authorization is required to execute this function call. See Also
INTERRUPT
Example
Thefollowing C++ program illustrates how to use the INSTALL SIQNAL HANDLER function to install thedefault interrupt signal handling routine in an embedded SQL application:
CH5EX5.SQC
/* /* /* /* /* /* /* /*
*/ NAME: PURPOSE: Illustrate How To Use The Following DBP API Function In A C++ Program: INSTALL
/ / Include The Appropriate #include <windows.h> #include #include <stdio.h> #include <sqlenv.h> #include <sql.h>
SIQNAL
Header
/ / Define The API-Class Class class API-Class
HANDLER
Files
*/ */ */
*/ */ */ */
Chapter 5: Program Preparationand General Programming APIs {
/ / Attributes public 2 struct eqlca eqlca; / / Operations public : long SetSignalHandlerO;
1; / / Define The SetSignalHandler() Member Function long API-C1ass::SetSignalHandlerO {
/ / Inetall DBZ8e Default Interrupt Signal Handler eqleisig(hsq1ca);
/ / If The Signal Handlerwas Installed Successfully, Display / / A Success Message if (sqlca.sqlcode == SQL-RC-OK) {
tout << "The default interruptsignal cout << "installed." << endl;
handler
has
been ";
1 / / Return The SQLCA Return return(sqlca.sqlcode);
Code To The
Calling
Function
1
/* /*
The min Function
int main() / / Declare The Local Memory Variables rc long = SQL-RC-OK; char conmcissions[ Z O ] ; structsqlcasqlca; / / Declare The SQL Host Memory Variable EXEC SQL BEGIN DECLARE SECTION; long TotalComm; EXEC SQL END DECLARE SECTION;
/ / Create An Instance Of The API-Class Class API-ClassExample; / / Install The Default Interrupt Signal Handler
rc
E
Example.SetSignalHandier0;
/ / Set Up A Simple SQL Error Handler EXEC SQLWHENEVER SQLERROR OOTO EXIT]
/ / Display A Message TellingThe User To Generate An Interrupt / / Signal By Pressing Ctrl-Break
*/
*/
Part 3 Application Programming Interface Functions cout << "Press Ctrl-Break to terminate thisprogram."
Amount Of Commissions
password; Paid
From
The
EXEC SQL SELECT SWM(C0MM) INTO :TotalCom FROM EldPLOYEE; / / Print The Information Retrieved sprintf(Commiesions, "$ %.21d.00", TotalCannn); cout << T h e company paid c < commissions << *' in commissions."; endl; cout
EXIT: / / If The ProcessWas Terminated BY A Signal / / An Error Message SayingSo
Interrupt, Display
if (8qlca.sqlcode =I: -952) cout << *'Processing was terminated due to an interrupt."; / / Otherwise, If An Error Has Occurred, DisplayThe SQL / / Code else if (sqlca.sqlcode I = SQL-RC-OK)
cout << "ERROR :
Return
<< sqlca.sqlcode << endl;
/ / Issue A Rollback To Free EXEC SQL ROLLBACK8
All
Locks
/ / Disconnect From The SAMPLE Database EXEC SQL DISCONNECT CURRENT;
/ / Return To The Operating return(rc);
System
1
Purpose
The INTERRUPT function is used to stop the processing of the w e n t database request.
syntax
SQL-API-RCSQL-API-INTReqleintr
Includes
#include <sqlenv.h>
Description
The INTERRUPTfunction is used to stop the processing of the current database request. This function is normally the firstfunction calledin an interrupt signal handler routine. An application's interrupt signal handler can be the default signal handler installed by the INSTALL SIGNAL HANDLER function or a more elaborate
() ;
Chapter 5: Program Preparation and General ProgrammingAPIs intempt handler routine supplied by the application developerand installed with the appropriate operating system call.In either case, whenan interrupthandler detects an interrupt signal (usually Ctrl-C and/orCtrl-Break),the handler takes control and performs oneor more actionsto ensure that all active processingis terminated gracefblly. When the INTERRUPT function is called whileother DB2 A P I functions are executing, the executing functionsare either interrupted or allowed to complete execution, dependingon the work they are performing. Table5-4 lists the effects the INTERRUPTfunction has on other API functions. Table 5 4
Interrupt Effects on SOL and API Actions
< t i , -..,.
&e,,.<
I,,.,
.,
*.. A . . . , . ..
-.'.
...
..,"
, ,
,"
..
.
-
~
.
~
~
~
z
m
?
x
IMPORT
The import process is canceled, and all database updates
are rolled back.
EXPORT
"he export process is canceled, and all database updates are
rolled back.
RUNSTATS
The run statistics process is canceled, and all database updatesare rolled back.
REORGANIZE TABLE
The reorganizetable process is canceled, andthetable
w
P
is left in its previous
State.
BACKUP
The backup processis canceled, and the backup data stored on the specified media may be incomplete.
RESTORE
The restore process is canceled, and thedatabase being restoredis deleted (DROP DATABASE is performed). This action is not applicable to table spacelevel restore operations.
LOAD
The load process
PRECOMPILE PROGRAM
The precompileprocess is canceled, and package creation is rolledback.
BIND
bind The
COMMIT
The COMMIT process runs to completion.
FORCE APPLICATION
The FORCE APPLICATION process runs to completion.
ROLLBACK
The ROLLBACK process runs to completion.
CREATE DATABASE
After a certain point, the CREATE DATABASE process cannot be terminated. If the interruptsignal is received beforethis point, the databaseis not created, and the database creation process is canceled. Ifthe interruptis received after this point, the CREATE DATABASE process runs to completion, and the databaseis created.
CREATE
After a Certain point, the CREATE DATABASE AT NODE process Cannot be terminated. If the interrupt signal received is beforethis point, the database is not created, andthe database creation process i s canceled. If the interrupt is received after this point, the CREATE DATABASE AT process NODE runs to completion, and the database is created.
ADD
DATABASEAT NODE
NODE
is canceled, and the data
storedtable in
may be
incomplete.
process is canceled, and package creation is rolled back.
After a certain point, the ADD NODE process cannot be terminated. If the interrupt signal is received beforethis point, the node is not added, andthe ADD NODE process is canceled. If the interrupt isreceived after this point,
"
~
?
Part 3 Application Programming Interface Functions Table 5-4
Interrupt Effects on SOL and API Actions (Continued)
the ADD NODE process runs to completion, and the node is added. DROP NODE
After a certain point, the DROP NODE VERIFY process cannot be terminated. If the interrupt signal is received beforethis point the DROP NODE VERIFY process is canceled. If the interruptis received after this point, the DROP NODE VERIFY process runs to completion.
VERIFY
The DROP DATABASE
DROP DATABASE DROP DATABASE
AT NODE
The DROP DATAEASE
process run8 to completion. AT NODE process
to completion.
The speciiied directory is left in a consistent state. Utility functionsmay or may not be performed.
DirectoryServices
SQL Data Definition Statements Database transactions are set to the state theywere in before the SQL statement wasexecuted. other SQL statementsDatabasetransactions ment was executed.
are set to thestate theywere in before the SQL state-
Adapted fromIBM's DB2 Universal Database A P Z &fireme, Table 5, page 147.
Comments
W
No DB2 function other than INTERRUPT should be called from a user-defined interrupt handler. M When creating an interrupt handling routine, follow all operating system programming techniques and practices to ensure that all previously installed signal handlers continue to work properly. W Any transaction that is in theprocess of being committedor rolled backcannot be
interrupted. W When a DB2 API function is interrupted, it places a return code that indicates it was interrupted in theappropriate SQLCA data structurevariable. Required
This function can be called at any time; a connection to a DB2 Database Manager
Connection
instance or to a DB2 database does not have to be established first.
Authorization No authorization is required to execute this function c a l l . see Also
Example
INSTALL SI-
HANDLER
The following c++ program illustrates how to use the defined intempt signal handling routine (Windows):
/* /* /* /* /*
I m E m m T function in
CHSEX6.8QC PURPOSE:Illustrate How To Wee The F o l l o w i n g DB2 API Function In A C++ P r o g r a m :
NAME:
a user-
*/ */ *I
*/ */
Chapter 5: Program Preparationand General ProgrammingAPIs /* /*
*/
INTERRUPT
*/ */
/*
/ / Include The Appropriate Header Files #include <windows.h, #include #include <stdio.h> #include aq1env.b #include *sql.h> / / Define The API-Class Class class -1-Class {
/ / Attributes public : struct sqlca sqlca;
1;
/ / Operations public : long OetCommission() ;
/ / Define The QotConaniesionO Member Function long API_Class::OetConanissionO {
/ / Declare The Local M e m o r y Variables char Commissions1201 ;
/ / Declare The SQL Host M e m o r y Variable EXEC SQL BEGIN DECLARE SECTION; long TotalCOnun; EXEC SQLEND DECLARE SECTION; / / Retrieve The Total Amount Of Commissions / / EMPLOYEE Table EXEC SQL SELECT SUM(C0MM) INTO :TotalCOnun FROM EMPLOYEE;
Paid
/ / Print The Information Retrieved sprintf (Conaniseione, "$ %.21d.OOn, TotalCOnun) ; cout ** "The campany paid <e Conaniseions << cout (( endl;
1
/* /* /*
/ / Return The SQLCA Return Code To The Calling return(sqlca.aqlcode);
in
Function
*/ The -in
int main() {
From The
Function
*/ */
Part 3: Application Programming. Interface Functions / / Declare The LocalMemory Variables = SQL-RC-OK; rc long structsplcasqlca; / / Create ~n Instance Of The API-Class Class API-ClassExample; / / Connect To The SAMPLE Database EXEC SQL CONNECT TO SAMPLE USER userID
/ / Display try
rc
commission
-ample.
USINQ
paesword;
Information
Getcomrmission ( ) ;
1 / / If An Exception Occurs catch(...)
...
{
/ / Terminate AllDB2 Database / / In Progress
Requests ThatAre Currently
epleintr( ) ;
1 / / Issue A Rollback To Free All Locks ExgC SQL ROLLBACK;
/ / Disconnect From The SAMPLE Database EXEC SQL DISCONNECT CURRENT; / / Return To The Operating return ( rc 1 ;
System
?
m m GET ADDRESS Purpose
The GET ADDRESS function is used to store the address of one variable into another variable in applications written inhost languages that do not support pointer manipulation.
syntax
SQL-API-RC SQL-MI-FN
Parameters
eplgaddr (char *Va&&le, char*OutputAddrees)
;
A pointer to a location in memory where the variable whose address is to be returned is stored. OutputAddress The address of a pointer to a location in memory where this function is to store the address retrieved of the variable specified in the Variable parameter.
Variable
Chapter 5: Program Preparation and General Programming APIs Includes
#include <sqlutil.h>
Description
The GET ADDRESSfunction is used to store the address of one variable into another variable in applications written in host languages that do not support pointer manipulation. T h i s function should only be used in applications written in either COBOL or FORTRAN. Applications written in host languages that support pointer manipulation (such as C and C++)should use the language-specific pointer manipulation elements provided.
Comments
The buffer that this function is t o store the retrieved address in (the OutputAddress parameter) must be four bytes long.
This function can be called at any time; a connectionto a DB2 Database Manager Comection Requirements instance or to a DB2 database does not haveto be established first.
Authorization No authorization is required to execute this function call.
see Also Example
DEREFERENCEADDRESS,COPY
MEMORY
Because this function shouldbe used onlyin applications written in either the COBOL or the FORTRAN programming language,an example programis not provided. Referto the IBM DB2 Uninversal Database API Reference for examples of how this function is used in COBOL and FORTRAN applications.
m m COPY MEMORY Purpose
syntax
The COPY MEMORY function is used to copy data from one memorystorage area to another in applications written in host languages that do not provide memory block copy functions. eqlgmcpy (void
SQL-API-RC SQL-I-FN
*!Parget, const void *Source, unsigned long nnrmayte~);
Parameters
Target Source NumBytes
Apointer to alocation in memory to which this function is to copy data. Apointer to alocation in memoryfromwhich this function is to copy data. The number of bytes of data that is to be copied from the Source memory storage area t o the Target memory storage area.
Includes
#include <sqlutil.h>
Description
The COPY MEMORYfunction is used to copy data from one memorystorage area to another in applications written in host languages that do not provide memory block copy functions. This function should be used only in applications written in either COBOL or FORTRAN. Applications written in host languages that provide memory
1
l 1 8 . j!
Part 3: Application Programming Interface Functions
-
copy functions (such as C and C++)should use the language memory block copy functions provided.
Comments
W The host programming language variable that contains the number of bytes of data to be copied (the NumBytes parameter) must be four bytes long.
Connection This function can be called a t any time; a connection to a DB2 Database Manager Requirements instance or to a DB2 database does nothave to be established first. Authorization No authorization is required to execute this function call. See Also
QET
Example
Because this function shouldbe used onlyin applications written in either the COBOL or the FORTRAN programming language, an example programis not provided. Referto the IBM DB2 Universal DatabaseAPI Reference for examples of' how this function is used in COBOL and FORTRAN applications.
ADDRESS,
DEREFERENCE
ADDRESS
DEREFERENCE ADDRESS The DEREFERENCE ADDRESS function is used to copy data from a buffer definedby a pointer t o a local data storage variable in applications written in host languages that do not support pointer manipulation.
syntax
SQL-API-RC SQL-API-FN sqlgdref
(unsigned int char char
NbmEyterr,
'Targetvariable, **SourceBuffer):
The number of bytes of data to becopiedfrom the SourceBuffer memory storage area to the !i!brgetVariablevariable. !i!brgetVariable A pointerto a local'storagevariable to which this function is to copy data. SourceBuffer The address of a pointer to a location in memory where this function is to copy data from.
Parameters
NumBytes
Includes
#include <sglutil.h>
Description
The DEREFERENCE ADDRESS function is used t o copy data from a buffer definedby a pointer to a local data storage variable in applications written in host languages that do not support pointer manipulation.This function shouldbe used onlyin applications written in either COBOL or FORTRAN. Applications written in host languages that support pointer manipulation (such as C and C++) should use the language-specific pointer manipulationelements provided. You can use this function to obtain results from other API functions that return pointers to data storage areas that contain the datavalues retrieved, such as GET NEXT
NODE
DIRECTORYENTRY.
F Chapter 5: Program Preparation and General Programming Comments
APIs
119
H The host programming language variable that contains the number of bytes of
data to be copied(theNurnBytes parameter) must be four bytes long.
Connection This function can be called at any time; a connection to a DB2 Database Manager Requirements instance or to a DB2 database does not haveto be establishedfirst. Authorization No authorization is required to execute this function call. See Also
GET ADDRESS, COPY
Example
Because this function should be used only in applications written in either COBOL or FORTRAN,an example programis not provided. Referto the IBM DB2 Universal Database MI Reference for examplesof how this function is used in COBOL and FORTRAN applications.
MEMORY
m m SET ACCOUNTING STRING Purpose
The SET ACCOUNTING STRING function is used to specify accounting informationthat is to be sent to a Distributed Relational Database Architecture (DRDA) server with the application’s next connect request.
syntax
SQL-API-R~ SQL-API-FN sqleeact
Parameters
AccountingString SQLCA
(char *AccountingString, etruct eqlca *SQJXA);
A pointerto a location in memory wherethe accounting informationstring is stored. A pointerto a location in memory where a SQL Communications Area(SQLCA) data structure variable is stored. This variable returns either status information (ifthe function executed successfully) or error information (ifthe function failed) to the calling application.
Includes
#include <eqlenv.h>
Description
The s m ACCOUNTING STRING function is used to specify accounting information that is to be sent to a DRDA server with the application’s next connect request. An application should callthis API function beforeattempting to connect to a DRDA database (DB2 forOS390 or DB2 forOS/400). If an application contains multiple CONNECT SQL statements, you can use this function to change the accounting string before attempting to connect to each database. Referto the beginning of this chapter for more information about the format and usage of accounting string information.
Comments
Once accountingstring information has been set, it remains in effect until the application terminates.
W The accounting string specified cannot exceed 199 bytes in length (this value is : defined as SQLACCOUNT-STR-sz in thefile sqZenv.h);longer accountingstrings will
automatically be truncated. W
To ensure that the accounting string isconverted correctly whentransmitted to the DRDA server, only use the characters A to Z, 0 to 9, and underscore 0.
Connection This function can be called at any time; a connection to a DB2 Database Manager Requirements instance or to a DB2 database does not haveto be established first. Authorization No authorization is required to execute this functioncall. See Also
Refer to the IBM DB2 Connect User’s Guide formore information about accounting strings and the DRDA servers that support them.
Example
Thefollowing C++program illustrates how to use the SET ACCOUNTINQ STRINQ functionto set accounting string information beforea connection to a database is established:
/* /* /* /*
In A C++ Program:
SET ACCOWTINQ STRINQ
*/ */
/*
*/
/ / Include The Appropriate Header Files #include <windows.h, #include #include <sqlenv.h, #include <sql.h* / / Define The API-Clase Class clase API-Clam 1: / / Attributes public: struct sqlca sqlca;
1;
*/ */
/ / Operations public: long SetAccountO;
/ / Define The SetAccountO Member Function long API-Class::SetAccount() {
/ / Declare The LocalMemory Variable8 charAccountingString[199];
i
Chapter 5: Program Preparation and General ProgrammingAPIs / / Initialize The Accounting String strcpy(AccountingString, "DB2-EXAMPLES"); / / Set The Accounting String splesact(AccountingString, &sqlca); / / If The Accounting StringWas Set, Display A if (sqlca.sqlcode PP SQL-RC-OK)
Success
Measage
{
tout << ''The specified accounting stringhas been set."; cout << endl;
1 / / Return The SQLCA Return return(sqlca.sq1code); '
Code TO The
Calling
Function
1
*/
/" /e
"/
The Main Function
int main() {
/ / Declare The Local M e m o r y Variables rc long = SQL-RC-OKI struct sqlca sqlca; / / Create An Instance Of The API-Class Class API-ClassExample; / / Connect To The SAMPLE Database rc = Example.SetAccount0; / / Connect To The SAMPLE Database Using The Specified / / Accounting String (In This Case The Accounting String / / Will Be Ignored)
EXEC SQL CONNECT
TO
SAMPLE USER userID
USING
password;
/ / If The Connected, Display A Success Message if (sqlca.eqlcode SQL-RC-OK) cout << Tonnected to the SAMPLE database." << endl; PP
/ / Issue A Rollback To Free EXEC SQL ROLLBACK;
All
Locks
/ / Disconnect From The SAMPLE Database EXEC SQL DISCONNECT CURRENT; / / Return TO The return ( rc ) ;
1
Operating
System
Part 3: Application Programming Interface Functions
GET ERROR MESSAGE Purpose
The QET ERROR MESSAQE function is used to retrieve message text that is associated with an error or warning condition (specifiedby the currentvalue of the sqlcode field of a sqlcu data structurevariable) &om a specialDB2 error message file. SQL-API-RC SQL-API-FN
sqlaintp (char short short etruct sqlca
Parameters
Buffer Buffersize
*Buffer, Buffersf za, MaxLineSize, *SQLCA)J
Apointer to alocation in memorywhere this function is to store the message text retrieved. The size, in bytes, of the memory storage buffer that the message
text retrieved is to be written to. MdimSize
The maximum number of characters that one line of message text should contain before line a break is inserted. A value of o indicates that the message text is to be returned without line breaks.
SQLCA
Apointer to a location in memorywhereaSQLCommunications Area (SQLCA) data structurevariable is stored. The valuein the sqlcode field of this variable is used to locate the appropriate error message text.
Includes
#include <sql.h>
Description
The QET ERROR mssAoE function is used to retrieve message text that is associated with an error or warning condition froma special DB2 error message file. TheDB2 error message file(db2sql.mo,located in themisc subdirectory of the sqllib directory where DB2 was installed) contains error message text correspondingto each error code value that can be generated by DB2. Each time this function is called, the value in thesqlcode field of a sqlcu data structurevariable is used to locate and retrieve appropriate error message text from this file. Oneerror message is returned per QET ERROR MSSAQE function call.
Return Codes When this function has completed execution,it returns one of the following values: +i A positiveinteger value indicating the number of bytes containedin theformatted message. Ifthis value is greater than thevalue specified in theBuffersize parameter, the message text will be truncated. If the message must be truncated to fit in thebuffer, the truncation will includem m for the stringNULLtermination character. -1 Insufficient memoryis available forthe message formatting services to work properly. Therequested message text is not returned. -2 The specifiedSQLCA data structurevariable did not contain an error or warning code (SQLCODE = 0). -3 The messagetext file is inaccessible or incorrect.
i
Chapter 5: Program Preparation and GeneralProgramming APIs
i
-' . - i
123
-4 The value specifiedin theM d i n e S i z e parameter is less than zero. -5 An invalid SQLCA data structurevariable, bad buffer address, or bad buffer length (size) was specified. If the returncode -1 or -3 is returned, the message bufferwill contain additional information aboutthe problem.
Comments
U
A new line (line feed or carriage returdline feed) sequence is automatically placed
at the end of each messagetext stringretrieved. U If a positive valueis specified forthe M d i n e S i z e parameter, new line sequences will be inserted between words so the lines of the message text stringdo not exceed the specified line length. If the lastword in a line will cause that line to be longer than the specified line width, the line is filled withas many characters of the word that will fit, a new line sequenceis inserted, and the remaining characters of the word are placed on the next line.
Connection This function can be called at any time; a connection to a DB2 Database Manager Requirements instance or to a DB2 database does not haveto be established first. Authorization No authorization is required to execute this function c a l l .
see Also Example
QET
SQLSTATE MSSAQE
Thefollowing C++ program illustrates how to use the GET ERROR MESSAGE function t o retrieve the errormessage text associated withthe error code stored in a SQLCA data structurevariable after another API function call fails: I*
/*
/* /* /*
/* /*
~~
~
~~~~~~
CH5EX8.CPP NAME: PURPOSE: Illuetrate How To Use The Following DB2 API Function In A C++ Program: QET ERROR MESSAGE
/*
/ / Include The Appropriate #include <windows.h> #include #include <eqlenv.h> #include <sqlca.h> / / Define The API-Class Clase claes API-Claes / / Attributes public : char ErrorMeg[l024lt
Header
Files
* l
*/
*/
*/ */ */ */ */
Part 3: Application Programming Interface Functions
1;
/ / Operations public : void GetErrorMsg(struct sqlca sqlca);
/ / Define The GetErrorMsg() Member Function void API-Class::GetErrorMsg(struct sqlca sqlca)
I / / Declare The LocalMemory Variables long rc = SQL-RC-OK;
/ / Retrieve The Error Message Text For The Error rc = eqlaintp(ErrorMsg, eizeof(Err0rMsg). 70, &sqlca); switch (rc)
Code
{
case -1: cout << break; case -3: cout << break; case -5: cout << cout << break; default: cout << break; 1
"ERROR : Insufficientmemory."
<< endl;
"ERROR : Message file is inaccessable." << endl;
"ERROR : Invalid SQLCA, bad buffer. ";
"or bad buffer length specified."<< endl;
ErrorMsg << endl;
/ / Return To The return;
Calling
Function
1
*/ */
/* Main
/ * The
*/
/* int
main()
{
/ / Declare The Local Memory Variables rc long = SQL-RC-OK; struct sqlca sqlca; / / Create An Instance Of The API-Class Class API-ClassExample;
/ / Attempt To Change The Comment Associated / / Database - This Should GenerateAn Error
sqledcgd(~aINVALID1r, **",
With An Invalid
"Invalid Database", &eqlca);
/ / If The CHANGE DATABASE COMMENT Function Failed, Retrieve / / The Error Message Text For The Error Code Returned if (sqlca.sqlcode l = SQL-RC-OK)
Example.GetErrorMsg(sqlca);
Chapter 5: Program Preparation and General ProgrammingAPIs
”l
/ / Return To The Operating System return(rc)t
1
GET SQLSTATE MESSAGE The QET SQLSTATE MESSAQE function is used to retrieve message text that is associated with a SQLSTATE value (specifiedby the value of the sqlstute field of a sqlcu data structurevariable) from a specialDB2 error message file.
syntax
Parameters
SQL-API-RCSQL-API-FNSqlOgStt
Buffer Buffersize MdineSize
SQLSTATE
(char short short char
*Buffer Buffersire, MaxGineSire, *SPLSTATEB)I
Apointer to alocation in memorywhere this function is to store the message text retrieved. The size, in bytes, of the memory storage buffer that the message text retrieved is to be written to. The maximum number of characters that one line of message text should contain before line a break is inserted. A value of o indicates that themessage text is to be returned without line breaks. A pointer to a location in memory where the SQLSTATE value that this function is to retrieve message text for is stored.
Includes
#include <sql.h>
Description
The GET SQLSTATE MESSAQE function is used to retrieve message text that is associated with a SQJSTATE value.Each time this function is called, the value in the sqstute field of a sqlcu data structurevariable is used to locate and retrieve the appropriate error message text. One messageis returned per QET SQLSTATEMESSAGE function call.
Return Codes When this function has completed execution,it returns one of the following values: +i A positive integer value indicating the number of bytes containedin theformatted message. If this value is greater than thevalue specifiedin theBuffersize parameter, the message text will be truncated. If the message must be truncated to fit in the buffer, the truncation will include room for the s t ~ NULLg termination character. -1 Insufficient memoryis available forthe message formatting services to work properly. Therequested message text is not returned. -2 The specified SQLSTATE value is in thewrong format.“his value must be alphanumeric and either two or five digits in length (and NULL-terminated if
P!
!
i
ij
"
"
1 I
126
Part 3: Application Programming Interface Functions two digits long). -3 The messagetext file is inaccessible or incorrect. -4 The value specified in the M a d i n e s i z e parameter is less than zero. -5 An invalid SQLSTATE value, bad bufferaddress, or bad bufferlength (size) was specified. If the returncode -1 or -3 is returned, the message bufferwill contain additional information about the problem.
Comments
W
A new line (line feed or carriage r e t u r n h e feed) sequenceis automatically placed at the end of each messagetext string retrieved.
W If a positivevalue is specified forthe M a d i n e s i z e parameter, new line sequences
will beinserted between wordsso the lines of the message text string do not exceed the specified line length. If the lastword in a line will causethat line to be longer than thespecified line width, the line is filled with as many characters of the word that will fit, a new line sequence is inserted, and the remaining characters of the word are placed on the next line. The value specifiedin the SQLSTATE parameter must be either a specific fivedigit SQLSTATE value or a two-digitSQLSTATE class value(the first two digits of a SQLSTATE value). Ifthe value provided forthis parameter is a two-digit SQLSTATE class value,it must be NULL-terminated.
Connection This function can be called at any time; a connection to a DB2 Database Manager Requirements instance or to a DB2 database does not haveto be established first.
Authorization No authorization is required to execute this function call. See Also
GET ERROR MESSAGE
Example
Thefollowing C++ program illustrates how to use the GET SQLSTATE MESSAGE function to retrieve the error message text associated with the SQLSTATE value stored in a SQLCA data structurevariable &er another API function call fails:
MESSAGE
/* /* NAME: /* PURPOSE: /* /* / *SQLSTATE /* /*
CHJEX9.CPP Illustrate H o w To Uee The Following DB2 API Function In A C++ Program:
GET
/ / Include The Appropriate Header Filee #include <windows.h> #include *ioetream.h> #include <eqlenv.h> #include <sqlca.h>
*/ */ */ */
*/ */ */
*/
Chapter 5: Program Preparationand General Programming M I S / / Define The API-Class Class class API-Class '
/ / Attributes public : char ErrorMsg[lO21]
;
/ / Operations public : void QetSQLSTATEMeg(struct sqlca SUlCa);
?; / / Define The QetSQLSTATEMsgO Member Function void API-Claes::QetSQLSTATEMsg(struct sqlca SqlCa) {
/ / Declare The LocalM e m o r y Variables long rc = SQL-RC-OK; / / Retrieve
The SQLSTATE Message Text For The SQLSTATE sqlogstt(ErrorMsg, sizeof(ErrorMsg), 70, (char *) &sqlca.sqlstate); switch (rc)
rc
Code
I
c
case -1: cout << break; case -3: cout << break; case -5: cout << cout << break; default : cout << break; ?
"ERROR : Insufficient memory." << endl;
"ERROR : Message file is inaccessable." << endl;
"ERROR : Invalid SQLCA, bad buffer,"; "or bad buffer length ~pecified.'~ << endl;
ErrorMsg << endl;
/ / Return To The return;
Calling
Function
?
/* /*
*/ */
The Main Function
int main() {
/ / Declare The LocalMemory Variables = SQL-RC-OK; rc long struct sqlca sqlca; / / Create An Instance Of The API-Class Class MI-Class Example; / / Attempt To Change The Comment
Associated
With An Invalid
Part 3: Application Programming Interface Functions
-
/ / Database This Should GenerateAn Error sqledcgd('INVALID","InvalidDatabase", &sqlca); / / If The CHANGE DATABASE COltMmT Function Pailed. Retrieve / / The Error MessageText For The SQLSTATE Code Returned
if (sqlca.sqlcode I = SQL-RC-OK) Example.t3atSQLSTATEMsg(sqlca); / / Return TO The Operating System return(rc) ;
1
FW FM GET AUTHORIZATIONS PUFpo-
The QET AUTHORIZATIONS function is used to retrieve the authorizations of the current user from both the database configuration fileand the authorization system catalog view (SYSCAT.DBAUTH).
Syntax
SQL-API-RC SQL-API-PN sqluadau (atruct sql-authorizations splca struct
Parameters
*Authorizations, *SQLCA);
'
Authorizations A pointer to a sql-authorizations structure where this function is to store the authorization information retrieved. SQLCA
A pointer to a location in memorywhere a SQLCommunications Area (SQLCA) data structurevariable is stored. This variable returns either statusinformation (ifthe function executed successfully) or error information (ifthe function failed)to the calling application.
Includes
#include <sqlutil.h>
Description
The GET AUTHORIZATIONS function is used to retrieve the authorizations of the current user from both the database configuration file andthe authorization system catalog view (SYSCAT.DBAUTH). The authorization information retrieved is stored in asql-authorizations structure thatcontains short integer elements that indicate which authorizations the currentuser does and does not hold. Thesqlputhorizutions structure isdefined in sq1util.h as follows: struct sql-authorizations short sql-authorizations-len; short sql-sysadm-auth; short sql-dbawauth;
/* The size of the /* sql-authorizatione structure /* The user has System Administrator /* authority /* The user has Database Administrator
*/ */ */ */ */
Chapter 5: Program Preparation and GeneralProgramming APIs
j
i
/
/* /*
authority The user has CREATETAB authority /* The user has BINDADD authority short sql-connect-authr /* The user has CONNECT authority /* The user belongs to a group that short eql-eyeadm-m-auth; /* has System Administrator authority short eql-dbawgrp-authr /* The user belongs to a group that /* has Database Administrator authority short sql-crestetabgrp-auth; /* The user belongs to a group that /* has CREATETAB authority ' /* The user belongs to a group that short sql-bindadd-grp-auth; / * has BINDADD authority short eql-connect-grp-authr /* The user belongs to a group that /* has CONNECT authority shorteql-eysctrl-authr /* The user has System Control authority short sql-sysctrlgrp-auth; /* The user belongs to a group that /* has System Control authority short sql-eyemaint-auth; /* The user has System Maintenance /* authority short eql-eyemaint-grp-authr /* The user belongs to a group that /* has SYSMAINT authority short eql-create_not_f~c-aunc_authi/* The user has CREATE NOT /* FENCED authority short eql-create-not-fenc-grp-auth; /* The user belongs to a group that has /* CREATE NOT FENCEDauthority short s p l - ~ l i c i t g c h ~ - a u t h ; /The ~ user has IMPLICIT SC?!EldA /* authority short eql_~licit-echema_grp-auth; /* The user belongs to a group that has /* IMPLICIT SCHEMAauthority 1;
short sql-createtab-authr short sql-bindadd-auth;
I
129 */ */ */ */ */
*/ */
*/
*/ */
*/ */ */
*/
*/
*/ */ */ */
*/ */
*/ */
*/ */
*/
*/ */ */ */ */
The first element in this structure,sqZ-uuthorizations-Zen, must be initialized to the size of the structureitself before the QET AUTHORIZATIONS function is called.
Comments
H Explicit SQL commands can be used to grant direct authorities to a specific user. System Administrator, System Maintenance, and System Controlare indirect authorities and therefore cannotbe granted directly to a user. Instead, they are available only through the groups to which a userbelongs. PUBLIC is a special group to which all users belong. If this function executeswithout error, each fieldof the sql-authorizations structure variable will contain either a o or a 1.A value of 1 indicates that the current userholds the corresponding authorization, whilea value of o indicates that theuser does not.
Connection This function can only be called if a connection to a database exists. Requirements Authorization No authorization is required to execute this function call.
Part 3: Application Programming Interface Functions Example
The following C++ program illustrates how to use the QET AUTHORIZATIONS function to determine whether or not the current user has been granted the authorizations needed to execute most of the DB2 N I functions:
*/
/* CHSEx10.8QC
/* /* /*
*/
NAME: PURPOSE: Illustrate How To Use The Following DE2 API Function In A C++ Program:
/* /* /*
*/
*/ */
*/ */
QET AUTHORIZATIO198
*/
/*
/ / Include The Appropriate #include <windowe.h> #include #include <eqlutil.h> #include <eql.h>
Header
Files
/ / Define The API-Claee Claee claee -1-Claes
c
/ / Attributes public: struct eqlca eplcat
/ / Operatione public: long QetAuthorizatione (); )l
/ / Define The QetAuthorizationeO Member Function long API_Claea:rQetAuthorizatione() (
/ / Declare The Local Memory Variables etruct eql-authorizatione AuthInfoi / / Initialize The Firet Element Of The AuthInfo Structura AuthInfo.eq1-authorizatione-len = eizeof(struct eql-authorizations)t / / Retrieve The Current Ueer’e Authorizatione eqluadau(MuthInfo, brsqlca); / / If The Ueer’e Authorization Information Wae Retrieved, Dieplay / / A Meemage Stating nether Or Not The Weer Rae The / / Authorization8 NeededTo Executa Most OfThe DB2 APIe
if (eqlca.sqlcde == SQL-RC-OK) (
if (AuthInfo.epl-eysa&auth AuthInfo.eq1-eyemaint-auth AuthInfo.eql-eyectrl-auth AuthInfo.eql-&a-auth
c
== == == ==
1 II 1 II 1 It 1)
Chapter 5: Program Preparationand General ProgrammingAPIs
1
c a t << current user haetheauthorizations c a t << %ceded to execute m e t o f n << endl; cout << Ythe DBP APIe." << endl;
else {
1
1
/* /*
1
tout << "The current user doee not havethe authorixatione c a t << Ythat are needed to execute many o f n << endl; cat e DB2 APIe." << endl;
/ / Return The SQLCA Return return(eqlca.eqlcode);
CodeTo The
Calling
Function
*/ */
The Main Function
int main() {
-
/ / Declare The Local Memory Variables rc long SQL-RC-OK; etruct eqlca eqlca; / / Create An Inetance Of The API-Claee Claee API-ClaeeExample; / / Connect TO The SAMPLE Database EXEC SOL CONNECT TOSAMPLE USER userID USINQ paeeword;
/ / Get The Current Ueer'e Authorizatione rc = ~1e.OetAuthorizationeO; / / Iesue A Rollback To Free EXEC SQL ROLLBACK1
All
Locke
/ / Dieconnect From The SAMPLE Database EXEC SQL DISCONNECT CURRENT;
1
/ / Return To The Operating return ( rc ) ;
System
This Page Intentionally Left Blank
F L
,
.
8
,
134 i I.
R!!
I
Part 3 Application Programming Interface Functions
m The DB2 Database Manager Server Processes
Before a database connection or DB2 Database Manager instance attachment can'be established by an embedded SQLor DB2 API application, the DB2 Database Manager server processes mustfirst be started. DB2 Database Managerserver processes are usually started when you issue the START DATABASE MANAGER command fromthe DB2 command-line processor. On DB2 server workstations, the DB2 Database Manager server processes are often started as part of the workstation boot-up sequence. You can also s t a r t the DB2 Database Managerserver processes fromwithin an applicationprogram by Calling the START DATABASE MANAGER function. Once started, these processes run in thebackground until they are explicitly stopped "when anapplication thst startedthese processes terminates, the processes continue running. You can stop the DB2 Database Managerserver processes byissuing the STOP DATABASE MANAGER command from the DB2 command-line processor or by calling the STOP DATABASEMANAGER function fromwithin an application program.
Creating and Deleting DB2 Databases A database is simply a set of all DB2-related objects. When you create a DB2 databise, you are establishing an administrative entity that provides an underlying structure for an eventual collection of tables, views, associated indexes, etc., as well as the table spaces in which they reside. You can create all the objects in a database through various embedded SQL statements. You must create the database itself, however, by some other means, andthe database must exist before anyof its objects can becreated. You can create DB2 databases by issuing the CREATE DATABASE command from the DB2 command-line processor. In many cases, however,it is desirable to create one or more databases from an application program. This statement is especially true for applications that are designed to install database applications on new workstations where the necessary databases do not already exist. You can create databases from an applicationprogram by callingthe CREATE DATABASE function. When a database is no longer needed, youcan delete it by issuing the DROP DATABASE command h m the DB2 command-line processor. You can also delete databasesh m within an application program by &g the DROP mTABASE function. By using THE CREATE DATABASE and DROP DATABASE functions together, an application can m a t e a temporary database whenit starts execution and drop it when it is no longer needed.
Starting and Stopping DB2 Databases When an applicationfirst issues a CONNECT SQL statement to establish a connection to a DB2 database, it must wait while the DB2 Database Manager starts up the appropriate database. In many cases,the application spends asignificantamount of time ini-
?q Chapter 6: DB2 DatabaseManagerControl and Database Control ApIs " .
!I 135 .. ...
-1
tializing the database before it can do other work. However, once a database has been started, other applicationscan simply connectto and begin usingit. To remove database start-up and initialization overhead from the &st application that establishes aCOMW tion, database administrators can use the ACTIVATE DATABASE functionto pre-start selected databases. Likewise,database adminstrators can remove the overhead of shutting down a database from an application by using the DEACTIVATE database function. When used together, these functions can improvethe performance of embedded SQL applications,particularly when database a is partitioned across several workstations (nodes).
Retrieving and Setting Other Connection Setting Values The typeof connectionan application makesto one or more databases is oRen determined by the precompiler optionsthat were speded when the application was precompiled. An application canretrieve these values by calling the QUERY CLIENT function any time during its processing. You can leavethese settings as they are or modify them by calling the SET CLIENT function before a connection t o a database is established. This method of specifying connection options is particularly helpful when usedby applications that contain no static embedded SQL statements (and therefore, do not need to be precompiled).
Controlling DB2 Database Manager Connection Instances As long as an application executesagainst a local database, one or more connectionsto the background DB2 Database Managerserver processes is sufficient for most processing needs. Whenan application is designed to execute against one or more remotedatabases, you must first establish a connectionto the DB2 Database Manager server process instance that is controlling the remote database. The ATTACH function can be used to establish a logicalinstance attachment to the DB2 Database Managerserver processes running at a remote workstation. When an application attaches to the remote DB2 Database Manager server processes, it starts a physical communications connectionto the workstation if one does not already exist. Whenall remote processingis complete, the DETACH functioncanbeused to close the physicalcommunicationsconnection to the workstation and detach fromthe remote DB2 Database Managerserver processes.
M F FW The DB2 Database Manager and DB2
Database Control Functions Table 6-1 lists the DB2 AFT functions that areused to interact with the DB2 Database Manager and that are used to create and delete DB2 databases. Each of these functions are described in detail in the remainder of this chapter.
I
I
1"~"
?
136 j
I
.
Table 6-1
Part 3: Application Programming Interface Functions
!
DB2 Database Manager Control and Database Control APls
P %
START
DATABASE
STOP
DATABASE
FORCE
MANAGER MANAOER
APPLICATION
CREATE DROP
DATAEASE
DATABASE
DEACTIVATE
Stops the DB2 Database Manager serverprocesses. Forces all local and remote usersand/or applications off a DB2 Database Manager instance. Creates a new database andita associated supportfiles. Deletes an existing database andall ita associated supportfiles.
DATABASE
ACTIVATE
Starts theDB2 Database Manager serverprocesses.
DATABASE
Activates a database andstarts up all appropriate databaseservices. Deactivates a database and shutsdown all appropriate databaseservices.
ATTACH
Specifies the node at which DB2 Database Managerinstance-level functions are to be executed.
ATTACB AND CIi?iNGE PASSWORD
Specifies the node at which DB2 Database Manager instance-level functions are to be executed (and permits the userto change the password for the instance being attached).
DETACH
Removes a logical DB2 Database Manager instance attachment.
QUERY SET
Specifies connectionsetting valuesfor an application.
CLIENT
QUERY SET
Retrieves the currentconnection setting valuesfor an application.
CLIENT
CLIENT
CLIENT
INFORMATION
INFORMATION
a client that is connected to a server. Retrieves information about
Specifies information abouta client that is connected to a server.
.
Chapter 6: DB2 DatabaseManagerControlandDatabaseControl
,
MIS
137
mm Purpose
syntax Parameters
The START DATABASE MANAOERfunction is used to start an instance of the DB2 Database Manager server background processeson a single nodeor on all nodes defined in a multi-node environment. SQL-API-RC SQL-API-FN sqlepstart (struct sqle-start-options sglca struct
Startoptions
*StartOgtion~, *SQLCA);
A pointer to a sqle-start-options data structure that contains information about how the DB2 Database Manager background processes are t o be initialized when started.
SQLCA
A pointer to a location in memorywhere a SQL Communications Area (SQLCA)data structurevariable is stored. This structure returns either status information (if the function executed successfully) or error information (ifthe function failed)to the calling application.
Includes
#include <sqlenv.h>
Description
The START DATABASE MANAG= function is used t o start aninstance of the DB2 Database Manager server background processes ona single nodeor on all nodes defined in a multi-node environment. These processes must be started before any database connections or instance attachments to the DB2 Database Manager canbe made. Once started, theDB2 Database Manager server processes run in the background until the STOP DATABASE MANAGER function or command is executed. When this function is called, a special structure (sqle-start-options) is used to pass start-up options to the DB2 Database Manager. Thesqle-start-options structure is defined in sqlenv.h as follows: struct sqle-start-options {
sqloptid
char
t 81 ;
*/
/* A structure identifier and */ / * eye-catcher €or storage dumps. This */ / * is a atring. 8 bytes in length,
/*
thatmust be initializedwith /* the value /* SQLE-STARTOPTID-V51. long
profile
*/
*/ */
unsigned
char
*/
*/
/* /* /* /*
Indicates whetheror not a profile file is specified. I€ no profile is specified,thefile db2profile is used.
/* /*
The name ofthe profile file to be executed at each node (to */
L2371 ;
*/ */ */ */ */ */
Part 3: Application Programming Interface Functions /* /*
/*
define the DB2environment). Thie file ie executed before the n d e ie etarted.
/* /*
Indicatee whetheror not a node number ie epecified
uneigned long isnodenum;
SQL-PDB-NODE-TYPE
ndenum;
/* /*
The node number that the START DATABASE MANAGER command ie to be I * ran againet. I€ no node number ie / * epecified, the command will be /* ran againet all nodes etored in /* the file ab2nodee.cfg.
unsigned long option;
/* Indicatee whether a /* operation ie to be /* (SQLE-NONE), a node
/*
/* /*
/* /* /*
Indicatee whetheror not a hoet / * name ie epecified
hoetname[257] ;
/* The name of the ayetem that the /* START DATABASE W A G E R command /* is to be ran againet ;
/* /*
Indicatee whetheror not a port number ie epecified
uneigned
long
/*
The port number that the START DATABASE W A G E R command ie to be ran againet. Indicatee whetheror not a net epecified
/* name is char
netname 12571 ;
/* The net name that the uneigned
long
START
/* /*
Indicatee whether temporary epacee are not to be created when a node ie added (SQLE-TABLESPACES-NONE), temporary table apace containere foran added node ehould be the eame ae thoee defined for the node (SQLE-TABLESPACES-LIKEJJODE),
/*
/* /* /* /*
/*
*/
*/ */ */
*/ */ */ */
*/ */ */
ran against
command ie to
*/ */
*/ */ */ */ */ */ be */ */ */ table*/ */ */
DATABASE MANAOER
/*
*/
*/
/* /* tblepace-type;
*/
*/
ienetname;
/*
*/
*/
SQL-PDB-PORT-TYPE port;
/* /*
*/
*/
/*
uneigned long ieport
*/ */ */
normal etart performed */ ie to be added */ when the etart operation ie */ performed (SQLE-ADDNODE), a */ databaee ie to be reetarted */ (SQLE-RESTART), or a node ie to *I be etarted in etand-alone mode */ (SQLE-STANDALONE). */
uneigned long iehoetname;
char
*/ */ */ */
*/
*/ */ */ */
*/
Chapter 6: DB2 Database Manager Controland DatabaseControl APIs
SQL-PDB-NODE-TYPE
char
camputer [l711
/* /* /* /*
/* /*
Specifies the node number that "/ temporary table epace definitione */ ehould be obtainedfrom. This node */ number must existin the */ dblnodes .cfg file, and is only */ used if the t b l 8 p a C g t y p e field */ is set to */ SQLE-TABLESPACES-LIKE-NODE */
/* /*
Indicates whetheror not a computer nameis specified
(SQLE-TABLESPACES-LIKE_CATALOG).
tblspace-node;
/* The name of the computer that /* START DATABASE MANAGER /* commapa is to be ran against
/*
*/ */ */ */
*/ */
the
ID ( O W 2 and
char *pPassword;
/*
*/ */
*/ */
iscamputer;
/* Logon account user /* Windows only)
Comments
*/
temporary table space containersfor an added node shouldbe the same as those defined for the catalog node of each database
char *puserName;
1;
1
139
/* /* /* /* /* /*
/* /*
unsigned long
!
Logon account passo~ord ( O W 2 and windows only)
*/ */ */ */ */
*/ */ */ */
H T h i s function does not need to be called on a client workstation if the applications
running on that workstation only accesses databases on a server workstation (i.e., if no local databases stored on the client workstationare to be accessed). W
If the DB2 Database Manager server processesare successfully started, a message will besent to the standardoutput device. Ifthe DB2 Database Manager server processes are not successfidlystarted, processing will stop,and an error message will be sent to the standardoutput device. Thestandard output device is normally the display monitor, unlessit has been redirected. H If this function is called whilethe DB2 Database Manager server processesare already running, an error will be generated. If this occurs, the application can ignore the error and continue execution (becausethe server processes are already running). W If no options are specified whenthis function is called in a multi-node database environment, the DB2 Database Manager is started on all parallel nodes specified in thenode configuration file. Applications should ensure that allapplicable nodes in a multi-node environment have beenstarted before issuing a request to the database.
1
140
1
Part 3: Application Programming Interface Functions
! l
" h i s function supports SIGINT and SIGATJtM signals on Unix platforms. Ifeither
signal occurs, all in-process start operations are interrupted,and a message
(SQL1044Nfor SIGINTand SQL6073N for SIGALRM) is returned to the error'log from each interrupted node. Nodesthat were already started arenot affected. If the SIGINT signalis issued on a node that is just starting, theSTOP DATABASE MANAQER function or command must be executed on that node before this function can be called again.
Connection This function can be called at any time; a connection to a DB2 Database Manager Requirements instance or to a DB2 database does not have to be established k t . Authorization Only users with either System Administrator(SYSADM) authority, System Control (SYSCTRL) authority, or System Maintenance(SYSMAINT)authority can execute this function call. See Also
STOPDATABASEMANAGER
Example
Thefollowing C++ program illustrates how t o use the START DATABASE MANAQER function to start the DB2 Database Managerserver processes:
~
/* /* /*
CH6EXl.CPP PURPOSE: Illustrate H o w To Use The Following DB2 API Function In A C++ Program:
NAME:
/*
MANAQER /*
*/
*/ */
DATABASE
*/
START
*/ *i/
/* /* / / Include The Appropriate #include <windows.h> #include #include <sqlca.h>
Header
Files
/ / Define The API-Class Class class API-Class {
/ / Attributes public : struct eqlca eqlca; / / Operations public : long StartDB2MgrOt )l
/ / Define The StartDB2MgrO Member Function long ~~I~Claes:rStartDB2MgrO {
*/
Chapter 6: DB2 Database Manager Control and Database Control
MIS
11
14 1
/ / Declare The Local M e m o r y Variables struct sple-etart-options StartOptions; / / Initialize The Start / / Structure
DB2 Database Manager Options
etrcpy(StartOptions.eqloptid. SQLE-STARTOPTID-V51); 9tartOptions.isprofile 0; strcpy(StartOptions.profile, 9tartOptione.isnodenum I 0; StartOptione.nodenum 0; 8tartOptions.option = SOLE-NONE; StartOptione.isbostname = 0; strcpy(StartOptione.hostname, StartOptiona.ieport I 0; StartOptione.port = 0; 9tartOptione.ienetname 0; strcpy(8tartOptione.netname. 8tartOptiOnS.tblepaCe-type S Q L E - T ~ ~ S ~ A C ~ s - ~ I ~ - ~ T ~ ; 9tartOptions.tblepace-node I 0; Start0ptions.iscomputer P 0; etrcpy(StartOptions.computer, u w ) ; 9tartOptione.pUeerName I NULL; 9tartOptions.pPassword = NULL; I
-
-
-
/ / Start The DB2 Database Manager Server Proceeses sqlepstart(hStartOptions, Bsqlca);
/ / If The DB2 Database Manager Server Processes Have Been / / Started. Display A Success Message if (sqlca.splcode -.I SQL-RC-OK.) cout << "The DB2 Database Manager hae been started.w << endl;
/*
/*
*/ The Main Function
int main( ) / / Declare The Local long rc = SQL-RC-OK;
Memory
Variables
/ / Create An Instance Of The API-Class Class API-ClassExample; / / Start
rc
I
The DB2 Database Manager Server Proceeses Example. StartDB2Mgr( ) ;
/ / Return To The Operating System return )(rc ;
1
*/
iI
144
n
l:, 1
Part 3: Application Programming Interface Functions M The DB2 Database Manager server processes cannotbe stopped if any DB2
application programsare currently connected to the DB2 Database Manager instance. TheFORCE APPLICATION function canbe used to disconnect all applications that are connected to a DB2 Database Manager instance. B If this function is called whenthe DB2 Database Manager server processes are not running, an errorwill be generated. B If this function is called whilethere areinstance attachments but no database connections, the instance attachments areforced off, and the DB2 Database Manager background server processes are stopped. B In a multiple-node environment: B All nodes that have been addedto the system sincethis function waslast called will be included in thedb2nodes.cfg configuration file.This function canbe used to remove a node from this configuration file. M The filedb2cshrc is not supportedand cannot be specified as a profile fileto use. B On UNM platforms, if the SIGALRM signal is encountered, this function will interrupt all stops that arein progress and return SQL6037N foreach interrupted node to the error log file. Nodesthat have already been stoppedare not affected.
Connection This function can be called at any time; a connection to a DB2 Database Manager Requirements instance or to a DB2 database does not haveto be established &st. Authorization Only users with System Administrator (SYSADM) authority, System Control (SYSCTRL) authority, or System Maintenance(SYSMAINT)authority can execute this function call.
see Also
START DATABASE MANAOER, FORCE APPLICATION
Fbmple
Thefollowing C++ program illustrates how to use the STOP DATABASE I U A N A Q ~ function to stop the DB2 Database Manager server processes:
/*
/* /* /* /* /* /*
NAME: CH6EX2 .CPP PURPOSE: I l l u s t r a t e How T o U s e The Following DB2 API Function In A C++ Program: STOP
DATABASEW A Q E R
/ / Include The Appropriate Header ~ i l e e #include *windows.h, #includedostream.h* #includeaqlenv.h, #include a q l c a . h *
*/ */
*/ */ */ */ */
Fi
I
'
II
Il
l ' 8
; l
Chapter 6: DB2 Database Manager Control and Database Control
MIS
'
i
145
/ / Define The API-Class Class class MI-Class
c
/ / Attributes public: struct eqlca sqlca; / / Operations public: long StopDB2Mgr ();
1; / / Define The StopDB2MgrO Member Function long API_Class::StopDB2MgrO {
The LocalMemory Variables etruct sqleUbstopopt StopOptions;
/ / Declare
/ / Initialize / / Structure
The stop DB2 Database Manager Options
stopOptions.isprofile = 0; strcpy(StopOptiona.profile, "") ; StopOptions.isnodenum = 0; StopOptions.nodenum = 0; StOpOptiOnt3.OptiOn = SQLE-NONE; Stop0ptions.callerac SQLE-DROP;
-
/ / stop The DB2 Database Manager Server Processes sqlepstp(&StopOptions, brsqlca);
/ / If The DB2 Database Manager Server Processes Have Been / / Stopped, Display A Success Message if (sqlca.sqlcode = SQL-RC-OK) cout *< "The DB2 Database Manager has been stopped.** *< endl;
~~
/* /*
*/
The Main Function
*/
int main() / / Declare The Local Memory Variables long rc = SQL-RC-OK; / / Create ~n Instance Of The API-Class Class API-classExample;
/ / Stop The DB2 Database Manager rc I Example. StopDB2Mgr () ; / / Return TO The raturn(rc) ;
1
Operating
System
Server
Proceases
I
Part 3 Application Programming Interface Functions
FORCE APPLICATION The FORCE APPLICATIONfunction is used to force bothlocal and remote users and/or applications off a DB2 Database Manager instance.
syntax
SQL_ApI-RC SQL-API-FN eqlefrce
Parameters
NumAgentIDs
AgentIDs
ForceMode
(long I?tunAgentIDs, unsigned long *AgentIDs, unsigned short ForceMode, etructeqlca *SQLCA);
The numberof agent connections that are to be terminated. This value should be the same as thenumber of elements in the array specified in theAgentIDs parameter. A pointer to a location in memory wherean array of unsigned long integers that contain the agent IDS of database users and/or applications to be forced off DB2 Database Manager instances is stored. The operating mode in which the FORCE APPLICATION function is to execute. Becausethe asynchronous operating mode is currently the only mode supported, this parameter must always be set to SQL-ASYNCH.
SQLCA
A pointer to a location in memory wherea SQL Communications Area (SQLCA)data structurevariable is stored. T h i s variable returns either statusinformation (ifthe function executed successfully) or error information (ifthe function failed)to the calling application.
Includes
#include <eqlenv.h>
Description
The FORCE APPLICATIONfunction is used to force both local and remote users and/or applications off a DB2 Database Manager instance. Forcinga user or an application off a DB2 Database Manager instance will result in the loss of that user's or application's connectionsto all databases. To preserve database integrity, onlyusers and applications that areeither idle or executing interruptible database operations can be forcedoff a DB2 Database Manager instance.
Comments
When this function is called withthe F0rceMod.e parameter set to SQL-ASYNCH (the only value permittedat this time), this function does not wait until all specified users and applicationsare terminated before returning. Instead, it returns as soon as its processing has completed or as soon as an error occurs. As a result, there might be a short interval between the time the FORCE APPLICATION completes and the time the specified connectionsare terminated. The STOP DATmAsE m m m m function cannot be executed by another application while this function is executing. Instead, the DB2 Database Managerserver remains active, so subsequent Database Manager operations can be handled
Chapter 6: DB2 Database Manager Control and Database Control APIs
1
f 147
without havingto make a START DATABASE MANAGER function Call. U Users and/or applicationsthat are in theprocess of creating a database cannot be forced off a DB2 Database Manager instance. U ARer this function is callq@he,D,B2,Database Managerwill still accept database
connect requests. Therefore, severalFORCE APPLICATION function calls maybe required to completely forceall users off a DB2 Database Manager instance. U You can usethe GET
SNAPSHOT function to obtain a list of the agent IDS of all active applications currently connected to a database. You can use other database system monitor functionsto gather additional information aboutthe users and/or applications attached t o the database. U Minimal validationis performed on the arrayof agent I D S specified in the AgentIDs parameter. Therefore, applications usingthis function must ensure that the value specifiedin theAgentIDs parameter points to an arraythat contains the same -numberof elements specifiedin the NumAgentIDs parameter. U If the value specifiedin theNumAgentIDs parameter is SQL-ALL-USERS, all users and applications will be forced off the DB2 Database Managerinstance, and any values specifiedin theAgentIDs parameter will be ignored. B If the value specifiedin theNumAgentIDs parameter is 0, an error will be returned. R All users and applications that can be forcedoff a database connection instance will be forcedoff the connection instance.If one or more specified agent IDS cannot be found, an error will occur. (Anagent ID might notbe found, forinstance, if the agent signs off between the time the agent ID information is collected and the time the FORCE APPLICATION function is called.) U The applicationthat calls this function is not forcedoff the DB2 Database Manager instance. B When a user and/or applicationis terminated by the FORCE APPLICATION function, a ROLLBACK is performed to ensure that database consistency is maintained. U Agent I D S are recycled, so when one user signs 0% another user might signon and acquire the same agent ID. Because of this feature, if a significant periodof time elapses betweenthe time agent IDS are collected and the time the FORCE APPLICATION function is executed, the wrong user mightbe forced off the DB2 Database Manager instanee. R If an operation that cannot be interrupted (such as BACRUP DATABASE or RESTORE DATABASE)is terminated because the application performingthe operation was terminated by this function, that operation must be successfully reexecuted before the specified database will become available again. B In a partitioned database environment, this function canbe issued from any node that is partof the partitioned database environment. U In a multi-node environment,this function affectsall nodes that are listed in the db2mdes.cfg configuration file.
Connection T h i s function can only be called if a connection to a DB2 Database Manager Requirements instance exists. To force users and/or applicationsoff a remote database server, an
Part 3: Application Programming Interface Functions application must first attach to that server. Ifno attachment exists, the FORCE APPLICATION function is executed locally.
Authorization Only users with either System Administrator (SYSADM) authority or System Control (SYSCTRL) authority are allowed to execute this function call.
see Also
STOP DATABASE WWAGER, ATTACH, DETACH
Example
"he following C++ program illustrates how to use the FORCE APPLICATION function to force all users andapplications off a DB2 Database Managerinstance:
CHBEX3.CPP
/* /* /*
/*
NAKE: PURPOSE: Illuetrate How To Wee The Following DB2 API Function In A C++ Program:
*/
"/
*/
/*
/*
*/ */
FORCE
APPLICATION
/* /*
*/ */
*/
/ / Include The Appropriate Header File8 #include <Whdow8.h> #include #include <eqlenv.h> #include <sqlca.h>
/ / Operatione public : long StartDBlMgr(); long StopDB2Mgr(); );
/ / Define The StartDB2Mgr() Member Function long API_Clase::StartDB2Mgr() / / Declare The Local M e m o r y Variables 8tr~Ctsqle-start-options StartOptions;
/ / Initialize The Start / / Structure
DB2 Databaa0 Manager Option8
etrcpy(StartOptione.eqloptid, SQLE-STARTOPTID-V5l); StartOptions.isprofile = 0 ; etrcpy(StartOptione.profile, Startoptione.ienodenum I 0; StartOptione.nodenum I 0; 9tartOptione.option = SQLE-NONE;
11
Chapter 6: DB2 Database Manager Control and Database Control APIs
i
".
1491
Start0ptions.ishostname E 0; etrcpy(StartOptions.hostname, u t ' ) ; 8tartoptions.isport = 0; 8tartOptions.port = 0; Startoptions.isnetname = 0; strcpy(StartOptions.netname, Startoptione.tblspace-type E SQLE-TABLESPACES-LIKE-CAT-; StartOptione.tblspace-node = 0; 9tartOptions.iscomputer = 0; strcpy(Startoptions.computer, l ) " ) ; StartOptiOnS.pUSerName = NULL; NULL; StartOptions.pPaseword 9
/ / Start The DB2 Database Manager Server Processes eqlepstart(&Startoptions, &sqlca); / / I€ The DB2 Database Manager Server Processes Have Been / / Started, Display A Success Message if (sqlca.sqlcode == SQL-RC-OK) cout << *The DB1 Database Managerhas been started." e < endl; / / Return The SQLCA Return return(sqlca.sqlcde);
Code TO The
Calling
Function
1 / / Define The StopDB2MgrO Member Function long API-Class::StopDB2M~gr() {
/ / Declare The LocalMemory Variables AgentID; unsigned long struct eqleabetopopt' Stopoptioner / / Force ~ l Applications l Off The DB2 Database Manager sqlefrce(SQL_ALL-USERS, &AgentID, SQLpSYNCH, hsqlca);
/ / If ~ l Users l Have Been Forced Off The DB2 / / Instance, Display A Success Message if (sqlca.sqlcode == SQL-RC-OK)
Databaee
Instance
Manager
c cout << UAll users haveM e n forced off the current DB2 cout << "Database Manager instance." <( endl;
1 / / Initialize / / Structure
The
Stop
DB2
Database
8topoptions.isprofile = 0; etrcpy(stopOptione.profile, 9topOptions.isnodenum E 0; StopOptions.nodenum = 0; StopOptions.opti0n = SQLE-NONE; 9topOptions.callerac = SQLE-DROP;
Manager
options
Part 3: Application Programming Interface Functions / / If The DB2 Database Manager Server Processes Have Been / / Stopped, Display A Success Message if (sqlca.sqlcode == SQL-RC-OK) cout << "The DB2 Database Managerhas been stopped." << endl; / / Return The SQLCA Return return(sqlca.eqlcode);
Code
To
The
Calling
Function
1
*/ */
/*
/* /*
The Main Function
*/
int main() {
/ / Declare The Local Memory Variables long rc r: SQL-RC-OK; / / Create An Instance Of The API-Class Class API-ClassExample;
/ / Start The DB2 Database Manager Server Processes rc = Example. StartDB2Mgr( ) ; / / Stop The DB2 Database Manager Server Processes rc = Example.StopDB2Mgr();
/ / Return To The return ( rc ) ;
Operating
System
1
Purpose
syntax
Parameters
The CREATE DATABASE function is used to create anew database (with an optional user-defined collating sequence),its three initial table spaces, its system tables, and its recovery log file. SQL-API-RC SQL-API-FN
DBName LocalDBAlias
sqlecrea (char char char struct sqleaMiesc etruct sqledbcountryinfo char void etruct sqlca
*DBName, *LocalDBAliae,
*Path, *DBDescriptor,
*CountryInfo, Reservedl, *Reserved2,
*SQLcn);
A pointer to a locationin memory wherethe name of the database to be created is stored. A pointer to a locationin memory wherethe local alias of the database to be created is stored. This parameter can contain a NULL value.
,
.
,
i' 15 1
'
Chapter 6: DB2 Database Manager Control and Database Control APIs
~
m
l
"
Path
DBDescriptor CountryInfo Reservedl Reserved2 SQLCA
A pointer to a location in memory where the pathname or the disk drive ID that specifies wherethe database isto be created is stored. T h i s parameter can contain a NULL value. A pointer to a sqledbdesc structure that contains database description information that is to be used whenthe database is created. A pointer to a sqledbcountryinfo structure thatcontains the locale and code set thatis to be used when the databaseis created. A character value that, at this time, is reserved for later use. For now, this parameter mustalways be set to '\O.' A pointer that, atthis time, is reserved forlater use. For now, t h i s parameter mustalways be set to NULL. A pointer t o a location in memory wherea SQL Communications Area (SQLCA) data structurevariable is stored. This variable will return either statusinformation (if the function executed successfully) or error information (if the function failed)to the calling application.
Includes
#include <eqlenv.h>
Description
The CREATE D A T m s E fundion is used to create anew database (with an optional user-defined collating sequence),its three initial tablespaces, its system tables, and its recovery log file. Whenthis function is executed, it performs the following actions: 1. Creates a database on the specified path or drive. In a multi-node system,the database is created on all nodes listed in thedb2nodescfg configuration file anda
$DB2INSTlNCEYNODJkaxx directory (where3mpc represents the local node number) is created underthe default path at each node.This process ensures that all database objects associated withMerent nodes are stored in different directories-even ifthe subdirectory $DB2INSTANCE is shared by all nodes. 2. Creates the system catalogtables and recovery logfor the new database.
3. Creates an entry in the server's localdatabase directory on the pathindicated by the value specified in thePath parameter (or onthe default path, if no path i s specified). 4. Creates an entry in the server's system database directory and sets the database alias equal to the databasename (if no other alias was specifiedin the LmalDBAlias parameter). 5. Creates a second entry in theserver's system database directory if a local alias
was specified and if the function was issued locally; otherwise, creates an entry in theclient's system database diredory(if called froma remote client). 6. Creates a system or local database diredoryif neither exists. If a description is
specified in theDBDescriptor parameter, the description (comment)is placed in both directories.
Part 3: Application Programming Interface Functions 7. Assigns the code set and territory specified in theCountryInfo parameter to the database. 8. Assigns the collating sequence specifiedin theDBDescriptor parameter to the
database. A flag is set in thedatabase configuration fileto indicate whetherthe collating sequence consists of unique weightsor an identity sequence. 9. Creates the SYSIBM, SYSCAT, SYSFUN, and SYSSTAT schemas (with
SYSIBM as the owner). Two node groups, IBMDEFAULTGROUPand IBMCATGROUP, are also created. 10. Binds previously definedDB2 Database Manager bind filesto the database. 11. Creates the SYSCATSPACE, TEMPSPACEl,and USERSPACEl table spaces
(in a multi-node environment,the SYSCATSPACE table space is only created on the catalog node,and the TEMPSPACEl and USERSPACEl table spaces are created on all other nodes). 12. Performs a special system catalogstep that creates extra views.
13. Grants thefollowing database authorizations:
- Database Administrator (DBADM) authority and CONNECT, CREATETAB, BINDADD, CREATE NOT FENCED, and IMPLICIT SCHEMA privilegesto the database creator.
- CONNECT, CREATETAB, BINDADD,and IMPLICIT SCHEMA database privileges to PUBLIC.
- SELECT privilegeon each system catalogto PUBLIC. - BIND and EXECUTE privilege to PUBLIC for each successfully bound utility. Once the database has been successfully createdin thedatabase server's system database directory, it is automatically catalogedin thesystem database directory with a database alias set to the database name. Two special structures (sqledbdesc and sqledbcountryinfb)are used to pass characteristics about a database t o the DB2 Database Manager whenthis fimction is called. Thefirst structure,sqledbdesc, is defined in sq1env.h as follows: etruct eqledbaeec
<
char
long long eqlabceet
eqldbaid[81t
W l W c pI
/* /* /* /* /* /*
/* /*
/*
/* /*
structure identifier and eye-catcher €or etorage dumpe. It is a string of eight bytee thatm e t be initialized with the value "SQLE-DBDESC-2' (defined in sq1env.h) The contentsof thie field are validated for version control. Codepagevalueused €or the database comment Indicates whether the databaee is to use a collating sequence provided by
A
*/ */ */
*/
. */
*/ */ */
*/ */
*/
I
Chapter 6: DB2 Database Manager Control and Database Control APIs
1
! j 1 53 I
7 "i
:.
"A
*/ /* the system (SQL-CS-SYSTEM) , a */ /* collating sequence provided by the */ /* user (SQL-CS-USER), a pre-Version 5 sequence */ /* collating /* (SQL-CS-COMPATIBILITY), or U0 collating*/ */ /* sequence (SQL-CS-NONE). uneigned char sqlabuact2561; /* User-defined collating sequence */ /* The nth byte of this field contains */ */ /* the sort weight ofthe code point */ /* whose underlying decimal */ / * representation is n in the c d e /* page of the database. If this field */ */ /* is not set to SQL-CS-USER, it is */ /* ignored. char sqlabcmt t311; /* Optional database comment */ pad[11; char /* Reserved */ unsigned long sqldbsgp; /* Reserved; no longer used */ to be sqlabnsg; short I * The number of file segments */ /* created in the database. The */ is 1 /* minimum value for this field */ /* and the maximum value is 256. If */ / * the value -1 is specified, this field */ /* will default to 1. If the value 0 is */ /* specified, a value for Version 1 */
/*
compatibility is provided. Reserved /* The default extent size, in 4KB /* pages, for each table space in the /* database. The minimum value for /* this field is 2 and the maximum /* value is 256. If the value -1 is /* specified, this field will be set /* to 32. struct SQLETSDESC *sqlcatte; /* A pointer to a table space /* deecription control block that / " defines the catalog tablespace. /" If NULL is specified, a catalog /" table space basedon the values /* in sqltstext and sqlabnsg will be /* created. struct SQLETSDESC *sqlusrts;/*A pointer to a table space that /* description control block space. If /* defines a user table /* NULL is specified, a user table /* space based on the values in / * sqltstext and sqldbnsg will be /* created. struct SQLETSDESC *sqlwts;/* A pointer to a table space that /* description control block space. /* defines a temporary table /* If NULL is specified, a temporary /* table space basedon the values /* in sqltstext and sqlabneg will be /* created.
char long
pad2 121 ; sqltsext;
/*
*/ */
*/ */
*/ */ */ */ */ */
*/ */ */ */
*/
*/ */ */
*/ */ */ */
*/ */
*/ */ */ */ */
*/
Part 3 Application Programming Interface Functions This structure contains three pointers to an additional structure, SQLETSDESC, which holds various table space description information. The SQLETSDESC structure isdefined in sqZenu.h as follows: etruct SQLETSDESC {
char eqltedidi81;
/* A etructure identifier and /* eye-catcher for storagedumps. It /* ie a etring of eightbytes that m e t /* be initialized withthe value /* 'SQLE-DBTSDESC-1" (defined in /* 8qlenv.h). The contente of
/*
*/ *l
*/ */ */ */
thia field are validated for vereion*/ control. */ long eqlextnt; /* The table apace extent eize, in */ /* 4KB pagee. If the value -1 ie */ /* specified, thie field will be set */ /* to the current value of the */ /* dft-extent-sz databaee */ /* configuration parameter. */ long eqlprftc; /* The table apace prefetch eize, in */ /* 4KB pagee. If the value -1 ie */ /* specified, thie field will be eet */ /* be eet to the current value ofthe */ /* dftgrefetch-sa databaee */ /* configuration parameter. */ double eqlpovhd; /+ The table apace I/O overhead, in */ /* millieeconde. If the value-1 ie */ /* epecified. thie field will defaultto */ /* 24.1 me (thie value could change */ /* in future releaeeeof DB2) */ double eqltrfrt; /* Thetableapace 1/0 tranefer rate, */ /* in millieeconde. If the value-1 is */ /* specified, thie field will defaultto */ /* 0.9 me (thie value could change in */ /* future releaeee ofDE2. */ char eqltetyp; /* Indicates whether the table apace */ /* is eyetem-managed (SQL-TBS-TYP-SMS) */ /* or databaee-managed (SQL-TBS-TYP-DMS). */ padl char ; /* Reeerved */ ehort eqlccnt ; /* The number of containere aeeigned */ /* to the table epace (the number of */ */ /* elemente in the containr array). etruct cantsinrill ;/* An array of SQLETSCDBSC */ /* structuree that define table apace */ /* containere to be assigned to the */ /* tableepace. */
/*
.
Chapter 6: DB2 Database Manager Control and Database Control APIs
I
!
I
I
,
I 15 5 1
This structure contains an arrayof SQLETSCDESC structures that store table space container information. TheSQLETSCDESC structure is defined in sqZenv.h as follows: StruCt SQLETSCDESC {
sqlctype; char
char long
sqlclen; short char pad2 char
1;
/* Indicateswhetherthetablespace */ device is */ /*a container file a */ /* (SQL-TBSC-TYP-DEW, */ /* (SQL-TBSC-TYP-FILE), or a path */ / * directory /* (SQL-TBSC-TYP-PATH). Note: The value */ */ / * specified in this field cannot be */ /* SQL-TBSC-TYP-PATH if the the */ /* sqltstypoffield is set to */ /* SQLETSDESC structure */ /* SQL-TBS-TYP-DMS. */ padlt31 ; /* Reserved sqlcsize; / * The size of the table space container,*/ */ /* specified */ /* in 4KB pages. Thevalueinthis the eqltstyp */ /* field is only valid when */ /* fieldof the SQLETSDESC structure setis to SQL-TBS-TYP-DMS. */ /* /* The lengthof the containername */ eqlcontr[256] ;/* The name container */ t21; /* Reserved; 2 bytes padding of */ container descriptions. */ /* between
If the database description blockstructure (sqledbdesc)is not set correctly when this function is called, an error message will bereturned, and thedatabase will not be created. The second specialstructure used by this function, sqledbcountryinfo, is defined in sqZe&.h as follows: struct sqledbcountryinfo {
charsqldbcodeset[lOl; database char sqldblocale [6lI 1;
/* The code set that will /* the /* database The territory
be used by
*/ */ */
If this structure is not set correctly, or if no code set or territory values are specified, the locale of the application makingthe CREATE DATABASE function call will be used to determine the code set andterritory values t o use. For a list of valid locale and code set values,.refer to the GET ROW PARTITIONING NUMBER function in Chapter 12.
m l 156
i
,
,
8
,
,
:
Part 3 Application Programming Interface Functions
Comments
If one or more of the previously defined Database Manager bind files are not successfully boundto the new database, this function willreturn a warning in the sqlca data structurevariable (referenced by the SQLCA parameter), along with information aboutthe bind operationsthat failed. If a bind operation fails,you can take corrective actionby manually bindingthe bind filethat failed to the new database after it is created. Thefailure to bind one or more predefined bind files does not preventthe database from being created. H When users have Database Administrator (DBADM) authority for a database, they
can grant authorizations to (and revoke authorizations from) other users or the PUBLIC group. Anotheruser with either System Administrator(SYSADM) authority or Database Administrator (DBADM) authority cannot revokeDBADM authority from the database creator. ,
H This function will fail ifthe application callingit is connected to a database. H ARer a database is created, all character comparisons performedin that database use the collating sequence specified. T h i s sequence affectsthe structureof indexes,
as well as theresults of queries. Thefollowing user-defined collating sequencesare available in theC and C++ language header files:
sqle819a
If the code page of the database is 819 (IS0 Latin/l), this sequence will sort according to the host CCSID 500 (EBCDIC International).
If the code page of the database is 819 (IS0 Latin/l), this sequence will sort according to the host CCSID 037 (EBCDICU.S. English). sqle860a If the code page of the database is 850 (ASCII Latin/l), this sequence willsort according t o the host CCSID 500 (EBCDIC International). sqle86Ob If the code page of the database is 850 (ASCII Latin/l), this sequence will sort according to the host CCSID 037 (EBCDICU.S. English). sqle932a If the codepageof the database is 932 (ASCII Japanese), this sequence will sort according to the host CCSID 5035 (EBCDIC Japanese). sqle932b If the code page of the database is 932 (ASCII Japanese), this sequence willsort according to the host CCSID 5026 (EBCDIC Japanese). You must specifya collating sequence when calling this function;this sequence cannot be changed oncethe database is created. In a multi-node environment,this h c t i o n affects all nodes that arelisted in the db2nocles.cfg configuration file. Theserver node that this function is called on becomes the catalog node forthe new database. H In multi-node environments,databases should notbe created in NFS-mounted directories.
sqle819b
Connection
This function can only be called if no connection to a database exists. In order to
Chapter 6: DB2 Database Manager Control andDatabase Control APIs Requirements create a database at another node, you must first attachto that node; if necessary, a temporary database connection is established by this fundion while it executes. Authorization Only users with either System Administrator(SYSADM) authority or System Control (SYSCTRL) authority can executethis function call. See Also
BIND, CATALOO DATABASE, DROP DATABASE
Example
The following C++program illustrates how to use the CREATE DATABASEfunction to create a new database and how to use the DROP DATABASEfunction to delete the database:
DATABASE DATABASE
/* /* /* /* /* /* /* /* /*
CR6EX4 .CPP PURPOSE: Illustrate How To Use The Following DBP API Functions In A C++ Program:
NAME:
*/
*/ */ */
CREATE DROP
*/
/ / Include The Appropriate #include <windows.h> #include #include <splenv.h> #include <sqlca.h>
Reader
Files
/ / Define The API-Class Class class -1-Class i / / Attributes public : etruct sqlca sqlca;
1;
*/ */ */ */
/ / Operations public : long CreateDBO; long DropDB ();
/ / Define The CreateDBt ) Member long API-Class ::CreateDB( )
Function
i / / Declare The Local M e m o r y Variables ; DBName[40]char [40] DBAliae char ; struct eqledbdesc DBDescriptor;
The LocalMemory Variables strcpy(DBName, "TEST-DB"); StrCpy(DBAliaS, "TEST-DB");
/ / Initialize
Part 3: Application Programming Interface Functions / / Initialize The Database Descriptor Variable strcpy(DBDescriptor.sqlabaid, SQLE-DBDESC-2); DBDescriptor.sq1dbccp = 450; DBDescriptor.sqldbcss = SQL-CS-SYSTEM; DBDescriptor.sqlabudc[0] = 0; strcpy(DBDeecriptor.sqldbcmt, "Test Database"); DBDescriptor.pad[O] = 0; DBDeecriptor.sqldbsgp = Q; DBDescriptor.sqldbnsg = -1; strcpy(DBDeacriptor.pad2, l' "); DBDescriptor.sqltsext = -1; DBDescriptor.eqlcatte = =L; DBDescriptor.sqlusrts = =L; DBDescriptor.sgltmpts = NULL;
/ / Create A New Database sqlecrea(DBName, DBAliae, NULL, kDBDescriptor, NULL, NULL, ksqlca); / / If The Database Was Created, Display A Success if (sqlca.eqlcode == SQL-RC-OK)
'\O',
Message
{
tout << "The database 'l << DBName; cout << has been createti." << endl;
1
/ / Define The DropDB() Member Function long API-Class::DropDB() {
/ / Declare The LocalMemory Variables char DBAlias [4Ol; / / Initialize The LocalMemory Variables strcpy(DBAlias, "TEST-DE"); / / Drop The Specified Database eqledrpd(DBAlias, ksqlca);
/ / If The Database WasDropped, Display A Succees Message if (sqlca.sqlcode I= SQL-RC-OK) {
< c DBAlias; c a t << "The database cout << has been deleted." << endl;
1 / / Return The SQLCA ReturnCode To The Calling return(eqlca.sqlco8e);
1
Function
Chapter 6: DB2 Database Manager Control and Database Control APIs /* /*
,
1<
159
1
*/
The Main Function
*/
int main0 {
/ / Declare The LocalMemory Variables long rc = SQL-RC-OK?
/ / Create ?m Instance Oi The API-Class Class API-ClassExample; / / Create
rc
I
A New Database Example.CreateDB ( ) ;
/ / Drop The New Database rc = Example. DropDB ();
1
/ / Return TO The Operating System return (rc);
DROP DATABASE The DROP DATABASE function is used to uncatalog and delete the contents of a database, along withall files associated withthe database.
syntax Parameters
SQL-API-RC SQL-API-FN
DBAlias SQLCA
sqledrpd (char *DaAlias, structsqlca
*SQLCA);
A pointer to a location in memorywhere the alias of the database to be dropped is stored. A pointer to a location in memorywhere a SQL Communications Area (SQLCA)data structurevariable is stored. T h i s variable returns either statusinformation (ifthe function executed successfully) or error information (ifthe function failed)to the calling application.
Includes
#include *eqlenv.h,
Description
The DROP DATABASEfunction is used to uncatalog and delete the contents of a database, along withall log files associated withthe database (and the database subdirectory).A database must be cataloged in the system database directory before it can be dropped. Whenthe database is dropped, only the specified database alias is removed from the database directory. Ifother aliases with the same database name exist, their entries arenot affected. Ifthe database being dropped is the last entry in the local database directory, the local database.directory is automatically deleted.
1 L
1
:
I
/
160 ; 1 ...~ .___: I
Comments
Part 3: Application Programming Interface Functions W Because this function deletes all user data and database log files, if you need the.
log files for a roll-forward recovery operation (after a database restore operation), save them before callingthis function. W "he database to be dropped must not bein use (i.e., no application can be connected to thedatabase) when this function is called. If necessary,the FORCE APPLICATIONfunction can be used to disconnect all applications connectedto the DB2 Database Manager instance that is controlling accessto the specified database. W If this function callis called from a remote client (or from a differentinstance on
the same workstation),the alias specified will be removed from the client's system database directory, and the corresponding database name will be removed fromthe server's system database directory. When this function executes,it automatically unlinks any files that are linked through DATALINK columns.Because.the unlink operation is performed asynchronouslyon the DB2 File Manager,its effects maynot be seen immediately, and the unlinked files maybe temporally unavailable for other operations. W When this function is called, all DB2 File Managersthat areconfigured to the
specified database must be available.
Connection This function can only be called if a connection to a DB2 Database Manager Requirements instance exists. It is not necessary to call the ATTACH function before dropping a remote database; however, if the database is cataloged as remote, an attachment to ' the DB2 Database Manager instance at the remote node will automatically be ; established for the duration of the function call. Authorization Only users with either System Administrator (SYSADM) authority or System Control (SYSCTRL) authority are allowed to execute this function call.
see Also
CREATE DATABASE, CAT-
Example
See the example providedfor the C R ~ A T EDATABASE function on page 157.
DATABASE, UNCATALOQ DATABASE
m m ACTIVATE DATABASE purpose
The ACTIVATE DATABASEfunction is used to start up all necessary database services so that a specificdatabase is available for connectionand use by any application.
syntax
SQL-API-RC SQL-API-FN sqle-activate-&
(char char char void struct sqlca
*DBAlias, *UserID, *Password, *ReEeNed, *SQLCA)j
i
: !
Chapter 6: DB2 Database Manager Control and Database ControlM I S Parameters
DBAZias UserID
Password
Reserved SQLCA
;
' 16 1
A pointer to a location in memorywhere the alias of the database to be activated is stored. A pointer to a location in memory where the authorization name (user ID) of the user starting thedatabase is stored. This parameter can contain a NULL value. A pointer to a location in memorywhere the passwordfor the authorization name specified is stored. This parameter can contain a NULL value unless an authorization name is specified in the UserID parameter. A pointer that, at this time, is reservedfor later use. For now, this parameter must always be set to NULL. A pointer to a location in memorywhere a SQLCommunications Area (SQLCA) data structurevariable i s stored. This structure returns either status information (ifthe function executed successfully) or error information (ifthe function failed)t o the calling application.
Includes
#include <eqlenv.h>
Description
The ACTIVATE DATABASE function is used t o start up all necessary database services so that a specific database is available for connectionand use by any application. If a database has not been started and a CONNECT SQL statement (or an implicit connect) is encountered in anapplication, that application must wait while the DB2 Database Manager starts and initializes the database. However, oncethe database has been started, other applications can simply connectt o and use it. By using the ACTIVATE DATAEASE function, a database administrator can s t a r t up selected databases in advance and eliminate the initialization overhead that would normally beincurred by the first application that established a connection.
Comments
W Databases that are started by this function can only be shut down by the DEACTIVATE DATABASE function or by the STOP DATABASE MANAGER function. W If a database was started by a CONNECT SQL statement and was later activated by this function, the DEACTIVATEfunction must be used to shut it down. If this function is used t o start a database that needs to be restarted, the database will either be restarted automatically or the RESTART DATABASE function will have to be executed beforethis function can be executed. Theautorestart parameter of the database configuration filedetermines whether or not the database will be restarted automatically. W This function activates the specified database on all nodes within the system. If one or more of these nodes encounters an error during activation of the database, a warning is returned (unless the error occurs on the coordinator nodeor the catalog node, in which case an error is returned). If a warning is returned, the database will remain active on all nodes wherean error was not encountered.
Connection This function can only be called when no database connection exists. Requirements
1
162
__".__
l,/
Part 3: Application Programming Interface Functions
5I
Authorization Only users with either System Administrator(SYSADM) authority, System Control (SQLCTRL) authority, or System Maintenance(SYSMAINT) authority are allowed to execute this functioncall. SeeAlm
Example
DEACTIVATE
DATABASE
The followingc++program illustrates how to use the ACTIVATE activate the SAMPLE database:
DATABASE functionto
/* /* /* /* /*
*/ CH6EX5.CPP NAME: PURPOSE: Illustrate Bow To Use The Following DB2 API Functions In A C++ Program:
DATABASE/* DATABASE /*
*/
ACTIVATE DEACTIVATE
*/
*/ */
/*
/* / / Include The Appropriate Header Files #include <windows.h> #include #include <sqlenv.h> #include <sqlca.h> / / Define The ?@I-Clase class API-Clase
Class
c / / Attributes public : etruct sqlca
eqlca;
/ / operations public : long ActivateDB(char *DBAlias); long DeactivateDB(char 'DBAlias);
1; / / Define The ActivateDB() Member Function long API-Class::ActivateDB(char *DBAlias)
c / / Activate The Specified Database eqlegctivate-db(DBAlias, *QaserIDn,U p a s s w o ~ n ,NULL, heqlca); / / If The Database Was Activated, Dieplay A Success Message if (8qlca.aqlcode == SQL-RC-OK)
c cout << #'The database #I << DBAliaet cout << has been activated." << endl;
1 / / Return The SQLCA ReturnCode To The return(eqlca.sulcode);
1
*/ */ */ */
Calling
Function
Chapter 6: DB2 Database Manager Control and Database Control
ApIs
j.:I :
1 63
/ / Define The DeactivateDB( ) Member Function long API-Class::DeactivateDB(char. *DBAlias)
c
/ / Deactivate The Specified Database sqle-deactivate-ab(DBAlias, UuserIDU, Upassword", NULL, brsqlca); / / If
The Database Was Deactivated, Display A 8uccess Message p= SQL-RC-OK)
if (sqlca.sqlcode
c cout << cout a 1
database << DBAlias; has been deactivated." << endl;
/ / Return The SQLCA Return return(sqlca.sulcode);
Code TO The Calling
Function
1
/* /* /*
*/ */ */
The Main Function
int main()
c / / Declare The Local Memory Variables long rc a SQL-RC-OK; char DBAlias[401 "SAMPLE"; / / Create An Instance Of The API-Class Class API-ClassExample; / / Activate The DB2 SAMPLE Database m Example.ActivateDB(DBAlias);
rc
/ / Deactivate The DB2 SAMPLE Database rc = Example.DeactivateDB(DBAlias); / / Return TO The Operating return(rc) ;
system
1
PUFpo-
The DEACTIVATE DATABASE function is used to shut down allnecessarydatabase services so that a specific databasei s n o longer availablefor connection anduse by an application.
syntax
SQL-API-RC SQL-API-FN eqle-deactivate-&
(char char char void
StNCt sqlca
*DEAliae, *UaerID,
*Paasword, *Reserved,
*SQLCA);
Part 3: Application Programming Interface Functions Parameters
DBAlias UserID
Password
Reserved SQLCA
A pointer to a location in memory wherethe alias of the database to deactivated is stored. A pointer to a location in memory wherethe authorization name (user ID) of the user stopping the database is stored. T h i s parameter can containa NULL value. A pointer to a location in memory wherethe password for the authorization name specified is stored. This parameter can contain a NULL value, unlessan authorization name is specified in the UserID parameter. A pointer that, at this time, is reserved forlater use. For now, this parameter must always be set to NULL. A pointer to a location in memory where a SQL Communications Area (SQLCA)data structurevariable is stored. This structure returns either statusinformation (ifthe function executed successfully) or error information (ifthe function failed)to the calling application.
Includes
#incluUe <eqlenv.h>
Description
The DEACTIVATE DATABASEfunction is used to shut down all necessary database services so that a specific database is no longer available for connection and use by an application.
Comments
Databases that are startedby the ACTIVATE DATABASE function canonly be shut down by this function or by the STOP DATABASE MANAGER function. W If a database was started by a CONNECT SQL statement and was later activated by the ACTIVATE DATABASE function, this function must be used to stop it. W This function deactivatesthe specified database on all nodes within the system. If one or more of these nodes encountersan error during deactivation of the database, a warning is returned (unless the error occurs on the coordinator node or the catalog node,in which case an error is returned). The database will remain active on all nodes where a warning or an error occurs.
This function can onlybe called whenno database connection exists. Connection Requirements
Authorization Only users with either System Administrator(SYSADM) authority, System Control (SYSCTRL) authority, or System Maintenance(SYSMAINT)authority are allowed to execute this function call. see Also
ACTIVATE
Example
See the example provided forthe ACTIVATE DATABASE function on page 162.
DATABASE, STOP DATABASE
MANAGER
PI !
I
:
(
;
Chapter 6: DB2 Database Manager Control and Database Control APIs
~
!
165
m m ATTACH Purpose
The ATTACH function is used to specify the node at which instance-level functions (for example, C-TE DATABASE and FORCE APPLICATION) are to be executed. SQL-API-RC SQL-API-FN
epleatin (char char char struct sqlca
Parameters
J
NodeName
UserID
Password
SQLCA
*NodeName, *UserID, *Password, *SQLCA);
A pointer to a location in memory wherethe name or alias of the DB2 Database Managerinstance that the application is to attach to is stored. "his parameter can contain a NULL value. A pointer to a location in memory wherethe authorization name (user ID) of a user is stored. This name is thename under which the attachment is to be authenticated. T h i s parameter can contain a NULL value. A pointer to a location in memory where the password forthe authorization name specified is stored. This parameter can contain a NULL value. A pointer t o a location in memory wherea SQL Communications Area (SQLCA)data structure variable is stored. This variable returns either statusinformation (ifthe function executed successfully) or error information (ifthe function failed)to the calling application.
Includes
#include <sqlenv.h>
Description
The ATTACH function is used to specify the node at which instance-level APIfunctions (for example, CREATE DATABASE and FORCE APPLICATION) are to be executed. This node might be the currentDB2 Database Manager instance (as defined by the value of the DB~INSTANCEenvironment variable), another DB2 Database Manager instance on the same workstation,or a DB2 Database Manager instance on a remote workstation. When called,this function establishes a logical instance attachment to the specified node and starts aphysical communications connection to the node if one doesnot already exist.
Comments
H If a logical instance attachment to a node is established when this function is
called, the sqlerrmc field of the sqlca data structurevariable (referenced by the SQLCA parameter) will containnine tokens separated by the hexadecimal value OXFF (similar to the tokens returned when a CONNECT SQL statement is successful). These tokenswill contain the following information: Token l The country codeof the application server Token 2 The code page of the application server Token 3 The authorization ID
Part 3 Application Programming Interface Functions lbkn 4 %ken 5 Tbkn 6 lbken 7 lbken 8 lbken 9
The node name, as specified with the ATTACH function The identity and the platform type of the database server The agent ID of the agent that was started at the databaseserver The agent index The node number of the server (always zero) The number of partitions on the server (if the server is a partitioned database server)
W If the node name specified in theNodeName parameter is a zero-length string or the NULL value, information about the current stateof attachment will be
returned in thesqlenmc field of the sqlca data structurevariable (as previously outlined). If no attachment exists, an error will be returned. H The alias name specified in theNodeName parameter must have a matching entry
in the local node directory. The only exception to this ruleis the local DB2 Database Manager instance (as specified by the DBSINSTMCE environment variable), which canbe specified as theobject of an ATTACH function call but cannot be used as a node name in thenode directory.A node name in the node directory can be regarded as analias for a DB2 Database Manager instance. W If this function is never executed,all instance-level API functions are executed
against the currentDB2 Database Manager instance (which is specified by the DBSINSTANCE environment variable).
B Certain functions (for example, START DATABASE MANAGER, STOP DATABASE MANAGER,
and all directory services functions) are never executed remotely. W If an attachmentalready exists when this function is called witha node name
specified, the current attachmentwill be dropped, and an attempt to attach to the new node will be made. If the attemptto attach to a new node fails,the application will be leftin an "Unattached" state. H Where the User IDIPussword pair is authenticated depends on the value of the
authentication parameter in the Database Manager configuration file, located on the node to which the application is attempting to attach. If this configuration parameter contains the value C L I ~the , User IDIPassword pair will be authenticated at the client machine from which the ATTACH function call is issued. If this configuration parameter contains the value SERVER, the User IDlPassword pair will be authenticated at the node that the application is attempting to attach to.If a User IDIPussword pair is not provided,the user ID associated with the current application processwill be used forauthentication.
Connection This function establishes a DB2 Database Manager instance attachment (and Requirements possibly a physical database connection) whenit is executed. Authorization No authorization is required to execute this function call. See Also
ATTACH AND CHANGEPASSWORD,DETACH
; j Chapter 6: DB2 Database ManagerControland Database Control APIs Example
'
i
\ !
1 67 I
Thefollowing C++ program illustrates how to use the ATTACH function to obtain information about the current DB2 Database Managerinstance attachment:
/* /* /*
CHBEX6.CPP PURPOSE: Illustrate How To Use The Following DB2 API Functions In A C++ Program:
NAME:
/* /* /* /* /*
*/ */ */
*/ */
ATTACH DETACH
*/
*/ */
/ / Include The Appropriate #include <windows.h> #include #include <sqlenv.h> #include <sqlca.h>
Header
Files
/ / Define The API-Class Class class API-Class
i / / Attributes public : struct sqlca eqlca; / / Operations public : long QetInstanceInfoO; ?l
/ / Define The QetInstanceInfoO Member Function long API~Class::QetInstanceInfo~~
i
/ / Declare The LocalMemory Variables int Separator = O d F ; int Length; charInfoStringt711; char "Bufferr char Results191 1711; / / Attach To The Default DB2 Database Manager sqleatin("DB2", "UserID", upassword'', &sqlca); / / If Attached, Retrieve Information / / And Paree It if (sqlca.eqlcode m= SQL-RC-OK)
About The Current Attachment
i strncpy(InfoString, sqlca.sqlerrmc, 70); InfoString[691 = 0 1 Length = strlen(1nfoString); Buffer .I strrchr(InfoString, Separator); InfoStringtLength strlen(8uffer)l P l \ O ' ~
-
Instance
Part 3: Application Programming Interface Functions for (int i = 8; i
-
c
B-
0;
i-)
Length etrlen(1nfoString); Buffer = etrrchr(InfoString, Separator); if (Buffer != NULL)
c 1 else 1
etrcpy(Reeulte[il, Buffer + l); InfoStringtLength strlen(Buffer)]
-
1
:m
: : :
: : : :
: :
<< endl << end11 << Results[Ol << << Reeultetll << << Results[21 << m << Resultet31 << << Results[QI << m << Resulte[5] a Resultst61 endl; << Resulte[7] << << Resultet81 <<
m
/ / Detach From The Default DB2 Database sqledtin(hsq1ca);
/ / Return The SQLCA Return return(eqlca.eqlcode);
/* /* The Main /*
'\O*;
strcpy(Results[il, Infostring);
/ / Display The Parsed Information C a t << "Current Attachment Settinge cout << UCoUntry Code cout << "Server Code Page cout << "Authori%ation ID cout << "Node Name cout << "Server Platform COut << "Agent ID cout << "Agent Index cout << "Node m e r cout << "Number Of Partitione
1
5
Manager
Code To The Calling
Function
*Y */ */
Function
/ / Declare The Local EIemOry Variables long rc a SQL-RC-OK.)
/ / Create An Instance Of The API-Claee Class API-ClassExample; / / Attach To A DB2 Database Manager / / Information About It rc = Example.OetInstanceInfo()
1
/ / Return To The return (rc);
endl; endl;
Instance
int main()
c
endl; endl; endl; endl; endl; endl;
Operating
System
Instance And Obtain
F '
Chapter 6: DB2 Database Manager Control and Database Control APIs
:
. . ,
I
I I
!
~
i
j
169 i
ATTACH AND CHANGE PASSWORD The ATTACH AM) CHANGE PASSWORD function is used to specify the node at which instance-levelAPI functions (for example,CREATE DATABASE and FORCE APPLICATION) are to be executed and to change the user password forthe instance being attached.
syntax
SQL-API-RC SQL-API-FN eqleatcp(char char char char etruct eqlca
Parameters
*N&eName, *UserID, *Password, *NewPassword, *SPLCA);
NodeName
A pointer to a location in memory wherethe name or alias of the DB2 Database Managerinstance that the application is to attach to is stored. T h i s parameter can containa NULL value.
UserID
A pointer to a location in memory wherethe authorization name (user ID) of a user is stored. This name is thename underwhich the attachment is to be authenticated. This parameter can contain a NULL value.
Password
A pointer to a location in memory wherethe password forthe authorization name specified is stored. T h i s parameter can contain a NULL value, unlessan authorization name is specified in the UserID parameter.
Newpassword
A pointer to a location in memory wherethe new password forthe authorization name specifiedis stored. If this parameter contains a NULL value, the password forthe authorization name specified in the UserID parameter remains unchanged.
SQLCA
A pointer to a location in memory wherea SQL Communications Area (SQLCA)data structurevariable is stored. T h i s structure returns either statusinformation (if the function executed successfully)or error information (if the function failed)to the calling application.
Includes
#include <eqlenv.h>
Description
The ATTACH AM) CHANOE PASSWORD function is used to specify the node at which instance-levelAPI functions (for example,CREATE DATABASE and FORCE APPLICATION) are to be executed andto change the user password forthe instance being attached. The node specified may bethe currentDB2 Database Managerinstance ( a s defined by the value of the DB~INSTANCEenvironment variable), another DB2 Database Manager instance on the same workstation,or a DB2 Database Manager instance on a remote workstation.When called,this function establishes a logical instance attachment to the node specified andstarts a physical communications connection to the node if one doesnot already exist.
I
m
Comments
Part 3: Application Programming Interface Functions D If a logical instance attachment to a node is established when this function is
called, the sqlerrmc field of the sqlca data structure variable (referenced by the SQLCA parameter) will containnine tokens separated by the hexadecimal value OgFF (similar to the tokens returned when a CONNECT SQL statement is successful). These tokenswill contain the following information: lbken I
The country code of the application server
lbken 2 lbken 3 lbken 4
The code page of the application server Theauthorization ID The node name, as specified with the ATTACH AND CHANQE PASSWORD function The identity and the platform type of the database server The agent ID of the agent that was started at the database server The agent index The node number of the server (always zero) The number of partitions on the server (if the server is a partitioned database server)
lbken 5 lbken 6 Ibken 7 Ibken 8 lbken 9
If the node name specified in theNodeName parameter is a zero-length string or the Nuu value, information about the current stateof attachment will be returned in thesqlenmc field of the sqlca data structurevariable (as previously outlined). If no attachment exists, an error will bereturned. The alias name specified in theNodeName parameter must have a matching entry in thelocal node directory. Theonly exception to this is thelocal DB2 Database Manager instance (as specified bythe DB~INSTANCEenvironment variable), which can be specified as the object of an ATTACH AND CHANOE PASSWORD function call but cannot be used as a node name in thenode directory.A node name in thenode directory can be regardedas an alias for a DB2 Database Manager instance. If this function is never executed,all instance-levelAPI functions are executed against the currentDB2 Database Manager instance (which is specified by the DB~INSTANCEenvironment variable). Certain functions (for example, START DATABASE MANAGER, STOP DATABASE MANAQER, and all directory servicesfunctions)are never executed remotely If an attachment already exists when this function is called witha node name specified, the currentattachment will be dropped, andan attemptto attach to the new node will be made. If the attemptto attach to a new node fails, the application is left in an "Unattached" state. Where the UserIDlPassword pair is authenticated depends on the value of the authentication parameter in theDatabase Manager configuration file, located on the node to which the application is attempting to attach. If this configuration parameter contains the value CLIENT, the UserIDIPassword pair is authenticated at the client machine from which the ATTACH AND CHANQE PASSWORD function callis issued. If this configuration parameter contains the value SERVER, the UserIDl
Chapter 6: DB2 Database Manager Control and Database Control APIs
:
i 1 7 1 1I
I
Password pair is authenticated at the node to which the application is attempting to attach. If a UserIDIPassword pair is not provided,the user ID associated with the currentapplication processwill be used forauthentication.
Connection This function establishes a DB2 Database Manager instance attachment (and RequiFements possibly a physical database connection) whenit is executed. Authorization No authorization is required to execute this function call.
see Also
ATTACH, DETACH
Example
Thefollowing C++ program illustrates how the ATTACH AND CHANQE PASSWORD function is used to attach to, change the password at, andobtain information abouta DB2 Database Manager instance:
*/
/* /*
P
/* /* /* APIe
DB2
/* /* /* /*
CH6EX7. NAME: PURPOSE: Illuetrate How To Use The Following DB2 API Functione In A C++ Program: ATTACH AND CHANQE PASSWORD OTHER
SHOWN:
DETACH
/*
*/
*/ */
*/ */ */
*/ */
*/ */
/* / / Include The Appropriate Header File8 #include <windowe.h> #include #include aq1env.b #include <eqlca.h* / / Define The API-Class Claee claee API-Claee {
/ / Attributes public: etruct eqlca aqlca; / / Operatione public : long OetInetanceInfoOl 11
/ / Define The QetInetanceInfo() Member Function long API-Claee::OetInetanceInfo() / / Declare The Local Memory Variables int Separator P OxFFl int Length; char InfoString[71]8 char*Buffer) char Reeults[9] [71] ;
Part 3: Application Programming Interface Functions / / Attach To The Default DB2 Database Manager Instance ~qleatcp("DB2~,nuserIDrn,"password", "newpass", brsqlca) ; / / If Attached, / / And Parse It
if (sqlca.sqlcode
Retrieve Information About The Current Attachment m-
SQL-RC-OK)
i strncpy(InfoString, sqlca.aqlerrmc, 70); InfoString[69] P 0; Length strlen(1nfoString); Buffer.= strrchr(InfoString, Separator); InfoString[Length strlen(Buffer)1 I ' \ O r ; for (int i = 8; i >I 0 ; i-)
-
I
-
{
Length = strlen(1nfoString); Buffer = strrchr(InfoString, Separator); if (Buffer l = NULL) {
strcpy(Results[il, Buffer + 1); InfoString[Length strlen(Buffer)]
-
P
'\O';
1 else strcpy(Results[il, Infostring);
1 / / Display The Parsed Information cout << "Current Attachment Settings :" << endl << endl; cout << '*Country Code : << Results[O] << cout << "Server Code Page : << Results[ll << cout << "Authorization ID : " << Results[2] << C a t << "Node Name : << Reaults[31 << cout c< "Server Platform : << Resulta[ll << cout << %gent ID : " << Resultat51 << cout << "Agent Index : << Results[6] << cout << "Node Number : " << Results[71 << cout << "NumberOf Partitions : << Results[EI <<
endl; endl; endl; endl; endl; endl; endl; endl; endl;
/ / Detach From The Default DB2 Database Manager Instance sqledtin(hsq1ca);
1
Main
/* /* /*
The
int main() {
*/ */ */
Chapter 6: DB2 Database Manager Control and Database Control APIs
1 1 1
” I
173
-
/ / Declare The LocalMemory Variables long rc SQL-RC-OK;
/ / Create An Inetance Of The API-Claee Claee API-ClaeeExampler / / Attach To A DB2 Database Xanager / / Information About It rc = Example.OetInetanceInfo0 t / / Return To The Operating return(rc) ;
Instance
And
Obtain
System
?
DETACH The DETACH function is used to remove a logical DB2Database Managerinstance attachment and t o terminate the physical communication connection there if areno other logical connectionsusing the instance attachment being removed.
syntax
SQL-API-RC SQL-API-FN eqledtin (etruct eqlca
Parameters
SQLCA
*SQLCA)i
A pointer to a location in memorywherea SQL Communications Area (SQLCA)data structurevariable is stored. This variable returns either status information (if the function executed successfully) or error information (if the function failed) to the calling application.
Includes
#include <eqlenv.h>
Description
The DETACH function is used to remove a logical DB2 Database Managerinstance attachment. If there are no other logical connectionsusing the DB2 Database Manager instance attachment whenthe logical instance is removed, the physical communication connectionwill also beterminated.
Connection This function can be calledat any time; a connection to a DB2 Database Manager Requirements instance or to a DB2 database does not have to be established first. When this function executes,an existing DB2 Database Managerinstance attachment (and possibly a physical communications connection) will be removed. Authorization No authorization is required to execute this function call. See Also
ATTACH, ATTACH
AND CHANGE
PASSWORD
ovi
rd
I
/ /
c escri~tionof each value that e h e field of this structure. § ~ Z e - c o ~ ~ - §connection ~ t t i ~ ~ setting s t ~ c t u r or e an array of s ~ Z e - c o ~ ~ - s econnection tti~~ setting s t ~ c t u r e s
n be retrieve e c o ~ e c t i o ns ~ t t i ~for g sm a ~ ~ l i c a t i ocan the a ~ ~ l i c a tisi oexecutin~). ~ If this function is executed before the § e t t i s~t ~~ c t u r will e contain the values of the ~ r e c o m ~ i l statement has been ~rocessed);otherwise, it will conta called at any time, zation is re~uiredto execute
am illust~ateshow to use
ction to
/* / / / / / / /
uric
"I / / / / /
*/ /
I
riat
r
Part 3: Application Programming-Interface Functians Table 6-2 ConnectionSettings
! SQL-CONNECT-TYPE
SQL-CONNECT-1
Type 1 CONNECTSare supported. This characteristic enforces the single dataof older base per transaction semantics releases. Type 1 CONNECTS are also known as Rules for Remote Unit of Work (RUOW) connects.
SQL-CONNECT-2
Type 2 CONNECTS(multiple databases per transaction semanticsof RUOW) are supported.
SQL-RULES
SQL-DISCONNECT
SQL-SYNCPOINT
SQL-RULES-DB2
Allows the CONNECT SQL statement to switch from the curmntconnection to an established (dormant)connection
SQLJlULES-STD
Allows the CONNECT SQL statement to only establish anew connection.The SET CONNECTION SQL statement must be used to switch from the I+rent connection to an established (dormant) connection.
SQL-DISCONNECT-EXPL
Terminates all connections explicitly marked for release by the RELEASE^ SQL statement when theCOMMIT SQL statement is executed.
SQL-DISCONNECT-COND
Terminates all connections explicit17 marked for release by the RELEASE SQL statement andall connections that do not contain W I m O L D cursors when statement SQL is executed. the C O M M ~ T
SQL-DISCONNECT-AUTO
Terminates all connections whenthe COMMIT SQL statement is executed.
SQL-SYNC-TWOPHASE
Uses two-phase commits to commit the work done byeach databasein multipledatabase transactions. This setting requires a lZansaction Manager (W)to coordinate two-phwe commits among databases that support this protocol.
SQL-SYNC-ONEP-E
Uses one-phasecommits to commit the work done by each databasein multiple-database transactions. Enforces single-updater, multipleread behavior.
t
,
Chapter 6: DB2 Database Manager Control and Database Control APIs
i
,
i
1 77
Table 6-2 ConnectionSettings(Continued)
Value
Description
SQL-SYNC-NONE
Uses one-phase commits to commit the work done by eachdatabase in multiple-database transactions but does not enforce single-updater, multiple-read behavior.
SQL-&UG-NETBIOS-CONNECTIONS
Any number between 1 and 254
Specifies the maximum number of concurrent connections that can be made in an application runningon a workstation thatis using the NETBIOS protocol.
SQL-DEFERRED-PREPARE-OPT
SQL-DEFEXUED-PREPARE-NO
Specifies that PREPARE SQL statementa are to be executedat thetime they are issued.
SQL-DEFERRED-PREPARE-=S
Specifies that the execution of PREPARE SQL statements is to be deferred untila corresponding OPEN, DESCRIBE,or EXECUTE statement is issued. A PREPARE statement will not be deferred if it contains the INTO clause (butno parameter markers). Specifies that all PREPARE SQL statements (other than PREPARE INTO statements, which contain parameter markers) are to be executed at the time theyare issued.
SQL-CONNECT-NODE
Any number between 0 and 999 or Specifies the node to which a connection is to be made.This setting overrides SQL-CONN_cAlrALoa_NODE the value of the DB2NODE environment variable.
SQL-ATTACH-NODE
Any number between o and 999
Specifies the node to which an attachment is to be made.This setting overrides the value of the DB2NODE environment variable.
Adapted from IBWs DB2 Universal DatabaseAPI Reference,Table 24, p. 388-390.
Part 3 Application Programming Interface Functions public: long Queryclient () ; long Setclient();
1; / / Define The QueryClient() Member Function long API-Claee: :Queryclient () {
/ / Declare The Local M e m o r y Variables etruct eqle-conn-setting ConnInfoi
/ / Initialize The Connection Information Structure ConnInfo.type = SQL-CONNECT-TYPE;
/ / If The Connection Information Wae Retrieved, Dieplay It if ( eqlca eqlcode == SQL-RC-OK)
c
1
.
cout << "Current connection Settingrn<< endl << endl; cout << nConnection Type I if (ConnInfo.value =m SQL-CONNECT-1) cout << UType 1" << endl << endl; else ~ 2" e<< endl << endl; cout << U
/ / Return The SQLCA Return return(eqlca.eqlcode);
Code To The Calling
Function
1 / / Define The Setclient0 Member Function long API-Claee::SetClientO
c
/ / Declare The Local Memory Variablee etruct sqle-conn-setting ConnInfo;
/ / Initialize The Connection Information ConnInfo.type = SQL-CONNECT-TYPE; ConnInfo.value = SQL-CONNECT-2;
structure
/ / Set The Current Connection Type To UType eqleeetc(&ConnInfo, 1, hsqlca); / / Return TheSQLCA Return return(eqlca.eqlcode);
Code
TO
The
an
Calling
Function
?
/* /*
The main Function
*/
*/
Chapter 6: DB2 Database Manager Control and Database Control APIs I
1
179
/ / Declare The Local Memory Variablee long rc = SQL-RC-OK;
/ / Retrieve Information About The Current Connection / / Settinge rc P Example.QueryClient ( 1 t / / Set The Current ConnectionType To **'Type2" rc = -le. Setclient ( 1
/ / Retrieve Information About The Current Connection Again / / TO verify That The Connection TypeHae Been Changed rc = Example.QueryCliont0;
1
/ / Return To The teturn(rc);
Operating
System
SET CLIENT Purpose
The SET CLIENT function is used to specifyconnection setting values for a DB2 application.
syntax
SQLXI-RC SQL-API-FN eqleeetc (etruct eqlo-coppeetting uneignd ehort etruct eqlca
Parameters
*Co~ectionSetting~% ZUku~~Valuee, *SPW) ;
ConnectionSettings
A pointer to a sqle-conn-setting structure or an array of sqle-conn-setting structures that contain connection setting options and their corresponding values.
NumValues
An integer value
SQLCA
A pointer to a location in memory where a SQL Communications Area (SQLCA)data structure variable i s stored. "his variable returns either status information (ifthe function executed successfully) or error information (if the function failed) to the calling application.
that specifies the number of connection information values to set. The value for this parameter can be any number between o and 7 .
Includes
#include <eqlenv.h>
Description
The SET CLIENT function specifies connection setting values for a DB2 application.
Part 3 Application Programming Interface Functions Before this function can be executed, an arrayof special structures (sqle-conn-setting structures) mustbe allocated. Referto the QUERY CLIENT function fora detailed description of this structure andfor more informationabout the connection options available. Oncean arrayof sqle-conn-setting structures has been allocated,the type field of each structure inthis array mustbe set t o one of seven possible connection setting options, and the corresponding value field must be set to the value desired for the specified connection option. Once the SET CLIENT function has executed successfully,the connection settings are fixed, and the corresponding precompiler options used to precompile the application’s source code modulesare overridden. All connections made by subsequent transactions will use the new connectionsettings. You can changethese new connection settings only by reexecutingthe SET CLIENT function.
Comments
Connection Requirements
If t h i s function is unsuccessful, the connection setting values for an application will remain unchanged. m The connectionsetting values for an application can only be changed when there are no active database connections associated withthe application (i.e. beforeany connection is established or after a mLgRsrt ALL SQL statement, followed bya COMKIT SQL statement, is executed). This function can only be called when no database connection exists.
Authorization No authorization is required to execute this h c t i o n call. See Also
QUERY CLIENT
Example
See the example provided forthe QUERY CLIENT function on page 175.
m m QUERY CLIENT INFORMXTION Purpose
T h e QUERY CLIENT INFORMATIONfunction is used to retrieve client information that is associated with a specific database connection.
syntax
SQL-API-RC SQL-API-FN eqleqryi(unsigned short DBAliaeLength, char unsigned short struct eqle-client-info struct eqlca
Parameters
*DBAliaP, *Nk~.mValuee, *ClientInfo, *SQLCA):
DBAliasLength The length of the databasealias name stored in the DBAlias parameter. DBAlias
A pointer to a location in memory where the alias of the database to retrieve client information fromis stored. This parameter can contain a NULL value.
Chapter 6: DB2-DatabaseManagerControlandDatabaseControl
APIs
n
1
181
NumValues
An integer value that specifies the number of client information values to retrieve. Thevalue for this parameter can be any number between 1 and 4.
ClientInfo
A pointer to a sqk-client-info structure or an array of sqle-clientinfo structures where this function is to store theclient information retrieved.
SQLCA
A pointer to a location in memory where an SQL Communications Area (SQLCA)data structurevariable is stored. This structure returns either status information (if the function executed successfully) or error information (if the function failed)to the calling application.
Includes
#include <sqlenv.h>
Description
The QUERY CLIENT INFORMATIONfunctionis used to retrieve client informationthat is associated witha specific database amnection.The infmation retrieved by this function is stored in a special structure (sqk-client-info) or an arrayof sql-client-info structures that contain one or more client information options. The sqk-client-info structure is .definedin sqknv.h as follows: struct sqle-client-info
i unsigned short type; unsignedshortlength; char
/* client information type /* The lengthofthealientinformation
/* *pvaluei ./* /* /*
1;
/*
value A pointer to location a in mcrmory that the client in€ormation value will either be written to (QUERY CLIENT INFORMATION) or read from (SET CLIENT INFORMATION)
*/ */ */
*/ */ */ */
Table 6-3 lists each valuethat can be s@ed for the type field of the sqk-client-infi structure, along witha description of each valuethat can be retrievdspecifIed for the corresponding pValue field of this structure. Before this function can be executed, an sqk-clientjnfo client information structure or an array of sqk-client-info client informationstructures must be allocated, andthe type field of each structure used must be set to one of the four possible client information values listedin Table 6-3. After this function has executed, the memory locations referenced bythe pValue field of each client information structure used will contain the current value (setting)of the client information option specified.
Comments
If this function is called with the DBAZias parameter set to NULL,client information will be retrieved for all connections (i.e.,the values that were set when the SET CLIENT INFORMATIONfunction wasused to set client informationfor all connections).
182
Part 3: Application Programming Interface Functions
Table 6-3 Client Information Settings
Information
on
SQL-CLIENT-INFO-USERID
char[25511
Specifies the authorization (user ID) for the client. This ID is for identification purposes only; it is not used for authentication.
SQL-CLIENT-INFO-WRKSTNNAME
char[255]'
Specifies the workstation name for the client
SQL-CLIENT-INFO-APPLNAME
char[255I1
Specifies the application name for the client
SQL-CLIENT-INFO-ACCSTR
char[20011
Specifies the accounting string used by the client2
Adapted from IBMs DB2 Universal Database API Reference, Table 22, p. 386. 'Some servers may truncate this value. 2Thisinformation can also be set using the SET ACCOUNTING STRING function; however, that function does not allow the accounting string to be changed once a connection exists, whereas the SET CLIENT INFORMATION function does. Refer to Chapter 5 for information about the format of this string.
The client information returned by this function can be retrieved at any time. If this function is used to retrieve the value of a client information option that has not been set, the length field of the correspondingsqle-client-info structure will be set to 0, and an empty, NULL-terminated string will be returned as the value.
Connection This function can be called at any time; however, a connection to the DB2 database Requirements specified in the DBAZias parameter must exist if this function is used to obtain client information about a specific connection. Authorization No authorization is required to execute this function call. See Also
SET CLIENT INFORMATION, QUERY CLIENT, SET CLIENT
Example
The following C++ program illustrates how to use the QUERY CLIENT INFORMATION function to obtain the current value of a client's application name:
I
I
/ * NAME:
/* /* /* /* /* /* /*
CH6EXS.SQC PURPOSE: Illustrate How To Use The Following DB2 API Functions In A C++ Program: QUERY CLIENT INFORMATION SET CLIENT INFORMATION
/ / Include The Appropriate Header Files #include <windows.h> #include #include <sqlenv.h> #include <sql.h> / / Define The API-Class Class
*/
.*/ */ */ */
*/ */ */
Chapter 6: DB2 Database Manager Control and Database Control APIs
183
class API-Class {
/ / Attributes public : struct sqlca
sqlca;
/ / Operations public : long QueryClientInfoO; long SetClientInfoO;
1; / / Define The QueryClientInfo ( ) Member Function long API-C1ass::QueryClientInfoO {
/ / Declare The Local Memory Variables char DBAlias [ 8 3 ; struct sqle-client-info ClientInfo; char ApplicationName 1201 ;
/ / Initialize The Local Variables strcpy(DBAlia8, "SAMPLE") ; / / Initialize The ClientInfo.type = Client1nfo.length ClientInfo.pValue
Client Information Structure SQLE-CLIENT-INFO-APPLNAME; = 0; = ApplicationName;
/ / Obtain Information About The Current Client Connection sqleqryi(strlen(DBAlias), DBAlias, 1, &ClientInfo, hsqlca); / / If Information About The Current Client Connection Was / / Retrieved, Display It if (sqlca.sqlcode == SQL-RC-OK) cout << "Application Name: *' << ApplicationName << endl << endl; / / Return The SQLCA Return Code To The Calling Function return(sqlca.sq1code);
1 / / Define The SetClientInfo ( ) Member Function long API-C1ass::SetClientInfoO {
/ / Declare The Local Memory Variables char DBAlias 181 ; struct sqle-client-info ClientInfo; char ApplicationName [ a ] ; / / Initialize The Local Variables strcpy(DBAlias, "SAMPLE") ; 8 trcpy ( Appl icat ionName, "AP ITest " ;
/ / Initialize The Client Information Structure
Part 3: Application Programming Interface Functiohs ClientInfo.type P SQLE-CLIENT-INpO-APPLNAME; ClientInfo.length = 7; ClientZnfo.pValue = ApplicationName; / / Set The Name Of The Client Application eqleeeti(etrlen(DBAliae), DBAliae, 1, brClientInfo, breqlca);
1
/* /*
/ / Return The BQLCA Return return(eqlca. eqlcode) ;
CodeTo The
Calling
Function
*/ */
The Main Function
int main()
c
/ / Declare The Local M e m o r y Variablee long SQL-RC-OK; struct eqlca eqlca;
rc
/ / Create An Instance Of The MI-Claee Claee API-ClaeeExample;
/ / Att-t EXEC SQL
To Connect To The SAMPLE Database CONNECTTO SAMPLE USERueerID USINQ paeewordj
-
/ / Retrieve Information About The Current Client Connection rc Example.QuetyClientInfo ( ) ;
/ / Set The Application Name ForThe Current Client Connection ; rc = -le.SetClientInfo( / / Retrieve Information About The Current Client Connection / / Again To Verify That The Application Name Has Set Been () ; rc = Example .QueryClientInfo / / Ieaue A Rollback To Free All EXEC SQL ROLLBACK;
Locks
/ / Dieconnect FromThe S A W L E Database EXEC SQL DISCONNECT CURRENT;
1
/ / Return TO The Operating )(rc ; return
Syetem
!7 Chapter 6: DB2 Database Manager Control and Database Control APIs
1 I
I
! 185 t
I
1
'
.
m m SET CLIENT INFORZMATION Purpose
The SET CLIENT INFORMATIONfunction is used to specify client information values that areassociated with a specific database connection.
syntax
SQL-API-RC SQL-API-FN
Parameters
eqleeeti(unsigne8 short char unsigned ehort etruct eqle-client-info etruct eqlca
DBAliaeLength, *DBAlias, *-Values, *ClientInfo, *SPICA) ;
DBAliasLength The length of the database alias name stored in theDBAlias parameter. A pointer to a location in memorywhere the alias of the database to DBAZias set client information for is stored. This parameter can containa NULL value. NumValues An integer value that specifies the number of client information values to set. The value for this parameter can be any number between o and 4. ClientInfo
A pointer to a sqle-client-info structure or an array of sqle-clientinfo structures that contain client information options and their corresponding values.
SQLCA
A pointer t o a location in.memorywhere an SQL Communications Area (SQLCA)data structurevariable is stored. This structure returns either statusinformation (ifthe function executed successfully) or error information (ifthe function failed)to the calling application.
Includes
#include <sqlenv.h*
Description
The SET CLIENT INFORMATION function is used to specify client information values that are associated with a specific database connection. Oftan, in a"ransaction Recessing monitor or three-tier clienthemer environment, there is aneed to obtain information aboutthe client (not just theapplication server that is working on behalf of the client). By using this function, an application can pass information about the client itselfto the DB2 server. Before this fundion can be executed,a special structure (sqle-client-info), or an array of sqle-client-info client informationstructures mustbe allocated. Referto the QUERY CLIENT INFORMATIONfunction for a detailed descriptionof this structureand for more information aboutthe client information options available. Once oneor more sqle-client-info structures have been allocated,the type field of each structure used must be set to one of the four client information options available. Also, the desired value forthe option must be stored in thememory locations referenced by the pValue field, and the length (in bytes) of each valuemust be stored in the length field.
Part 3 Application Programming Interface Functions
1 I
Comments
W This function can be used to set values prior to connecting to any database, or it!
can be used to set or modify values once a connection has been established. W Ifthis function is called with the DBAZias parameter set to NULL, client information will be set for all existing, as well as all future,c 0 ~ e d i O I 1 B . W This function can only be used to set client information outside a transaction (i.e.,
m
either before a SQL statement is executed or after a transaction is committed or rolled back). Ift h i s function is successful, the new values will be sent to the DB server, grouped withthe next SQL request sent on the specified connection. Client information valuesset for a specific connection bythis function w l iremain in effect until the specified connectionis broken. Client information valuesset for all connections by this function will remain in effect until the application that called this function terminates.
Connection This function can be called at any time; however, a connection to the DB2 database Requirements specified in the DBAZias parameter must exist if this function is used to set client information valuesfor a specific connection. Authorization No authorization is required to execute this function call. See Also
QUERY CLIENT
Example
See the exampleprovidedfor the QWRY CLIENT INFORMATIONfunction on page 182.
INFORWATION,QWRY CLIENT,BET CLIENT
1 l
188
Part 3: Application Programming Interface Functions
a
" "
lllnma
m
ConfiguringDB2 The DB2 Database Manager uses the values stored in two sets of configuration parameters to determine how to allocate system resources (disk space and memory) for itself and for each opendatabase. In many cases,the default values provided for the configuration parameters are sufficient to meet an application's needs. However, becausethe default values provided are oriented toward workstations that have relatively small amounts of memory and are dedicated database servers,you can improve overall system and application performanceby changing oneor more configurationparameter values. DB2 database applications can range from modestdata entrysystems that contain one or two simple insert SQL statements to large data collection and management systems that contain hundreds of complex SQL queries for accessing dozens of tables within a single transaction. Different types of applications (and users) have different response timerequirements and expectations. Additionally, each application's transaction processing environment contains or one more unique aspects. These differences can have a profound impacton the performance of the DB2 Database Manager, especially when the default configuration parameter values are used. For this reason, it is strongly recommendedthat you fine-tune the DB2 configuration filesto obtain the maximum performance from your particular operating environment. Configuration parameter values should always be modified if your database environment contains one or more of the following elements: W Large databases W Databases that normally service alarge number of concurrent connections W One or more special applications that have high-performancerequirements W A specialhardware configuration Unique query and/ortransaction loads W Unique query and/ortransaction types
DB2 Database Manager Configuration Parameters DB2 Database Manager configuration parameter values are stored in the file db2systm, which is located in the sqllib subdiredory where DB2 was installed. This file is created along withDB2 Database Managerduring the DB2 product installation process. Mostof the parameter values in this file control the amount of system resources allocatedto a single instance of the DB2 Database Manager. Otherparameter values in this file contain information aboutthe DB2 Database Manager itself and cannot be changed. You can use any of the following methodsto view, change, or reset the value of one or more DB2Database Manager configuration parameters from an application program: m The DB2 database director The GET DATABASE MANAGER CONFIGURATION command The GET
DATABASE
MANAGER
CONFIOURATION function
.'
Chapter 7: DB2 Database Manager and Database Configuration APIs
:
!. I
i 189
I
i
The UPDATE DATABASE MANAGER CONFIGURATION command TheUPDATE DATABASE MANAGER CONFIGURATIONfunction The RESET DATABASE MANAGER CONFIGURATION command The RESET DATABASE MANAGER CONFIGURATION function B The GET DATABASE MANAGER CONFIGURATION DEFAULTS function
DB2 Database Configuration Parameters Configuration parameter values for an individual database are stored in the file SQLDBCON, which is located in the SQLxxwm directory that is created when the database is created ( x x w m represents the number assignedby DB2during the database creation process). T h i s file is created along with the directory and other database control files whenever a new database is created. Most of the parameter values in this file control the amount of system resourcesthat areallocated t o the specified database. Other parameter values in thisfile contain information about the DB2 database itself and cannot be changed. You can use any of the following methodsto view, change, or reset the value of one or more DB2 database configuration parameters from an application program: The DB2 database director The GET DATABASE CONFIGURATION command The GET DATABASE CONFIGURATION function The UPDATE DATABASE CONFIGURATION command TheUPDATE DATABASE CONFIGURATIONfunction The RESET DATABASE CONFIGURATION command The RESET DATABASE CONFIGURATION function The GET DATABASE CONFIGURATION DEFAULTS function
The DB2 Database Manager and Database Configuration Functions Table 7-1 lists the DB2 API functions that are used to retrieve, modify, or reset DB2 Database Manager and DB2 database configuration fileparameters. Each of these functions are described in detail in the remainder of this chapter.
1190;: I
Part 3: Application Programming Interface Functions
GET
DATABASEW A G E R CONFIGURATION
Retrieves the currentvalue of one or more DB2 Database Managerconfiguration fileparameters.
GET
DATABASEMANAGER CONFIGURATION
of one or more DEFAULTS Retrieves the system default value DB2 Database Manager consgurationfile parameters.
UPDATE
DATABASEW A G E R CONFIGURATION DATAEASEMANAGER CONFIGURATION
RESET GET
DATAEASE
GET
DATABASECO1sFIGURATION DEFADLTS
UPDATE RESET
CONFIGURATION
DATABASE DATABASE
CONFIGURATION CONFIGURATION
Changes the value of one or more DB2 Database Manager configurationfile parameters. file Resets all DB2 Database Manager configuration parameters to their system defaultvalues. Retrieves the currentvalue of one or more database configuration fileparameters. Retrieves the system default value of one or more database configuration fileparameters. Changes the value of one or more database configuration file parameters. Resets all database configurationfile parameters to their system default values.
!
Chapter 7: DB2 DatabaseManagerandDatabaseConfiguration
APIs
~
;
191
1
I
1 1 1GET DATABASE MANAGER
CONFIGURATION Purpose
The GET DATABASE MANAGER CONFIGURATIONfunction is used to retrieve the m e n t value of one or more configurationparameters (entries) in a DB2 Database Manager configuration file.
syntax
SQL-API-RC SQL-API-FN
SplfxSyS
(USigned short StrUCt SplfUpd
StrUCt splca
Parameters
Numltems
ItemCist
SQLCA
NUlIUt~S,
*ItaiSt,
*SQLCA)I
Thenumber ofDB2 Database Managerconfiguration parameter values to retrieve. This value identifies the number of elements contained in the array of sqlfupd structures specified in the ItemList parameter. A pointer t o an array of sqlfupd structures that specifywhichDB2 Database Manager configurationparameters values are to be retrieved. A pointer to a location in memorywhere an SQLCommunications Area (SQLCA) data structurevariable is stored. T h i s variable returns either status information (if the function executed successfully) or error information (ifthe function failed)to the calling application.
Includes
#include <eplutil.h>
Description
The GET DATABASEW A G E R CONFIGURATION function is used to retrieve the current value of one or more configurationparameters (entries) in a DB2 Database Manager configuration file. DB2 Database Manager configurationparameter values are stored in a file nameddb2systm, which is located in thesqllib subdirectory. This file is automatically created along with the DB2 Database Manager whenthe DB2 Universal Database product is installed. Most of the values stored in this file control the amount of system resources that areallocated to a single instance of the DB2 Database Manager and can be modifiedto increase DB2's overall performance.Other parameter values in this file containstatic information aboutthe DB2 Database Manager instance itself and cannot be changed. T h i s function uses an arrayof special structures (sqlfupd)to retrieve the current
Table 7-2 DB2 Database Manager Configuration Parameters F.-?rm#.wa-r-v-
agent-stack-sz Specifies amount the
of memory allocated and committed by the operating systemfor each agent.This parameter specifies the number of pages for each agent stackon the server.
SQLF-KTN-AGENTSTACK-SZ
unsigned int
l
WI i
-1
I
Part 3: Application Programming Interface Functions
Table 7-2 DB2 Database Manager Configuration Parameters (Continued) d . ., . . ~ .+ . . ., . ~ . .... . . . . : -
.
:
"
-,5,
-?
agentpri
Specifies the execution priority assigned to DB2 Database Managerprocesses and threads on a particular workstation.
aslheapsz
Specifies the size (in pages) of the memory shared between a local client application anda DB2 Database Manager agent.
audit-buf-sz
Specifies the size (in pages) of the buffer used when auditinga database.
authentication
Specifies howand where authentication SQLF-KTNof a user takesplace. A value of CLIENT AUTHENTICATION indicates that all authentication takes place at theclient workstation.A value of SERVER indicates that theuser ID and password are sentfrom the client workstation to the server workstation, so authentication can takeplace a t the server.
unsigned int
backbufsz
Specifies the size (in pages) of the buffer that is wed when backing up a database. "his value is only used if the buffer size is not specified whenthe Backup utility is invoked.
unsigned long
commbandwidth
Specifies the nominal communications bandwidth (in megabytes per second) that isused by the SQL optimizer to estimate thecost of performing certain operations between the database servers of a partitioned database.
float
conn-elapse
Specifies the number of seconds that a T C P m connection is to be established between two nodesin.
SQLF_KTN_CONNELAPSE
unsigned int
cpuspeed
Specifies the CPU speed (in milliseconds per instruction)that is used by the SQL optimizer to estimate thecost of performing certain operations.
SQLF-KTN-CPUSPEED
float
dft-account-str
Specifies the default accountingstring that is to be used whenconnecting to DRDA servers.
SQLF-KTN-DFTACCOUNl-STR
chad261
*-client-adpt
Specifies the default client adapter number for the NetBIOS protocol whose server nameis extracted from DCE Directory Services.This parameter is only wed with the OW2 operating system.
SQLF-KTN-AGENTPRI
int
unsigned long
SQLF-KTN-AUDITBUF-S2
long
unsigned int
p! .
l
'
,
'
~
!
I
i
~
Chapter 7: DB2 Database Manager and Database Configuration APIs
I
Ii
1; 19 3 j "_
Table 7-2 D62 Database Manager Configuration Parameters [Continued)
I dftclient-comm
Specifies the communication protocols that all client applications attachedto a specific DB2Database Manager instance can usefor establishing remote connections.
SQLF-KTN-DFTCLIENT-COMM
chad311
df-monswitches
Specifies all default valuesfor the snapshot monitor in a single value. You can manipulatethe bitsof this unsigned integer value,or you can use the individual tokensthat make upthis value (see the footnote for more information).
SQLF-KTN-DFTMONSWITCHES
unsigned int
dft-mon-buijmol
Specifies the default valueof the snapshot monitor's bufferpool switch.
SQLF-KTN-DFT-MONBUFPOOL
unsigned int
dft-mon-lock
Specifies the default valueof the snapshot monitor's lock switch.
SQLF-KTN-DFTJdON_ LOCK
unsigned int
dft-mon-sort
Specifies the default valueof the snapshot monitor's sort switch.
SQLF-KTN-DFT-MONSORT
unsigned int
dft-mon-stmt
specifies the default valueof the snapshot monitor's statement switch.
SQLF-KTN-DFT-MONSTMT
unsigned int
dft-mon-table
Specifies the default valueof the snapshot monitor's table switch.
SQLF-KTN-DFT-MONTABLE
unsigned int
dft-mon-uow
Specifies the default valueof the snapshot monitor's Unit of Work WOW) switch.
SQLF-KTN-DFT-MON-
unsigned int
wow
Wbpath
Specifies the default driveor directory path to use to store new databases. If no path i s specified when adatabase is created, the databaseis created in the location indicated by this parameter.
SQLF-KTN-DFTDBPATH
chard161
diaglevel
Specifies the diagnostic error capture level usedto determine the severity of diagnostic errors that get recorded in the error log file(db2diug.log).
SQLF-KTN-DIAQLKVEL
unsigned int
diagpath
Specifies the fully qualified path thatis to be used to locate DB2 diagnostic information.
SQLF-KTN-DIAQPATH
chardlS]
dir-cache
Specifies whether directorycache support is enabled. If this parameter is set to YES, database, node, and DCS directory files are cached in memory. This process reduces connect overhead by eliminating directoryfile V 0 and minimizing the directory searches
unsigned int
I
194 j
Table 7-2
1
Part 3 Application Programming Interface Functions
D62 Database Manager Configuration Parameters (Continued)
required to retrieve directory information. dir-objpame
Specifies the object name that represents a DB2 Database Manager instance (or a database)in theDCE directory namespace. The concatenation of this value andthe dirqath-name value yields a global name that uniquely identifies the DB2 Database Manager instance or database in the name space governed bythe directoryservices specified in thedir-type parameter.
dir-patkname
Specifies the directory path name in SQLF-KTN-DIR-PATHthe DCE name space. The unique name NAME of the DB2 Database Manager instance in theglobal name spaceis made up of this value andthe value in the dir-obj-mme parameter.
char[255]
dir-type Specifies
the type of directory services used (indicates whether the DB2 Database Manager instance uses the DCE global directory services).
unsigned int
discover Specifies
the type of discovery request SQLF-KTN-DISCOVER that is supported on a client or server workstation. A value of SEARCH indicates that a DB2 client searches the network for DB2 databases. A value of KNOWN indicates that a DB2 client searches a specific DB2 Administration Server for DB2 databases. A value of DISABLE indicates that the client (or the server) does not support any type of discovery request.
discover-comm Specifies
the communications protocols that DB2 clients use to issue search discovery requests andthat servers w e to listen for search discovery requests. Cnly TCP/IP and NetBIOS are supported.
discover-inst Specifies
whether a DB2 client can discover a DB2 Database Manager instance.
SQLF-KTN-DISCOVER-
Specifies the DOS requester I/O block size. This parameter controls the size of the V 0 blocks allocatedon both the client and the server workstations. This parameter is applicable onlyon
SQLF-KTN-DOSRQRIOBLK
dos-rqriobk
SQLF-KTN-DIR-TYPE
unsigned int
unsigned int
INST
unsigned int
Table 7-2 DBZ Database Manager Configuration Parameters (Continued)
DOS clients, including DOS clienta running under O S A . drda-heap-sz
Specifies the size, in pages, of the DRDA heap. This heap is used by the D m A AS clause andby DB2 Connect.
fan-num-anchors
Specifies the number of FCM message anchors that are to be used among the nodes of an instance to send messages among themselves.
fcm-nun-buffers
Specifies the number of 4Kl3 buffers that are to be used for internal commuuications amongthe nodes of an instance.
unsigned long
fcm-num-connect
Specifies the number of connection entries thatare to be used among the nodes of an instance to pass data among themselves.
long
faiumm-rqb
Spe&es the number of FCMrequest blocks that are to be used to pass information between the FCM daemon and an agent.
unsigned long
fileserver
Specifies the IPX/SFX file server name (the name of the Novell NetWare file server) wherethe internetwork address of the DB2 Database Manageris registered.
unsigned int
SQLF-KTN-FCMJ"ANCHORS
SQLF-KTN-FILESERVER
long
char[48]
Note: "he following characters are not valid/ \ : ; * ? indexrec
Specifies wheninvalid database indexes SQLF-KTN-INDEXREC should be recreated. This parameter is used if the databaseconfiguration parameter inohrec is set to SYSTFX.
unsigned int
A value of ACCESS indicates that invalid indexes should be recreated the next time theyare accessed. A value of RESTART indicates that invalid indexes should be recreated when the database is restarted. intra-parallel
Specifies whether the DB2 Database Manager can use intra-partition parallelism. In a Symmetric Multiprocessor (SMP) environment, the default for this parameter is YES. In a non-SMP environment, the default value for this parameter is NO. This
SQLF-KTN-INl" PARALLEL
integer
Table 7-2
DB2 Database Manager Configuration Parameters (Continued)
h . . ." ."* " . .. ., .. . 1
I
~
L
parameter can be used on both partitioned and non-partitioned database systems. ipxsocket
Specifies a %ell-known" W S P X socket number and representsthe connection end point in a DB2 server's NetWare internetwork address.
java-heap-sz
Specifies the maximum size (in bytes) . of the heap that is used by the JAVA Interpreter. For non-partitioned database systems,one heap (of this size) is allocated for the instance; for partitioned database systems, however, oneheap (of this size) is allocated for eachdatabase partitionserver.
jdkllgath
Specifies the directory under which the JAVA Development Kit, Version 1.1,is installed.
SQLF-KTN-JDK11-PA"E
char[266]
keepdari
Specifies whether to keep a Database Application Remote InteTface (DARI) process after each DARI call. Ifthis parameter is set to NO, a new DARI process will be created and terminated for each DARJ invocation. Ifthis parameter is setto Y E S , a DARI process will be reused for subsequent DARI calls and be terminated only when the associated user application exits.
SQLF-KTN-KEEPDARI
unsigned int
maxagents
Specifies the maximum number of DB2 Database Manager agentsthat can exist simultaneously on a node, regardless of which database is being used.
unsigned long
maxcagents
Specifies the maximum number of DB2 Database Manager agentsthat can be concurrently executinga Database Manager transaction.This parameter cannot exceed the maxagents parameter.
long
max_connretries
Specifies the maximum number of connection retries (attempts)to make in order to establish a connection to a node.
maxcoordagents
Specifies the maximum number of coordinating agentsthat can exist at one time on a single node.
maxdari
Specises the maximum number of
SQLF-KTN-IPX-SQCRET
char[41
long
SQLF-KTN-BViXCONNRETRIES
unsigned int
long
SQLF-KTN-BViXDARI
long
Chapter 7: DB2 Database Manager and Database Configuration APIs
I
1
197 I1
Table 7-2 DB2 Database Manager Configuration Parameters (Continued)
DAM processes that can reside at the database server. The valueo f this parameter cannotexceed the value o f the maagentsparameter. Specifies the maximum degree of parallelism for an SQL statement to use when executing on this instanceof the DB2 Database Manager. For multi-node systems, this parameter applies to the degree of parallelism to use withina single node. Specifies the maximum time difference, in minutes,that is permitted among the system clocks o f the nodes listed in the nodes configuration file (db2nodes.cfg). maxtotfilop
Specifies the maximum number o f files that can be open per OS/2 application. The valuespecified in this parameter defines the totalnumber o f database and applicationfile handles that can be used bya specific process connected to a database (OS2 only).
min-priv-mem
Specifies the number o f pages that the database serverprocess willreserve as private virtualmemory when a DB2 Database Manager instanceis started (OS/2 only).
SQLF-KTN-MAXTOTPILOP
unsigned int
SQLF-KTN-MIN-PRN-
unsigned long
MKM
mon-heap-sz
Specifies the amount of memory to allocate (in 4KB pages) for database system monitor data (database system monitor heapsize).
nname
Speci6es the name of the node or workstation. Databaseclients use t h i s value to access database server workstations usingNetBIOS. If the database server workstation changes the name specified in nname,all clients that access the database server workstation must catalogit again and specify the new name (OW2 only).
SQLF-KTN-NN2WE
char181
nodetype
Specifies whether the node is wnfigured as a server withlocal and remote clients, a client, or a server with local clients.This parameter ie not updatable.
SQLF-KTN-NODETYPE
unsigned int
Part 3: Application -Programming Interface Functions Table 7-2
DB2 DatabaseManagerConfigurationParameters(Continued)
numdb
Specifies the maximum number of local databases that can be concurrently active (i.e., that can have applications connected to them).
SQLF-KTN-"DB
unsigned int
num-initagents
Specifies the initial number of agents that are to be created in the agent pool when the DB2 Database Manageris started.
SQLF-KTN-NIJ" INITAGENTS
unsigned long
numplagents
Specifies the size to which the agent pool is allowed to grow. The agent pool can contain bothidle agents and MPP/SMP-associated subagents.
SQLF-KTN-NOIUPOOLAGENTS
long
objectname
Specifies the Ipx/spx database SQLF-KTNmanager obiect name of the DB2 Database OBJSCTNA~IE Manager instancein a Novel1 NetWare network.
char1481
"
Note: The following characters are not valid/ : l , * ? priv-mem-thresh
Specifies a threshold below whicha server will not releasethe memory associated witha client when that client's connectionis terminated.
query-heap-sz
Specifies the maximum amount of memory (in 4KB pages) that can be allocated forthe query heap.A query heap stores each query in theagent's private memory.
release
Specifies the release level of the DB2 Database Manager configuration file. This parameter is not updatable.
unsigned int
restbufsz
Specifies the size (in 4KB pages) of the buffer that is used when restoringa database. This value is only usedif the buffer size is not specified whenthe Restore utilityis invoked.
unsigned long
Specifies the time interval(in seconds) after which a TransactionManager (TM) or Resource Manager(RM) retries the recovery of any outstanding, indoubt transactionsfound in theTM or the RM. This parameter valueis only used when transactionsare running in a DUOW environment. route-obj-name
Specifies the name of the default routing informationobject entry that is used by all client applications
SQLF-KTN-RESYNCINTERVAL
unsigned int
char[255]
Chapter 7: DB2 Database Managerand Database Configuration APIs
I 1 199 j i
Table 7-2 D62 Database Manager Configuration Parameters (Continued)
a , '
.
.
.
~
,
Name
P
~
~
~
"
~
Description
l
....
,
. . T ,
attempting to access a DRDA server (DCE only). rqrioblk
Specifies the size (in bytes) of the communication bufferthat is used by remote applications andtheir database agents on the databaseserver.
sheapthres
Specifies a limit on the total amount of memory (in 4KB pages) availablefor sorting acrossthe entireDB2 Database Manager instance.
spm-logfile-sz
Specifies the size (in 4KB pages) of the Sync Point Manager (SPM) log file. This log fileis contained in thespmlog subdirectory of the sqllib subdirectory Sync and is created the first time the Point Manageri s started.
spm-logpath
Specifies the directory wherethe SPM log filesare written. By default, SPM log filesare writtento the sqllib subdirectory.
spm-mm-resync
Specifies the number of simultaneous agents that can be used to perform resync operations.
spm-name
Specifies the name of the SPM instance. SQLF-KTN-S~"NAME The SPM name mustbe definedin the system databasedirectory, and if remote, in thenode directory.
ss-logon
Specifies whether a LOGON user ID and password are required to stop the DB2 Database Managerbackground processes (OS12only).
st&-stop-time
Specifies the time, in minutes,in which all nodes must respondto START DATABASE MANAGERandSToP DATABASE MANAGER requests. Specifies a service namethat represents the DB2 Database Manager instancein a TCP/IP network. Specifies the group namethat has System Administration(SYSADM) authority for the DB2 Database Manager instance. This authority is the highest level of authority within the Database Manager andcontrols all database objects.
SQLF-KTN-RQRIOBLK
unsigned int
SQLF-KTN-SHEAPTRRES
unsigned long
SQLF-KTN-STARTSTOP-TIME
char[8]
unsigned int
I
l
! !
200 i
j
Part 3: Application Programming Interface Functions
Table 7-2 D62 Database Manager Configuration Parameters [Continued)
. 7
-"=w -m xr"
.I
sysctrl_group
SQLF-KTN-SYSCTRLSpecifies the group name that has System Control (SYSCTRL)authority GROUP for the DB2 Database Manager instance. This level allows operations that affect system resources butdoes not allow direct access to data.
charP61
sysmaint-up
Specifies the group namethat has System Maintenance (SYSMAINT) authority for the DB2 Database Manager instance.This level allows maintenance operationson all databases associated withan instance butdoes not allow direct access to data.
charll61
tm-database
Specifies the name of the Transaction Manager (TM)database for each DB2 Database Manager instance.
tp-man-name
Specifies the name of the Transaction monitor Processing (W) product being used.
SQLF-KTN-TP-MONNAME
charll91
tpname
Specifies the name of the remote transaction programthat the database client must use when issuing an allocate request to the DB2 Database Manager instance using the APPC communication protocol.
SQLF-KTN-TPNAME
char[&]
trust-allclnts
Specifies whether all cliente are trusted clients, in which case a level of security is available-and users can be validated a t the client. This parameter, and thetrust-clntauth parameter (see next paragraph),are used together to determine where users arevalidated.
trust-chtauth
Specifies whether all users of trusted clients are validated at the client. This parameter and the trust-allclnts parameter are used togetherto determine where usersare validated.
udf-mem-sz
For a fenced User-DefinedFunction (UDF),this parameter specifies the default allocation for memoryto be shared between the databaseprocess and the UDF. For an unfenced process, this parameter specifies the size of the private memory set. In both cases, this memory passes data to a UDF and back to a database.
SQLF-KTN-SYSMAINTGROUP
chad81
unsigned int
SQLF-KTN-TRUST-
unsigned int
CLNTAUTH
unsigned int
Chapter 7: DB2 DatabaseManager and DatabaseConfiguration APIs Table 7-2
DB2 DatabaseManagerConfigurationParameters(Continued) "<S"..
. ,.
.
-"-"
I
20 1 [
~.i=","~T-".rm-c*
Note: The bits of the SQLP-KTN-DPT-MONSWITC~S parameter value indicate the default monitor switchsettings. The individual bits making up this composite parametervalue are: Bit 1 (xxxxa) dft-mon-uow : Bit 2 (xxxx xxlx): dft-mon-stmt Bit 3 (xxxxx h ) : df-mon-table Bit 4 (xxxxh) dft-mon_buffpool : Bit 6 (rwrl xxxx): dft-mon-lock Bit 6 (h xxxx): dft-mon-sort Adapted from IBM DB2 Universal DatabaseM I Reference,Tables 46 and 47, p. 4 2 M 2 8 .
value of one or more configurationparameters. The sqlfupd structure is defined in sq1util.h as follows: struct sqlfupd
uneigned short token;
*ptrvalue; char 1;
/* /* /*
A
token that identifiee the configuration parameter whose value is to be retrieved /* A pointer to location a in /* memory where the configuration /* parameter value ie to be stored
*/ */ */ */
*/ */
Table 7-2 lists each DB2 Database Manager configuration parameter token that can be specified for the token field of a sqlfupd structure, a description of each corresponding DB2 Database Manager configuration parameter, and information about the WC++ data type of the value retrieved. Before this function can be executed,an arrayof sqlfupd structures mustbe allocated, the token field of each structure in this array mustbe set to one of the DB2 Database Manager configuration parameter tokens listed in Table 7-2, and the ptrvalue field must contain a pointer to a valid location in memory wherethe configuration parameter value retrieved is to be stored. When this function is executed, the current value (setting) of each DB2 Database Manager configuration parameter specified is placed in the memory storage areas (local variables) referred to by the ptrvalue field of each sqlfupd structure in the array.
Comments
If an application is attached to a remote DB2 Database Manager instance (or to a Merent local DB2 Database Managerinstance), the currentvalues of the DB2 Database Manager configuration file parameters the for attached server will be returned; otherwise, the current values of the local DB2 Database Manager configuration file parametersw l ibe returned.
i
202
L""
~
-
:
:
Part 3: Application Programming Interface Functions
.. ...
The applicationthat calls this function is responsible for allocating sufficient memory for eachdata value retrieved. If an error occurs whilethis function is executing, the DB2 Database Manager configuration informationretrieved will be invalid. If an error occurs becausethe DB2 Database Manager configuration filehas been corrupted,an error message will be returned, and you must reinstall the DB2 product to correct the problem. W For detailed informationabout each DB2 Database Manager configuration file parameter, refer to the IBM DB2 Universal Database Administration Guide.
Connection This function can be called at any time to retrieve DB2 Database Manager Requirements configuration fileparameter values from the current DB2 Database Manager instance (as defined by the value of the DB2 INSTANCE environment variable);a connection to the current DB2 Database Manager instance does not have to be established first. In order to retrieve DB2 Database Manager configuration fileparameter values for a DB2 Database Manager instance located at a remote node,an application must attach to that node before callingthis function. Authorization No authorization is required to execute this function call. See Also
GET DATABASE MANAGER CONFIGURATION DEFAULTS,RESET DATABASE MANAGER CONFIGURATION,UPDATE DATABASE MANAGER CONFIGURATION
Example
Thefollowing
c++program illustrates how t0 use the GET DATABASE MANAGER CONFIGURATION function t o retrieve DB2 Database Manager configuration file pa-rameter values:
/* /* /* /* /* /* /*
CH7EXl.CPP NAME: PURPOSE: Illustrate How To Use The Following DB2 API Function In A C++ Program:
*/ CONFIomuLTION GET MANAGER DATABASE
*/ */ */ */
*/ */
/ / Include
#include #include #include #include
The Appropriate Header Files <windows.h> <sqlutil.h> <eqlca.h>
/ / Define The API-Claee class class API-Class 1 / / Attributes public : struct eqlca eqlca; / / operatione
i, 1
Chapter 7: DB2DatabaseManager and DatabaseConfiguration "1s
203
public : long QetDBMgrInfoO;
1; / / Define The GetDBMgrInfoO Member Function long API-Class::GetDBMgrInfo() {
/ / Declare The Local Memory Variables etruct eqlfupd DBManagerInfot21 ; DBPath[216] char ; unsigned int NumDB = 0; / / Initialize An Array Of DB2 Database Manager / / Parameter Structures DBATanagerInfotO1.token SQLF-Km-DFTDBPATH; DeManagerInfo[Ol .ptrvalue E DBPath; DBManagerInfo[ll .token= SQLF-KTN-NUMDB; DBManagerInfo[ll .ptrvalueI (char *) PEFumDB;
-
/ / Obtain The Current Value Of The DB2 / / Configuration Parameters Specified eqlfxsye(2, hDBManagerInfo[O], breqlca);
Database
/ / If The Current ValuesOf The Configuration / / Specified Were Retrieved, Dieplay Them if (sqlca.eqlcode m = SQL-RC-OK) {
1
Configuration
Manager
parametere
'"ax.
COut << number of local databasesthat can be active"; cout : EFumDB << endl; cout << "Path used to etore all databases cout << : << DBPath << endl;
/ / Return TheSQLCA Return return(eqlca.sq1code);
CodeTo The Calling
Function
1
/* Main
/* /*
The
*/ */ */
Function
int main() {
/ / Declare The Local long rc = SQL-RC-OK;
Memory
Variables
/ / Create An Instance Of The API-Class Claee API-ClassExamplet / / Get The Current ValuesOf Specific / / Configuration File Parameters rc = Example.QetDBMgrInfo0; / / Return To The return(rc) ;
?
Operating
System
DB2 Database Manager
1
1
204
Ij
Part 3 Application Programming Interface Functions
I
m Purpose
GET DATABASE MANAGER CONFIGURATION DEFAULTS The GET DATABASEW A G E R CONFIGURATION DEFAULTS function is used to retrieve the system default values for oneor more parameters (entries) in a DB2 Database Manager configuration file.
syntax
Parameters
NumItems
ItemList
SQLCA
Thenumber ofDB2 Database Managerconfiguration parameter default values t o retrieve. This value identifiesthe number of elements contained in the array of sqlfupd structures specified in the ItemList parameter. Apointer to an array of sqlfupd structures that specifieswhich DB2 Database Manager configurationparameter system default values are to be retrieved. A pointer to alocation in memorywhere a SQL Communications Area (SQLCA) data structure variable is stored. This variable returns either status information (ifthe function executed successfully) or error information (if the function failed)to the calling application.
Includes
#inclu&e<eqlutil.h>
Description
The GET DATABASE MANAGER CONFIGURATION DEFAULTS function is used to retrieve the system defaultvalues for oneor more parameters (entries) in a DB2 Database Manager configuration file.This function uses an array of sqlfupd structures to retrieve the system default values for one or more configuration parameters. Refer to the GET DATABASEW A G E R CONFIGURATION function for a detailed descriptionof this structureand for more information about the DB2 Database Manager configurationparameters available. Before this function can be executed, an array of sqlfupd structures must be allocated, the token field of each structure in this arraymust be set t o one of the DB2 Database Manager configurationparameter tokens listed in Table 7-2 (refer to the GET DATABASEW A G E R CONFIGURATION function), and the p t r u a h field must contain a pointer t o a valid locationin memory wherethe configuration parameter default value retrievedis to be stored. Whenthis function is executed, the system default value for eachDB2 Database Manager configurationparameter specified i s placed in thememory storage areas (local variables) referred to by the ptrualue field of each sqlfupd structure in thearray,
Comments
a If an application is attached to a remote DB2 Database Manager instance (or to a different localDB2 Database Manager instance), the system defaultvalues of the DB2 Database Manager configuration file parameters for the attached server will
Chapter 7: DB2 Database Manager and Database Configuration M I S
j
1
2 05
be returned; otherwise, the system default values of the local DB2 Database Manager configuration file parameters will be returned. W The applicationthat calls this function is responsible for allocating sufficient
memory for eachdata value retrieved. M The current value of a non-updatable configuration parameter is returned as that parameter's system default value. M If an error occurs while this function is executing,the DB2 Database Manager default configuration information returned will be invalid. Ifan error om& because the DB2 Database Manager configuration file has been corrupted, an error message will be returned, and you must reinstall the DB2 product to correct the problem. M For a brief descriptionabout each DB2 Database Manager configuration file parameter, refer to the GET DATABASE MANAGER CONFIGURATION function. For detailed information about each DB2 database manager configuration file parameter, refer to the IBM DB2 Universal Database AdministrationGuicle.
Connection This function may be called at any time to retrieve DB2 Database Manager Requirements configuration fileparameter default values for the current DB2 Database Manager instance (as defined bythe value of the DB2INSTANCE environment variable); a connection to the current DB2 Database Manager instance does not have to be established first. parameter In order to retrieve default DB2 Database Manager configuration file default values for a DB2 Database Manager instance located at a remote node,an application must first attachto that node before calling this function. Authorization No authorization is required to execute this function call. See Also
Example
GET DATABASE MANAGER CONFIOURATION,RgSET DATABASE MANAGER CONFIGURATION,UPDATE DATABASE MANAGER CONFIGURATION
Thefollowing
c++program illustrates how to use the GET
CONFIGURATION
DATABASE MANAGER function to retrieve DB2 Database Manager DEFAULTS
configuration fileparameter system default values:
/* /* /* /* /* /* /* /*
CH7EX2.CPP NAME: PURPOSE: Illustrate H o w To Use The Following DB2 API Function In A C++ Program: QET DATABASE MANAQER CONFIQURATION DEFAULTS
/ / Include %e Appropriate #include <windows.h> #include #include <eqlutil.h>
*/ */ */ */ */ */ */
*/
Header
Files
1
I
i include 6sglca.h> / / Define The -1-Class class APIClass
Class
c / / Attributes public : struct sglca
sglca;
/ / Ogerat ions
ublic : long GetDBMgrInfo();
3; / / Define The GetDBM~rInfoO Member ~ n c t i o n long ~P~-Class::GetDB~grInfo()
c / / Declare The Local Memory Variabl~s
truct sglfugd char u n s i ~ e dAnt
DBManagerInf0[21; DBPath [ 216 1 ; iUwnDB = 0;
/ / Initialize An Array Of DB2 Database
ter Structures Info[O].token = SQLF-KT~-DFTDBPATH; InfoCOl .ptmalue = DBPa Info [I].token = SQLF-KT Infotll .gtmalue = (cha tain The System Default Value Of The D nerger Configuration Par sglfdsy~(2, &DBManage~Info[Ol, &sglca); / / If The System Def It Values Of The Conf iguration P a r ~ e t / / Specified Were Retrieved, Displ if (sglca.sglcode == SQL-RC-OK)
c cout << "Max. COUt (6 " : " II
cout
<6
#'
:
<6
DBPath
66
.
endl;
3 Return The SQLCA Return Code To The Callin
3
- */
/+
*/
- */ c / / Declare The Loc
// //
rc
ific D
tab
fi et
value of one or more ~arameters( e n t ~ ~i s )
PI-F
I
t,
ems
~aram~ter. iSt
>
ate the value of
Part 3 Application ProgrammingInterface Functions etruct eqlfupd uneigned ehorttoken1
/*
/* char
*ptrvaluet
/* /* /*
/* /*
A
token thatidentifiee the configuration parameter whoee value ie t o be updated A pointer t o a location in memory where thenew configuration parameter value ie etored
11
,
*/ */
*/ */ */
*/ */
Before this function can be executed, an arrayof sqlfupd structures must be allocated, the token field of each structure in this array must be set to one of the DB2 Database Manager configurationparameter tokens listed in Table 7-2 (refer to the GET DATABASE MANAGER CONFIGURATION function), and the ptrualue field must, contain a pointerto a valid locationin memory wherethe new configuration parameter value is stored. Whenthis function is executed, the new DB2 Database Manager configurationparameter values are copied fromthe memory storage areas (local variables) referred to by the ptrvalue field of each sqlfupd structure in the array to the appropriate location in theDB2 Database Manager configuration file,' provided the parameters specified can be updated.
NOTE: If a user attempts to edit aDB2 Database Manager configurntionfile using a method other thanthose provided by DB2, the database management system can become unusable.A DB2 Database ManagerConfiguration file should only be updated with one of the following methods: H The DB2 Database Director H The DB2 command-line processor(UPDATEDATABASEMANAGER CONFI(XIRATI0N and RESETDATABASEMANAGERCONFIGURATION commands) H The appropriate DB2M I finction calls (UPDATE DATABASE MANAGER CONFI@VRATION a d RESET DATABASEMANAGERCONFIGURATION)
Comments
H If an application is attached to a remote DB2 Database Manager instance (or to a
different localDB2 Database Manager instance), the current values of the DB2 Database Manager configuration file parameters for the attached server will be updated; otherwise, the current values of the local DB2 Database Manager configuration fileparameters will be updated. H Changes to DB2 Database Manager configuration file parameters only become effective whenthe modified configuration file is loaded into memory. T h i s means that for database server workstations, the DB2 Database Manager must be stopped and restarted before new values take effect (refer to the STOP DATABASE DATABASE MANAGER functions). For client workstations, new MANAGER and START values will take effect the next time a client application connects to a server workstation. Although new configuration parameter values do not take effect
P! Chapter 7: DB2 Database Manager and Database Configuration APIs
j
209
immediately, when configuration parameter values are retrieved, the most recent update values are always returned. D If an error occurs whilethis function is executing, the DB2 Database Manager configuration file willremain unchanged. D A DB2 Database Manager configuration file cannot be updated if its checksum is invalid. Checksumscan become invalid if a configuration file is changed by something other than thetools providedwith the DB2 product. If aDB2 Database Manager configuration file cannot be updated, an error message will be returned, and you must reinstall the DB2 product to correct the problem. D The values used for eachDB2 Database Manager configurationparameter differ for eachtype of configured database node (server, client, or server with remote clients). For detailed informationabout the ranges and values that can be set for each node type, refer to the IBM DB2 Universal Database Administration Guide. D For a brief descriptionabout each DB2 Database Manager configuration file parameter, refer t o the GET DATABASE MANAGER CONFIGURATION function. For detailed informationabout each DB2 database manager configuration file parameter, refer to the IBM DB2 Universal Database Administration Guide.
Connection This function can be calledat any time t o update DB2 Database Manager configRequirements uration file parameter values for the current DB2 Database Manager instance (as defined bythe value of the DB2 INSTANCE environment variable); a connection to the current DB2 Database Manager instance does not havet o be established first. In order to update DB2 Database Manager configuration fileparameter values for a DB2 Database Manager instance that is located at a remote node,an application must attach to that node before callingt h i s function. Authorization Only users with System Administrator(SYSADM) authority are allowed to execute this function call. See Also
GET DATABASE MANAGER CONFIGURATION DEFAULTS, GET DATABASE MANAGER CONFIGURATION,RESET DATABASE MANAGER CONFIGURATION
Example
Thefollowing
c++program illustrates how to use the UPDATE
DATABASE
MANAGER
CONFIGURATIONfunction to change the values of DB2 Database Manager
configuration fileparameters:
/* /* /* /* /* /* /* /* /*
*/ NAME: CH7EX3.CPP PURPOSE: Illustrate HOW To Use The Following DB2 API Functions In A C++ Program:
*/
*/
*/
*/ UPDATE DATABASE MANAQER CONFIQURATION DATABASE RESET MANAQER CONFIQURATION OTHER DB2
APIe SHOWN: QET DATABASE MANAQER CONFIQURATION
*/
*/ */ */ */
'
Part 3: Application Programming Interface Functions /* /*
*/ */
/ / Include The Appropriate #include <windows.h> #include #include <sqlutil.h, #include <sqlca.h>
Header
Piles
/ / Define The API-Class Class class APT-Clase
c
/ / Attributes public: struct sqlca sqlca;
1;
/ / Operations public : long QetDBMgrInfo()i long SetDBMgrInf 0( ) I
/ / Define The QetDBMgrInfo() Member Function long API-Class::QetDBMgrInfo() {
/ / Declare The Local ~ e m o r yVariables struct sqlfupd DBManagerInfot21 ; unsigned intN'umDB = 0; int Query~eapSize = 0 ; / / Initialize An Array Of DBS Database Manager Configuration / / Parameter Structures DBManagerInfot0l.token = SQLP-KTN~~?~MDB; DBManagetInfo[Ol .ptrvalue= (char * ) & h h r m D 8 8 DBManagerInfo 111 .token P SQLP-KTN-QUBRY-HEAP-SZ; DBManagerInfoti1.ptrvalue = (char *) &QueryHeapSize; / / Obtain The Current value Of The DBS Databasemnager / / configuration Parameters Specified
sqlfxsys(2, &DBManagerInfotOI, brsqlca); / / If The Current ValuesOf The Configuration / / Specified Were Retrieved, Display Them if (sqlca.sqlcode == SQL-RC-OK) {
1
1
cat cout cout cat
Parameters
<< uldax. number o f local databases thatcan be active l ' ; << Uat one time : << N U ~ B<< end18 << "Max.amount of memory that can be allocated for U ; << "the query heap : << QueryHeapSize << endl;
/ / Return The SQLCA Return return(sqlca.sqlcode);
U
CodeTo The
Calling
Function
Chapter 7: DB2 Database Manager and Database ConfigurationAPIs
I.'-"--"I
/ / Define The setDBMgrInfo() Member Function long API-C1ass::SetDBMgrInfoO (
/ / Declare The Local Memory Variable8 struct sqlfupd DBManagerInfotal ; unsigned intNimDB = 0; int QueryHeapSize = O t
/ / Initialize An Array Of DBI Database Manager Configuration / / Parameter Structures DBManagerInfo[O].token = SQLF-KTN-NUMDBt DBManagerInfo[O] .ptrvalue (char * ) hEFumbB; DBManagerInfo[ll.token 3 SQLF-KTN-QUERY-XiEA-SZt DBManagerInfo[ll .ptrvalueP (char *) &QueryHeapSize;
-
/ / Modify The Values Of The DB2 Database / / Configuration Parameters Specified
-
Manager
-
4; N'umDB QueryAeapSize 1024; sqlfueye(2, QDBManagerInfo[Ol. PSqlCa);
/*
*/ */
The Main Function
/* int main() (
/ / Declare The LocalM e m o r y Variables = SQL-RC-OK; rc long struct sqlca sqlca;
/ / Create An Instance Of The API-Class Class API-ClaseExample; / / Get The Current Values Of Specific DB2 / / Configuration File Parameters cout << "Before Update:" << endl; Example.GetDBMgrInfo(); rc
Database
Manager
-
/ / Change The Values Of Specific DB2Database / / Configuration File Parameters if (rc E= SQL-RC-OK) rc = Example. SetDBMgrInf o( ) i
Manager
/ / Get The Current Values Of Specific DB2 Database Manager / / Configuration File Parameters To See If They, Were Changed if (rc -E SQL-RC-OK) {
tout << endl "After Update:"
<< endl;
Part 3: Application Programming Interface Functions rc
Bxample.QetDBMgrInfo();
1 / / Reset The Values Of All DB2 Database Manager / / Parameters To Their System Default Values
Configuration
sqlfrsys(&sqlca); / / Qet The Current Values O f Specific DB2 Database Manager / / Configuration File Parameters To See If They Have Been Reset
if (rc == SQL-RC-OK)
I cout << end1 << "After Reset:" << endli () t rc = Example. QetDBMgrInfo
1 / / Return To The Operating return )(rc ;
System
1
RESET DATABASE W A G E R CONFIGURATION The RESET DATABASE MANAGER CONFIGURATION function is used to reset the values of all updatable configuration parameters (entries) in a DB2 Database Manager configuration filet o their original system defaults.
syntax Parameters
SQLCA
Includes
#include <sqlutil.h>
Description
The RESET DATABASE MANAGER CONFIGURATION function is used to reset the values of all updatable configuration parameters (entries) in a DB2 Database Manager configuration file to their system defaults. When this function is executed, all non-updatable parameters in the configuration fileremain unchanged.
Comments
A pointer to a location in memorywhere a SQLCommunications Area (SQLCA) data structure variable is stored. This variable returns either status information (ifthe function executed successfully) or error information (ifthe h c t i o n failed) to the calling application.
If an application is attached to a remote DB2 Database Manager instance (or a Merent local DB2 Database Manager instance), the values of the DB2 Database Manager configuration fileparameters for the attached server will be reset; otherwise, the values of the local DB2 Database Manager configuration file parameters will be reset. Changes to DB2 Database Manager configuration fileparameters only become
Chapter 7: DB2 Database Manager and Database Configuration APIs
j
213
.-.. "" .- .
"
effective whenthe modified configuration fileis loaded into memory. "his means that for database server workstations, the DB2 Database Manager must be stopped and restarted before the values take effect (refer to the STOP DATABASE DATABASE MANAGER functions). For client workstations,new MANAGER and START values will take effect the next time a client application connects to a server workstation. Althoughnew configuration parameter values do not take effect immediately, when configuration parameter values are retrieved, the most recent update values are always returned. If an error occurs whilethis function is executing,the DB2 Database Manager configuration file will remain unchanged. A DB2 Database Manager configuration file cannot be updated if its checksum is invalid. Checksumscan become invalid if a configuration fileis changed by something other than thetools providedwith the DB2 product. If a DB2 Database Manager configuration file cannot be reset, an error message will bereturned, and you must reinstall the DB2 product to correct the problem. H For a brief descriptionabout each DB2 Database Manager configuration file parameter, refer to the GET DATABASE MANAGER CONFIGURATION function. For detailed informationabout each DB2 Database Manager configuration file parameter, refer to the IBM DB2 Universal Database Administration Guide.
Connection T h i s function can be called at any time to reset DB2 Database Manager configuration Requirements file parameter values for the current DB2 Database Manager instance (as defined by the value of the DB2INSTANCE environment variable);a connection to the current DB2 Database Manager instance does not haveto be established first. To reset DB2 Database Manager configuration file parameter values for a DB2 Database Manager instance that is located at a remote node,an application must attach to that node before calling this function. .
Authorization Only users with System Administrator (SYSADM) authority are allowed to execute. this function call.
see Also
GET DATABASE MANAGER CONFIGURATION DEFAULTS, GET DATABASE MANAGER CONFIGURATION, UPDATE DATABASE MANAGER CONFIGURATION
Example
See the example provided forthe UPDATE function on page 209.
DATABASE
MANAGER
CONFIGURATION
GET DATABASE CONFIGURATION The GET DATABASE CONFIGURATION function is used to retrieve the current value of one or more configurationparameters (entries) in a specific database configuration file.
syntax
SQL-API-RC SQL-AFT-FN
eqlfxdb
(char
*DBAliae,
pointer to a location in memo^ where the alias name of the database that parameter values are to be retrieved for is stored. The number of database confi~rationparameter values to retrieve. is value identi~esthe number of elements contained in the array of s ~ Z ~ sut ~p c~t u r e specified s in the Ite ointer to an array of s ~ Z ~ su p ctures ~ that s p e c i which ~ p a r ~ e t evalues r are to be retrieved.
s ) data
s t ~ c t variable ~ e is store
inclu ION function is
used to retrieve the current value
value of one or more database c o n ~ ~ r a t i paramet on efiied in s ~ Z u t ~ as Z . follows: ~
ch~r
*
to r e t ~ e v ethe c u ~ e n t s ~ Z structure ~ ~ p is~
*/ */ */ i
"I
*/ */ 3;
e
ter
s DB2 Database Con~gurationParameters (Continued)
Description
Parameter Name
%ken
C Data Type
value, efore this h c t i o n can be executed, an array of s ~ Z ~ u ps dt ~ c t u r e must s be allocated, the t o ~ e nfield of each structure in this array must be set to one of the database confi~rationparameter tokens listed in Table 7-3, and the ptruaZ~efield must contain a pointer to a valid location in memo^ where the c o n f i ~ a t i o n parameter value retrieved is to be stored. 'When this function is executed, the current value (setting) of each database confi~rationparameter specified is placed in the ~ e m o r ystorage areas (local variables) referred to by the ptruaZue field of each s ~ Z ~ structure up~ in the array. tries in the database confi~rationfile that do not have a correspon~ngtoken e listed in Table 7-3 are not accessible to an application. application that calls this function is responsible for allocating sufficient m e ~ for o each ~ data value retrieved. If an error occurs while this function is executing, the database confi~ration information returned will be invalid. If an error occurs because the database confi~rationfile has been c o ~ p t e dan , error message will be returned and you st restore the database from a good backup image to correct the problem. r detailed i n f o ~ a t i o nabout each database confi~rationfile parameter, refer to the ~ l Dl332 ~niversaZ ~ Data~aseA d ~ i n i s t r a t i oGuide. ~ DB2 Database Con~gurationParameters
Parameter Name app-ctl-heap-sz
Dewription
%ken
C Data Type
Specifies the maximum size, in 4KB pages, of the application control heap. "he application control heap is required in order to share information among agents working on behalf of the same application at a node in an MPP or
SQL~-DBTN-APP-CTLKEXLP-SZ
unsigned int
applheapsz
Specifies the size, in pages, of the application heap that is available for each individual agent. Memory to be used for caching packages (specified by the ~ c ~ c u c ~ parameter) esz is allocated from the application heap.
asdm-m~tclass
Specifies how the server should manage the backup versions or archive copies of objects being backed up. M e n pedorming any ASDM backup, the DB2 atabase Manager uses this parameter
unsigned int
char[301 CLASS
Part 3: Application Programming Interface Functions 1rable 7-3 DB2 Database Configuration Parameters (Continued)
~~
~
r to pass the appropriate management class to ASDM. asdm-nodename
Specifies the node name that is associated withthe ASDM product. This name is used when restoring databases that were backedup to ASDM from another node.
SQLF-DBTN-ASDMNODENAME
chad641
asdmowner
Specifies the owner name that is associated with the ASDM product.
SQLF-DBTN-ASDMOWNER
char[64]
adsmgassword
Specifies the password that isassociated with the ADSM product.
SQLF-DBTN-ADSMPASSWORD
char[64]
autorestart
Specifies whether the DB2 Database SQLF-DBTN-AUTOa RESTART Manager can automatically issue RESTART DATABASE command when a connection is attempted, if the last database connection was disrupted,or if the database was not closed normally during the previous session. If this parameter is set to ON,the databaseis restarted automatically. Ifthis parameter is setto OFF, the database mustbe restarted manually.
unsigned int
avgappls
specifies the average number of active SQLF-DBTN-AV&APPLS applications that will accessthe database at a given time.This parameter is used by the SQL optimizer to help estimate how much bufferpool memory will be available for the chosen accessplan at application run time.
unsigned int
backup-pending
Specifies whether a database needs to be backed up. If this parameter is set to NO, the databaseis in a usable state.If this parameter is set to Y E S , an OFFLINE backup must be performed before the database canbe used.This parameter is not updatable.
SQLF-DBTN-BACXUPPENDING
unsigned int
buffpage
Specifies the size, in pages, of the buffer pool that stores and manipulates data read from the database.
SQLF-DBTN-BUFF-PAQE
unsigned long
catalogcache-sz
Specifies the size, in pages, of the internal catalogcache (allocated from the dbheup) that i s used by the SQL precompiler to hold the packed descriptors for commonly referenced objects such as tables andconstraints.
SQLF-DBTNCATALOGCACREJ3Z
long
11
!
Chapter 7: DB2 Database Manager and Database Configuration APIs
:
Table 7-3
"l
2 17
DB2DatabaseConfigurationParameters(Continued)
chngpgs-thresh Specifies
the level (percentage)of pages that must changed be before the asynchronous page cleaners will be started (if they are not alreadyactive).
SQLF-DBTN-CHNGPGSTHRESH
unsigned int
codepage
Specifies the code page of the database. This parameter is not updatable.
SQLF-DBTN-CODEPAGE
unsigned int
codeset
Specifies the code set of the database. This parameter is not updatable.
SQLF-DBTN-CODESET
char191
collate-info
Specifies the collate sequence that is used by thedatabasewhenmaking character comparisons. This parameter is not updatable.
SQLF-DBTN-COLLATE-
char12601
INFO
Specifies all databaseattributes in a SQLF-DBTN-DETS single value. You can manipulate the bits of this unsigned integer value or use the this value individual tokens making up (see the footnote formore information).
unsigned int
the Enables or disablesdatabase protect attribute (OS12 only).
SQLF-DBTl-COPYPROTECT
unsigned int
Specifies the country code of thedatabase. This parameter is not updatable.
SQLF-DBTN-COUNTRY
unsigned int
database-consistent
Specifies whether thedatabase is in a consistent state. If this parameter is set to Y E S , all transactions havebeen committed or rolled back,and the datain the database is consistent. If this parameter is set to NO, a transaction or some other task ispending on the database, and the data in the database is not consistent at this time.T h i s parameter is not updatable.
SQLF-DBTNCONSISTENT
unsigned int
database-level
Specifies the release level of the DB2 Database Manager that can be used to access the database. This parameter is not updatable.
SQLF-DBTN-DATABASELEVEL
unsigned int
dbheap
SQLF-DBTN-DBHEAP Specifies the size, in pages, of thedatabase heapthat holds control information on all open cursors that are accessing the database. Both log buffersand catalog cache buffersare allocated fromthe database heap.
unsigned int
Specifies the default valuefor the H T DEGREE Special register and the DEGREE bind option.
long
copyprotect
copy-
SQLF-DBTN-DFTDEGREE
1
Part 3 Application Programming Interface Functions Table 7-3 DB2 Database Configuration Parameters (Continued)
t
Specifies the default extent size (in pages) of all tablespaces.
SQLF-DBTN-DFTEXTENT-SZ
unsigned long
Specifies the default numberof load recovery sessions that can be used during the recovery of a table load operation.This parameter is only applicable if roll-forward recoveryis enabled.
SQLF-DBTN-DFTLOADREC-SES
int
Specifies the default prefetchsize (in pages) of all table spaces.
SQLF-DBTN-DFTPREFgTCH-SZ
int
Specifies the default query optimization SQLF-DBTN-DFTclass that is to be used to direct the SQL QWRYOPT optimizer to use different degrees of optimization whencompiling SQL queries.
long
df-sqlmathwarn
Specifies the default valuethat determines whether arithmetic errors and retrieval conversion problemsare treated as errors or warnings during SQL statement compilation.
SQLF-DBTN-DFTSQLMATHWARN
int
dir-obj-name
Specifies the object name in theDCE name spacethat represents a DB2 Database Manager instance(or database) inthe directory.
SQLF-DBTN-DIR-OBJNAME
chrn[2SS]
discover-db
Specifies whether or not information about a database is returned to a client when a discovery request is issued against theserver.
SQLF-DBTNDISCOVER
unsigned int
dlchktime
Specifies the time intervalfrequency (in milliseconds) a t which the DB2 Database Manageris to check fordeadlocks among all the applications connected to a database.
SQLF-DBTN-DLCHKTIME
unsignedlong
dl-expint
Specifies the i n t e ~ aof l time, in seconds, for whicha DB2 File Manager file access token generatedis valid.
SQLF-DB'IW-DL-EXPINT
long
dl-num-backup
Specifies the number of most recent database backupsthat theDB2 File Manager is to keep backup information for.
SQLF-DBTN-DLJKI"
unsigned int
BACKUP
dl-num-copies
Specifies the number of additional copies SQLF-DBTN-DL-NU" COPIES of a filethat are to be made inthe archive server (such as an ASDM server) when a file is linked to the database.
unsigned int
dl-time-drop
Specifies the interval of time (in days)
unsigned int
SQLF-DBTN-DL-TIME-
!
l
! l
i 2 19
Chapter 7: DB2 Database Manager and Database Configuration APIs Table 7-3 DB2 Database Configuration Parameters (Continued)
DROP that files are to be retained on an archive server (suchas anASDM server) after a DROP TABLE, DROP TABLESPACE, or DROP DATABASE SQL statement is issued.
estore-segsz
Specifies the number of pages that are to be used in each extended memory segment of the database.
indexrec
Specifies when invalid indexes are to be recreated. This parameter can be set to
SQLF-DBTN-INDEXREC
unsigned int
SYSTEM (ACCESS), SYSTEM (RESTART), ACCESS,or RESTART.The default setting is SYSTEM, which specifiesthat thevalue
of the DB2 Database Manager configuration parameteri n h r e c is to be used. indexsort
Specifies whether or not index key sorting is to occur during index creation.
SQLF-DBTN-INDEXSORT
unsigned int
locklist
Specifies the maximum storage (in pages) that is to be allocated to the lock list.
SQLF-DBTN-LOCKLIST
unsigned int
locktimeout
Specifies the number of seconds an application will wait to obtain alock before timing out.
SQLF-DBTNLOCKTIMEOUT
int
logbufsz
Specifies the number of pages used to buffer logrecords before they are written to disk.This buffer is allocated from the databaseheap.
logfilsiz
SQLF-DBTN-LOQFIL-SI2 Specifies the amount of disk storage space (in pages) that is to be allocated to log files that areused for data recovery. This parameter defines the size of each primary andsecondary log file.
unsigned int
loghead
Specifies the name of the log filethat contains the head of the active log. The next log record written will start at the head of the active log file.This parameter is not updatable.
charIl21
logpath
Specifies the current pathused to access log files.This parameter is not updatable.
SQLP-DBTN-LWPATH
char12421
logprimary
Specifies the number o f primary log files that c m be used for database recovery.
SQLF-DBTNLOQPRIMARY
unsigned int
logretain
Specifies whether active logfiles are to be retained as archived log files form e
SQLF-DBTN-LOQRETAIN
unsigned int
Part 3 Application Programming Interface Functions Table 7-3 DB2 Database Configuration Parameters (Continued) -7%-
Parameter
Descripl in roll-forward recovery(also known as log retention logging).
logretain-stab
Specifies whether or not log files are retained for use in roll-foward recovery. This parameter is not updatable.
SQLF-DBTN-LOGRETAIN-STATUS
unsigned int
logsecond
Specifies the number of secondary log files that are to be used for database recovery.
SQLF-DBTN-LOGSECOND
unsigned int
maxappls
Specifies the maximum number of application programs (both local and remote) that can be connected to the database at one time.
SQLP-DBTN"AXJiPPLS
unsigned int
maxfilop
Specifies the maximum number of database files an application program can haveopen at one time.
SQLF-DBTN_MAXFILOP
unsigned int
maxlocks
Specifies the maximum percentage of the lock list that any one application program canuse.
SQLP-DBTN-~XLOCKS
unsigned int
mincommit
Specifies the number of SQL commits that can be groupedfor the database. You can achieve better control of YO and log activity by groupingSQL commits.
SQLP-DBTNJIINCOKKIT
unsigned int
multipage-doc
Specifies whether multipagefile allocation is to be used to improve insert performance when working with SMS table spaces. This parameter is not updatable.
SQLP-DBTNMULTIPAOE_AGLOC
unsigned int
newlogpath
Specifies an alternate pathto use when SQLF-DBTNsearching for recovery log files. Because NEWLOGPATH this parameter accepts only fully qualified directories, you must specify the absolute path.
char12421
nextactive
Specifies the name of the next recovery log file to be used for logging. "his parameter is not updatable.
SQLF-DBTNL NEXTACTIVE
char[l2]
num-estore-segs
Specifies the number of extended storage segments that are available for use by the database.
SQLP-DBTN-NIMESTORE-SEOS
long
num-fkqvalues
Specifies the number of most-frequent used valuesthat will be collected when the WITH DISTRIBUTION option is specified in the RUN STATISTICS function (or command).
SQLF-DBTN-NUMFREQVALVES
unsigned int
1 22 1 l
Chapter 7: DB2 DatabaseManager and Database Configuration APIs
."
"
3
numjocleaners
Specifies the numberof asynchronous page cleaners for the database.
SQLF-DBTN-NlJ" IOCLEANERS
unsigned int
num-ioservers
Specifies the number of I/O servers for the database. I/O servers are used on behalf of database agentsto perform prefetch and asynchronous I/O that is needed by utilities such as BACKUP and
SQLF-DBTN-NUMIOSERVERS
unsigned int
RESTORE.
num-quantiles
Specifies the number of quantiles (values in a column that satisfy a RANGE predicate) that will be collected option when the WITH DISTRIBUTION is specified in the RUN STATISTICS function or command.
SQLF-DBTNJl"QUANTILES
unsigned int
numsegs
Specifies the number of containers that were created withinthe default SMS table spaces. This parameter is not updatable.
SQLF-DBTN-NUMSEGS
unsigned int
pckcachesz
Specifies the amount of application heap memory that is to be used for caching packages.
rec-his-retentn
Specifies the number of days that historical information on backups is to be retained.
SQLF-DBTN-MC-HISRETENTN
int
release
Specifies the release level of the database configuration file.This parameter is not updatable.
SQLF-DBTN-RELEASE
unsigned int
Specifies whether the database hasa
SQLF-DBTN-RESTOREPENDING
unsigned int
rollfwdgending
SQLF-DBTN-ROLLPWDSpecifies whether a roll-forward PENDING recovery procedureneeds to be performed beforethe databasecan be used. This parameter can be set to NO (neither the database nor any of ita table spaces are in roll-forward pending state), DATABASE (the database needsto be rolled forward beforeit can be used), or TABLESPACES (one or more table spaces to be rolled forin the database needs ward). T h i s parameter is not updatable.
unsigned int
seqdetect
Specifies whether sequential detection for the database is enabled or disabled.
SQLF-DBTN-SEQDETECT
unsigned int
SORmaX
specifies the maximum percentage of log filespace to be consumed beforea
SQLF-DBTN-SOFTMAX
unsigned int
restore-pending
RESTORE PENDING Status.
unsigned int
! I
A
I
Part 3: Application Programming Interface Functions Table 7-3
DB2DatabaseConfigurationParameters(Continued)
soft checkpoint is taken.
sortheap
Specifies the number of private memory pages that are to be available for each sort operation in anapplication program.
stat-heap-sz
Specifies the maximum size of the heap space (in pages) that is to be used for creating andcollecting all table statistics when distribution statisticsare being gathered.
SQLF-DBTN-SORT"
unsigned long
SQLF-DBTN-STAT-
unsigned long
mAP-92
stmtheap
Specifies the heapsize (in pages) that is to be used to compile SQL statements.
SQLF-DBTN-STMTEEAP
unsigned int
territory
Specifies the territoryof the database. This parameter is not updatable.
SQLF-DBTN-TERRITORY
chad61
userexit
Specifies whether a user exit function for archiving or retrieving log filescan be called the next time the databaseL opened. If this parameter is set to OFF, a user exit function cannotbe called.If this parameter is set to ON, a user exit function can be called.
SQLF-DBTN-USER-EXIT
unsigned int
user-exit-status
Specifies whether a user exit function can be calledto store archivelog files. If this parameter is set to OFF, a user exit function cannot be calledto store archive log files. Ifthis parameter is set to ON, a user exit function can be called to store archive log files.This parameter is not updatable.
SQLF-DBTN-USEREXIT-STATUS
unsigned int
util-heap-sz
Specifies the maximum amount of shared memory that can be used simultaneously by the Backup, Restore,and Load utilities.
SQLF-DBTN-UTIL-
unsigned long
none
"S2
a single SQLF-DBTN-INTFLAGS Specifies the database status in value. You may examinethe bitsof this unsigned integer value, or you can use the individual tokensthat make up this value (see footnote for more information).
unsigned int
The bits of the SQLF-DBTN-DETS parameter value indicate the database attribute settings. The individual bits making upthis composite parameter valueare the following: Bit 1 (xxxxxxxl): copyprotect Bit 2 (xxxx xxlx): logretain userexit : Bit 3 (xxxxh)
j i
Chapter 7: DB2 DatabaseManager and DatabaseConfiguration ApIs
1 223 -i
"1
.-
Bit 4 (xxxxh) autorestart : The bitsof the SQLF-DBTN-INTFLAOS parameter value indicate database status. The individual bits making up this composite parameter valueare: Bit 1(xxxx d): database-consistent Bit 3 (xxxx xlxx): backup-pending Bit 4(xxxxIrwr):rollfwdgending Bit 6 (xxxlxxxx) logretain-status Bit 6 ( x x l x xxxx): user-exi-status Bit 7 (xlxx xxxx): tablespace roll-forward pending The combination of bits 4 and7 make upthe rollfbdgendingparameter. If the rollfwd-pending bit (4) is on, the database needsto be rolled forward (rollfwd-pending= DATABASE). If the rollfwdgending bit (4) is off ancl bit 7 is on, oneor more table spaces needto be rolled forward(rollfwdgending = TABLESPACES).If both bits are off, neither the database nor any of its table spaces needto be rolled forward(rollhd-pending = NO). Adapted from IBWs OB2 Universal DatabaseAPI Reference,Tables 44 and 45, p. 422 to 424.
Connection This function can only be called if a connection to a DB2 Database Manager instance Requirements exists. In order to retrieve database configuration fileparameter values for a DB2 database located at a remote node,an application must attachto that node. If necessary, a temporary connectionis established by this function during its execution.
Authorization No authorization is required to execute this function c a l l . See Also
Example
GET DATABASE CONFIGURATION DEFAULTS, RESET DATABASE CONFIGURATION, UPDATE DATABASE CONFIGURATION
c++program illustrates how to use the GET DATABASE CONFIGURATION function to retrieve database configuration fileparameter values for
Thefollowing
the SAMPLE database: /*
/*
/* /* /*
/* /*
NAME: CH7EX4 .CPP PURPOSE: Illustrate How To Use The Following DB2 API Function ~n A C++ Program:
CONFIOURATION GET DATABASE
/ / Include The Appropriate Header Files #include <windows.h> #include #include <sqlutil.h> #include <splca.h> / / Define The API-Class Class class API-Class
I
*/ */ */
*/
*/ */ */
Part 3: Application Programming Interface Functions / / Attributes public: struct sqlca sqlca; / / Operations public: long GetDBaseInfo () ;
1; / / Define The GetDBaseInfoO Member Function long API_Class::~tDBaseInfo()
c / / Declare The Local Memory Variables struct sqlfupd DBaseInfo[Q] ; unsigned intAutoRestart = 0; unsigned int AVgAppliCatiOnS = 0 ; unsigned int DeadlockChkTime = 0;
/ / Initialize An Array Of SAMPLE Database Configuration / / Parameter Structures DBaseInf0 [ 01 token = SQLF-DBTN-AUTO-RESTART; DBaseInfo[O] .ptrvalue= (char *) &AutoRestart; DBaseInfo[l] .token P SQLF-DBTN-AVG-APPLS; DBaseInfo[l].ptrvalue = (char * ) MvgApplications; DBaseInfo[a] .token = SQLF-DBTN-DLCWTIME; DBaseInfO[2].ptrvalue E (char * ) hDeadlockChkTime;
.
/ / Obtain The Current Value Of The SAMPLE Database / / Configuration Parameters Specified sqlfxdb("SAMPLE", 3, &DBaseInfo[Ol, &eqlca); / / If
The Current values Of The Configuration Parameters
/i Specified Were Retrieved, Display Them if (sqlca.sglcode == SQL-RC-OK)
c cout << "Automatically restart the database if necessary : ##; if (AutoRestart -= 0) cout << 'WO" << endl; else cout << '9Yesn << endl; : "; cout << "Avg. number of active applications allowed cout << AvgApplications << endl; : "; cout << "Time interval between deadlock checks cout << DeadlockChkTime << milliseconds" << endl; I'
1 / / Return The SQLCA Return return(sqlca.sq1code); ,
Code
To
The
Calling
Function
1
Main
/* /* /*
The
int main()
*/
*/ */
l
Chapter 7: DB2 DatabaseManager and DatabaseConfiguration APIs / / Declare The Local P SQL-RC-OK; long rc
Memory
i'
1
225
I
Variables
/ / Create An Instance Of The API-Class Class API-ClassExample; / / Get The Current ValuesOf Specific SAMPLE / / Configuration File Parameters
rc = Example.
Database
QetDBaseInf 0();
/ / Return TO The return(rc) ;
Operating
System
1
m m GET DATABASE CONFIGURATION DEFAULTS
Purpose
The GET DATABASE CONFIGURATION DEFAULTS function is used to retrieve the system default values for oneor more configurationparameters (entries) in a database configuration file.
syntax
SQL-API-RC SQL-API-FN
Parameters
DBAlias Numltems
ItemList
SQLCA
Sqlfddb (char unsigned short struct sqlfupd structeglca
*DBAlias, NbmItems,
*rtemList,
*SPLcA);
A pointer to a location in memorywhere the alias name of the database that parameter values are to be retrieved foris stored. "he number of database configuration parameter default values to retrieve. This value identifiesthe number of elements contained in the arrayof sqlfupd structures specified in theItemList parameter. A pointer to an array of sqlfipd structures that specifywhich database configuration parameter system default values are to be retrieved. A pointer t o alocation in memorywhere a SQL Communications Area (SQLCA)data structure variable is stored. This variable returns either status information (if the function executed successfully)or error information (ifthe function failed) to the calling application.
Includes
#include <sqlutil.h>
Description
"he GET DATABASE CONFIGURATION DEFAULTS function is used to retrieve the system default values of one or more configurationparameters (entries) in a database configuration file.This function uses an array of special structures (sqlfupd)to retrieve the system default values for one or more database configuration parameters. Refer to the GET DATABASE CONFIGURATION function for a detailed
Part 3: Application Programming Interface Functions description of this structureand for more information about the database configuration parameters available. Before this function can be executed, an arrayof sqlfipd structures must be allocated, the token field of each structure inthis array must be set to one of the database configuration parameter tokens listed in Table 7-3 (refer to the GET function), and the ptrvalue field must contain a pointer DATABASE CONFIGURATION to a valid locationin memory wherethe configuration parameter value retrieved i s to be stored. Whenthis function is executed, the system default value for eachdatabase configuration parameter specified is placed in the memory storage areas (local variables) referred to by the ptrvalue field of each sqlfipd structure in thearray.
Comments
H The application that calls this function is responsible for allocating sufficient
memory for eachdata value retrieved. H The current value of a non-updatable configurationparameter is returned as that configuration parameter's systemdefault value. H If an error occurs whilethis function is executing, the database configuration information returned will be invalid. Ifan error occurs becausethe database configuration filehas been corrupted,an error message willbe returned, and you must restore the database from a good backup imageto correct the problem. U For a brief descriptionabout each database configuration fileparameter, refer to the GET DATABASE CONFIGURATION function. For detailed information about each database configuration fileparameter, refer to the IBM DB2 Universal Database Administration Guide.
Connection This function can only be called if a connection to a DB2 Database Manager instance Requirements exists. In order to retrieve default database configuration fileparameter values for a DB2 database located at a remote node,an application must attach to that node. If necessary, a temporary connection is established by this function whileit executes. Authorization No authorization is required to execute this function call.
see Also
RESET DATABASE CONFIGURATION, UPDATE DATABASE CONFIGURATION, GET DATABASE CONFIGURATION
Example
Thefollowing
c++program illustrates how to use the GET
CONFIGURATION
DATABASE DEFAULTS function to retrieve the system defaultdatabase
configuration fileparameter values for the SAMPLE database:
.CPP
/* /* /* /* /* /* /* /*
NAME:
CH7EX5 PURPOSE: Illustrate H o w To Wee The Following DB2 API Function In A C++ Program: GET
DATABASE
CONFIGURATION
DEFAULTS
*/ */ */ */ */ */ */ */
Chapter 7: DB2 Database Manager and Database Configuration
I1
APIs
1 ~
227
/ / Include The Appropriate HeaUer Files #include <windows.h> #include #include <eqlutil.h> #include <sqlca.h> / / Define The API-Class Class class API-Class i / / Attributes public : struct sqlca sqlca;
/ / Define The QetDBaseInfo() Member Function long API-Class::GetDBaseInfo() {
/ / Declare The Local Memory Variables struct sqlfupd DBaseInfo[4]; unsignedintAutoRestart = 0; unsignedintAvgAppliCatiOne = 0; unsignedint DeadlockChkTime = 0;
/ / Initialize An Array Of SAMPLE Database Configuration / / Parameter Structures DBaseInfo[O].token a SQLF-DBTN-AUTO-RESTART; DBaseInfo[O] .ptrvalue= (char * ) &AutoRestart; DBaseInfo[ll.token P SQLF-DBTN-AVQ-APPLS; DBaseInfo[l] .ptrvalue= (char * ) &AvgApplications; DBaseInfo[2].token P SQLF-DBTN-DLCHKTIME; DBaseInfo[2] .ptrvalue= (char * ) hDeadlockChkTime; / / Obtain The System Default Value Of The / / Configuration Parameters Specified SqlfCldb("SAMPLE", 3, &DBaseInfo[O], brsqlca);
SAMPLE Database
/ / If The System Default Values Of The Configuration / / specified Were Retrieved. Display Them
Parameters
if (sqlca.sqlcode == SQL-RC-OK) {
1
tout << dnAutomatically restart the Uatabase if necessary : "; if (AutoRestart =m 0 ) cout << "NO" << endl; else cout#*Yesn << endl; cout << "Avg. number of active applications allowed : "; cout << AvgApplications << endl; cout << "Time interval between Ueadlock checks : 'a; cout << DeadlockChkTime << at millisecondsn << endl;
I
Part 3 Application Programming Interface Functions / / Return TheSQLCA Return return(sqlca.eqlco8e);
CodeTo The
Calling
Function
1
Main
/* /* /*
*/ */ */
The
int
main( ) / / Declare The LocalMemory Variables long rc a SQL-RC-OK; / / Create An Instance Of The API-Class Class API-ClassExample;
/ / Get The System Default Values Of Specific SAMPLE / / Configuration File Parameters rc = Example.GetDBaseInfo0;
1
/ / Return To The return(rc) ;
Operating
Database
System
BM M UPDATEDATABASE
CONFIGURATION Purpose
The UPDATE DATABASE CONFI~URATIONfunction is used to change the value of one or more parameters (entries) in a specific database configuration file.
syntax
SQL-API-RC SQL-API-FN
Parameters
DBAZius
A pointer to a location in memorywhere the alias name of the database that parameter values are to be updated for is stored.
NumItems
The number of database configuration parameters values to update. This value identifies the number of elements contained the array of sqlfupd structures specified in theItemList parameter.
ItemList
A pointer t o an array of sqlfupd structures that specifywhich database configuration parameter values are to be updated, along with their corresponding values.
SQLCA
A pointer to a location in memory wherean SQL Communications Area (SQLCA)data structure variable is stored. This variable returns
sqlfudb (char
*DBAliae, unsigned short mnutema, struct sqlfupcl *ItBmCiSt, struct sqlca *SQLCA);
Chapter 7: DB2 Database Manager and Database Configuration APIs
I
j 1 2 29
I
either status information (if the function executed successfully) or error information (if the function failed)to the calling application.
Includes
#include <sglutil.h>
Description
The UPDATE DATABASE CONFIGURATION function is used to change the value of one or more configurationparameters (entries) in a specificdatabase configuration file. This function uses an arrayof special structures (sqlfupd)to update the value of one or moredatabase configuration parameters. The sqlfupd structure isdefined in sqluti1.h as follows: etruct sqlfupd
I uneigned short token:
*ptrvalue;
char
/* /* /* /* /* /* /*
A
token that identifies the configuration parameter whoee value ie to be updated A pointer to a location in memory where the new configuration parameter value ie etored
*/
*/ */ */ */
*/ */
Before this function can be executed,an array of sqlfupd structures mustbe allocated, the token field of each structure in this arraymust be set to one of the database configuration parameter tokens listed in Table 7-3 (refer to the GET function), and the ptrvalue field of each structure must DATABASE CONFIGURATION contain a pointerto a valid locationin memory wherethe new configuration parameter value is stored. When this function is executed, the new database configuration parameter values are copied fromthe memory storage areas (local variables) referred to by the ptroalue field of each sqlfupd structure in the arrayto the appropriate location in the database configuration file, providedthe parameters specified can be updated.
NOTE:If a user attempts to edit a database configuration file using a method other than those provided by DB2, the database canbecome unusable.A database configuration file should only be updated with one of the following methods: H The DB2 Database Director The DB2 command-lineprocessor (UPDATE DATABASE CONFIOURATION and RESET DATABASE CONFIGURATION commands) The appropriate DB2 API function calk (UPDATE DATABASE CONFIQURATION and RESET DATABASE CONFIGURATION function calls)
Comments
Changes to database configuration file parameters only become effective when the modified configuration fileis loaded into memory. This process will not occuruntil all applications are disconnected fromthe database and a new connectionis
j r
230 j j
Part 3 Application Programming Interface Functions established (whenthe firstnew connection to the database is established, the new values willtake effect). Although new configurationparameter values do not take effect immediately, when configuration parameter values are retrieved, the most recent update values are always returned. If an error occurs whilethis function is executing, the database configuration file will remain unchanged. A database configuration file cannotbe updated ifits checksum is invalid. Checksums can become invalid aifconfiguration fileis changed by something other than the tools provided withthe DB2 product. If a database configuration file cannot be updated, an error message is returned,and you must restore the database from a good backup imaget o correct the problem. The values used for each database configuration parameter differ for each type of configured database node (server, client,or server with remote clients). For detailed information aboutthe ranges and values that can be set for each node type,refer to the IBM DB2 Universal Database Administration Guide. For a brief description about each database configuration file parameter, refer to the GET DATABASE CONFIGURATION function. For detailed information about each database configuration fileparameter, refer to the IBM DB2 Universal Database Administration Guide.
Connection T h i s function can onlybe called ifa connection t o a DB2 Database Manager instance Requirements exists. In order to update database configuration fileparameter values fora DB2 database located at a remote node,the application must attachto that node. If necessary, a temporary connectionis established by this function whileit executes. Authorization Only users with System Administrator(SYSADM) authority, System Control (SYSCTRLJ authority, or System Maintenance(SYSMAINT)authority can execute this function call. Restrictions
see Also Example
There are no restrictions associated with this function call. GET DATABASE CONFIGURATION DEFAULTS, RESET DATABASE CONFIGURATION
GET
DATABASE
CONFIGURATION,
The followingc++ program illustrates how to use the UPDATE DATABASE CONFIGURATION function to change the values of database configuration file parameters: l*
/* /*
/*
~~
NAME:
CH7EXC.CPP PURPOSE:. Illustrate H o w To Dee The Following DB2 API Functione fn A C++ Program:
/* /* DATABASE CONFIOURATION /* DATABASE
UPDATE RESET
CONFI(3uRATION
* J
*/
*/ */ */ */ */
' l
Chapter 7: DB2 Database Manager and Database Configuration M I S
!
I ,
/* /* /*
!
j 23 1
-__ */
OTHER DB2 APIsSHOWN: DATABASE GETCONFIGURATION
*/
*/
/*
*/
/ / Include The Appropriate Header Files #include <windows.h> #include #include <eqlutil.h> #include <eqlca.h> / / Define The API-Class Class class APT-Class {
/ / Attributes public: struct sqlca sqlca;
1;
/ / operations public : long GetDBaseInfo(); long SetDBaseInfo () ;
/ / Define The QetDBaseInfoO Member Function long API-Class::GetDBaeeInfo() {
/ / Declare The Local Memory Variables struct eqlfupd DBaseInfo[41; unsigned intAutoRestart = 0; unsigned int DeadlockChkTime I 0; / / Initialize An Array Of SAMPLE / / Parameter Structures
Database Configuration
DBaseInfo [ O 1 .token .I SQLF-DBTN-A~O-REST?LRT; DBaseInfo[O] .ptrvalue= (char *) WiutoRestart; DBaseInfo[l] .token = SQLF-DBTN-DLCHKTIME; DBaseInfo[ll.ptrvalue = (char *) CiDeadlockChkTime; / / Obtain The Current Value Of The SAMPLE / / Configuration Parameters Specified sqlfxdb("SAMPLE", 2, &DBaseInfo[O], hsqlca);
Database
/ / If The Current Values Of The Configuration / / Specified Were Retrieved, Display Them if (sqlca.eq1code == SQL-RC-OK)
Parameters
I cout << nAutomatically restartthe database if necessary : if (AutoRestart =I 0) cout << #'Non << endl; else cout << 'VesW << end11 cout << "Time interval between deadlock checks :
";
p I
!
Part 3 Application Programming Interface Functions
/ / Define The SetDBaseInfoO Member Function long API-Class::SetDBaseInfo() / / Declare The Local Memory Variables struct sqlfupd DBaseInfo[11; unsigned intAutoRestart = 0; unsigned int DeadlockChkTime = 0; / / Initialize An Atray Of SAMPLE / / Parameter Structures
Database
Configuration
DBaseInfo[Ol.token = SQLF-DBTN-AUTC-RESTART; DBaseInfo[OI .ptrvalue= (char * ) &AutoRestart; I SQLF-DBTN-DWHRTIME; DBaseInfo[l] .token DBaseInfo[ll.ptrvalue = (char * ) &DeadlockChkTime; / / Modify The Values Of The Specified SAMPLE Database / / Configuration Parameters AutoRestart = 08 DeadlockChkTime P 8000; sqlfu&('"SAMPLE", 2, &DBaseInfo[Ol, &sqlca); / / Return The SQLCA Return return(eqlca.sqlcode);
CodeTo The Calling
Function
1
*/
/*
/* The Main Function
*/
.
/*
*/
int main0 / / Declare The LocalMemory Variables = SQL-RC-OK; rc long etruct sqlca sqlca;
/ / Create An Instance Of The API-Class Class API-ClassExample; / / Get The Current Values Of Specific SAMPLE / / Configuration File Parameters
Database
cout << "Before Update:" << endl; rc = Example.OetDBaseInfo(); / / Change The Values Of Specific SAMPLE / / Configuration File Parameters if (rc == SQL-RC-OK) rc = Example. SetDBaseInfo( ) ;
Database
Isa ,
I
.. ,,
Chapter 7: DB2 Database Manager and Database ConfigurationAPIs
,
.
1 233
/ / Get The Current ValuesOf Specific SAMPLE Database / / Configuration File Parameters To See If They Were Changed if (rc == SQL-RC-OK) {
tout << endl << "After Update:tr<< endlj rc = Example.GetDBaseInfo()j
1 / / Reset The Values Of All SAMPLE Database Configuration / / Parameters To Their System Default Values sqlf rdb ( '%AMPLE", brsqlca)f / / Get The Current Values Of Specific SAMPLE Database / / Configuration File Parameters To See If They Have Been if (rc p= SQL-RC-OK)
Reset
{
cout << end1 << UAfter Reset:" << endl; rc P Example.GetDBaseInfo():
1 / / Return To The return )(rc j
Operating
System
1
m m RESET DATABASE CONFIGURATION Purpose
The RESET DATABASE CONFIGURATION function is used to reset the values of all updatable configuration Parameters (entries) ina database configuration fileto their original system defaults.
syntax
SQL-API-RC SQL-API-FN sqlf
Parameters
DBAlias SQLCA
r&
(char *DBAliae, struct sqlca *SQLCA);
A pointer to a location in memorywhere the alias name of the database that parameter values are to be reset for is stored. A pointer to a location in memorywhere a SQL Communications Area (SQLCA)data structure variable is stored. "his variable returns either status information (if the function executed successfully) or error information (if the function failed)to the calling application.
Includes
#include <eglutil.h>
Description
The RESET DATABASE CONFIGURATION function is used to reset thevalues of all updatable configurationparameters (entries) ina database configuration fileto their original system defaults.When this function is executed, all nonupdatable parameters in the configuration file remain unchanged.
Comments
Changes to database configuration fileparameters only become effective whenthe modified configuration fileis loaded into memory. "his process will notoccur until
Part 3: Application Programming Interface Functions all applications have disconnected from the database and a new connectionis established (when the e s t new connectionto the database is established, the new values will take effect). Although new configurationparameter values do not take effect immediately, when configuration parameter values are retrieved, the most recent update values are always returned. If an error occurs whilethis function is executing, the database configuration file will remain unchanged. A database configuration file cannot be updated if its checksum is invalid. is changed by something Checksums can become invalid if a configuration file other than thetools provided withthe DB2 product. If a database configuration file cannotbe reset, an error message is returned, and you must restore the database from agood backup imageto correct the problem. W For a brief descriptionabout each database configuration fileparameter, refer to the GET DATABASE CONFIGURATION function. For detailed informationabout each database configuration fileparameter, refer to the IBM DB2 Universal Database Administration Guide.
Connection This function can onlybe called if a connection to a DB2 Database Manager Requirements instance exists. In order to reset database configuration fileparameter values for a DB2 database located at a remote node,an application must attach to that node. If necessary, atemporary connection is established by this function during its execution.
Authorization Only users with System Administrator (SYSADM) authority, System Control (SYSCTRL) authority, or System Maintenance(SYSMAINT)authority can execute this function call. See Also
GET DATABASE CONFIGURATION DEFAULTS, GET DATABASE CONFIGURATION, UPDATE DATABASE CONFIGURATION, RESTORE DATABASE
Example
See the exampleprovidedfor page 230.
the UPDATE DATABASE CONFIGURATION function on
ode, Directory Management APIs DB2 uses a set of special directories to keep track of the workstations and databases that are available for use. This chapter is designed to introduce you to the set of DB2 API functions that are used to add entries to,remove entries from, and retrieve the contents of each of these directories. Thefirst part of this chapter provides a general discussion about the various DB2 diredories. Then,the functions that are used to retrieve and m o m the contents of the various DB2 database directories are described. Next, information aboutthe functions that are used to retrieve and modify the contents of the workstation directoryis provided. " h i s is followed by a discussionof the functions that areused to retrieve and modify the contents of the DRDA database Then, the functions that are used to make a DB2 server visible
directory.
PI function that #m,and retrieve ovided.
1“-
1
236 F:
I
Part 3: Application Programming Interface Functions
111 DB2 Directories DB2 uses the following set of directoriesto access other remote workstations and both local and remote databases: W A system database directory W One or more volume (local)directories W A workstation (node) directory W A Database Connection Services (DCS) diredory
Refer to the DB2 Database Directories sectionin Chapter 1 for detailed information about these directories.
The System Database Directory Whenever a database is cataloged, an entry containing information that is needed in order for DB2 to establish a connection to that database is stored in the system database directory. Think of this diredory as the master directory for a DB2 workstation, because it contains one entry for each localand remote catalogeddatabase that can be accessed bythat workstation. Databases are implicitly cataloged in this directory when the CREATE DATABASE function or command i s executed. You can explicitly catalog new databases and aliases for existing databases in this directory by calling the CATALOQ DATABASE function in an application or by issuing the CATALOG DATABASE command fromthe DB2 commandline processor. Youcan remove (uncatalog)entries from this directory whenthey are no longer valid (or needed) by calling the UNCATAMX: DATABASE function in an applica-, tion or by issuing the UNCATALOG DATABASEcommand from the DB2 command-line processor. You can examinethe entries inthis directory by callingthe OPEN DATABASE DIRECTORY SCAN,GET NEXT DATABASE DIRECTORY ENTRY, andCLoSE DATABASE DIRECTORY SCAN functions from within an application program.
Volume Directories In addition to the system database directory, a volume directoryexists on each logical disk drive on a workstation that contains one or more DB2 databases. The number of volume database directories that exist on a workstation is determined by the number of logical disk drives on that workstation that contain one or more DB2 databases. A volume directorycontains one entry for eachdatabase that is physically stored on the logical disk drive. Volume directories are automatically created the fist time a database is created on a logical disk drive, and DB2 updates their contents (with implicit CATand UNCATALOG commands) each time a database creation or deletion event occurs. Youcan explicitly catalog or uncatalog new databases andaliases for existing databases in a volume directorythe same wayyou would explicitly catalog and uncatalog them in the system directory. Likewise, you can examine the entries stored in a volume directory
Chapter 8: Database, Node, and DCSDirectoryManagement
APIs
i
1 2371 -.
the same way you would examine the entries in the system directory. However, the actual volume database directory where entries areto be added, deleted, or retrieved must be specifiedin the CATALOG DATABASE, UNCATALOG DATABASE, and OPEN DATABASE DIRECTORY SCAN function calls.
The Workstation (Node) Directory The workstationor node directory contains oneentry for each remotedatabase server workstation that can be accessed.Entries in the workstation directoryare used in conjunction with entries in the system directoryto make connectionsto remote DB2 Universal Database database servers. Entries in theworkstation directoryare also usedin conjunction withentries in the DCS directory for making connectionsto host (OS/390, AS/400,etc.) DB2database servers.You can explicitly catalog new workstation nodes in this directory by calling the CATALOG NODE function in an application or by issuing the CATALOG NODE command fromthe DB2 command-line processor. You can uncatalog node directory entries when they are no longer valid (or needed) by calling the UNCATALOO NODE function in anapplication or by issuing the UNCATALOG NODE command fromthe DB2 command-line processor.You can examine the entries in this directory by calling the OPEN NODE DIRECTORYSCAN, GET NEXT NODE DIRECTORY ENTRY, and CLOSE NODE DIRECTORYSCAN functions fromwithin an application program.
The Database Connection Services (DCS) Directory A DCS directory onlyexists ifthe DB2 Connect producthas been installed on the workstation. T h i s directory contains one entry for eachhost (OS/390, ASI400,etc.) database that DB2 can access via the DRDA. You can explicitly catalog newDCS databases in this directory by calling the CATALOG DCS DATABASE function in anapplication or by issuing the CATALOG DCS DATABASE command fromthe DB2 command-line processor. You can remove entries from this directory whenthey are no longer valid (or needed) by calling the UNCATALOG DCS DATABASE function in an application or by issuing the UNCATALOG DCS DATABASE command fromthe DB2 command-line processor.You can examine an entry in this database directory by calling the OPEN DCS DIRECTORY SCAN,GET DCS DIRECTORY ENTRIES,GETDCS DIRECTORY ENTRY FOR DATABASE, and CLOSE DCS DIRECTORY SCAN functions from within an application program.
BM PM! Registerinmeregistering DB2
Database Servers with NetWare As long as DB2 database servers are serving clients in an environment that uses the CommunicationsManager to handle networkprocessing, server workstations are always visible to their clients. However, if Novel1 NetWare handles the network processing, a DB2 server must be made visibleto the network registry before clients can
Part 3: Application Programming Interface Functions access the server. You can addDB2 servers toa Novell NetWare registry by calling the an application or by issuing the REGISTER command from the DB2 command-line processor. You can remove DB2 servers from a NetWare registryby calling the DEREGISTER function in anapplication or by issuing the DEREGISTER command fromthe DB2 command-line processor. REGISTER function in
PW P 4 The DB2 Database, Node, andDCS
Directory Management Functions Table 8-1 lists the DB2API functions that areused to add, list, and delete entries stored in the various DB2 system directories.
_.".".
.-.j:-.r.*
..,,..
....
,
,
.,
".-.-... -.
..-..l,.~
'2,
it..w?..n"y'*.~
Description CATALOG
UNCATALOG CHANGE
OPEN GET
Stores information about a database in either the local or system database directory.
DATABASE
Removes information about a database from either the local or system database directory.
DATABASE
DATABASE
DATABASE NEXT
Adds or changes the comment (description) associated with a database that iscataloged in either the localor system database directory.
COMMENT
Stores a snapshot copy of the local or system database directory in memory.
DIRECTORYSCAN
DATABASE
DIRECTORY
ENTRY Retrieves an entryfrom the snapshot copy of the database directory that was placed in memory by the OPEN DATABASE DIRECTORY SCAN function.
CLOSE DATABASE DIRECTORY SCAN
fi&s system resources allocated by the OPEN DIRECTORY SCAN function.
CATALOG
Stores information about a remote workstation in the node directory.
NODE
UNCATALOG OPEN GET
NODE
CLOSE
Removes information about a remote workstation from the node directory.
NODE
NEXT
NODE
Stores a snapshot copy of the node diredory inmemory.
DIRECTORYSCAN NODE
DATABASE
DIRECTORY
DIRECTORYSCAN
ENTRY
Retrieves an entry from the snapshot copy o f the node : directory that was placed in memory by the OPEN NODE DIRECTORY SCAN function. Frees system resources allocated by the OPEN NODE SCAN function.
DIRECTORY CATALOG DCS DATABASE
Stores information about a DRDA database in the DCS directory.
UNCATALOO DCS DATABASE
Removes information about a DRDA database from the DCS directory.
Chapter 8: Database, Node, and DCS DirectoryManagement APIs
;
i
239"l1
-".
"
~~~~~~~
Table 8-1
Database, Node, and DCS Directory Management APls (Continued)
OPEN DCS DIRECTORY
SCAN
Returns the number of entries found in the DCS directory.
GET DCS DIRECTORY
ENTRIES
Copies entries in the DCS directory to a user-allocated memory storage area.
QET DCS DIRECTORY ENTRY FOR DATABASE
Retrieves an entry from the copy of the DCS directory that was placed in memory by the GET DCS DIRECTORY ENTRIES function.
CLOSE DCS DIRECTORY SCAN
Frees system resources allocated by the OPEN DCS DIRECTORY SCAN function.
REGISTER
Registers a DB2 database serverat a Novell NetWarefile server regis-.
DEREQISTER
Removes a DB2 database server registration from a Novell NetWare fileserver regis-.
I
240
1I
Part 3: Application Programming Interface Functions
lB!!J CATALOG DATABASE Purpose
The CATDATABASE function is used to store informationabout a database in the system database directory. char unsigned char char char char unsigned short char etruct eqlca
Parametem
*DBNazne, *DBAliaE, me, *NodeName, *Path, *Comment, Authentication, *LCEPrincipal, *SQLCn)J
DBName
A pointer to a location in memory where the name of the database to be cataloged is stored.
DBAlias
A pointer to a location in memory where the alias name of the database to be catalogedis stored. Designates whetherthe database is local (indirect), remote,or accessed viaa Distributed Computing Environment(DCE). This parameter must be set to one of the following values:
Ope
SQL-INDIRECT
Specifies that the database is local (i.e., that itresides at the same locationas the DB2 Database Manager instance). SQL-REblOTE
Specifies that the databaseresides at another instance. SQL-DCE
NodeName
Path
Comment
Specifies that the database is accessed via DCE. A pointer to a location in memory where the name of the node where the database physically resides (ifthe database being cataloged is not a local database) is stored. A pointer to a location in memory where theletter of the drive OR the name of the pathon which the database being cataloged resides (if the databasebeing catalogedis a local database) is stored.
A pointer to a location in memorywhere a description of the database is stored. If t h i s parameter contains a NULL value, no description (comment)will be stored for the database.
Authentication S e e s where user authenticationis to occur.Authentication is the process by which DB2verifies that database users are who they claim to be. This parameter must be set to one of the following values: SQL-AUTHENTICATION-SERVER
Specifies that user authentication is t o take place on the node containing the database.
Chapter 8: Database, Node, and DCS Directory ManagementAPIs m SQL-AUTHENTICATION-CLIENT Specifies that user authenticationis to take place on the node where applicationsthat access the cataloged database are invoked.
m
SQL-AUTHENTICATION-DCS
Specifies that user authentication is to take place on the node containing the database, except whenDB2 Connect is used (when the DRDA AS option specifiesthat authentication i s to takes place at the DRDA server). SQL-AUTHENTICATION-DCE
Specifies that user authentication is t o be performed by DCE Security Services.
m SQL-AUTHENTICATION-NOT-SPEC DCEhincipal
SQLCA
The locationat which user authentication is to take place is not specified. A pointer to a location in memory where the DCE principal name of the DB2 server that the database resides on is stored.
A pointer to a location in memorywhere a SQLCommunications Area (SQLCA)data structure variable is stored. This variable returns either statusinformation (ifthe function executed successfully)or error information (ifthe function failed)to the calling application.
Includes #include <sqlenv.h>
Description
Comments
The CATALOG DATAEASE function is used to store information about a database in the system database directory. This function can catalog databases that arephysically located on either thesame physical workstationas the DB2 Database Manager instance or on a different remote workstationnode. It can also recatalog databases that for some reason have been uncataloged. In addition, this function can catalog multiple aliases for a single database, regardless of its physical location. DB2 automatically catalogsan entry in thelocal (volume)database directory and another entry in thesystem database directory whenevera new database is created. If a database is created from a remote client workstation(or from a client application executing froma different DB2 Database Manager instance on the same machine),an entry for the database will also be made in thesystem database directory that i s stored at the client instance. The value specified for the Path parameter cannot exceed 215 characters in length. If a NULL value is specified forthe Path parameter, the currentvalue of the dftdbpath DB2 Database Manager configuration fileparameter will be used to locate the database. The value specified for the ,Comment parameter cannot exceed 30 characters in length. This function canbe used to recatalog a database that has been removed
(uncataloged)from the system database directory, providedthe database has not
Part 3: Application Programming Interface Functions been deleted (dropped). B The value specifiedin the DCEPrincipaZ parameter must match the value stored in theserver’s keytab file. B If anything other than SQL~AWTHENTICATION~DCE is specified in the Authentication parameter, the DCEPrincipal parameter is ignored. B In a partitioned database environment, this function must be invokedfrom a node on the server wherethe database physically resides. Access to all database objects is dependent upon user authentication. The Authentication parameter should alwaysbe set to ~QL~AUTHENTI~ATION~NOT~SPEC, except whenyou are cataloging a database that resides on a DBW2 Version 1.x or a DBW6000 Version 1.x server. W If a NULL pointer is specified for boththe Path and the NodeName parameters, DB2 will assume that the database is local and the location of the database is in the location specifiedin theDB2 Database Manager configuration file. B If a database is cataloged withthe Type parameter set to SQL-INDIRECT, the value specifiedin theAuthentication parameter will be ignored, and the authentication value in the system database directory willbe set to SQL-AUTHENTICATION-NOT-SPEC. B Databases created at the currentDB2 Database Manager instance (as defined by
the value of the DBlINSTANCE environment variable) are cataloged as indirect (local).Databases created at other DB2 Database Managerinstances are cataloged as remote (evenif they physically resideon the same machine). B The CATALOG
DATABASE function will automatically create a system database
diredory if one does notalready exist. The systemdatabase diredory isstored on the disk driveor path that contains the DB2 Database Manager instance currently being used. B The systemdatabase directory is maintained outsideof the database. Each entry
in this directory containsthe following information: -Database name -Database alias -Database comment (description) -Database entry type -Local database directory (ifthe database is a local database) -Node name (if the database is a remote database) -Authentication type -DB2 release (version) information YOU C811 use
the OPEN DATABASE DIRECTORY SCAN,GET NEXT DATABASE and CLOSE DATABASE DIRECTORY SCAN functions to list the ENTRY, contents of the system database directory. Together,these three functionswork like
DIRECTORY
Chapter 8: Database, Node, and DCSDirectoryManagement
i 1 243 1
APIs
a SQL cursor (i.e., they use the OPEN/J?ETCWCLOSEparadigm). B If directory cachingis enabled, database, node, and DCS directory filesare cached
in memory. An application’s directory cacheis created during the firstdirectory lookup. Becausethe cache is only refreshed whenan application modifies oneof the directory files, directory changes made by other applications might notbe effective until theapplication is restarted.To refresh DB2’s shared cache (server only), an application should stopand then restart thedatabase. To refresh an application’s directory cache, the user should stopand then restart that application. For more information about directory caching, refer to the GET DATABASE MANAGER CONFIGURATIONfunction.
Connection This function can be called at any time; a connection to a DB2 Database Manager Requirements instance or to a DB2 database does not haveto be established first. Authorization Only users with either System Administrator(SYSADM) authority or System Control (SYSCTRL) authority areallowed to execute this function call.
see Also
UNCATALOG DATABASE, OPEN DATABASE DIRECTORYSCAN,GET NEXT DATABASE DIRECTORY ENTRY, CLOSE DATABASE DIRECTORY SCAN
Example
Thefollowing c++ program illustrates how to use the CATALOG to catalog an alias for the SAMPLE database:
*/
/*. /* NAME:
/*
/* /* DATABASE /* /* /*
CHIEX1 .CPP PURPOSE: Illustrate How To Use The Following DB2 API Function In A C++ Program:
CATALOG
*/
*/ */
*/ */
*/ */
/ / Include The Appropriate Header Files #include <windowe.h> #include #include <sqlca.h*
/ / Define TheAPI-Class Class class API-Class / / Attributes public : etruct sqlca
1;
DATABASEfunction
sqlca;
/ / Operations public : long CatalogDB () I
Part 3: Application Programming Interface Functions / / Define The CatalogDBO Member Function long API-Class::CatalogDB()
i / / Declare The Local M e m o r y Variables char DBName[ 91 ; char DBAlias[ 91 : char Comment 1311 1
/ / Initialize The Local Memory variables Strcpy(DBName, WAB@LED); StrCRY(DBAliaS, "SAMPLEDB"); strcpy(Comment, u ~ Sample ~ M Database"); / / Catalog A New Alias For The SAMPLE Database sqlecadb(DBName, DBAlias, SQL-INDIRECT, NULL, NULL, Comment, SQL-AUT€IENTICATION-NOT-SPEC, NULL, Psplca); / / If The New Alias Was Cataloged, Display A Success Message if (sp1ca.sqlcode =P SQL-RC-OK)
i
cout << UThe alias " << DBAlias << B' has been cataloged " 1 cout << Ufor the * << DBName << U database." << endl;
1 / / Return The SQLCA Return ,return(sqlca.splcode);
Code To The
Calling
Function
1
*/
/*
/*
*/ */
The Main Function
/* int main() / / Declare The Local long rc i. SQL-RC-OK;
Memory
/ / Create An Instance' API-ClassExample;
Variables
OfThe API-Clase Class
/ / Catalog A New Alias For rc = Example.CatalogDB ( ) ; / / Return To The return )(rc ;
Operating
The
SAMPLE
Database
System
l!!!!! UNCATALOGDATABASE Purpose
The UNCATALOG DATABASE function i s used to delete an entry fromthe system database directory.
Chapter 8: Database, Node, and DCS Directory ManagementAPIs syntax
SQLJLPI-RC SQLJLPI-FN
Parameters
DBAlias
SQLCA
sqleuncd (char
*DJ3Alia8, etruct sqlca *SQLCA)/
A pointer to a location in memorywhere the alias name of the database to be uncatalogedis stored. A pointer to a location in memorywhere a SQL Communications Area (SQLCA)data structure variable is stored. This variable returns either statusinformation (if the function executed successfully)or error information (if the function failed)to the calling application.
Includes
#include <eqlenv.h>
Description
The TJNCATZUOG DATABASEfunction is used to delete an entry from the system database directory. This function can only deleteentries in thesystem database directory. Entries in thelocal (volume) database diredory mustbe deleted with the DROP DATABASEfunction.
Comments
You can changethe authentication type of a database when communicatingwith a down-level serverby first uncataloging the database and then cataloging it again with a different authentication type. Refer to the CATALOG DATABASE function for more information aboutauthentication types. YOU Can use the OPEN DATABASE DIRECTORY SCAN,GET NEXT DATABASE DATABASE DIRECTORY SCAN functions to list the DIRECTORY ENTRY, and CLOSE contents of the system database directory. Together,these three functions work like an SQL cursor (i.e., they use the OPEN/FETCWCLOSE paradigm). B If diredory caching is enabled, database, node, and DCS diredory files are cached in memory. An application’s diredory cache is created during the firstdirectory lookup. Becausethe cache is only refreshed whenan application modifies oneof the diredoryfiles, directory changes made by other applications might notbe effective until theapplication has been restarted. To refresh DB2’s shared cache (server only), an application shouldstop and then restart thedatabase. To refresh an application’s directory cache,the user should stop and then restart that application. For more information about directory caching, refer to the GET DATABASE MANAGER CONFIOURATION function. ’
Connection This function canbe called at any time; a connection to a DB2 Database Manager Requirements instance or to a DB2 database does not have to be established first. Authorization Only users with either System Administrator(SYSADM) authority or System Control (SYSCTRL) authority can executethis function call. See Also
CATALOG DATABASE, OPEN DATABASE DIRECTORYSCAN, GET NEXT DATABASE SCAN DIRECTORY ENTRY, CLOSE DATABASE DIRECTORY
Example
The following C++ program illustrates how to use the UNCATALOG DATABASE function to remove an alias for the SAMF’LE database from the system database directory:
1
246
1i
Part 3 Application Programming Interface Functions /* /* /* /* /* /*
*/ CHBEX2.CPP PURPOSE: Illustrate How To Use The Following DB2 API Function In A C++ Program:
NAME:
UNCATALOG
DATABASE
/* /*
*/ */
*/ */ */ */ */
/ / Include The Appropriate Header Files #include <windowa.h> #include #include <sqlenv.h> #include <sqlca.h> / / Define The -1-Class class API-Class
Class
c / / Attributes public : struct eqlca sqlca;
/ / Operations public: long UncatalogDB () ;
1; / / Define The UncatalogDBO Member Function long API-Class::UncatalogDB()
I / / Declare The LocalMemory Variables char DBAlias [ g ] ; / / Initialize The Local Memory Variables etrcpy(DBAlias, "SAMPLEDB"); / / Uncatalog An Alias For sqleuncd(DBAlias, &sqlca);
The
SAMPLE
Database
/ / If The Alias Was Uncataloged, Display A Success Message if (sqlca.sq1code m = SQL-RC-OK)
c
cout << "The alias cout << endl;
<< DBAlias <<
I*
has been uncataloged.";
1 / / Return TheSQLCA Return return(sqlca.sqlcode);
CodeTo The
Calling
Function
1
/*
/*
The Main Function
/* int main()
c / / Declare The Local Memory Variables
*/ */ */
W
Chapter 8: Database, Node, and DCSDirectoryManagement long rc
APIs
I
247
1
= SQL-RC-OK;
/ / Create An Instance O f The API-Class Class API-ClassExample; / / Uncatalog An Alias For The SAMPLE Database () ; rc = Example .UncatalogDB / / Return To The Operating System return(rc) ;
1
FM W4 CHANGE DATABASE COMMENT Purpose
The CHANGE DATAaASE COMMENT function is used to add or change the comment (description) associated with a database that hasbeen catalogedin either the system database directory or the local (volume)database directory.
syntax
SQL-API-RC SQL-API-FN sqledcgd
Parameters
DBAlias
(char char char struct sqlca
*DBAliee, *Path, *Comment,
*SQLCAI;
A pointer t o the location in memory where the alias name of the database whose commentis to be updated is stored.
Path
A pointer to a location in memorywhere thepath to the local database directory is stored. If the value specified forthis parameter is NULL,the system database directory is used.
Comment
A pointer to a location in memorywheredescriptiveinformation (a
SQLCA
comment) about the database is stored. This parameter can contain a NULL value. A pointer to a location in memorywhere a SQL Communications Area (SQLCA)data structure variable is stored. This variable returns either status information (ifthe function executed successfully)or error information (ifthe function failed)to the calling application.
Includes
#include <sglenv.h>
Dehcription
The CHANGE DATABASE COMMENT function is used to add or change the comment (description) associated with a database that has been catalogedin either the system database directory or the local database directory. Onlythe comment associatedwith the database alias specified is modified by this function. Other entries in the system database directory or the local database directory that have the same database name but different aliases are not affected.
Comments
M The value specified for the DBAlias parameter cannot exceed eight characters in
length. M If a path name is specified in the Path parameter, the database alias specified in the DBAZias parameter must be cataloged in the local database directory. Ifno path name is specified, the database alias must be catalogedin thesystem database directory. M The value specified for the Comment parameter cannot exceed30 characters in length. If the Comment parameter is setto NULL, the database comment will be unchanged. If the Comment parameter contains text, the new text will replace any existing comment text when this function is executed. The commentis only changedin the local database directory or the system database directory on the node from which this function is invoked. To change the database comment on each node usedby a partitioned database, this function must be executed from every node. To modifi an existing database comment, an application should performthe following steps: 1. Call the OPEN DATABASE DIRECTORY SCAN function. 2. call the GET
NEXT DATABASE DIRECTORY ENTRY function to retrieve the existing database comment. 3. Modify the retrieved comment. 4. call the CLOSE DATABASE DIRECTORY SCAN function. 6. Call this function using the modified comment.
Connection This function can be called at any time; a connection to a DB2 Database Manager Requirements instance or to a DB2 database does not haveto be established first. Authorization Only users with either System Administrator (SYSADM) or System Control (SYSCTRL) authority are allowed to execute this function call.
see Also
CREATE DATABASE, CATALOG DATABASE
Example
ThefollowingC++program illustrates how t o use the CHANGE DATABASE COMMENT h c t i o n to change the description (comment) associated with the SAMPLE database:
/* /*
/*
/* /* /* /* /*
NAME: CH8EX3 .CPP PURPOSE: Illuetrate How To U s e The Following DB2 API Function In A C++ Program: CHANGE DATABASE
*/ */ */ */
*/
COEWENT
/ / Include The AQQr0Qriat.eHeader File0 #include <windowe.h, #include
*/
*/ */
Chapter 8: Database, Node, andDCS Directory ManagementApIs #include <eqlenv.h> #include <eqlca.h> / / Define The API-Claee Claee claee API-Claee {
/ / Attributes public : etruct eqlca eqlca;
1;
/ / operations public : long Changecomment();
/ / Define The Changecomment() Member Function long API-Claee: :ChangeComment ( ) {
/ / Declare The Local Memory Variablee char DBAliae L91 ; char Cannnent 1311 ; / / Initialize The Local M e m o r y Variablee strcpy(DBAliae, "SAMPLED) ; etrcpy(Cannnent, "DB2 UDB Sample Database") ; / / Change The Comment Associated with The SAMPLE eqledcgd(DBAliae, Comment, breqlca);
Database
Aliae
/ / If The Comment Wae Changed, Display A Succeee Meeeage if (eqlca.eqlcde I= SOL-RC-OK) {
1
cout << "The comment aeeociated with the D << DBAliae; database aliae hae been changed." << endl; cout <<
/ / Return The SQLCA Return return(eqlca.eqlcode);
Code To The
Calling
Function
1
/* /*
*/ The Main Function
*/ I
int main( ) {
/ / Declare The LocalMemory Variablee long rc = SQL-RC-OK;
/ / Create An Inetance Of The API-Claee Claee API-ClaeeExample;
/ / Change The Comment For The SAMPLE Database rc = Example.ChangeComment0;
i
250
:I
Part 3: Application Programming Interface Functions
"
/ / Return To The Operating return(rc) ;
System
m m OPEN DATABASE DIRECTORY SCAN Purpose
The OPEN DATABASE DIRECTORYSCAN function is used to store a copy of the system database directory or the local database directory in memory and t o obtain a count of the number of entries found in thedirectory specified.
syntax
SQLJiPI-RC SQL-API-FN
Parameters
Path
Handle
sqledosd (char
*Path, unsigned short *Handle, unsigned short *mmEntriee, struct sqlca *SQLCA);
A pointer to the location in memorywhere thepath that identifies where the local database directory resides is stored. If the value specified forthis parameter is NULL, the system database directory is used. A pointer to alocation in memorywhere this function is to store a directory scan buffer identifier that will be used in subsequent GET NEXT DATABASE DIRECTORY ENTRYandCLOSE function Calls. DIRECTORY SCAN
NumEntries
SQLCA
DATABASE
A pointer t o a location in memory where this function is to store a count of the number of entries found in the database directory specified. A pointer to alocation in memorywhereaSQLCommunications Area (SQLCA)data structure variable is stored. This variable returns either status information (if the function executed successfully)or error information (if the function failed)to the calling application.
Includes
#include <sqlenv.h>
Description
The OPEN DATABASE DIRECTORY SCAN function is used to Store a Copyof the system database directory or the local database directory in memory and to obtain a count of the number of entries found in thedirectory specified. Thecopy of the database directory that is placed in memory represents a snapshot of the directory when the diredoryscan is opened. T h i s copy is never updated, even if the directory itself changes. T h i s function is normally followed by one or more GET NEXT DATABASE DIRECTORY ENTRY function calls and one CLOSE DATABASE DIRECTORY SCAN function call. Together, these three functions worklike an SQL cursor (i.e.,they use the OPEN/FETCWCLOSE paradigm). The memory buffer that is used to store the
Chapter 8: Database, Node, and DCS DirectoryManagement ApIs
l.:';/25 1
database directory data obtained by the directory scan is automaticallyallocated by this function and a pointer to that buffer (the buffer identifier) is stored in the Handle parameter. This identifier is then used by subsequent GET NEXT DATABASE and CLOSE DATABASE DIRECTORY SCAN function calls to access DIRECTORY ENTRY information stored in the thememory buffer area.
Comments
B Multiple OPEN
DATABASE DIRECTORYSCAN function calls can be issued against the same database directory. However, becausethe directory can change between each call,the directory entries copied into memory by each call might vary.
B An application can haveup to eight database diredoryscans open at one time.
Connection This function can be called at any time; a connection to a DB2 Database Manager Requirements instance or to a DB2 database does not have to be established first.
Authorization No authorization is required to execute this function call.
seeAle0 Example
GET NEXT DATABASE DIRECTORY ENTRY, CLOSE DATABASE DIRECTORY
SCAN
Thefollowing C++ program illustrates how to use the OPEN DATABASE DIRECTORY SCAN, GET NEXT DATABASE DIRECTORY ENTRY, andCLOSE DATABASE DIRECTORY SCAN functions to retieve theentries in the system database direct~ry:
/* /*
/* /* /*
/* /* /*
*/
NAME:
CH8EX4 .CPP PURPOSE: Illustrate How To Use The Following DB2 API Functions In A C++ Program: OPEN DATABASE DIRECTORY SCAN GET NEXT DATABASE DIRECTORY ENTRY CLOSE DATABASE DIRECTORY SCAN '
/*
/*
/ / Include The Appropriate Header Piles #include <windows.h> #include #include <sqlenv.h* #include <sqlca.h* / / Define TheAPI-Class Class class API-Class i / / Attributes public : struct sqlca sqlcat / / Operations public : long ShowDatabases(); 11
*/ */ */ */ */ */
*/ */ */
Part 3: Application Programming Interface Functions / / Define The ShowDatabasee() Member Function long API-Clase::ShowDatabasee() {
/ / Declare The Local Memory Variables unsigned short Handle; unsigned short DBCount; Btruct sqledinfo *DB-DirInfo I NULL;
/ / Scan The Database Directory Buffer And Retrieve ~ l Database l / / Names And Descriptions stored There
if (8qlca.sqlcde
m=
SQL-RC-OK)
{
tout << mAlias Descriptionm <e endl; COUt << m for ( ; D B C m t I = 0; DBCOunt-)
<< end11
{
/ / Retrieve The Next Database Directory sqledgne(Handle, &DB-DirInfo, hsqlca);
Entry
/ / Display Database' Directory if (sqlca.eqlcode == SQL-RC-OK)
Retrieved
{
Entry
char Alias [ g ] ; cout.width(14)t cout.setf(ios::left)r strncpy(Alias, DB-Dirlnfo-.alias, 8 )t Alias[81 = 0; cout e< Alias; cout.width(30); cout.setf(ios::left); cout << DB-DirInfo->caPnnsnt << endl;
1 1 / / Close The Database Directory Scan And Free All Resources / / Obtained B y The Open Databaee DirectoryScan API sqledcls(Hand1e. &sqlca)t
1
1
/* /*
/ / Return The SQLCA Return return(sqlca.aqlcode)t
Code To The
Function
*/ */ */
The Main Function
/*
int main() {
/ / Declare The Local Memory long rc = SQL-RC-OK;
Calling
variables
Chapter 8: Database, Node, and DCS DirectoryManagement APIs
/ / Qenerate And DiSplay A List OF Available rc P Example. ShowDatabasee( ) J
! ,
1
1 253 1
Databases
/ / Return TO The Operating System return(rc)J ,
1
F M W4 GETNEXTDATABASE
DIRECTORY ENTRY purpose
The GET NEXT DATABASE DIRECTORY ENTRY function is Used t0 retrieve the next entry from the copy of the system database directory or the local database directory that was placed in memory by the OPEN DATABASE DIRECTORY SCAN function.
syntax
SQL-API-RC SQL-API-FN
Parameters
Handle DBDirEntry
SQLCA
sqledgne (unsigned short Handle, struct sqledinfo **DBDirBntry, struct eqlca *SQLcA);
Thedirectory scan buffer identifier that was returned by an associated OPEN DATABASE DIRECTORY SCAN function call. A pointer to the address of an sqledinfo structure where this function is t0 store the database directory entry information retrieved. Apointer to alocation in memorywherea SQL Communications Area (SQLCA) data structure variable is stored. This variable returns either status information (ifthe function executed successfully)or error information (ifthe function failed) bto the calling application.
Includes
#include <sglenv.k>
Description
The GET NEXT DATABASE DIRECTORY ENTRY fundion is Used t0 retrieve the next entry from the copy of the system database directory orthe local database directory that W a 8 placed in memory by the OPEN DATABASE DIRECTORY SCAN function. The information retrieved is stored in a specialstructure, sqledinfo, that is defined in sqlenv.h as 'follows: struct sqledinfo {
char alias char char drive[215];
[el; abname[81 J
/* /* /*
The database alias (alternate) The database name
The path
name
name or the disk drive ID
*/ */ */
Part 3: Application ProgrammingInterface Functions that epecifiee where the databaee */ phyeically resides. A value ie only */ returned for thia field if the ayetem*/ /* databaee directory wae opened for */ / * ecanning. */ char intname t 8I ; */ /* Thesubdirectory m e where the /* databaee resides. A value is only */ /* returned for thie field if the local */ /* database directory wae opened for */ /* scanning. */ char / * The name of the node where the */ /* databaee ie physically located. A */ /* value ie only returned for thiefield*/ /* if the databaeeia a remote databaee.*/ char /* DB2 Databaee Manager releaee */ abt~r~et2Ol ; / * inionnation */ char comment [ 3 0 ] ; /* The comment (deecription) that ie */ / * aaeociated with the database */ ehort cmcodepage; /* The code page ofconnnent. Thie field */ /* ie no longer ueed. */ char /* Indicatee whether the databaee wae */ t m et /* wae created by the current inetance */ /* (SQL-INDIRECT), reeidee at a */ /* different inetance (SQL-REMOTE), */ /* reeidee on thie volume (SQL-HOME), */ /* or reeidee in a DCE directory */ /* (SQL-DCE) */ uneignedehortauthentication;/*Indicateewhetherueer ID and */ /* paasword authentication occureat */ /* the databaee eerver worketation */ /* (SQL-AUTHENTICATION-SERVER), */ /* at the client worketation */ /* (SQL-AUTHENTICATION-CLIENT), */ /* at the DCS eerver */ /* (SQL-AUTHENTICATION-DCS), by DCE */ /* Security Servicee */ /* (SQL-AUTHENTICATION-DCE), or ie */ /* unepecified */ /* (SQL-AUTHENTICATION-NOT-SPEC) */ char lbabname 1255l ; /* The global name of the target */ /* databaee in the DCE directory if the*/ /* tyBe field of this etructure ie set*/ /* to SQL-DCE */ char dceprincipal[1024]~ /* The DCE principal name. A value ie */ /* only returnedfor thie field if */ /* authentication is performedby DCE */ /* Security Services. "/ cat-nodenum; ehort /* The catalog node number */ nodenum; ehort /* The node number */ 1;
/* /* /*
.
Chapter 8: Database, Node, and DCS Directory ManagementAPIs W When this function is executed, the value in theDBDirEntry parameter points to the next database directory entry in the copy of the database diredory that resides in memory. Each subsequent GET NEXT DATABASE DIRECTORY ENTRY function call retrieves the database directory entry immediately following the current directory entry, unlessthere areno more directory entries available (in which case an error is returned). R You can use the value returned in the NumEntries parameter when the OPEN DATABASE DIRECTORY SCAN function is executed to set up a loop that scans through the entire database directory by issuing GET NEXT DATABASE function calls, oneat a time, until thenumber of calls issued DIRECTORY ENTRY equals the number of entries found in thedirectory. Prerequisites The OPEN DATABASE function is called.
DIRECTORY SCAN function must be executed before
this
Connection This function can be called at any time; a connection to a DB2 Database Manager Requirements instance or to a DB2 database does not haveto be. established first. Authorization No authorization is required to execute this function call. See Also
OPEN
Example
See the example provided for the OPEN page 251.
DATABASE
DIRECTORYSCAN,CLOSE
DATABASE
DATABASE
DIRECTORY
SCAN
DIRECTORY SCAN function on
m m CLOSE DATABASE DIRECTORY SCAN Purpose
The CLOSE DATABASE DIRECTORY SCAN function is used to free system resources that were allocated by the OPEN DATABASE DIRECTORY SCAN function. SQL-API-RC
Parameters
Handle
SQLCA
SQL-API-FN
eqledcle (unsigned short Handle, etruct eqlca *SQLCA);
Thedirectoryscan buffer identifier that was returned by an SCAN function Call. associated OPEN DATABASE DIRECTORY A pointer to a location in memory where a SQLCommunications Area (SQLCA)data structure variable is stored. This variable returns either statusinformation (ifthe function executed successfully)or error information (ifthe function failed)to the calling application.
Inaludes
#include <sqlenv.h>
Description
The CLOSE DATABASE DIRECTORY SCAN function is used to free system resources that were allocated.bythe OPEN DATABASE DIRECTORY SCAN function.
This function canbe called at any time; a connection to a DB2 Database Manager Connection Requirements instance or to a DB2 database does not havet o be established first.
Part 3: Application Programming Interface Functions Authorization No authorization is required to execute this function call. See Also
OPEN DATABASE DIRECTORY
Example
see the exampleprovidedfor
SCAN,GET NEXT DATAEtASE DIRECTORY ENTRY
the OPENDATABASEDIRECTORY
SCAN function on
page 251.
M!!!!
CATmOGNODE
purpo=
The CATALOGNODE function is used to store informationabout the location of another DB2 Database Manager (server) instance and the associated communications protocol that is used to access that instance in theworkstation node directory.
ssntax
SQLMI-RC SQLPPI-FN
Parameters
Nodelnfo ProtocolZnfo
SQLCA
sqlectnd (struct sqle-node-struct void struct eqlca
*N&eInfo,
*ProtocolInfo, *SQLCA)I
A pointer to a sqle-m&-struct structure that containsinformation about the node that is to be cataloged. A pointer to the appropriate protocol information structure that contains information aboutthe communications protocolthat will be used to access the specified node. A pointer to a location in memorywhere a SQL Communications Area (SQLCA)data structure variable is stored. “ h i s variable returns either statusinformation (ifthe function executed successfully)or error information (ifthe function failed)to the calling application:
Includes
#incluBe <eglenv.h>
Description
The CATALOGNODE function is used to store information about the location of another DB2 Database Manager (server) instance and the associated communications protocol that is to be used to access that instance in theworkstation node directory. “his information is needed in order foran application to establish a connection or an attachment to a remote DB2 database server. Two special structures (sqle-nodestruct and an appropriate protocol information structure) areused t o pass characteristics about a node t o the DB2 Database Manager whenthis function is called. Thefirst of these structures, sqle-node-struct, is defined in sqlenv.h as follows: etruct sqle-node-struct {
unsigned short
etruct-id;
unsignedshort
codepage:
/* /* /* /*
A
unique structure identifier value. This field must always be set to SQL-NODE-STRJD.
Codepagevalueused
for the node
*/ */ */ */
1
,
! I
i ;
. .
Chapter 8: Database, Node, and DCS Directory ManagementAPIs
i 257
I
camment */ Optionaldescriptionof the node */ */ /* Node name /* Indicates whether the protocol that */ with the node ie */ /* communicates */ /* APPC (SQL-PROTOCOL-APPC), */ /* NetBIOS (SQL-PROTOCOL-NETB), */ / * APPN (SQL-PROTOCOL-APPN), */ /* TCP/IP (SQL-PROTOCOL-TCPIP), /* TCP/IP Ueing SOCKS (SQL-PROTOCOL-SOCKS)*/ */ /* CPIC (SQL-PROTOCOL-CPIC), */ /* IPX/SPX (SQL-PROTOCOL-IPXSPX), /* LOCAL protocol€or an instance on the*/ /* same workstation (SQL-PROTOCOL-LOCAL) */ /* or a named pipe (SQL-PROTOCOL-NPIPE) */
/* comment char char unsigned char protocol;
[311 t nodename[91 I
/*
1;
The secondspecial structure used bythis function (the protocol information structure) is determined bythe communications protocolthat is to be usedto communicate with the cataloged node.This structure can beany of the following DB2-defined structures: D sqle-node-appc Advanced Program-to-Program Communications (APPC) protocol D sqle-node-appc
Advanced Peerto-Peer Networking (APPN) protocol sqle-node-mtb NetBIOS protocol U sqle-node-tcpip TCP/IP H sqle-node-cpic Common Programming Interface Communications (CPIC) protocol U sqle-node-ipmpxInternetworkPacketExchangeISequencedPacketExchange U sqle-node-local
D sqle-node-npipe
(IPWSPX) protocol Local node Named pipe
The sqle-node-appc structure is defined in sq1env.h as follows: struct eqle-node-appc The logical unit (SNA port) name used*/
char
locallu [g] ;
/* /*
char
partner-lu 91 ;
/* The logical unit (SNA port)name at
char
mode L91 ;
/*
/* /*
/*
to establish the connection. the remote DB2 instance. The name of the tranemiseion mode to use. This field ie usually eet to "SQLL0001".
*/ */
*/
*/ */ */
Part 3 Application Programming Interface Functions The sqle-node-appn structure is defined in sq1env.h as follows: struct sqle-node-appn i char networkidL 9I ; char remote-lu L9 1 ; char
local-lu 91 ;
char
mode L93 ;
/*
/*
/* /* /*
/*
/* /*
The network ID The logical unit (SNA port) name at the remote DB2 instance The logical unit (SNA port) name used to establish the connection The name of the transmission mode to use. This field is usually set to "SQLLOOOl".
*/ */ */ */ */
*/ */ */
The sqle-node-mtb structure is defined in sq1env.h as follows: struct sqle-node-netb
c
unsigned short adapter;
char
/* /* /*
The LAN adapter number. This parameter*/ can be set to any of the following */ values : */ */ /* SQL-ADAPTER-O (adapter number 0 ) , */ /* SQLJDAPTER-l (adapternumber l), */ /* SQL-ADAPTER-MIN (the m i n i m */ /* adapter number), or */ /* SQL-ADAPTER-MAX (the maximum number. */ /* adapter remote-nnameL91 ;/* The workstation name thatis stored */ */ /* in the nname parameterof the /* Database Manager configuration file */ workstation. */ /* on the remote must field */ /* beThis */ /* NULL-terminated or blank filled */ /* up to 9 characters.
The sqle-node-tcpip structure is defined in sq1env.h as follows: struct sqle-node-tcpip {
char hostname char
1;
L2561 ;
service-name L 15I ;
*/ /* The name of the TCP/IP host that /* the DB2 instance (server) resideson */ /* The TCP/IP service name (or port */ /* number) of the DB2 instance (server) */
The sqle-node-cpic structure is defined in sqZenv.h as follows:
Chapter 8: Database, Node, and DCS Directory ManagementAPIs eym_8estgamet91;/* The symbolic destination name of /* the remote partner unsigned short security-type; /* The security type used. This field /* must be set to /* SQL-CPIC-SECURITY-NONE, /* SQL-CPIC-SECURITY-PROGFW4, /* or SQL-CPIC-SECURITY-SAME. Char
*/
*/ */ */ */ */ */
1;
The sqle-node-ipmpx structure is defined in sqlenv. has follows: struct sqle-node-ipxspx {
char
/*
fileserver 1491 ;
/* /* /* /* /*
char objectname t491;
The name of the Netware file server */ where the DB2 server instance is */ registered */ The name particular aof */ DB2 server instance that is stored */ in the Netware file aerverbindery. */
The sqle-node-local structure is defined in sqlenv. has follows: struct sqle-node-local
i char
instance-name 19I ;
/*
/* /*
/*
The name of a DB2 Database Manager instance. This field must be NIILLterminated or blank filled up to 9 characters.
*/
*/ */ */
?;
The sqle-node-npipe structure is defined in sqlenv.h as follows: struct sqle-node-npipe
c char computername
char
[l61;
instance-namet91;
/*
/* /* /* /*
The name of the computer that a DB2 Database Manager instance (server) resides on The name ofaDB2DatabaseManager instance
*/
*/ */ */
*/
1;
Comments
W This fundion will automatically create a node directory ifone does not already exist. On OS12 and Windows, the node directoryi s stored on the disk drive that
contains the DB2 Database Manager instance that i s currently being used. On all other systems, the node directoryi s stored in thedirectory wherethe DB2 product was installed. YOUcan use the OPEN NODE DIRECTORY SCAN, GETNEXTNODEDIRECTORY
Part 3: Application Programming Interface Functions ENTRY, and CLOSE NODE DIRECTORY SCAN functions to list the contents Of the node directory. Together,these three functions work likean SQL cursor (i.e., they use the OPEN/FETCWCLOSE paradigm). W If directory cachingis enabled, database, node, and DCS directory filesare cached in memory. An application’s directory cache i s created during the firstdirectory lookup. Becausethe cache is only refreshed whenan application modifies oneof the directory files, directory changes made by other applications might notbe effective until theapplication is restarted.To refresh DB2’s shared cache (server only), an application should stopand then restart thedatabase. To refresh an application’s directory cache, the user should stopand then restartthat application. For more information about directory caching, refer to the GET DATABASE MANAGER C O N F I ~ T I O function. N
Connection This function can be called at any time; a connection t o a DB2 Database Manager Requirements instance or to a DB2 database does not haveto be established first. Authorization Only users with either System Administrator(SYSADM) authority or System Control (SYSCTRL) authority can executethis function call.
see Also Example
VNCATALOG NODE, OPEN NODE DIRECTORYSCAN,GET NEXT NODE DIRECTORY ENTRY, CLOSE NODE DIRECTORY SCAN
ThefollowingC++program illustrates how to use the CATALOG catalog a remote workstationnode:
/* /* /* /* /* /* /*
NODEfunction to
CH8EX5.CPP PURPOSE: Illuetrate How TO Uee The Following DB2 API Function In A C++ Program:
N A M E :
CATALOQ NODE
/ / Include The Appropriate Header Files #include *windowe.h, #include #include aq1env.b #include aq1ca.b
/ / Define The API-Claee Claee claee API-Claee / / Attributes public : etruct eqlca eqlcar / / operatione public 2
*/
*/ */
*/ */ */ */
i 1 i 1
Chapter 8: Database, Node, andDCS Directory ManagementAPIs long
1;
!I
261
CatalogNode();
/ / Define The CatalogNodeO Member Function long API-C1ass::CatalogNodeO {
/ / Declare The Local Memory Variable8 struct sqle-node-struct NodeInfo; struct sqlegode-netb Protocol; / / Initialize The Node Information Data Structure NodeInfo.struct-id = SQL-NODE-STR-ID; strcpy(Node1nfo.comment. "Test Database Serverw); strcpy(NodeInfo.nodename. "TESTSVR"); NodeInfo.protoco1 = SQL-PROTOCOL-=TB; / / Initialize The NetBIOS Protocol Data Structure Protocol.adapter = SQL-?DAPTER-O; strcpy(Protocol.remote-nname, "TESTSVR"); / / Catalog A New Worketation Node sqlectnd(&NodeInfo, (void *) &Protocol, &eqlca); / / If The New Worketation Was Cataloged, Display A Success if (eqlca.sqlcode =- SQL-RC-OK)
Message
{
1
tout << "The node cout has been
<< NodeInfo-nodename; cataloged." endl;
/ / Return The SQLCA Return return(eqlca.eqlcode);
Code To The
Calling
Function
? ~~
/* /*
int main( ) {
/ / Declare The Local long rc = SQL-RC-OK;
Memory
Variables
/ / Create ?m Instance Of The API-Class Class API-ClassExample; / / Catalog A New Workstation rc = &xample.CatalogNodeO;
/ / Return To The return(rc) ;
1
-- I
*/ */
The Main Function
Operating
Node
System
L262 j j
Part 3: Application Programming Interface Functions
”
Purpose
The UNCATALOG
syntax
SQL-API-RC SQLJiPI-FN
Parameters
NodeName SQLCA
NODEfunction is used eqleuncn
to delete an entry from the nodedirectory.
(char struct eqlca
*NodeName, *SQLCAl;
A pointer to a location in memorywhere the name of the node to be uncataloged is stored. A pointer to a location in memory where a SQL Communications Area (SQLCA)ata structure variable i s stored. This variable returns either statusinformation (ifthe function executed successfully)or error information (ifthe function failed)t o the calling application.
Includes
#include <eglenv.h>
Description
The UNCATALOG
Comments
W The CATALOG
NODE function is used
to delete an entry from the node directory.
NODE function can be used to recatalog a node that was removed (uncataloged)from the node directory. YOU Can use the OPEN NODE DIRECTORY SCAN, GET NEXT NODE DIRECTORY NODE DIRECTORY functions SCAN to list the contents of the ENTRY, and CLOSE node directory. Together,these three functions work like a SQL m o r (i.e., they use the OPEN/FETCWCLOSE paradigm). W If directory cachingis enabled, database, node, and DCS directory filesare cached in memory. An application’s directory cacheis created during the firstdirectory lookup. Becausethe cache i s only refreshed whenan application modifies oneof the directory files, directory changes made by other applications might nottake effect until theapplication is restarted.To refresh DB2’s shared cache (server only), an application should stopand then restart thedatabase. To refresh an application’s directory cache,the user should stop and then restartthat application. For more information about directory caching, refer t o the GET DATABASE W A G E R CONFIGURATION function.
Connection This function can be called at any time; a connection to a DB2 Database Manager Requirements instance or to a DB2 database does not haveto be established first. Authorization Only users with either System Administrator(SYSADM) authority or System Control (SYSCTRL) authority are allowed to execute this function call. See Also
CATALOG NODE, OPEN NODE DIRECTORY SCAN,GET NEXT NODE DIRECTORY SCAN ENTRY, CLOSE NODE DIRECTORY
Example
Thefollowing C++ program illustrates how to use the UNCATALOG uncatalog a remote workstationnode:
NODEfunction to
Chapter 8: Database,Node,and DCSDirectoryManagement
HEEX6.CPP
j!
MIS
" .
/* /*
/* /* /*
263
*/ NAME: PURPOSE: Illustrate How To Use The Following DB2 API Function In A C++ Program:
"
*/
*/ */ *I
/* /* /*
*/
UNCATALOO NODE
*/
*/
/ / Include The Appropriate Header Files #include <windows.h> #include #include <sqlenv.h> #include <eqlca.h> / / Define TheAPI-Clam Class class API-Class
/ / Attributes public : struct eqlca
1;
sqlca;
/ / Operatione public : long UncatalogNodeO;
/ / Define The UncatalogNodeO Member Function long API-Class::UncatalogNode()
c / / Declare The Local M e m o r y Variables char NodeName[ 91 ; / / Initialize The LocalM e m o r y Variables strcpy(NodeName, "TESTSVR") ;
/ / Uncatalog The Specified sqleuncn(NodeName, Gsulca); / / If The Node
Node
Was Uncataloged, Display A Succese Message
if (sqlca.splcode == SQL-RC-OK)
c
1
1
/* /* /*
cout << ''The node '* << NodeName << cout << endl;
/ / Return The SQLCA return(sqlca.sqlcode);
Return
hae been uncataloged.n;
Code TO The Calling
Function
*/ The Main Function
int main()
*/
*/
Part 3: Application Programming Interface Functions {
/ / Declare The Local Memory Variables long rc = SQL-RC-OK;
/ / Create An Instance API-ClassExample;
Of
The API-Class Class
/ / Uncatalog A Workstation
rc
I
Node Example.UncatalogNode0;
/ / Return To The Operating System return(rc);
1
OPEN NODE DIRECTORY SCAN The OPEN NODE DIRECTORY SCAN function is used to store a copy of the node directory in memory and to obtain a countof the number of entries found in thenode directory. SQL-API-RC SQL-API-FN
Parameters
Handle
SqhnOpS
(unsigned short *Handle, unsigned short * W n t r iea, Struct sqlca "SQLCA);
Apointer to a location in memorywhere this function is to store a directory scan buffer identifier that will be used in subsequent GET NEXT
NODE
DIRECTORYENTRYandCLOSE NODE
DIRECTORY
SCAN
NumEntries
SQLCA
function calls. A pointer to a location in memory where this function is to store a count of the number of entries found in the node directory. A pointer to alocation in memorywhereaSQLCommunications Area (SQLCA) data structure variable is stored. This variable returns either status information (ifthe function executed successfully)or error information (ifthe function failed) to the calling application.
Includes
#include <eqlenv.h>
Description
The OPEN NODE DIRECTORY SCAN function is used to store a copy of the node directory in memory and to obtain a countof the number of entries found in thenode directory. Thecopy of the node directorythat is placed in memory represents a snapshot of the directory whenthe directory scanis opened. This copy is never updated, even ifthe directory itself changes. This function is normally followed by one or more GET NEXT NODE DIRECTORY NODE DIRECTORY function SCAN call. Together, ENTRY function d s and one CLOSE these three functions worklike a SQL cursor (i.e., they use the OPENIFETCWCLOSE paradigm). "he memory bufferthat is used to store the node
r"l ij
Chapter 8: Database, Node, and DCSDirectoryManagement APIs "
11 :"
275
l
directory data obtained by the directory scan is automatically allocatedby this function and a pointer to that buffer (the buffer identifier) is stored in the Handle parameter. This identifier is then used by subsequent GET NEXT NODE DIRECTORY NODE DIRECTORY SCAN function calls to access the information ENTRY and CLOSE stored in thememory bufferarea.
Comments
IMultiple OPEN
NODE DIRECTORY SCAN functioncallscanbeissued against the same node directory.However, becausethe directory can change between each call, the directory enties copied into memory by eachcall may v q . IAn application can have up to eight node directory scans open at one time.
Connection This function can be called at any time; a connection to a DB2 Database Manager Requirements instance or to a DB2 database does not haveto be established first. Authorization No authorization is required to execute this function call.
see Also
GET NEXT NODE DIRECTORY ENTRY, CLOSE NODE DIRECTORY
Example
Thefollowing C++ program illustrates how to use the OPEN NODE DIRECTORY SCAN, GET NEXT NODE DIRECTORY ENTRY, and CLOSE NODE DIRECTORY SCAN functions to retieve entiesin thenode directory:
SCAN
/*
/*
NAME: CH8EX7.CPP PURPOSE: Illustrate How To Wee The Pollowing DB2 API Functione In A C++ Program:
/* /* /* DIRECTORY /* /*
NODE
DIRECTORY NODE /*
OPEN QET ENTRY DIRECTORY NEXT NODE CLOSE
*/
SCAN
/*
*/
/ / Include The Appropriate Header Piles #include *windowe.h, #include *ioetream.h, #include *eqlenv.h, #include *sqlca.h> / / Define The API-Claee Claee claee API-Claee {
/ / Attributes public: etruct eqlca eqlca;
*/ */
*/ */ */
SCAN
/*
*/ */
*/
Part 3: Application Programming Interface Functions / / Define The ShowNodes ( ) Member Function long API-Class::ShcnrNodes()
c
/ / Declare Tho Local M e m o r y Variables unsigned short Handle; unsigned short NodeCount; struct sqleninfo *Node-DirInfo = NULL;
/ / open The Node Directory Scan sqlenope(&Iiandle, BNodeCount, brsqlca); / / Scan The Node Directory BufferAnd Retrieve / / And Descriptions Stored There if (sqlca.sqlcode =I SQL-RC-OK)
All
Node Namee
{
tout << V o d e Name Descriptionn << endl; COUt << " for ( ;Nodecount I = 0; Nodecount-) {
/ / Retrieve TheNext Node Directory Entry sqlengne(Handle, brNode-DirInfo. brsqlca); / / Display The Node Directory -try if (sqlca.sqlcode == SQL-RC-OK) {
1
<< endl;
1
Retrieved
char NodeName [ 91 ; cout.width(14); cout.eetf(ios::left); strncpy(NodeNam0, Node-DirInfo-modename, 8); NodeName [el = 0; cout << NodeName; cout.width(30); cout.eetf(ioe::left); cout << Node-DirInfo-*comment e endl;
/ / Close The Node DirectoryScan ?md Free All Resources / / Obtained By The open Node Directory Scan A ~ I eqlencle(Handle, brsqlca);
1
1
/* /*
/ / Return TheSQLCA Return code return(sqlca.sqlcode);
TO
The
Calling
Function
*/ The Main Function
int main0 {
/ / Declare The LocalM e u m r y Variables long rc I SQL-RC-OKj
*/
Chapter 8: Database, Node, and DCS Directory ManagementAPIs / / Create An Instance Of The API-Claee Claee API-ClaeeExample; / / Qenerate And Display A List Of Available Nodee rc m Example. Shordlodee ();
1
/ / Return To The Operating return(rc) ;
Syetem
m m GET NEXT NODE DIRECTORY ENTRY purpose
The GET NEXT NODE DIRECTORY ENTRY function is used to retieve the next entry from the copy of the node directorythat was placed in memory bythe OPEN NODE DIRECTORY SCAN function.
Ssntax
SQL-API-RC SQL-I-FN
Parametem
Handle NodeDirEntry
SQLCA
eqlengne (unsigned ehort Rendle, struct eqleninfo **NodeDirEntry, etruct eqlca *SQLCAIi
The direct~ryscan buffer identifier that was returned by an associated OPEN NODE DIRECTORYSCAN function 4 1 . A pointer to the address of an sqleninfo structure where this function is to store the node diredory entryinformation retieved. A pointer to a location in memorywhere a SQLCommunications Area (SQLCA) data structure variable is stored. This variable returns either status information (if the function executed successfully)or error information (ifthe function failed)to the calling application.
Includes
#include <eqlenv.h>
Description
The GET NEXT NODE DIRECTORY function ENTRY is used to retrieve the next entry from the copy of the node directory that was placedin memory by the OPEN NODE DIRECTORY SCAN function. The informationretrieved is stored in a special structure, sqleninfo, that is defined in sq1env.h as follows: etruct eqleninfo
c
nodename char char
[8 I ;
local-lu [ 8 1 1
char partner_lu[8];
char
modet81 ;
/*
/* /* /* /* /* /*
/*
char comment 1301 I unsigned short cam_codepage;
/* /* /*
Node
name
*/
The logical unit ( S N A port) */ name ueedto eetablieh the connection*/ The logical unit (SNA port) name at */ the remote DB2 DatabaseManager */ instance */ The name of the trandeeion eervice */ mode used */ Optional node comment (deecription) */ Code page value used for the node */ comment */
Part 3: Application Programming Interface Functions */
unaigned short char networkid char protocol;
char
The NetBIOS LAN adapter number */ [ 8I ; The APPN network ID */ Identifies the protocol that is used */ /* to communicate with the node. This */ /* field can set be to */ /* SQL-PROTOCOL-APPC, SQL-PROTOCOL-NETB, */ / * SQL-PROTOCOL-APPN, SQL-PROTOCOL-TCPIP,*/ /* SQL-PROTOCOL-CPIC, SQL-PROTOCOL-SOCKS, */ */ /* SQL-PROTOCOL-IPXSPX, /* SQL-PROTOCOL-LOCAL, or */ /* SQL-PROTOCOL-NPIPE. */ sym_dest-name[8]; /* TheCPICsymbolicdestinationname of*/ partner remote /* the */
adapter;
/* /* /*
security-type;
/ * The CPIC security type. This field
*/
unsigned short
char char char
char
char
char char
*/
/*set can be to */ /* SQL-CPIC-SECURITY-NONE, */ /* SQL-CPIC-SECURITY-PROGRAM, */ /* or SQL-CPIC-SECURITY-SAME. */ hostname[2551; /* TheTCP/IP host name at the D82 */ /* database manager instance (server) */ service-name[l41 ; /* The TCP/IP service name of the DB2 */ /* database manager instance (server) */ fileeerver[l81; /* The NetWare file server name where */ /* the D82 server instance is */ */ /* regietered objectname[483; /* The name of a particular DB2 database*/ /* manager instance (server) that is */ /* stored in the Novell NetWare file */ bindery /* server */ inetance-name[E]; / * The LOCAL name of D82 a database */ instance /* manager */ computername[l5]; /* The server nodeta camputer name */ systen-name[21]; /* The D82systemname €or theremote . */
/* server *I char remote-inetname[81;/* ThenameoftheDB2serverinstance */ char catalog-node-type;/* type catalog node The */ unaigned short */ os-type I /* Theoperatingaystemused by theserver*/ );
Comments
H All character fields in the node diredory entry information buffer are right-padded
with blanks. H When this function is executed, the value in theNodeDirEntry parameter points to
the next nodediredory entry in thecopy of the node directorythat resides in memory. Each subsequent GET NEXT NODE DIRECTORY ENTRY function call retieves thenode directoryentry immediately followingthe current directory entry, unless there areno more directoryentries available (in which casean error is returned).
Chapter 8: Database, Node, and DCS Directory ManagementAPIs U You can use the value returned in theNumEntries parameter when the OPEN NODE DIRECTORY SCAN function is executed to set up a loop that scans through
the entire node directory by issuing QET NEXT NODE DIRECTORY function ENTRY calls, oneat a time,until the number of calls issued equals the number of entries found in thedirectory.
Prerequisites The OPEN NODE DIRECTORY SCAN function must be executed before this function is called. Connection This function can be called at any time; a connection to a DB2 Database Manager Requirements instance or to a DB2 database does not have to be established first. Authorization No authorization is required to execute this function call. See Also
OPEN
Example
See the example provided forthe OPEN
NODE
DIRECTORY
SCAN,
CLOSE
NODE
NODE
DIRECTORY
SCAN
function SCAN on page 265.
DIRECTORY
m m CLOSE NODE DIRECTORYSCAN Purpose
The CLOSE NODE DIRECTORY SCAN function is used to free system resourcesthat were allocated by the OPEN NODE DIRECTORY SCAN function.
syntax
SQL-API-RC
Parameters
Handle
SQL-API-FN sqlencls (unsigned short S t N C t eqlca
'
SQLCA
Handle,
*st?-)/
Thedirectory s c a n buffer identifier that was returned by an associated OPEN NODE DIRECTORY SCAN function d. A pointer to alocation in memorywhere a SQL Communications Area (SQLCA)data structure variable is stored. This variable returns either status information (if the function executed successfully)or error information (if the function failed) to the calling application.
Includes
#include<sqlenv.h>
Description
The CLOSE NODE DIRECTORY SCAN function is used to free system resources that were allocated by the OPEN NODE DIRECTORY SCAN function.
This function can be called at any time; a connectionto a DB2 Database Manager Requirements instance or to a DB2 database does not have to be established first. Authorization No authorization is required to execute this function call. see Also
OPEN NODE DIRECTORY SCAN,QET NEXT NODE DIRECTORY ENTRY
Example
See the exampleprovidedfor the OPEN
NODE
DIRECTORY
SCAN function on page265.
Part 3: Application Programming Interface Functions
CATALOG DCS DATABASE Purpose
The CATALOG DCS DATABASE function is used to store information abouta DRDA database in theDCS directory.
syntax
SQL-API-RC SQL-API-FN eqlegdad (struct sql-dir-entry struct splca
Parameters
DCSDirEntry SQLCA
*LJCSDirBntry,
*mm) i
A pointer to an sql-dir-entry structure that contains information about the DCS database that is t o be cataloged. A pointer to a location in memorywhere a SQLCommunications Area (SQLCA) data structure variable is stored. This variable returns either status information (ifthe function executed successfully)or error information (ifthe function failed) to the calling application.
Includes
#include <sglenv.h>
Description
The CATALOG DCS DATABASE function is used to store information abouta DRDA database in the DCS directory. Databases in thisdirectory are,accessed through an application requester, such as IBMs DB2 Connect product. Whena DCS directory entry has a database name that matches a database name in thesystem database directory, the application requester associated with the DCS database forwards all SQL requests made against that database to the remote server where the DRDA database physically resides. A special structure (sql-dir-entry) is used to pass characteristics about a DCS database to the DB2 Database Manager whenthis function is called. The sql-dir-entry structure is defined in sqlenv.h as follows: struct sql-dir-entry {
unsigned short
struct-id;
unsigned short release; unsigned shortcodepage; char ldb[91;char char ar[91; char char parm[513]
1;
comment[31]; tdb[191 i ;
This field */ /* must always be set to SQL-DCS-STR-ID. */ /* Releaselevelofthe DCS database entry*/ /* Code page valueusedforthe DCS */ comment /* database */ / * optional DCS database comment */ database /* Local name */ /*database Actual host name */ /* Application client library name */ /* Transaction program prefix, transaction*/ /* program name, SQLCODE mapping file */ /* name, disconnect option. and security */ /* option */
/ * The structure identifier.
NOTE:Each character field in thisstructure must be either NULL-terminated or blank, filled up to the specified length of the field.
Chapter 8: Database, Node, and DCS DirectoryManagement APIs Comments
~
271
I
W This function w ill automatically create a DCS directory if one does not already
exist. On OS/2 and Windows, the DCS directoryis stored on the disk drivethat contains the DB2 Database Manager instance currently being used. On all other systems, the DCS directoryis stored in thedirectory wherethe DB2 product was installed. W "he DCS directory is maintained outsideof the database. If a database is cataloged in the DCS directory, it must also be catalogedas a remote database in the system database directory.
W You can use the OPEN DCS DIRECTORY SCAN,GET DCS DIRECTORY GET DCS DIRECTORY
ENTRIES, ENTRY FOR DATABASE,andCLOSE DCS DIRECTORY
SCAN functions to obtain information about oneor more entries in the DCS
directory. W If directory cachingis enabled, database, node, and DCS directory filesare cached
in memory. An application's directory cacheis created during the first directory lookup. Becausethe cache is only refreshed whenan application modifies oneof the directory files, directory changes made by other applications mighttake not effect until the application is restarted. To refresh DB2's shared cache (server only), an application should stopand then restart the database. To refresh an application's directory cache,the user should stop and then restart that application. For more information about directory caching, refer to the GET DATABASE W A G E R CONFIGURATION function. W IBM's DB2 Connect product provides connections to DRDA application servers,
such as: -DB2 for OW390 on Systed370 and System/390 architecture host computers -DB2 for VM and VSE on Systed370 and Systed390 architecture host computers -0S/400 on Application System/400 (AS/400) host computers
Connection This function can be called at any time; a connection to a DB2 Database Manager Requirements instance or to a DB2 database does not haveto be establishedfirst. Authorization Only users with either System Administrator(SYSADM)authority or System Control (SYSCTRL) authority are allowed to execute this function call. See Also
UNCATALOG DCS DATABASE, OPEN DCS DIRECTORY SCAN, GET DCS DIRECTORY ENTRIES, GET DCS DIRECTORY ENTRY FOR DATABASE, CLOSE DCS DIRECTORY SCAN, CATALOG DATABASE
Example
"he following c++ program illustrates how to use the CATALOG DCS DATABASE function to catalog an alias for a DCS database:
/* /* /* /*
*/ NAME: CH8EX8 .CPP PURPOSE: Illustrate How To U60 The Following DB2 API Function In A C++ Program:
*/ */
*/
Part 3: Application Programming Interface Functions /*
/* /*
CATAtoa DCS DATABASE
/*
*/
/ / Include The Appropriate #include <windows.h> #include #include <sqlenv.h, #include <sqlca.h>
Reader
*/ */ */
Files
/ / Define The API-Class Class class API-Class {
/ / Attributes public: struct sqlca sqlca; / / Operations public : long CatalogDCSDB () ;
?; / / Define The CatalogDCSDBO Member Function long API-ClaSS::CatalOgDCSDB() {
/ / Declare The LocalM e m o r y Variables struct sql-dir-entry DCSInfo; / / Initialize The DCS Database Information Data Structure DCSInfo.struct-id = SQL-DCS-STR-ID; DCSInfo.release = 0; DCSInfo.codepage = 450; StrC9Y(DCSInfO.Cmu~tnt, "DB2 For MVS Database"); StrCpy(DCSInfO.ldb, "SAMPLEDB"); strcpy(DCSInfo.tdb, u ~ ~ ~ ~ " ) ; strcpy(DCSInfo.ar, strcpy(DCSInfo.parm, "") ; / / Catalog A New DC8 Database eqlegdad(hDCSInfo, hsqlca);
/ / If The New DCS Database WasCataloged, Display A Success / / Message if (sqlca.sqlcode == SQL-RC-OK) {
>
tout << "The DC8 database << DCSInfo.ldb; cout << hasbeen cataloged.nend11
/ / Return The SQLCA Return return(aqlca.eqlcode);
Code To The Calling
Function
?
/*
*/
fl l ! i !
i 273
Chapter 8: Database, Node, and DCS Directory ManagementAPIs /*
*/
The Main Function
/*
*/
int main() {
/ / Declare The Local Memory Variables long rc .I SQL-RC-OK;
/ / Catalog A New DCS Database rc I Example.CatalogDCSDB ( ) ;
1
/ / Return To The Operating Wetem return(rc) ;
UNCATALOG DCS DATABASE The UNCATALOG DCS DATABASE function is used to delete an entry from the DCS directory.
syntax
SQL-API-R~ SQL-API-FN eplegdel (struct eql-air-entry struct eqlca
Parameters
DCSDirEntry
SQLCA
*DCSDirBntty, *SPLcA) ;
A pointer to an sql-dir-entry structure that contains information about the DCS database that isto be uncataloged. Apointer to alocation in memorywherea SQL Communications Area (SQLCA) data structure variable is stored. This variable returns either status information (ifthe function executed successfully)or error information (ifthe function failed) to the calling application.
Includes
#include <sglenv.h>
Description
The UNCATALOO DCS DATABASE function is used to delete an entry from the DCS directory. Beforethis function can be executed, a special structure (sql-dir-entry) must be initialized with information about the DCS database that is to be uncataloged. Refer to the CATALOG DCS DATABASE function for a detailed descriptionof this structure. only two fields of this structure are used by the UNCATALOG DCS DATABASE function: struct-id and ldb. The database name stored in theldb field of this structure specifies the local name of the DRDA database that is to be uncataloged.
Comments
I A DCS database should always be catalogedin the system database directory as a remote database. Therefore, when aDCS database i s uncataloged, its correspondingentry in thesystem database directory shouldbe uncataloged (with the UNCATALOG DATABASE function).
Part 3 Application Programming Interface Functions YOU c8n use
the OPEN DCS DIRECTORY SCAN,GET DCS DIRECTORY ENTRIES, GET DCS DIRECTORY ENTRY FOR DATABASE,andQLOSE DCS DIRECTORY
SCAN functions to obtain
information aboutone or more entries in the DCS
directory. If directory cachingis enabled, database, node, and DCS directory filesare cached in memory. An application’s diredory cache is created during the firstdirectory lookup. Becausethe cache is only refreshed when an application modifies oneof the directory files, directory changes made by other applications might notbe effective until theapplication is restarted.To refresh DB2’s shared cache (server only), an application should stopand then restart thedatabase. To refresh an application’s directory cache, the user should stopand then restart that application. For more information about directory caching, refer to the GET DATABASE
MANAGER
function. CONFIGURATION
Connection This function can be called at any time; a connection to a DB2 Database Manager Requirements instance or to a DB2 database does not have to be established first.
Authorization Only users with either System Administrator(SYSADM) authority or System Control (SYSCTRL) authority can execute this function call. See Also
CATALOG DC8 DATABASE’OPEN DCS DIRECTORY SCAN,GET DCS DIRECTORY ENTRIES,GET DCS DIRECTORY ENTRY FOR DATABASE, CLOSE DCS DIRECTORY SCAN, UNCATALOG DATABASE
Example
The following c++program illustrates how to use the UNCATALOG DCS DATABASE function to uncatalog an alias for a DCS database:
/* NAME:
/*
/*
CH8EX9.CPP PURPOSE: Illuetrate How To Uee The Following DB2 API Function In A C++ Program:
/* /* /*
UNCATALOQ DCS DATABASE
*/ */ */ */
*/ */
*/
/* / / Include The Appropriate Header Files #include avindowe.h, #include doetream.h, #include aqlenv.h> #include aqlca.h,
/ / Define The API-Claee Claee c l a m MI-Claes
i / / Attribute0 public: etruct eqlca eqlcat
Chapter 8: Database, Node, andDCS Directory ManagementAPIs / / operations public : long UncatalogDCSDB( ) ; ?I
/ / Define The UncatalogDCSDB() Member Function long API-Cla8s::UncatalogDCSDB~)
i '
/ / Declare The Local Memory Variables etruct sal-dir-entry DCSInfo; / / Initialize TheDC8 Database Information Data DCSInfo.struct-id = SQL-DCS-STR-ID; DCSInfo.release E 0; DCSInfo.codepage = 450; strcpy(DCSInfo.c~lrrm~nt, "DB2 For MVS Database"); strcpy(DCSInfo.1db. "SAMPLEDB"); strcpy(DCSInfo.tdb, "SAMPLE"); strcpy(DCSInfo.ar, ""1; strcpy(DCSInfo.panm, "") ;
Structure
/ / Uncatalog The specified DCS Database sqlegdel(&DCSInfo, &sqlca)t / / If The DCS Database Was Uncataloged, Display A Success Messaga if (sqlca.sqlcode == SQL-RC-OK)
c
cout ** "The DCS database *' DCSInfo.1db; cout << hasbeen uncataloged."endl; *#
1 / / Return TheSQLCA Return return(sqlca.sqlcode);
CodeTo The
Calling
Function
1
/* /*
*/
*/
The Main Function
int main()
i / / Declare The LocalM e m o r y Variables long rc .I SQL-RC-OK;
/ / Create An Instance O f The API-Class Class API-ClassExample; / / Uncatalog A DCS Database
rc
I
Node Example.UncatalogDCSDB();
/ / Return TO The return(rc)i .
1
operating
System
Part 3: Application Programming Interface Functions .
.
.. .
OPEN DCS DIRECTORY SCAN
Purpose
The OPEN DCS DIRECTORY SCAN function is used to obtain a count of the number of entries found in theDCS directory.
syntax
SQL_API-RC SQL-API-FN
Parameters
NumEntries
SQLCA
sqlegdsc (short *Nummtrierr, struct sqlca *SPLCA);
A pointer to a location in memory where this function i s to store a count of the number of entries found in theDCS directory. A pointer to a location in memorywhere a SQLCommunications Area (SQLCA)data structure variable is stored. This variable returns either status information (ifthe function executed successfully)or error information (ifthe function failed)to the calling application.
Includes
#include <sqlenv.h>
Description
The OPEN DCS DIRECTORY SCAN function is used to obtain a count of the number of entries found in theDCS directory.An application canuse this number to determine the amount of memory it needs to allocate in order to retrieve information about each DCS directory entry available. Once the correct amountof memory is allocated, you can use the GET DCS DIRECTORY ENTRIESfunction and the GET DCS DIRECTORY function to retrieve information about eachentry stored in ENTRY FOR DATABASE the DCS directory.
This function can be called at any time;a connection to a DB2 Database Manager Connection Requirements instance or to a DB2 database does not haveto be established first.
Authorization No authorization is required to execute this function call. See Also
CLOSE DCS DIRECTORY SCAN,GET DCS DIRECTORY ENTRIES, GET DCS DIRECTORY ENTRY FOR DATABASE
Example
ThefollowingC++program
illustrates how to use the OPEN DCS DIRECTORY SCAN, GET DCS DIRECTORY ENTRIES,GET DCS DIRECTORY ENTRY FOR DATABASE, and CLOSE DCS DIRECTORY SCAN functions to retrieve the information associated with the DCS directory entry for a specified database:
/* /* /* /* /*
/* /* /* /*
CH8EXlO.CPP PURPOSE: Illustrate How To Use The Following DE2 API Functions In A C++ Program:
N A M E :
OPEN DCS DIRECTORY SCAN
GET DCS DIRECTORY ENTRIES GET DCS DIRECTORY ENTRY FOR DATABASE CLOSE DC8 DIRECTORY SCAN
*/ */ */
*/ */ */ */
*/ */
Chapter 8: Database,Node,andDCSDirectoryManagement /* /*
1::/ 277
APIs
____
*/
/ / Include The Appropriate #include <windoPre.h> #include #include <eqlenv.h> #include <eqlca.h>
Header
*/
Files
/ / Define The API-Claee Claee claee API-Claee {
/ / Attributes public: struct eqlca eqlca; / / Operatione public : long ShowDCSDBInf o() ;
1; / / Define The ShowDCSDBInfo( ) Member long API-ClaeerrShowDCSDBInfo()
Function
I / / Declare The Local Memory Variablee ; DCSCOunt short etruct eql-dir-entry *DCS-DirInfo = NULL) char Namet91; / / Open The DCS Directory Scan eqlegdec(&DCSCount, &eqlca);
/ / Scan The DCS Database Directory / / About A Specific DCS Databaee if (eqlca.eqlcode -m SQL-RC-OK)
I
Buffer And Retrieve
Information
/ / Copy The DC8 Directory EntriesInto A Weer-Allocated / / Storage Buffer DCS-DirInfo = (etruct eql-dir-entry *) aizeof(etruct eql-dir-entry)); malloc(DCSCount eqlegdgt(&DCSCount. DCS-DirInfo, sreqlca); / / Initialize TheDC8 Information Data Structure DCS-DirInfo->etruct-id = SQL-DCS-STLID; etrcpy(DCS-DirInfo->ldb, uSAMPLEDBn);
/ / Retrieve The DC8 Directory Entry ForThe Specified DCS / / Database FromThe Memory Storage Buffer eqlegdge(DCS-DirInfo, esqlca); / / Dieplay The DC8 Directory Entry Retrieved c a t << "DCS Database Name Database Name Deecription"; cout << endl; COUt << U "8 cout << endl;
Memory
Part 3: Application Programming Interface Functions cout .width(20) ; cout.eetf(ioe::left); e t ~ C p Y ( N ~ e DCS-DirInfo->l&, . 8); Namet81 = 0; cout << Name; cout.width(16); cout.eetf(ios::left); StrnCpY(Nmte, DCS-DirInfo->tdb, 8 ) ; Namet81 0; cout (< Name; cout << DCS-DirInfo->conrment (< endl; / / Cloee TheDC9 Directory / / Memory Storage Buffer
ScanAnd Free The User-Allocated
eqlegdcl(&sqlca); free(DCS-DirInfo);
1
1
/* /* /*
/ / Return The SQLCA Return return(sqlca.eqlcode);
The
Main
Code TO The
Calling
Function
*/ */ */
Function
int main() {
/ / Declare The Local long rc = SQL-RC-OK;
Memory
Variables
/ / Create An Instance Of The API-Clam Class API-ClaeeExample; / / Dieplay Information About A DCS Databaee rc = Example.ShowDCSDBInfo0; / / Return To The return(rc);
Operating
System
1
P4 FM GET DCS DIRECTORY ENTRIES purpose
The GET DCS DIRECTORY ENTRIESfunction is used to transferacopyofthe DCS directory to a user-allocated memory storage buffer that i s supplied by the calling application.
syntax
SQL-API-RC SQL-API-FN eqlegdgt (short
Parameters
*Nkuul.?ntriee, etruct eql-dir-entry etruct eqlca
NumEntries
*XSDirBntries,
*SPLcAl ;
A pointer to alocation in memorywhere the numberof
Chapter 8: Database, Node, and DCS DirectoryManagement APIs
l
..
2 7.1 .j . ..
"
.
sql-dir-entry structures contained in the user-allocated memory storage buffer is stored. When this function is executed, the number of entries actually copied fromthe DCS directory to the userallocated memorystorage buffer is stored in the location referred to by this parameter. DCSDirEntries A pointer to an arrayof sql-dir-entry structures where this function is to copy the DCS directory entry information retrieved. SQLCA
A pointer to a location in memory where a SQL Comm~cations Area (SQLCA) data structurevariable is stored. This variable returns either status information (if the function executed successfully)or error information (ifthe function failed) to the calling application.
Includes
#include <sqlenv.h>
Description
The GET DCS DIRECTORY ENTRIES function is used to transfer a copyof the DCS directory to a user-allocated memory buffer. Beforethis function can be executed, a memory storage buffer containing an array of a sql-dir-entry structures mustbe allocated. Referto the CATALOG DCS DATABASE function for a detailed description of this structure. You can determine the amount of memory needed forthis storage buffer by multiplyingthe number of entries found in theDCS directory withthe OPEN DCS DIRECTORYSCAN function by the size of a single sql-dir-entry structure. Once a memory buffer is allocated, the number of DCS directory withentries that the buffer can hold(the number of elements in the arrayof sql-dir-entry structures) must be stored in theNumEntries parameter. When this function is executed, the number of DCS directory entries that areactually copied t o the memory storage buffer is returned in the NumEntries parameter. By comparing the "before" function call and "after" function callvalues of this parameter, an application candetermine whether all DCS directory enties were copied to the storage buffer area.
Comments
W If this function is executed when a copyof the DCS directory entries is already in
memory, the previous copy will be replaced bya new copy of DCS directory entries. W If all DCS directory entries arecopied to the user-allocated memorystorage area, the DCS directory scan will automaticallybe closed, and all resources allocated by the OPEN DCS DIRECTORY SCANfunction will be released. W If one or more DCS directory entries were not copied to the user-allocated memory storage area, you can make subsequent calls to this function to copy them. If these enties are not needed, you can call the CLOSE DCS DIRECTORY SCAN function to free system resources that were allocated by the OPEN DCS DIRECTORY SCAN function.
Prerequisites The OPEN DCS DIRECTORY SCANfunction should be executed before this function is called (so the calling application can allocatea memory storage buffer that is large enough t o hold the entriesstored in the DCS directory).
,
Part 3: Application Programming Interface Functions Connection This function can be called at any time; a connection to a DB2 Database Manager Requirements instance or to a DB2 database does not haveto be established first. Authorization No authorization is required to execute this function call.
see Also
OPEN DCS DIRECTORY SCAN,GET DCS DIRECTORY DCS DIRECTORY SCAN
Example
See the example provided for the OPEN DCS DIRECTORY
ENTRY FOR DATABASE,
CLOSE
SCAN function on page 276.
GET DCS DIRECTORY ENTRY FOR DATABASE purpose
The GET DC8 DIRECTORY ENTRY FOR DATABASE function is used to retrieve an entry for a specified database from the copy of the DCS directory that was placed in memory by the GET DCS DIRECTORY ENTRIESfunction.
syntax Parameters
DCSDirEnhy
SQLCA
A pointer to the address of an sql-dir-entry structure where this function is to store the DCS directory entry information retrieved. A pointer to a location in memory where a SQL Communications Area (SQLCA)data structurevariable is stored. This variable returns either status information (if the function executed successfully)or error information (if the function failed)to the calling application.
Includes
#include <sqlenv.h>
Description
The GET DCS DIRECTORY ENTRYFOR DATABASE function is used to retieve an entry for a specified database from the copy of the DCS directory that was placedin memory by the GET DCS DIRECTORY ENTRIESfunction. Before this function is executed, the local name of the database whose DCS directory entry isto be retrieved must be stored in the Zdb field of a sqZ-dir-entry structure. Refer to the CATALOG DCS DATABASE function for a detailed description of this structure. The remaining fieldsof this structure arefilled in when this function executes.
This function canbe called at any time; a connection to a DB2 Database Manager Connection Requirements instance or to a DB2 database does not haveto be established first.
Authorization No authorization is required to execute t h i s function call.
see Also
CATALOG DCS DATABASE,UNCATALOG DCS DATABASE, OPEN DCS DIRECTORY SCAN,GET DCS DIRECTORY ENTRIES, CLOSE DCS DIRECTORY SCAN
Chapter 8: Database, Node, and DCS Directory ManagementMIS
, __ ..
"
Example
See the example provided forthe OPEN DCS DIRECTORY
SCAN function on page
"
276.
m m CLOSE DCS DIRECTORYSCAN Purpose
The CLOSE DCS DIRECTORY SCAN function is used to free system resourcesthat were allocated by the OPEN DC5 DIRECTORY SCAN function.
syntax Parameters
SQLCA A pointer to a location in memory wherea SQL Communications Area (SQLCA) data structurevariable is stored. This variable returns either status information (if the function executed successfully) or error information (if the function failed) to the calling application.
Includes
#include<eqlenv.h>
Description
The CLOSE D Cs DIRECTORY SCAN function is used to free system resourcesthat were allocatedby the OPEN DCS DIRECTORY SCAN function. This function should be called onlyif one or more DCS directory entries were not copied to the user-allocated memory storage area by the GET DCS DIRECTORY ENTRIESfunction.
Connection This function can be called at any time; a connection to a DB2 Database Manager Requirements instance or to a DB2 database does not have to be established first. Authorization No authorization is required to execute this function call. See Also
OPEN DCS DIRECTORY SCAN,GET DCS DIRECTORY DIRgCTORY ENTRY FOR DATABASE
Example
See the example provided forthe OPEN DC8 DIRECTORY
ENTRIES,
GET DC8
SCAN function on page 276.
m m REGISTER Purpose
The REGISTER function is used to register a DB2 database server at a Novell NetWare file server.
Parameters
Registry
Specifieswhere on the networkfile server to register the DB2 database server. For now, this parameter must be set t o
RegisterInfo
A pointer to a sqle-reg-nwbindery structure that contains a valid
SQL-NWBINDERY.
Part 3 Application Programming Interface Functions
SQLCA
NetWare user ID and password that can be used to access the network file server. A pointer to a location in memorywhere a SQL Communications Area (SQLCA)data structurevariable is stored. This variable returns either statusinformation (ifthe function executed successfully)or error information (if the function failed) to the calling application.
Includes
#include <eqlenv.h>
Description
The REGISTER function is used to register a DB2 database server at a Novell NetWare file server. Whenthis function is executed, the DB2 database server's network address is stored in a specified registry on the file server, whereit can be retrieved by any client applicationthat uses the IPX/SPX communication protocol. Before this function can be called, a valid user ID and passwordthat can be used to access the Novell network server must be stored in a special structure, sql-reg-nwbindery, which is defined in sq1env.h as follows: etruct eqle-reg-nwbindery {
char uidt491;
uneigned reserved-1-1; ehort char pewat1291 I uneigned reeerved-len-2i ehort
/* /* /* /* /* /* /*
The user ID that is to be ueed to log into the Novell Netwars file server Reeerved The paeeword that ie to be ueed to validate the user ID Reeerved
*/ */ */ */
*/
*/
*/
)i
If the value specifiedin theRegistry parameter is 801,-NWBINDERY (this is the only value currently supported), the NetWare user ID and password storedin the sql-reg-nwbindery structure isused to log onto the neeork server specified in the fileserver parameter of the DB2 Database Manager configuration file. This function determines the IPX/SPX address of the workstation to register (which is the workstation from whichit was invoked),and then creates an object in thespecified fileserver bindery usingthe DB2 Database Manager objectname specified in the objectname parameter of the DB2 Database Manager configuration file. The Ipx/spx address of the server is stored as anattribute in that object. In order fora client to connect or attach to the registered DB2 server using this information, it must first catalog an IPWSPX node (using the same fileserver and objectnume values) in its node directory. Comments
The Navel1 NetWare user ID and password specified in the sqle-reg>wbindery structure musthave supervisoryor equivalent authority. This functioncan onlybe issued locally froma DB2 database server workstation. Remote executionof this function is not supported.
After IPX/SPX support software is installed and configured, the DB2 database server should be registered on the network server (unless IPX/SPX clients will only
be using direct addressing to connect to this DB2 server).
W Once a DB2 database server is registered on the network server,if you need to reconfigure IF'WSFX or change the DB2 server's network address,deregister the DB2 server from the network server (with the DEREGISTER function) and then register it again (usingt h i s function) after the changes have been made. W This function cannot be used in applications that run on the Windows or the Windows NT operating system. Connection This function can be called at any time; a connection to a DB2 Database Manager Requirements instance or to a DB2 database does not haveto be established first. Authorization No authorization is required to execute this function call. See Also
DEREGISTER
Example
Thefollowing C++program illustrates how to use the REGISTER function and the DEREGISTER function to register and deregister the currentDB2 database server at a NetWare file server:
/* /* /* /*
NAME: CHEEXl1.CPP PURPOSE: Illuetrate How To Wee The Following DB2 API Function In A C++ Program:
*/ */ */
*/
/*
*/ */
REQISTER DEREQISTER
/* /* /*
*/ */
/ / Include The Appropriate #include <windows. h> #include #include <eqlenv.h> #include <eqlutil.h> #include <eqlca.h>
Header
Filee
/ / Define The API-Claee Claee claee API-Claee
I / / Attributes public : etruct eqlca sqlca;
/ / Operations public : long Re&terservcrr ()1 long DeregieterServerO?
l? / / Define
The RegieterServer() Member Function
Part 3: Application ProgrammingInterface Functions long API_Class::RegisterServer() {
/ / Declare The Local Memory Variables struct sqle-reg-nwbindery NIQInfo; DBManagerInfo; SqlfUpd StlXCt struct sqle-start-options StartOptions; struct sqleabstopopt StopOptions; char Pileserver1101 ; / / Initialize The DB2 Database / / Parameter Structure
Manager Configuration
strcpy(FileServer, '~PCEOSTu) ; DBManagerInfo.token = SQLP-KTN-FILESERVER; DBManagerInfo.ptrvalue = (char *) Fileserver; / / Store The Novel1 NetWare Pile Server / / Database Manager Configuration File
Name In The DB2
sqlfusys(1, PDBManagerInfo, Psqlca); / / Initialize / / Structure
The Stop DB2 Database Manager Options
-
0; StopOptions.ieprofile strcpy(StopOptions.profile, StopOptions.isnodenum = 0; 8topOptions.nodenum = 0; StopOptions.option = SQLE-NONE; Stop0ptions.callerac P SQLE-DROP; / / Stop The D82 Database Manager Server Processes SqlepStp(h8tOROptiOnS, &SqlCa); / / Initialize The Start DB2 Database Manager Options / / Structure strcpy(StartOptions.sqloptid, SQLE-STARTOPTID-V51); 8tartOptions.isprofile = 0; strcpy(StartOptions.profile, ""); StartOptione. isnodenum = 0; 8tartOptions.nodenum = 0; 8tartOptione.option = SQLE-NONE; StartOptions. ishostname = 0;
strcpy(StartOptions.hostname, ""); StartOptions.ieport = 0; StartOptione .port= 0; 8tartOptione.isnetname 0; strcpy(ltartOptions.netname, 8tartOptions.tblspace-type = SQLE-TABLESPACES-LIKE-CATALOG; StartOptions.tblspace-node P 0; StartOptions.iscomputer P 0; strcpy(StartOptions.cam(puter, ""1; StartOptiOnS.pUSerName P NULL; Startoptions.pPassword NULL;
-
-
/ / Re-Start The DB2 Database Manager Server Processes (This / / Will Make DB2 See The Changes Made To The Configuration
Chapter 8: Database, Node, and DCS Directory ManagementM I S / / File sqlepstart(hStartOptions, hsqlca); / / Initialize The NetWare Registry strcpy(NWInfo.uid, "userid"); strcpy(NWInfo.pswB, "password");
Information
/ / Register The CurrentDB2 Server On A NetWare sqleregS(SQL-NWBINDERY, hNWInfo, hsplca);
Data
File
/ / If The DB2 Server Was Registered On A NetWare / / Display A Success Message if (splca.sqlcode =p SQL-RC-OK)
Structure
Server
FileServer,
I 1
cout << "The DB2 Server has been registered at the cout << 'wetware file server.tr << endl;
/ / Return The SQLCA Return return(sqlca.sqlcode);
Code To The Calling
l';
Function
1
/ / Define The DeregisterServerO Member Function long API-Class::DeregisterServer()
I / / Declare The Local Memory Variables struct sqle-reg-nwbindery NWInfo;
/ / Initialize The Netware Registry Information Data Structure ; etrcpy(mnfo.uid, 8~ueerid8') strcpy(mnfo.pswd, "password"); / / Deregister The Current D82 Server From A NetWare sqledreg(SQL-NWBINDERY, PNWInfo, hsplca); / / If The DB2 Server Was Deregistered On A NetWare / / Display A Success Message
if (splca.sqlcode
1
1
/* /*
=P
File
File
/ / Return The SQLCA Return return(sqlca.sqlcode);
Code To The Calling
int main()
I LocalMemory Variables I SQL-RC-OK;
";
Function
*/ The Main Function
The
Server,
SQL-RC-OK)
tout << "The DB2 Server has been m-registered at the cout e< "Netware file server." << endl;
/ / Declare rc long
Server
*/
Part 3 Application Programming Interface Functions / / Create An Instance O f The API-Class Class API-ClassExample; / / Register A DB2 Server With A NetWare rc = $xample.RegisterServer() ;
File
/ / Unregister A DB2 Server With A NetWare if (rc == SQL-RC-OK) rc = Example.DeregisterServer();
/ / . Return To The return ( rc ) ;
Operating
Server
File
Server
System
P4 B M DEREGISTER The DEREGISTER function is used to deregister a DB2 server (removea DB2 server‘s network address) from a registry at a Novell NetWarefile server.
syntax
SQL-API-RC
Parameters
Registry
SQLSI-FN
sqledreg (unsigned short void StNct splca
Regi8tz-y. *RegisterInfo, *SQLCA);
Indicateswhere on the networkfileserver to deregister the DB2 database server. For now, this parameter must be set to SQL-NWBINDERY.
RegisterInfo
SQLCA
A pointer to a sqle-reg-nwbindery structure that contains a valid NetWare user ID and password that can be used to access the network server. A pointer to a location in memorywhere a SQL Communications Area (SQLCA)data structurevariable is stored. “his variable returns either statusinformation (if the function executed successfully)or error information (ifthe function failed)to the calling application.
Includes
#include <eqlenv.h>
Description
The DEREGISTER function is used to deregister a DB2 server from a registry at a Novell NetWare file server. Before calling this function, you must store a valid user ID and password that can be used to access the Novell network serverin a special sql-reg-nwbindery structure. Refer to the REGISTER function for a detailed description of this structure.
Comments
W TheNovellNetWare user ID and password specified in the sqle-reg-nwbindery
structure musthave supervisoryor equivalent authority. W This function can only be issued locally from a DB2 database server workstation.
Chapter 8: Database, Node, and DCS Directory ManagementAPIs
! 287
i
'
i,
m
l-~.-
"
Remote executionof this function is not supported. W Once a DB2 database server is registered on the network server,if you need to
reconfigure IPWSPX or change the DB2 server's network address,deregister the DB2 server from the network server (using this function), and then register it again (withthe REGISTER function) aRer the changes have been made. H This function cannotbe used in applications that run on the Windows or the Windows NT operating system.
Connection This fundion can be called at any time; a connection to a DB2 Database Manager Requirements instance or to a DB2 database does not haveto be established first. Authorization No authorization is required to execute this function call. See Ale0
REGISTER
Example
See the exampleprovided for the REGISTER function on page283.
This Page Intentionally Left Blank
DB2 uses tables to store data andtable spaces to logically group tables and other data objects. This chapter is designed to introduce youto the setof DB2 A P I functionsthat areused to obtain information about database table spaces and to reorganize data in and update statistics for database tables. The first part of this chapter provides a general overview of table spaces and table space containers.Then, informationis provided onreorganizing and updating the statistics for a database table. Finally, a
Part 3: Application Programming Interface Functions
Table Spaces and Table Space Containers Table spaces are designed to provide a level of direction between user tables and the database in which they reside. Two basic types of table spaces exist:Database-Managed Space (DMS) table spaces, whichsupport raw devices and files, and System-Managed Space (SMS)table spaces, whichsupport directories. You can retrieve information about all table spaces that have been defined for a particular database by calling the TABLESPACE QUERYfunction. This function retrieves information about all table spaces that have been defined for a single database and copies it into a large memory storage buffer. If several table spaces have been defked for a database, you can retrieve this information in smaller pieces by callingthe OPEN TABLESPACE QUERY, FETCH TABLESPACE QUERY, and CLOSE TABLESPACE QUERY functions. Together,these three functions work like an SQL cursor (i.e., they use the OPENFETCWCLOSE pardigm). A single table space can consistof one or more containers;for example, a DMS table space can reference many Merent drives and/or directories.You can retrieve information about all containers that have been defined for a specific table space by callingthe TABLESPACE CONTAINER QUERY function.This function retrieves information about all table space containers that have been defined fora single table space and copiesit into a large memory storage buffer. If a.table space consists of many table space containers, you might want to retrieve this information in smaller pieces. You can do this bycalling the OPEN TABLESPACE CONTAINER QUERY, FETCH TABLESPACE CONTAINER QUERY, and CLOSE TABLESPACE CONTAINER QUERY functions. These three functionswork in a manner similar to their OPEN/F)2TCH/CLOSE TABLESPACE QUERY counterparts.
Reorganizing Table Data Database tables that undergo many updates and deletes will, in time, become fragmented (i.e.,the table and its indexes will contain empty space). As a table becomes fragmented, its performance drops.DB2 provides a utility that can reorganize the datain a table in order to reclaim this lost space. You can invoke this utility from within an application by calling the REORGANIZE TABLE function. Table reorganization exports data (in some particular order) to an external file, deletes all entries in the table, and then imports the data back. This process can bea time-consuming operation and can require a large amount of disk space as tables grow in size. Unfortunately, while a database table i s being reorganized,no other applications and/or users can access it. This restriction makes table reorganization a difficult task to add to the normal flow of an application. Therefore,applicationsthat call the REORGANIZE TABLE functionshould only be executed when they will not significantly affect other users andapplications.
!
MIS
Chapter 9: Table and Table Space Management
I
211
i
1""1
Updating Table Statistics '
.
The system catalog tables that are created as a part of a database contain, among other things, statistics on all user-defined tables and indexes. Database statistics include items such as the number of rows in a table, information about indexesthat have been created for a table, and the overall sizeof a table. Thesestatistics areimportant, because they are used by the SQL optimizerto build the most optimal access plans for eachSQL statement used in an embedded SQL application. Unfortunately, these statistics arenot automatically kept to update. This means that if you develop an application that accesses a particular database table, and you later create an index forthat table, the staticSQL statements in your application will not be able to take advantage of the new index (i.e., performance will not be increased). An application canupdate statistics for a specified table by calling the RUN STATISTICS function. Once a table's statistic information is updated, you need to rebind all packages that access the table so they can take full advantage of the updated statistical information.
F 4 FW The DB2 Table and Table Space
Management Functions Table 9-1 lists the DB2 API functions that are used to manage tables and table spaces. . Each of these functions are described in detail in the remainder of this chapter.
-
Table 9-1 Table and Table Space ManagementAPls . .
~
m
^
~
~
~
~
.
~
.
"
~
,
~
.
~
~
-
~
~
" "
~
-
"
l
-
n
i
~
. ..c
-
.
~
,
.
~
~
*
~
~
~
c
r
-
"
"
~
-
~
~
~
~
~
~
~
~
~
~
Fiknction Name
D e s aril?tion
OPEN
Obtains a count of the numberof table spaces that have been defined for the currentconnected database.
TABLESPACEQUERY
FETCH
TABLESPACEQWRY
Retrieves andcopies a specifiednumber of rows of table space information to a user-allocated memorystorage buffer.
CLOSE TABLESPACE QWRY
Ends a table space query request that was madeby the OPEN TABLESPACE QWRY function.
TABLESPACE QWRY
Stores a copy of all table space information available for the current connected database ina large DB2-allocated memory storage buffer.
SINGLE
a single, currently defined table Retrieves information about space.
TABLESPACEQWRY
GET TABLESPACE STATISTICS
Retrieves information about the space utilization of a table space.
OPEN
Obtains a count o f the number of tablespacecontainers that have been definedfor either a specifiedtable spaceor for the current connected database.
TABLESPACE
CONTAINER QWRY
"
-
,
~
~
~
I . ,
Part 3: Application Programming Interface Functions
L " ,
FETCH
TABLESPACE
CONTAINER QWRY
Retrievesand copies a specified number of rows of tablespace container informationto a user-allocated memorystorage buffer.
CLOSE
TABLESPACE
CONTAINER
Endsatablespacecontainerqueryrequest that wasmade by the OPEN TABLESPACE CONTAINER Q W R Y function.
TABLESPACE
FREE
CONTAINER
MEMORY
REORQANIZE TABLE RUN STATISTICS
QUERY
QUERY
Stores a copy of all table space container information available for either a specified table space or for the currentconnected database in a largeDB2-allocated memorystorage buffer. Frees memory that was allocated by either theTABLESPACE QUERY or the TABLESPACE CONTAINER Q W R Y function. Reorganizes a table so that fragmented data is eliminated and information is compacted. Updates statistical information about a table and anyor all of its associated indexes.
Chapter 9: Table and Table Space Management MIS
OPEN TABLESPACE QUERY The OPEN TABLESPACE QUERY function is used to obtain a count of the number of table spaces that have been defined for the currentconnected database.
Parameters
SQLCA
QueryOptwns
A pointer to a location in memory where a SQL Communications Area(SQLCA) data structurevariable is stored. This variable returns either statusinformation (ifthe function executed successfully)or error information (if the function failed)to the calling application. Specifies the type of table spaceinformation that is to be retrieved. This parameter must be set to one the following values: SQLB-OPEN-TBS-ALL
Retrieve information aboutall table spaces that have been defined forthe database. SQLB-OPEN-TBS-RESTORE
Only retrieve information abouttable spaces that arebeing restored by the user’s agent.
Num!lbbleSpaces A pointer to a location in memory where this function is to store the actual number of table spaces foundin thecurrent connected database that meet the specified criteria (QueryOptions). Includes
#include <eqlutil.h>
Description
The OPEN TABLESPACE QUERY function is used to obtain a count of the number of table spaces that have been defined for the currentconnected database. This function is normally followed by one or more FETCH TABLESPACE QUERY functions calls and one CLOSE TABLESPACE QUERY function call. Together, these three functions work like an SQL cursor (i.e., they use the OPEN/J?ETCWCLOSE paradigm). An application can usethese three fundions to scan a list of table spaces and search for specific information.
Comments
Only one table space querycan be active at one time. The first time this function is c a l l e d , a snapshot of the table space information available is buffered in the agent that is servicing the application. Ifthe application callsthis function again, this snapshot is replaced with refreshed information. M Because lockingis not performed by this function, the information returned in the
Part 3 Application Programming Interface F’unctions snapshot buffer may not reflect recent changes made byanother application.
Connection This function can only be called if a connection to a database exists. Requirements Authorization Only users with System Administrator(SYSADM) authority, Database Administrator (DBADM) authority, System Control(SYSCTRL) authority, or System Maintenance (SYSMAINT) authority can executethis function call. See Also
FETCH TABLESPACE QUERY, CLOSE TABLESPACE QUERY, TABLESPACE QUERY, SINGLE TABLESPACE QmRY
Example
Thefollowing C++ program illustrates how to use the OPEN TABLESPACE QUERY, FETCH TABLESPACEQUERY, and CLOSE TABLESPACEQUERY functions to retrieve information aboutthe table spaces defined fora database:
/*
/* /* /* /* /* /* /* /*
*/
NAME: CHJEX1.SQC PURPOSE: Illustrate How To Wee The Following DB2 API Functione In A C++ Program:
TABLESPACE
OPEN TABLESPACE QUERY FETCH QUERY TABLESPACE QUERY CLOSE
/*
/ / Include The Appropriate #include <windows. h> #include #include <eqlutil.h> #include <eql.h>
Header
Files
/ / Define The API-Claee Claee class API-Claee
i / / Attributes public : struct eqlca eqlca;
1;
/ / Operatione Public : long QetTSpaceInfoO;
/ / Define The QetTSpaceInfo() Member Function long API-Claee::QetTSpaceInfo()
i / / Declare The Local Memory Variables uneignedTSCount long ; etruct SQLB-TBSPQRY-DATA *TableSpaceHead; BtruCt SQLB-TBSPQRY-DATA *TableSpaceData;
*/ */ */ */ h/
*/ */ */ */
Chapter 9: Table and Table Space Management APIs unsigned long
MrmRoors ;
/ / Allocate AMemory Storage Buffer TabhSpaCeData = (StYXCt SQLB-TBSPQRY-DATA *) malloc(TSC0unt * sizeof(StYXct SQLB-TBSPQRY-DATA));
/ / Initialize TheMemory Storage BufferAnd Store Its / / Address (So It C a n Be Freed Later) strcpy(TableSpaceData->tbspq'Ver, SQLB-TBSPQRY-DATA-ID); TableSpaceHead = TableSpaceData; / / Copy The Table Space Data Into The Memory Storage / / (Fetch Table space Data)
Buffer
sqlbftpq(hsqlca, TSCount, TableSpaceData, & m o w s ) ; if (sqlca.sqlcode !I SQL-RC-OK) return(sqlca.sqlcode); / / Display The Table space Data Retrieved c a t << WTable Spaces Defined For The SAMPLE Database" << endl; Type" << endl; cout << "ID Name COUt << U " << endl; for (int i = 0; i < (int) NumRowe; i++, TableSpaceData++)
I
cout .width (4 ) ; cout.setf(ios::left); cout << TableSpaceData->id; cout.width(14); cout.setf(ios::left); cout << TableSpaceData->name; switch (TableSpaceData->flags)
I case SQLB-TBS-SMS: cout << *%!yatem Managed Space" << endl; break; case SQLB-TBS-DMS: cout << "Database muaged Space" << endl; break; case SQLB-TBS-ANY: cout << "Regular ContentsW << endl; break; caae SQLB-TBS-LONG: cout << "Long ~ i e l dData" << endl; break; case SQLB-TBS-TMP: cout << "Temporary Data" << endl; break; default: cout << endl; 1
Part 3: Application Programming Interface Functions
/ / Close The Table space sqlbctsq(&sqlca); free(Tab1eSpaceAead); / / Return TheSQLCA Return return(sqlca.sqlcode);
Query And Free
CodeTo The
All
Resources Used
Calling
Function
1
/*
/* /*
The
Main
*/ */ */
Function
int main0
I
-
/ / Declare The Local Memory rc long SQL-RC-OK; struct sqlca sqlca;
Variables
/ / Connect To The SAMPLE Database USINQ password; BXEC SQL CONNECT TO SAMPLE USER userID
/ / Get Information AboutThe Table / / The SAMPLE Database rc = Example.QetTSpaceInfo(); / / Issue A Rollback To Free EXEC SQL ROLLBACK;
All
SpacesThat Are Defined For
Locks
/ / Disconnect FromThe SAMPLE EXEC SQL DISCONNECT CURRENT;
Database
/ / Return To return )(rc ;
System
The
Operating
FETCH TABLESPACE QUERY purpose
The FETCH TABLESPACE QUERY function is used to retieve (fetch)andtransfera specified number ofrows of table space informationto a user-allocated memory storage buffer thatis supplied by the calling application. SQL-MI-RC
SQLMI-FN
sqlbftpq (struct eqlca *SQW, MaxTableSpaces, long unsigned etruct SQLB-TBSQRY-DATA *TableSpaceData, t unsigned *NumTableSpaces) long
Chapter 9: Table and Table Space Management APIs Parameters
SQLCA
MaxlbbleSpaces ThbleSpaceData
NumlbbleSpaces
A pointerto a locationin memory where aSQL Communications Area (SQLCA) data structure variable is stored. This variable returns either status information (ifthe function executed successfully) or error information (ifthe function failed)to the calling application. The maximum numberof rows of table space data that theuserallocated memorystorage buffer can hold. A pointerto a user-allocatedarray of SQLB-TBSPQRYJATA structures where this function is to store the table space data retrieved. A pointerto a locationin memory wherethis function is to store the actual number of rows of table space data retrieved.
Includes
#include <eqlutil.h>
Description
The FETCH TABLESPACEQUERY function is used to retrieve (fetch) and transfer a specified numberof rows of table space informationto a user-allocated memory storage buffer that is supplied by the calling application. The copy of table space data that is placed in memory represents a snapshot of the table space informationat the time this function was executed. Becauseno locking is performed, the information in this snapshot may not reflectrecent changes madeby other applications. Before this function can be executed, an array of SQLB-TBSPQRY-DATA structures must be allocated, and the number of elements in this array must be stored in the MaxlbbleSpaces parameter. TheSQLB-TBSPQRY-DATA structure is defined in sqlutil.h as follows: struct SQLB-TBSPQRY-DATA {
char unsigned unsigned
long long
char unsigned
long
unsigned long unsigned long unsigned long unsigned long unsigned unsigned
long long
unsigned long char char
tbspqvert81 ; /* The structure version identifier */ */ id: /* The internal ID for the table space */ nameLen; /* The length of the table space name */ /* (for languages other than C and C++ */ name 11281 : /* The table space name (NULL-terminated) totalPapem; / * The total numberof pages occupied by */ /* the table space (DM9 table spaces only*/ useablepagee; /* The total number of 4KB pages occupied*/ */ /* by the table space(EMS table spaces only flags; /* Bit attributes for the table space */ pagesize; /* The size (in bytes) of OIPB page of memory*/ fixed at 4K *I /* currently extsize; /* The extent size (in pages) of the table*/ */ '/* space prefetchsize; /* The table space prefetch buffer size */ ncontainers; /* The number of containers in the table */ */ /* space tbsState; /* The state of the table space */ lifeLSNt61 ; /* The date andtime that the table space */ */ /* was created used alignment for */ paat21 ; /* Reserved;
-
Part 3: Application Programming Interface Functions f lag02;
/* /*
Additional bit attribute0 for the table*/ apace */
*/
char unaigned
long
uneigned
long
unsigned long
DATA
minimumRecTime[27] ; /* The earlieet point in time thatmay be*/ /* epecified for apoint-in-time */ /* roll-forward recovery */ padl [ l 1 I /* Reeerved; ueed for aliment */ StateChngObj; /* The object ID in table apaceStateChugD */ /* that caueed the table apace etate to be*/ /* set to SQLB-LOAD-PENDING or */ /* SQLB-DELETE-PENDING */ StateChugID; / * The table apaceID of object StateQmgQbj*/ /* that caused the table apace state to be*/ /* set to SQLB-LOAD-PENDING or */ /* SQLB-DELETE-PENDING */ nQuieecera; / * The number of quieacera of the table */ /* apace (ifthe table apace etateie eet to */ /* SQLB-LOAD-PENDING or SQLB-DELETE-PENDING */
*/ */
0ttuCt quieecer[5]; char reeervedt321; 1;
/*Information Quieecer /* Reeerved €or
*/ future uee
*/
This structure contains a pointer to an arrayof SQLB-QUIESCERpATA structures that provide additional information about any quiescers of the table space. The SQLB-QUIESCER-DATA structure is defined in sqluti1.h as follows: SQL-STRUCTURE SQLB-QUIESCER-DATA {
uneignedlongquieeceId; uneigned long quiesceobject; 1
Comments
/*
/*
The tableapace ID ofquieeceObject The table space object in quieecerci
The flags field of the SQLBTBSPQRY-DATA structure can contain one of the following values: B SQLB-TBS-SMS System-ManagedSpace (SMS)table space B SQLB-TBS-DMS Database-Managed Space (DMS) table space B SQLB-TBS-ANY Regular data table space B SQLB-TBS-LON0 Longfield data table space B SQLB-TBS-TMP Temporary data table space B The tbsState field of the SQLB-TBSQRYPATA structure c& contain one of the
following values: SQLB-NORMAL
Nom1
SQLB-QUIESCED-SHARE SQLB-QUIESCED-UPDATE
Quiesced: SHARE Quiesced: UPDATE
SQLB-QUIESCED-EXCLUSIVE
Quiesced: EXCLUSIVE
*/
*/
Chapter 9: Table and Table Space Management HIS Load pending
SQLB-LOAD-PENDING
Delete pending SQLB-BACKUP-PENDING Backup pending SQLB-ROLLFORWARD-IN~PROGRESS Roll-forward recovery in progress SQLB-ROLLFORWARD-PENDING Roll-forward recovery pending SQLB-RESTORE-PENDING Restore pending Disable pending SQLB-DISABLE-PENDING SQLB-REORG-IN-PROGRESS n b l e reorganization in progress Backup in progress SQLB-BACKUP-IN-PROGRESS SQLB-STORDEF-PENDING Storage must be defined Restore in progress SQLB-RESTORE-IN-PROGRESS SQLB-STORDEF-ALLOWED Storage can be defined H SQLB-STORDEF-FINAL-VERSION Storage definition in final state SQLB-STORDEF-CHANGED Storage definition changed prior torollforward recovery SQLB--BAL-IN-PROGRESS DMS rebalancer active SQLB-PSTAT-DELETION %ble space deletion in progress H SQLB-PSTAT-CREATION %ble space creation in progress SQLB-DELETE-PENDING
When the arrayof SQLB-TBSPQRYgATA structures that was allocated forthis function is no longer needed,it must be freed by the application that allocated it. H If this function is executed when a snapshot of table space informationis already
in memory, the previous snapshot will be replaced with refreshed table space information. One snapshot buffer storage area i s used for table space queries and another snapshot buffer storagearea is used fortable space container queries. These buffers are independent of one another.
Prerequisites The OPEN called.
TABLESPACE
QUERY function must be executed before this function is
Connection This function can only be called if a connection to a database exists. Requirements Authorization Only users with System Administrator(SYSADM) authority, System Control (SYSCTRL)authority, System Maintenance(SYSMAINT)authority, or Database Administrator (DBADM) authority can executethis function call. See Also
OPEN TABLESPACE QUERY, CLOSE TABLESPACE QUERY, TABLESPACE QUERY, . SINQLE TABLESPACE QUERY, GET TABLESPACE STATISTICS
Example
See the exampleprovidedfor the OPEN
TABLESPACE
QUERY function on page 294.
Part 3: Application Programming Interface Functions
CLOSE TABLESPACE QUERY The CLOSE TABLESPACEQUERY function is used to terminate a table space query request made by the OPEN TABLESPACEQUERY function.
syntax Parameters
SQLCA
A pointer to a location in memory where a SQL Communications Area (SQLCA)data structurevariable is stored. This variable returns either statusinformation (ifthe function executed successfully) or error information (if the h c t i o n failed) to the calling application.
Includes Description
The CLOSE TABLESPACEQUERY function is used to end a table space query request made by the OPEN TABLESPACEQUERY function and to free all associated resources.
Connection T h i s function canonly be called ifa connection to a database exists. Requirements Authorization Only users with System Administrator(SYSADM) authority, SystemControl (SYSCTRL) authority, System Maintenance(SYSMAINT)authority, or Database Administrator (DBADM) authority are allowed to execute this function call. See Also
OPEN TABLESPACE QUERY, FETCH SINGLE TABLESPACE QUERY, GET
Example
See the example provided forthe OPEN
TABLESPACEQUERY, TABLESPACE QUERY, TABLESPACE STATISTICS TABLESPACEQUERY function on page 294.
m m TABLESPACE QUERY Purpose
The TABLESPACE QUERY function is used to retrieve a copy of the table space information that is available for the currentconnected database into a large DB2allocated memory storage buffer. SQL-API-RC SQL-API-FN
Parametera
SQLCA
NumlbbleSpaces
eqlbmtsq (struct eqlca 'SQLCA, uneigned long *nRunTableSpacee, etruct SQLB-TBSPQRY-DATA **TableSpaceData);
A pointer to a location in memory where a SQL Communications Area (SQLCA)data structurevariable is stored. T h i s variable returns either status information (if the function executed successfully)or error information (ifthe function failed)to the calling application. A pointer to a location in memory where this function is to store the actual number of table spaces foundin
!
Chapter 9: Table and Table Space Management APIs
i
301
j
! L " : : -
the current connected database. TableSpaceData
A pointer to 'the address of an array of SQLBTBSPQRY-DATA s t r u d s where this function is to store the table space information retrieved.
Includes
#include <sqlutil.h>
Description
"he TABLESPACE QUERY function is used to retrieve a copy of the table space information that is available forthe currentconnected database into a large DB2allocated memorystorage buffer. When called, this function alsoreturns thenumber of table spaces that have been definedfor the current connected database to the application. This function provides a one-callinterface to the OPEN TABLESPACE QUERY, FETCH TABLESPACEQUERY, and CLOSE TABLESPACEQUERY functions (which can also be used t o retrieve the table space informationfor a connected database). When this function is executed, a memorystorage buffer that is used to hold all of the table space informationretrieved is automatically allocated, a pointer to that buffer is stored in theTableSpaceData parameter, and the number of table spaces found in thecurrent connected database is stored in theNumTableSpaces parameter. "he memory storage buffer that holds the table space informationis actually an array of SQLB-TBSPQRY-DATA structures and the value returned in this NumTableSpaces parameter identifies the number of elements in thisarray. Referto the FETCH TABLESPACEQUERY function for a detailed descriptionof the SQLBTBSPQRY-DATA structure.
Comments
When this function is executed, if a sufEcient amountof free memory is available, a memory storage buffer will automaticallybe allocated.This memory storage buffer can only be fieed by calling the FREE MEMORY function. It is up to the application to ensure that all memory allocated bythis function is fieed when it is no longer needed. If sufficient memoryis not available,this function simplyreturns the number of table spaces foundin theconnected database, and no memory is allocated. M If there is not enoughfree memory availableto retrieve the complete set of table space information availableat one time, you can use the OPEN TABLESPACE QUERY, FETCH TABLESPACEQUERY, and CLOSE TABLESPACEQUERY functions to retrieve the same table space informationin smaller pieces.
Connection This function can only be called if a connection to a database exists. Requirements Authorization Only users with System Administrator (SYSADM) authority, System Control (SYSCTRL) authority, System Maintenance(SYSMAIN") authority, or Database Administrator (DBADM) authority are allowed t o execute this function call.
see Also
OPEN TABLESPACE QUERY, FETCH TABLESPACE QUERY, CLOSE TABLESPACE QUERY, SINGLE TABLESPACEQUERY, GET TABLESPACE STATISTICS, FREE
Part 3 Application Programming Interface Functions MEMORY
Example
The following C++ program illustrates how to use the TABLESPACE Q m R Y function to retrieve idormation about the table spaces that have been definedfor the SAMPLE database:
*/
/*
/*
/* /* /* QUERY /* /* /* /*
NAME: CH9EX2.SQC PURPOSE: Illustrate HOW To wee The Following DB2 API Functions In A C++ Program:
TABLESPACE FREE MEMORY
*/
/ / Include The Appropriate Header Files #include *windows .h> #include dostream.h, #include <sqlenv.h> #include <eqlutil.h> #include <sql.h> / / Define The API-Clase Class class API-Class {
/ / Attributes public : struct sqlca sqlca;
1;
/ / Operations public: long QetTSpaceInfo ():
/ / Define The QetTSpaceInfoO Member Function long API-Class::GetTSpaceInfo() {
/ / Declare The Local Memory Variables unsigned TSCount long ; struct SQLB-TBSPQRY-DATA **TableSpaceData; / / Retrieve Table Space Data sqllmtsq(heqlca, brTSCount, br(Tab1espaceData). SQLB-RESERVEDl, SQLB-RESERVEDZ); if (sqlca.sqlcode 11 SQL-RC-OK) return(sqlca.sqlcode); / / Display The Table space Data Retrieved cout << "Table Spaces Defined For The SAMPLE Database" << endl; C m t << "ID Name Type" << endl; COUt ** " ** endl; for (int i 0 ; i < (int) TSCOunt; i++)
-
*/ */ */ */ */
*/ */
Chapter 9: Table and Table Space ManagementM I S i cout.width(4); cout.setf(ios::left); cout << TableSpaceDatati]->id; cout.width(14); cout.setf(ios::left)l cout << TableSpaceData[i]->name; switch (TableSpaCeData[i]->flagS) f case SQLB-TBS-SMS: cout << "system Managed Space" << endl; break; case SQLB-TBS-DMS: cout << "Database Managed Space"<< endl; break; case SQLB-TBS-ANY: cout << "Regular Contents" << endl; break; case SQLB-TBS-LONG: cout << aaLong Field Data" << end1; break; case SQLB-TBS-TMP: cout << "Temporary Data" << endl; break; default: cout << endl; 1
1 / / Free All Resources Associated With The Table Space Query sqlefmem(&eqlca, TableSgaceData); / / Return The SQLCA Return return(sqlca.sglcode);
Code To The
Calling
Function
1 *I
I*
Main
/* /*
*/ */
The
int main( ) f / / Declare The Local Memory Variables = SQL-RC-OK; rc long struct sqlca sqlca;
/ / Connect TO The SAMPLE Database EXEC SQL CONNECT TO SAMPLE USER userID / / Get Information About The / / The SAMPLE Database rc = Example. GetTSpaceInf o'() ;
USINQ
paSSWOrd;
Table Spaces That Are Defined For
n
I
Part 3: Application Programming Interface Functions / / Ieeue A Rollback To Free All Locks EXEC SQL ROLLBACK; / / Disconnect From The SAMPLE Databaee EXEC SQL DISCONNECTCURRENT;
1
/ / Return To The Operating System return )(rc 1
SINGLE TABLESPACE QUERY The SINGLE TABLESPACE QUERY function is used to retrieve information about a single, currently defined table space. long uneigned TableSpaceID, struct SQLB-TBSQRY-DATA *TableSpaceData);
SQLCA
TableSpaceID TableSpaceData
.
A pointer to a location in memory where a SQL Communications Area (SQLCA) data structure variable is stored. This variable returns either status information (if the function executed successfully) error or information (ifthe function failed)to the calling application. The ID of the table space that information is to be retrieved €or. A pointer to a SQLB-TBSPQRY-DATA structure where this function is to store the table space information retrieved.
Includes
#include <sqlutil.h>
Description
The SINGLE TABLESPACE QUERY function is used to retrieve information about a single, currently defined table space. The informationretrieved is stored in a special structure, SQLB-TBSPQRY-DATA, that is defined in sq1util.h. Refer to the FETCH TABLESPACE QUERY function for a detailed descriptionof this structure. The SINGLE TABLESPACEQUERY function provides an alternative to the more expensive combination Of OPEN TABLESPACEQUERY, FETCH TABLESPACEQUERY, and CLOSE TABLESPACEQWRY function calls whenthe table space identifier of a table space is already known.
Comments
H Table spaceI D S for table spaces canbe found in theSYSCAT.TABLESPACES
system catalog table.
QC
l
i
Chapter 9: Table and Table Space ManagementAPIs M No agent snapshot is takenwhen this fundion is executed. Becausethere is only
one table space entry to return, theentry is returned directly. M When the table space identifieris not known in advance, you must use either the
OPEN TABLESPACEQUERY, FETCH TABLESPACE QUERY, and CLOSE TABLESPACE QUERY functions or the TABLESPACE QUERY to retrieve information about the desired table space.
Connection
T h i s function can only be called if a connection to a database exists.
Requirements
Authorization Only users with System Administrator(SYSADM),System Control (SYSCTRL) authority, System Maintenance(SYS"l') authority, or Database Administrator (DBADM) authority are allowed to execute this function call.
see Also Example
OPEN TABLESPACE QUERY, FETCH TABLESPACE QUERY, CLOSE TABLESPACE QUERY, TABLESPACE QUERY, GET TABLESPACE STATISTICS
Thefollowing C++ program illustrates how to use the SINGLE TABLESPACE function to retrieve information abouta table space whose IDis already known:
/* /* /* /* /* /* /*
"/
CH9EX3 PURPOSE: Illustrate How To Wee The Following DB2 API Function In A C++ Program:
NAME:
TABLESPACE'
SINGLE
QUERY
/*
*/ */
*/
*/ */ */ */
/ / Include The Appropriate Header Files #include <windowe.h> #include #include <eqlutil.h> #include <sql.h> / / Define The -1-Claee Claee claee API-Claee {
/ / Attributes public : etruct eqlca eqlca; / / Operatione public : long GetTSpaceInfoO;
1; / / Define The GetTSpaceInfoO Member Function long API-C1aee::QetTSpaceInfoO / / Declare
The
Local
Memory
Variablee
Part 3 Application Programming Interface Functions etruct SQLB-TBSPQRY-DATA TableSpaceData; / / Initialize The Memory Variable etrcpy(TableSpaceData.tbspqver, SQLB-TBSPQRY-DATA-ID);
/ / Retrieve The Table Space Data Into A Local Variable eqlbetpq(hSqlCa, 2, hTableSpaceData, SQLB-RESERVgDl); / / Display The Table Space Data if (eqlca.eqlcode m= SQL-RC-OK)
Retrieved
{
tout << "Table Spaces Defined For The SAMPLE Database" << endl; "ID cout Name Type" << endl; COUt << U << endlt cout.width(4); cout.eetf(ios::left)t cout << TableSpaceData.id; cout.width(14); cout.eetf(ioe::left)r cout << TableSpaCeData.name; switch (TableSpaceData.flage)
< case SQLB-TBS-WbS : cout "system Managed Space" << endlt break; case SQLB-TBS-DMS: cout << "Database Managed Space"<< endl; break) case SQLB-TBS-ANY: cout 'Regular Contents" << endlt break; case SQLB-TSS-LONG: cout << "Long Field Datau endl; break; case SQLB-TBS-TMP: cout << "Temporary Data" << end18 break; default : cout << endl; 1
1 / / Return TheSQLCA Return return(eqlca.eqlcoc¶e);
CodeTo The Calling
Function
1
/* /*
The Main Function
int main() {
/ / Declare The Local Memory Variables = SOL-RC-OKt rc long struct eqlca eqlca;
*/ */
Chapter 9: Table and Table Space ManagementAPIs / / Create An Instance Of The API-Claes Claee -1-ClassExamplet
/ / Connect To The SAMPLE Database TO SAMPLE USER userID EXEC SQL CONNECT / / Get Information About The / / The SAMPLE Database rc I Example .GetTSpaceInfo( ); / / Ieeue A Rollback To Free EXEC SOL ROLLBACK;
1
/ / Return To The return(rc) I
GET
Operating
Table Spaces That Are Defined For
All
/ / Dieconnect From The SAMPLE EXEC SQL DISCONNECT CURRENTt
USING paeswordt
Locke
Database
Syetem
TABLESPACE
STATISTICS
The GET TABLESPACE STATISTICS function is used to retrieve information about the space utilization of a specific table space. SQLpPI-RC SQL-AE’I-PN
Parameters
SQLCA
TableSpaceID TableSpaceStats
SplbOtee (StruCt sqlca uneigned long etruct SQLB-TBS-STATS
*SQX&
TableSpaceID, *TableSpaceState);
A pointer to a location in memory where a SQL Communications Area(SQLCA) data structurevariable is stored. This variable returns either status information (ifthe function executed successfully) or error information (ifthe function failed)to the calling application. The ID of the table space that space usage information is to be retrieved for. A pointer to the address of a SQLB-TBS-STATS structure where this function i s to store the table space usage information retrieved.
Includes
#include <eqlutil.h>
Description
The GET TABLESPACE STATISTICS function is used to retrieve information about the space utilization of a specific table space. The information retrieved i s stored in a special structure, SQLB-TBS-STATS, that is defined in sq1util.h as follows:
Part 3: Application Programming Interface Functions 8tYXCt SQLB-TBS-STATS
<
unsigned long
total~agee~
/* /*
/* /* /*
/*
uneigned long
ueablepagee;
/* /* /* /* /*
/*
uneigned long
ueed~agee;
uneigned long
freepagee;
uneigned long
highWaterMark;
/* /* /* /* /* /* /*
/* /* /*
/* /* /* /* /* /* /*
/* /*
/*
/* /*
/*
/*
1;
The total amount of operating */ eyetem apace (in 4KB pagee) */ needed by the table apace. For */ DM8 table 8paCe8. thi8 i 8 the 8Um */ of the table apace container eizee */ (including overhead). For 816s */ table 8paCe8, thi8 i8 the 8Um O f all */ file apace ueed for the tablee */ etored in thie table apace. */ The total amount of operating */ eyetem apace (in 4KB pages) */ needed by the table apace minue */ overhead (for DMS table spacee). */ For SMS table epacee, thie value i e */ equal to the totalpagesvalue. */ The total number of 4KB pages */ currently beingueed by the table */ apace (for DMS table spaces). */ POI: 816s table 8paCe8, thi8 Value i 8 */ equal to the totalpages value. */ The total number of 4KB pagee */ that are available for DMS a table */ space (usablepages value minue */ usedPages value). Thie field ie not */ applicable for =S table epacee. */ The current '#end" of the DMS */ table apace addressapace, in other */ words. the page number of the */ firet free 4KB page following the */ laet allocated extent of the table */ apace. Thie field ie not applicable */ for 816s table 8paCe8. Note: thi8 i 8 */ not really a '%igh-water mark" but */ rather a "current-water mark" */ eince the valuecan increase or */ decreaee. */
Connection This functioncan only be called if a connection to a database eists. Requirements Authorization Only users with System Administrator (SYSADM)authority, System Control (SYSCTRL) authority, System Maintenance(SYSMAINT) authority, or Database Administrator (DBADM) authority can executethis function call. See Also
OPEN TABLESPACE Q W R Y , FETCH TABLESPACE QUERY, CLOSE TABLESPACE QWRY, TABLESPACE QUERY, SINGLE TABLESPACE QUERY
Example
Thefollowing
c++
program illustrates how to use the GET TABLESPACE STATISTICS functionto retrieve space usage information for the SYSCATSPACE table
C
Chapter 9: Table and Table Space ManagementAPIs space (of the SAMPLE database):
/* m: /* PURPOSE: /* /*
CH9EX4 Illustrate H o w To Use The Following DBP API Function In A C++ Program:
STATISTICS /* TABLESPACE
QET
/* /*
/ / Define The,API-Class Class class API-Class
i / / Attributes public: struct eqlca sqlca; / / Operations public : long QetTSpaceStateO;
/ / Define The QetTSpaceStatsO Member Function long API-Clase::GetTSpaceStatsO
i
*/ */ */ */ */
*/
/ / Include The Appropriate Header Files #include <windows.h> #include 4ostream.b #include <sqlutil.h> #include <eql.h>
1;
*/
/ / Declare The LocalMemory Variables struct SQLB-TBS-STATS TableSpaceStats; / / Retrieve The Table Space Statistics eqlbgtes(&eqlca, 0, &TableSpaceStats);
/ / Display The Table
if (sqlca.sqlcode
m6
Space Statistical Data Retrieved SQL-RC-OK)
i cout cout cout cout cout cout cout cout cout cout cout
?
<< "Statistics for SYSCATSPACE Table Space :" << endl; << "Total Number Of Pages : '1; << TableSpaceStats.totalPagee << endl; << "Total Number Of Usable Pagee : "; << Tab1eSpaceStats.useablePages << endl; << "Total Number Of Used Pages : 'l; << Tab1eSgaceStats.usedPagee << endl; << ''Total Number Of Free Pages : << Tab1eSpaceStats.freePages << endl; << "Current End Of Address Space : << Tab1eSpaceStats.highWaterMark << endl;
Part 3: Application Programming Interface Functions
/*
/*
*/ The Main Function
*/ */
/* int main()
c
/ / Declare The LocalMemory Variables rc long = SQL-RC-OK; struct sqlca sqlca;
/ / Connect To The SAMPLE Database EXEC SQL CONNECTM SAMPLE USERuserID USING / / Get Statistics About / / The SAMPLE Database
password;
The First Table Space Defined For
rc = Example.QetTSpaceStats(); / / Issue A Rollback To Free EXEC SQL ROLLBACK;
All
Locks
/ / Disconnect From The SAMPLE Database EXEC SQL DISCONNECT CURRENT;
1
IW ! Purpose
syntax Parameters
/ / Return To The return (rc);
Operating
System
OPEN TABLESPACECONTAINER QUERY The OPEN TABLESPACE CONTAINER QWRY function is used to obtain a count of the number of table space containersthat have been defined foreither a specified table space or for the currentconnected database. SQL--1-RCSOL-API-FN
SQLCA
sqlbotcq (struct sqlca unsigned long unsigned long
*SQm,
TableSpaceID, *NtunContainerrr);
A pointer to a location in memory wherea SQL Communications Area (SQLCA) data structurevariable is stored. T h i s variable returns either status
fl :
l
! I :
Chapter 9: Table and Table Space ManagementAPIs
lbbleSpaceID
NumContainers
l
311
.i
information (ifthe function executed successfidly) or error information (if the function failed)to the calling application. The ID of the table space that container informationis to be retrieved for. If the value specified forthis parameter is SQLB-ALL-TABLESPACES, a count of table space containers forthe entiredatabase will be returned. A pointer to a location in memory wherethis function is to store the actual number of containers foundin the specified table space (or database).
Includes
# i n c l u d e< s q l u t i l . h >
Description
The OPEN TABLESPACE CONTAINER QUERY function is used to obtain a count of the number of table space containersthat have been defined foreither a specified table space or for the currentconnected database. This function is normally followed by oneor more FETCH TABLESPACE CONTAINER QUERY function Calls and one CLOSE TABLESPACE CONTAINER QUERY function call. Together, these three functions work like an SQL cursor he., they use the OPENLFETCWCLOSE paradigm). An application canuse these three functions to scan a list of table space containersand search for specific information.
Comments
B Only one table space container query can be active at one time. B The first time this function is called, a snapshot of the table space informationis
buffered in the agent that is servicing the application. If the application callsthis function again, this snapshot is replaced with refreshed information. Because lockingis not performedby this function, the information returned in the snapshot buffer may not reflect recent changes made by another application.
Connection This function can only be calledif a connection to a database exists. Requirements Authorization Only users with System Administrator(SYSADM) authority, System Control (SYSCTRL) authority, System Maintenance(SYSMAINT)authority, or Database Administrator (DBADM) authority can executethis function call.
see Also
FETCH TABLESPACE CONTAINER QUERY, CLOSE TABLESPACE CONTAINER QUERY, TABLESPACE CONTAINER QUERY
Example
Thefollowing
c++
program illustrates how to use the OPEN TABLESPACE QUERY,FETCH TABLESPACE CONTAINER QUERY,andCLOSE TABLESPACE CONTAINER QUERY functions to retrieve a list of containers for a
CONTAINER
specified table space:
l !
l
Part 3: Application Programming Interface Functions /* /*
/* /* /*
- */ NAME: CH9EXS.SQC PURPOSE: Illustrate How To In A C++ Program:
/*
Wee The Following DB2API Functions
TABLESPACE OPENCONTAINER QUERY TABLESPACE FETCHCONTAINER QUERY TABLESPACE CLOSECONTAINER
/* /* /* /*
QWRY
/ / Include The Appropriate Header Filee #include <windows.h> #include #include <sql.h> / / Define The API-Claes Claes claes API-Class
c / / Attributes public: struct eqlca sqlca; / / Operations public: long QetTSCInf o() ;
1; / / Define The QetTSCInfo( ) Member long API_Claee::QetTSCInfo()
Function
c / / Declare The Local M e m o r y Variables TSCCount uneigned long 8 struct SQLB-TBSCONTQRY-DATA *TSContainerData E NULL; struct SQLB-TBSCONTQRY-DATA *TSCDataHead I NULL; unsigned long NumRows;
/ / open The Table Space Container Query sqlbotcq(&sqlca, 2, eTSCCount); if (sqlca.sq~code I = SQL-RC-OK) return(sqlca.eqlcode)t / / Allocate AMemory Storage Buffer *) TSContainerData(structSQLB-TBSCONTQRY-DATA malloc(TdCC0unt * sizeof(etruct SQLB-TBSCONTQRY-DATA)); / / Store The Memory Storage Buffer's / / Freed Later)
TSCDataHead
-
Address (So It Can Be
TSContainerData;
/ / Copy The Table Space Container Data IntoM e mThe o r y Storage / / Buffer / / (Fetch Table Space Container Data) sqlbftcq(&eqlca, TSCCount, TSContainerData, &NumRows);
*/ */
*/
*/ */ */ */ */ */
Chapter 9: Table and Table Space Management“1s
/ / Display The abl le cout << “Containere cout << endl << “ID COUt << for (int i P 0; i <
Space Container Data Retrieved Defined ForThe USERSPACE1 Table Spacen; Name” << endl; << endl; (int) NumRows; i++, TSContainerData++)
{
tout .width ( 4 ; cout.setf(ioe::left); cout << TSContainerData->id; cout.width(14); cout.setf(ios::left); cout << TSContainerData->name;
? / / Close The Table / / Used
Space
Container Query And
Free
All
Resources
sqlbctcq(brsq1ca); free(TSCDataHead); / / Return TheSOReturn return(sqlca.sqlcode);
CodeTO The
Calling
Function
? I
~~~~
/* /*
*/ */
The Main Function
int main() {
/ / Declare The Local M e m o r y Variables rc long = SQL-RC-OK; struct eqlca sqlca;
/ / Create An Instance Of The-1-Class -1-ClaeeExample;
/ / Connect To The SAMPLE Database EXEC SQL CONNECT TO SAWPLE USER
Class
ueerID
USING
password;
/ / Get Information About The Table Space Containers / / That Are Defined For The SAMPLE Database GetTSCInf 0() ; rc = Example.
/ / Ieeue A Rollback TO Free EXEC SQL ROLLBACK;
All
Locks
/ / DiSCOnneCt From The SAMPLE Database EXEC SQL DISCONNECT CmRRENT;
1
/ / Return TO The herating syatem return( rc ) ;
Part 3 Application ProgrammingInterface Functions
FETCH TABLESPACEC O N ' I ! ! R QUERY purpose
The FETCH TABLESPACE CONTAINERQUERY function is used to retrieve (fetch) and transfer a specified numberof rows of table space container information to a userallocated memory bufferthat is supplied by the calling application.
syntax
SQL-1-RC
Parameters
SQLCA
Includes
#include <eqlutil.h>
Description
The FETCH TABLESPACE CONTAINER QUERY function is used to retrieve (fetch) and transfer a specified numberof rows of table space container information to a userallocated memorystorage buffer that is supplied by the calling application. Thecopy of table space container data that is placed in memory represents a snapshot of the table space container information at the time this function was executed. Because no locking is performed, the information in this snapshot might not reflect recent changes made byother applications. Before this function can be executed, an arrayof SQLB-TBSCOIWQRY-PATA structures mustbe allocated, and the number of elements in this array must be stored in the MazContainers parameter. "he SQLB-TBSCONTQRY-DATA structure is defined in sq1util.h as follows:
*sffLcA,
SQLMI-FN eqlbftcq (etruct eqlca
unsigned long MsxContainers, struct SQLB-TBSCONTQRY-DATA*ContainerData unsigned long *IWmContainere);
A pointer to a location in memorywhere a SQL Communications Area (SQLCA)data structure variable is stored. This variable returns either status information (if the function executed successfully)or error information (ifthe function failed) to the calling application. MazContainers The maximum numberof rows of table space container information that theuser-allocated memorystorage buffer can hold. ContainerData A pointer to the address of an array of SQLB-TBSCONTQRY-PATA structures where this function is to store the table space container information retrieved. NumContainers A pointer to &location in memory wherethis function is to store the actual number of rows of table space container information retrieved.
etruct SQLB-TBSCONTQRY-DATA {
uneigned long uneigned long
id? rime;
/*
/*
/*
/* /*
uneigned long uneigned long
tbeID; nameLen;
/* /*
The container identifier */ The number of table epaceesharing thia*/ container. The value for this parameter*/ is alwaye 1 (DM8 table epacee can have*/ only 1 container spaceat thie time). */ The table space identifier */ The length of the container name (for */
Chapter 9: Table and Table Space ManagementAPIs languagesother than C and C++) */ container The name (NULL-terminated) */ Indicateswhetherthetablespace */ container is underthedatabase */ directory ( 1 ) or not (0). */ unsignedlongcontType; Indicateswhetherthetablespace */ container specifies a directory path */ (SQLB-CONT-PATH) , a raw device */ (SQLB-COW-DISK), or a file */ (SQLB-CONT-FILE). Note: the v a h e */ SQLB-CONT-PATH is onlyvalid for */ SMS table spaces. */ unsigned long totalPapes; /* Total number of 4KB pages occupied by */ /* the table space container (DMS table */ only) /* spaces */ unsigned long usablepagee; /* Total mrmber of 4- pages occupied by the*/ /* table space container overhead (DM8 */ only) spaces /* table */ unsigned long ok; /* Indicates whether the table space */ /* container is accessible (1) or */ /* inaccessible ( 0 ) . A value of 0 indicates */ / * an abnormal situation that might require*/ /* the database administrator's attention. */ 1; char namet2561; unsignedlongunderDBDir;
Comments
/* /* /* /* /* /* /* /* /* /* /* /*
H When the array of SQLB-TBSCONl'QRY-DATA structures that was allocated for
this function is no longer needed,it must be freed bythe application that allocated it. If this function is executed whena snapshot of table space container information is already in memory, the previous snapshot willbe replaced with refreshedtable space container information. One snapshot buffer storagearea isused fortable space queriesand another snapshot buffer storagearea isused for table space container queries. These buffers are independent of one another.
Prerequisites The OPEN TABLESPACE function is called.
CONTAINER
QUERY function must be executed before this
Connection This function can only be called if a connection to a database exists. Requirements Authorization Only users with System Administrator(SYSADM) authority, System Control (SYSCTRL) authority, System Maintenance(SYSMAMT) authority, or Database Administrator (DBADM) authority can executethis function call.
see Also
OPEN TABLESPACE CONTAINER QUERY, CLOSE TABLESPACE CONTAINER QUERY, TABLESPACE CONTAINER QUERY
Example
See the exampleprovidedfor page 312.
the OPEN TABLESPACE CONTAINER QUERY function on
Part 3: Application Programming Interface Functions
CLOSE TABLESPACE CONTAINER QUERY Purpose
The CLOSE TABLESPACE CONTAINER QUERY function is used t o terminate a table space container query request that was made by the OPEN TABLESPACE CONTAINER QUERY function.
syntax
SQL-API-RC SQL-API-FN
Parameters
SQLCA
Includes
#include <sqlutil.h>
Description
The CLOSE TABLESPACE CONTAINER QUERY function is used to end a table space container query request that was madeby the OPEN TABLESPACE CONTAINER QUERY function and to free dl associated resources.
sqlbctcq (struct sqlca
*SPLCA);
A pointer to a location in memory where a SQL Communications Area data structurevariable is stored. This variable returns either status information (ifthe function executed successfully) or error information (if the function failed) to the calling application.
Connection This function can only be calledif a connection to a database exists. Requirements Authorization only users with System Administrator (SYSADM)authority, System Control (SYSCTRL) authority, System Maintenance(SYSMAINT) authority, or Database Administrator (DBADM) authority can executethis function call.
see Also Example
OPEN TABLESPACE CONTAINER QUERY, FETCH TABLESPACE TABLESPACE CONTAINER QUERY
See the example provided for the OPEN page 312.
TABLESPACE
CONTAINER
CONTAINER
QUERY,
QUERY function on
m m TABLESPACE CONTAINER QUERY Purpose
The TABLESPACE CONTAINER QUERY function is used to retrieve a copy of the table space container information that is available for a table space (or for all table spaces in the currentconnected database) into a large DB2-allocated memorystorage buffer.
syntax
SQL-API-RC SQL-API-FN
sqlbtcq (etruct sqlca unsigned long unsigned long struct SQIa-TESmNTQRY-D?iTA
*SPLCA, TableSpaceID, *NUmContainers, **ContainerData);
F i
i
!
! j 317 I
Chapter 9: Table and Table Space Management Parameters
MIS
SQLCA
Apointer to alocation in memorywhereaSQLCommunications Area (SQLCA) data structure variable is stored. This variable returns either status information (if the function executed successfully) or error information (ifthe function failed)to the calling application.
TableSpaceID
The ID of the table space that container information is to be retrieved for. Ifthe value specified forthis parameter is SQLB-ALLTABLESPACES,a compositelist of table space container information for all table spaces in the entiredatabase will be returned.
NumContainers A pointerto a locationin memory wherethis function is to store the actual number of table space containers found forthe table space specified. ContainerData A pointerto the address of an arrayof SQLB-TBSCON!l’QRY-DATA structures where this function is to store the table space container information retrieved.
Includes
,#include <sqlutil.h>
Description
The TABLESPACE CONTAINER QUERY function is used to retrieve a copyof the table space container informationthat is available for atable space (or for all table spaces in the currentconnected database) into a large DB2-allocated memorystorage buffer. When called,this function also returns thenumber of table space containers that have been definedfor a specified table space (or for all table spaces in thecurrent connected database) to the application. “his function provides a one-call interface to the OPEN TABLESPACE CONTAINER QUERY, FETCH TABLESPACE CONTAINER TABLESPACE CONTAINER QUERY functions (which can also be QUERY, and CLOSE used to retrieve the table space container information for oneor more table spaces). When this function is executed, a memory storage buffer that is used to hold all of the table space container information retrieved is automatically allocated,a pointer to that buffer is stored in the ContainerData parameter, and the number of table space containers foundin either the specified table spaceor in the current connected database is stored in the NumContainem parameter. The memorystorage buffer that holds the table space container information is actually an array of SQLB-TBSCONTQRYDATA structures, and the value returned in the NumContainers paramekr identifies the number of elements in this array Refer to the FETCH TABLESPACE CONTAINERQ W R Y function for a detailed description of the SQU-TBSCONTQRYDATA structure.
Comments
When t h i s function is executed, if a sufficient amount of free memory is available, a memorystorage buffer will automatically be allocated. This memory storage buffer can only be freed bycalling the FREE MEMORY function. It is up to the application to ensure that all memory allocatedby this function is freed whenit is no longer needed. If sufficient memory is not available,this function will simply return thenumber of table space containers found, and no memory is allocated. If there is not enoughfree memory availableto retrieve the complete set of table space container information available at one time, you can use the OPEN TABLESPACE CONTAINERQUERY, FETCH TABLESPACE CONTAINER QUERY, and
Part 3 Application Programming Interface Functions TABLESPACE CONTAINER QUERY functions to retrieve the same table space container informationin smaller pieces.
CLOSE
Authorization Only users with System Administrator(SYSADM) authority, System Control (SYSCTRL) authority, System Maintenance(SYSMAINT) authority, or Database Administrator (DBADM) authority are allowed t o execute this function call. See Also
Example
OPEN TABLESPACE CONTAINER QUERY,FETCH TABLESPACE CONTAINER CLOSE TABLESPACE CONTAINER QUERY, FREE MEEIORY
"he following C++ program illustrates how to use the TABLESPACE CONTAINER QUERY function to retrieve information aboutthe table space containers defined for the SYSCATSPACE table space:
/* /* /*
/* /*
/* /* /*
CH9EX6.SQC P m O S E : Illustrate How TO Use The Following DB2 API Functions In A C++ Program:
NAME:
/ / Include The Appropriate #include <windows.h> #include #include <sqlenv.h> #include <sqlutil.h> #include <sql.h>
Header
Files
{
/ / Attributes public: struct sqlca sqlca; / / Operations public : long OetTSCInfoO;
1; / / Define The QetTSCIPfO() Member Function long API-Class::GetTSCInfo() {
The
*/ */ */ */ */ */
/ / Define The API-Class Class class API-Class
/ / Declare TSCCount long unsigned
*/ */
*/
QUERY CONTAINER TABLESPACE FREE MFNORY
/"
r
QUERY,
Local~ e m o r yVariables ;
Chapter 9: Table and Table Space Management MIS stact SQLB-TBSCONTQRY-DATA *TSContainerData; / / Retrieve The Table Space Container Data sqlbtcq(&sqlca, 2, &TSCCount, &(TSContainerData)); if (sqlca.sqlcode l = SQL-RC-OK) return(sqlca.sq1code);
/ / Display The Table Space Container Data Retrieved Space"; cout << "Containers Defined For The USERSPACE1 Table cout << endl << "ID Name" << endl; << endl; cout << " for (int i 0 ; i < (int) TSCCount; i++) P
{
1
cout.width(4); cout.setf(ios::left); cout << TSContainerData->id; cout.width(14); cout.setf(ios::left); cout << TSContainerData-.name;
/ / Free All Resources Associated / / Container Query sqlefmem(&sqlca, TSContainerData); / / Return The SQLCA Return return(sqlca.sq1code);
Code
With
To
The
The
Table
Calling
Space
Function
1
/*
/*
"/
*/ */
The Main Function
/* int main0
c
/ / Declare The LocalMemory Variables rc long = SQL-RC-OK; struct sqlca sqlca; / / Create An Instance Of The API-Class Class API-ClassExample; / / Connect To The SAMPLE Database EXEC SQL CONNECTTO SAMPLE USER UserID
USING
password;
/ / Get Information About The Table Space Containers / / That Are Defined For The SAMPLE Database rc P Example.GetTSCInfo ( ) ; / / Issue A Rollback To Free EXEC SQL ROLLBACK;
All
Locks
/ / Disconnect From The SAMPLE Database EXEC SQL DISCONNECT CURRENT;
Part 3: Application Programming Interface Functions / / Return To The Operating return(rc);
System
mm Purpose
The FREE MEMORY function is used to free memory that has been allocated by either the TABLESPACE QUERY function or the TABLESPACE CONTAINER QUERY function.
syntax
SQL-API-RC SQL-I-FN
Parameters
SQLCA
A pointer t o a location in memorywhere a SQLCommunications Area (SQLCA) data structurevariable is stored. This variable returns either status information (ifthe function executed successfully)or error information (if the function failed) to the calling application.
Buffer
A pointer t o a location in memory that contains thestarting address of the DB2-allocated memorystorage buffer that this function is to free.
eqlefmem
(etruct eqlca void
*SQLCA, *Buffer) ;
Includes
#include <eglenv.h>
Description
The FREE MEMORY function is used to free memorythat has been allocatedby either the TABLESPACE QUERY function or the TABLESPACE CONTAINERQ W R Y function.
Comments
Because the TABLESPACE CONTAINER QUERY and TABLESPACE Q W R Y functions do not release the memory they allocate, this function shouldbe called whenever either of these two functions are used.
Connection. T h i s function can be calledat any time: a connection to a DB2 Database Manager Requirements instance or to a DB2 database d&s not have to be established first. Authorization No authorization is required to execute this function call. Example
See the examplesprovidedfor the TABLESPACE QUERYfunction on page302 and the TABLESPACE CONTAINER QUERY function on page 318.
F 4 REORGANIZETABLE Purpose
The REORGANIZE TABLEfunction is used to reorganize a table by reconstructing the rows in that table so that fragmented data is eliminated and information is
i !
I;
Chapter 9: Table and Table Space ManagementAPIs
I
321
" "
compacted.
syntax
SQL-mI-RC
SQL-AP1-m
sqlureot-api (char
*TableName,
char char struct sqlca
Parameters
%bleName
ZndexIVame
%bleSpace
SQLCA
*IndexName, 'TabhSpaCe, *SQLCA);
A pointer to a location in memory where the name of the table t o be reorganized is stored. Thetable name specified can be an alias, except in thecase of down-level servers, in which case a fully qualified table name must be used. A pointer to a location ixi memory where the fully qualified name of the index to be used when reorganizing the table is stored. Ifthis parameter is set to NULL,the datawill not be reorganized in any specific order. A pointer to a location in memory where the name of a temporary table space (if a secondary work area is to be used) is stored. This parameter can contain aNULL value. A pointer to alocation in memory where a SQL Communications Area (SQLCA)data structure variable is stored. This variable returns either status information (if the function executed successfully) or error information (ifthe function failed) to the calling application.
Includes
#include <eglutil.h>
Description
The REORGANIZE TABLE function is used to reorganize atable by reconstructingthe rows in that table so fragmented data is eliminated and information is compacted. Tables that have been modifiedso often that they contain fragmenteddata, which noticeably slows down access performance, are excellent candidatesfor reorganization. After a table is reorganized, the RUN STATISTICS function shouldbe executed to update the table's statistics, and packages that reference the table should be rebound (with either the BIND or the REBIND function or command), so that new and possibly more efficient accessplans will be generated.
Comments
B You must complete all database operation and release all acquired locks (by
issuing either COMMIT or ROLLBACK SQL statements from all active transactions) before this function can be called. You can use the REOROCHK command to determine whether or not a table needs to be reorganized. B If an index nameis specified in the ZndexName parameter, the DB2 Database Manager willreorganize the data accordingto the order of the index. To maximize DB2 and application performance,specify indexes that are used often in SQL queries. This function cannotbe used to reorganize views. W This function cannot be usedon a table while an online backupof the table space in
I
322
11 .1
Part 3: Application ProgrammingInterface Functions
~
which the table resides is being performed(if the table space is a DMS table space).
W To complete a table space roll-forward recovery operation following a table reorganization, all data andLOB table spaces usedmust be enabled forrollforward recovery. If a table contains LOB columns that do not use the COMPACT option, the LOB data storage object can be significantly larger following table reorganization. This increase in size can result from the order in which the rows were reorganizedand from the types of table spaces used(SMS or DMS). DB2 for CommonServers,Version 2.x, doesnot supportdown-level client requests to reorganize a table.If a Version 2 client requests to reorganize a table on a Version 2 server, and if that request specifies a path instead of a temporarytable space name in the TbbleSpace parameter, the REORGANIZE TABLE function will choose a temporary table space in which to place the work files on behalf of the user. A temporary table space name containing a path separator character (/ or \) should notbe specified,rather, it will beinterpreted as a temporary path (a request before Version 2)and the REOROANIZE TABLE function will choose a temporary table space on behalf of the user. W If the specified table is not successfully reorganized whenthis function is executed, do not delete any temporary files that are created. TheDB2 Database Manager will need these files in order to recover the database.
Connection This function cad onlybe called if a connection to a database exists. Requirements Authorization Only users with System Administrator (SYSADM) authority, System Control (SYSCTRL) authority, System Maintenance(SYSMAINT)authority, or Database Administrator (DBADM) authority (or CONTROL authority for the specified table) are allowed to execute this function call. see Also
Example
RUNSTATISTICS,REBIND
ThefollowingC++program illustrates how to use the REORr3ANIZE TABLE function to reorganize the EMPLOYEE table in theSAMPLE database:
/* /* m: /* PURPOSE: /* /* /* /*
*/ CH9EX7.SQC Illuetrate Bow To Uee The Following DB2 API Function In A C++ Program: REORGANIZE TABLE
*/ */
/*
/ / Include The Appropriate #include <windowe.h> #include
*/ */ */ */ */
Header
Files
Chapter 9: Table and Table Space ManagementM I S #include <eqlenv.h* #include <sqlutil.h> #include <eql.h* / / Define The API-Class Claes c l a m API-Clam
i / / Attributes public : struct eqlca eqlcat
/ / Operatione public : long ReorgTableO;
1; / / Define The ReorgTable() Member Function long API-Clase::ReorgTable()
i
/ / Create An Index On The EMPLOYEE Table EXEC SQL CREAm INDEX USERID.EMP-NUM ON USERID.EMPLOYEE(EMPN0); if (sqlca.eqlcde == SQL-RC-OK)
i 1
cout << "Index EMPJ" ham been created cout << "the EMPLOYEE table." << end11
for
/ / Delete The Index On The EMPLOYEE Table EXEC SQL DROP INDEX USERID.EMP-NUM; if (eqlca. eqlcode== SQL-RC-OK) cout << UInaex EMp_N" has been deleted." << endl;
1
/ / Return The SQLCA Return return(eqlca.eq1cde);
Code To The Calling
/*
/* /*
The Main Function
*/ */
*/
int main()
i
Function
/ / Declare The Local Memory Variables rc long P SQL-RC-OK; struct eqlca eqlca;
Part 3: Application Programming Interface Functions r
/ / COIUIeCt TO The SAMPLE Database TO SAMPLE USER ueerID EXEC SQL CONNECT / / Reorganize TheEMPLOYEE Table In The rc = Example.ReorgTable( ) ;
USINQ
password;
SAMPLE
Database
/ / Issue A Rollback To Free All Locks EXEC SQL ROLLBACK; / / Dieconnect FromThe SAMPLE E W C SQL DISCONNECTCURRENT;
1
/ / Return To The return (rc);
Operating
Database
System
The RUN STATISTICS function is used to update statistical information about the characteristics of a table and any or all of its associated indexes. SQL-API-RC SQL-API-FN sqluetat
Parametera
llrbleName
NumIndems
IndexList Statsoption
(char *TableName, uneigned short Nunundexea, char * *rndaxcist, unsigned charStataOption, unsigned charShareLevel, struct sqlca * S Q m ) t
A pointer to a locationin memory wherethe name of the table that statistics are to be updated for is stored. Thetable name specified can be an alias, except in thecase of down-level servers,in which case a fully qualified table name must be used. The number of indexes that statistics are to be updated for. Ifthis parameter is setto 0, statistics will be calculated forall indexes that have been definedfor the table. A pointer to a locationin memory wherean arrayof fully qualified index names is stored. Specifies whichstatistical calculations are to be updated. T h i s parameter must be set to one of the following values: SQL-STATS-TABLE
Update basic table statistics only. SQL-STATS-EXTTABLE-ONLY
Update basictable statistics with extended (distribution) statistics.
i
! 325 j I
Chapter 9: Table and Table Space Management
APIs
.
i
m
- -7"1
" "
" "
SQL-STATS-BOTH
Update both basictable statistics and basic statistics for indexes. H SQL-STATS-EXTTTAEtLE-INDEX
Update both basictable statistics (with distribution statistics) and basic statistics for indexes.
m
SQL-STATS-INDEX
Update basicstatistics for indexes, only H SQL-STATS-EXTINDEX-ONLY
Update extended statistics for indexes only H SQL-STATS-EXTINDEX-TABLE
Update extendedstatistics for indexesand basic table statistics.
m
SQL-STATS-ALL
Update extended statistics for indexes and basic table statistics (with distribution Statistics). Specifies how the statistics are to be gathered with respect to other users. T h i s parameter must be set to one of the following values:
ShareLmel
SQL-STATS-REF
'
Allow other users t o have read-only access while the statistics are being gathered.
m
SQL-STATS-CHG
Allow other users to have bothread and write access whilethe statistics are being gathered. SQLCA
A pointer to alocation in memory where a SQL Communications Area (SQLCAI data structure variable is stored. This variable returns either status information (if the function executed successfully)or error information (if the function failed) to the calling application.
Includes
#include <sqlutil.h>
Description
The RUN STATISTICS function is used to update statistical information about the characteristics of a table and any or all of ita associated indexes.This information includes, amongother things, the number of records in the table, the number of pages used to store the table, and the average recordlength. The SQL optimizer uses these statistics to determine the best access path to use when preparing SQL statements. You should callthis function wheneverany of the following situations occur: H When atable has been modified manytimes (for example, if large a number of
updates have been made,or if a significant amount of data hasbeen inserted or deleted). When a table has been reorganized. H When oneor more new indexes have been created.
After a table's statistics are updated, you should rebindall packages that reference
I
I
326
Part 3: Application Programming Interface Functions the table (with either the BIND or the REBIND function or command), so new and possibly more efficient access plans will be generated.
Comments
Each string stored in the index list array (referenced by the IndexList parameter) should contain a fully qualified index name, and the value stored in the NumIndexes parameter should be equivalent to the number of index names stored in this index list (unless the NumIndexes parameter is set to 0, in which case the index list array is ignored). If this function is to be called with the Statsoption parameter set to SQL-STATSTABLE or SQL-STATS-EXTTTABLE, make the call before creating any indexes on the table. This guarantees that statistics gathered during index creation will not be overlaid by estimates gathered during the calculation of the table statistics. If index statistics are requested and statistics have never been run on the table containing the index, statistics for both the table and the indexes will be collected.
After calling this function, an application should issue a COMMIT SQL statement to release all locks acquired. All statistics collected are based on the table data that is physically located on the database partition where this function is executed. Complete statistics for a partitioned table can be derived by multiplying the values obtained at the database partition where this function is executed by the number partitions in the nodegroup over which the table is partitioned. If this function is called from a database partition that does not contain a table partition, the request is sent to the first database partition in the nodegroup that contains a partition for the table (and is executed there). If inconsistencies are found while this function is executing (usually caused by activity on the table after this function was called), a warning message is returned. When this situation occurs, this b c t i o n should be called again to refresh the table and/or index statistics. This function can only be called if a connection to a database exists. Connection Requirements
Authorization Only users with System Administrator (SYSADM) authority, System Control (SYSCTRL) authority, System Maintenance (SYSMAINT) authority, or Database Administrator (DBADM) authority (or CONTROL authority for the specified table) are allowed t o execute this'function call. See Also
GET DATABASE CONFIGURATION,REORGANIZE TABLE,BIND, REBIND
Example
The following C++ program illustrates how t o use the RUN STATISTICS function to update the statistics for the EMPLOYEE table in the SAMPLE database after a new index is created:
Chapter 9: Table and Table Space Management APIs
327
/* /*
NAME: CH9EXE.SQC PURPOSE: Illustrate How To Use The Following DB2 API Function /* In A c++ Program:
/* /* /*
RUN STATISTICS
*/ */ */ */ */ */ r
I
/ / Include The Appropriate Header Files #include <windows.h> #include #include <sglenv.h> #include <sglutil.h> #include <sgl.h>
/ / Define The API-Class Class class API-Class {
/ / Attributes public : struct sqlca
sglca;
/ / Operations public : long Runstatso;
1; / / Define The RUnStatSO Member Function long API-Claas::RunStatsO {
/ / Declare The Local Memory Variables char *IndexArray = "USERID.EMP-NUM"; / / Create An Index On The EMPLOYEE Table EXEC SQL CREATE INDEX USERID.EMP-NUM ON USERID.EMPLOYEE(EMPN0); if (sglca.sglcode == SQL-RC-OK) {
tout << "Index EMP-NUM has been created for "; cout << "the EMPLOYEE table." << endl;
1 / / Update The Statistics For The EMPLOYEE Table, So That The / / EMP-NUM Index Will Be Used When Creating Access Plans
sglustat ("USERID.EMPLOYEE", 1, &IndexArray, SQL-STATS-ALL, SQL-STATS-RgF, &sglca); if (Bglca.sglcode == SQL-RC-OK) {
tout < c "The statistical information for the EMPLOYEE table cout << "has been updated." << endl;
1 / / Delete The Index On The EMPLOYEE Table EXEC SQL DROP INDEX USERID.EMP-NUM; if (sglca.sglcode == SQL-RC-OK) cout << "Index EMP-NUM has been deleted." << endl; / / Return The SQLCA Return Code To The Calling Function
";
This Page Intentionally Left Blank
-.
"
b-------
----
Disaster Recovery APIS When working with DB2 databases, it is important to keep in mind that problems can and willoccur. Most problems are directly related t o some type of media or storage failure, power interruptions, andor application failures. Because database problems can never beeliminated, it is imperative that a database administrator in charge of a DB2 Universal Database database become familiar with the different recovery mechanisms that areavailable with DB2. This chapter is designed to introduce you t o the setof DB2 AJ?I functions that areused to migrate, restart, back up, and restore DB2 databases and to work with a database's recovery history file (which keeps track of backup, restore, and bulk load operations)."he first part of this chapter providesa general discussion of the database migration process.Then, information about the database recovery mechanismsavailable with DB2 is provided.Next, the recoverv histom file that is automaticah mentnd nnd " I C i led be nd
Part 3: Application Programming Interface Functions
Database Migration DB2 Universal Database Version 5.2 is the seventh form of the Database 2 software product released for microcomputers. Each version of DB2 released has its own unique internal format for creating and storing database information. Becauseof significant differences between eachinternal format, databases created under one version of the DB2 product cannot be directly accessed by another version of DB2. However,databases created under earlier versions of DB2 can be convertedto a more recent version’s format. The MIGRATE DATAEWE function canbe used by an application to convert databases created under earlier versions of DB2 to DB2 Universal Database Version 5.2 format. Unfortunately, the database conversion process only performs upward compatibility conversions.You cannot convert DB2 Universal Database Version 5.2 databases to an earlier DB2 version format.
Recovering from an “Inconsistent” State Whenever oneor more transactions (also known as units of work) are unexpectdy interrupted, all databases being accessed at the time the transaction was interrupted are placed in aninconsistent or unstable state. Once placedin an inconsistent state, a database must be returned to a consistentstate before it can be used again. database A notifies an application that it is in an inconsistent state via a specificreturn code that gets generated whenthe application attempts to establish a connectionto the database. Any DB2 database can be returned to a consistent state by issuing the RESTART DATABASE command fromthe DB2 commandline processor-or by invoking the RESTART DATABASE API function from an application program. Whenthe RESTART DATABASE command or function callis executed, all incomplete or indoubt transactions that were still in memory whenthe transaction was interrupted are rolled back,and all completed transactions that were s t i l l in memory whenthe transaction was interrupted are committed. Figure 10-1 illustrates how a database is placed in and removed froman inconsistent state. The autorestart parameter in a DB2 database’s configuration file can also be used to return aninconsistent database to a consistentstate. By default, this parameter is set so that the RESTART DATABASEcommand is automatically executed wheneverthe DB2 Database Manager determines that a database is in an inconsistent state.
NOTE:DB2 Database Manager checks the state of a database when it attempts to establish the first connection to the database. The =START DATABASE function is designed to handle database problems that are caused by powerinterruptions and application failure. However, the RESTART DATABASE function cannot handle database problems that occur becauseof media or storage failure. To handle these types of problems,the DatabaseAdministrator must establish some type of backuphestore program.
Chapter 10: Database Migration and Disaster Recovery APIs
TIME
F
Figure 10-1 Normal processing4 transactions are executed, they are written to a memory buffer and toa transaction log file. When transactions are ended (with ROLLBACK is full, all or COMMIT), the transaction log fileis updated. When the memory buffer transactions stored there are written to the database. a memory buffer Abnormal processing4 transactions are executed, they are written to and to a transaction log file. When the transaction is unexpectedly interrupted, the database is placed in an inconsistent state. When the database is restarted, all completed transactions stored in the transaction log are fileapplied to the database;all incomplete or indoubt transactions are rolled back.
BW U Creating Backup Images DB2 provides a utility for creating backup imagesof a database or of one or more individual table spaces within a database. Backup images can be created by issuing the BACKUP DATABASE command from the DB2 command line processor-or by incorporating
I
332
!
Part 3 Application Programming Interface Functions
L . " " l
the BACKUP D A T w E API functionin an application program. After one or more backup images are created, they can be used to rebuild a database or a table space if either become damaged or corrupted. A special file,known as the database recovery file, is automaticallycreated when the first backup imageis created. Once created, this file is updated withsummary information each timea new backup imageis made.
IRestoring Datbase and Table Spaces from Backup Images Whenever a database or one of its table spaces becomes damagedor corrupt, it can be restored to its state when the last backup image was made by executing the RESTORE DATABASEfunction or command. Becausethe database recovery history file containssummary information about each backup image created, the file is used as a tracking mechanism during a recovery (restore) operation. Each backup image fde contains special information in its header that is checked against the records in the recovery history file to verify that thebackup image being used corresponds to the database being restored. Each backup image also contains a copy ofthe database's recoveryhistory file. When a backup image is used to restore an existing database, its recovery history file is not overwritten. If, however, a backup image is used to create a new database (a backup image can be used to create an exact duplicate of the database that thebackup image was created from), the recovery history file stored in the backup image becomes the recovery history fde for that database. If the current databaseis unstable, and if its recovery history file is damaged or has been deleted,just therecovery history file itself can be restored from a backup image.
m
FW Performing Redirected Restore
Operations Backup imagescontain a list of all table space containers that were being usedat the time the backup image was made. Duringa restore operation, all table space containers listed in the backup image are checked to see if they still exist and areaccessible. If one or more of these table space containers no longer exists or is no longer accessible, the restore operationwill fail. When this condition exists,table space containerscan be redefined during a special restore operation known as a redirected restore. The SET TABLESPACE CONTAINERS API function is used t o define newtable spaces during a redirected restore operation. Because there is no SET TABLESPACE CONTAINERS command, redirected restore operations can only be performed byan application program. When new table space containers are defined during a redirected restore operation, all previous table space containers defined for the specified table space become invalid.Unfortunately, DB2 does not automatically release the media storage used by invalid table space containers.T h i s task mustbe performed by the Database Administrator after the redirected restore operation has completed.
Chapter 10: Database Migration and Disaster Recovery M I S
Using Roll-Forward Recovery When a database is restored from a backup image, all changes made to the database since the backup image was created will be discarded unless roll-forward recovery has been enabled. Roll-forward is enabled by setting thelogretain and/or the userexit parameter in thedatabase configuration fileto the appropriate value. Roll-forward recovery uses a database's transaction log files t o reapply some or all changes recorded since the last backup image was made to the database. The Roll-Forward Recovery Utility is invoked byissuing the ROLLFORWARD DATABASE command fromthe DB2 command line processor-or by incorporating the ROLLFORWARD DATABASE API function in an application program. A roll-forward recovery operation can follow the completion of a full database restore operation, or it can be performedon any table space that is in a "Rollforward Pending"state. However, ifa roll-forward recovery operation is to follow a full database restore, all database log files must be copied to a separate directory before the restore operation is performed (otherwise, they will be replaced with the log files stored in the backup imageduring the restore operation). These log files must then be copied to the appropriate log file path (as specified in the database configuration file) after the restore operation executes and before the ROLLFORWARD DATABASE function is called or the directory that they are stored in must be specified when the ROLLFORWARD DATABASE command or function is invoked. If the database transaction log files cannotbe accessed bythe Roll-Forward Recovery Utility, the roll-forward recovery operation will fail. Figure10-2 illustrates how roll-forward recovery is used in conjunction withthe backup and restore utilities to return a database to the stateit was in at a specified pointin time. If a roll-forward recovery operationis to follow a redirected restore, it may not be desirable to reapply table space container changes recorded in thedatabase's transaction log files (for example, the if specified table spaces no longer exist).When an appliationinvokes the SET TABLESPACE CONTAINERS function to redefine table space containers during a redirected restore operation, it can specify whether table space container transactions found in the database's transaction log files are to be reapplied or ignored.
Recovery History Files As mentioned earlier, a recovery history fileis created when a database is created and is automatically updatedin the following situations: When the database or one of its table spaces is backed up H When the database or one of its table spaces is restored
When one of the database's tables is loaded The recovery history file contains a summary of backup informationthat is used in case all or part of the database must be recovered to a specific pointin time (roll-forward'
Part 3: Application Programming Interface Functions RECOVERY HISTORY FILE
DATABASE DATABASE
4
ONS RESTORE ROL APPLIED DATABASE DATABASE
ARD
0
BACKUP
IMAGE
TIME Figure 10-2 As transactions are applied to the database, they are also written to the changes recovery history file. When the database is restored from the backupallimage, was created are lost. When roll-forward made to the database since the backup image recovery is applied to the database [using the recovery history file], the database inis theleft same stateas it was before the restore operation began.
recovery). The informationstored in this file includesthe following:
m The tables and table spaces of the database that were backed up, restored,or loaded How the backup, restore, or load operation was performed The timethe backup image was made (if a backup operation was performed) The locationof the backup or copy image that was created(stating both the device information and the logical way to access the image) The last time a restore operation was performed Each backup image containsa copy of the database’s recovery history file. When a backup imagei s restored to a database that already has a recovery history file, the existing recovery history fileis not overwritten.However, ifa backup imageis restored to a new database, the recovery history file stored in the backup image becomesthe recovery history file for that database. If the current database is unstable or unavailable and if ita recovery history fileis damaged or has been deleted,just therecovery history file
Chapter 10: Database Migration and
i 33g
Disaster Recovery APIs ,
itself can be restored from a backup image. An application can retrieve records (entries) stored in a database recovery history file by performingthe following steps: 1. Call the OPEN RECOVERY HISTORY FILE
SCANfunction to copy select recovery history file records t o a function-allocated memorystorage buffer. 2. Allocate a sqluhinfo structure with space forx number of table spaces, wherex is the value returned in theNumEntries parameter after the OPEN RECOVERY HISTORY FILE SCANfunction is called. This number is normally the number of table spaces that have been defmed for the specified database. You can use the macro SQLUHINFOSIZE(X),defined in sqlutil.h, to determine how much memoryis required for a sqluhinfo structure with x table space fields. 3. Set thesqln field of the allocated sqluhinfo structure to x 4. In a loop, performingthe following steps: a. Call the QET NEXTRECOVERY FILE HISTORY ENTRY function to retrieve records from the history file. b. Check the sqlca.sqlcode value returned by the GET NEXT RECOVERY FILE HISTORY ENTRY function call. Ifthe sqlca.sqlcode value is SQL-RC-OK, use the sqld field of the sqluhinfo structure to determine the number of table space entries returned. If the sqlca.sqlcode value is SQLUH-SQLUHINFO-VARS-WARNING (meaning not enough spaceis allocated forall the table spaces that DB2 is trying to return), free and reallocate the sqluhinfo structure with enough space forsqld table space entries-and set sqln to sqld. If the sqlca.sqlcode value is SQLE-RC-NOMORE, all records have beenretrieved. c. Display or process the information retrieved. 5. When all recovery history fde records are retrieved, call the CLOSE RECOVERY HISTORY FILE SCANfunction t o free the resources allocated bythe OPEN RECOVERY HISTORY FILE s ~ ~ ~ f u n c t i o n .
You can changeentries in a database recovery history file by call the UPDATE RECOVERY HISTORY FILE function and you can remove entries in a recovery history file that are no longer valid(or needed) by callingthe PRUNE RECOVERY HISTORY FILE function.
W! The DB2 Database Migration And
Disaster Recovery Functions Table 10-1 lists the DB2 API functionsthat areused to migrate, restart, backup, and restore DB2 databases, and that areused t o manipulate a database's recovery history file. Each of these functions are described in detail in theremainder of t h i s chapter.
I
. ,
336 i i
Part 3: Application Programming Interface Functions
,
8-
Database Migration andRecovery APls
Table 10-1
MIGRATE
DATABASE
Converts databases created underprevious versionsof DBW2 and DB2/6000 to DB2 for CommonServers, version 2.1.
RESTART
DATABASE
Restarts a database that hasbeen left in an inconsistent state.
BACKUP DATAEIASE
Creates a backup image of a database or of one or more table spaces.
RESTORE
Rebuilds a database (or one ormore table spaces)by restoring themfrom a backup image.
DATABASE
RECONCILE
Validates all references to external files that aremade by DATALINK data columns in a specificdatabase table.
SET
Allows adatabase to be restored into a different set of table space storage containers.
TABLESPACECONTAINERS DATABASE
Restores a database (or one or more table spaces)by applying transactionsrecorded in the databaselog files to it after it hasbeen restored from a backup image.
ASYNC€IRONOIJS READ LOG
Extracts specific logrecords from a DB2 Universal Database transactionlog fileOR queries the Log Manager for current log state information.
ROLLFORWARD
OPEN RECOVERY
QET
NEXT
CLOSE UPDATE PRUNE
HISTORY
RECOVERY
RECOVERY RECOVERY RECOVERY
FILE SCAN
HISTORY ENTRY FILE
HISTORY HISTORY HISTORY
FILE SCAN FILE FILE
Stores a copy ofselected records retrieved from a database recovery history file in memory. Retrieves a record fromthe copy ofrecovery history file records that was placed in memory by the OPEN RECOVERY HISTORY FILE s ~ ~ ~ f u n c t i o n . Frees system resources allocated by the OPEN RECOVERY HISTORY FILE ScANfunction. Changes the location, devicetype,or comment associated with a record in a recovery history file. Removes oneor more records from a recovery history file.
Chapter 10: Database Migrationand Disaster Recovery APIs
m1111 MIGRATE DATABASE Purpose
"he MIGRATE DATABASE function is used to convert databases created under previous versions of DB2 to DB2 Universal Database Version 5.2 format.
syntax
SQL-API-RC SQL-API-FN
Parameters
DBAlias UserID
Password
SQLCA
eqlemgdb (char *UserID, char char etruct sqlca
*DBAliaE,
*PassworU, *SQLCA);
A pointer to a location in memory where the alias of a database that was createdwith an earlier version of DB2 is stored. A pointer to a location in memorywhere the user's authorization name (user identifier) is stored. This name is the name under which the attachment is authenticated. This parameter can contain a NULL value. A pointer to a location in memory where the password for the authorization name specifiedis stored. This parameter can.contain a NULL value. A pointer to a location in memorywhere a SQL Communications Area (SQLCA)data structurevariable is stored. This variable returns either status information (ifthe function executed successfully) or error information (if the function failed)to the calling application.
Iml*s
#include <eqlenv.h>
Description
The MIGRATE DATmAsE function is used to convert databases created under previous versions of DB2 to DB2 Universal Database Version 5.2 format. Databases created under the following DB2 productscan be converted bythe DB2 Universal Database Version 5.2database migration process: M DB2 for OS/2, Version 1.x
DB2 for OS/2, Version 2.x M DB2 for AM, Version 1.x N DB2 forAM,Version 2.x N DB2 for HP-UX, Version 2.x M DB2 for Solaris, Version 2.x N DB2 for WindowsNT, Version 2.x M DB2 Parallel Edition, Version 1.x Once a database has been converted (migrated)to DB2 Universal Database Version 5.2 format,it cannot bereturned to its original format. Becauseof this, it is a good idea to create a backup imageof a database before it is migrated.
I 338 1 1 Comments
Part 3 Application Programming Interface Functions E A database must be cataloged in the system datlabase directory before it can be
migrated.
B You can use the Database he-Migration Tool (db2ckmig command) to determine whether or not a DB2 database can be migrated (refer to the ZBM DB2 Command Reference for more informationabout this tool).
Connection This function can be called at any time; a connectionto a DB2 Database Manager Requirements instance or to a DB2 database does not haveto be established first. When this function is called, it establishes a connectionto the specified database. Authorization Only users with System Administrator (SYSADM)authority can execute this €unction call.
see Also Example
BACXUP DATABASE
The following C++ program illustrates how to use the MIGRATE DATABASE function to convert aDB2 for WindowsNT Version 2.0 database to the DB2 Universal Database Version 5.2 format
/* /* /* /* /* /* /*
*/
NAME:
CH1OEXl.CPP PURPOSE: Illustrate H o w To Uee The Following DE2 API Function In A C++ Program:
*/
*/ */ */
MIGRATE DAT-E
/* / / Include The Appropriate #include <windows.h> #include #include <sqlenv.h> #include <sqlca.h>
*/ */ */
Header
Files
/ / Define The AFT-Claee Clase class MI-Class / / Attributes public : struct sqlca sqlca; / / operations public: long MigrateDB () i ?I
/ / Define The MigrateDB() Member Function long API-C1ass::MigrateDBO
c
/ / Migrate The DB2 Database To DB2 ODE Version 5.2 sqlemgdb (USAMPLE", UuserIDn, upassword", &sqlca);
Chapter 10: Database Migration and Disaster Recovery APIs // // // // if
1
/* /* /*
If The DB2 Database Was Migrated Successfully, Display Success Message Note: The Return Code 1103 Will Be Returned If The Database Is Already At The Current Level (sqlca.eqlcode =E SQL-RC-OK I1 sqlca.sq1code == 1103) cout << '"The SAMPLE databasehas been migrated." << end11
A
/ / Return The SQLCA Return return(eqlca.sqlcode);
Code To The Calling
Function
*/ */ */
The m i n Function
int main0 {
/ / Declare The Local M e m o r y Variables long rc = SQL-RC-OK;
/ / Migrate The SAMPLE Database rc Exaraple.MigrateDB()t
1
/ / Return To The Operating return )(rc ;
System
RESTART DATABASE purpo.=
smt=
Parameters
The RESTART m T i w m s function is used to restart a database that has been abnormally terminated and left in aninconsistent state. SQL-I-RC
SQL-MI-FN eqlerstd (char
*DBAliae,
char *UserID, char *Paeemrd, struct sqlca. *SQLCA);
DBAlias UserID
Password
A pointer to a location in memory where the alias of thedatabase to be restarted isstored. A pointer to a location in memory where the user's authorization name (user identifier) is stored. This name is thename under which the attachment is authenticated. This parameter can contain a NULL value. A pointer to a location in memory where the password for the
Part 3: Application Programming Interface Functions
SQLCA
authorization name specifiedis stored. This parameter can containa NULL value. A pointer to a location in memorywhere a SQLCommunications Area (SQLCA)data structurevariable is stored. "his variable returns either statusinformation (ifthe function executed successfully) or error information (ifthe function failed)to the calling application.
Includes
#include <sqlenv.h>
Description
The RESTART DATABASE function is used to restart a database that was abnormally terminated and left in an inconsistent state. This function should be called whenever an attemptto connect to a database produces an error message that indicates that the database must be restarted. This error message will only be generated if the previous session withthe specified database was terminated abnormally.
Comments
B
Upon successful completionof this function, a shared connection to the specified
database is maintained if the user who called the function has CONNECT authorization. B Whenever a database is restarted,a SQL w h g is generated ifone or more indoubt transactions exist (in this case, the database is usable). If the indoubt transactions are not resolved beforethe lastconnection to the database is terminated, however, another RESTART DATABASEfunction call must be issued before the database can be used again. Thetransaction APIs discussed in Chapter 13 can be usedto generate a list of and correctly process indoubttransactions. When this function is called, it establishes a connection to the specified database. Connection Requirements
Authorization No authorization is required to execute this function call.
see Also Example
CONNECT
(SQL statement)
Thefollowing C++ program illustrates how to use the RESTART DATAEASEfunction to restart a database that hasbeen left in aninconsistent state:
/* /* /* /*
CHlOEX2.SQC PURPOSE: Illustrate How To Use The Following DB2 API Function In A C++ Program:
NABtE:
/*
/* /* /*
RESTART
DATABASE
/ / Include The Appropriate Header Files #include <windowe.h> #include #include <sqlenv.h>
*/ */
*/ */ */
*/ */ */
Chapter 10: Database Migration and Disaster Recovery APIs #include <sql.h> / / Define The API-Class Class class "1-Class {
/ / Attributes public: struct sqlca sqlca;
1;
/ / operations public : long RestartDBOj
/ / Define The RestartDBO Member Function long API-C1ass::RestartDBO {
/ / If Necessary, RestartThe SpecifieU Database cout << "Restarting the database. Please wait." <( endl; sqlerstd('SAMPLE", '*userID", t8password**, Bsqlca) ; / / If UnableTo Restart The Database, Display An Error / / Message if (aqlca.sqlcoUe l = SQL-RC-OK) {
tout << "ERROR : Unable to restart the SAMPLEdatabase."; cout << endl; 1 / / Return The SQLCA ReturnCode To The Calling return(sqlca.sqlcode);
Function
1
/* /*
The
*/ -in
Function
/* int main0 {
/ / Declare The Local Memory Variables rc long = SQL-RC-OK; struct sqlca sqlca;
/ / Attempt To ConnectTo The SAMPLE Database EXEC SQL CONNECTTO SAMPLE USER userID USING // // // if
password;
If Necessary, RestartThe SpecifieU Database Note: The Return Code-1015 Will Be Returned If The Database Needs To Be Restarted (sqlca.eqlcode == -1015) rc P Example.RestartDB0;
*/ */
Part 3 Application Programming Interface Functions / / Issue A Rollback TO Free EXEC SQL ROLLBACK;
All
Locks
/ / Disconnect From The SAMPLE Database EXEC SQL DISCONNECTCURRENT; / / Return To The return(rc) ;
Operating
System
1
m BACKUPDATABASE Purpose
The BACKUP DATABASE function is used to create a backup copy of a database or of one or more table spaces.
Sm=
SQL-API-RC SQL-API-FN eqlubkup
Parameters
DBAlias Buffersize
BackupMode
(char *DBAliaE, unsigned long Buffersize, unsigned long BackupMode, unsigned long BackupType, unsigned long CallerAction, char *AppliCatiOnID, char *Timestamp, unsigned long NUmBuffere, struct eqlu-tablespace-bkret-list *T,3bleSpaCeLiEt, struct sqlu-mediplist *MediaTargetLiEt, char *UBerNme, char *PaSEWOrd, void *ReEervedl, unsigned long *VendomtioneSize, void *VeIIdOrOptiOnE, unsigned long Parallelism, unsigned long *Backupsize, void *Re~erved2, void *Reserved3 struct sqlca *SQLcA);
A pointer to a locationin memory wherethe alias name of the database to back up is stored. The size,in 4KB pages, that all temporary buffers created and used during the backup operation should be. Temporary backup buffersmust be at least eight 4KB pages in size. Specifies how the backup utility i s to be run.“ h i s parameter must be set t o one of the following values: SQLW_OFFLINE
The backuputility i s to be run off-line (i.e., noother applications can connect t o the database while the
Chapter 10: Database Migration and Disaster Recovery APIs backup operationis inprogress).
m SQLUB-ONLINE
BackupQpe
"he backup utility is to be run online (i.e.,other applications can connectto and access the database while the backup operationoccurs). Specifies the type of backup imageto create. T h i s parameter must be set to one of the following values:
m
SQLUB-FULL
A full database backup imageis to be created. SQLUB-TABLESPACE
A backup image containing one or more table spaces is t o be created. If this value is specified, a list of the appropriate table spaces must be provided in the TbbleSpaceList parameter. CallerAction
Specifies the action this function is to take when it is executed. This parameter must be set to one of the following values:
m
SQLUB-BACKUP
"he backup operationis to be started. SQLUB-NOINTERRUPT
m
The backup operationis to be started, and it isto run unattended. When this caller actionis specified, scenarios that normally require user intervention will be attempted without returning to the calling application (if they fail, they will generate an error). SQLUB-CONTINUE
"he backup operationis to be continued after the user has performed some actionthat was requested by the Backup utility (inserting a diskette, mounting a new tape, etc.). SQLUB-TERMINATE
The backup operationis to be terminated because the user failed to perform some actionthat was requested by the Backup utility. SQLUB-DEVICE-WRMINAW
A particular device is to be removed from the listof devices used by Backuputility. When a particular medium is full, the Backup utility returns a warning to the caller (while continuingto process usingthe remaining devices).By calling the BACKUP DATzmAsE function again with this caller action specified, you can remove the device that generated the warning condition
-F 344 : j
Part 3 Application Programming Interface Functions from the listof devices being used. SQLm3-PARAM-CHECK
The parameter values specified forthe m c m p DATABASE function are to be checked for validity."his caller action does not terminate thedatabase connection, nor doesit invoke the Backup utility. After using this caller actionto validate parameters, the mcmp DATABASEfunction can be called again withthe SQLW-CONTINW caller action specified to start the backup utility. SQLW-PARAM-CHECK-ONLY
The parameter values specified forthe m c m DATABASE function are to be checked for validity.This caller action does not invokethe backup utility,and it causes the m c m ~DATABASE function to terminate thedatabase connection upon completion. ApplicatwnID
A pointer to a location in memory wherethis function is to store a string that identifies the agent that is servicing the application. (You can use the application ID string to obtain information aboutthe progress of the backup operation via the database monitor).
Timestamp
NumBUffers TableSpaceList
MediunrgetList
UserName
Password
Reserved1
A pointer to a location in memory wherethis function is to store the time stamp (inIS0 format) that identifies when the backup image was created.This value is also storedin the backup image. The numberof temporary buffers that are to be created and used by the Backup utility. A pointer to a sqlu-tablespace-bkrst-list structure that contains a list of table space namesthat are to be used when creating a table space backup image. If a full database backup is to be performed,this parameter will be ignored. A pointer to a sqlu-media-list structure that contains a list of destination devices that areto be used forstoring the backup image. A pointer to a location in memory where the authorization name (user identifier) that is to be used to connect t o the database is stored. A pointer t o a location in memory where the password for the authorization name specified is stored. This parameter can containa Nuu value. A pointer that is reserved forlater use. For now,this parameter must always be set to NULL.
U i
.i
t
:
,
Chapter 10: Database Migration and Disaster Recovery APIs VendorOptionsSize VendorOptions
Parallelism
Backupsize
Reserved2 Reserved3
SQLCA
'
,!
.
I ; 345 ;
I
:
,
Thesize, in bytes, of the data stored in the structure referenced by the VendorOptwns parameter. A pointer to a sqlu-vendor structure that containsvendor specific informationthat is to be passed from the application callingthe BACKUP DATABASEfunction to one or more vendor-supplied functions. "he number of buffer manipulators that areto be used by the Backup utility (i.e., the degree of parallelism usedby the database). A pointer to a location in memory wherethis function is to store the size (in megabytes) of the backup imagethat was created. A pointer that is currently reserved for later use. For now, this parameter must always be set to NULL. A pointer that is reserved forlater use. For now, this parameter must always be set to NULL. A pointer to a location in memory wherea SQL Communications Area(SQLCA)data structurevariable is stored. T h i s variable returns either statusinformation (if the function executed successfully)or error information (if the function failed)to the calling application.
Includes
#include <sqlutil.h>
Description
The BACKUP DATABASE function is used to create a backup copy of a database or of one or more table spaces. If you havea database backup image available andthe database becomes damaged or corrupted, it can be returned to the stateit was in the last time it was backed up.Furthermore, if the database is enabled for roll-forward recovery, it can be restored to the state it was in just before the damage occurred. Table space level backup images can also be made for a database. You can usetable space backup imagesto repair problems that only affect specifictable spaces. Two special structures (sqlu-tablespace-bkrst-list and sqlu-media-list) are used to pass table space names and backup device informationto the Backup utility when this function is called. Thefirst of these structures, sqlu-tablespace-bkrst-list, is defined in sqlutil.h as follows: typedef struct sqlu-tableepace-bkret-list 1 long nun-entry$
etruct eqlu-tableepace-entry
eqlu-tableepace-bluet-list1 1
The number of entries */ in the list of table space*/ names etored in the */ / * the tableepace field */ *tableepace$ /* A pointer to an array of */ /* sqlu-tableepace-entry */ /* etructures that contain8 */a /* liet of table space names */
/* /* /*
This structure contains a pointer to an array of additional sqlu-tublespuce-entry structures thatare used to hold table space names. The sqlu-tublespuce-entry structure is defined in sq1util.h as follows: tmedef struct sqlu-tablespace-entry {
uneigned long
/* The
reserve-lent
/*
/* /*
/* /*
filler[l]
/* /*
char “=tZYtWI char 1 sqlu-tablespace-entry;
length of the table space name storedin the tableepace-entry field. This field is only ueed if the table spacename is not NULL-terminated. The table space name Reserved
*/ */ */
*/ */ */ */ */
The second specialstructure used by the BACKUP DATABASE function,the sqlu-media-list structure,is used to describe the type(s1 of media that thebackup image is to be written to.The sqlumdia-list structure is defined in sqluti1.h as -~ follows: typedef struct eqlugaedia-list {
char
media-type;
/*
Indicates that the media
/* type is one or more devices /* local /* (SQLU-LOCAL-MEDIA) , a
/* /*
char long
filler131 t
seesionst
DBP A8DM shared library (SQLU-ASDUEDIA), /vendor * aproduct shared /*library /* (SQLU-OTHER-MEDIA), /* or a user exit routine /* (SQLU-USELEXIT). Local /* devices can be any /* combinationof tapes, /* disks, or diekettee. /* Reserved /* The mmrber of entriesin /* the liet of devices /* stored in thetarget /* field
union sqlu-media-list-targets target1
/*
/* /* /* /*
/* /* 1 sqlugPedia-listI
/* /*
*/ */ */ */
*/ */
*/ */ */
*/ */ */ */ */ */
*/ */
*/ */
pointer to an array */ of one of toro type8 of */ structures that contains */ additional device */ information. Thetype */ ofstructureused is */ determined by the value */ specified in the */ media-type field. */
A
Chapter 10: Database Migration and Disaster Recovery APIs This structure contains a pointerto an arrayof structures that provide additional information about the specific media devicesto be used.This array can contain either of the following DB2-defined structures:
m
sqlu-media-entry sqlu-vendor
Local media information (SQLU-LOCALMEDIA) Other vendor specific media information (SQLU-OTHER-MEDIA)
The sqlu-media-entry structure is defined in sqluti1.h as follows: typeaef struct eqlu~nedia-entry
i unsigned long
reserve-leu;
char media-entry[2161; 1 eqlu-media-entry;
/* /* /* /* /*
The length of
the path name */ etorea in the media-entry field. */ This field is only used if the path*/ name is not NULL-terminated. */ A path valid name */
The sqlu-vendor structure is defined in sq1util.h as follows: typedef struct eqlu-vendor
i uneignea long reserve-lenl;
char
shr-libt2561;
unsigned long reserve-lenl;
char
filename[l561I
*/ / * The lengthof the sharedlibrary */ /* name stored in the 8hr-lib field. /* This field is only ueed if the shared */ / * library name is not null-terminated. */ a */ /* he name of vendor-supplied is usedfor */ / * sharedlibrarythat data */ /* etoring and retrieving input */ /* m e length op the load name stored in the */ /* eource-file /* filename fiela. This field is only ueed */ is not */ /* if thesource-filename */ /* NULL-terminated. */ /* The name of an input source file */ /* that.ie to beusedforproviding shared library / " infonnation to a
*/
1 eqlu-vendor;
The typeof structure used to provide additional information about specific media devices is determined bythe value specifiedin themedia-type field of the sqlu-media-list structure as follows:
m m
SQLU-LOCAL-MEDIA
m
SQLU-OTHER-MEDIA
SQLU-ADSM-MEDIA
One or more sqlu-media-entry structures. No structure is needed (ifthe ADSTAR Distributed Storage Manager (ADSM) shared library providedwith DB2 Universal Databasei s used). If a Merent version of an ADSM shared libraryis used, the SQLU-OTHER_MEDIA value should be used. One or more sqlu-vendor structures.
i
348
L".
i
I
"!
i ~
!
Part 3 Application Programming Interface Functions W SQLU-USER-EXIT
No structure is needed.(Note that this value can onlybe specified withOS/2.)
Refer to the IBM DB2Administration Guide fora general discussion of DB2 Universal Database's backup and restore utilities.
Comments
W If the BuckupQpe parameter is set to SQLUB-TABLESPACE, the TableSpaceList parameter must contain a pointer to a list of valid table space names. W The CaZlerAction parameter must be set to SQLUB-BACKUP, SQLUB-NOINTERRUPT, SQLUB-PARAM-CHECK or SQLUB-P--CHECK-ONLY the first time this function is called. W The CaZlerActionparameter should beset to SQLW-NOINTERRUPT whenever all media needed forthe backup operationis available anduser interaction is not needed. W The applicationID string returnedby this function can beup to 33 characters in length (including the NULL-terminator character). W The timestamp stringreturned by this function can beup to 15 characters in length (including the NuLGterminator character). The sqlu-vendor structure that theVendoroptions parameter referencesmust be flat (i.e., it must not contain any levelof indirection). Bytereversal is not performed on this structure andcode pagevalues are not compared. W Online backupsare only permitted if roll-forward recoveryis enabled. An online backup can be performed whilethe database is being accessed and modified by other applications. W In order to perform an ofltline backup, the Backup utility must beable to connect to the specified database in exclusive mode. Therefore,this function willfail if any application,including the application callingthe BACKUP DATABASEfunction, is connected to the specified database. If the Backup utility can connectt o the specified database in exclusive mode,it will lock out all other applicationsuntil the backup operation is complete. Becausethe time required to create a database backup image can besignificant (especially forlarge databases), o f h e backups should only be performed when a database will not be needed by other applicationsfor an extended periodof time.
An oftline backupoperation will fail if the specified database or table space(s) are not in a consistent state. If the specified database is not in a consistent state, it must be restarted with the RESTART DATABASE function (tobring it back to a consistent state)before this function can be executed. W Backup images can bedirected to fixed disks, diskettes, tapes, ADSM, or other vendor products that are enabled for DB2. In order to direct backup imagesto tapes in OS/2, a unique device driver for the tape drive being usedmust be installed (there is no native tape support in OS/2), and this function must be called with SQLO-USER-EXIT specified as the media type (in the media-type field of the sqlu-media-list data structurestored in the MedianrgetListparameter).
W Although you canuse the BACKUP DATABASE function to back up databases located
I
Chapter 10: Database Migration and Disaster Recovery APIs
;
i
349
I__ - . .- ..
at remote sites, the backup imageitself must be directed to devices that arelocal to the machine on which the database resides (unless ADSM or another DB2enabled vendor productis used). WithADSM and other DB2-enabled vendor products, the interface for the backup is local, but the location of the storage media to which the backup imageis to be written can be remote. H If a database that hasbeen enabled for roll-forward recovery is backed up, it can be returned to the stateit was in at a specific pointin time (refer to the msmm DATABASE and ROLLFORWARD DATABASE functions for more information). H If a database is left in a partially restored state because of a system failure during restoration, the restore operation must be successfullyrerun before this function can be executed. If the databaseis placed in the "Rollforward-Pending"state after a successful restoration, the database must also be rolled forwardto a consistent state before this function can be executed. H If a database is changed fromthe "Rollforward Disabled"to the "Rollforward Enabled" state, either the logretain or userexit database configuration parameter must be set appropriately before this function can be executed (refer to Chapter 7 for more informationabout retrieving and setting database configuration parameters). H A table space level backup image cancontain one or more table spaces. H While onetable space is being restored, all other table spaces are available for processing. H To ensure that restored table spaces are synchronized withthe rest of the database, they must be rolled forwardto theend of the recovery history log f l e (or to the point wherethe table spaces werelast used). Because of this, table space level backup images can only be made if roll-forward recovery is enabled. H A user might choose to store data, indexes, long field(LONG) data, andlarge object (LOB)data in Merent table spaces. If LONG and LOB data do not reside in the same table space, a table space backupcannot be performed. H You can backup andrestore each componentof a table by independentlybacking up andrestoring each table space in which the table components reside. H Temporary table spaces cannot be backed up. Ifa list of table spaces to be backed up contains one or more temporarytable space names,the backup operation will fail. H Table space level backupsand restores cannot be run concurrently. Connection This function can be called at any time; a connection to a DB2 Database Manager Requirements instance or to a DB2 database does not have t o be established first. When this function is called, it establishes a connection to the database specified. Authorization Only users with SystemAdministrator (SYSADM)authority, System Control (SYSCTRL) authority, or System Maintenance(SYSMATNT) authority can execute this function call.
Part 3: Application Programming Interface Functions see Also Example
tionID[33];
RESTORE DATABASE,ROLLFORWARD DATABASE,
RESTART DATABASE
The following C++ program illustrates how to use the BACKUP DATABASEfunction to back up the SAMPLE database to a subdirectory on the D: drive:
/* /* /* /* /* /* /* /*
*/ CHlOEX3.CPP PURPOSE: Illustrate How To Use The Following DB2 API Function In A C++ Program:
N A M E :
BACKUP
DATABASE
/ / Include The Appropriate #include <windws.h> #include #include
Header
Files
/ / Define The API-Class Class class -1-Class
i / / Attributes public : struct sqlca sqlca;
1;
/ / Operations public : long BackupDB ():
/ / Define The BackupDB() Member Function long API-Class ::BackupDB ( )
i / / Declare The Local Memory Variables struct sqluBedia-list Media-List; structsqlu-media-entryMedia-Entry: char Timestamp char 1271 ;
/ / Initialize The Media List Information Data Structure Media-List.media-type = SQLU-LOCAL-MEDIA; Media-List.eessione = l: strcpy(Media-Entry.media-entry, UD:\\Backupn); Media-Liet.target.media = brMedia-Entry; / / Tell The User That The Backup Process Is Being Started cout << "Starting Backup . . . I << endl << endl; / / Start Backing Up The SAMPLE Database Sqlubkup ("SAMPLE", 16, SQLUB-OFFLINE, SQLW-FULL, SQLW-BACKUP, ApplicationID, Timestamp, 4, NULL,
*/ */ */ */ */ */ */
l
I
i 1
I , :
Chapter 10: DatabaseMigration and Disaster Recovery APIs
I.
li
,
1
.
I
351
__ .- -
" "
/ / If The Database CouldNot Be BackedU p , Display An Error / / Message And Terminate The Backup Process if (sqlca.sqlcode I = SQL-RC-OK) {
tout << "ERROR : << eqlca.sq1code << endl; sqlubkup ("SAMPLE", 16, SQLW-OFFLINE, S Q L W - m L , SQLUB-TERMINATE, ApplicationID, Timestamp, 4. NULL, media-Liet, "US€irID", "password", NULL, NULL, NULL, hsqlca);
0,
1 / / If The SAMPLE Database / / Message Saying So
Was
Successfully
Backed Up, Display A
else
c
cout << '*The SAMPLE database was successfully backed up."; cout << endl;
1 / / Return The SQLCA ReturnCode To The Calling return(sqlca.sqlcode);
Function
1
*/ */ */
/"
Function
/* /*
The Main
int
main( 1
{
/ / Declare The Local Memory Variables long rc = SQL-RC-OK; / / Create ~n Instance Of The -1-Class -1-ClassExample;
Class
/ / Back Up The SAMPLE Database rc = Example.BackupDB( 1 ;
W4 PM/ RESTOREDATABASE purpose
"he RESTORE DATABASE function is used to rebuildadamaged or corrupteddatabase (or one or more damaged or corrupted table spaces) by restoring it from a backup image (created with theBACKUP DATABASE command or function).
j I
i
l
i i
352 .. . .
!
,
Part 3: Application Programming Interface Functions
~
"
Parameters
SQL-API-RC SQL-API-FN
sqlurestore (char
SourceDBAlias
A pointer to a location in memory wherethe alias name of the database that was used to create the backup image (source)is stored. A pointer to a location in memory where the alias name of the target database that thebackup imageis to be restored to is stored. If this parameter is setto NULL, the backup image is restored t o the database alias specified in the SourceDBAlias parameter.
TargetDBAlias
*SourceDBAlias, char *TargetDBAlias, unsigned long Buffersize, unsigned long RollFomraFaode, unsigned long DatalinkMode, unsigned long RestoreType, unsigned long RestoreMode, unsigned long CallerAction, char *AppliCatiOnID, char *Timestamp, char *Targetpath, unsigned long muffera, char *RepOrtFile, struct e=lu-tableepacepkrst_liet *TableSpaceList, struct eplu-media-list *MediaSourceList, char *UserName, char *Password, void *Reservedl, unsignedlong VendorQptionsSize, void *VenUorOptions, unsignedlong Parallelim, void *RestoreInfo, void *ContainerPageList, void "Reserved2, structeqlca *SQLCA);
Buffersize
The size,in 4KB pages, that all temporary buffers created and used during the restore operation shouldbe. Temporary restore buffers must be at least sixteen 4KB pages in size.
RollForwardMode
Specifieswhether or not the database should beplaced in "Rollforward Pending"state after the database is restored. This parameter must be set to one of the following values:
m
SQLUD-ROLLFom)
The database is to be placed in "Rollforward Pending" state after it has been successfully restored. SQLUD-NOROLLFWD
The database is not to be placed in "Rollforward Pending" state after it has been successfully restored.
Chapter 10: Database Migration and Disaster Recovery APIs DatalinkMode
Specifies whether or not tables with DATALINK columns are to be placed in “Datalink Reconcile Pending”state and validation (reconciliation)of linked filesis to be performed (provided the table has theRECOVERY YES option specified).This parameter must be set to one of the following values: SQLIJD-DATALINK
Linked file validation (reconciliation)is to be performed by the restore utility. SQLIJD-NODATALINK
Linked file validation (reconciliation) is not t o be performed by the restore utility. Restorenpe
Specifies the type of restore operation to perform. This parameter must be set to one of the following values: SQLIJD-FULL
Everything foundin thebackup imageis to be restored. If this value is specified, the restore utility will be run offline. SQLIJD-ONLINF,-TABLESPACE
Only table space level information found in the backup image is to be restored. If this value is specified, the restore utility will be run online. SQLIJD-HISTORY
Only the database’s recovery history file is to be restored.
RestoreMode
Specifies how the restore utility is to be run. This parameter must be set to one of the f o l l o h g values: W SQLIJD-OFFLINE
The restore utility is t o be run offline (i.e.,no other applications can connectto the database while the restore operation is inprogress). SQLIJD-ONLINE
The restore utility is to be run online (i.e.,other applications can connectto and access the database while the restore operation is in progress). CallerAction
Specifies the action this function is to take when it is executed. T h i s parameter must be set to one of the following values: SQLIJD-=STORE
The restore operation is to be started. W SQLIJD-NOINTERRUPT
The restore operationis to be started and is to m unattended. When this caller actionis specified, scenarios
Part 3 Application Programming Interface Functions that normally require user intervention will be attempted without returning to the calling application (if the attempt fails, an error will be generated). SQLUD-CONTINW
The restore operation is to be continued aRer the user has performed some actionthat was requested by the Restore utility (for example,inserting a diskette or mounting anew tape). SQLUD-TERMINATE
The restore operation is to be terminated because the user failed to perform some actionthat was requested by the Restore utility. SQLUD-DEVICE-TERMINATE
A particular device is to be removed fromthe list of devices usedby the Restore utility. When particular a device has exhausted ita input, theRestore utility returns a warning to the caller (while continuing to process using the remaining devices).By calling the RESTORE DATABASE function again with this caller action specified,you can remove the device that generated the warning condition fromthe list of devices being used. SQLUD-PANLb-CHECK
The parameter values specified forthe RESTORE DATABASE function call are to be checked for validity. This caller action doesnot invoke the Restore utility. SQLUD-RESTORE-STORDEF
ApplicatwnID
TimStamp
12zrgetPath
One or more table space redefinitionsare to be performed during the restore operation. A pointer to a location in memory wheret h i s function is to store a string that identities the agent that is servicing the application. (You can use this application ID string to obtain idormation about the progress of the restore operation via the database monitor). A pointer to a locationin memory that contains a time stamp that identifies whenthe backup imageto be used was created.“his value is not needed if there is only one backup imageon the backup image source media specified. A pointer to a location in memory wherethe relative or fully qualifiedname of the targetdatabase is stored. “his parameter is only used if a new database is to be created from the backup image being used.
Chapter 10: Database Migration and Disaster Recovery APIs
. ,
NumBuffers ReportFile
!lbbleSpaceList
MediaSourceList
UserName
Password
Reservedl VendorOptwnsSize VendorOptwns
Parallelism
RestoreInfo ContainerPageList Reserved2 SQLCA
,
" -
I-
The numberof temporary buffers that areto be created and used by the Restore utility. A pointer to a locationin memory where the name ofthe file in which the names of all DATALINK files that become unlinked during the restore operationare to be reported is stored. A pointer to an sqlu-tablespace-bkrst-list structure that is currently reserved for later use. For now, this parameter must always be set to NULL.
A pointer to an sqlu-media-Zist structure that contains a list of devices that are to be used whenrestoring the database or one or more table spaces from a backup image created by the Backup utility. A pointer to a locationin memory wherethe authorization name (user identifier) that is to be used to connect to the database is stored. A pointer to a locationin memory where the password for the authorization name specified is stored. This parameter can contain a NULL value. A pointer that is currently reserved forlater use. For now, this parameter must always beset to NULL. The size,in bytes, of the datastored in the structure referenced by the VendorOptions parameter. A pointer to an sqlu-vendor structure that contains vendorspecific informationthat is to be passed fromthe application callingthe RESTOREDATABASE function to one or more vendor-supplied functions. The number of buffer manipulators that areto be used by the restore utility (i.e., the degree of parallelism used by the database). A pointer that is currently reserved forlater use. For now, this parameter must always beset to NULL. A pointer that is currently reserved for later use. For now, this parameter must always be set to NULL. A pointer that is currently reserved for later use. For now, this parameter must always be set to NULL. A pointer to a location in memory where SQL a Communications Area(SQLCA)data structure variable is stored. This variable returns either status information (if the function executed successfully)or error information (if the function failed) to the calling application.
Part 3 Application Programming Interface Functions Includes
#include <eqlutil.h>
Description
The RESTORE DATABASE function is used to rebuild a damaged or corrupted database (or one or more damagedor corrupted table spaces) byrestoring it from a backup image that was created with the BACKUP DATABASE command or function. Backup images of databases or table spaces must have beencreated with the BACKUP DATABASE command or function in order t o be used by the RESTORE DATABASE function. When adatabase is restored, it is placed in the same state it was in when the backup copy image was made. If the database was enabled for roll-forward recovery before the backup image was made, you can return it t o the stateit was in just before the damage occurredby executing the ROLLFORWARD DATABASE function after the RESTORE D A T m z m function is successfully executed.
NOTE: Database log files must be copied to a separate directory before a database is restored i f they are to be used to roll a database forward.Otherwise, they will be replaced with the log files stored in the backup imageduring the restore operation. Theselog files must then be copied to the appropriate log file path ( a sspecified in the database configuration file) afterthe restore operation executesand before the ROLLFORWARD DATABASEfunction is called-r the directoy they are stored in mustbe specified in the Overf1owLogPathparameter of the ROLLFORWARD DATABASEfunction. If these logfiles cannot be accessed by the roll-forward recovery utility, the roll-forward recovery operation will fail (refer to the ROLLFORWARD DATABASE function for more informution). A database backup image canbe restored m a new database if the original database from whichthe backup image was made no longer exists (the new database will havethe same name). Also, because adatabase backup imagecan be restored to a database with a different name,the RESTORE DATABASEfunction essentially provides a method for copying entire databases. You can also use the RESTORE DATABASE function to restore one or more table spaces froma table space level backup image that was created with the BACKUP DATzmAsE function. Table space backup images can be usedto repair problems that only affect specifictable spaces. Two special structures (sqlu-tablespace-bkrst-list and sqlu-media-list) are used to pass table space namesand restore device informationto the Restore utility when t h i s function is called. Referto the BACKUP DATABASEfunction for a detailed description of each of these structures and for more information about how they are initialized.
Comments
H If a database is left in the "Rollforward Pending"state after it has been
successfully restored, the ROLLFORWARD DATABASEfunction must be executed before it can be usedby other applications. The CallerAction parameter must be set to SQLUD-RESTORE, SQLUD-NOINTERRUPT, SQLUD-RESTORE-STORDEF, or SQLUD-PARM-CHECK the fist time this function is called. H The CallerAction parameter should beset to SQLUD-NOINTERRUPT whenever all media needed forthe restore operation is available h d user interaction is not needed.
P
Chapter 10: Database Migration and Disaster Recovery APIs
i! I
’
’
I -357 -~ -
”
m The CullerAction parameter should beset to SQLUD-DEVICE-TERMINATE to close a device whenit is no longer needed.For example, ifa user is restoring a database from a backup imagestored on three tapevolumes using two tape devices, and all the dataon one of the tapes has been restored, the application callingthe RESTORE DATABASE function will receive control from the function, alongwith a SQL return code that indicates that theend of the tapewas reached. The application can then prompt the user to mount another tape, and if the user indicates that there areno more tapes, the application can call the RESTORE DATABASE function again with the CulZerAction parameter set to SQLUD-DEVICE-TERMINATE to signal that there isno more media available. The device driver will beterminated, but the restof the devices involvedin therestore operation will continueto have their input processed until all segments of the backup imageare restored (the number of segments in the backup imageis placed on the lastmedia deviceduring the backup process). H The applicationID string returned by this function can be up to 33 characters in length (including the NULL-terminator character). The time stamp stringspecified in theTimestamp parameter can be up t o 15 characters in length (including the NULLterminator character). m The sqlu-vendor structure that the Vendoroptions parameter references must be flat (i.e., it must not containany level of indirection). Byte reversal is not performed on this structureand code page values are not compared.
m In order to perform an offline restore, the Restore utility must be able to connect to the specified database in exclusive mode. Therefore,this function willfail if any application, includingthe application callingthe RESTORE DATABASE function, is connected to the specified database. If the Restore utility can connectto the specified database in exclusive mode,it will lock out all other applications until the restore operation is complete. Becausethe time required to restore a database from a backup image can besignificant (especially forlarge databases), ofline restores should onlybe performed whena database will notbe needed by other applications foran extended periodof time. m When restoring an existing database, if a system failure occurs during a crucial stage of the restore operation, the database will be left in a partially restored state, and the restore operation must be successfully rerun before anyusers and/or applications can connect t o the database. Unfortunately, this condition may notbe detected until an application or user attempts to connect to the partially restored database. When restoring to a nonexistent or new database, if a system failure occurs during a crucial stage of the restore operation, the restored database will be deleted (dropped). m If a database was not configured for roll-forward recovery when its backup image was made,and if the currentdatabase configuration filehas roll-forward recovery enabled, the user must either make a new backup imageof the database or disable
Part 3: Application Programming Interface Functions the Zogretain and userexit database configuration fileparameters immediately after the restore operation is completed. No user or application can connectto the database until one of these actions is performed. M If the Restorenpe parameter is set to SQLUD-HISTORY, the recovery history file
stored in thebackup image willbe restored over the existing recovery history file for the database, effectively erasing any changesthat were made to the recovery history file&er the backup image was created. If this action is undesirable, restore the recovery history fileto a new database so you can view its contents without destroyingany changes that have taken place sincethe backup image was made. Refer to the OPEN RECOVERY HISTORY FILE SCAN,GET NEXT RECOVERY HISTORY FILE ENTRY,and CLOSE RECOVERY HISTORY FILESCAN functions for information on how to view the contents of a recovery history file. If roll-forward recoveryis disabled fora database after a table space level backup image was made,you cannot restore the table space(s) from the backup table space image and then roll the table space(s1 forwardt o the currentpoint in time. Instead, all table space level backup images made prior to the time roll-forward recovery was disabled canno longer be used (the RESTORE DATABASE function will fail if the user attempts t o restore from sucha backup image).In cases whereyou cannot determine whether or a backup imageis invalid, the restore operation might appear to be successful. The invalid backup image will only be detected during the roll-forward recovery operation. In order to perform a redirected restore (a restore operation in which a database is restored and a different set of operating system storage containers are desired or required), the CaZZerAction parameter must be set to SQLUD-RESTORE-STORDEF and the SET TABLESPACE CONTAINERS function must be used to identify the new system storage locations. Referto the SET TABLESPACE CONTAINERS function for more information. M The current configuration file forthe database being restored will not be replaced by the configuration file storedin thebackup image unlessthe file is no longer usable. If the configuration fileis replaced, a warning messagewill be returned to the calling application.
Connection The connection requirements for this function are dependent upon the type of restore Requirements operation being performed When restoring a backup imageto an existing database, this function can be called at any time. A connection to a DB2 Database Manager instance or to a DB2 database does not haveto be established first. When this function is called, it establishes a connection to the database specified. M When restoring a backup imageto a new database, this function cannotbe called
unless a connection to both a DB2 Database Manager instance i d a DB2 database exists (an instance attachment is required to create the new database). M When restoring a backup imageto a new database at a remote DB2 Database Manager instance,an instance attachment must exist beforethis function is called.
i !
Chapter 10: Database Migration and Disaster Recovery APIs
j i I
1
1_5_9_
'
Authorization Only users with System Administrator(SYSADM) authority, System Control (SYSCTRL) authority, or System Maintenance(SYSMAINT)authority can execute this function to restore a backup imageto an existing database. Only users with either SYSCTRL or SYSADM authority can executethis function t o restore a backup image to a new database.
see Also
BACKUP
DATABASE, ROLLFORWARD DATABASE,MIGRATE DATABASE, SET
CONTAINE!RS,OET DATABASE
Example
ionID[33];
TABLESPACE
CONFIODRATION
The followingC++ program illustrates how to use the RESTORE DATABASEfunction to restore the SAMPLE database from a backup image storedin a subdirectory on the D: drive:
/* /* NAME: CHlOEX4.CPP /* PURPOSE: Illustrate How To Use The Following DB2 API Function /* In A C++ Program: /* DATABASE /* RESTORE /*
/*
/ / Include The Appropriate Header Pilee #include <windows.h> #include #include #include <eqlutil.h> #include <eqlca.h> / / Define The API-Claee Claee' claee API-Clams {
/ / Attributes public: etruct eqlca eqlca;
/ / Operatione public : long ReetoreDBO;
1; / / Define The ReetoreDBO Member Function long API-C1aee::ReetoreDBO
c
/ / Declare The Local Memory Variables etruct eqlu-media-list Media-List; etructeqlu-media-entryMedia-Entry; char
-
/ / Initialize The Media List Information Data Structure Media-Liet.media-type SQLU-LWAI-MEDIA; Media-Liet.eeeeione = 1;
*/ */ */ */ */ */
*/
*/
Part 3 Application Programming Interface Functions strcpy(Media-Entry.media_entry, "D:\\Backup"); Media-List.target.media = &Media-Entry; / / Tell The UserThat The Restore Process Is Being Started cout << "Starting Restore << endl << endl;
..."
/ / Start Restoring The SAMPLE Database eqlureetore (l#SAMPLE", "SAMPLE", 16, SQLUD-NOROLLFWD. SQLUD-NODATALINK, SQLUD-FULL, SQLUD-OFFLINE, SQLUD-RESTORE, ApplicationID, 0, "D:" I 4, NULL, NULL, &Media-List, '*userID", "password", NULL, NULL, 4, NULL, NULL, NULL, hsqlca);
/ / Ignore The Warning Message Stating That The / / Database Will Be Overwritten if (sqlca.sqlcode == 2529 I t sqlca.eqlcode m- 2539)
0,
Existing
c
SqlU~eStOre ("SAMPLE", "SAMPLE", 16, SQLUD-NOROLLFWD, SQLUD-NODATALINK, SQLUD-FULL, SQLUD-OFFLINE, SQLUD-CONTINUE, ApplicationID, 0, "D:", 4, NULL, NULL, &Media-List, "userID", "password", NULL, NULL, 4, NULL, NULL, NULL, hsqlca);
0,
1 / / If The Database Could Not Be Restored, DisplayAn Error / / Message And Terminate The Restore Process
if (SqlCa.SqlCOde l = SQL-RC-OK)
c
1
<< sqlca.sqlcode << endl; cout << "ERROR : sqlurestore ("SAMPLE", "SAMPLE", 16. SQLUD-NOROLLFWD, SQLUD-NODATALINK, SQLUD-FULL, SQLUD-OFFLINE, SQLUD-TERMINATE, ApplicationID, 0, "D:" , 4, NULL, NULL, &Media-List, '%werID", "password", NULL, NULL, 4, NULL, NULL. NULL, hsqlca);
/ / If The SAMPLE Database / / Message SayingSo else
0,
Was Restored Successfully, Display A
{
>
tout << "The SAMPLE database was successfully restored.#*; cout << endl;
/ / Return TheSQLCA Return return(sqlca.sqlcode);
CodeTo The
Calling
Function
j i I
Chapter 10: Database Migration
and Disaster Recovery APIs
: I
j/ 361
II l
*/
/*
/*
1
*/
The Main Function
* l
I*
int main() {
/ / Declare The Local Memory Variables long rc = SQL-RC-OK;
/ / Restore The SAMPLE Database rc = Example.RestoreDB() ; / / Return TO The return( rc ) ;
Operating
From A Backup
Image
System
m
RECONCILE
purpose
The RECONCILE function is used to validate any references to files that are stored in DATALINK columns of a specificdatabase table.
syntax
SQL-API-RC SQL-API-FN
sqlurcon (char char char char void struct sqlca
Parameters
*TableName, *Reeervedl, *DLFMServerName, *ReportFile, *Reserved2, *SQLCA);
TbbleName
A pointer to a locationin memory wherethe name of the table that DATALINK file validationis to be performed for is stored.
Reserved1
A pointer that iscurrently reserved forlater use. For now, this parameter must always contain ablank string (” ”). A pointer to a locationin memory wherethe name of a DATALINK File Server that was preconfigured for use with the database that the specified table resides in is stored. A pointerto a locationin memory wherethe name of the file in which informationabout all DATALINK files that have become unlinked will bewritten to is stored. A pointer that is currently reserved forlater use. For now, this parameter must always be set to NULL. A pointer to a locationin memory where a SQL Communications Area(SQLCA) data structurevariable is
DLFMServerName
ReportFile
Reserved2
SQLCA
Part 3: Application Programming Interface Functions stored. This structure returnseither status information (if the function executed successfully) or error information (if the function failed)to the calling application.
Includes
#include <eqlutil.h>
Description
The RECONCILE function is used to validate any references to files that arestored in DATALINK columns of a specificdatabase table. During reconciliation (validation), DB2 attempts to link DATALINK files that arereferenced by table data but that no longer exist according to DLFM server metadata (provided no other conflict is found). If, during reconciliation, a file reference link cannot be established,the violating rows remain in thetable, and the offendingDATALINK values are setto NULL. If the DATALINK columnis defined as NOT NULL, the TJRL part of the DATALINK value is replaced by a zerolength sting, and the comment remains untouched.
Comments
If no DLFM server name is specified in the DLFMServerName parameter when this function is called, reconciliationis performed with respect to all DATALINK data found in thetable. If aDLFM server name is specified, reconciliationis performed with respect to all DATALINK data found in the table that references the specified DLFM server. Other servers are not contacted. Before this function can be executed,the table specified must be in the"Datalink Reconcile Pending"state. If reconciliationis performed with respect to all DLFM servers, the table is takenout of the "Datalink Reconcile Pending"state when this function completes execution.If reconciliation is performed with respectto a single DLFM server, the table is only taken out of the "Datalink Reconcile Pending"state when this function completes executionif no other DLFM servers are referenced by DATALINKdata. If the integrity of the datais certain (after reconciliation has been performedin respect to one or more servers referenced by DATALINK data), a table can be taken out of "Datalink Reconcile Pending"state by issuing the SET CONSTRAINTS. IMMEDIATE UNCHECKED SQL statement.
..
This function can only be called if a connection to a database exists. Connection Requirements
Authorization Only users with System Administrator (SYSADM) authority, System Control (SYSCTRL) authority, System Maintenance(SYSMAINT) authority, Database Administrator (DBADM) authority, or CONTROL authority on the table specified are allowed t o execute thi5 function call.
see Also
RESTORE DATABASE
Example
Thefollowing C++ program illustrates how to use the RECONCILE function to validate a DATALINK file referencein a database table:
Chapter 10: Database Migration /* /* /* /* /*
1
363
and Disaster Recovery APIs
*/ NMdE: PURPOSE:
CRlOEX5.SQC Illustrate How To Use The Following DB2 ~n A C++ Program:
/*
*/
API Function
*/ */
*/ */ */
RECONCILE
/* /* ,
*/
/ / Include The Appropriate Header Files #include <windowe.h> #include #include <eqlutil.h> #include <sqlenv.h> #include <sql.h> / / Define The API-Claes Claee claee API-Claes {
/ / Attributes public : struct sqlca sqlca; / / Operations public: long Reconcile();
1; / / Define The .Reconcile() Member long API-C1aes::ReconcileO
I
Function
/ / Declare The Local Memory Variables char TableNamcr[20]; char ServerName 1201 ; char RecInfoFileName[801; / / Initialize The Local Variables etrcpy(TableName, nEXTERNAL-SITESn); strcpy(ServerName, ; etrcpy(RecInfoFileName, "C:\\REC_INFO.DAT"); / / Validate All DATALINK Referencee sqlurcon(TableName, "",ServerName, RecInfoFileName, NULL, brsqlca);
/ / If DATALINK Reference Information / / success Meeeage if (eqlca.sqlcode .I- SQL-RC-OK)
Was
Obtained,
Dieplay
{
cout cout COUt cout
<< << << <<
YInformation about all DATALINK references used "in the EXTERNAL-SITES table -re" << endl; UCOlleCted and placed in the file C:\\REC-1NFO.DAT."; endl;
A
Part 3: Application Programming Interface Functions / / Return The SQLCA Return return(sqlca.sqlcode);
Code TO The
Calling
Function
1
/* /* /*
The
Main
*/ */ */
Function
int main() / / Declare The Local Memory rc long = SQL-RC-OK; struct eqlca sqlca;
Variables
/ / Declare The SOL Host Memory Variable EXEC SQL BEGIN DECLARE SECTION; CTStringt2551; char char IString 11801 ; EXEC SQLEND DECLARE SECTION; / / Create ?m Instance Of The API-Class Class API-ClassExample; / / Connect To The SAMPLE Database EXEC SQL CONNECT TO SAMPLE USER;userID USINQ / / Create The EXTERN?G-SITES Table strcpy((char * ) CTString, ''CREATE TABLE etrcat((char * ) CTString,SITE-ID strcat( (char *) CTString, URL strcat( (char * ) CTString, LINKTYPE
paeeword;
EXTERNAL-SITES ( CHAR(2)NOT N m L , DATALINK(200) URL NO LINK CONTROL)
/ / Prepare The Create Table SOL Statement EXEC SQL PREPARE SQL-STMNT1FROM :CTString; if (sqlca.sqlcode =P SQL-RC-OK) {
/ / Execute The Insert Statement EXEC SQL EXECUTE SQL-STMNTl;
/ / Conunit The Transaction EXEC SQL COMXIT;
/ / Build An Insert SQL Statement String etrcpy(IString, "INSERT INTO EXTERNAI-SITES VALUES ( ' O l ' , Strcat(IString, "DLVALQE('http://dlfs.almaden.ibm.com/a.bt, strcat(IString, "'TJRL', 'IBM Data'))
") i
"1 3 "1 ; ") 1
Chapter 10: Database Migration and Disaster Recovery APIs / / Prepare The Insert SQL Statement EXEC SQL PREPARE SQL-STMNT FROM :IString; if (sqlca.sqlcode P= SQL-RC-OK) {
/ / Execute The Insert Statement EXEC SQL EXECUTE SQL-ST";
/ / Tell The User That The New Record Was Added if (sqlca.sqlcode -= SQL-RC-OK) {
tout << "New data has cout << endl << endl;
been
added to the SAMPLE database.";
1 1 / / cammit The Transaction EXEC SQL COMMIT1 / / Validate
rc
P
TheMTALINK Reference Example.Reconcile0;
/ / Disconnect From The SAMPLE Database EXEC SQL DISCONNECT CURRENT; / / Return To The Operating return( rc ) ;
System
1
m
BM SET TABLESPACECONTAINERS
purpose
The SET TABLESPACE CONTAINERS function is used to facilitate a redirected restore operation (a restore operation in which a database is restored and a different set of table space storage containersare desired or required).
syntax
SQL-API-RC SQL-API-FN sqlbstsc (StruCt
Parameters
SQLCA
SqlCa *SPLCA, unsigned long RecoveryOption, long unsigned TdleSpaceID, hTmContainers, long unsigned struct SQLB-TBSCONTQRY-DATA *ContainerData);
A pointer to a location in memory where a SQL Communications Area(SQLCA) data structure variable is stored. This variable returns either status information (ifthe function executed successfully) or error information (ifthe function failed) to the calling application.
Part 3: Application ProgrammingInterface Functions RecoveryOption
specifies how ALTER TABLESPACE operations found in a recovery logfile are to be handled when a rollforward database recovery operationis performed. This parameter must be set to one of the following values: SQLB-SET-CONT-INIT-STATE ALTER TABLESPACE operations foundin the
recovery log file(s> are to be redone when performing a roll-forward recovery operation SQLB-SET-CON"-FINAL-STATE ALTER TABLESPACE operations foundin the
recovery log file(s) are to be ignored when performing a roll-forward recovery operation TableSpaceID
The IDof the table space that one or more storage containers are to be redefined for.
NumContainers
The number of table space container definitions (elements)stored in the arrayof SQLB-TBSCONTQRYDATA structures referenced by the ContainerData parameter.
ContainerData
A pointer to an arrayof SQLB-TBSCONTQRYJlATA structures that contain oneor more table space container definitions.
Includes
#include <eqlutil.h>
Description
"he SET TABLESPACECONTAINERS function is used to facilitate a redirected restore operation (a restore operation in which a database is restored and a differentset of table space storage containers is desired or required). Before this function is executed, an array of special structures (SQLB-TBSCONTQRY-DATA)must first be allocated and initialized with table space container definitions. Referto the FETABLESPACE CONTAINER QUERY function for adetailed description of the SQLB-TBSCONTQRYDATA structure. Although an array of SQLB-TBSCONTQRYRATA structures must be provided, onlythe contppe, totalpages, n a m e , and nameLen fields of each structure mustbe initialized.AU other fields in this structure areignored. This function is used in conjunction with the RESTOREDATABASE function to restore a database or one or more table spaces that were backedup with the BACKUP m T m E command or function. A backup imageof a database, or of one or more table spaces, contains information about all table space containers that were defined for the database or table space(s) whenthe backup operationtook place. During a restore operation, all containers identified in thebackup imageare checked to see ifthey exist and are accessible. If one or more of these containers no longer exists or for
Chapter 10: Database Migration
and Disaster Recovery APIs
j 1
I 367 " I I
.
some reason has become inaccessible,the restore operation will fail. This function can be used t o add, change,or remove table space containersduring a restore operation, therebygetting around this problem and allowing a backup imageto be successfully restored. The following steps illustrate how to use this function in a redirected restore operation: 1. Call the RESTORE DATABASE function withthe CuZZerAction parameter set to SQLTJ"RFSTORE_STORDEF.
2. Wait for the RESTORE DATABASEfunction to return a SQL return code indicating
that one or more of the required table space containers is inaccessible.
3. Call the SET TABLESPACE CONTAINER function with the appropriate table space container definitionsand theRecoveryOptwn parameter set t o the appropriate state (SQLB-SET-CONT-FINAL_STATE is the recommended state to use). 4. Call the RESTORE DATABASE function again, this time with the CuZZerAction parameter set t o SQLUD_CONTINW. This will allow the restore operation to use the new table space container definitions. Any table space container referenced in recovery log file(s) will be ignored when the ROLLFORWARD DATABASE function is called (ifthe SQLB-SET-CONT-FINAL-STATE state was specified).
Comments
Only use this function when a table space is in a "Storage Definition Pending" or a "Storage Definition Allowed"state. These states occur during a restore operation, immediately priorto the restoration of database or table space pages. When creating the table space containerlist, keep in mind that there mustbe sufficient disk spacet o allow for the restore and roll-forward operationsto place all the original data into these new containers. Ifthere isnot enough disk space available, oneor more table spaces will be left in the "Recovery Pending"state until sufficient disk spaceis made available.It is a good idea to keep recordsof disk usage on a regular basis. Then, whena restore and roll-forward operation needsto be performed, you can determinein advance how much disk spacewill be required. W When new containers are defined foran existing table space, they will replace containers that currently exist forthe table space whenthe redirected restore operation is performed. When new containers replace existing containers, the existing containersare not automatically removed from the storage mediaon which they reside. Therefore, it is theuser's responsibility to remove unused containers after a redirected restore operation is performed.
Connection This function can only be called if a connection to a database exists. Requirements
Authorization Only users with either System Administrator(SYSADM) authority or System Control (SYSCTRL) authority are allowed to execute this function call.
i! 368 p
l".
.
.
l
1
P
!
Part 3 Application Programming Interface Functions
l
"I
See Also
Example
BACKUP DATABASE, RESTORE DATABASE, ROLLFORWARD DATABASE
Thefollowing C++ program illustrates how to use the SET TABLESPACE CONTAINERS function to redefine table space containersduring a restore operation:
/* /* /*
NAME:
CHlOEX6.SQC PURPOSE: Illuetrate How To Uee The Following DB2 API Function In A C++ Program: SET
TABLESPACE
CONTAINERS
/*
*/
/ / Include The Appropriate Header Filee #include <windowe.h> #include #include <eqlutil.h> #include <splenv.h> #include <eql.h>
/ / Define The API-Clae6 Claee claes API-Claee
i / / Attributes public : struct eqlca eqlca; / / Operatione public : long BackupDB () ; long ReetoreDB () ;
1; / / Define The BackupDB( ) Member long API-Claee ::BackupDB ( )
Function
i
/ / Declare The Local~ e m o r yVariable6 etmct eqlu-media-list Media-Liet; etmct sqlu-media-entryMedia-Entry; ApplicationID[33] 'char Timestamp char [a71 ;
1
/ / Initialize The Media Liet Information Data Structure Yedia-Liet.media-type I SQLU-LOCAL-MEDIA; Media-Liet.ee6SiOn6 = l; etrcpy(Media-Entry.media-entry, "D:\\Backup"); Media-Liet.target.media = &Media-Entry; / / Tell The veer That The Backup Proceee Ie Being Started cout << #'Starting Backup << endl << endl;
..."
*/ */
*/ */ */
/*
/* /*
*/
Chapter 10: Database Migration and Disaster Recovery APIs / / Start Backing Up The SAMPLE Database sqlubkup("SAMPLE", 16, SQLUB-OFFLINE, SQLUB-FULL, SQLUB-BACKUP, ApplicationID, TimeStamp, 4, NULL, &Media-List, "UserID", "password", NULL, 0, NULL, NULL, brsqlca); / / If The Database Could Not Be BackedUp, Display An Error / / Message AnB Terminate The Backup Process if (sqlca.sqlcode I n SQL-RC-OK) {
tout << -ERROR : << sqlca.sqlcode << end11 sqlubkup ( "SAMPLE", 16, SQLW-OFFLINE, SQLW-FULL, SQLUB-TERMINATE, ApplicationID, TimeStamp, 4, NULL, &Media-List, tauserID", "password", NULL, NULL, NULL, Gsqlca);
0,
1 / / If The SAMPLE Database / / Message SayingSo else
Was Successfully Backed Up, Display A
c
cout << "The SAMPLE database was successfully backed up."; cout << endl;
1 / / Return The SQLCA Return return(sqlca.sqlcode);
Code To The
Calling
Function
1 / / Define The RestoreDBO Member Function long API-Class: :RestoreDB () {
ApplicationID[331; '
/ / Declare The Local~ e m o r yVariables struct sqlu-media-list Media-List1 struct sqlu-media-entry Media-Entry; char BtlVCt SQLB-TBSCONTQRY-DATA TSContainers[3]; / / Initialize The Media List Information Data Structure Media-List.media-type = SQLU-LOCAG_MEDIAI Media-Liet.sessions 1; strcpy(Pedia_Entry.me8ia-entryr "D:\\Backup")i Media-List.target.media = srMedia-Entry;
-
/ / Tell The User That The Restore ProcessIs Being Started cout << "Starting Restore << endl << endl;
..."
/ / Start Restoring The SAMPLE Database sqlurestore("SAMPLE", "SAMPLE", 16, SQLUD-NOROLLFWD, SQLUD-NODATALINK, SQLUD-FULL, SQLUD-OFFLINE, SQLUD-=STORE-STORDEF, ApplicationID, 0 , "D:", 4, NULL, NULL, &Media-List, "userID", "password", NULL, NULL, 4, NULL, NULL, NULL, srsqlca);
0,
Part 3: Application Programming Interface Functions / / Ignore The Warning Meeeage Stating That The gxieting / / Database WillBe Overwritten if (8qlca.eqlcode = m 2529 I I eqlca.eqlcode =- 2539) {
eqlureetore('SAMPLE", "SAMPLE", 16, SQLUD-NOROLLFWD, SQLUD-NODATUINK, SQLUD-FULL, SQLUD-OFFLINE, SQLUD-CONTINUE, ApplicationID, 0, "D:", 4, NULL, NULL, &Media-Liet, "ueerID", upaeeword", NULL, NULL, 4, NULL, NULL, NULL, &eqlca);
0,
1 / / If The Error Meeeage Stating That A Table Space Container / / No Longer Exiete In Generated. DefineNew Table Space / / Containere if (eqlca. eqlcode == 1277) {
/ / Tell The User That New Table Space Containere Are Being / / Defined cout << "Defining New Table Spaces << endl << end18
..."
/ / Define A New List Of Table Space Containere TSContainere[Ol .contType m SQLB-COW-PATH; etrcpy(TSContainere[O].name, "D:\\NEW-TSP1.1"); TSContainere[ 11 contType .I SQLB-CONT-PATH; etrcpy(TSContainere[ll.name, "D:\\NEW-TSPl.2")t
.
/ / Set The New Table Space Containere eqlbetec(&aqlca, SQLB-SET-CONT-INIT-sTATE, 3, 2, (etruct SQLB-TBSCONTQRY-DATA *) &TSContainere[O] ) t / / If The New Table / / Display An Error
if ( eqlca
.aqlcoBeIP
Space Containere Message SQL-RC-OK)
Could Not Be Set,
{
tout << uERROR : eqlca.eqlcde return(eqlca.eqlcode);
epdl << endl;
1 / / Continue The Reetore Operation eqlureetore (USAMPLE", "SAMPLE", 16, SQLUD-NOROLLFWD. SQLUD-NODATALINK, SQLUD-FULL, SQLUD-OFFLINE, SQLVD-CONTINUE, ApplicationID, 0 , "D:", 4 , NULL, NULL, &Media-Liet, "ueerIDu, "PaSBWOrd", NULL, NULL, 4, NULL, NULL, NULL, &eqlca)i
1 / / If The Database CouldNot Be Restored, Dieplay An Error / / Meeeage And Terminate The Reetore PlOCeBS if (eqlca.eqlcode I = SQL-RC-OK) {
COUt << "ERROR : << eqlca. eqlcde << endlt eqlureetore("SAMPLE", "SAMPLE", 16, SQLUD-NOROLLFWD, SQLUD-NODATALINK, SQLUD-FULL, SQLUD-OFFLINE, SQLUD-TERMINATE, AppliCatiOnID, 0, "D:" , 4.
0,
i l
Chapter 10: Database Migration
d 371 1
and Disaster Recovery AF'Is
! 1
/ / If .TheSAMPLE Database / / Message Saying So else
i
Was Restored Successfully, Display A
cout << T h e SAMPLE databasewas euccesstully restored."; cout << endl;
1 / / Return The SQLCA Return Code To The return(eqlca.sqlc&e);
Calling
Function
1
/* /* ,
*/ */
The Main Function
int main( / / Declare The Local Memory P SQL-RC-OK; rc long struct sqlca eqlca;
Variables
/ / Create ?m Instance Of The -1-Class -1-ClassExample;
Class
/ / Connect To The SAMPLE Database SQL CONNECTTO SAMPLE USER userID
EXEC
USING
password;
/ / Create A TemporarySMS Table Space EXEC SQL CREATE TEMPORARY TABLESPACE MY-SPACE MANAGED BY SYSTIW USING ('D:\TMPTBSPl.TSP', 'D:\TMPTBSP2.TSP') EXTENTSIZE 256;
/ / Tell The User That The Table Space Was Created if (sqlca.sqlcode =P SQL-RC-OK)
I
cout << "The SMS Table Space MY-SPACE has been created."; c a t << endl;
1 / / Comnit The Transaction EXEC SQL COMMIT; / / Disconnect From The SAMPLE Database EXEC SQL DISCONNECTC U R R E N T ) / / Backup The SAMPLE Database rc = Example. BackupDB () ;
Part 3 Application Programming Interface Functions / / Re-Connect To The SAMPLE Database EXEC SQL CONNECT TO SAMPLE USER userID
USING paeewordi
/ / Delete The Table Space Created Earlier EXEC SQL DROP TABLESPACE MY-SPACE;
/ / Commit The Transaction EXEC SQL COMMIT; / / Re-create TheT m o r a r y SMS Table Space (Minuel Container) EXEC SQL CREATE TEMPORARY TABLESPACE MY-SPACE MANAGED BY SYSTEM USING ('D:\TmTBSPl.TSP') EXTENTSIZE 256; / / Tell The Deer That The Table Space Wae Modified if (sqlca.sqlcde == SQL-RC-OK) {
tout << "The SMS Table cout (< endl;
SpaceMY-SPACE hae been modif
ied. R ;
1 / / Commit The Traneaction EXEC SQL COMMIT; / / Disconnect From The SAMPLE CURRENT; EXEC SQL DISCONNECT
Database
/ / Reetore The SAMPLE Database rc = Example.ReetoreDB0; / / Return To The Operating return (re) ;
Syetem
1
l!@A
ROLLFORWARD DATABASE
purpo=
"he ROLLFORWARD DATABASEfunction is used to returna damaged or corrupted database (or one or more damagedor corrupted table spaces) to the stateit was in just before the damage occurred.
syntax
SQL-API-RC SQL-API-FN sqluroll (etruct rfwd-input *RfMInput, etruct rfwd-output *RfwaOutput, etruct eqlca *SQLcA);
Parameters
RfwdInput
A pointer to a rfwd-input structure that containsinformationabout the type of roll-forward recovery operationto perform.
Chapter 10: Database Migration and Disaster Recovery APIs RfwdOutput
ki
-'i
373
A pointer t o a rfwd-output structure where this function is to store information aboutthe statusof the roll-forward recovery operation just performed. A pointer to a location in memorywhere a SQL Communications Area (SQLCA)data structurevariable is stored. This structure returns either statusinformation (if the function executed successfully) or error information (ifthe function failed)to the calling application. '
SQLCA
'
Includes
#include <sqlutil.h>
Description
The ROLLFORWARD DATABASEfunction is used to return a damaged or corrupted database (or one or more damagedor corrupted table spaces)to the stateit was in just before the damage occurredby applying transactionsrecorded in thedatabase log files to it after a successful restore operation. When this function is called, the DB2 Database Manager uses information storedin both archivedand active log filesto reconstruct the transactions performedon the database since the last backup imagewas made. The ROLLFORWARD DATABASE function is normally called after the RESTORE DATABASEfunction has been used to restore a database or one or more table spaces, or when one or more table spaces have beentaken offline bythe database due to a media error.A database must be enabled for roll-forward recovery (that is, either the logretain parameter andlor the userexit parameter in thedatabase configuration file must be set appropriately) beforeit can be used with this function. Two special structures (rfwd-input and rfwd-output) are used to pass information to and obtain status information from the Roll-Forward Recoveryutility. Thefirst of these structures, rfwd-input, is defined in sq1util.h as follows: SQL-STRUCTURJ~ rfwd-input {
unsigned long vereion;
/* /* /* /*
/*
char
*pDbAlias;
unsigned short CallerAction:
char
*pStopTime;
Identifies the version of the ROLLFORWARD DATABASE fUnCtiOn parameters being used. This field should always be set to SQLUM-RFWD-mRSION.
*/ */ */ */ */ */
I* A pointer to a location in memory /* where the alias name of the */ /* database to be rolled forward is */ /* etored. */ /* Specifiee the action the */ /* ROLLFORWARDDATABASEfunction is */ /* to take when it is executed. This */ /* field must be set to one of the */ /* values shown in Table 10-2. */ /* A pointer to a location in memory */ /* where a time stamp value is etored */ /* (in IS0 format). This value is used */ /* to epecify a point in time to whichthe*/
i
'! 374 j
I
.
Part 3: Application Programming Interface Functions /* /* /*
database is to be rolled forward. */ If the value */ SQLUM-INFINITY-TIMESTAMP is used, */ /* the database will be rolled forward*/ /* as far as possible. */ char *pUserNamei /* A pointer to a location in memory */ /* where the authorization name (user */ /* ID) of the person performingthe */ /* roll-forward recovery operation is */ /* stored. */ char *pPassword: /* A pointer to a location in memory */ /* where the passwordf o r the */ /* authorization name specified inthe */ / * pUserName field is stored. This */ /* field can contain a NULLvalue. */ char *pOverflowLogPath; /* A pointer to a locationin memory */ /* where an alternate log file path */ /* (that is to be used when searching */ /* for active and archived log files) */ /* is stored. This field can contain a */ /* NULL value. */ unsigned short NumChngLgcwrflw: / * The numberof overflow log paths */ /* changed in a multi-node database */ /* environment (=P only). */ BtNCt sqlur€-Ilewlogpath*pChngLogOvrflw: /* A pointer to an array of structures */ /* that contain fully qualifiednames */ /* of changed overflow logpaths. */ /* These overflowlog paths only */ /* override the default overflow log */ /* path for the node specified. (=P */ /* only). */ unsigned short Connection~ode~ /* Specifies that the roll-forward */ /* recovery utility isto be run */ / * offline (SQLUM-OFFLINE), or online */ /* (SQLUM-ONLINE). The roll-forward */ /* recovery utility must run be offline */ / * if a database isbeing rolled */ /* forward: it can be run offline or */ /* online if a table spaceis being */ /* rolled forward. */ struct s p ~ u ~ t a b ~ e s p a c e ~ b k r s t _pTablespaceList; liet */ /* A pointer to a structure that */ /* contains a list of table space names */ /* that identify specific table spaces */ /* that are to be rolled forward. I€ no */ /* list of table space namesis */ /* provided ( i . e . , if this field is set */ /* to NULL), all table spacesthat need */ /* to be rolled forwardwill be. */
.
PI !
!
i
i
i :
Chapter 10: Database Migration ehort
and Disaster RecoveryAPIs
AllNOdeFhg:
/*
/* /*
/* /*
/* /*
8hOrt NunWodee;
/* /* /* /* /* /* /* /* /*
/*
I
j 375
I
Indicate8 whether the roll-forward operation ie to be performed at all nodee definedin the db2nodee.cfg configuration file (SQLURF-ALL-NODES), at the catalog node only (SQLURF-CAT-NODE-ONLY), at all nodee identified in the node liet that the pNodeLiet field of thi8 etructure referencee (SQLURF-NODE-LIST), or at all nodee except thoee identifiedin the node liet that the pNodeLiet field of thi8 etructure referencee (SQLURF-ALL-EXCEPT). The number of n d e e etored in the node liat that the pNodeLiet field of thie etructure referencee.
*/ */ */ */ */ */ */ */ */ */ */
A pointer to a locationin memory where an array of node numbereie etored.
*/ */
*/ */ */ */ */ */
SQL-PDB-NODE-TYPE
/*
/* /*
*/
ehort NunWodeInfo;
un8igned char
8hOrtDlMode 1 *pRepOrtFile;
/* /* /* /* /* /* /* /*
/*
:*
/* /* /*
NOTE: SQL-PDBJODE-TYPE
Identifies the number nodes that are*/ being rolled forward.In a eingle */ node environment, thie field m ~ 8 tbe */ aet to 1. */ Currently, thie fieldie not ueed */ and 8hOuld alwaysbe eet to 0. */ A pointer to a location in memory */ where the name of the file in which */ information about all DATAGINX file8 */ that become unlinkedduring the roll- */ forward recovery operation will be */ written to ie etored. */
is a type clefinitionfir eigned
short.
The rfwd-input structure contains apointer to an array sqlurf-newlogpath data structures and a pointer to a sqlu-tablespace-bkrst-list data structure. Thefirst of these, thesqlurf-newlogpath structure, is defined in sqluti1.h as follows: SQL-STRUCTURE eqlurf-newlogpath SQL-PDB-NODE-TYPE un8igned short pathlen;
ndenum;
/* /*
/* /* /*
A
number that identifieea epecific node*/ (withinamulti-node environment). */ The length of the overflow log path */ epecified in the logpath field of thie */ etructure. */
,
376
p i i. .
Table 10-2
,
Part 3: Application Programming Interface Functions
ROLLFORWARD DATABASEFunctionActions
SQLIJM-ROLLFWD
The database is to be rolled forward tothe point in time specified by the value storedin thepStopTime field of the rfwd-input structure. If this caller action is specified, the database will be placedin "Rollforward Pending" state.
SQLTJ!-STOP
"he roll-forward operation is to be terminated. If this caller action is specified, the databasewill be taken outof the "Rollforward Pending" state, no new log recordswill be processed,and all uncommitted transactions will be backedout.
SQLTJ"ROLLF(QD_STOP
The database is to be rolled forwardto the point in timespecified by the value storedin thepStopTime field of the rfwd-input structure, and the roll-forward operation i s to be terminated. If this caller action is specified, the databasewill betaken outof the "Rollforward Pending" state when the roll-forward operation terminates. Values forthe nextarclog,frstarcdel,lastamdel, and lastcommit fields of the sqlurf_infostructure are to be obtained fromthe recovery log files. This caller action does not invoke the Roll-Forward Recovery utility. Specifies that all parameterlstrudure valuesspecified forthe ROLLFORWARD DATABASE function call are to be checked for validity. This caller action does not invokethe Roll-Forward Recovery utility. "he roll-forward recoveryoperation that is currently runningis to be terminated. If this caller action i s specified, the database will be left in the "Recovery Pending"state. per"he roll-forward operation is to be continued after the user has formed someaction that was requested by the Roll-Forward Recovery utility (for example,mounting a new tape).
A particular device is to be removed fromthe list of devices used by the Roll-Forward Recovery utility. Whena particular device has exhausted ita input, theRoll-Forward Recoveryutility returns a warning to the application (while continuing to process using the remaining DATABASE function again with devices). By calling the ROLLFORWARD this caller action specified, youcan remove the device that generated the warning condition from the listof devices beingused.
All devices being usedby roll-forward recoveryare to be terminated.
char logpath12551
;
/* A pointer to a location in memory where */ /* au alternate log file path (thatis to */ /* be used when searching€or active and */ /* archived log files) is stored. */
It
Refer to the BACKUP DATABASEfunction for a detailed description of the sqlu-tablespacebkrst-list structure.
l
j
! /
Chapter 10: Database Migrationand Disaster Recovery APIs
j j 377
The second structure used bythis function, the rfwd-output structure, is defined
in sqlutil. h as follows:
char
*pApplicationIdr
long
*pNumRepliee;
etruct eqlurf"0
~ n l € o ;
/* /* /* /*
location in memory */ wheretheROLLFORWARDDATABASE */ function ie to etore a etring that */ identifieetheagentthat ie */ /* servicing the application. This */ /* ID can be used to obtain */ /* information about the progrese of */ /* a roll-fornard recovery operation.*/ /* Thie field can contain a m~ */ /* value. */ /* A pointer to a location in memory */ */ /* where the ROLLFORWARD DATABASE /* function ie to store thenumber of */ /* node repliee received. Each node */ /* that repliee fills in a sqlurf-info*/ /* sqlurf-info structure. In a */ /* eingle-node environment, the value */ /* 1 ie alwaye returned. */ /* A pointer to a ueer-defined array */ /* of etructures that the ROLLFORWARD*/ /* DATABASE */ /* function is to etore information */ /* about each node involved in a */ /* roll-forward recovery operation. */ A pointer to a
This structure contains a pointer to an array ofsqlurf-info structures. T h e sqlurf-info structure is defined in sq1util.h as follows: SQL-STRUCTURE eqlurf-info {
long etate; uneigned char nextarclog 1131 ;
/*current The state /* The name of /* fileneeded utility. /* Recovery
of a node. the next recovery log by theRoll-Rorward
*/ */ */ */
uneigned char firstarcdel[l3]~
/*
/*
/*
/* . /* /* /*
uneigned char laetarcdel[13];
uneigned char laetcolmait[271;
/* /* /* /*
The name o f the firet recovery log */ file used (and no longer needed) by */ the Roll-Forward Recovery utility. */ The name of the laet recovery log file*/ ueed (and no longer needed) by the */ Roll-Forward Recovery utility. */ A time stamp (in IS0 format) that */ identifiee when the laet traneaction*/ wae committed. This value ie provided */ afterthe Roll-Forward Recovery */ terminatea. operation */
NOTE:Log files mustbe copied to a separate directory beforea database is restored if they are to be used to roll a database forward (otherwise, they will be replaced with thelog files stored in the backup imuge during therestore operation). These log files must thenbe copied to the appropriate log file path ( a sspecifid in the database configuration file) after the restore operation executes and befbre the ROLLFORWARD DATABASE function is called (or the directory in which they are stored must be specif2d in the OverflowLogPath parameter). If these log files cannot be accessed by the Roll-Forward Recovery utility, the roll-forward recovery operation will fail. Once roll-forward recoveryis started, it will not stop until one of the following events occurs: H No more recovery log files are found in thespecified directories. M A time stamp in the current recovery logfile being used exceedsthe completion
time stamp specified in thepstopnme field of the rfwd-input structure. H
Comments
An error occurs whilereading a recovery log file.
H The CallerAction field of the rfwd-input structure must be set to SQLUM-ROLLFWD, SQLRQWRY,
or S
Q L R P ~ C ~ C Xthe
firsttime this functionis called.
M The pStopTime field of the rfwd-input structure mustbe set to SQLIJM-INFINITY-TIMZSTAMP,
for table space roll-forward recovery operations.
M If the CallerAction field of the rfwd-input structure is setto anything other than SQLRQWRY and a filenameis returned in thenextarclog field of the sqlurf-info structure, an error occurred whileattempting to access that file. Possible causesof this type of error include the following:
-The file was not found in thedatabase log directory nor in the pathspecified in the pOverflowLogPath field of the rfwd-input structure. -The user exit program failedto return thearchived recovery log file. H AU log filesup to and including the log file(name) returned in thelastarcdel field
of the sqlurf-info structure parameter can be removed fromthe storage media to make room for other files. For example, ifthe recovery log file name returned in the firstarcdel field of the sqlurf-info parameter is SOOOOOOl.LOG, and the recovery log filename returned in thelastarcdel field is SOOOOOO5.LOG, the following recovery log files can be deleted SOOOOOOl.LOG, SOOOOOO2.LOG, SOOOOOO3.LOG,SOOOOOO4.LOG, and SOOOOOO5.LOG.
F ,
l
l
Chapter 10: Database Migration and Disaster Recovery M I S
'
i
{
I
(
:
i
[ j 1
-
379
During roll-forward recovery, all recovery log filesare searched for, first in the directory specifiedin the logpath parameter of the database configuration fileand then in theoverflow logpath specified in the pOverflowLogPath field of the rfwd-input structure. If no overflow log path is specified, all active log files and archived log files needto be located in theZogpath directory. This means that one or more log files might have to be physically moved from one location to another before they can be used by the Roll-Forward Recoveryutilib. With this approach, problems can occur there if is not sufficient space in thelogpath directory. If you store the location of archived recovery log files in the pOverflowLogPath field of the rfwd-input structure, recovery logfiles do not have to be moved-and potential problems can be avoided.
W In a multi-node environment,the overflow log path specified must be a valid,fully qualified path. The default path used is thedefault overflow logpath for each node. In a single-node environment,the overflow logpath can be a valid, fully qualified path or a valid,relative path if the server is local. W For table space roll-forward recovery operations,the SQLM-ROLLPWD, SQLKSTOP, and SQLM-ROLLPWD-STOP caller actions have the same effect, whichis rolling forwardall table spaces that are in the"Rollforward Pending"(SQLB-ROLLFORWAREPENDING) or "Rollforward in Progress" (SQLB-ROLLPORWARXIN-PROQRESS) states.
.
W The action performed when this function is executed dependson the current value of the database's rollforwardqending configuration fileparameter (you can determine the value of this parameter by executing the QET DATABASE "Rollforward Pending"state CONFIQURATION function). Ifthe database is in the (SQLB-ROLLFORWARD-PENDING), this parameter will beset to DATABASE. If oneor more table spaces are in the"Rollforward Pending"state (SQLB-ROLLFORWARDPENDINQ) or "Rollforward in Progress" state (SQLB-ROLLFORWARD-IN-PROQRESS), this parameter will beset to TABLESPACE.If neither the database nor any of its table spaces needsto be rolled forward,this parameter will be set to NO. W If the database is in the"Rollforward Pending"state (therollforwardqending configuration fileparameter is setto DATABASE) when this function is called, the entire database (and all of its table spaces that are not in anabnormal state)will be rolled forward. If one or more table spaces are in the "Rollforward Pending" state (the rollforwardqending configuration fileparameter is set to TABLESPACE), only the table spaces in the"Rollforward Pending"state will be rolled forward. If a table space roll-forward recovery operation terminates abnormally, table spaces that were being rolled forward will be put in the"Rollforward in Progress" state (the rollforwardqending configuration fileparameter is set to TABLESPACE), and the next time the ROLLFORWARD DATABASEfunction is executed, only the table spaces in the"Rollforwardin Progress" state will be processed. Ifthe setof table space names specified doesnot include all table spaces that are in the "Rollforward in Progress" state, thetable spaces that are rolled forward will be placed in the "Restore Pending"(SQLB-RESTORE-PENDING) state.
m
!
! ;
380
i
c
i
:
i1
Part 3: Application Programming Interface Functions M If the specified database is not in the"Rollforward Pending"state, no action will be
taken when this function is called. M More information must be stored in a database's recovery log files for LOB data and LONG VARCHAR fields if roll-forward recovery is enabled (less information has to be retained if the database is not enabled for roll-forward recovery). M The ROLLFORWARD DATABASE function reads recovery log files, starting with the log file that is matched with the backup imagethat was usedto restore the database. You can determine the name of this log file by calling this function with the CallerAction field of the rfwd-input structure setto SQLUM-QUERY before the rollforward recovery operationis started. All transactions contained in recovery log files are reapplied to the database, if possible, as they are read. Recovery log files are processed as far forward in time as information is available, unless an earlier time is specified. If an earlier time is specified, the lastcommit field of the sqlr,f-info structure will containthe time stamp of the lastcommitted transaction that was appliedto the database. M If a database recovery was necessary because of application or human error, atime stamp value can be specifiedin thepSt0pTim.e field of the rfwd-input structure so roll-forward recovery processing will end before the application or human error occurred. Also, if a time stamp value is specified forthe pStopTime field, you can stop the roll-forward recovery process before a recovery logread file error occurs (if this type of error occurred during an earlier roll-forward recoveryattempt). This process only appliesto full database roll-forward recovery operations. When the rollforwardqending configuration fileparameter is setto DATABASE,the database specified is not available foruse by other applications until the rollforward recovery processterminates. You can terminate the process by calling this function with the CallerAction field of the rfwd-input set to S Q L ~ S T O Por SQLIJ"ROLLPORWAFU-STOP; either of these values will bring the database out of "Rollforward Pending"state. If the rollforwardqending configuration file parameter is setto TABLESPACE,the database is available foruse by other applications during the roll-forward recovery process, but table spaces in the "Rollforward Pending"and "Rollforwardin Progress" states will not be available until this function is called to perform the necessary table space roll-forward recovery operation. M The SQLUY_CANCELcaller action cannot be used while the roll-forward recovery
operation is inprogress. Instead, it can only be usedif the roll-forward recovery operation is paused (that is, waiting forinput), or if a systemfailure occurs. In either case, this caller action shouldbe used with caution. M In a multi-nodedatabase environment, this function can only be called from the catalog node. The roll-forward recovery operation itself only affects the nodes that are listed in thedb2mdes.cfg configuration file,unless specific nodesare specified. If no roll-forward recovery operationis needed on a particular node, that node is ignored. M Rolling databases forward might involveprerequisites and restrictions that are
11 I
Chapter 10: Database Migration and Disaster Recovery APIs
381
beyond the scope of this reference. Referto the IBM DB2 Universal Database Administration Guide for more information aboutroll-forward recovery.
Connection This function can be called at any time; a connection to a DB2 Database Manager Requirements instance or to a DB2 database does not haveto be established first. When this function is called, it establishes a connection to the database specified.
Authorization Only users with System Administrator(SYSADM) authority, System Control (SYSCTRL) authority, or System Maintenance(SYSMAINT) authority can execute this function call.
see Also
BACKUP DATABASE,
Example
Thefollowing C++ program illustrates how to use the ROLLFORWARD DATABASE function to bring the SAMPLE database to the state it was in just before a crucial error occurred ,
RESTORE
DATABASE, LOAD
~~~~~
/* NAME: /* PURPOSE: /* /* DATABASE /* /*
CHlOEX7.SQC Illustrate H o w To Use The Following DB2 APT Function ~n A C++ Program:
*/ */
ROLLFORWARD
*/ */
/*
/ / Include The Appropriate #include <windows.h> #include #include <stdlib.h> #include <sqlutil.h> #include <sqlenv.h> #include <sql.h>
Header
Files
/ / Define The API-Class Class class API-Class / / Attributes public : struct sqlca sqlca;
/ / Operations public : long BackupDB( ; long RestoreDB( ); long RollforwardDBO;
1; / / Define The BaCkupDB() Member Function long API-Class ::BackupDB ( )
c
*/ */ */
Part 3: Application ProgrammingInterface Functions / / Declare The LocalM e m o r y Variables struct eqlu-media-list Media-List; struct sqlugedia-entry Media-Entry; char char
iOnID[33]; pt271;
ionID[33];
/ / Initialize The Media List Information Data Structure Media-List.media-type = SQLW-LOCAL-MEDIA; Media-Liet.eeseions = l; etrcW(Media-Entry.media-entry, 18D:\\Backupw); Media-Liet.target.media 6daedia-Entry;
-
/ / Tell The User That The Backup Process Is Being Started cout << "Starting Backup << endl << endl;
..."
/ / Start Backing Up The SAMPLE Database Sqlubkup ("SAMPLEn816, SQLUB-OFFLINE, SQLUB-FULL, SQLUB-BACKUP, ApplicationID, Timestamp, 4, NULL, &Media-List, nuserID", "passwordtr, NULL, 0, NULL, NULL, Beqlca); / / If The Database CouldNot Be BackedU p , Display An Error / / Message And Terminate The Backup Process if (sqlca.sqlcode l = SQL-RC-OK)
I cout << "ERROR : << eqlca.sqlcde (< endl; Sqlubkup ("SAMPLE", 16, SQLUB-OFFLINE, SQLUB-FULL, SQLUB-TERMINATE, ApplicationID, Timestamp, 4, NULL, &Media-List, "userID", "passwordtt, NULL, NULL, NIJLL, &sqlca);
0,
1
was Successfully Backed m, Display A
/ / If The SAMPLE Database / / Message Saying So
else {
Gout << "The SAMPLE cout << endl;
database was successfully backed up."#
1 / / Return The SQLCA Return
CodeTo The
/ / Define The ReetoreDBO Member Function long API-Clase::ReetoreDB() {
/ / Declare The Local M e m o r y Variables etruct sqlu-media-list Media-List; structeqlu-media-entryMedia-Entry; char
Calling
Function
i
Chapter 10: Database Migration and Disaster Recovery APIs
383
/ / Initialize The Media List Information Data Structure Media-Liat.media-type = SQLU~LOCALMEDIA; Media-List.sessions = 1; strcW(Media-Entry.media-entry, "D:\\Backup"); Media-List.target.media = &Media-Entry; / / Tell The UserThat The Restore ProcessIs Being Started cout << '#Starting Restore << endl << endl;
..."
-
/ / Start Restoring The SAMPLE DatabaseNote That The / / Database Will Be Left In A Rollforward-Pending State sqlurestore("SAMPLE", "SAMPLE", 16, SQLUD-ROLLFWD, SQLUD-NODATALINK, SQLUD-FULL, SQLUD-OFFLINE, SQLUD-RESTORE, ApRliCatiOnID, 0 1 "D:" , 4, NULL, NULL, brMedia-List, "userID", "password", NULL, 0, NULL, 4, NULL, NULL, NULL, &sqlca); / / Ignore TheWarning Message Stating That The Existing / / Database Will B0 Overwritten if (sqlca.sqlcode =I 2529 I I sqlca.sqlcode == 2539) {
sqlurestore("SAMPLE", "SAMPLE", 16, SQLUD-ROLLFWD. SQLUD-NODATALINK, SQLUD-FULL, SQLUD-OFFLINE, SQLUD-CONTINUE, ApplicationID, 0 , "D:" , 4, NULL, NULL, brMedia-List, "userID", "password", NULL, 0, NULL, 4, NULL, NULL, NULL, &sqlca);
1 / / If The Database Could Not Be Restored, Display An Error / / Message And Terminate The Restore ProCBBB if (sqlca.sqlcode I = SQL-RC-OK)
i
cout << 8 8 ~ : ~ << 0 sqlca. ~ sqlcode << endl; sqlurestore("SAMPLE", "SAMPLE", 16, SQLUD-ROLLFWD, SQLUD-NODATALINK, SQLUD-FULL, SQLUD-OFFLINE, SQLUD-TERMINATE, ApplicationID, 0 , "D: " , 4, NULL, NULL, &Media-List, "UserID", "password", NULL, NULL, 4, NULL, NULL, NULL, &sqlca);
0,
1 / / If The SAMPLE Database / / Message SayingSo
Was Restored Successfully, DiSplaY A
else {
1
tout << uThe SAMPLE cout << endl;
databasewas successfully restored.";
/ / Return The SQLCA Return return(sqlca.sqlcode);
1
Code To The
Calling
Function
Part 3: Application Programming Interface Functions / / Define The RollforwardDB() Member Function long API-Class::RollforwardDB() {
Memory Variables / / Declare The Local int rc 0; char Connnand L50 J ; struct rfwd-input Input; struct rfwd-output Output; char DBAlias 1101 ; char UserID[10] ; char Paseword[lO] ; char LogDir [ 121 ; char ApplicationID[33]; long EFUmReplies; struct sglurf-info NodeInfo; / / Create A Temporary Directory ?md Copy The / / Transaction Log Piles To It rc = CreateDirectory("D: \ \LOGDIR~,NTJLL) ; if (rc I = 0 )
SAMPLE Database's
strcpy(Connnand, %opy *') ; strcat(Conrmand, "D:\\DB2\\NODE0000\\SQLOOOOl\\SQ~DIR\\"); strcat (Command, "*. * D: \\LOGDIR") ; rc = system(Corarnand); if (rc I = -1) {
tout << "The log files cout << endl;
directory has been relocated.";
1
// // // // rc
-
Restore The SAMPLE Database This Will Overwrite The Existing Log Piles(Which Is Why They Were Copied To A New Location Before The Restore Operation Was Started) And Leave The DatabaseIn A Rollforward-Pending State = RestoreDB( ) ;
/ / Initialize The Local Variables strcpy(DBAlia8, "SAMPLE") ; strcpy(UserID, "UserID"); strcpy(Password, "password8*) ; strcpy(LogDir, "D: \\LOGDIR"); / / Initialize The Roll-Forward Recovery Input Structure 1nput.version .I SQLUM-RFWD-WRSION; Input.pDbAlia8 e DBAlias; 1nput.CallerAction = SQLUM-ROLLFWD-STOP; 1nput.pStopTime = SQLUB-INFINITY-TIMESTAMP; 1nput.pUserName = UserID;
Chapter 10: Database Migrationand Disaster Recovery APIs Input .pPassword = Password; 1nput.pOverflowLogPath = LogDir; IIlpUt.N'umChtlgLgOvrf1W 0; 1nput.pChngLogOvrflw = NVLL; 1nput.ConnectMode SQLUb-OFFLINE; 1nput.pTablespaCeLiSt = IiULL; 1nput.AllNodeFlag = SQLURF-ALL-NODES; 1nput.Num.Nodee = 0; Input .pNOdeLiSt NULL; 1nput.modeInfo = 1; Input .DlMode= 0; 1npUt.pRepOrtFih / / Initialize The Roll-Forward Recovery Output Structure Output.pApplicationId = ApplicationID; Output .pNulnueplies = PNumRepliee; Output.pNodeInfo BNodeInfo;
-
/ / Perform Roll-Forward Recovery For The SAMPLE Database cout "Starting the database roll-forward recovery process.n; cout << endl << endl; eqluroll(&Input, &Output, brsqlca); / / If The SAMPLE Database Was / / Display A Message Saying So
if (rc
PE
Rolled Forwarded Succeeefully,
SQL-RC-OK)
cout << ''The SAMPLE database was succesefully rolled #It cout << l"forward. << endl;
1
Function
/* /*
*/ The Main
int main0 / / Declare The Local long etruct eqlfupd unsigned int unsigned int unsigned long etruct eqlca
Memory Variables rc = SQL-RC-OK; DBaeeInf0 2 1 ; LogRetain = l; UserExit = 0; AgentID; sqlca;
*/
Part 3: Application Programming Interface Functions / / Declare The SQL Host M e m o r y Variable EXEC SQL BEGIN DECLARE SECTION; InsertString[l80]; char EXEC SQL END DECLARE SECTION;
/ / Turn On Roll-Forward Recwery For TheSAMPLE Database DBaseInfo[Ol.token = SQLF-DBTN-"RETAIN; DBaeeInfo[Ol .ptrvalue= (char * ) PLogRetain; DBaseInfo[ll.token E SQLF-DBTN-USER-EXIT; DBaseInfo[l] .ptrvalueI (char *) &UeerExit; eqlfudb("SAMPLE", 2, &DBaseInfo[OI, hsqlca);
/ / Force All Apulications Off The DB2 Database Manager sqlefrce(SQL-ALL-USERS, &AgentID, SQL-ASYNCH, Beqlca); / / Backup
rc
The SAMPLE Database Example.BackupDB( ) ;
/ / Connect To The SAMPLE Database TO SAMPLE USERuserID USING EXEC SQL CONNECT
paeeword;
/ / Build An Insert SQL Statement String strcpy(InsertString, *#INSERT INTO D E P ~ T wu.,rns ~ ~ ~ T( U); strcat(InsertString, U'K508, d ~ ~ S a 0~0 0 5~0 0 8~, 8 ~~ 0 0t' . U ,) ; strcat (Insertstring, u r ~ C) ")f ; / / Prepare The InsertSQL Statement EXEC SQL PREPARESQL-SlWNT FROM :Insertstring; if (sqlca.eqlcode =I SQL-RC-OK)
I / / Execute The Insert Statement EXEC SQL EXECUTE SQL-STMNT;
/ / Tell TheUser That The New Record Wae Added if (sqlca.sqlcode == SQL-RC-OK) {
tout << "Data has cout << endlendl;
been addedto the SAMPLE database.";
1 1 / / Commit The Transaction EXEC SQL COMMIT;
/ / Dieconnect From The SAMPLE Database EXEC SQL DISCONNECT CURRENT;
InStanCo
Chapter 10: Database Migration and Disaster Recovery APIs / / Force All Applicatione Of€ The DB2 Database Manager eqlefrce(SQL-?iLL-USERS, MgentID, SQL-ASYNCH, breqlca);
/ / Reetore And Roll ForwardThe SAMPLE rc I Example. Rollf OrwardDB( ) ; / / Return To lrae Operating return(rc) ;
Instance
Database
System
ASYNCHRONOUS READ LOG Purpose
The ASYNCHRONOUS READ LOO function is used to query the Log Manager for current log state information and to extract specific records froma database’s log files.
syntax
SQL-I-RC SQL-API-FN
Parameters
CaZZerAction
eqlurlog (unsigned long SQLU-LSN SQLU-LSN char unsigned long SQLU-RLOt-INFO etruct eqlca
CallerAction, Startinoam BndingLSN, *LogBuffer, LogBufferSise, LogInfo, *SQLCAlt
Specifies the action this h c t i o n is to take when it is executed. This parameter must be set to one of the following values: SQLU-RLOQ-QUERY
Query the Log Manager forcurrent log state information. SQLU-”READ
Read the database log, beginning at the startinglog sequence number specified(StartingLSN and continuing to the ending log sequence number specified (EndingLSN),and return all propagatable log records foundwithin this range. H SQLU-RLO-READ-SINQLE
StartingLSN EndingLSN LogBuffer
is identified bythe startinglog Read a single record, which sequence number specified (StartingLSN). A pointer to a SQLUJSN structure where a valid starting log sequence numberis stored. A pointer to a SQLUJSN structure where a valid ending log sequence numberor ending relative byte address is stored. A pointer to a location in memorywhere all propagatable log records read from the database’s recoverable log file are to be stored (sequentially).
Part 3: Application Programming Interface Functions LogBufferSize
The length of the memory storage buffer wherethis function is to store all log records retrieved(LogBuffer).
LogInfo
A pointer to a SQLU-RLOG-INFO structure where this function is to store current log state information. A pointer to a location in memorywhere a SQLCommunications Area (SQLCA)data structurevariable is stored. This structure returns either statusinformation (if the function executed successfully) or error information (ifthe function failed)to the calling application.
SQLCA
Includes
#include <sqlutil.h>
Description
The ASYNCRRONOUS READ LOQ function is used t o query the Log Manager for current log state information and to extract specific recordsfrom a database's log files. To query the Log Manager for state information, an application calls this function with the CallerAction parameter set to SQLU-RLOQ-QUERY. When this function executes, current active log information is returned in an SQLU-RLOG-INFO structure. To extract specific recordsfrom a database's log files,an application callsthis function with the CallerAction parameter set to SQLU-RLW_READ or SQLU-RLOO-READ-SINor morelogrecords are returned in the OLE. When this functionexecutes,one user-allocated buffer pointed to by the LogBuffer parameter and current active log information is returned in an SQLUJELOGJNFO structure. Typically, an application will querythe Log Manager to obtain a valid starting log sequence number, then it will use that number to read one or more records from the database log files. The SQLU-RLOGINFO structure is defined in sqluti1.h as follows: typedef SQL-STRUCTURE SQLU-RLOO-INFO {
SQLU-LSNinitialLSN;
SQLU-LSNfirstReaaLSN; SQLU-LSN1astReaaLSN;
/*
/* /* /* /* /*
/* /*
SQLU-LSNcurActiveLSN;
/* /* /*
Ueioned long 1ogRecsWritten;
/*
maioned
/* /* 1onglopByteeWritteni /*
/* /*
The log sequencenumberof the first */ log record written to the database */ after the first connection was */ */ established */ The logsequencenumberofthefiret log record read */ Thelogsequencenumberofthelog */ record that correspondsto the last */ byte read */ Thelogsequencenumberof the */ current active log record */ The number o f log records writtento */ the user-allocated buffer (referenced*/ in the L o g B u f f e r parameter) */ */ The number of bytes written to the user-allocated buffer (referenced in */ the L o g B u f f e r parameter), */
Chapter 10: Database Migration
and Disaster Recovery APIs
: 381
This structure contains four fieldsthat use another structure, the SQLU-LSN structure to store log sequence numbers. The SQLU-LSN structure isdefined in sq1util.h as follows:
The structure of the actual log record information returned to the user-allocated buffer (referencedby the LogBuffer parameter) by this function is dependant upon the log record itself. Refer to Appendix B for more information about the structureof each log recordthat can be returned. Comments
W The starting log sequence number specified in the StartingLSN parameter must
correspond to the startof an actual log record. W The ending log sequence number specified in the EndingLSN parameter can be
one of the following: W The valueof the curActiveLSN field of a SQLU-RLOG-INFO structure that was populated whenthe Log Manager was queried. W A value that is greater than the value of the initialLSN field of a SQLU-RLOG-DVFO structure that was populated whenthe Log Manager was queried.
I OxFFFF
OxFFFF
OxFFFF (which is interpreted as the end of the current log
file) The ending log sequence number specified in the EndingLSN parameter must be greater than the starting log sequencenumber specified in theStartingLSN parameter. W The bufferthat this function is to store all propagatable log records read in (whose
address is stored in theLogBuffeer parameter) must be large enough to hold at least one log record. Ata minimum, this buffer should beat least 32 bytes in length (the size of the log recordheader). Its maximum sizeis dependent uponthe requested log sequence number range. IEach log recordreturned in thelog record bufferis prefixed by a six-byte log
sequence number that is used to identify the log record itself. W To read the next sequential log recordin a file (after this fimction has been called
once), add1t o the log sequence numberof the last log recordreturned and call this function again with this value specified as thenew starting log sequence number (StartingLSN). IIf this function returns the SQL return code SQLTJ-F~LOG-~-TO-CUFSENT
(stored in thesqlcoale field of the sqlca data structure), the log reader has read t o the end of the current active log file.
W T h i s function can only be used on databases that have roll-forward recovery
Part 3: Application Programming Interface Functions enabled (i.e the database configuration parameters Zogretuin and/or userexit must be enabled).
Connection This function can only be called if a connection to a database exists. Requirements Authorization Only users with System Administrator(SYSADM)authority or Database Administrator (DBADM) are allowed to execute this function call. See Also
Example
CH1OEXB.SQC
ROLLFORWARD DATABASE
Thefollowing C++ program illustrates how to use the ASYNCHRONOUS READ LOQ function to view a record storedin the SAMPLE database's recoverable log file:
/* //* NAME: /* PURPOSE: /*
/* /* /* /*
Illustrate HOW TO uee The Following DB2 API Function In A C++ Program: ASYNCHRONOUS READ LOQ
/ / Include The Appropriate Header Files #include <windowe.h> #include #include <etdlib.h> #include <sqlutil.h> #include <eqlenv.h> #include <sql.h> / / Define The API-Claee Class class API-Class
/ / Attributes public: etruct sqlca
eqlca;
/ / Operations public : long BackupDB (); long ReadLogFileO;
>; / / Define The BackupDBO Member Function long API-C1ass::BackupDBO
c
/ / Declare The LocalMemory Variable6 etruct eqlu-media-list Media-List; struct eqlu-media-entry Media-Entry; ApplicationID[33] char [27] Timestamp char
t
;
/ / Initialize The Media List Information Data Structure Media-Liet.media-type = 8QLU-LOCAL"EDIA;
*/ */ */ */ */ */ */ */
Chapter 10: Database Migrationand Disaster Recovery APIs Media-List.sessions = I; strcW(Media-Entry.media-entry, 'tD:\\Backup"); Media-List.target.media = media-Entry; / / Tell The User That The Backup Process Is Being << endl << endl; cout << "Starting Backup
..."
Started
/ / Start Backing Up The SAMPLE Database sqlubkup("SAMPLE", 16, SQLW-OFFLINE8 SQLW-FVLL, SQLW-BACKUP, ApplicationID8 Timestamp, 4, NULL, &Media-List, "UserID", '*password", NULL, 0 , NULL, NULL, hsqlca)I / / If The Database CouldNot Be BackedUp, Display An Error / / Message And Terminate The Backup PrOCeSS if (sqlca.sqlcode l = SQL-RC-OK) {
tout << "ERROR : " << eqlca.eqlcode << endl; Sqlubkup ("SAMPLE", 16, SQLUB-OFFLINE, SQLW-FULL, SQLW-TERMINATE, ApplicationID, Timestamp, 4, NULL, &Media-List, 8tuserID", Upassword", NULL, NULL, NULL, hsqlca);
0,
1
/ / If The SAMPLE Database / / Message Saying So
Was Successfully Backed Up, Display
A
else {
tout << *'The SAMPLE cout << endl;
databaeewas successfully backed up.";
? / / Return The SQLCA Return return(sqlca.sqlcode);
Code To The
Calling
Function
? / / Define The ReadLogFileO MIember Function long API-Class::ReadLogFile()
I / / Declare'The Local M e m o r y Variables StartLSN; SQLU-LSN EndLSN; SQLU-LSN char *LogBuf f er; SQLU-RLOG-INFO LogInfo; fPtr; *Bufchar *LongVal; long *CharVal; char / / Allocate ~emoryFor The Log LOgBuffer = new chart10241; BuffPtr P LogBuffer;
Record Buffer
/ / Query The Database Log To Obtain / / mnnber
A
Valid
Starting
Log
Sequence
Part 3: Application Programming Interface Functions
/ / If The Database Log Query / / Information Obtained if (eq1ca.eqlcode = p SQL-RC-OK)
Was Succeeeful, Dieplay The
{
/ / Initialize The Starting a d Ending Log Sequence w e r e StartLSN.lenWord[Ol = LogInfo.initialLSN.lenWord[O]; StartLSN.lenWord[ll = LogInfo.initialLSN.lenWord[1]; StartLSN.lenWord[2] LogInfo.initialLSN.lenWord[2];
.
EndLSN lenword [ 01 = OxFFFF; EndLSN.lenWord[ll = OxFFFF; EndLSN.lenWord[2] I OxFFFFt / / Retrieve The Firet Record StoredIn The Log File 6qlurlog(SQLD_RLOQ_READ_8INOLE, PStartLSN, PEndLSN, LogBuffer,
1024, PLogInfo, Peq1ca)j / / Print Information About The Record Retrieved BuffPtr +I 6; LongVal = (long *) BuffPtr; of record : << *LongVal << endl; cout ULength BuffPtr += 4; CharVal = (char *) BuffPtri coutUTypeofrecord : << CharVal << endl;
1 / / Free Allocated Memory delete t 1 LogBuf fer;
1
/*
/ / Return The SQLCA Return return(eqlca.eqlcode);
Code TO The Calling
The Main Function
*/ */
/* int main()
I / / Declare The Local M e m o r y Variable6 rclong I SQL-RC-OK; etruct eqlfupd DBaeeInfo[2] ; uneigned int LogRetain = l; unsigned int Deerwit I 1; etruct eqlca sqlca; / / Declare The SQL Hoet Memory Variable EXEC SQL BEGIN DECLARESECTION; IneertString[lBOl; char EXEC SQL END DECLARE SECTION;
/ / Create An Instance
Function
Of The API-Claes Claee
Chapter 10: Database Migrationand Disaster Recovery APIs API-ClassExample; / / Turn On Roll-Forward Recovery For The SAMPLE Database DBaseInf0 [ 01 token = SQLF-DBTN-LOG-FUZTAIN; DBaseInfo[Ol .ptrvalueP (char *) BLogRetain; DBaseInfo[l] .token = SQLF-DBTN-USER-EXIT; DBaseInfo[ll.ptrvalue = (char *) &UserExit; sqlfudb('%AMPLE", 2, &DBaseInfo[Ol, &sqlca);
.
/ / Backup The SAMPLE Database rc I Example. BackupDB (); / / Connect TO The SAMPLE Database EXEC SQL CONNECT TO SAMPLE USER userID
USING paeswordt
/ / Build An Insert SQL Statement String strcpy(1nsertString. '"INSERT INTO DEP?iRWE!NT VALWS ( "); strcat(InsertString, '"K50','TESTING', '000500'. 'AOO', etrcat(InsertString, u'NC')u);
" ) j
/ / Prepare The Insert SQL Statement EXEC SQL PREPAFtE SQL-STMNT FROM :Insertstring; if (sqlca.sqlcode == SQL-RC-OK) {
/ / Execute The Insert Statement EXEC SQL EXECUTESQL-STMNT; / / Tell The User That The New if (sqlca.sqlcode == SQL-RC-OK)
Record Was Added
I
>
c a t << ,'New data has beenadded to the SAMPLE database."; cout << endl << endl;
1 / / Commit The Transaction EXEC SQL COMMIT; / / Retrieve And Display The First Record Found In The SAMPLE / / Database#s ReCOVetabki Log File rc = Example.ReadLogFi1e ( ) ;
/ / Disconnect From The SAMPLE Database EXBC SQL DISCONNECT CURRENT;
1
/ / Return TO The return( rc ) ;
operating
System
I 394 [
L ” “ :
B!!?!
;
Part 3: Application Programming Interface Functions
’
IOPEN RECOVERY HISTORY FILE
SCAN Purpose
syntax
Parameters
The OPEN RECOVERY HISTORY FILE SCAN function is used to store a copy of selected records retrieved from database a recovery history file in memory and to return the number of records foundin the recovery history file that meet specified selection criteria to the calling application. SQL-API-RC
SQL-API-FN
DBAlias
sqluhops (char char char unsigned short unsigned short unsigned short void structeqlca
*DBAlias, *MmeStamp, *ObjectNme, *Wntriee, * H a d le , Recordme,
*Reserved, *SQLCA);
A pointer to a location in memorywhere the alias name of a database is stored.
A pointer to a location in memory where astring that specifies a time stamp that is to be used for selecting recovery history file records is stored. Records whose timestamp value is equal to or greater than thetime stamp value specified are retrieved. This parameter can containa NULL value. ObjectName A pointer to a location in memory wherethe table name or table space name that i s to be used for selecting recovery history file records is stored. This parameter can contain aNULL value. NumEntries A pointer to a location in memory where this function is to store the number of records foundin therecovery history file that match the selection criteria specified. Handle A pointer to a location in memory where this function is to store a recovery history file scan buffer identifier that i s to be used in subsequent GETNEXTRECOVERY HISTORY F I L E ENTRY and CLOSE RECOVERY HISTORY FILE SCAN function calls. RecordType Specifies which recordsin the recovery history file (that meet the selection criteria) are to be retrieved. This parameter must be set to one of the following values: Timestamp
m
m
SQLUH-LIST-M”HISTORY
All records in the recovery history file that meet the selection criteria specified are to be retrieved. SQLUH-LISTJD”BACKUP
Only backup and restore records that meet the selection criteria
specified are to be retrieved.
i j !
Chapter 10: Database Migration and Disaster Recovery APIs B
I i 315 i
SQLUH-LIST-ADI-ROLLFORWARD
Only roll forwarddatabase records that meet the selection criteria specified are to be retrieved.
W SQLUH-LISTLAD%-RWSTATS Only run statistics (RWSTATS) records that meet the selection criteria specified are to be retrieved. W SQLUH-LIST-ADM-REORQ Only reorganizetable records that meet the selection criteria specified are to be retrieved. W SQLUH-LISTJLD"ZWI"I'R-TABLESPACE only AGTER TABLESPACE records that meet the selection criteria specified are tobe retrieved. W SQLUH-LISTJ4DlU-DROPPED-TABLE Only DROP TABLE records that meet the selection criteria specified are to be retrieved. W SQLUH-LIST-ADM_LOA Only load recordsthat meet the selection criteria specified are to be retrieved. Reserved
SQLCA
A pointer that is currently reserved for later use. For now, this parameter must always beset to NULL. A pointer to alocation in memorywhereaSQLCommunications Area (SQLCA) data structurevariable is stored. This variable returns either status information (ifthe function executed successfully) or error information (ifthe function failed)to the calling application.
Includes
#include <eqlutil.h>
Description
The OPEN RECOVERY HISTORY FILE SCAN function is used to store a copyof selected records retrieved from adatabase recovery history file in memory and to return the number of records foundin therecovery history file that meet the selection criteria specified to the calling application. The copy of the recovery history file records placed in memory represents a snapshot of the recovery history file at the time the recovery history file scanis opened. This copy is never updated, even if the recovery history file itself changes. This function is normay followed by oneor more QET NEXT RECOVERY HISTORY FILE ENTRY functions calls and one c m s E RECOVERY HISTORY FILE SCAN function call. Together, these three functions worklike a SQL cursor (i.e., they use the OPEN/FETCWCLOSE paradigm. The memory buffer that is used to store the recovery history file records obtained by the recovery history file scanis automatically allocatedby DB2 and a pointer to that buffer (the buffer identifier) is stored in theHandle parameter. This identifier is thenused by subsequent QET NEXT RECOVERY HISTORY FILE ENTRY and CLOSE RECOVERY HISTORY FILE SCAN function
Part 3: Application Programming Interface Functions calls to access the information stored in memory bufferarea.
Comments
W "he values specified in the TimeStamp, ObjectName,and CallerActionparameters are combined to define the selection criteria that filters the records in therecovery history file. Only recordsthat meet the specified selectioncriteria are copied to the memory storage buffer. W If the TimeStamp parameter is set to NULL (or to the address of a localvariable that contains the value 01, time stamp information willnot be a part of the recovery history file record(entry) selection criteria. B If the ObjectName parameter is set to NULL (or to the address of a localvariable a of the recovery that contains the value o), the object name will not bepart history file record(entry) selection criteria. W The filtering effect of the ObjectName parameter depends on the type of object name specified: -If a table name is specified, only records for loads canretrieved, be because this is the only informationkept for tables in the recovery history file. -If a table space name is specified, all records can be retrieved. W If the ObjectName parameter refers to a database table name, the fully qualified table name must be specified. W If boththe TimeStamp parameter and the ObjectName parameter are setto NULL and the CallerAction parameter is set to SQLU-LIST-HISTORY, every record foundin the recovery history file will be copiedto the memory storage buffer. B An application can have upto eight recovery history file scans open at one time.
T h i s function can only be called if a connection to a DB2 Database Manager Connection Requirements instance exists. In order to open a recoveryhistory file scan for adatabase at another node, youmust first attachto that node. If necessary,this function canestablish a temporary attachment to a DB2 Database Manager instance while it is executing.
Authorization No authorization is required to execute this function call.
see Also
QET NEXT RECOVERY HISTORY FILE ENTRY,CLOSE RECOVERY HISTORY FILESCAN, UPDATE RECOVERYHISTORY FILE,PRUNE RECOVERY HISTORY FILE
Example
The followingC++ program illustrates how the OPEN RECOVERY HISTORY FILE SCAN, QET NEXT RECOVERY HISTORY FILE ENTRY, and CLOSE RECOVERY HISTORY FILE SCAN functions are used to retrieve records fromthe SAMF'LE database's recovery history file:
/* /* /*
/*
/* /* /*
CHlOEX9.CPP PURPOSE: Illuetrate How TO Use The Following DB2 API Functions In A C++ Program:
NAME:
SCAN OPEN RECOVERY HISTORY FILE QET NEXT RECOVERY HISTORY FILE
*/ */
*/
*/ */
*/
ENTRY
*/
; :
1
j 397
Chapter 10: Database Migrationand Disaster Recovery APIs /* /* /*
CLOSE HISTORY RECOVERY
*/
FILE SCAN
*/ */
/ / Include The Appropriate Header Files #include <windows.h> #include #include qeqluti1.b #include <sqlca.h> / / Define The API-Class Class class API-Class
c / / Attributes public : struct eqlca sqlca; / / Operations public : long ShowHiStOryi) ;
1; / / Define The ShowHistoryO Member Function long MI-Class ::ShowHiatory( ) {
/ / Declare The Local Handle; short unsigned short unsigned short struct sqluhinfo struct sqluhadm
Memory
Variables
Size; hlumRows i *HistoryInfo; AdminInf0 ;
/ / Open The Recovery History Pile Scan sqluhope( "SAMPLE", NULL, NULL,PhlumRowe, &Handle, SQLUH-LIST---HISTORY, NULL, heqlca); / / Allocate Memory For A Recovery Hietory / / The Three Default Table Spaces
-
File
Record Using
HiStoryInfO (StruCt Sqluhinfo *) lMllOC (SQLUHINFOSIZE(3)); HiStOryInfO->Sqln 3; / / scan The Recovery Hietory / / Information Stored There
if (sqlca.sqlcode
=p
File
Buffer And Retrieve
The
SQL-RC-OK)
c cout << endl << * Object Comment (Truncated) cout << endl; COUt << " "1 COUt << << endl; for (~NumRows1 1 0; NumRows-) / / Retrieve TheNext Recovery History File Entry sqluhget(Handle, SQLUH-QET-NEXTJNTRY, 0, HistoryInfo, &AdminInfo, N"LL, Psqlca);
I
Part 3: Application Programming Interface Functions / / If The Memory Area Allocated For Recovery / / Records Was To Small, Reallocate It if (sqlca.sqlcode == SQLUH-SQLUHINPO-VARS-WAFWINQ)
History
Pile
i Size P HistoryInfo->sqld; free(History1nfo); HistoryInfo = (struct sqluhinfo *) malloc (SQLUHINPOSIZE(Size))j HistoryInfo->sqln = Size; sqluhgne(Handle, NULL, HistoryInfo, hsqlca);
1 / / Display The ReCWery History if (sqlca.sqlcode == SQL-RC-OK)
Pile
Entry
Retrieved
c
1
1
cout.width(3); cout.setf(ios::left); cout << HistoryInfo->operation; cout.width(20); cout.setf(ios::left); cout <( HistoryInfo-.objectgart; cout.width(30); cout.setf(ios::left); cout <( HistoryInfo->comment << endl;
/ / Close The Recovery History File Scan And Free All / / Resources Obtained By The Open Recovery History / / scan API sqluhcls(Handle, NULL, hsqlca); free(Aistory1nfo);
Pile
1
1
/ / Return The SQLCA Return return(eqlca.sqlcode);
Code To The
Calling
Function
/*
Function
/* /*
*/
*/
The Main
*/
int main() / / Declare
long
IC
The Local Memory Variables = SQL-RC-OK;
/ / Create An Instance Of The API-Class Class API-ClassExample; / / Generate And Display Recovery rc = Example.ShowHistory();
1
/ / Return To The return )(rc ;
Operating
History
System
File
Information
Chapter 10:Database Migration
and Disaster Recovery APIS -
i 394 5
FILE ENTRY purpose
The QET NEXT RECOVERY HISTORY FILE ENTRY function is used to retrieve the next record fromthe copy of recovery history file recordsthat was placedin memory by the OPEN RECOVERYHISTORY FILE SCAN function.
syntax
SQL-API-RCSQL-API-FNsqluhget
Parameters
(USigned short unsigned short unsigned long struct sqluhinfo etruct eqluhadm
Ilandle, Entryl!ype, Reservedl, *HiStOryInfO,
void
*AdminInfo, *Reeerved2,
struct sqlca
*SQLCA);
Handle
Therecovery history file scan buffer identifier that was returned by an associated OPEN RECOVERY HISTORY FILE SCAN function call.
Entrynpe
Specifies the type of recovery history file entry to retrieve. T h i s parameter must be set t o one of the following values: SQLUH-QET-NEXT-ENTRY
Retrieve the next matchingentry in the recovery history file. SQLUH-QET-DDL
Retrieve the DDL data associated with the last matching entry retrieved from the recovery history file. A pointer that is currently reservedfor later use. For now, this parameter must always beset to NULL. A pointer to a sqluhinfo structure where this function is to store the recovery history file entry (record) information retrieved.
Reservedl HistoryInfo
A pointer to a sqluhadm structure where this function is to store administration information associatedwith the recovery history file entry (record) retrieved. A pointer that is currently reserved for later use. For now, this parameter must always be set to NULL.
AdminInfo
Reserved2
SQLCA
.
A pointer to a location in memorywhere a SQL Communications Area (SQLCA) data structurevariable is stored. This variable returns either status information (ifthe function executed successfully) or error information (ifthe function failed)to the calling application.
Includes
#include <sqlutil.h>
Description
The QET NEXT RECOVERY HISTORY FILE ENTRY function is used to retieve the next record fromthe copy of recovery history file recordsthat was placedin memory by the OPEN RECOVERY HISTORY FILE SCAN function. The informationretrieved is stored
1
400
Part 3: Application Programming Interface Functions
j
in two special structures: sqluhinfo and sqluhadm. The first of these structures, sqluhinfo, is defined in sqlutil. has follows: 8tIllCt 8qluhinfO
c
/* A etmcture identifier and /* eye-catcher for etorage dumpe. It /* i8 a etring of eight byte8 that muet /* be initialized with the value /* ”SQLUHINF” or “SQLUHADM”. /* The aize of the sqluhinfo etructure
char eqluhinfoid[8];
long 8qluhinfObC; Win; ehort ehort
/*
char operation[2]
The total numberof table apace element8 referenced The total number of table apace /* elements ueed /* Indicatee whetherthe recovery /* operation is a backup operation /* (B), a reetore operation (R), a / * load operation (L), or a drop table /* operation (D), /* a roll-forward operation(F), /* a reorganize table operation,(G), / * a run statietice operation(S), /* or an alter tablespace operation(T). /* Indicates whether the recovery /* operation ia a full operation(D), */ /* a table space operation(P), or a */ /* table operation (T). Thia field */ /* epecifiee the granularity used in the */ /* recovery operation. */ */ /* The recovery hietory file record /* identifier. The firet 14 charactere */ /* of this identifier are time a stamp */ /* value (with the format */ */ /* yyxymndAhhnnss) that indicatee /* when the operation wae performed. */ */ /* The laet three character8of thie /* identifier are a unique operation */ /* eequence number. */ /* specifiee additional qualification */ /* information about the operation. */ /* If the operation waea full level */ /* databaee or table apace backup, */ /* F indicates offline,backup and */ /* N indicate8 online backup. If */ /* the operation wae load a */ /* operation. R indicates replace, A *’/ /* indicatee append. and C indicatee */ / * copy. For all other operations, thie */ /* field ie left blank. */ /* Indicatee how information in the */ / * location field ie to be interpreted. */ /* Information in thie field can be */ /* interpreted to mean a diek(D), a */
/* /*
Wldl ;
char
object [a] J
char
objectgart[l81 I
char
o p t m e tal t
char
device_type[al I
*/ */ */ */ */ */ */ */ */ */ */ */ */ */ */ */ */ */ */ */
Chapter 10: Database Migrationand Disaster Recovery APIs diskette (K), a tape (T), an */ ADSTAR distributed storage */ /* manager (A), a user exit routine */ /* (U), or something else (0). */ /* The most recent log file ID used */ /* Values for this field range from */ /* sooooooo to 59999999. */ /* The latest log file ID used. Values */ SO000000 /* for this field range from */ */ /* to s9999999. the /* A time stamp value with */ 8 /* format ~ d h h 1 1 1 1 8 that */ /* refers to one or more file entries */ /* that represent backup operations.. */ /* For a full databaserestore, the */ /* value stored in this field refersto */ /* the full database backup image */ / * that was restored. For a table */ /* space restore, the value in this */ /* field refers to the table space */ /* backup image or the full */ / * database backup image that was */ /* used to restore the specified table * / /* spaces. For any other operation, */ /* this field is left blank. */ /* The authorizationID of the user */ /* who created the table. This fieldis */ /* only filled in for load operations. */ /* The name of the table. This fieldis */ /* only filled in for load operations. */
/* /* char
first-logtl31;
char
last-log t131
char
backup-id t 151 ;
char
table-creatort91
char
table-name [l91 ;
;
char
char
locationt2561;
/* The number of table spaces */ /* involved in a backup or restore */ /* operation */ /* For backups and copies for */ /* loads, this field indicates where the*/ /* data has beensaved. For backup */ /* entries in the file, this field */ /* contains the sequence number */ /* that identifies which part */ /* of the backup is found in the */ /* specified location. For restore and */ /* load operations, the field identifies*/ /* where the first partof the data */ /* restored or loaded (sequence */ /* number 001) has been saved. */ /* Otherwise, the value stored in this */ /* field contains different information,*/ /* depending on the value stored in */ /* the device-type field. For disk or */ /* diskette (D or K) values, this field */ /* contains a fully qualified filename1 */ / * for tape (T) values, this field */ volume a labelt for */ /* contains
Part 3: Application Programming Interface Functions
AD=
CQmmePtE311 i
char
/* /*
record (entry). Reserved; need to define the /* of this structure.
char filler; struct
/* (A) values, this.field /* contains the server name; and /* €or user exit or other (U or 0) /* values. this field contains free/* form text. /* A free-formcommentthat /* describes the recovery history file
sqluhtsp
sire
*/ */ */ */ */ */ */ */ */ */
tablespace [l];
/*
/* /* /*
An array
of S & U h t E p structures that contain the table space names that are associated with the recovery operation.
*/
*/
*/ */
1;
This structure contains an array of sqluhtsp structures that are used to store table space name information. Thesqluhtsp structure is defined in sqluti1.h as follows: etruct eqluhtep
I char tablespace-name[l9]; char filler;
/* /* /*
The
name of a table space Reserved; used to define' the s i z e of this structure.
*/ */ */
1;
The second structure used by this function, the sqluhadm structure, is defined in sq1util.h as follows: SQL-STRVCTVRE sqluhadm {
char
end-time[lS];
char
id[25] ;
structsqlca struct sqlchar 1;
event-splca; c-d;
/*
A time stamp value (with the format */ /* ~ ~ C U I ~ ~ I that U E E identifies ) whenthe*/ /* completed operation was */ / * Unique object identifier for dropped a */
/*
Comments
/* /*
table SQLCAresultsfor the operation command text f o r the operation
*/
*/
*/
m The recovery history file records that reside in memory are selected from a recovery history file based uponthe selection criteria specifiedwhen theOPEN RECOVERY HISTORY FILE SCAN function was executed. H When this function is executed, the value in the HistoryZnfo parameter points to
the next recovery history file record in the copy of recovery history file records that reside in memory. Each subsequent GET NEXT RECOVERY HISTORY PILE ENTRY function call obtains the recovery history file record immediately followingthe
Chapter 10: Database Migration and Disaster Recovery APIs current recovery history file record,unless there are no more recordsto retrieve (in which case, an error is returned). If this function is called withthe Entryope parameter set to SQLUH-GET-DDL immediately after a recovery history file entry (record) has been retrieved, the DDL data associated withthat entry will be returned. Currently, only dropped table events contain DDL information that can be retrieved by this function. Ifthis function is called withthe Entryope parameter set to SQLUH-GET-DDL after any other type of record has been retrieved, no additional data will be returned. m You can usethe value stored in the NumEntries parameter after the OPEN RECOVERY HISTORY FILE SCAN function is executed to set up a loop that scans through all of the recovery history file records byissuing GET NEXT RECOVERY HISTORY FILE ENTRY function calls, oneat a time, until the number of calls issued equals the number of records copied fromthe recovery history file. W Each backupoperation can producemultiple records in a recovery history file (when the backup imageis saved in multiple files or on multiple tapes).The sequence number usedin therecovery history file recordidentifier (returned in the objectqart field of the sqluhinfo structure) enables you to specify multiple locations during a backup operation. Becauserestore and load operations produce only one recordin a recovery history file, the sequence number 0 0 1 is always used for these types of operations. W The value stored in the first-log field of the sqluhinfo structure is: "Required to apply roll-forward recovery foran online backup. -Required to apply roll-forward recovery foran offline backup. -Applied after restoring a full database or table space level backupthat was current when the load operation started. E The value stored in the last-log field of the sqluhinfo structure is: -Required to apply roll-forward recovery foran online backup. -Required to apply roll-forward recoveryto the current point in time foran offline backup. -Applied after restoring a full database or table space level'backupthat was current when the load finished (this value will bethe sank as the first-log value if roll-forward recoveryis not applied).
W Each table space backup image cancontain one or more table spaces, and each table space restore operation replaces one or more table spaces. Ifthe num-of-tablespaces field of the sqluhinfo structure is not zero (indicating a table space level backupor restore operation),subsequent recordsin the recovery history file willcontain the name(s) of the table space(s) backedup or restored, (represented by an 18-characterstring). One recordis written t o the recovery history file for eachtable space containedin the backup image. Prerequisites The OPEN RECOVERY HISTORY FILE function is called.
SCAN
function must be executed before this
i
!
L
404
" "
..
l7 i
Part 3: Application Programming Interface Functions
Connection This function can only be called if a connection to a.DB2 Database Manager Requirements instance exists. If necessary,this function will establish a temporary attachment to a DB2 Database Manager instance while it is executing. Authorization No authorization is required to execute this function call. See Also
OPEN RECOVERY HISTORY FILE SCAN,CLOSE RECOVERY HISTORY RECOVERY HISTORY FILE, PRDNg RECOVERY HISTORY FILE
Example
See the example provided for the OPEN RECOVERY HISTORY FILE page 396.
FILE SCAN,UPDATE
SCAN
function on
CLOSE RECOVERY HISTORY FILE SCAN The CLOSE RECOVERY HISTORY FILE SCAN functionis used to free system resources that were allocated by the OPEN RECOVERY HISTORY FILE SCAN function. SQL--1-RC SQL-API-FN
Parameters
eqluhcle (unsigned ehort void struct eqlca
Handle, *Reserved, *SQLCA);
Handle
Therecoveryhistoryfilescanbuffer identifier that was returned by an associated OPEN RECOVERY HISTORY PILE SCAN function call.
Reserved
A pointer that is currently reservedfor later use. For now, this parameter must always be set to NULL. A pointer to a location in memorywhere a SQLCommunications Area (SQLCA)data structurevariable is stored. This variable returns either statusinformation (ifthe function executed successfully) or error information (ifthe function failed)to the calling application.
SQLCA
Includes
#include <eqlutil.h>
Description
The c m s E RECOVERY HISTORY FILE SCAN function is used to free system resources that were allocated by the OPEN RECOVERY HISTORY FILE SCAN function.
Connection This function canonly be called if a connection to a DB2 Database Manager Requirements instance exists. If necessary,this function willestablish a temporary attachment to a DB2 Database Manager instance while it is executing. Authorization No authorization is required to execute this function call. See Also
OPEN RECOVERY HISTORY FILE SCAN,OET NEXT RECOVERY HISTORY FILE ENTRY, UPDATE RECOVERY HISTORY FILE,PRUNE RECOVERY HISTORY FILE
lI
l7 : j Chapter 10: Database Migration Example
’ 1i 4 0 5 ~
and Disaster Recovery M I S
. -.
See the example provided for the OPEN RECOVERY HISTORY FILE page 396.
SCAN
function on
m m UPDATE RECOVERY HISTORYFILE Purpose
The UPDATE RECOVERY HISTORY FILE function is used to change the location, device type, or comment associated witha record in a database’s recoveryhistory file.
syntax
SQL-API-RC SQL_API-FN
sqluhupd (char char char char void struct eqlca
Parameters
*RHFEntryID, *NewLOcation, *NewDeviceType, *NewConrment, *Resenred, *SQLCAI i
RHFEntryID
A pointer to a location in memory where the identifier for the backup, restore, or load copy recoveryhistory file recordto update is stored. T h i s identifier has theform of a time stamp, followed bya sequence number ranging from001 to 999.
Newhation
A pointer t o a location in memory where the new location forthe backup, restore, or load copy image associated witha specific recovery history file recordis stored. T h i s parameter can contain a NULL value.
NewDevicenpe A pointer to a location in memory wherea new device type for storing the backup, restore, or load copy image associatedwith a specific recoveryhistory file record is stored. This parameter can contain a NULL value. NewCommnt
A pointer to a location in memory where a new comment describing a specific recoveryhistory file record is stored. T h i s parameter can contain a NULL value.
Reserved
A pointer that is currently reserved for later use. For now, this parameter must always be set to NULL.
SQLCA
A pointer to a location in memory where a SQL Communications Area (SQLCA) data structurevariable is stored. This variable returns either status information (if the function executed successfully) or error information (if the function failed) to the calling application.
Includes
#include <sqlutil.h>
Description
The UPDATE RECOVERY BISTORY FILE function is used to change the location, device type, or comment associated with a record in a database’srecovery history file. When a record in a recoveryhistory file is updated, all information associated with the
1 406
, ’
~
Part 3: Application Programming Interface Functions
i
l
record that existed prior to the update operation is replaced with the new information. Unfortunately,all original information is lost, because changes madeto the recovery history file are not written t o the transaction log. The recoveryhistory file is only used foractivity recording purposes and is not used directly by the RESTORE DATABASE or ROLL FORWARD DATABASEfunctions. During a restore operation,you can specifythe location of the backup imageof a database and use the recovery history file t o keep track of this location. You can then provide this location informationto additional BACKUP DATABASE function calls,so other backup imagesare stored in the same location.
Comments
If the N e w h u t i o n parameter is set to NULL (or to the address of a local variable that contains the value o), the location information for the recovery history file record will remain unchanged. If the NewDeviceQpe parameter is set to NULL (or to the address of a local variable that contains the value o), the device type information forthe recovery history file record will remain unchanged. B If the NewCornment parameter is set t o NULL (or to the address of a localvariable that contains the value o), the comment that describes the recovery history file record will remain unchanged. W If the location of a load copy image is moved, subsequent roll-forward recovery operations must be informed of the new locationand storage media.
Connection This function can only be called ifa database connection exists. In order to update Requirements records in the recovery history file fora database other than the default database, an application must first establish a connection to that database before this function is called. Authorization Only users with SystemAdministrator (SYSADM),System Control (SYSCTRL), System Maintenance(SYSMAINT),or Database Administrator (DBADM) authority can executethis function call. See Also
OPEN RECOVERY HISTORY FILE SCAN,QET NEXT RECOVERY HISTORY FILE ENTRY,CLOSE SCAN, PRUNE RECOVERY HISTORYFILE RECOVERY HISTORY FILE
Example
The followingC++program illustrates how to use the UPDATE RECOVERY AISTORY FILE function to change the comment associated witha record stored in theSAMPLE database’s recoveryhistory file:
/*
/* /* /* /*
CH1OEXlO.SQC NAME: PURPOSE: Illustrate How To Use The Following DB2 API Function In A C++ Program:
*/
*/
*/
*/
*/
FILEHISTORY RECOVERY UPDATE
*/ */
/* /* l / Include The Appropriate
Header
Files
Chapter 10: Database Migration and Disaster Recovery "Is "
#include #include #include #include
.
1
.
<windows.h> <sqlutil.h> <sql.h>
/ / Define The API-Class Class class API-Class {
/ / Attributes public : struct sqlca sqlca;
1;
/ / Operations public : long ShowIiistoryO;
/ / Define The ShowHistoryO Member Function long API-Class::ShowIiistoryO {
/ / Declare The LocalMemory Variables unsigned short Handle; short Size; unsignedshort MunRows ; structsqluhinfo*HistoryInfo;
/ / Open The Recovery History File Scan sqluhops("SAMPLE", NULL, NULL, & ~ m R o w s ,&Handle, SQLWI-LIST_ADM_HISTORY, NULL, &SqlCa); / / Allocate Memory For A Recovery History File Record Using / / The Three Default Table Spaces HistoryInfo = (struct sqluhinfo *) malloc (SQLWIINFOSIZE(3));
HiStOryInfO->Sqln = 3; / / Scan The Recovery History File / / Information Stored There
if (sqlca.sqlcode
=m
BufferAnd Retrieve
The
SQL-RC-OK)
{
tout << endl << Object Comment (Truncated) cout <* endl; 88. cout << " COUt << << endl; for ( ;hRllpRows 1 I 0; NurnRows-)
";
{
/ / Retrieve TheNext Recovery History File sqluhgne(Handle, NULL, HistoryInfo, &sqlca);
Entry
/ / If The ~ e m o r yAtea Allocated For Recovery History / / Records Was To Small, Reallocate It if (sqlca.sqlcode =P SQLUH-SQLWIINFO-VA€lS_WARNING) {
File
Part 3: Application Programming Interface Functions Size = HietoryInfo->eqldi free(Hietory1nfo); HietoryInfo = (struct egluhinfo *) malloc (sQxmiImOSIZE(Size)); HietoryInfo->eqln = Size; sqluhgne(Randle, NULL, HietoryInfo, &sulca); 1
/ / Display The Recovery History if (sqlca.eqlcode I= SQL-RC-OK)
File
Entry
Retrieved
{
cout.width(3); cout.eetf(ios::left); cout << HistoryInfo-*operation; cout.width(20); cout.setf(ios::left); cout << HietoryInfo->objectgart; cout.width(30) 8 cout.setf(ioer:left)l cout << HietoryInfo->conrment << end18
1
1 / / Cloee The Recovery Hietory File Scan And Free All / / Resourcee ObtainedBy The open Recovery Hietory File / / scan API eqluhcle(Hand1e. NULL, &eqlca); free(HietoryInf0);
1 / / Return TheSQLCA Return return(eqlca.eqlcode);
CodeTo The
Calling
Function
1
/*
/* /*
*/
*/ */
The Main Function
int main( )
I / / Declare The Local Memory rc = SQL-RC-OK; long etruct sqlca eglca;
variables
/ / Create An Irmtance Of The API-Claee Class API-ClaeeExample; / / Attempt To Connect To The SAMPLE Database EXEC SQL CONNECT TO SAMPLE USER ueerID USING paseword; / / Dieplay
The
ContentsOf The Recovery
rc = Bxample.ShowHistoryOt
History
File
m i i I
. !.
:
Chapter 10: Database Migration and Disaster Recovery APIs / / Change The Comment Associated With The Recovery / / File Entry For The Last Backup Operation sqluhupd(8~19990204130435001n, NULL, NULL, "Last Backup", NULL, &sqlca); / / Display The Contents Of The / / To See The Change rc E Example. ShowHistory( );
/ / Iseue A Rollback To Free EXEC SQL ROLLBACK;
Recovery
All
i
j
409 -
.""
..~
"
History
History File Again
Locks
/ / DiSCOnneCt From The SAMPLE Database EXEC SQL DISCONNECT CURRENT; / / Return TO The Operating return(rc);
System
1408
purpose
syntax
.
The PRUNE RECOVERY HISTORY FILE fimction is used to removeone or morerecords from a database's recovery history file. *!rimestamp, unsigned ehort ForceQption, void *ReaerveU,
SQL-API-RC SQL-API-FN eqluhprn
(char
etruct sqlca
Parameters
Timestamp
Forceoption
*SQLCA);
A pointer to alocation in memory that contains a string that specifies atime stamp that is t o be used for selecting recovery history file recordsthat areto be deleted. Records whose time stamp value is equal to or greater than thetime stamp value specifiedare deleted. T h i s parameter can contain aNULL value. Specifies whether or not history file records for the most recent full backup and its correspondingrestore set should be kept. A restore set includes all table space backupsand load copiestaken since the last (most recent) full database backup operation was pedormed. T h i s parameter must be set to one of the following values: SQLU?-NO-FORCE
All recent restore set records are to be kept, even ifthe time stamp is less than or equal to the time stamp specified. SQLUH-FORCE
All records in the recovery history file are to be pruned according t o the time stamp specified. Recentrestore set records with time stamps less than or equal t o the time stamp specified are t o be deleted fromthe file.
Part 3: Application Programming Interface Functions Reserved
A pointer that is currently reserved for later use. For now, this parameter must always be set to NULL.
SQLCA
A pointer to alocation in memorywhere a SQLCommunications Area (SQLCA)data structurevariable is stored. This variable returns either status information (if the function executed successfully) or error information (if the function failed)to the calling application.
Includes
#include <eqlutil.h>
Description
The PRUNE RECOVERY HISTORY FILE function is used to remove one or more records from a database’s recoveryhistory file. When recordsin a recovery history file are deleted, the actual backup imagesand load copy files that therecords refer to remain untouched. “he application that calls this function must manually delete these files to free up thedisk storage space they consume.
Comments
If the latest full database backup records need to be pruned from a recovery history file (and their corresponding files needto be deleted fromthe media (disk storage) where they are stored), the user must ensure that all table spaces, including the system catalogtable space and all usertable spaces on which the database resides, are backed up first. Failure to back up thesetable spaces may result in a database that cannot be recoveredor the loss of some portion of user data previously stored in the database.
Connection “ h i s function can only be calledif a database connection exists. In order to delete Requirements records in the recovery history file for a database other than thedefault database, an application must first establish a connection to that database before callingthis function is called. Authorization Only users with System Administrator (SYSADM) authority, System Control (SYSCTRL)authority, System Maintenance(SYS”l3 authority, or Database Administrator (DBADM)authority are allowed to execute this function call. See Also
OPEN RECOVERY HISTORY FILE SCAN,GET NEXT RECOVERY HISTORY FILE ENTRY,CLOSE RECOVERY HISTORY FILE SCAN,UPDATE RECOVERY HISTORY FILE
Example
Thefollowing C++program illustrates how to use the PRUNE RECOVERY HISTORY FILE function to remove records fromthe SAMPLE database’s recoveryhistory file:
/* /* /* /* /* /* /*
NAME:
CH1OEXll.SQC PURPOSE: Illustrate How To Use The Following DE2 API Function In A C++ Program:
*/ */ */
*l
*/ */ */
FILE HISTORY RECOVERY PRUNE
/ / Include
The
Appropriate
Header
Files
Chapter 10: Database Migration and Disaster Recovery APIs #include #include #include #include
<windowe.h> <eqlutil.h> <eql.h>
/ / Define The API-Class Class class API-Class {
/ / Attributes public : struct sqlca
eqlcal
/ / Operations public : long ShowBistoryOI
>; / / Define The ShowBietory() Member Function long API-Class: :ShowBistory() {
Size1
/ / Declare The LocalM e m o r y Variablee unsigned short Handle; short unsignedshort hlumRowe ; struct sqluhinfo *HistoryInfor / / Open The Recovery History File Scan eqluhope ("SAMPLE", NULL, NULL,&NumRowe, &Handle. SQLUH-LIST-ADM-HISTORY, NULL, &SqlCa);
/ / Allocate Memory For A Recovery History File Record Using / / The Three Default Table Spaces HistoryInfo = (struct eqluhinfo *) malloc (SQLUHINFOSIZE(3)); HietoryInfo->sqln = 3; / / scan The Recovery History File / / Information Stored There if (sqlca.eqlcode == SQL-RC-OK)
Buffer And Retrieve The
c
cout << endl << Object c a t << endl; COUt << m cout << for (;NunRows I = 0; NmRows-) {
Comment (Truncated)n;
<< endl;
/ / Retrieve The Next Recovery History File Entry sqluhgne(Hand1e. NULL, HistoryInfo, Peqlca);
/ / If TheM e m o r y Area Allocated For Recovery Hietory / / Records Was To Small, Reallocate It if (eqlca. eqlcode =E SQLUH-SQLU?IINFO-VARS-WARNINQ) {
File
Part 3: Application Programming Interface Functions Size = HistoryInfo->sqld; free (HistoryInfo) ; HistoryInfo = (struct sqluhinfo*) malloc (SQLURINFOSIZE(Size)); HistoryInfo->sqln = Size; sqluhgne(Hand1e. NULL, HistoryInfo, &sqlca); 1 / / Display The Recovery History if (sqlca.sqlcode == SQL-RC-OK)
c
1
1
File
Entry
Retrieved
cout .width (3 1 ; cout.setf(ioe::left); cout << HistoryInfo-~o9eratioht cout.width(20); cout.setf(ios::left); cout << HistoryInfo->objectBart; cout.width(30); cout.setf(ios::left); cout << HistoryInfo->comment << endl;
/ / Close The Recovery History File Scan And Free All / / ReSOUtCeS Obtained By Theopen Recovery History File / / scan API
sqluhcls(Handle, NULL, hsqlca); free(History1nfo); 1 / / Return TheSQLcn Return return(sqlca.sq1code);
CodeTo The
Calling
Function
1
/* /* /*
*/
*/ */
The min Function
int main()
c / / Declare The LocalMemory Variables rc long a SQL-RC-OK; charTimeetamp [SQLU-T~-STAMP-LEN struct sqlca sqlca;
+
1J ;
/ / Create An Instance Of The API-Class Class API-ClassExample;
/ / Attempt To Connect To The SAMPLE Database TO SAMPLE USER userID USING password; EXEC SQL CONNECT / / Display The ContentsOf The rc = Example. Shomistory ( ) ;
Recovery
History
File
Chapter 10: Database Migration and Disaster Recovery APIs / / Delete All EntriesIn The Recovery History strcpy(Timestamp, "19990104130435"); sqluhprn(Timestamp, SQLUH-FORCE, NULL, tisqlca); / / Display The ContentsO f The / / To See The Change rc I Example.ShowEistory0;
/ / Issue A Rollback To Free EXEC SQL ROLLBACK;
Recovery
All
Locks
/ / Disconnect From TheSAMPLE Database EXEC SQL DISCONNECT CURRENT; / / Return To The Operating return(rc) ;
System
File
History
File
Again
This Page Intentionally Left Blank
.ing Although a database is normally a self-contained entity, there are times whenit is necessary fora database to exchange data with the outside world. This chapter is designed to introduce you to the set of DB2 API functions that are used to move data between a DB2 database and external files. Thefirst partof this chapter describes how data can be copied from a DB2 database to an external file. Then, information about the various methods of moving data stored in external files into database tables is provided. Finally,a detailed reference section covering each DB2 API function that can be used to transfer data between databases and external files is provided.
j 416 ! : L
" "
~
"
"
""
*
Part 3: Application Programming Interface Functions
I
Exporting Data There are times when you need to make some or all of a database's data available to the outside world. On these occasions, an application can make select portionsof database data available to other applications by calling the EXPORT function (which, in turn, invokes the Export facility). TheEXPORT function can:
m m m
Copy the contents of a table, along with its indexes, to an external file (using a format that other DB2 products can access). Make a backup copy of a database table. Copy select data to an external file and put the data in a format that other applications recognize.
A s g L s c T SQL statement is used to id en ti^ the data thatis to be exported. When large object (LOB) columns are included in thisSELECT statement, the &t 32KB ofdata are written to the file by default. However, by specifyingWerent values in one of the EXPORT function's input parameters, you can store LOB data, inits entirety, in different external files.
m
Importing Data Just asthere may be times that you need t o export data to an external file, occasionally you mayneed to make data stored in an external file availableto a DB2database. An application can make data in an external file availableto a database by calling the IMPORT function (which invokes the Import facility) or by calling the LOAD function (which invokesthe Load facility). TheIMPORT function can: Create a table, along with its indexes, froman external data file (providedthe file is stored in a formatthat DB2 products can access). Restore adatabase table from a backupcopy made by the Export facility. Copy data from an external data file producedby another application into a database table. When data is imported, if the table or updateable view receiving the data already contains data, thenew data can either replace or be appended to the existing data-as long as thebase table receiving the datadoes not contain aprimary key that is referenced by a foreign keyof another table. (Ifthe base table contains a primary key that is referenced by a foreign key, imported data can only be appended to the existingtable.) LOB data can reside either in thefile being imported or in a separate external file that is referenced by the imported file. If LOB data resides in external files, DB2 expects there to be a separate file for each LOBdata value needed. The import facility can also create new tables from the external file being imported, provided that thefile wascreated by another DB2 product, using the DB2 product standard file format.
Chapter 11:Data Handling APIs
Wl W4 Loading Data The Load facilityworks similarly to the Import facility,but some functional differences do exist. These differences are outlined in Table 11-1.
Significantly slower than LOAD on large amounts of data.
Significantly faster than IMPORT on large amounts of data.
Tables, hierarchies, and indexes can be created from IXF format files.
Tables and indexes mustexist before data can be loaded into them.
Files formatted in Work Sheet Format(WSF)are supported.
Files formatted in WSF are not supported.
Data canbe imported into tables and views (aliases are supported).
Data canonly be loaded into tables(aliases are not supported).
Table spaces in which the table and ita indexes reside remain online during an Import operation.
Table spaces in which the table andita indexes resideare taken offline during a Load operation.
All row transactions are written to the log file.
Minimal logging is performed.
"riggers can be fmed during the import process.
"riggers are not supported.
If an Import operationis interrupted anda
If a Load operation is interrupted anda consistency point (commit frequency)value is specified, the table remains in a "Load Pending"state andcannot be used until either the load processis restartedin order to continue the Load operation or the table spacein which the tableresides is restored from a backup imagethat was createdbefore the Load operation wasstarted.
commit frequency.valueis specified, the table will remain usable andwill contain all rows that were inserted up to the lastcommit operation.The user can restart theImport operationor leave the table as it is. The amountof free disk spaceneeded to import data is approximatelythe size of the largest index being imported, plus about 10 percent. This space is allocated fromthe temporary table spaces defined forthe database.
The amount of free disk space needed to load data is approximatelyas large as thesum of all indexes for the database. This space is temporarily allocated outside the database.
All constraint checking is performed during an
Only uniqueness checking is performed during a Load operation.All other constraintchecking must be performed after the load operation has completed (with the SET CONSTRAINTS SQL statement).
Import operation.
The keys of each row are inserted intothe appropriate index during an Import operation.
All keys are sorted during a Load operation, and the indexes are rebuilt whenthe Load operation is complete.
The RON STATISTICS function or command must be executedafter an Import operation,so the statistics for the affected table are updated.
Statistics are collected and updated duringa Load operation.
Data can be imported intoa host database through Data cannotbe loadedinto a host database. DB2 Connect.
Part 3: Application Programming Interface Functions
uata nles to De lmported must resideon the same workstation from which the Importfacility is invoked.
Data files and named pipes to be loaded must resideon the same workstationon which the databasereceiving the dataresides.
A backup imageis not created duringan Import operation.
A backupimage can be created during aLoad operation.
"he Import utility makes limited useof intra-partition parallelism.
"he Load utility takes full advantage of intra-partition parallelism on symmetric multiprocessor ( S M P ) machines.
N referential integrity checking and constrainta checking is performed on user-supplied data.
Referential integritychecking and constraints checking on user-supplied data can be reduced.
Data conversion between codepages is not performed during an Import operation.
Character data (and numericdata expressed in characters) canbe converted from one code page to another duringa Load operation.
Hierarchical data is supported.
Hierarchical data is not supported.
Numeric data to be imported mustbe stored m character representations.
Numeric data (other than DECIMAL) can be stored and loaded in eitherbinary form or as character representations.
Decimal data to be imported mustbe stored m character representations.
Decimal data can be stored andloaded in eitherpackeddecimal form or as character representations.
Adapten from I B W s DB2 Universal Database AdministrationGuide, pp. 247-248
The Loadfacility is intended to be used foran initial load of a base table when large amounts of data need to be moved. "he Load facility is significantly faster than the Import facility, because it writes formatted data pages directly to the database, as opposed to executing multipleINSERT SQL statements. The Loadfacility also eliminates almost all transaction logging that is normally associated with the loading of data. Instead of logging transactions, the Load facility optionally stores a copy of the data being loadedin an external file. "he load process consistsof three separatephases:
Load
Data is written to the table.
Build
Indexes are created for
Delete
the table.
data that caused a unique key violation
is removed f h m the table.
During the Load phase, data is loaded into the specified database table, then index key and table statistics information is collected. Save points (alsoknown as points of consistency) are established when the Load process is started and a specified number of rows are committed as data isloaded. If a failure occurs during the Load phase, you can skip the number of rows that were successfully committedat the last save point when the load process is restarted. During the Build phase, indexes are created basedon the index keyidormation that was collected during the Load phase. Index keys are automatically sorted during the
Chapter 11:Data Handling M I S Load phase, and index statistics arecollected. Ifa failure occurs during the Build phase, it is restarted from when the Load operation is restarted.Rows containing valuesthat cause unique key violationsto occur are placed in an exception table (if one is specified), and messages aboutthe rows are writtento a message file,so they canbe manually correctedafter the Load process has completed. During the Delete phase, all rows containing valuesthat caused unique key violations to occur are removed from the table, and information aboutthese rows is stored in a temporary file.If a failure occurs during the Delete phase,the Load operation must be manually restarted. When a Load operation is restarted beginning at the Delete phase, violating rows are removed from the table based on information stored in the temporary file.If no temporary filesexist, the Load operation shouldbe restarted at the beginning of the Build phase.You must not modify temporary files in any way, and you must call the LOAD function with the same parameter values that were used whenthe load facility was originally started-or the restart of the Delete phasewill fail. It is always a good idea to restrict access t o the table spaces associated witha table that is receiving load data. You can restrict table space access by calling the QUIESCE TABLESPACES FOR TABLE function before the Load operation is started,and you can call this function again to restore the table spaces t o their original state after the Load process has completed.
m
W4 Supported Export, Import, and Load
File Formats Four types of file formatsare suppohd by the Import facility,and three types of formats are supported by the Export and Load facilities. File formats determine how data is physically storedin a file. The file formats that aresupported are: Delimited ASCII
This format consistsof data values (variable in length) that are separated by a delimiting (field separator) character. Because commasare typically used as the field separator character, this format is sometimes referredto as comma-separated variable (CSV) format. This format is used for exchanging data with a wide variety of application products, especially other database products.
Nondelimited ASCII
This format consistsof data values (withthe same
length) that are column-aligned.This format is also used for exchangingdata with a wide variety of application products, especially spreadsheet products.
Work Sheet Format
This format is specifically intendedto define data
stored in a tile format that is compatible with Lotus Development Corporation's Lotus 1-2-3 and
Lotus Symphony products. The Load utility does not support this file format. PC Integrated Exchange Format This format definesdata that is stored in a file format that is compatible with DB2 products. When this format is used, tables in thedatabase do not haveto exist before data can be imported into them. Refer to the IBM DB2 Universal Database AdministrationGui& for more information about the Export, Import,and Load facilities-and for more information about their supported file formats.
m
The DB2 DataHandlingFunctions Table 11-2 lists the DB2 API functions that are used t o move data between database tables and external files. Each of these functions are described in detail in theremainder of this chapter.
Table 1 1-2 Data HandlingAPls
EXPORT
data Copies
from a DB2 database to an external file.
from a an to external file
DB2 database.
IMPORT
data Copies
LOAD
data Loads fromtapes, files, base table.
LOAD QUERY
Queries the DB2 database server Load operation.
QUIESCE TABLESPACES FOR TABLE
Places all table spaces associated with particular a database table in a quiesced (restricted access)state.
or named pipes
into a DB2 data-
forcurrent the status
of a
m
!, \
Chapter 11:Data Handling M I S
Purpose
syntax
'
421
The EXPORT function is used to export (copy) data from a database to oneof several external file formats. SQL-API-RC
SQL-API-FN
(char eqluexpr
void
*DataFiletVame, *LOBPathList, *LOBFileLirrt, *DataDeecriptor, WelectStetement, *Fileme, *File!l!ypellldl, *MsgFileNsme, CallerAction, *NkunRows, *Reserved,
etruct eqlca
*SQLcA);
sqlu-media-list eqlu-mediplist etruct eqldcol struct eqlchar char etruct eqlchar char ehort etruct eqluexpt-out
Parameters
~
A pointer to a location in memory where the path and name of the external file that data isto be exported into is stored. LOBPathList A pointer t o a sqlu-media-list structure that contains a list of local paths on the client workstationthat identi@where LOB data files are to be stored. LOBFileList A pointer to a sqlu-media-list structure that contains a list of base LOB filenames that areto be generated. DataDescriptor A pointer to a sqldcol structure that contains the column names that are to be written to the external file. Selectstatement A pointer to a sqlchar structure that contains a valid dynamic SELECT SQL statement that specifies whichdata isto be extracted from the database and written to the external file. FileType A pointer to a location in memorywhere a string that specifies the format to use whenwriting data to the external file is stored. This parameter must be set t o one of the following values:
DataFileName
SQL-DEL
Data is to be written to the external file using delimited ASCII format. SQL-WSF
Data is to be written to the external file usinga worksheet (Lotus Symphony and Lotus 1-2-3) format. SQL-IXF
FileTypeMod
MsgFileName
Data is t o be written to the external file usingthe PChtegrated Exchange format. A pointer to a sqlchar structure that contains additional information (unique to the format being used)that is to be to used to write data to the external file. A pointer to a location in memory where the name of the file that all
I 422
Part 3 Application Programming Interface Functions error, warning,and informational messagesare to be written t o is stored. Specifies the action that this function is t o take when it executes. T h i s parameter must be set to one of the following values: EXPORT
CallerAction
SQLU-INITIAL
The EXPORT operation is to be started. SQLU-CONTINUE
The EXPORT operation is to be continued after the user has performed some actionthat was requested by the Export utility (for example,inserting a diskette or mounting a new tape). SQLU-TERMINATE
NumRows
Reserved SQLCA
Specifies that theEXPORT operation is to be terminated because the user failedto perform some actionthat was requestedby the Export utilih. A pointer to a sqluexpt-out structure where this function is to store a count of the number of rows that were exported(written) to the external file. A pointer that is currently reservedfor later use.Fornow, this parameter must always be set to NCTLL. A pointer to a location in memorywhere a SQLCommunications Area (SQLCA)data structurevariable is stored. This variable returns either statusinformation (ifthe function executed successfully)or error information (if the function failed)to the calling application.
Includes
#include *eqlutil.h>
Description
The EXPORT function is used to export (copy)data from a database to an external file. The data to be copied is specified by a SELECT SQL statement and can be written to an external file in one of three internalformats: M Delimited ASCII M Lotus Worksheet W PC Integrated Exchange Format
(m)
NOTE:LXF is the preferred formatto use when exporting data from a table. Files created in this format canlater be imported or loaded much easier into the same table or into another database table. Three specialstructures (sqldcol, sqlu-media-list, and sqlchar) are used to pass general informationto the DB2 Export utility when this function is called. An additional structure, sqluexpt-out, is used to determine how many records were actually copied t o an external file by the Export utiliQ. The first of these structures, sqldcol, is defined in sqluti1.h as follows:
423 1
Chapter 11:Data Handling APIs
/* /* /* /* /* /* /* /*
A value indicating the method to use to select and name columns within the data file The number of columns specified in the dcolneme array A pointer to an array of sqldcoln structures that contain a list of column names
*/ */ */ */ */
*/ */ */
This structure contains a pointer to an array of sqldcoln structures that are used to build a list of column names that areto be written to the external file during the Export process. Thesqldcoln structure isdefined in sqlutil. has follows: struct sgldcoln 1 short dcolnlen;
/* The
size of the data element pointed
/* bydcolnptr the field char *dcolnptri
1;
/*
/* /*
A pointer to location a in memory
to */
*/
where*/
the datael-t specified by the dColmeth*/ field of thesqldcol structure is stored*/
The second specialstructure used by this function, sqluexpt-out, is used to obtain a count of the number of records that were written to the external file after the Export operation is completed. Thesqluexpt-out structure isdefined in sq1util.h as follows: struct sqluexpt-out
c
unsigned long sizeofstruct; unsigned long rowsExported;
1;
/* /* /* /* /*
The size of the sqluexpt-out structure The number of records copied fromthedatabase to thetarget file
*/ */ */ */ */
Another structure, thesqlu-media-list structure, isused to describe the type of media that the external file is to be written to.Refer to the BACKUP DATABASE function in Chapter 10 for a detailed descriptionof the sqlu-media-list structure and for more information abouthow it is initialized.
Comments
If a list of local paths that identify where LOB data files are to be stored is specified in the LOBPathList parameter, LOB data will be written to the first path in this list untilfile spaceis exhausted, then to the second path, and so on. W When LOB data files are created during an Export operation, DB2 constructs the filenames by combining the currentbase name in the listof base LOB file names
Part 3 Application Programming Interface Functions specified in theLOBFileList parameter with the current path (obtained fromthe list of paths provided in theLOBFilePath parameter), and then appending athreedigit sequence numberto it. For example, ifthe current LOB path is the directory /uer/local/LOB/emgdata,and the current base LOB filename is resume,then the LOB files produced will be named /uer/local/LOB/empdata/ree~e. 001, /uer/local/LOB/emg-Bata/ree~e.0 0 2 , and so on.
W The dcolmeth field of the sqldcol structure specified in theDataDescriptor parameter defmes how column names are to be provided forthe exported data file. This parameter can be set to either of the following values: W
SQL_aaET?-N
Specifies that column names in theexternal file are provided via the sqldcol structure. W SQL”ETH-D (or NULL) Specifies that column names in the external file are to be derived fromthe SELECT statement specified in SelectStatement parameter (the column names specified in theSELECT statement become the names of the columns in the external file).
W If the DataDescriptor parameter is set to NULL or if the dcolmeth field of the sqldcol structure specified in the DataDescriptor parameter is setto SQLJQITH-D, the dcolnum and dcolname fields of the sqldcol structure areignored. W A warning message is issued whenever the number of columns specifiedin the external column name array (stored in the DataDescriptor parameter) does not equal the number of columns that were generated by the SELECT SQL statement that was usedto retrieve the datafrom the database. When these numbers do not match, the number of columns written to the external file is thelesser of the two numbers. Excessdatabase columns or external file columnnames are not usedto generate the external file. W The sqlca structure specified in theSelectStatement parameter must contain a valid dynamic SELECT SQL statement. This statement specifies howdata isto be extracted from the database and written to the external file. The columns for the external file (specified in the DataDescriptor parameter) and the database columns returned from the SELECT statement are matched accordingto their respective lisustructure positions. When this function is executed, the SELECT statement is passed to the database for processing,and the first column of data retrieved is placed in the first column of the external file, the second columnretrieved is placed in the second column, and so on. A warning message is issued whenever acharacter column with a length greater than 254 is selected as part of the data that to is be exported to a delimitedASCII (SQL-DEL) file. M If the MsgFilelvame parameter contains the pathand the name of a filethat already exists, the existing file will be overwritten whenthis function is executed. If this parameter contains the pathand the name of a filethat does not exist, a new file will be created. Messages placed in the external message file include
Chapter 11: Data Handling M I S on information returned from the message retrieval service. Each message begins a new line. The CallerAction parameter must be set t o SQLTJI-INITIAG the firsttime this function is called.
All table operations need to be completed and all locks must be released beforethis function is called. You can accomplishthis by issuing either a ROLLBACK or a COMMIT SQL statement &r closing all cursors that were opened withthe WITH HOLD option. Oneor more COMMTI SQL statements are automatically issuedduring the export process.
m You can use delimited ASCII format files to exchange data with many other . Database Managerand File Manager programs.
If character data containing row separators is exported to a delimited ASCII (SQL-DEL) file that is later processed by a text transfer program, fieldsthat contain row separators will either shrink or expand in size. Use the PC/IXF (SQL-IXF) file format when exporting data to files that will be imported into other databases, because PC/IXF file format specifications permit the migration of data between differentDB2 products. You can performdata migration by executing the following steps: . 1. Export the data from one database to a file. 2. Binary copy the files betweenoperating systems. This step is not necessaryif the
source andtarget databases are both accessible fromthe same workstation. 3. Import the datafrom the file into the other database.
You can useDB2 Connect to export tables from DRDA servers such as DB2 for OS/390, DB2 for W S E , and DB2 for OW400.In this case, only the PC/IXF file format is supported. Index definitionsand NOT NULL WITH DEFAVLT attributes for a table are included in PC/IXF format files whena SELECT FROM statement isspecified in the SelectStatement parameter, and the DataDescriptor parameter is setso that default column names are generated. Indexesare not saved ifthe SELECT statement specified in theSelectStatement parameter contains a join-or if the SELECT statement references views. WHERE, GROUP BY, and HAVING clauses do not affect the saving of indexes. The EXPORT utility cannot create multiple-part PC/IXF format files when executed on an AM system. The data field of the sqlchar structure specified in the FileQpeMod parameter can contain anyof the following values: udldelfl
"lobeinfilett
"coldelfl "chardelfl
Part 3: Application Programming Interface Functions
"4"
"L" "S"
These values provide additional information about the chosen file format.Only a portion of these values are used witha particular file format.If the FileQpeMod parameter is set to NULL or if the length field of the sqlchar structure is set to 0, default informationis provided forthe file format specified.
If data isbeing exportedto either a delimited ASCII(SQL-DEL) or PC/MF (SQL-IXF) format file,the FileTypeMod parameter canspecify where LOB data isto be stored. If this parameter is setto "lobeinfile,"LOB data will be stored in separate files; otherwise, all LOB data will be truncated to 32KB and stored in the exported file. When "lobeinf ile" is specified for PC/IXF files, the original lengthof the LOB data is lost, andthe LOB fle length is stored in the exported file. Ifthe IMPORT functionis later used to importthe file-and if the CREATE option is specified-the LOB value created will be 267 bytes in size. If data i s exported to a delimited ASCII (SQL-DEL) format file,the FileQpeMod .parameter can be usedto specifg characters that override the following options: Datalink delimiters
By default, the inter-field separator for a DATALINK value i s a semicolon (;l. Specifying "dldel" followed by a character will cause the specified character to be used in place of a semicolon as the inter-field separator. The character specified must be different fromthe characters used as row, column, and character string delimiters.
Double character delimiters
Specifying "ndloubledel"will cause recognitionof all double-byte character delimiters to be suppressed.
Column delimiters
By default, columns are delimited with commas. Specifying "coldel" followed by a character will cause the specified character to be used in place of a comma to signal the end of a column. By default, character strings are delimited with double quotation marks. Specifying "chardel"
Character string delimiters
Chapter 11: Data Handling APIs followed by a character will causethe specified character t o be used in place of double quotation marks to enclose a character string. Decimal point characters
By default, decimalpoints are specified with periods. Specifying“decpt” followed by a character will causethe specified character t o be used in place of a period as a decimal point character.
Plus sign character
By default, positive decimal values are prefixed with a plus sign. specifying“decplueblank”will cause positive decimal values to be prefixed with a blank spaceinstead of a plus sign.
Date format
Specifying “dateaieo”will causeall date data values to be exported in IS0 format.
If two or more delimitersare specified, they must be separated by blank spaces. Blank spaces cannot be used as delimiters. Each delimitercharacter specified must be different from all other delimiter characters being used,so it can be uniquely identified. Table 11-3 lists the characters that can be usedas delimiter overrides. If data is being exportedto a worksheet (SQL-WSF) format file,the FileQpeMod parameter can be used to specify whichrelease (version) of Lotus 1-2-3or Lotus Symphony the file is compatible with(only one product designator can be specified for a worksheet format file): 1 Causes a worksheetformatfile that is compatiblewithLotus 1-2-3 Release 1 or Lotus 1-2-3Release l a to be created. This is the default version used if no version is specified.
a
Causes a worksheet format file that is compatible with Lotus Symphony Release 1.0 to be created.
3
causes a worksheetformatfile that is compatiblewith Lotus 1-2-3 Version 2 or Lotus Symphony Release 1.1 to be created.
4
Causes a worksheetformatfile created.
L
Causes a worksheet format file that is compatible with Lotus 1-2-3Version 2 to be created.
S
Causes a worksheet format file thatis compatible with Lotus Symphony Release 1.1 to be created.
that contains DBCS characters to be
M This function will not issue a warning if you attempt to specify optionsthat are not supported by the file type specified in theFileQpe parameter. Instead, this
function willfail, and an error will be generated.
1
L
428
_L
l
i
j
i
Part 3: Application Programming Interface Functions
Table 11-3 Delimiter Characters for Use with Delimited ASCII Files . .... . . ”.._ ”. . , , , . .. . . ,. , . I , ,. -- r W - m n-” - ” : ..
-
,
,
”
marksDouble quotation
S4
37
%
ox25
sign Percent
38
ox26
Ampersand
‘
39
ox27
Apostrophe
(
40
Ox28
1
41
ox29
82
*
ox2A
42
,
Comma
44
l
ox2F
ox2C
ox2E
46
Left parenthesis parenthesis Right Asterisk Periodvalid (not
as a character string delimiter)
Slash or forward slash
47 68
0x3A
Colon
,
59
0x3B
Semicolon
<
60
sign Less-than ox3c
--
61
0x3D 0x3E
signEqual
>
62
?
63
0x3F
Question mark
-
95
Ox6F
Underscore (valid
I
124
ox7c
Vertical bar
Greater-than sign only in single-byte character systems)
These charactersare thesame for all code pagevalues. Adapted fromIBM’s DB2 UniversalDatabase Command Reference, Table6, pp. 166 and 167.
If any of the bind files (particularlydb2uexpm.bnd) that are shipped with DB2 have to be manually boundto a database, do not use the FORMAT option during the bind operation.If you do,this function will not work correctly.
Connection “his function can only be called if a connection to a database exists. Requirements Authorization Only users with System Administrator(EXSADM)authority, Database Administrator (DBADM) authority, or CONTROL or SELECT authority for eachtable and/or view specified can execute this function call. See Also
IMPORT,LOAD
Example
The following C++ program illustrates how to use the EXPORT function to copy data from the DEPARTMENT table inthe SAMPLE database to a PC/MF formatted external me:
Chapter 11: Data Handling APIs
aPileName[8011
ing[801;
/* /*
/* /* /*
E*
N m : CH11EXl.SQC PURPOSE: Illustrate How To Uee The Following DB2 API Function In A C++ Program:
*/
*/ */
EXPORT
*/
/*
/ / Include The Appropriate Header Filee #include <windowe.h> #include #include <eqlutil.h> #include <sql.h> / / Define The API-Clam Claee class API-Claee
c / / Attributes public: , etruct eqlca eqlca;
1;
*/ */ */
/ / Operations pub1ic : long ExportData (
;
/ / Define The ExportDataO Member Function long API-C1ase::ExportDataO
i / / Declare The Local Memory Variables char MsgFileName char [SO] ; char eqlchar *Selectstring; etruct struct eqluexpt-out OutputInfo;
/ / Initialize The Local Variables etrcpy(DataFi1eName. *T:\\DEPT.IXF"); etrcpy(MegFileName, UC:\\EXP-MSG.DATn); OutputInfo.eize0fStruct = SQLWXPT-OWI-SIZEI / / Define The SELECT Statement / / Data To Be Exported
That
Will Be Used To Select The
StrCpy(String, "SELECT * FROM DEPARTMENT"); Selectstring m (etruct eqlchar *) malloc (etrlen(9tring) + eizeof(etruct eqlchar)); etrncpy(Se1ectString->data, String, etrlen(String)); Selectltring->length P etrlen(String); / / Export The Data To An IXF Format Pile eqluexpr(DataFi1eName. NULL, NULL, NULL, Selectstring, SQL-IXF8 NULL, MegFileName, SQLU-INITIAL8 brOUtPUtInf01 NULL8 &eqlca) ;
/
I
3
*/
/ / /
+/
*/
I
c
in a
PI-FN
e g l ~ i ~ (char ~ r
long ct sglca
pointer to a location in memory where the external file that data is to be importe - Z i s t that contai pointer to a s ~ Z ~ - ~ e ~ i ~structure paths on the client workstation that identify where
columns in the ext of the ~ c o l ~ efie th be selected &om the external file. pointer to a s ~ Z s Ct ~~c t~ ~that ~r e sta~ementthat ide~tifiesthe action to data into tables that already contain
ctio~
pointer to a location in ~ e m o r y whe~ea string that specifies the fo~matof the external data set to one of the following values:
e
ata in the exte
ata in the external file is stored in
file. me
o i ~ t to e ~a locatio
emory w
Part 3: Application Programming Interface E'unctions IMPORT error, warning, and informational messagesare to be written to is stored.
CallerAction
Specifies the action that this function is to take when it executes. This parameter must be set to one of the following values: SQLU-INITIAL "he IMPORT operation isto be started.
m
SQLU-CONTINUE
The IMPORT operation is to be continued after the user has performed some actionthat was requestedby the Import utility (for example,inserting a diskette or mounting a new tape). W SQLU-TERMINATE
The IMPORT operation is to be terminated because the user failed to perform some actionthat was requested by the Import utility. ImportInfoIn
A pointer to a sqluimpt-in structure that contains information about the number of records to skip and the number of records to retieve before committing changesto the database.
ImportInfoOut
A pointer to a sqluimpt-out structure where this function is to store summary information aboutthe IMPORT operation.
NullZndicators
A pointer to an array of integers that indicates whether or not each column of data retrieved can containNULL values. This parameter is only used if the Filenpe parameter is setto SQL-DEII.
Reserved
A pointer that is currently reservedfor later use. For now, this parameter must always beset to NULL.
SQLCA
A pointer to a location in memorywhere a SQL Communications Area (SQLCA)data structurevariable is stored. This variable returns either status information (ifthe function executed successfully)or error information (ifthe function failed)to the calling application.
Includes
#include <eplutil.h,
Description
The IMPORT function is used to copy data stored in an external file (of a supported file format) into a database table or view. Data can be imported from any filethat uses one of the following internal file formats: W Delimited ASCII
Nondelimited ASCII Lotus Worksheet W PC Integrated Exchange Format (IXF)
Chapter 11: Data Handling APIs
NOTE: IXF is the preferred formut to use when exporting data from and importingdata to a DB2 database table.
Three special structures (sqldcol,sqlu-media-list, and sqlchar) are used to pass general informationto the DB2 Import utility when this function is called. Referto the EXPORT function fora detailed description of the sqldcol structure, and refer to the BACKUP DATABASE function for a detailed description of the sqlu-media-list structure. A special structure (thesqlloctab structure) may also be used by the sqldcol structure (if the dcolmeth field is setto SQL"P.TH-L) when this function is executed. The sqlloctab structure is defined in sq1util.h as follows: etruct eqlloctab {
struct eqllocpair locpair[ll;
/*
/* /* /*
A
pointer to an array of sqllocpair etructuree that containsa list o f ending and column starting positione
*/ */ */ */
T h i s structure contains a pointer to an arrayof sqllocpair structures that areused to build a listof starting and ending column positionsthat identify how data isstored in an external file. Thesqllocpair structure is defined in sqlutil. has follows: struct eqllocpair
c short begin-loci end-loci short
/* /* /* /*
The starting poeition of the columndataintheexternalfile The ending position of the column data in external the file
*/ */ */ */
1;
Two additional structures, sqluimpt-in and sqluimpt-out, are used to pass IMPORspecific information to and receiveI M P O R T - S ~ ~ information ~~~~C h m the DB2 Import facility whent h i s function is called. Thefirst of these structures, sqluimpt-in, passes information about whendata isto be committed to the database to the Importfacility and is deked in sqlutil. h as follows: etruct sqlubpt-in {
uneigned long eizeOfStruct; unsigned long cannnitcnt;
/* /* /*
The size of the sqluimpt-in structure */ The number of records to import before */ a COMMIT SQL statement is executed. */
Part 3: Application Programming Interface Functions
unsigned long reetartcnt;
/* /* /* /* /* /* /* /* /*
COMMIT statement is executed each */ time this number of records import&*/ are to make the additionspermanent. */ The number of recorda to skip in the file*/ before starting theImport process. This*/ field can be used aifprsviaue attempt to*/ import records failed after n number of */ rows of data were already committed */ to the database. */
A
The secondof these structures, sqluimpt-out, is used to return statistical information about the import operationto the application after all data hasbeen copied to the table. "he sqluimpt-out structure is defined in sq1util.h as fOllOWS: StruCt eqluimpt-out
c
unsigned long sizeOfStruct;
/*
The size ofthe eqluilqpt-out structure unsigned long rowsRead; /* The number of records read from /* the external file /* The number of records skipped unsigned long rms8kipped; / * before the import process was /* started unsigned long roweInserted; /* The numberof rows inserted into /* the specified database table unsigned long rowenpdated; /* The number of rows updated in /* the specified table. Indicates the / * number of recordsin the file that /* have matching primary key values /* in the table. unsigned long roweRejected; /* The number of records in the file /* that, for some reason, could not /* be imported unsigned long rwscommitted; /* The number of rows successfully /* imported and committed
/*
*/ */ */ */
*/ */
*/ */ */ "/
*/ */
*/ */ */ */ */ */ */
NOTE: Data that has minor incompatibility problems will usually be accepted by the Import facility(forexample, you can import character data by using padding or truncation and numeric data by using adifferent numeric data type). Data that hasmajor incompatibility problemswill be rejected.
Comments
The dcolmeth field of the sqldcol structure specified in the DataDescriptor parameter defines how columns are to be selected for importfrom the external data file. This parameter can be set to any of the following values:
m SQL-METH-N Specifies that column names provided in the sqldcol structure identify the data
Chapter 11:Data Handling APIs I
j
I
435
l
that is to be imported from the external file. This method cannot be used if the external file is indelimited ASCII format.
m SQL"ETH-P Specifies that starting column positions providedin thesqldcol structure identify the datathat is to be imported from the external file. This method cannot be used if the external file is indelimited ASCII format.
m SQL-METH-L Specifies that starting and ending column positions providedin the sqldcol structure identify the datathat isto be imported fromthe external file. This method is theonly methodthat can be used ifthe external file is in delimited ASCII format. SQL-METI-D
Specifies that the f i s t column in the external file is to be imported into the first column of the table, the second column in theexternal file into the second column of the table, and so on. W If the DataDescriptor parameter is setto NULL or if the dcolmeth field of the
sqldcol structure specified in theDataDescriptor parameter is set to SQLJIETH-D, the dcolnum and dcolnume fields of the sqldcol structure areignored. M If the dcolmeth field of the sqldcol structure in the DataDescriptor parameter is set
to SQL-ME~KN, the dcolnptr pointer of each elementof the dcolnume array must point to a string, dcolnlen characters in length, that contains the name of a valid column in theexternal file that is to be imported. If the dcolmeth field of the sqldcol structure in theDataDescriptor parameter is set to SQL"J$TI-P, the dcolnptr pointer of each elementof the dcolnume array is ignored and the dcolnlen field of each elementof the dcolname array mustcontain a valid column positionin the external file that is to be imported. The lowest column (byte) position value that can be specified is 1 (indicating the f i s t column or byte), andthe largest column (byte) position valuethat can be specified is determined by the number bytes containedin one row of data in theexternal file. If the dcolmeth field of the sqldcol structure in the Datdescriptor parameter is set to SQL-METH-L, the dcolnptr pointer of the firstelement of the dcolnume array points to a sqlloctab structure that consists of an arrayof sqllocpair structures. The numberof elements in this array must be stored in the dcolnum field of the sqldcol structure. Each elementin this array must contain a pair of integer values that indicates the positions in thefile wherea column beginsand ends. Thefist integer value i s the byte position(in a row) in thefile wherethe column begins, and the second integer value is thebyte position(in thesame row) wherethe column ends. Thefirst byte position valuethat can be specified is 1 (indicating the first byte in a row of data), and the largestbyte position valuethat can be specified is determined by the number of bytes containedin one row of data in the external file. Columns defined bystarting and ending byte positions can overlap. m If the dcolmeth field of the sqldcol structure in the DataDescriptor parameter is set
Part 3: Application Programming Interface Functions to SQL-~TH-L, the DB2 Database Manager will rejectan IMPORT call if a location pair is invalid becauseof any of the following conditions: - Either the beginning or the ending location specifiedis not valid. -The ending location valueis smaller than thebeginning location value. -The input column width definedby the beginningend location pair is not compatible with the datatype and length of the targetdatabase table column. B Beginnindend location pairs that have both values set to o indicate that a column i s nullable and that it i s to be filled with NULL values. B If the DataDescriptor parameter is setto NULL or if the dcolmeth fieldof the
sqldcol structure specified in the DataDescriptor parameter is setto SQL-METH-D, the first n columns (wheren is the number of database columns into which the data is to be imported)of data found in theexternal file will be imported in their natural order.
m Columns in external files can be specified morethan once, but anything that is not a valid specificationof an external column (i.e.,a name, position, location,or default) will causean error t o be generated. Every column foundin anexternal file does not have to be imported. The SQL statement specified in the ActwnString parameter must be in the following format: [Action] INTO [TableName <(ColurrmName,...)>I
TABLESI(Tab1eName (ColumnName, ) > HIERARCHY [STARTINO TabIdame, . l l
...
where: ActionSpecifies
..
how thedata i s to be imported into the database table.The action can be any of the following values: INSERT
Specifies that imported data rows are to be addedto a table that already exists in the database-and that any data previously stored in the table should not be changed. INSERT-UPDATE
Specifies that imported data rows are to be added to a table if their primary keys do not match existing table data-and that they are to be used to update data ina table if matchingprimary keys are found. This option is only valid whenthe targettable has a primary key and when the specified (or implied) list of target columns being imported includes all columns forthe primary key. This Action cannot be applied to views. REPLACE
Specifies that all existing data ina table is to be deleted before data is imported. Whenexisting data isdeleted, table and index definitions remain undisturbed unless otherwise specified
Chapter 11: Data Handling APIs I
(indexes are deleted and replaced ifthe FilenpeMod parameter is set t o “indexixf” and if the Filenpe parameter is set to SQL-IXF). If the table is not already defined, a n error will be returned. If an error occurs after existing data isdeleted, that data will belost and can only be recovered if the database was backed up before the IMPORT function was called.
m CREATE Specifies that if the table does not already exist, it will be created using the table definition stored in thespecified PC/IxF format data file. Ifthe PC/MF file was exported from DB2 a database, indexes will alsobe created. If the specified table name is already defined, an error will be returned. This Action is only valid for PC/IXF format files. REPLACE-=TE
Specifies that if the table already exists, any data previously stored in it will be replacedwith the dataimported fromthe PC/IxF format file. Ifthe table does notalready exist, the table will be created using the table definition stored in thespecified PC/IXF format data file. Ifthe PC/MF file was exported from a DB2 database, indexes will also be created when the table is created. This Action is only valid for PC/IXF format files.anIf error occurs after existing data isdeleted fromthe table, that data will be lost and can only be recovered if the database was backed up before the IMPORT function was called. ThbleName
is to Specifies the name of the table or updatable view that the data be inserted into. A alias name can be used ifthe REPLACE, INSERT-UPDATE, or INSERTAction is specified, exceptin thecase of a down-level server.In this case, atable name (either qualified or unqualified) should always be used.
ColumnName
Specifies oneor more columnnames within the table or view into which data from the external file is to be inserted. Commas must separate each columnname in thislist. If no column names are specified, the column names defined forthe table will be used.
ALL
Specifies to import all tables specified in thetraversal order list when importing a hierarchy.
TABLES
HIERARCHY
Specifies that hierarchical data isto be imported.
STARTING
Specifies that thedefault order of a hierarchy,starting at a given sub-table name, is to be used whenimporting hierarchical data. Specifies that thenew hierarchy, sub-hierarchy,or sub-table is to be created under a given sub-table.
UNDER
SubThbleNam Specifies the parent table to use when creating one or more sub-
tables in a hierarchy. LE
Specifies that the new hierarc~y,sub-~erarchy,or created as a stand-alone hierarchy.
a ~the e C o l u ~ list n parameters ~ ~ ~ ~correspond to the The ~ a b l e ~ and ~ a ~ l e and ~ a~ ~o el ~ list a par ~ e eters of the ~ ~ ~ SE L R statement T that is used to import the data, and they have the same rest~ctions.
e columns in the ~ o l u ~ nlist ~ and a ~ the e columns (either specified or implied) in the external file are matched according to their position in the list or in the s ~ l ~ c structure ol (data from the first column specified in the s ~ l ~ c structure ol is inserted into the table or view column that corresponds to the first element of the C o l u ~ n ~ list). a ~ eIf unequal numbers of columns are specified, the number of columns actually processed is the lesser of the two numbers. This situation could cause an error message (because there might not be values to place in some NOT ~~L table columns) or an i n f o ~ a t i o n amessage l (because some external file columns are ignored) to be generated. e ~ a parameter ~ e contains the path and the name of a file that s, the existing file will be o v e ~ ~ t t when e n this ~ n c t i o nis executed.
nction is called. The caller action repeat call facility provides support for i m p o ~ i n gdata from support diskettes. t o r smust match the number of e number of elements in the ~ u Z Z ~ n ~ ~ c aarray
L statement is executed, two age identifies the number of
statement was
drive, rather than on ~ i s ~ e t t e s . non-~efaultcolumn t of table columns in remote database slower.
eter or an
in tio
import in^ to a
and the potential growth in the size ofthe database.
if a
or if an application inte leted, part or all of the o
stem failure
I
440
1i
Part 3: Application Programming Interface Functions "If it is likely that subsequent INSERT statements w l ifail and that there is potential for database damage, an error message will be written to the message He, and processing will stop.
H Data from external files cannot be imported to system catalogtables.
H Views cannot be created with a CREATE import. H
m P u c E and m P m c E - c m m m imports cannotbe performed on object tables that
have other dependents (other than themselves) or on object views whose base tables have other dependents (including themselves).To replace such a table or a view, perform the following steps:
1. h p all foreign keysin which the table i s a parent. 2. Execute the IMPORT function. 3. Alter the table to recreate the foreign keys. Ifan error occurs while recreating the foreign keys,modi@ the dataso that it maintains referential integrity. D Referential constraints and key definitionsare not preserved whentables are created (CREATEAction) from PC/IXF (SQL-IXF) format files. W You can use the IMPORT function to recover a previously exportedtable if the PC/IXF (SQLLIXF) format was used. Whenthe IMPORT function is executed, the table returns to the state it was in when the table was exported.This operation i s similar to but distinct from a backupand restore operation. U The data field of the sqlchar structure specified in the FileQpeMod parameter can
contain any of the following values:
Chapter 11: Data Handling APIs “decptx” “ndoubledel” “defer-import” “forcein” “indexixf” ”indexechema=.achema” “nochecklengthe”
These values provide additional information about the chosen file format. Only a portion of these values are used with a particular file format. If the FileQpeMod parameter is set t o NULL or if the length field of the sqlchr structure is set to 0, default information is provided forthe file format specified. If the FileQpeMod parkmeter is set to “no-type-id,” all imported data will be converted into a single sub-table. m If the source columnin anexternal file is not explicitly specified,and if the is to be loaded into is not nullable, the correspondingtable column that the data FileQpeMod parameter can be set to “nodefaulte”to keep default values from being substituted. Otherwise, adefault value is substituted if the table column is nullable and if a default value exists. A NULL is substituted if the table column is nullable and no default exists - or an error occurs ifthe table column is not nullable. If the source columnin anexternal file has been explicitly specified,and if it does not containdata for oneor more rows,the FileQpeMod parameter can be set t o “ueedefaulte”to ensure that default values are substituted. Otherwise, aNULL is substituted if the table column is nullabl-r the row is not loadedif the table column is not nullable. m If data isbeing imported fromeither a delimited ASCII(SQL-DEL) or PC/IxF (SQL-IXF) format file, the FileQpeMod parameter can specify whereLOB data is stored. If this parameter is set to “lobeinfile,” LOB data is stored in separate external files; otherwise,all LOB data isassumed to be truncated to 32KB and stored in thesame file. B If the FileQpeMod parameter is setto “lobeinfile”and the CREATE option is used, the original LOB length is lost, and the LOB value stored in thedatabase is truncated to 32KB. B If the FileQpeMod parameter is set to “~ompound-2(where x is any number between 1and 100 or 7 on DOS/Windows platforms), nonatomic compound SQL is used to insert theimported data (i.e., x number of statements will be processedas a singlecompound SQL statement). If data is being imported from a delimited ASCII (SQL-DEL) format file, the FileQpeMod parameter can be set to “noeofchar”to specify that the optional endof-file character (OxlA) is not to be recognizedas theend-of-file character.If this option is set, theend-of-file character (OxlA)is treated as a normal character.
442 j
Part 3: Application Programming Interface Functions H If data is being importedfrom a delimited ASCII (SQL-DEL) format file,the
I"ile!&peMod parameter can be set to reclennxxxx (where xxrx is a number no larger than 32767) to specify that 3c~wc1ccharacters are to be read infor eachrow. In this case, a new-linecharacter does not indicate the end of a row. If data is being imported from a delimited ASCII (sQL-D!im) format file,you can use the FilenpeMod parameter to specify characters that override the following options: Datalink delimiters
By default, the inter-field separator for a DATALINK value is a semicolon C).Specifsing "dldel" followed by a character will cause the specified character to be used in place of a semicolon as theinter-field separator. The character specified must be different from the characters used as row, column, and character string delimiters.
Double character delimiters
Specifying %odoubledel" will cause recognition of all double-byte character delimiters to be suppressed.
Column delimiters
By default, columns are delimited with commas. Specifying "coldel" followed by a character will cause the specified character to be usedin place of a comma to signal the end of a column.
Character string delimiters
By default, character strings are delimited with double quotation marks. Specifying "chardel" followed by acharacter will cause the specified character to be used in place of double quotation marks to enclose a character string.
Decimal point characters
By default, decimal points are specified with periods. Specifying"decpt" followed bya character will cause the specified character to be used in place of a period as a decimal point character.
Plus sign character
By default, positive decimalvalues are prefixed with a plus sign. Specifyingudecplusblank"will cause positive decimalvalues to be prefixed witha blank space instead of a plus sign.
Date format
Specifying "dateeieo" will cause all date values to be imported in IS0 format.
If two or more delimiters are specified, they must be separated by blank spaces. Blank spaces cannot be used as delimiters.Each delimiter character specified must be different from the delimiter characters already being usedso all delimiters can be uniquely identified. Table11-3 (refer to the EXPORT function)
Chapter 11: Data Handling APIs lists thecharacters that can be used as delimiter overrides. B If data isbeing imported froman ASCII (SOL-DEL or SOL-MC) format file,the
FileFypeMod parameter can be set to “implieddecimal”to specify that the location of an implied decimal pointis to be determined by the table column definition (for example, if the value 12345 wereto be loadedinto a DECIMAL(8,B)col-, it would be loadedas 123.45, notas 12345.00-which would otherwise bethe case). If data is being imported from a non-delimited ASCII(SOL-ASC) format file,the FileFypeMod parameter can be set to “nullindchar=g (where x equals a character) to specify that a NULL value is to be replaced witha specific character. The character specified is case-sensitive forEBCDIC data files, except whenthe character is an English character. If data isbeing imported froma non-delimited ASCII(SOL-ASC) format file,the FileFypeMod parameter can be set to “etriptblanke“to spec@ that trailing blank spaces (after the lastnonblank character) are to be removed (truncated) when data is imported. Ifthis option is not set, trailingblanks are kept. B If data is being imported froma non-delimited ASCII(SQLASC) format file,the
FileQpeMod parameter can be set to “etriptnulle”to specify that trailing NULLS (after the lastnonblank character) are to be removed (truncated) when data is imported into variable length fields. Ifthis option is not set, NULLS (0x00 characters) are kept. B The “etriptblanke”and the “striptnulle”options are mutually exclusive. If one is
specified, the other cannot be used. B If data is being imported froma P C m (SOL-IXF) format file,the FileQpeMod parameter can be set t o “defer-import” to specify that the tabledsub-tables stored
in thefile are t o be created, but thedata is not to be imported.This setting can only be used with a CREATEimport. B If data isbeing imported froma PC/MF (SOL-IXF) format file,the FileFypeMod parameter can be set to “forcein”to tell theimport utility to accept data inspite
of code page mismatches and to suppress all translations between code pages. B If data is being importedfrom a PC/IXF (SOL-IXF) format file,the FileQpeMod
parameter can be set to “nochecklengthe”to specify that checking to ensure that k e d length target fields are large enough to hold the imported data is not to be performed. T h i s option is used in conjunction withthe “forcein”option. H If data isbeing imported froma PC/IXF (SOL-IXF) format file, the FileFypeMod parameter can beset to “indexixf”to tell the import utility to drop all indexes
currently defined on the existing table and create new ones from the index definitions foundin the PC/IXF format file being imported. This option can only be used when the contents of a table are being replaced.This option cannot be used with a view. W If data isbeing imported from a PC/IxF(SQLLIXF)format file,the FileFypeMod
parameter can be set to “indexechema-8chema”(where echema is avalid schema
1 I
444
I R
i
Part 3: Application F'rogramming Interface Functions
I
name) to indicate that thespecified schemais to be used forthe index name whenever indexesare created. If no schema is specified, the authorization ID that was used to establish the currentdatabase connection will be usedas thedefault schema. T h i s function will not issue a warning ifyou attempt to specify optionsthat are not
supported by the file type specifiedin theFileope parameter. Instead, this function willfail, and an error will be generated. If data isbeing imported froma WSF (SQL-WSF) format file,the FileTypeMod parameter is ignored. "he
LOAD function is
a faster alternative to the IMPORT function.
Connection This function can only be called if a connection to a database exists. Requirements Authorization Only users with System Administrator(SYSADM) authority, Database Administrator (DBADM) authority, or CONTROL, INSERT, or SELECT authority for the specified table or view can executethis function with the INSERT action (ActionString parameter) specified. Onlyusers with SYSADM authority, DBADM authority, or CONTROL authority for the specified table or view can executethis function withthe INSERT-UPDATE,REPLACE,or REPLACE-CREATE action (Actionstring parameter) specified. Onlyusers with SYSADM authority, DBADM authority, or CREATETAB authority for the specified table or view can executethis function withthe CREATE or the REPLACE-CREATE action (Actionstring parameter) specified.
see Also Example
EXPORT, LOAD
Thefollowing C++ program illustrates how t o use the IMPORT function to insert data from an external file into the DEPARTMENT table of the SAMPLE database:
/*
CRllEX2.
/* /* /* /* /* /*
*/ NAME: SQC PURPOSE: Illustrate How To Use The Following DB2 API Function In A C++ Program:
*/ */
*/ */
IMPORT
/*
/ / Include The Appropriate Reader Piles #include *windows.h, #include 4ostream.b #include <sqlutil.h> #include <sql.h> / / Define The API-Class Class class API-Claes {
/ / Attribute8 public:
*/ */ */
Chapter 11: Data Handling APIs struct eqlca eqlca; / / Operations public: long ImportData ();
1; / / Define The ImportDataO Member Function long API-Class ::ImportData( ) {
MsgFileName[801; String[EOl;
/ / Declare The Local M e m o r y Variables DataFileName char [EO] char char struct sqlchar *ACtiOnString; struct sqluimpt-in 1nput1nfo; atruct sqluimpt-out Output1nfo;
;
/ / Initialize
The Local Variables strcpy(DataFileName, *'C:\\DEPT.IQ"); etrcpy(MsgFileName, B8C:\\IMP-MS0.DAT"); / / Initialize The Import Input Structure 1nputInfo.sizeOfStruct = SQLUIMPT-IN-SIZE; 1nput1nfo.conanitcnt 20; 1nputInfo.restartcnt = 0;
-
/ / Initialize Them o r t Output Structure OutputInfo.sizeOfStruct = SQLUIMPT~O~-SIZE;
/ / Define The Action / / Data Is Imported
String
That
Will
Be To Used Control How
strcpy(String, "REPLACE INTO DEPARTMENT") ; ActionString(structsqlchar *) malloc (strlen(String) + sizeof (struct sqlchar)); Actionstring->length = strlen(String); strncpy(ActionString->data, String, strlen(String)); / / Import Data IntoThe D E P A R m N T Table FromAn IQ Format / / File (This FileWas Created By The EXPORT Example)
sqluimpr(DataFileName, NULL, NULL, ActionString, SQL-IXF, NULL, MsgFileName, SQLU-INITIAL, &InputInfo, &OutputInfo, NULL, NULL, &sqlca); / / If The Data / / Message
Was Imported Successfully, Display A Success
if (aqlca.sqlcode
m=
SQL-RC-OK)
coutOutputInfo.rowsInserted << '' cout << "rows of data were inserted into the DEPARTMENT cout << "table from the '' << endl; cout << "file C:/DEPT.IQ.n << endl;
1 / / Free
All
Allocated Memory
446
Part 3: Application Programming Interface Functions if (Actionstring != NVLL) free (Actionstring); / / Return The SQLCA Return Code To The Calling Function return(sqlca.sqlcode);
1 1
I
/ * The Main Function
*/
I
I
int main ( ) {
/ / Declare The Local Memory Variables
long struct sqlca
rc = SQL-RC-OK; sqlca;
/ / Create An Instance Of The API-Class Class API-Class Example; / / Connect To The SAMPLE Database EXEC SQL CONNECT TO SAMPLE USER userID USING password; / / Import Data Stored In An External File Into The DEPARTMENT / / Table (In The SAMPLE Database)
rc = Example. ImportData ( ) ; / / Issue A Rollback To Free All Locks EXEC SQL ROLLBACK; / / Disconnect From The SAMPLE Database EXEC SQL DISCONNECT CURRENT;
/ / Return To The Operating System return(rc);
1
LOAD Purpose Syntax
The LOAD h c t i o n is used to bulk load data from external files, tapes, or named pipes into DB2 database tables. SQL-API-RC SQL-API-FN sqluload (sqlu-media-list *DataFi1eList, sqlu-media-list *LOBPathList, struct struct char struct char char short struct struct
sqldcol sqlchar sglchar
sgluload-in sqluload-out
*DataDescrigtor, *Actionstring, *File r n e , *Fi1e TygeMod, *LocalMsgFileName, *Remot eMsgFi 1eName, Calle r A c t i on, *LoadInfoIn, *LoadInfoOut,
447
Chapter 11:Data Handling APIs eglu-media-list sqlu-media-list long void struct sglca
Parameters
*WorkDirectoryList, *CoppargetList, *NzzllIndicators, *Reserved, *SQLCA);
DataFileList
A pointer to a sqlu-media-list structure that contains a list of external data files, devices, vendors, or named pipes that identify where data is to be loaded from.
LOBPathList
A pointer to a sqlu-media-list structure that contains a list of local paths on the client workstation that identifj. where LOB data files are to be loaded from.
DataDescriptor
A pointer to a sqldcol structure that contains information about the columns in the external data file(s) that are to be loaded. The value of the dcolmeth field of this structure determines how columns are selected from the external file(s).
Actionstring
A pointer to a sqlchar structure that contains a valid dynamic SQL statement that identifies the action to be taken when loading data into tables that already contain data.
Fileope
A pointer to a location in memory where a string that specifies the format of the external data file(s)is stored. This parameter must be set to one of the following values: SQL-DEL
Data in the external file(s) is stored in delimited ASCII format. SQL-ASC
Data in the external file(s) is stored in nondelimited ASCII format. SQL-IXF
Data in the external file(s)is stored in PCAntegrated Exchange format.
FileTypeMod
A pointer to a sqlchar structure that contains additional information (unique to the format used) about the data stored in the external file.
LoculMsgFileName
A pointer to a location in memory where the name of the file that all LOAD error, warning, and informational messages are to be written to is stored.
RemoteMsgFileNume
A pointer to a location in memory where the base name that is to be used for naming temporary files created by the
L448
1
L
Part 3: Application Programming InterfaceFunctions
i
.
CaZlerAction
Load operation currently in progress is stored. Specifies the action that this function is t o take when it executes. This parameter must be set to one of the following values:
m SQLU-INITIAL "he LOAD operation is to be started. SQLU-CONTINUE
The WADoperation is to be continued aRer the user has performed some actionthat was requested by the Load utility (for example,inserting a diskette or mounting a new tape). SQLU-TERMINATE
The LOAD operation is to be terminated because the user failed to perform some actionthat was requested by the Load utility. SPLU_NOINTERRUPT
"he WADoperation is to run without suspending processing. SQLU-ORT The LOAD operation is to be terminated. SQLU-RESTART The LOAD operation is to be restarted. SQLU-DEVICE-TERMINATE
A particular device should be removed fromthe listof devices used bythe LOAD utility. When a particular device has exhausted its input, theLOAD utility returns a warning to the caller (while continuing to use the remaining devices).By calling the LOAD function again with this caller action specified, you can remove the device that generated the warning condition fromthe list of devices being used. LoadInfoIn
A pointer to an sqluload-in structure that contains information aboutthe number of records to skip, numberof records to load, sizesof internal buffers, and load fail conditions.
LoadInfoOut
A pointer to an sqluload-out structure where this function is to store summary information aboutthe LOAD operation.
WorkDirectoryList
A pointer to an sqlu-media-list structure that contains a list of optional work directoriesthat areto be used for sorting index keysduring the LOAD operation. This
Chapter 11:Data Handling APIs
:
449
parameter can be set to NULL. CopylbrgetList
NullIndicators
Reserved
SQLCA
A pointer to an sqlu-media-list structure that contains a list of external data files, devices,or shared libraries where copy images of the data(if created) are to be written. A pointer to an arrayof integers that indicates whether or not each columnof data retrieved can containNULL values. This parameter is only used if the Fileope parameter is setto SQL-DEL. A pointer that is currently reserved forlater use. For now, this parameter must always be set to NULL. A pointer to a location in memory wherea SQL Communications Area(SQLCA) data structurevariable is stored. This variable returns either statusinformation (if the function executed successfully)or error information (if the function failed)to the calling application.
Includes
#include <sqlutil.h>
Description
The LOAD function is used to bulk loaddata from external files, tapes, or named pipes into DB2 database tables. Data can be loaded fromany filethat uses one of the following internal file formats: W Delimited ASCII W Nondelimited ASCII W PC Integrated Exchange Format IXF
Three special structures (sqldcol, sqlu-media-list, and sqlchar) are used to pass general informationto the DB2 Load utility when this function is called. Referto the EXPORT function fora detailed descriptionof the sqldcol structure, and referto the BACKUP DATABASE function fora detailed descriptionof the sqlu-media-list structure. A special structure (thesqlloctab structure) may also be used bythe sqldcol structure (if the dcolmeth field is set to SQL-METH-L) when this function is executed. Refert o the IMPORT function for a detailed descriptionof this structure. Two additional structures, sqluload-in and sqluload-out, are used to pass LOADspecific informationto and receive specific information from the DB2 Load facility whenthis function is called. Thefirst of these structures, sqluload-in, passes information suchas when data isto be committed and the number of records t o skip before starting theload operationt o the Load facility and isdefined in sqluti1.h as follows: struct sqluload-in unsigned long size0fStruct; unsigned long savecnt;
/* The size of the sqluload-in structure */
/* /*
The number of records to loadbefore a COMMIT SQL etatement is executed
*/ */
Part 3: Application Programming Interface Functions /*
A COMKIT statement is executed each */ time thie numberof records are loaded */ /* to make the addition8 permanent */ unsigned long reetartcnt; /* The number of recon% to skip in the file */ /* before starting the load process. This */ /* field canbe wed if a previaus a t t m t to*/ /* load records failed aftern number of */ committed*/ /* rows of data had already been /* to the database. */ unsignedlong rmnt; /* The numberof rows ofdata to load */ unsigned long warningcnt; /* The number of warning conditione to */ /* ignore before failing */ unsigned long data-hffer-size; /* The size, in ~ R B pages. of the bufferto */ /* be used when loading data */ unsigned long sort-buffer-size; /* The size, in 4KB pages, of the bufferto*/ /* be used when sorting data */ unsigned shorthold-quiescei /* A flag indicating whetheror not the table*/ /* eaaces for the table being loaded are */ /* in a quieeced state */ char /* Indicatesthat an interruptedload */ reetartphase; /* operation is to be restarted at theload*/ /* phase (SQLU-LOAD-PHASE), at the */ /* build phase (SQLU-BUILD-PHASE), */ /* or at delete thephase */ /* (SQLU-DELETE-PHASE) */ char etateopt; /* Specifies the granularity to uee when */ /* collecting etatietical information &ring*/ /* the load aperation. TMS field can contain*/ /* any of the following values: */ /* SQLU-STATS-NONE */ */ /* SQL-STATS-TABLE, /* SQL-STATS-EXTTABLE-OmY, */ /* SQL-STATS-BOTH, */ /* SQL-STATS-EXTTTABLE-INDEX, */ /* SQL-STATS-INDEX, */ /* SQL-STATS-EXTINDEX-ONLY, */ / * SQL-STATS-EXTINDEX-TABLE, */ /* SQL-STATSALL. Refer to the RUN */ /* STATISTICS function for more */ /* information about etatistic granularity. */ unsigned short cpugaralleliem;/* The number of processes or threads that*/ /* the load utilityis to spawn for parsing,*/ /* converting, and formatting records when */ /* building table objecte. If thie field */ /* will autamaticallybe set to 1 if loading*/ /* tables containing either LOB or LONG */ / * VARCHAR fielde. */ migned ehort disk paralleliem; /* The number of processesor threads that*/ /* the load utility is to spawn 'for writing*/ */ /* data to table space containers unsigned short noprecoverable; /* ulaicatee that the load transaction ie to*/ /* marked non-recoverable be */ /* (SQLU-NON-RECOVERAE3LE-LOAD) or */ /* recoverable (SQLU-RECOVERABLE-LOAD). */ /* This field identifies whether or not*/ it
/*
Chapter 11: Data Handling APIs /* /* /*
will be possibleto recover the LOAD */ operation with a roll-forward recovery */ operation */
The second ofthese structures,sqluload-out, is used to return statistical information aboutthe load operationto the application after all data hasbeen loaded. The sqluload-out structure isdefined in sq1util.h as follows: struct sqluload-out {
unsigned long Sizeofstruct?
/*
/* unsigned long rowsRead; unsigned
long rowslkipped;
unsigned long rowsLoadedt unsigned
long rowsllejected;
unsigned long unsigned long
\e 1;
1
/*
/* /*
/* /* /* /*
/* /* /* /* /* /* /*
The size of the sqluload-out structure The number of records read from the external file The numberof records skipped before the load process was started The number of rows inserted into the specified database table The number of records in the file that, for some reason, could not be loaded The number of duplicate rows that were deleted The number of rows succeeefully loaded and committed
*/ */ */ */ */ */
*/ */ */ */ */ */
*/ */
*/ */
NOTE: Data that has minor incompatibility problemswill usually be accepted by the load facility (for example, youcan load character data by using padding or truncationand numeric data by using adifferentnumeric data type). Data withmajor incompatibility problems will be rejected.
Comments
D The type of structure used to provideinformationaboutwhere
data is to beloaded from is determined by the value specifiedin themedia-type field of the sqlu-medialist structure (stored in the DataFileList parameter) asfollows: SQLU-SERVER-LOCATION
One or more sqlu-location-entry structures. The sessions field of the sqlu-media-list structure should indicatethe number of sqlu-location-entry Structures used. SQLU-ADSM4IgDIA
One sqlu-vendor structure. The filename field of the sqlu-vendor structure should contain a unique identifier forthe datasource to be loaded. The Load utility will start each sessionwith a different sequencenumber,but with the same data specified in thesqlu-vendor structure. SQLU-OTfIFiR4IgDIA
One sqlu-vendor structure. The shr-lib field of the sqlu-vendor structure should
.
Part 3: Application Programming Interface Functions contain a validshared library name, and the filename field of the sqlu-vendor structure should contain a unique identifier for the datato be loaded. TheLoadutility will start each sessionwith a different sequencenumber but with the same data specified in thesqlu-vendor structure. W Data files that were created with the EXPORT function or command will have LOB
data filenames stored in them if the specified data setcontained LOB data andif the “lobsinfile”option was specified. These names are appended to the paths specified in thesqlu-medialist structure during the Load processto provide a reference to LOB data. The typeof structure used t o provide informationabout external LOB data file paths isdetermined by the value specified in themedia-type field of the sqlu-medialist structure stored in the LOBPathList parameter as follows: SQLU-LOCALMEDIA
One or more sqlu-media-entry structures. The sessions field of the sqlu-media-list structure should indicate the number of sqlu-media-entry structures used. SQLU-AD=-MEDIA
One sqlu-vendor structure. The filename field of the sqlu-vendor structure should contain a unique identifier for the datat o be loaded. The Loadutility will start each ADSM session with a different sequence numberbut with the same data specified in the sqlu-vendor structure. W SQLU-OTHER-BEDIA
One sqlugendor structure. The shr-lib field of the sqlu-vendor structure should contain a validshared library name, and the filename field of the sqlu-vendor structure should contain a unique identifier for the datat o be loaded. The Load utility will start each sessionwith a different sequence number but with the same data specified in the sqlu-vendor structure. W The dcolmeth field of the sqldcol structure specified in the DataDescriptor
parameter defines how columns are selected for loading from the external data file. This parameter can be set to any of the following values: SQL-METH-N
Specifies that column names providedin thesqldcol structure identify the data that is to be loaded fromthe external file. T h i s method cannot be used ifthe external file is in delimited ASCII format.
m SQL-METH-P Specifies that starting column positions providedin the sqldcol structure identify the data that to is be loaded fromthe external file. T h i s method cannot be used ifthe external file is in delimited ASCII format.
m
SQL-BETH-L
Specifies that startingand ending column positions providedin the sqldcol structure identify the data thatis to be loadedfrom the external file. This
Chapter 11: Data Handling APIs method is theonly methodthat can be used the if external file is in delimited ASCII format. SQL-ME'Ri-D
Specifies that thefirst column in theexternal file is to be loadedinto the first column of the table, the second columnin theexternal file is to be loaded into the second columnof the table, and so on. W If the DataDescriptor parameter is set to NULL or if the dcolmeth field of the
sqldcol structure specified in theDataDescriptor parameter is setto SQL-METH-D, the dcolnum field and the dcolname field of the sqldcol structure areignored. W If the dcolmeth field of the sqldcol structure in the DataDescriptor parameter is set
to SQL-METE-N, the dcolnptr pointer of each element of the dcolname array must point to a string, dcolnlen characters in length, that contains the name of a valid column in theexternal file that is to be loaded. W If the dcolmeth field of the sqldcol structure in the DataDescriptor parameter is set to SQL-METH-P, the dcolnptr pointer of each elementof the dcolname array is
ignored and the dcolnlen field of each elementof the dcolname array must contain a valid column positionin theexternal file that is be loaded. The lowest column (byte)position value that can be specifiedis 1 (indicatingthe firstcolumn or byte), and the largest column (byte) position valuethat can be specifiedis determined by the number bytes containedin one rowof data in theexternal file. to'
W If the dcolmeth field of the sqldcol structure in the DataDescriptor parameter is set
to SQL-METH-L, the dcolnptr pointer of the firstelement of the dcolname array points to a sqlloctab structure that consists of an array of sqllocpair structures. The number of elements in this array must be stored in thedcolnum field of the sqldcol structure. Each element in this arraymust contain a pair of integer values that indicate the position in thefile wherea column beginsand ends. Thefirst integer value is the byte position(in a row) in thefile wherethe column begins, and the second integer value is thebyte position(in the same row) wherethe column ends. Thefirst byte positionvalue that can be specified is 1 (indicatingthe first byte in a row of data), and the largest byte position valuethat can be specified is determined by the number of bytes containedin one row of data in the external file. Columns definedby starting and ending byte positionscan overlap. M If the dcolmeth field of the sqldcol structure in the DataDescriptor parameter is set
to SQL-METH-L, the DB2 Database Manager will rejecta LOAD call if a location pair is invalid becauseof any of the following conditions: - Either the beginning or the ending location specifiedis not valid.
-The ending location value is smaller than
thebeginning location value.
-The input column width defined by the beginnindend location pair is not compatible with the datatype and length of the targetdatabase table column.
H Location pairs that have bothvalues set to o indicate that a column is nullable and that it is to be filledwith NULL values.
of database columns into ata is to be loaded) of data found in the external file will be loaded in their mns in external files can be specified more than once, but anything that is not mn (a name, position, location, or default)
sting data is deleted, that data is lost if the database was backed up before
d load o~erationis to be
lin
s recommended for general use and should only be used if an unrecoverable error has occurred.~ t t e m pto t restart an i n t e ~ p t e dload whenever possible.
Tab l e ~ a ~ e Specifies the name of the table that the data is to be loaded i alias name, a fully qualified name, or an un~ualifiedname can b specified. If an u n ~ u a l i f i ename ~ is speci~ed,the authori~ati the current user will be used as the default qualifier. Colu m n ~ a m e Specifies one or more column names within the table into which data $.om the external file is to be loaded. omm mas must separate each column n m e in this list. If no column names column names defined for the table are used. If a c contains spaces or lower-case characters, the name must be enclosed by a quotation. Specifies the name of the exception table to which all data causes an error to occur during the load Data that violates a unique index or a p specified table is stored here, e Table~arneand the Column~amelist parameters c Tuble~ameand ~ o l ~ a r list n e parameters of the ~ ~ S E ~ T used to load the data, and they have the same restrictions. The columns in the Colurnn~amelist and the columns (either specified or i ~ p l i e d ) in the external file are matched according to their position in the list or in the s4Z~colstructure (data from the first column specified in the ~ 4 1 ~ structure ~01 is inserted into the table column that corresponds to the first Colum~~am list). e If unequal numbers of columns are spec columns actually processed is the lesser of the two num error message (because there might not be Val ble columns) or an informational message (bee columns are ignored) to be generated.
constraint checks are included in the table definition, the tables are placed in
~ n c t i o nis called.
F I
456 ;
" "
~~
" "
! .
Part 3: Application Programming Interface Functions
1 I
If a list of work directoriesto use for sorting index keysduring the load operation is not specifiedin the WorkDirectoryListparameter, the tmp subdirectory of the sqllib diredory will be used. The typeof structure used to provide informationabout paths, devices, or shared libraries where copy images of loaded data areto be stored is determined by the value specified in the media-type field of the sqlu-medialist structure (stored in the Copyl'izrgetList parameter) as follows: SQLU_LOCAL-mDIA
One or more sqlu-media-entry structures. The sessions field of the sqlu-media-list structure should indicate the number of sqlu-media-entry structures used.
m SQLU-AD~M-~DIA No other structure is needed.
m SQLU-OTRER-~DIA One sqlu-vendor structure. The shr-lib field of the sqlu-vendor Structure should contain the shared library name of the vendor product being used. The Load utility will start each sessionwith a different sequencenumber but with the same data specified in thesqlu-vendor structure. The number of elements in the Nullhdicators array must match the number of columns in theexternal data file (i.e.,the number of elements must equal the dcolnum field of the sqldcol structure in the DataDescriptor parameter). There is a one-to-one ordered correspondence between the elements of this array and the columns being loaded from the datafile. Each elementof this array must contain either a number identifyinga column in the datafile that is to be usedas a null indicator fieldor a o to indicate that thetable column is not nullable. Ifthe element contains a number identifyinga column in the datafile, the identified column must contain either a 'Y' or an "N" (a "Y" value indicates that the table column data is NULL, and an "N" value indicates that the table column data isnot
NULL). The data field of the sqlchur structure specified in theFileFypeMod parameter can contain any of the following values:
"fastparaen
'hoheader"
bagefreeepace-X
Chapter 11: Data Handling M I S “codepage=x” “dumpfile-X Uimplieddecimai” %oeof
char”
“binarynumerics” Unullindchar=2 “packeddecimal“ “reclen=X “striptblanks” “striptnulle” “chardel2 “coldelx” “dateiso” “decplusblank” “decptX %odoubledel” “forcein” “nochecklengths”
These values provide additional information about the chosen file format.Only a portion of these values is used with a particular file format.If the FileFypeMod parameter is setto NULL or if the length field of the sqlchur structure is set to 0, default information is provided forthe file format specified. If data is being loaded fromeither a delimited ASCII (SQL-DEL) or PC/IXF (SQLLIXF) format filethe FileFypeMod parameter can specify where LOB data is stored. If this parameter is setto “lobsinfile,”LOB data is stored in separate external files; otherwise, all LOB data is assumed to be truncated to 32Kf3 and stored in thesame file. If the FileFypeMod parameter is setto “norowwarnings,” all warnings that are generated because rowsof data were rejectedare ignored. H If the FileFypeMod parameter is set t o “pagefreespaced (where x is an integer
between 0 and loo), the value specifiedfor 2 is interpreted as thepercentage of each data page that is to be leR as free storage space.
If the FileFypeMod parameter is setto “totalpagefreeepaced’(where x is an integer between 0 and 1001,the value specified forx is interpreted as the percentage of the total number of pages in the table that areto be appended to the end of the table as free storage space. For example, ifx is 20 and the table contains 100 data pages, 20 additional empty pages will be appended to the table. If a value of 100 i s specified forx, each row of data will be placedon a separate page. H If data isbeing loaded froma delimited ASCII (SQL-DEL) format file,the
Part 3: Application Programming Interface Functions RleQpeMod parameter can be set to“noeofchar”t o specify that theoptional endof-file character (OxlA) is not to be recognizedas theend-of-file character. If this option is set, theend-of-fde character is treated as a normalcharacter. M If data is being loaded froma delimited ASCII(SQL-DEL) format file,the FileQpeMod parameter can be set t o “ r e c l e n = d (where zmcx is an number no larger than 32,767) to specify that m . m characters are to be read in for eachMW.
In this case, a new-line character does not indicate the end of a row. M If data is being loaded froma delimited ASCII(SQL-DEL) format file, you canuse the RleQpeMod parameter to specify characters that override the following options: Datalink delimiters By default, the inter-field separator for a DATALINK value is a semicolon (;l. Specifying “dldel”followed by a character will cause the specified character to be used in place of a semicolon as theinter-field separator. The character specified must be different from the characters used as row, column, and character string delimiters. Specifying “nodoubledel”will cause recognition of Double character delimiters all double byte character delimiters to be suppressed. By default, columns are delimited with commas. Column delimiters Specifying “coldel”followed bya character causes the specified character to be used in place of a comma to signal the end of a column. By default, character strings are delimited with Character string delimiters double quotation marks. Specifying“chardel” followed by a character causes the specified character to be used in place of double quotation marks to enclose a character string. By default, decimal pointsare specified with Decimal point characters periods. Specifying“decpt”followed by a character causes the specified character to be used in place of a period as adecimal point character. By default, positive decimalvalues are prefixed Plus sign character with a plus sign. Specifying “decplusblank”will cause positive decimalvalues to be prefixed witha blank space instead of a plus sign. Specifying “datesiso”will cause all.date values to Date format be imported in IS0 format. M If two or more delimiters are specified, theymust be separated by blank spaces. Blank spacescannot be used as delimiters. Each delimiter character specified must be different from the delimiter characters already being used, so all delimiters can
Chapter 11:Data Handling APIs
i
459
be uniquely identified. Table 11-3 (refer to the EXPORT function) lists thecharacters that can be used as delimiter overrides. H If the FileQpeMod parameter is set to “anyorder”,the order of the source data
does not have to be preserved. Ifthis option is specified, significant performance gains can be seen on SMP systems.
m
If the FileQpeMod parameter is set to “faetparee”,less data checking is performed on user-supplied column values.This option does not affect referential integrity checking or constraints checking;instead, it reduces syntax checking to improve overall performance.
H If the FileQpeMod parameter is setto “indexfreespaced’(where x is an integer between 0 and 99), the value specified forx is interpreted as thepercentage of each
index pagethat is to be left as free storage space when loading the index.
m
If the RleQpeMod parameter is setto “noheader”,the header verification code that is written to files by the Data Declustering Tool (db2split)is ignored. This option should only be used when loading files into a table that exists on a singlenode nodegroup.
m
If the source columnin an external file has been explicitly specified,and if it does not containdata for oneor more rows,the FileQpeMod parameter can be set to “ueedefaulte”to ensure that default values are substituted. Otherwise, aNULL is substituted if the table column is n u l l a b l r r the row is not loadedif the table column is not nullable.
m
If data isbeing loaded froman ASCII (sQL-mL or SQL-ASC) format file, the FileQpeMod parameter can be set to“codepage=-” (where xxlc equals a character string) to specify the code page of the data in the external file.
m
If data isbeing loadedfrom an ASCII (SQL-DEL or SQL-ASC) format file,the FileQpeMod parameter can be set to “dumpfi1ed’(where x equals a valid file name) to specify the name of an exception filethat exception rowsof data will be written to.
m
If data isbeing loaded froman ASCII (SQL-DEL or SQLJSC) format file, the FileQpeMod parameter can be set to “implieddecimal”to specify that the location of an implied decimal pointis to be determined by the table column definition (for example, ifthe value 12,345 wereto be loadedinto a DECIMAL(8,B)column, it would be loadedas 123.45, notas 12345.00-which would otherwise bethe case).
If data is being loaded from a non-delimited ASCII (SQL-ASCI format file, the FileQpeMod parameter can be set to “binarynumerice”to specify that numeric data (other than DECIMAL) is stored and is to be loaded in binary format (not a character representation). H If data isbeing loaded from a non-delimited ASCII (SQL-ASC) format file,the FileQpeMod parameter can be set to “nullindchar=x”(where x equals a character)
to specify that a NLnL value is to be replaced with a specific character. The character specified is case-sensitive forEBCDIC data files, except whenthe character is an English character.
i 460 I
,!
i
Part 3: Application Programming Interface Functions W If data is being loaded froma non-delimited ASCII(SQL-ASC) format file,the File2)peMod parameter can be set to “packeddecimal”to specify that DECIMAL, numeric data isstored and is to be loadedin packed-decimal format(not a character representation). W If data isbeing loaded froma non-delimited ASCII(SQL-ASC) format file,the
FileQpeMod parameter can be set to “striptblanks”to specify that trailing blank spaces (afterthe last nonblank character) are to be removed (truncated) when data is imported. Ifthis option is not set, trailing blanks are kept. If data isbeing loaded froma non-delimited ASCII(SQL-ASC) format file,the FileTypeMod parameter can be set to “striptnulls”to specify that trailing NULLS (after the lastnonblank character) are to be removed (truncated) when data is imported into variable length fields. Ifthis option is not set, NULLS (Ox00 characters) are kept. W The “striptblanks”and the “striptnulls“options are mutually exclusive. If one is
specified, the other cannot be used.
W If data isbeing loaded froma PC/IXF (SQL-IXF) format file,the FilenpeMod parameter can be set to “forcein”t o tell the import utility to accept data inspite of code page mismatches-and t o suppress all translations between code pages.
m If data isbeing loaded froma PChXF’ (SQL-IXF) format file,the FiZeTypeMod
parameter can beset to “nochecklengths”to specify that checking to ensure that fixed length target fields are large enough to hold the imported data is not to be performed. T h i s option is used in conjunction with the “forcein”option.
W Data cannot be loadedinto system catalog tables. W Data is loaded in thesame sequence (order)it is stored in. Ifyou want a particular data sequence, makesure the data sorted is before it is loaded. W This functionw l inot issue a warning if you attempt to specify optionsthat arenot
supported by the file types specified in the FileType parameter. Instead, the LOAD function will fail, and an error will be generated.
W The LOAD utility builds indexesby using existing definitions. W The LOAD utility does not enforcereferential constraints, check constraints, or
update summary tables that aredependent uponthe table being loaded. Tables that have referential or check constraints are placed in the “Check Pending“state after a load operation.Summary tables that are dependent on the tables being loaded are also placed in the“Check Pending“state.
W If clustering is required, the datashould be sorted on a clustering index beforeit is loaded. W The remote filename specified in theRemoteMsgFileName parameter resides on the server workstation and is accessed exclusivelyby DB2. Therefore, it is imperative that any file name qualification givent o this file correspondt o the directory structure of the server-not the client-and that the DB2 instance has read/write permissionon this file.
[80];
,
Chapter 11: Data Handling APIs
i
I
,
j
i.- 461 I I
m WOdifferent LOAD operations that use the same fully qualified remote message file name cannotrun at the same time. Authorization Only users with either System Administrator (SYSADM) authority or Database
Administrator (DBADM) authority can executethis function call. See Also
IMPORT, EXPORT, LOAD QUERY,QUIESCE TABLESPACES FOR TABLE
Example
Thefollowing C++ program illustrates how to use the the DEPARTMENT table ofthe SAMPLE database:
/* /* /* /*
/* /*
/* /*
LO^
function to load data into
*/ CHllEX3 .SQC NAME: PURPOSE: Illustrate How To Use The Following DB2 API Functions In A C++ Program: LOAD TABLE TABLESPACES FOR QUIESCE
/ / Include The Appropriate Header Files #include <windows.h> #include #include <sqlenv.h> #include <sqlutil.h> #include <eql.h>
/ / Define The API-Class Class class API-Class
c / / Attributes public: struct eqlca sqlca; / / Operations public : long LoaaData () :
1; / / Define The LoadDataO Member Function long API-C1ass::LoadDataO
c / / Declare The LocalMemory Variables char char TempFileName[80] char etruct sqlu-media-list DataFiles; struct sqlu-location-entry Location-Entry; *Actionstring: sqlchar struct DataDescriptor; sqldcol struct sqluload-in struct InputInfo; sqluload-out structOutputInfo;
;
*/ */ */ */ */ */ */
p I
462
Part 3 Application Programming Interface Functions / / Initialize The Local Variables strcpy(MsgFi1eName. T:\\LOAD~MSG.DATw); strcpy(TempFi1eName. "C:\\TEMP"); DataDescriptor.dcolmeth = SQL-BETH-D;
/ / Initialize The LoadInput Structure 1nputInfo.eizeOfStruct = SQLULOAD-IN-SIZE; 1nputInfo.eavecnt I 0; 1nputInfo.restartcnt = 0; Input Inf 0 . rowcnt = 0 ; 1nputInfo.warningcnt = 20; 1nputInfo.data-buffer-size = 0; 1nputInfo.sort-buffer-size = 0; 1nputInfo.hold-quiesce = FALSE; 1nputInfo.reetartphase = SQLU-LOAD-PHASE; 1nputInfo.stateopt = SQL-STATS-ALL; 1ngutInfo.cpugarallelism P 5; 1nputInfo.diskgarallelism = 5; 1nputInfo.non-recoverable = SQLU-RECOVERABLE-LOAD; / / Initialize The Load Output Structure OutputInfo.sizeOfStruct = SQLULOAD-OUT-SIZE; / / Define The Action / / Data Is Loaded
String That Will Be Used To Control How
strcpy(String, "REPLACE INTO DEPARTMENT") ; Actionstring = (struct splchar * ) malloc (strlen(String) + sizeof(struct splchar)); Actionstring->length etrlen(String); strncpy(Acti0nString->data, String, strlen(5tring)); 6
/ / Initialize The Media List Information Data Structure DataFilea-mediptype = SQLlJ-SERVER-LOCATION; DataFiles.sessions = l; strcpy(Location-Entry.location-entry, 8T://DEPT.IXF'r); DataFiles.target.1ocation = &Location-Entry; / / Restrict Access To The Table Spaces That Are Associated With / / The DEPARTMENT Table (Quieece The Table Spaces) spluvqdp ("DEPARTMENT",SQLU-QUIESCEMODE-EXCLUSIVE, NULL, &sqlca);
/ / If The Table Spaces Were Quiesced, Display A Message if (splca.eplcode == SQL-RC-OK) I cout << "Table spaces for the DEPARTMENT table have been "I cout << "quieeced." << endl << endl;
1
/ / Load Data Into The DEPARTMENT Table From An IXF Format / / (This File was Created By The EXPORT Example)
Pile
sqluload(&DataFiles, NULL, LDataDescriptor, Actionstring, SQL-IXF, NULL, MsgFileName, TempPileName, SQLU-INITIAL, hInputInfo, &OutputInfo, NULL, NULL, NULL, NULL, brsqlca);
.
I
Chapter 11: Data Handling M I S / / If The Data Was Loaded Successfully, / / Message if (sqlca.sqlcode == SQL-RC-OK)
463 I
Display A SUCCeSS
I cout << OutputInfo.rowsLoaded << ** cout << ttrowsof data were loaded into the DEPARTMENT cout << "table from the << endl; cout 'Vile C:/DEPT.I~~." << endl << endl;
";
1 / / Remove The Access RestrictionThat Was Placed On The Table / / Spaces That Are Associated With The DEPARTMENT Table Sqluvqdp ("DEPARTMENT", SQLU-QUIESCEMODE-RESET, NULL, brsqlca) ; / / I€ The Quiesced Table Spaces Were Released, Display A Message if (sqlca.sqlcode == SQL-RC-OK)
tout << "Table spaces for the DEPARTMENT cout << '*released." << endl << endl;
table have been ";
1 / / Free
All AllocatedMemory
if (Actionstring != NULL) free(Acti0nString); / / Return The SQLCA Return return(sqlca.sq1code);
Code To The Calling
Function
1
/* /*
*/ */
The Main Function
int main() {
/ / Declare The LocalMemory Variables = SQL-RC-OK; rc long struct sqlca sqlca; / / Create An Instance Of The API-Class Class API-ClassExample; / / Connect To The SAMPLE Database EXEC SQL CONNECT TO SAMPLE USER userID
USING
/ / Load Data StoredIn An External File / / Table (In The SAMPLE Database)
rc = Example.LoadData0; / / Issue A Rollback To Free All Locks EXEC SQL ROLLBACK; / / Disconnect From The SAMPLE Database EXEC SQL DISCONNECT CURRENT;
password;
Into The DEPARTMENT
Part 3: Application Programming Interface Functions / / Return To The Operating return(rc) ;
System
1
m m LOAD QUERY purpose
The LOAD QUERY function is used to query a DB2 Database Managerinstance for the current statusof a Load operation.
syntax
SQL-API-RC
Parameters
LocalMsgFileName
SQLAPI-FN
RemoteMsgFileName
SQLCA
aqluqry (char *LocalM.gFileName, char *RemoteMsgFileName, etruct eqlca *SQLCA);
A pointer to a location in memory where the name of the local filethat all load status messages are to be written t o is stored. A pointer to a location in memory where the name of the remote message filethat all load error, warning, and informational messagesare written to is stored. A pointer to a location in memory where a SQL Communications Area(SQLCA)data structurevariable is stored. This variable returns either status information (if the function executed successfully)or error information (if the function failed)to the calling application.
Includes
#include <eqlutil.h>
Description
The LOAD QWRY function is used to query a DB2 Database Manager instance for the current statusof a load operation.This function retrieves the statusof a Load operation from the remote message filethat is created and used by the Load operation that is currently in progress, and places the resultsin the file specified by the LocalMsgFileName parameter.
Comments
M The remote file name specified must be the same as the file name specified in the
RemoteMsgFi1eIVam.eparameter of the LOAD function call.
Connection This function canonly be called if a connection to a DB2 Database Manager instance Requirement# exists. Authorization No authorization is required to execute this function call. See Also
LOAD
Example
The following C++ program illustrates how the the statusof a Load operation:
LOAD QUERY
function is used to obtain
k
F I
I I !
I
i
Chapter 11:Data Handling APIs /* /* NAME:
/* /* /*
CHllEX4.SQC PURPOSE: Illustrate How To Use The Pollopding DB2 API Function In A C++ Program:
/* /*
LOAD Q W R Y
/ / Include The Appropriate Header Piles #include <windowe.h> #include #include <sqlutil.h> #include <sql.h> / / Define The API-Class Class class API-Class {
/ / Attributes public : struct sqlca sqlca; / / Operations public : long GetLoadStatusO;
1; / / Define The GetLoadStatue() Member Function long API-Class::GetLoadStatue() {
/ / Declare The LocalM e m o r y Variables ; charMsgFileName[EOl char StatsFileName [EO];
/ / Initialize The Local Variables strcpy(MsgPileName, "C:\\TEMPw); strcpy(StatsFileName, *T:\\L-STATS.DAT"); / / Query The StatusOf The Current Load Process sqluqry(StateFileName, MsgFileName, brsqlca); / / If Load / / Message
Status Information Was Obtained, Display A Success
if (sqlca.sqlcode
P=
SQL-RC-OK)
{
1
1
tout '"The status of the current load process has been cout << a8collectedand placed in'# << end11 cout << #'the file C:\\L-STATS.DAT.n endl;
/ / Return The SQLCA Return return(eqlca.eqlcode);
Code To The
Calling
Function
*/ */ */ */ */ */ */
Part 3: Application Programming Interface Functions /* /*
*/ */ */
The Main m c t i o n
/* int main0
c
/ / Declare The Local Memory Variables rc long I SQL-RC-OK; atruct splca splca;
/ / Create An Instance Of The -1-Class API-ClassExample;
Class
/ / Connect TO The SAMPLE Database EXEC SQL CONNECTTO SAMPLE USER userID
AboutThe Status Of A Example.QetLoadStatus();
/ / Qet Information
rc
/ / ISSUB A Rollback EXEC SQL ROLLBACK;
TO
Free
/ / Disconnect FromThe SAMPLE EXEC SQL DISCONNECTCURRENT;
/ / .Return TO The Operating return( rc ) ;
All
USING Load
password; Operation
Locks
Databaae
System
1
IBM M4 QUIESCE TABLESPACES FOR TAB= Purpose
The QVIESCE TABLESPACES FOR TABLE fundion is used to place all table spaces that are associated with a particular database table in a quiesced (restricted access) state.
Syntax
SQL-API-RC SQL-API-FN
Splumdp
(char long void
*TableName,
QuiesceMde,
*Reserved, struct eqlca *SPLCA);
Parameters
TabZeName
A pointer to a location in memory where the name of the table, as it is defined in the system catalog,is stored.
QuiesceMode
Specifies the quiesce mode to be used. “his parameter must be set to one of the following values: SQLU-QUIESCEMODE-SHARE
The Tablespace(s)are to be placed in the “Quiesced Share” state. SQLU-QVIESCEMODE-INTENT-VPDATE
Table space(s)are to be placedin the UQuiesceIntent to Update” state.
Chapter 11: Data Handling APIs SQLU-QUIESCEMODE-EXCLUSIVE
Table space(s)are to be placed in the“Quiesce Exclusive”state. SQLU-QUIESCEMODE-RESET
Table space(s)are to be returned to their normal state if the caller owns the quiesce-or if the caller who originally set the quiesce disconnects. SQLU-QUIESCEMODE_RESET-~D
Table space(s)are to be returned to their normal state if the caller owns the quiesce. Reserved
A pointer that is currently reservedfor later use. For now, this parameter must always be set to Nuu.
SQLCA
A pointer to a location in memory where a SQLCommunications Area (SQLCA)data structurevariable is stored. This variable returns either statusinformation (ifthe function executed successfully) or error information (if the function failed)to the calling application.
Includes
#include <eqlutil.h>
Description
The QUIESCE TABLESPACES FOR TABLE function is used to place all table spaces that are associated with a particular database table in a quiesced (restricted access) state. When this function is executed, only transactions that areholding the table space in a quiesced state aregranted access to the table space. All other transactions are ”locked out” of the table space until it is returned to its normal state. Table spaces can be placed oneof the following quiescestates: “Quiesced Share” “Quiesced Update” “Quiesced Exclusive” These states determine how other transactions that currently hold a quiesce state on the table space or that attempt to set a quiesce state for the table space can access the table space.
Comments
The table name specified in the!hbleName parameter can be a two-part name with the schema and table name separated by a period. If the schema is not provided, the authorization ID that was used to establish the database connection will be used as the default schema.
W The table name specified in the !hbleNam parameter cannot be a system catalog table.
W When the SQLU-QUIESCEMODE-SHARE value is specified in the Quiesc&& parameter, the transaction requests a Share lock forthe specified table and Intent Share locks for all associated table spaces. Whenthe transaction obtains the loch,
Part 3 Application Programming Interface Functions the state of the table spaces is changed to “Quiesced Share.”This state isonly granted to the application that quiesced the table space (the quiescer) if there is no conflicting state held by other applications. Thestate of the table spaces is recorded in thetable space table, along with the authorization ID and the database agent ID of the quiescer, so the state ispersistent. The table specified cannot be changed whilethe table spaces forthat table are in the “Quiesced Share” state. However, other share mode requests to the table and table spaces are allowed. Whenthe transaction is committed or rolled back,the locks are released, but thetable spaces forthe table remain in the“QuiescedShare” state until the state is explicitly reset (by another call to this function). When the SQLU-QUIESCEM~DE-EXCLUSI~ value is specified in the QuiesceMocle parameter, the transaction requests a Super-Exclusive lock forthe table specified and Super-Exclusive locks for all associated table spaces. Whenthe transaction obtains the locks, the stateof the table spaces changesto “Quiesced Exclusive,” and the stateof the table spaces, along withthe authorization ID and the database agent ID of the quiescer, are recorded in the table space table. Sincethe table spaces are held in super-exclusive mode,no other access to the table spaces is allowed. Thetransaction that invokes this function, however,has exclusive access to the table and the table spaces. When the SQLU-QUIESCEMODE-I~ENT_~~PDATEvalue is specified in the QuiesceMode parameter, the transaction requests an Update lock for the table specified and Intent Exclusive locks forall associated table spaces. Whenthe transaction obtains the locks, the state of the table spaces changesto the “Quiesced Update”and the state of the table spaces, alongwith the authorization ID and the database agent ID of the quiescer, are recorded in the table space table. Becausethe table spaces are held in exclusive mode,no other access to the table spaces is allowed. The transaction that invokes this function, however, has exclusive accessto the table and the table spaces. M There is a limit of five quiescerson a table space at any given time. Becausethe “Quiesced Exclusive”state isincompatible with any other state, and a “Quiesced Update” state isincompatiblewith another “Quiesced Update”state, thefivequiescer limit, if reached, must consist of at least four “Quiesced Share” states and, at most, one “Quiesced Update” or one “Quiesced Exclusive” state. A quiescer can upgrade the stateof a table space from aless restrictive state t o a more restrictive one (for example, SHAREto UPDATE or UPDATE to EXCLUSIVE). Ifa user requests a state lower than one that is already held, the original state will be returned. Quiesce states cannot be downgraded. Once changed, you must explicitly reset thequiesced state of a table space by executing this function with the SQLU-QIJIESCEMODE-RESET value specified in the QuiesceMode parameter. M In a multi-node environment,this function acts locally on a single node; i.e.,it only quiesces that portion of one or more table spaces that belong to the node that this
Chapter 11:Data Handling APIs function is called from.
Connection This function can only be called if a connection to a database exists. Requirements Authorization Only users with System Administrator(SYSADM) authority7System Control (SYSCTRL) authority, System Maintenance(SYSMAINT) authority, or Database Administrator (DBADM) authority can executethis function call. See Also
LOAD
Example
See the exampleprovidedfor the LOAD function on page 461.
This Page Intentionally Left Blank
Part 3 Application Programming Interface Functions
F 4 lAllllB Nodegroups And Data Partitioning As mentioned earlier,the DB2 Database Manager controls what can be done to data in a
-
database and manages any system resources that have been assignedto it. DB2 Universal Database 5.0 and later enables the Database Managerto operate in a parallel, multinode (workstation) environment by allowing a database to be broken into several different partitions. Adatabase partitionis a part of a single database that contains its own indexes, configuration files, and transaction log files. You can deiinea named subset of one or more database partitions; each named subset is referred to as a nodegroup, and each nodegroup that contains more than one database partition is known as a multi-partition nodegroup. However, each database partition defined in a multi-partition nodegroup must belong to the same DB2 Database .Manager instance. Each nodegroupis associated withapartitioning n a p , which is an array of 4096 partition numbers. The partitioning index that isautomatically createdfor each row of a partitioned table is used as an index into the partitioning map. This index is used to determine which partition a particular row of data is stored on. The GET TABLE PARTITIONING INFORMATION and GET ROW PARTITIONING NUMBER functions can be used to view partitioning map and index information. The REDISTRIBUTE NODEGROUP function can be used to rearrange thecontents of a partitioning madindex. A single-partition database is adatabase that has only one partition; all of the database's data isstored in that partition. In this case, a nodegroup is present; however, the nodegroup does not provide any additional capability. Apartitioned databaseis a database that has been dividedinto two or more partitions. Data (i.e. tables) in apartitioned database can reside in one, several, or all available partitions. When a table is in a multi-partition nodegroup, someof its rows are stored in one partition, and the restof its rows are stored in other partitions. Usually, a single database partition exists on each physical node(workstation)in a multi-node system, and the processors located at each node are used by the Database Manager to manage that partition's part of the database's data. This process allowsan application to utilize the power of multiple processors to satisfy large data manipulation requests.Data retrieval and update requests are divided into sub-requeststhat are executed in parallel on the applicable partitions. The fact that the database is split across multiple partitions is transparent to users. That's because user interaction is always performed througha single partition, which is known as thecoordinator node. The coordinatorr u n s on the same database partition as theapplication, or in thecase of a remote application,the partition to which the application is connected. Any database partition can be used as acoordinator node.
lrmwnl W! Types Of Parallelism There are different ways that a task can be performed in parallel. Three factors-the nature of the task, thedatabase configuration, and the hardware environment-determine how DB2will perform a task in parallel. Using these factors, DB2 can initiate one of the following types of parallelism:
Chapter 12: DB2 Database Partition Management Functions U 0 parallelism W Query parallelism
I/O Parallelism For situations in which multiple storage containers exist for a single table space, the DB2 Database Manager can initiate 110 parallelism. I/O parallelism refers to the process of reading from or writing t o two or more inputloutput WO) devices at the same time. I/O parallelism can cause significant improvements to I/O throughput.
Query Parallelism Query parallelism controls how database operations are performed. DB2 Universal Database supports two types of query parallelism: inter-query parallelism and intraquery parallelism. Inter-query parallelism refers t o the ability to allow multiple applications to query adatabase at the same time. Withthis type of query parallelism, each application’s query will execute independentlyof the others, but all queries will be executed at the same time. Intra-query parallelism refers to the ability to break large database operations such as index creation,loads, and complex SQLqueries into multiple parts that are then executed simultaneously, using either intra-partition parallelism, inter-partition parallelism, or both.
INTRA-PARTITIONPAR.ALLELISM With intra-partition parallelism, database operations are subdivided into multiple parts which are then executed in parallel within a single database partition. Figure12-1 shows how a large SQL query might be executed faster using intra-partition parallelism. In this example,the query is broken into three park-which are then executed at the same time in the same partition. All four parts areessentially acopy of each other. Whether or not:intra-partition parallelism will be utilized is determined by the database configuration file. The degree of parallelism specified controls the number of parts that a query canbe broken into for executing.
INTERPARTWION PROCESSING With inter-partition parallelism, database operations are subdivided into multiple parts, which are thenexecuted in parallel a m s s one or more partitions of a partitioned database (which may reside on one machine or on multiple machines). Figure 12-2 shows how a large SQL query might be executed faster using inter-partition parallelism. In this example, the query is broken into three parts, which are then executed at the same time across multiplepartitions. With inter-partition parallelism, the degree of parallelism usedis largely determined by the number of partitions created and by the way nodegroups have been defined.
Part 3: Application Programming Interface Functions "SELECT
... FROM ...
tt
DATABASE
SINGLE DATABASE PARTITION Figure 12-1
Intra-PartitionParallelism.
"SELECT
... FROM ...
tt
i DATABASE
DATABASE PARTITION
Figure 12-2
Inter-PartitionParallelism.
Chapter 12: DB2 Database Partition Management Functions
USING BOTH INTRA-PARTITIONPARALLELISM AND INTER-PARTITIONPARALIBLISM Intra-partition parallelism and inter-partition parallelism are not mutally exclusive. Both can be used at the same time. This characteristic, in effect, provides two dimensions of parallelism.When used together,an even moredramatic increase in the speed at which database operations are performed can be achieved.
Enabling Query Parallelism In order to take advantage of parallelism within a database partition or within a nonpartitioned database, you must modify the parameters in the DB2 Database Manager configuration file(and in some cases the parameters in one or more database configuration files). For example,the configuration file parameters that affect intra-partition parallelism include the DB2 Database Manager configuration file parameters max-querydegree and intraqarallel and thedatabase configuration file parameter dft-degree. Refer to the GET DATABASE MANAGER CONFIOURATIONfunction and the GET DATABASE CONFIOURATIONfunction in Chapter 9 for more informationabout configuration fileparameters.
Enabling Data Partitioning Before creating a partitioned database, you must decide whetheryour workstation will be a local or a remote client to the DB2 Database Manager instance where the database will be created. Then, you must decide which partition will serve as the catalog node for the database.The workstation on which you execute the CREATE DATABASEcommand or function will becomethe catalog node forthat particular database (thecatalog nodeis the partition on which all system catalogtables are stored).All accessto the system tables must go through this partition. When you executethe CREATE DATABASEcommand or function, the new database is automatically created across all database partitions that aredefined in the db2nodes.cfg configuration file.In addition, the following three nodegroups are defined IBMCATGROUP (forthe SYSCATSPACE table space, to hold all system tables) M IBMTEMPGROUP (forthe TEMPSPACE1 table space, to hold all temporary tables
that arecreated during database processing) W IBMDEFAULTGROUP (for the USERSPACE1 table space, to hold user-defined
tables and indexes) Once the database has been created, parameters in both the DB2 Database Manager configuration fileand in the new database’s configuration file have to be modified in order to take advantage of data partitioning. Specifically, the conn-elapse, fcm-num-anchors, fcm-num-buffers, fcm-num-connect, fcm-num-rqb, max-connretries,mm-coordagents, mm-timediff,numqoolagents, and stop-start-time DB2 Database Manager configuration parameters s e c t database partitioning. Refer to the
-
l
476 i
,
,
Part 3: Application Programming Interface Functions
L . "
GET DATABASE WAGER CONFIGURATIONfunction and the GET DATABASE CONFIGURAabout configuration fileparameters. TION function in Chapter 9 for more information
Im The DB2 Database Partition
Management Functions
Table 12-1 lists theDB2 API functions that areused to manage nodegroupsand database partitions. Each of these functions is described in detail in the remainder of this chapter.
Table 12-1
DB2DatabasePartitionManagementFunctions
Addsnode a new
ADD NODE
DROP
NODE
CREATE DROP
Identifies whether or not a specific nodeis currently being used by a database.
VERIFY
Creates a databaseat a specific nodein a parallel database system.
DATABASEAT NODE
DATABASE
AT
Removes (drops)a database from a specific nodein a parallel database system.
NODE
Sets the run-time degree of intra-partition parallelismthat is to be used to process SQL statements.
SET RUNTIME DEGREE BET
TABLE
to a parallel database system.
PARTITIONINB
GET ROW PARTITIONING
REDISTRIBUTENODEGROUP
INFORMATIONObtains the partitioninginformation for a database table.
NUMBER
Obtains the partitionnumber andnode number at which a specific rowo f data in a tableis stored (in a parallel database system). Redistributes data across the nodes in a nodegroup.
Chapter 12: DB2 Database Partition Management Functions
ADD NODE Purpose
The ADD
syntax
SQL-API-RC
Parameters
NodeOptionsSize
NODE function is used
Nodeoptions
SQLCA
SQL-API-FN
to add a new node to a parallel database system.
sqleaddn (unsigned short NodeOptionsSiee, void *NodeOptions, struct sqlca *SQLCAJ:
The length, in bytes, of the sqle-addn-options structure stored in the Nodeoptions parameter. A pointer to a location in memorywhere an sqle-addn-options structure that contains information about the node to be added is stored. A pointer to a location in memorywhere a SQL Communications Area (SQLCA) data structurevariable is stored. This structure returns .either status information (ifthe function executed successfully) or error information (ifthe function failed)to the calling application.
Includes
#include <sqlenv.h>
Description
The ADD NODE function is used t o add a new node to a parallel database system. When this function is called, database partitions are automatically created (on the new node) for eachdatabase that is currently defined in the MPP server instance, and the configuration parameters for each newdatabase partition are setto the system default values. However, these partitions cannot be usedto store user data until the ALTER NODEQROUPSQL statement has been used to add the new node to an existing nodegroup. This function uses a special structure, the sqle-acldn-options structure, to specify information about the node (ifany) in which the temporary table space definitionsfor all database partitions to be created is stored. "he sqle-addn-options structure is defined in sqlenv.h as follows:
struct sqle-addn-options {
char sqladdid
unsigned long tblspace-type;
t 8I ;
/* An
*'eye catcher" value that is used */ / " to identify the structure.This field*/ */ /* W S t be Set to SQLE_ADWPTID-V51. /* Indicates that temporary table */ /* spaces should be the same as those */ at the specified node */ /* found /* (SQLE-TABLESPACES-LIKE-NODE), the */ /* same as those found at the catalog */ each */ /* node ofdatabase /* (SQLE-TABLESPACES-LIKE_CATALOG), */ */ /* or not created at all /* (SQLE-TABLESPACES-NONE). */
Part 3: Application Programming Interface Functions SQL-PDB-NODE-TYPEtblspace-node;
/* /* /* /* /* /* /*
Specifies the node number that */ tablespacedefinitionsshouldbe */ obtained from (provided the */ tblspace-type field is set */ to SQLE-TmLESPACES-LIKE-NODE). */ Note: The node number specified must */ exist in thefile ab2nOaes.cfg. */
B This function must be called from the node that is to be
Comments
added, and it can only beissued against an MPP server. B Before a new node can beadded, sufficientdisk space must exist for eachstorage
container that will be created (for each existingdatabase) on the system. B If an add node operationfails while creating a database partition locally, a cleanup phaseis initiated,and all database partitions that have already been created are dropped (i.e.database partitions are removed from the node being added-the local node). Ifthe clean-up phase is initiated,existing database partitions on other nodes are not affected. W If this function is called whilea database creation (CREATE DATABASE)or a database deletion (DROP DATABASE) operation is in progress, an error will be returned. W If temporary table spaces are to be created withinthe database partitions that are
automatically created whenthis function is called, this function may communicate with another node in the MPP system to retieve existing table space definitions. In this case, the start-stoptime DB2 Database Manager configuration file parameter is used to specify the time, in minutes, in which the other node must respond. If this time is exceeded, an error will be returned.
Connection Database Manager Requirements first.
This function canbe called at any time; a connection to a DB2
instance or to a DB2 database does not haveto be established
Authorization
Only users with either System Administrator(SYSADM) authority or System Control(SYSCTRLJ authority are allowed to execute this function call.
See Also
DROP
Example
The followingC++ program illustrates how to use the ADD NODE function to add a new node to an MPP system:
CH12EXl.CPP
NODEVERIFY
/*
/* /* /* /*
NAME: PURPOSE: Illustrate How To Use The Following DB2 API Function In A C++ Program:
*/ */ */ */ */
Chapter 12: DB2 Database Partition Management Functions /* /*
*/
ADD NODE
*/
/ / Include The Appropriate Header Files #include <windows.h> #include #include <sqlenv.h> #include <eqlca.h,
/ / Define The API-Class Class claee API-Class i / / Attributes public: struct sqlca eqlca; / / operations public : long AddNode ();
1; / / Define The AddNodeO Member Function long API-Class::AddNodeO i / / Declare The LocalMemory Variables struct eqle-addn-options Nodeoptions;
/ / Initialize
TheAdd Node option8 Structure etrcpy(Nodeoptions.spladdid, SQLE-ADDOPTID-V51); NodeOptione.tb1space-type = SQLE-TABLESPACES-NONE; NodeOptions.tblepace-node = 0; / / Add The New Node sqleaddP(&NodeOptione, hsqlca); / / If The New Node Has Been Added, Display A Succeee if (sqlca.sqlcode == SQL-RC-OK) cout << "The new node has beenadded." << endl; / / Return The SQLCA Return return(sqlca.eqlcode);
Code To The
Calling
Message
Function
> I
/*
*/
The Main Function
/*
*/
int main() {
/ / Declare The LocalMemory Variables long rc SQL-RC-OK; P
/ / Create An Instance API-ClaseExample;
Of
The API-Class Class
Part 3: Application Programming Interface Functions / / Add A New Node
rc
E
TO A
Parallel
Database
system
Example.AadNode ( ) j
/ / Return To The Operating System return(rc) ;
m m DROP NODE VERIFY Purpose
The DROP NODE VERIFY function is used to identify whether or not a specific nodein a parallel database system is currently being usedby a database.
syntax
SQL_API-RC SQL-I-FN
Parameters
Action
void
Action, *Reserved,
struct eqlca
*SQLCA);
sqlearpn (unsigned short
Specifies the action that this function is to perform. This parameter must be set to the following value: SQL-DROPNODE-VERIFY
Reserved
A pointer that, at this time, is reserved for later use. For now, this parameter must always be set to Nuu.
SQLCA
A pointer to a location in memorywhere a SQLCommunications Area (SQLCA) data structurevariable is stored. This structure returns either status information (if the function executed successfully) or error information (if the function failed)to the calling application.
Includes
#include aq1env.b
Description
The DROP NODE VERIFY function is used to identify whether or not a specific nodein a parallel database system is currently being used by a database. If this function indicates that a node is not being usedby one or more databases, the STOP DATAEASE MANAQER command or function can be used to remove the node fromthe database system (by removingits correspondingentry in the db2nodes.cfg file). However, ifthis function indicates that a node is being usedby one or more databases, the following steps must be performed beforethe node can be removed fromthe database system: 1. If the node contains data, call the REDISTRIBUTE NODEGROUP function to move the data to other nodes within the database system. 2. Call the xumsmIBmE NODEGROUP function or execute the mTER NODEGROUP SQL statement to remove the node fromany node groupsthat thenode has been assigned to.Note that this step mustbe done for each database that has thenode defined in a node group. 3. Delete (drop)any event monitorsthat have been defined for the node.
Chapter 12: DB2 Database Partition Management Functions 4. Call the DROP NODE VERIFY function again to ensure that thenode is no longer being usedby one or more databases. 5. Call the STOP DATABASE MANAGER function to remove the node from the database
system. "his function must be called from the node that is to be verifiedremoved fromthe
Comments
database system, and the function can only be issued against an MPP server.
Connection This function can be called at any time; a connection to a DB2 Database Manager Requirements instance or to a DB2 database does not have to be established first. Authorization Only users with either System Administrator (SYSADM) authority or System Control (SYSCTRL) authority are allowed to execute this function call.
see Also
ADD NODE, STOP DATABASE MANAGER, REDISTRIBUTE NODEGROUP
Example
The following C++ program illustrates how to use the DROP NODE VERIFY function to determine whether or not specific nodein a parallel database system is currently being usedby a database:
CH12EX2.CPP
VERIFY
/* /* NAME: /* PURPOSE: /* /* NODE /*
Illustrate How To Use The Following DB2 API Function In A C++ Program: DROP
/"
/* / / Include The Appropriate #include <windows.h, #include #include <eqlenv.h> #include <sqlca.h>
Header
Files
/ / Define The API-Class Class class API-Class {
/ / Attributes public: struct sqlca sqlca;
1;
/ / Operations public : long CheclrNodeO;
/ / Define The CheclrNodeO Member Function long API-Class::CheckNoBe()
c
/ / Declare The Local Memory Variables char Message[l0241;
*/ */ */ */ */ */ */ */
Part 3: Application Programming Interface Functions / / Determine
WhetherOr Not The Current Node Ie Being Used By / / A Database sqledrpn(SQL-DROPNODE-VERIFY, NmtL, hep1Ca); / / Display The Meeeage Returned eqlaintp(Message, 1024, 7 0 . breqlca); cout << Meseage << endl;
/ / Return The SQLCA Return return(eqlca.sqlc&e);
Code To The Calling
Function
3
/* /* /*
*/ */ */
The Main Function
int main()
I / / Declare The Local M e m o r y Variables long rc = SQL-RC-OK;
/ / Create An Instance O f The -1-Claee API-ClassExample; / / D e t e d n e Whether Or Not The / / Database rc = Example.CheckNode( ) ;
/ / Return To The return(rc);
Operating
Class
Current
Node
Ie
Being
Used By A
System
1
CREATE DATABASE AT NODE Purpose
The CREATE DATABASE AT NODE function is used to create a database at a specific node in a parallel database system.
syntax
SQL-1-RC SQL-API-FN
eqlecran (char
void
struct sqlca
Parametem
DBName Reserved SQLCA
*DBName,
*Reserved,
*SQLCA)r
A pointer to location in memory where the name of the database to create is stored. A pointer that, at this time, is reserved forlater use. For now, this parameter must always be set to NULL. A pointer to a location in memory wherea SQL Communications Area (SQLCA)data structurevariable is stored. "his structure returns either statusinformation (ifthe function executed successfully) or error information (ifthe function failed)to the calling application.
Chapter 12: DB2 Database Partition Management Functions Includes
#include <eqlenv.h>
Description
The CREATE DATABASE AT NODE function is used to create a database at a specific node in a parallel database system. This function should only be used to recreate a database partition (at a node) that has been damaged and is unusable.
\%
'1
NOTE: Improper use of this function can cause inconsistencies in a database system. Therefore, this functionshould be usedwith extreme caution.
Comments
H This function must be called from the node that the database is to be created on and it can only be issued against an MPP server. W When a database is created at a specific node,the database is placed in the
"Restore Pending"state and must be restored beforeit can be used.
Connection This function can only be called when a connection to a DB2 Database Manager instance Requirements exists. To create a database at another node, an attachmentto that node must first be established. A database connection is temporarily establishedby this function forthe duration of the call. Authorization Only users with either System Administrator(SYSADM) authority or System Control (SYSCTRL)authority are allowed to execute this function call. See Also
DROPDATABASE
Example
Thefollowing C++program illustrates how to use the CREATE DATABASE AT NODE function to recreate a database at a specific nodein a parallel database system:
/* /* /*
/*
AT NODE
*/ CH12EX3.CPP NAME: PURPOSE: Illustrate How TO Wee The Following DB2 API Function In A C++ Program:
*/
*/
/*
/*
*/ */
DATABASE CREATE
AT NODE
/* / / Include The Appropriate Header Filee #include <windows.h> #include #include <eqlenv.h> #include aq1ca.b
/ / Define The API-Claee Claee claee API-Clam
c / / Attributes public: etruct eqlca eqlcat
*/ */
Part 3: Application Programming InterfaceFunctions / / Operations public : long CreateDBAtNodeO;
1; / / Define The CreateDBAtNdeO Member Function long API-Class::CreateDBAtNode() {
/ / Declare The Local Memory Variables char Instance [ g ] ; / / Obtain
The Current Value Of The / / Variable sqlegins(Inetance, &sqlca); 0; Instancet81
DBSINSTANCE
Environment
-
/ / Attach To The Current DB2 Database Manager Instance sqleatin(Instance, "userid##, 8fpassword8t, &sqlca) ; / / Create TheTEST Database At The sqlecran(18TESTm,NULL, &sqlca); / / If The TEST / / Message
Current
Node
Database Has Been Created, Display A Success
if (sqlca.sqlcode
=I
SQL-RC-OK)
{
tout << "The TEST databasehas been created cout << Uat this node." (< endl;
1 / / Detach From The Current DB2 Database Manager Instance sqledtin(hsq1ca); / / Return The SQLCA Return return(sqlca.sqlcode);
Code To The
Calling
Function
1
Main
/* /*
*/ */
The
int main0 {
/ / Declare The LocalM e m o r y Variables long rc m SQL-RC-OK; / / Create An Instance Of The API-Clase Class API-ClassExample; / / Create TheTEST Database At The Current rc = Example.CreateDBAtNode ( ) ; / / Return TO The return )(rc ;
1
Operating
system
Node
Chapter 12: DB2 Database Partition Management Functions
m m DROP DATABASE AT NODE The DROP DATABASE AT NODE function is used to remove (drop)a database from a specific nodein a parallel database system.
Purpose syntax
Parameters
DBAlias
A pointertolocation in memorywhere the alias of the database to be removed (dropped)is stored.
Reserved
A pointer that, at this time, is reserved for later use. For now, this parameter must always beset to NULL.
SQLCA
A pointer to a location in memorywhere a SQLCommunications Area (SQLCA) data structure variable is stored. This structure returns either status information (ifthe function executed successfully) or error information (ifthe function failed)to the calling application.
Includes
#include <eqlenv.h*
Description
The DROP DATABASE AT NODE function is used to remove (drop) a database from a specific nodein a parallel database system. This function is used by utilities that are supplied withDB2 Universal Database ExtendedEnterprise Edition and is not intended for general use.
NOTE: Improper use of this function cancause inconsistencies in a database system. Therefore, this functionshould be used with extreme caution.
Comments
W This function must be called from the node that the database is to be dropped from, and it can only be issuedagainst an MPP server.
Connection This function can be called at any time; a connection to a DB2 Database Manager Requirements instance or to a DB2 database does not have to be establishedfirst. An attachment to a DB2 Database Manager instance is implicitly established forthe duration of the c a l l . Authorization Only users with either System Administrator(SYSADM)authority or System Control (SYSCTRL) authority are allowed to executethis function call. See Also
CREATEDATABASEATNODE
Example
Thefollowing C++ program illustrates how to use the DROP DATABASE AT NODE function to remove a database from a specific nodein a parallel database system:
I
i
I 486 !-
.
.
I
:
c
Part 3 Application Programming Interface Functions
!
"
/*
/*
/* /* /*
CH12EXI.CPP PURPOSE: Illustrate How To Wee The Following DB2 API Function In A C++ Program:
Nrn:
/*
DATABASE
DROP
AT NODE
/*
*/ */ */ */ */ */ */
/ / Include Thempropriate Header Pilea #include <windows.h> #include #include <sqlenv.h> #include <sqlca.h> / / Define The API-Clam Claee class API-Claes
I / / Attribute0 public: etruct eqlca eqlca;
1;
/ / Operatione public : long DropDBAtNode () ;
/ / Define The DropDBAtNde( Member Function long API-C1ase::DropDBAtNodeO
i
/ / Drop The TEST Databaee At The Current Node sqledpan("TEST8', NULL, heqlca); / / If The TEST / / Meeeage
Databaee
Rae
Been Dropped, Display A
8ucceee
if (0gka.0qkOde e= SQL-RC-OK) i cout << "The TEST databaee hae been dropped "; cout << "at thie node." << endl; 1
1
/ / Return The SQLCA Return return(eqlca.eqlcode);
Code To The
Calling
Function
~
Main
/* The
/* int
I / / Declare The Local Memory Variable0 long rc = SQL-RC-OK;
~~~~
*/ */
Chapter 12: DB2 Database Partition Management Functions / / Drop The TEST Database At The Current Node rc = Example.DropDBAtNode0;
1
/ / Return To The Operating System return ( rc ) ;
SET RUNTIME DEGREE Purpose
The SET RUNTIME DEGREE function is used to set therun-time degree of intrapartition parallelism that is to be used to process SQLstatements for oneor more active applications.
syntax
Parameters
NumAgentZDs
The total number of active applicationsto which the new degree of intra-parallelism is to apply (i.e., the number of elements in the array of agent IDS specified in theAgentZDs parameter).
AgentIDs
A pointer to alocation in memorywhere an array of active application agent IDS are stored. The maximum run-time degree of intra-partition parallelism that is to be usedto process SQLstatements. A pointer to alocation in memory where a SQLCommunications Area (SQLCA) data structurevariable is stored. T h i s structure returns either status information (ifthe function executed successfully) or error information (ifthe function failed)to the calling application.
Degree
SQLCA
Includes
#include <sqlenv.h>
Description
The SET RUNTIME DEQREE function is used to set therun-time degree of intrapartition parallelism that is to be used to process SQLstatements for oneor more active applications.This function has no effect on the run-time degree of intrapartition parallelism that is used by the CREATE INDEX SQL statement.
Comments
If the NumAgentZDs parameter is set to SQLALL-USERS, the new degreevalue specified in theDegree parameter will be appliedto all active applications,and the value specifiedin theAgentZDs parameter is ignored. W The value specified in theDegree parameter must be in therange of 1to 32767.
p Part 3: Application Programming Interface Functions W The database system monitor functions describedin Chapter 13 (specifically,the GET SNAPSHOT function) can be used to generate a list of agent IDS (and run-time degrees) of all active applications. H A limitedamount of validation is performed whenan array of agent I D S i s
referenced by the AgentZDs parameter. The application must ensure that the number of elements found in the arrayof agent IDS referencedis thesame as the value specified in the NumAgentZDs parameter., W If one or more of the agent IDS specifiedin theAgentZDs parameter cannot be found whenthis function is executed, they are ignored-and no error is returned. For example, an agent ID may not be found ifuser a signs off (an application terminates) between the time its agent ID was collected and the time this function is called. H Agent I D S are recycled. When oneuser signs off, another user may signon and
acquire the same agent ID. Therefore, if this function is not called immediately after agent I D S are collected, the run-time degree of intra-partition parallelism that is to be used to process SQL statements may be modified forthe wrong application. W This function affeds all nodes that are identified in the db2nodescfgconfiguration file.
Connection This function can only be called when a connection to a DB2 Database Manager instance Requhments exists. In order to change the run-time degree of intra-partition parallelism on a remote server,an attachment must first be made to that server.
'
Authorization Only users with either System Administrator (SYSADM) authority or System Control (SYSCTRL)authority are allowed to execute this function call. See Also
GET SNAPSHOT
Example
ThefollowingC++program illustrates how to use the SET RUNTIME DEGREE function to set therun-time degree of intra-partition parallelism that is to be used to process SQL statements for all active applications: I*
/*
/* /* /* /* /*
CH12EX5.CPP NAME: PURPOSE: Illustrate How To Use The Following DB2 API Function In A C++ Program: DEGREE
SET RUNTIME
/ / Define
Header
TheAPI-Class Class
*/ */
*/ */ */ */
/*
/ / Include The Appropriate #include <windows.h> #include #include <sqlenv.h> #include <sqlca.h>
*/ */
Files
Chapter 12: DB2 Database Partition Management Functions
I.
,j
489 j
class API-Class
I / / Attributes public : struct sqlca aqlca;
/ / Operations public : long SetRuntimeDegreeO;
1; / / Define The SetRuntimeDegreeO Member Function long API-Class::SetRuntimeDegree()
I / / Declare The Local char Instance 191 ; / / Obtain The / / Variable
Memory
Variables
Current Value Of The DB2INSTANCE Environment
sqlegine(Instance, hsqlca); Instance[B] = 0; / / Attach 40 The Current DB2 Database Manager Instance sqleatin(Instance, "userid", ltpasswordN,brsqlca); / / Set The Maximum Runtime Degree Of Intra-Partition Parallelism / / To Be Used To Process SQL Statements( B y All Active / / Applications)
sqlesdeg(SQL-ALL_OSERS, NULL, 16384. hsqlca); / / I€ The TEST Database Bas Been Created, Display A Success / / Meaaage if (sqlca.aqlcode == SQL-RC-OK) {
1
cout << "The runtime degree of intra-partition ''; cout << t8parallelismis n w 16K " << endl; cout << "(for all applications) << endl;
."
/ / Detach From The Current DB2 Database Dfanager Inatance aqledtin(hsq1ca); / / Return The SQLCA Return return(sqlca.sqlcode);
1
Code To The
Calling
Function
.. I
/*
*/ */
The Main Function
/* int main( ) { ,
/ / Declare The Local longrc = SQL-RC-OK;
Memory
Variables
/ / Create An Instance Of The API-Class Class
Part 3: Application Programming Interface Functions
/ / set The m imum Runtime Degreeof Intra-Partition Parallelim / / That Is To Be Used To Process SQL Statements
rc = Example. SetRuntimeDegree(
1
/ / Return To The return )(rc ;
Operating
;
System
PR! FM GET TABLE PARTITIONING
INFORMATION Purpose
The GET TABLE PARTITIONING INFORMATIONfunction is used to obtain the partitioning information fora database table.
syntax
SQL-I-RC SQL-API-FN
Parameters
Sqlugtpi (unsigned char struct eqlupi struct sqlca
*TableNme,
"PartionInfo,
*SQLCA);
TbbleName
A pointer to location in memory wherethe name of the table that
PartitionInfo
partitioning information is to be retrieved for is stored. A pointer to a location in memory wherean sqlupi structure that this function is to return partitioning information to is stored.
SQLCA
A pointer to a location in memory wherea SQL Communications Area (SQLCA)data structurevariable is stored. T h i s structure returns either statusinformation (ifthe function executed successfully) or error information (ifthe function failed)to the calling application.
Includes
#include <sqlutil.h>
Description
The GET TABLEPARTITIONING INFORMATIONfundion is used to obtain the partitioning information for a table (for example,the partitioning map and the column definitions of the partitioning key) in a partitioned database. This fundion r e h n s partitioning information in a special structure, sqlupi, which is defined in sqluti1.h as follows:
/* /* /* /* /*
The length, in bytes, o f the partitioning map. For a singlenode table, this value is equal to sizeof(SQL-PDB-NODE-TYPE). For a multi-node table, this value is
*/ */
*/ */ */
m1 1 : i
Chapter 12: DB2Database Partition Management -Functions
!:
l
491
“ I
/* SQL-PDB-NODE-TYPE
pmap[40963 I
unsigned
sqldr
short
equal to 4096
*
*/
/*
sizeof(SQL-PDB_NODE_TYPE).
*/
/* /*
The partitioning map The number o f columns in a partitioning key (i.e. the number o f elements in thesqlpartkey array).
*/ */ */ */ */
/* /*
/* struct sqlpartkey sqlpartkey[500];
/* The description of the partitioning*/ / * columns in a partitioning key */
1;
Table 12-2 SOL Data Types and Lengths for theSQLUPI Data Structure (NULLS
Not Allowed)
(NULLS
Allowed)
Length
Date
384
385
Ignored
Time
388
389
Ignored
Timestamp
392
393
Ignored
Variable-length character string
448
449
Length of the string
Fixed-length character string
452
453
Length of the string
Long character string
456
457
Ignored
NULLterminated character string
460
461
Length of the string
Floating point
480
481
Ignored
Decimal
484
485
Byte 1 equals Precision Byte 2 equals Scale
Large integer
496
497
Ignored
Small integer
500
501
Ignored
Variable length graphicstring
464
466
Length in double-byte charactera
Adapted from IBM’s DB2 Universal Database API Reference, Table 75, page 463.
This structure references an additional structure,sqlpartkey. The sqlpartkey structure is defined in sqluti1.h as follows: struct sqlpartkey {
unsigned short sqltyper unsigned short eqllen;
1;
/* /* /* /* /*
The SQL data type of a column in a partitioningkey(SeeTable 12-2) The length of the data stored in a column in a partitioning key (See Table 12-2)
*/ *./ */
*/ */
l
" "
Part 3: Application Programming Interface Functions
"'
Table 12-2 lists theSQL data types and column length valuesthat can be returned for each columnin apartitioning key when this function is called. Information returned by this function can be used as input to the GET Row PARTITIONING NUMBER function.
Comments
This function affects all nodes that areidentified in thedb2nodes.cfg configuration file. Connection This function can only be called if a connection to a database exists. Requirements Authorization Only users with either System Administrator(SYSADM) authority, Database Administrator (DBADM) authority, CONTROL authority for the table specified, or SELECT authority for the table specified are allowed to execute this function call. See Also
QET ROW PARTITIONINQ NUMBER,
Example
The followingC++ program illustrates how to use the GET TABLE PARTITIONING INFORMATIONfimction to retrieve partition information for a table in theSAMPLE database:
CH12EXB.SQC
/* /* /* /* /*
/* /*
REDISTRIBUTE
NODEQROUP
*/ NAME: PURPOSE: Illustrate How To Use The Following DB2 API Function In A C++ Program:
*/
PARTITIONING INFORMATION TABLE GET
*/
*/
/ / Include The Appropriate Header Files #include <windowe.h> #include 4.oetream.b #include <SplUtil.h> #include *eqlca.h> / / Define The API-Class Class class API-Class
E / / Attributes public: etruct eqlca splca;
/ / Operations public : long QetTablePartitionInfoO;
1; / / Define The QetTablePartitionInfoO Member Function long API-ClaSS::GetTablePartitionInfoO
E
*/ */ */
Chapter 12: DB2 Database Partition Management Functions / / Declare The Local Memory Variables unsigned char *TableName; PartitionInfo; eqlupi / / Initialize The Local Memory variables TableName P new unsigned char[20]; * ) TableName, "EMPLOYEE"); strcpy( (char
/ / Get The Partitioning Information For The / / In The SAMPLE Database sqlugtpi(TableName, aPartitionInfo, asqlca); if (sqlca.sqlcode l = SQL-RC-OK) return(sqlca.sqlcode);
EMPLOYEE
Table
/ / Display The Partitioning Information Retrieved For The EMPLOYEETable"; cout << "Partitioning Key Information cout << endl << endl; for (int i a 0; i < (int) PartitionInfo.sqld; i++)
tout << "Data m e : cout.width(4); cout.setf(ioe::left); cout << PartitionInfo.eqlpartkey[il.sqltype;
cout << "Data Length : cout.width(4); cout.setf(ioe::left); cout << PartitionInfo.sqlpartkey~i1.eqllen;
1 / / Free Previously delete [ l TableName;
1
Main
/* /*
Allocated Memory
/ / Return The SQLCA Return return(sqlca.eqlcode);
Code To The
Calling
Function
*/ */
The
int main( ) {
/ / Declare The LocalMemory Variables long rc = SQL-RC-OK; struct eqlca eqlca; / / Create An Instance Of The API-Claes Class API-ClassExample; / / Connect To The SAMPLE Database EXEC SQL CONNECT TO SAMPLE USER / / Get The
rc
I
saerye
Table Partition Information Example.GetTablePartitionInfo();
USING
For
The
Pdr793; EMPLOYEE
Table
I- 494
Part 3: Application Programming Interface Functions / / Issue A Rollback To Free EXEC SQL ROLLBACK;
All
Locks
/ / Disconnect From The SAMPLE Database EXEC SQL DISCONNECT CURRENT; / / Return To The return(rc);
Operating
System
PW lmaAlarl GET ROW PARTITIONING NUMBER Purpose
The GET ROW PARTITIONINQ NUMBERfunction is used to obtain the partition number and node number at which a specific row ofdata in a table (in a parallel database system) is stored.
syntax
SQLXI-RC SQL-API-FN
Parameters
NumKeys
PartitionKeys
Keyhngths
CountryCode
sqlugrpn (unsigned short unsigned char unsigned short unsigned short unsigned short struct sqlupi short SQL-PDB-NODE-TYPE unsigned short struct sqlca short void void
meyrr, **Partitio-eyrr, *KeyLengths, CountryCode, Codepage, *PartitionInfo, *PartitionNlunber, *Nodemer, CheckLevel, 'SQLCA, KeyFoxma t , *Reservedl,
*Re~erved2) ;
Thenumber of partition keys stored inthearray of partition keys stored in the PartitionKeys parameter. A pointer to location in memory where an array of character representations of values for eachpart of the partitioning key identified in thePartitionInfo parameter is stored.
A pointer to location in memory where an array of lengths for each partition key value stored in the PartitionKeys parameter is stored. Specifies the country code of the target database. This parameter must be set to one of the following values: 1 (United States of AmericdCanada) 3 (Latin America) 7 (Russia) 27 (South Africa)
Chapter 12: DB2 Database Partition Management Functions 30 31 32 33 34 36 39 40 41 42 43 44 45
46 47 48 49 55 61 64 66 81 82 86 88 90 351 353 354 358 359 370 371 372 375
(Greece) (Netherlands) (Belgium) (fiance) (Spain) (Hungary) (Italy) (Romania) (Switzerland) (Czech Republic) (Austria) (United Kingdom) (Denmark) (Sweden) (Norway) (Poland) (GernanY) (Brazil) (Australia) (New Zealand) (Thailand) (Japan) (South Korea) (China) (Taiwan) (Turkey) (Portugal) (Ireland) (Iceland) (Finland) (Bulgaria) (Lithuania) (Latvia) (Estonia) (Belarus)
l
p Part 3: Application Programming Interface Functions 380 381 385 386 389 785 938 972
Codepage
(Ukraine) (Serbia/Montenegro) (AlbanidCroatia) (Slovenia) (FormerYugoslav Republic (Arabic Countries) (Slovakia) (Israel)
of Macedonia)
Specifies the code page of the targetdatabase. T h i s parameter must be set to one of the following values: 37
273
277
278
280
284
285
297
420
423
424
437
500
737
813
819
850
852
855
857
860
862
863
8 64
866
869
870
871
874
875
912
915
916
920
921
922
930
932
933
935
93.7
938
939
942
943
948
949
950
954
964
970
1025
1026
1046
1051
1089
1112
1122
1131
1140
1141
l142
1143
1144
1145
1146
1147
1140
1149
1250
1251
1252
1253
1254
1255
1256
1275
1280
1281
1282
1283
1363
1364
1381
1383
1386
1388
5026
5035
5039
PartitionInfo
A pointer to a location in memory wherean sqlupi structure that this function is to obtain partition key and partitioning map information fromis stored.
PartitionNumber
A pointer to a location in memory wherethis function is to store the partition number wherethe specified row of data resides.
NodeNumber
A pohter to a location in memory wherethis function is to store the node number wherethe specified row of data resides.
Chapter 12: DB2 Database Partition Management Functions
'
j __4971 " "
CheckLevel
Specifies the level of checking that is to beperformed on all input parameters before t h i s function is executed. For now, ifthis parameter is set to 0, no checking is performed; and, if this parameter is setto any non-zero number,all input parameters are checked.
SQLCA
A pointer to a location in memory wherea SQL Communications Area (SQLCA) data structurevariable is stored. This structure returns either status information (ifthe function executed successfully) or error information (ifthe function failed) to the calling application.
KeyFonnat
Specifies thedata type that is used to represent partitioning key values. This parameter must be set to one of the following values:
m
SQL-CHARSTRING-FORMAT
All partitioning key values are represented by character Strings.
m SQL-PACKEDDECIW-FORMAT All decimal partitioning key values are stored in packed decimal format.
m SQL-BINARYNWERICS-FORMAT Reservedl Reserved2
All numeric partitioning key values are stored in binary format. A pointer that, at this time, is reservedfor later use. For now, this parameter must always be set to NULL. A pointer that, at this time, is reservedfor later use. For now, this parameter must always beset to NULL.
Includes
#include <sglutil.h>
Description
The GET ROW PARTITIONING =ER function is used to obtain the partition number and node number at which a specific rowof data ina table (in a parallel database system) is stored. T h i s information can be useful when analyzing how data is distributed in a partitioned database environment. Either the contents of an sqlupi structure that hasbeen populatedby the GET TABLE PARTITIONING INFORMATIONfunction, or a set of partitioning key values,must be available beforethis function canbe executed. Referto the GET TABLE PARTITIONING INFORMATIONfunction fora detailed descriptionof the sqlupi structure.
Comments
If partitioning map information is not provided as input, only the partition number is returned when this function is executed. If this function is called with the NodeNumber parameter set to something other than NULL, partitioning map informationmust be provided (i.e.,the pmaplen field of the sqlupi structure provided in the PartitwnInfo parameter must equal 2 or 8,192).
L498 Pi :
Part 3: Application Programming Interface h c t i o n s
i
B If a NULL value is assigned to a non-nullable partitioning key column whenthis
function is called, an error will occur. B If this function is called beforethe partitioning key has been defined (i.e.,the sqld field of the sqlupi structure provided in the PartitionZnfo parameter equals o), an error will occur. B Any data type that is supported by the operating system can be usedto define a
partitioning key. B CHAR, VARCHAR, GRAPHIC,and VARGWHIC data values must be converted
to the code page specified beforethey can be used as partitioning key values. B The character representations of numeric and datetime data values must use the
same code page as that of the operating system in use where this function is invoked. B All leading and trailingblanks found in thecharacter representations of partitioning key values (provided in the PartitionKey parameter) areremoved, unless the datatype of the partitioning key is CHAR, VARCHAR, GRAPHIC,or VARGRAPHIC; in which case, onlytrailing blanks are removed. W This function canbe called from any nodethat is identified in the db2nodes.cfg
configuration tile.
Connection This function can only be called if a connection to a database exists. Requirements Authorization No authorization is required to execute this function call.
see Also Example
QET DATABASE CONFIQWRATION, GET TABLE PARTITIONING INFORMATION,REDISTRIBUTE NODEQROUP
The following c++program illustrates how to use the QET ROW PARTITIONINQ NUKEIER function to obtain the partition number and node numberat which a specific row of data in atable (in a parallel database system) i s stored:
/* /* /* /* /* /* /*
CHlZEX7.SQC NAME: PURPOSE: Illustrate How To Use The Following DB2 API Function In A C++ Program:
*/ */ */ */
ROWQET
PARTITIONINQ NUMBER
/ / Include The Appropriate Reader Files #include *windows.h> #include #include *sqlca.h>
*/
*/ */
Chapter 12:DB2 Database Partition Management Functions / / Define The API-Claee Claea claee API-Clam f / / Attributes public: struct eqlca sqlca; / / Operatione public : long GetRowPartitionNumber~); ?l
/ / Define The GetRowPartitionNumber() Member Function long API-C1ase::QetRowPartitionNumberO
c
/ / Declare The Local M e m o r y Variablee uneigned *TableName; char eqlupi ehort SQL-PDB-NODE-TYPE NodeNumber;
PartitionInfo; PartitionNumber;
/ / Initialize The Local Memory Variables TableName = new uneigned charI201; strcpy ( (char *) TableName, "EMPLOYEE") ; / / Get The Partitioning Information / / In The SAMPLE Database
For The EMPLOYEE Table
eqlugtpi(Tab1eName. brPartitionInfo, srsqlca); if (eqlca.eqlcode !E SQL-RC-OK) return(aqlca.eqlcode); / / Get The ROW Partitioning Number For The EMPLOYEE Table eqlugrpn(PartitionInfo.sqld, NULL, NULL, 1, 1252, brPartitionInfo, brPartitioPNumber, &NodeNumber, 0, esqlca, SQL-CHARSTRING-FORMAT, NULL, NULL);
/ / If The Row Partitioning Number Wae Retrieved, Display It if (sqlca.sqlcode == SQL-RC-OK) {
**
tout "The row partitioning number forthe EMPLOYEE cout *< '%able ie : ** <* PartitionNumber << endl;
";
? / / Free Previouely delete 1l TableName;
Allocated Memory
/ / Return The SQLCA Return return(eqlca.sqlcode);
Code To The
Calling
Function
? I*
/*
*I
The Main Function
*/
Part 3: Application Programming Interface Functions / / Declare The LocalM e m o r y Variables long rc = SQL-RC-OK; struct eqlca eqlca;
/ / Create An Instance O € The API-Claes Claes API-ClassExample; / / Connect To The SAMPLE Database EXEC SQL CONNECT TO SAMPLE USER
ueerid
/ / Get The ROW Partitioning Number For rc = Example.GetRowPartitionNumber0; / / Issue A Rollback To Free EXEC SOL ROLLBACK#
All
USING
paeeword;
The EMPLOYEE Table
Locks
/ / Dieconnect From The SAMPLE Database EXEC SQL DISCONNECT CURRENT; / / Return To The returntrc);
Operating
System
1
mm Purpose
REDISTRIBUTE NODEGROUP The REDISTRIBUTE in a nodegroup.
NODEGROUP function is used to redistribute data across the nodes
SQL-API-RC SQL-API-FN eqlurdt
Parameters
NodeGroup PartitionMapFile
DataDistributionFile
AdalJVodeList
(char char char SQL-PDB-NODE-TYPE unsigned short SQL-PDB-NODE-TYPE unsigned short unsigned char struct sqlca
*NodeGroug, *PartitiOrZM&pFile, *DataDiEtributionFile, AddNodeLi Et, AddNodeCoun , t DropNodeLis , t DropNodeCoun , t 'CallerAction, *SQLCA) ;
A pointer t o location in memory wherethe name of the nodegroup to be redistributed is stored. A pointer to location in memory wherethe name of the file that contains the targetpartitioning map is stored. This parameter can containa NULL value. A pointer to a location in memory wherethe name of the file that contains data distribution information is stored. This parameter can contain a NULL value. A list of nodes that are to be addedto the nodegroup during data redistribution. This parameter can containa NULL value.
A Chapter 12: DB2Database Partition Management Functions
,
,
i
.
.
I
~
"
I
501
AddNodeCount
Thenumber of nodes defined in the Ado!.NodeList parameter.
DropNodeList
A list of nodes that are to beremovedfrom the nodegroup during data redistribution. T h i s parameter can contain a NULL value. Thenumber of nodesdefined in the DropNdList parameter.
DropNodeCount CallerActwn
Specifies the action this function is to take when the function is executed. This parameter must be set to one of the following values: U .
Data in thenodegroup is to be redistributed to achieve a balanced distribution. If a data distribution file is provided (the DataDistributionFile parameter does not equal NULL), it is assumed that the values in thisfile represent the way data is to be distributed. If a data distribution file is not provided (the DataDistributionFile parameter equals NULL), it is assumed that the data is t o be distributed uniformly (that is, each has partition is to represent the same amount of data). .T
Data in the nodegroup is to be redistributed according to the contents of a target partitioning map file (referenced by the PartitionMapFile parameter). C .
A nodegroup redistribution operation that failed earlier is to be continued. B R
SQLCA
A nodegroup redistribution that failed is to be rolled back. A pointer to a location in memory wherea SQL Communications Area(SQLCA) data structure variable is stored. This structure returns either status information (if the function executed successfully)or error information (if the function failed) to the calling application.
Includes
#include <eqlutil.h>
Description
"he REDISTRIBUTE NODEGROUP function is used to redistribute data across the nodes in a nodegroup. Whenthis function is called, a redistribution algorithm selectsany partitions that areto be moved according to how data i s currently distributed. Nodegroups that contain replicatedsummary tables or tables that have been defined with DATA CAPTURE CHANGES constraints cannot be redistributed.
Comments
This function can only be called froma database's catalog node. The GET NEXT
l
j
i 502
P' Part 3: Application Programming Interface Functions
,
DATABASE DIRECTORY ENTRY function
canbe used to determine which node is the
catalog node fora database. W If a directory path isnot includedin thefile name specifiedin the
PartitionMapFile or DataDistributionFile parameter, this function assumes that the file is located in thecurrent directory. H The partition map file referencedby the PartitionMapFile parameter must be in character format, and the file must contain either one entry (for a single-node nodegroup) or 4,096 entries (for a multi-node nodegroup). Eachentry must identie a valid node number. W The data distribution file referencedby the DataDistributionFile parameter must be in character format and must contain 4,096 positive integer entries. Each entry
must indicate the weight of the correspondingpartition, and the sum of all entries should be less than or equal to 4,294,967,295. H If the CallerAction parameter is setto D, nodes listed in theAddNodeList
parameter are added to the nodegroup, and nodes listed in the DropNodeList parameter are removed from the nodegroup during the dataredistribution operation. Otherwise,these parameters, along with the AddNodeCount and DropNodeCount parameters, are ignored. W If the CallerActwn parameter is setto U, the PartitionMapFile parameter should
contain a NULL pointer. TheDataDistributionFile parameter may or may not contain a NULL pointer. W If the CallerAction parameter is set to T, the DataDistributionFile, AddNodeList,
and DropNodeList parameters should containNULL pointers. "he AddNodeCount and DropNodeCount parameters should be set to 0 , and the PartitionMapFile parameter must contain a valid file reference. H If the CallerAction parameter is set to c or R, the PartitionMapFile,
DataDistributionFile, AddNodeList,and DropNodeList parameters should contain NULL pointers, and the AddNodeCount and DropNodeCount parameters should be set t o 0. H This function performsintermittent commits while executing. H The ALTER NODEGROUP SQL statement can be used to add nodes to a nodegroup.
NOTE:h'e!.!
ADD NODE and DROP NODE SQL statements thatwere provided in DB2 Parallel Edition forAIX Version l are supported for userswith SYSADM or SYSCTRL authority. When theADD NODE SQL statement is processed, containersare created like the containers found on the lowest node number of existing nodes within the nodegroup.
R When this function executes,all packages that have a dependency on a table that
has been redistributed are invalidated.Therefore, it is important to explicitly rebind all packages that were affected immediately aRera redistribute nodegroup operation has completed. Explicit rebindingeliminates the initial delay that will
5 Chapter 12: DB2 Database Partition Management Functions
i
503
' __
.-
result the first time an SQL request attempts to use an invalid package.It is also a good idea t o update table statistics for all tables that have beenredistributed. When a redistribution operation is performed, a message fileis written to:
W The $HOMElsqlliblredistdirectory on UNIX based systems, usingthe following format: database-name.no&gmup-name.timestamp,where timestamp is thetime at which this function was called W The $HOME\sqllib\redist directory on other operating systems, usingthe following format: database-name\Frst-eight-characters-of-nodegrollp-nam\date\time, where date and time are the dateand time at which this function was called Connection This function can only be called if a connection to a database exists. Requirements Authorization Only users with either System Administrator(SYSADM) authority, System Control . (SYSCTRL) authority, or Database Administrator(DBADM) authority are allowed to execute this function call.
see Also
DROP NODE VERIFY, REBIND, RUNSTATS
Example
Thefollowing C++ program illustrates how to use the REDISTRIBUTE NODEOROUP function to activate the SAMPLE database:
/* /* NAME: /* PURPOSE: /* /* /*NODEQROUP /* /*
CHl2EX8.SQC Illustrate How To Use The Following DB2 API Function IU A C++ Program: REDISTRIBUTE
*/ Header
/ / Define The API-ClassC h S e class API-Claee
/ / operations public :
*/ */ */ */
/ / Include The Appropriate #include <windows.h> #include #include <sqlutil.h> #include <sqlca.h>
/ / Attributes public: struct sqlca
*/ */ */
eqlca;
Files
Part 3: Application Programming InterfaceFunctions long RedistributeNdegroupO; 11
/ / Define The RedistributeNodegroupO Member Function long API-C1ass::RedistributeNodegroupO
f / / Declare The LocalM e m o r y Variables char NodeQroup1201 ; / / Initialize The Local Memory Variables etrcpy(NodeGroup, t"IBMTEMPGROUP"); / / Redistribute The Nodegroup Uniformly sqludrdt(NodeOroup, NULL, NULL, NULL, 0, NULL, 0, 'U',
&sqlca);
/ / If The Nodegroup Has Been Redistributed, Display A Succeea / / Meseage if (sqlca.sqlcde l a SQL-RC-OK) cout << nodegroup has been redistributed." << endl;
I*
I
~ ~
/*
~~~~
~
*I
~
~~~
*/ */
The Main Function
/* int main0
c
/ / Declare The LocalMenwry Variables long rc = SOL-RC-OK; struct sqlca sqlca; / / Create An Instance Of The API-Class Class -1-ClassExample; / / Connect To The SAMPLE Database EXEC SQL CONNECTTO SAMPLE USER userid / / Redistribute
rc
I
The SpecifiedNdegroup Example.RedistributeNodegroup0;
/ / Issue A Rollback To Free EXEC SQL ROLLBACK;
All
Locks
/ / Disconnect From The SAMPLE Database EXEC SQL DISCONNECTCURRENT; / / Return To The return(rc);
operating
System
USINQ
password;
Processing APIs DB2 has a Database System Monitor utilitythat can be used to monitor activity on one or more databases. DB2 also provides a mechanism that breaks the commit process into two phases to be& ter ensure data integrity when working with multiple database& This chapter is designed to introduce youto the set of DB2API functions that are used to set database monitor switches and retrieve database monitor data-and to the set of A P I functions that are used to list and process indoubttransactions (partiallycommitted transactions that have been executed in a twephase commit environment). The h t part of this chapter providesa generaloverview of the DB2 Database System Monitor and of the APIs that are used to interact withit.Then, the two-phase commit process is described in detail, and the APIs that are used to list and process indoubt
1 I
506
1j
l
Part 3: Application Programming Interface Functions
I
The DB2 DatabaseSystem Monitor The DB2 Database System monitoris a facility that can collect information about database activityand performance at a given pointin time. Specifically,the Database System Monitor can collectthe following types of information: Status information at theDB2 Database Manager instance,database, table, and table space levels.Status information contains counters,status indicators, and other data that is specific to each level.
W Application-level information.This information includestransaction status, lock status, numerous counters,and information aboutthe currentSQL statement being processed.
W Locking details, such as lock waits and deadlock cycles. W Status information on distributed database connection servicesCDDCS) applications (if an application is using DB2 Connect to access a DRDA database server). The DB2 Database System Monitor can also collect SQL statement information. When t h i s type of information is collected, information forthe SQL statement being processed when the snapshot was taken is returned. If no SQL statement is being processed at the time the snapshot is taken, information for the last SQL statement processed is returned. You can specifywhat information a snapshot monitor collectsand access collected snapshot monitor informationby using the commands provided with the DB2 command-line processorinterface-or by including the database system monitor APIs in anapplication program.
Database System Monitor Switches "he information collected by a database system monitorsnapshot is divided into six separate groups (to simplify data collection and interpretation). Table 13-1 lists these six groups along with a description of some of the information that is collected for each groUP. Table 13-1
Database Monitor Groups
sorts
Number of heaps used, overflows, and number
Locks Tables Amount
Number of locks held and number of deadlocks detected of activity (numbero€rows read and written)
Buffer pools
Number of readsand writes and thetimetaken
of sorts performed
for eachreadand
write operation
Units o f work (transactions) "ransaction start times, transaction end times, and transaction completion status SQL statements Start
time, stop time, and statement
identification
,
I
Chapter 13: Database Monitor and Indoubt Transaction ProcessingAPIs j
'*
507
You can determine whether or not informationis being collected for any of the monitor groups listed in Table 13-1 by calling the OETIUPDATE MONITOR SWITCHES function. Information about when the monitoring of these different groups was started (that is, when the group switch wasturned on), along with the currentstate of each monitor group switch is returned when this function is executed. The OETIUPDATE MONITOR SWITCHES function can also beused to turn one or more monitor group switches ON or OFF (which, in turn, startsor stops data collection for the specified monitor group). If the SQL statement monitor switchis turned on while an SQL statement is being processed, the database system monitor will start collecting information when the next SQL statement isexecuted. As a result,the snapshot monitor will not return information about SQLstatements that theDB2 Database Manager is in the process of executing whenthe SQL statement monitor group switchis turned on. The same applies to unit of work (transaction) information and the unit of work (transaction) switch. When a monitor group switch is turned OFF, the counter elements related to that group are automatically reset to zero, and all of the data elements associated with the monitor group will contain either zero or blank values, depending upon their data types. You can set default valuesfor each snapshot monitor by using the appropriate DB2 Database Manager and database configuration fileparameters. If a snapshot monitor group switchis turnedon in the configuration fileand an application takes asnapshot without updating or resetting that monitor group switch, the datareturned will reflect the database activity sincethe DB2 Database Manager wasstarted. Every application that connects to a database automatically inherits these default switchsettings.
NOTE: The snapshot monitor always collects some basic snapshot information, even if all
'1
G==-
monitor group switches are turned ofl Obtaining detailed information from some monitor groups can significantlyaffect application performance. Take this into consideration whenever you turn amonitor group switch on.
When Counting Starts A snapshot contains, amongother things, cumulative informationthat covers all database activityfrom the time database monitoring was started to the time the snapshot is taken. This cumulative informationis collected by various activity counters.When counters are used to monitor activity,the counting beginsat the following times: the When an application connectsto the database (at the application level, when application establishes a connection; at the database level, whenthe first application establishes a connection; at the table level, whenthe table,is first accessed; and at the table space level, whenthe table space is first accessed) When counters are reset When a monitor group switchis turnedon
In many cases, you will want to collect counter information for a specific period of time. This means that you might needto reset counters while an application is running. (For example, if youare runningiterative tests andobtaining snapshot information for each iteration, you might wantto reset the counters between iterations.) You can reset counters for one or all databases controlled by the DB2 Database Manager by calling the RESET MONITOR function. When counters are reset, their current values are set to zero. If the counters for all active databases are reset, some DB2 Database Manager information will also be reset to maintain consistency. You cannot selectively reset specific data items of a monitor group with the RESET MONITOR function.When this function is called, all resettable data items for the database specified or for all active databases are setto zero. You can, however,reset all the data items related to a specific monitor group by turning that monitor group switchoff and then on again.
Retrieving SnapshotMonitor Data Before an application program can collect snapshot monitor data, the program must first allocate a memory storage buffer that is large enough to hold the snapshot information retrieved. The amountof memory required for this buffer dependson the number of monitoring applications (snapshot and event) being run, the types of monitor information being collected,and thelevel of database activity.
NOTE:Stopping certain applications allows you to focus on a single application or on a group of applications, which mightmake it easier for you to interpret the database system monitor output. Subsequently, as the number of applications runningdecreases, the amount of memory required to holdsnapshot monitordata also decreases. An application can accurately estimate the amount of memory to allocate for this buffer by calling the ESTIMATE DATABASE SYSTEM MONITOR BUFFER SIZE function. After memory forthe bufferhas been allocated, you can collect a snapshot of the monitor data specified by calling the QET SNAPSHOT function. When this function is executed, snapshot data is collected and copied directly to the previously allocated memory storage buffer (provideda large enough bufferhas been allocated). Portionsof this buffer must then be typecast to specially defineddata structuresbefore the application canretrieve the snapshot data collected. If all applications disconnect from a database, that database’ssnapshot monitordata will no longer be available. Alternatively, you can maintain one permanent connection to the databasethat will not be terminated until your final snapshot is taken. Keep in mind that if you are maintaining a permanent connectionto a database, there i s some amount of resource overhead associated withthat connection.
Chapter 13:Database Monitor and Indoubt Transaction Processing ApIs i
509
I
“ “ d
Working with Multiple Databases In its simplest form,a database application will only access and/or updatedata stored in a single database. However, it is often desirable for an application to access andor update data that is distributed across two or more different databases.In either case, applications that interactwith databases must ensure that data consistency is always
maintained. One of the best ways to maintain data consistency when working with two or more databases is to combine several read andor write operations in a single transaction (known as a distributed unit of work). Applicationsthat execute in a distributed unit of work environment (DUOW in DRDA terminology) can utilizea process known as twophase commit to roll back or commit changes made by a transaction. T h i s process is designed to maintain data consistency across multiple databases while transactions are executing.
How the Two-Phase Commit Process Works The DB2 Database Manager containsa component knownas thetransaction coordinator that is designed to coordinate readwrite operations that are made to several databases within a single transaction. The transaction coordinator usesa special database, known as theTransaction Managerdatabase, to register each transaction (unit of work) and to track the completion status of that transaction across all databases that the transaction is involved with. The database that is to be used as a Transaction Manager database is determined by the value stored in the tm-database parameter of the DB2 Database Manager configuration file. The Transaction Managerdatabase can be any database that an application can connectto, however, for operational and administrative reasons,the database must reside on a robust machinethat is up and running most of the time. Additionally,all connections to the Transaction Managerdatabase should be made by the transaction coordinator. An application program should never attempt to connect directlyto the Transaction Managerdatabase. The following list describes the actual steps that are taken during the two-phase commit process: 1. When the application programstarts a transaction, it will automatically
connect to the Transaction Managerdatabase. 2. Just before the firstSQL statement in the transaction is executed, the request to the transaction coordinator sends a Dunsaction Register -G) Transaction Managerdatabase in order to register the new transaction.
3. The Transaction Managerdatabase responds to the application programby providing a unique globaltransaction ID for the new transaction (because the XREG request was sent without a predefined ID). 4. After receiving the transaction ID, the application programregisters the new transaction (using the transaction ID) withthe database containing the
.
required user data. response is sent back to the application pro^^ when the transaction has been succes L statements issued against tabase containing the user data are ed in the normal manner9with the return code for each S processed being returned in Steps 2 and 5 are repeated for each database that is accessed by the transaction. All other databases ac d in the transaction receive the global transaction ID just before the first s t a t e ~ e nis t e~ecutedagainst it, The L statement is used to switch between each database conn~ction. en the application p r o ~ a mrequests that the current t r ~ s a c t i o nbe com~itted? the transaction coordinator sends a databases that have been accessed by the trans receives this message writes a “ P ~ E ”Precord ~ ~to their log files and sends a response back to the transaction coordinator, en the transaction coordinator receives a positive response firom all ~ e s s a g ewas sent to, it sends a messa to inform it that the transaction has been epared and is now ready to be committed. This completes the first phase of e two-phase commit process. anager database writes a “P ” record to its log file and sends a message back to the transaction coordinat~r,inform in^ it that the second phase of the commit process can now be started. The transaction coordinator then f o ~ a r d this s message to the application p r o ~ a m .
to the transaction coordinator.
e 13-1 illustrates this sequence of events.
COMMIT:
How the two-phase commit process works
dles two~~has@ commit errors as ~ 0 1 ~ 0 ~ s :
~oc@ss. In this case, a
the transaction.
I
l1
512
1I
Part 3: Application Programming Interface Functions Second PhaseErrors Error handling at the second stage of a commit is dependent upon whetherthe second phase is to commit or roll back the transaction. "he second phase will only roll back the transaction if the firstphase encountered an error. If one of the participating databases fails to commit the transaction (possibly due to a communications failure), the transaction coordinator will continue(until successful) to try to commit the transaction to the database that failed. "he value stored in the resync-internal parameter of the DB2 Database Manager configuration fileis used to determine how long the transaction coordinator will wait between attempts to commit the transaction. Transaction Manager DatabaseErrors If for some reason the Transaction Managerdatabase fails, the transaction coordinator will resynchronizethe transaction when the Transaction Manager database is restarted. This resynchronization processwill attempt to complete all indoubt transactions; that is, all transactions that have completed the first phase, but not the second phase,of the two-phase commit process. "he DB2 Database Manager instance where the Transaction Managerdatabase resides will perform the resynchronization by:
1. Connecting to the databases that replied that they were "PREPARED"to commit during the first phase of the commit process. 2. Attempting to commit the indoubt transactions at thatdatabase. (If no indoubt transactions can be found, the DB2 Database Manager assumes that the database successfully committedthe transaction during the second phase of the commit process.) S. Committing the indoubt transactions in theTransaction Managerdatabase after all indoubt transactions have been committedin theparticipating databases.
Other Database.Errors If oneof the databases accessed in thetransaction fails and is restarted, theDB2 Database Manager forthat database will check the log files of the Transaction Manager database to determine whetherthe transaction should be rolled backor committed. Ifthe transaction is not found in the Transaction Managerdatabase log files,the DB2 Database Manager assumes the transaction was rolled back,and the indoubt transactions for this database willbe rolled back. Otherwise,the database w l iwait for a commit request from the transaction coordinator.
Manually Resolving Indoubt Transactions If, for some reason, you cannot wait for the transaction coordinator to automatically resolve indoubt transactions, you can manually resolve them by "making a heuristic decision" and applyingthat decision to all applicable records. In order to apply a heuristic decision to an indoubt transaction, its global transaction ID must first be acquired. The LIST INDOWT TRANSACTIONSfunction can be used to obtain the global transaction ID
Chapter 13:Database Monitor and Indoubt Transaction ProcessingApIs
\$
,
~
5 13
1
for all indoubt transactions that exist for a specified database. Once an indoubt transaction's global transaction ID has been obtained,the COMMIT AN INDOUBT TRANSACTION function can be used to heuristically commit the transaction, and the ROLLBACK AN INDOUBT TRANSACTION function canbe used to heuristically rollit back. After a transaction has been heuristically committedor rolled back,the FORGET TRANSACTION STATUS function canbe used to tell the DB2 Database Manager to "forget it" by removingall log records that refer to it-and by releasing ita log space.
NOTE: If the LIST IWUBT TRANSACTIONS command is executed with the WITH PROPMTINQ option, it can alsobe used to heuristically roll back, commit, orforget indoubt transactions. The indoubttransaction processing commandand MISshould be used with extreme caution and only as a last resort. The best way to resolve indoubttransactions is to wait for the transaction coordinator to drive the resynchronization process. Otherwise,you could cause data integrity problems to occur (for example, ifyou manually commit or roll back a transaction in one database and perform the opposite action for another database). Recovering fromdata integrity problems requires that you understand the application logic and the datachanged or rolled back-and to perform a point-in-time recovery of the database (or manually undohedothe database changes made). If the transaction coordinator will not be available an forextended periodof time (to initiate the resynchronization process), and if an indoubt transaction is tying up resources that are urgently needed (i.e., locks on tables and indexes,log space,and storage taken up by the transaction), manually resolving the indoubt transaction may be necessary. Thereare no foolproof waysto manually recover indoubttransactions. However, the following steps can be used as a guideline: 1. Connect to the database for which yourequire all transactions t o be complete. 2. Use the LIST
INDOUBT TRANSACTIONS function t o display the indoubt transactions. The transaction ID returned represents the global transaction ID and is identical in all other databases that were accessedby a transactionincluding the Transaction Manager database.
3. For each indoubt transaction found, use your knowledge about the application and the tm-database parameter of the DB2 Database Manager configuration file to determine the names of the Transaction Manager database and the other databases that were accessedby the transaction. 4% Connect to the Transaction Manager database. If you wereable to connect to this database, use the LIST INDOUBT TRANSACTIONSfunction to display the indoubt transactions recorded in theTransaction Manager database. If there is an indoubt transaction with the same global transaction ID as thatfound in step 2 and with type '''I",''you can connect to each database participating in the transaction and heuristically commit the transaction using the COMMIT AN INDOUBT TRANSACTION function or the LIST INDOUBT TRANSACTIONS WITH PROMPTING command. If there is no indoubt transaction with the same global transaction ID (and with type "11"') as thatfound in step 2, you can connect to each database
Part 3: Application Programming Interface Functions participating in the transaction and heuristically roll backthe transaction using the ROLLBACK AN INDOUBT TRANSACTIONfunction or the LIST INDOUBT TRANSACTIONS WITH PROMPTING command.
4b. If you are unable to connect to the Transaction Managerdatabase, you will have to use the statusof the transaction in theother participating databases to determine which actionyou should take:
W If at least one of the other databases has committed the transaction, then you should heuristicallycommit the transaction in all the participating databases using the COMMIT m INDOUBT TRANSACTIONfunction or the LIST INDOUBT TRANSACTIONS WITH PROMPTING command. H If at least one of the other databases has rolled backthe transaction, then
you should heuristicallyroll back the transaction in all the participating databases using the ROLLBACK AN INDOUBT TRANSACTION function or the LIST INDOUBT TRANSACTIONS m m PROMPTING command.
W If the transaction is in"PREPARED" (indoubt) state inall of the pahicipating databases, then you should heuristically roll back the transaction in all the participating databases using the ROLLBACK AN INDOUBT TRANSACTION function or the LIST INDOUBT TRANSACTIONS WITH PROMPTING command. M If you are unable to connect to one or more of the other participating
databases, then you should heuristically roll back the transaction in all the participating databases using the ROLLBACK AN INDOUBT TRANSACTION function or the LIST INDOUBT TRANSACTIONS WITH PROMPTING command. If you heuristically commit or roll back an indoubt transaction, you do not haveto "forget it" immediately afterward.Instead, it is a good idea to wait until the Transaction Managerdatabase is accessible so that your decisions can be verified. That way, if a transaction was committedor rolled back incorrectly, the Transaction Manager database can detectthe error. Whenerrors of this type are found, the Transaction Manager will write a message to the db2diug.Zog tile indicating "heuristic damage" has occured to a particular database (this will occur whenthe Transaction Managerattempts to synchronize).
Two-Phase CommitProcessing. Usingan XACompliant Transaction Manager The XA interface is a widely used interfacethat was defined by the WOpen Company T h i s interface is used to exchange information betweentransaction managers (suchas CICS) and resource managers (such as DB2 C/S) to ensure data consistency when working with multiple databases in a single transaction. If your application needs to perform readwrite operations to resources that use the XA interface, the application will have to use an XA-compliant transaction manager in place of DB2's transaction coordinator. In this case, eachdatabase referenced in a transaction must be identified with an XA open string that has thefollowing format:
Chapter 13:Database Monitor and Indoubt TransactionProcessing APIs 1
1
5 15
”
‘“database-alias ~ , u s e r n a ~ n e , p a s s w o r d ~ ~
The database-alias specifies the alias name for the database and the username and password (optional) are used to provide authentication information to the database manager instance.ARer each database has been identified,the XA-compliant transaction managertreats it as a separate resource manager. An XA-compliant transaction manager uses a two-phase commit process similar to that used by DB2 Universal Database. The primary difference between the two environments is thata Transaction ProcessingMonitor providesthe function of logging and controlling a transaction, rather thana Transaction Manager database. Because the rest of the process is virtually the same, there is no difference in the way errors are handled.
The DB2 Database Monitor and Indoubt Transaction Processing Functions Table 13-1 lists the DB2 A P I functions that are used to setheset database monitor switches, collectdatabase monitor data, and manually resolve indoubt transactions. Each of these functions is described in detail in theremainder of t h i s chapter. Table 13-1 ~
-
Database Monitor and lndoubt Transaction ProcessingAPls r
-
~
~
”
~
-
.
,
~
.
-
~
iption GET/UPDATE
MONITOR
Turns various databasesystem monitor switches on or o f f and queriesthe DB2 database systemmonitor for a group monitoringswitch’s current state.
SWITCHES
Resets the internal data monitor switches of a specified database (or of all active databases)to zero.
RESET MONITOR ESTIMATE GET
LIST
DATABASESYSTEM MONITOR
BUFFER
SIZE Estimates thesize of the buffer neededto hold the information collectedby the QET 8NApSHOT function.
Retrieves specific DB2 Database SystemMonitor information andcopies it to a user-allocateddata storage buffer.
SNAPSHOT
DRDA INDOWT TRANSACTIONS
Retrieves a list o f all indoubt transactionsthat exist between partner logical units (LUs) that are connected by LU 6.2 protocol.
LIST INDOWT TRANSACTIONS
Retrieves a list of all indoubt transactionsfor the current connected database.
COMMIT AN INDOWT TRANSACTION
Heuristically commits an indoubt transaction.
ROLLBACK AN INDOWT TRANSACTION
Heuristically rolls back an indoubt transaction.
FORGET
Tells the Resource Manager to erase all knowledge of an indoubt transactionthat was heuristically committed or rolled back.
TRANSACTION
STATUS
,
Part 3 Application Programming Interface Functions
L. -.
m
FW GETNPDATE MONITORSWITCHES
Purpose
The GETIUPDATE MONITOR SWITCHES function is used to selectively turn various database monitor switches (information groups to be monitored) on or off and to query the database monitor fora group monitoring switch's current state.
syntax
int SQL-APT-FN
Parameters
Version
sqlmon (unsigned long char sqlm-recording-group struct sqlca
Version,
*Reserve& CroupStatesC 1 . *SQLCA) ;
Specifies the version number of the database monitor data to collect. must be set t o one of the following values:
T h i s parameter
SQL"DBMON-VBRSION5
DB2 Version 5.0 (or later) database monitor data is to be collected. SQLBt-DBMON-VBRSION2
DB2 Version 2.1 database monitor data isto be collected. SQLM-DBMON-mRSION1
Reserved Groupstates
SQLCA
DB2 Version 1.0 database monitor data is t o be collected. A pointer that is currently reservedfor later use. For now, this parameter must always be set to NULL. A pointer to a location in memory that contains the starting address of an arrayof six sqlm-recordingsoup structures that contain state information about each group monitor switch available. A pointer to a location in memory wherea SQL Communications Area (SQLCA) data structure variable is stored. This variable returns either status information (ifthe function executed successfully)or error information (ifthe function failed)to the calling application.
Includes
#include <sqlmon.h>
Description
The QET/UPDATE MONITOR SWTICHES function is used to selectively turn various database monitor switches (associated with information groupsthat areto be monitored) on or off and to query the database monitor for a group monitoring switch's current state. This function uses an arrayof six sqlm-recordingsoup structures to retrieve and update database monitor switch values. The sqlm-recordingsroup structure isdefined in sqlmon.h as follows: struct sqlm-recording-group {
unsigned long
input-state;
/*
Indicates whether the specified
/ * information group monitoring
*/
*/
i
'
. .
Chapter 13:Database Monitor and Indoubt Transaction ProcessingAPIs / I i
'
5 17 i
/ * switch shouldbe turned on
/*
/*
unsignedlongoutput-state;
/* /*
/* /*
/* /*
sqln-timestamp start-time;
/* /* /*
/* /* /* /*
I
(SQLM-ON) , turned off (SQLM-OFF), or left in its Current state (SQLM-HOLD) The current state ofthe specified group monitoring switch. Indicates whether the specified information group monitoring switchis currently turnedon (SQLM-ON) or turned off (SQLM-OFF). The date andtime that the specified group monitoring switch was turned on. If the specified group monitoring switch is turned off, this field is set to 0.
.
!
*/ */ */ */ */ */ */ *! */ */
*/
*/ */ */
*/ */
1;
This structure contains a reference to an additional structure, sqlmtimestamp, that stores timestamp information about whena group monitoring switch was turned on. The sqlmtimestamp structure is defined in sqlmon.h as follows: typedef struct sqln-timestamp {
unsigned long seconds:
/*
The dateandtime,expressed as the number seconds of since /* January 1, 1970 ( m ) . The of number /*elapsed 0 to /* microseconds,rangingfrom /* 999999, in the current second.
/*
unsigned long microsec;
*/ */ */ */ */ */
? sqln-timestamp;
An array of six sqlm-recordinggroup structures mustbe definedor allocated before this function is called. Ifthis function is used to set the value of one or more group monitor switches, each corresponding structure in the array must also be initialized beforethis function is invoked. After this function executes,this array will contain information aboutthe current state of each group monitor switch available. You can obtain information abouta specific group monitor switch by indexing the array with one of the following symbolic values: SQLM-UOW-SW
References unit of work (transaction) group monitor switch information. 8QI.d"STATEMEN'I-SW
References SQL statement group monitor switch information.
m SQLM-TABLE-SW References table group monitor switch information.
!
i
Part 3: Application Programming Interface Functions H SQLM-BUFFER-POOL-SW
References bufferpool group monitor switch information. SQLM-LOCK-SW
References lock group monitor switch information. SQWSORT-SW
References sort group monitor switch information. Refer to the beginning of the chapter for more informationabout the database system monitorelements associated with each of these monitoring group switches.
Comments
H
If database monitor data is to be collected for earlier versions ofDB2 (i.e., if the Version parameter is setto SQLM-DEMON-VERSIONI), this function cannot be
executed remotely. H You can use this function to query the current state of different information group switches without modifying them by specifying SQU-HOLD for the input-state element of each structure in the Group States array. H If this function attempts to obtain database monitor data for a version that is higher than thecurrent server version, only information that is valid forthe server's level will bereturned.
M For detailed informationon using the database system monitor,refer to the IBM DB2 Universal Database System Monitor Guide and Reference. Connection This function can only be called if a connection to a DB2 Database Manager Requirements instance exists. In order to obtain or set thedatabase monitor switchsettings for a remote instance (or for a different local instance), an application must first attachto that instance. Authorization Only users with System Administrator (SYSADM),System Control (SYSCTRL),or System Maintenance(SYSMAINT) authority can executethis function call. See Also
ESTIMATE DATABASE SYSTEM MONITOR BUFFER SIZE,GET SNAPSHOT,RFSET MONITOR
Example
Thefollowing C++ program illustrates how to use the OETIUPDATE MONITOR SWITCHES function to retrieve and change the current values of the database monitor group switches:
/*
/* /* /*
/* /* /* /*
NAME: CH13EXl.CPP PURPOSE: Illustrate How To Use The Following DE2 API Function In A C++ Program: OET/UPDATE MONITOR
SWITCHES
*/ */ */
*/ */ */ */ */
R I ! ,
.
I
I
Chapter 13: Database Monitor and Indoubt Transaction Processing APIs
I
li
I
! 5 19 I 1
I
/ / Include The Appropriate #include <windows.h> #include #include <sqlmon.h> #include <sqlca.h>
Header
Files
/ / Define The API-Class Class class API-Class {
/ / Attributes public: struct aqlca sqlca; / / Operations public: long aetsetMonswitches~);
1; / / Define The QetSetMonSwitchesO Member Function long API-Class::QetSetMonSwitches() {
/ / Declare The Local Memory Variables struct sqh-recording-group GroupStates[61; / / Initialize The Database Monitor Group States Array / / (Turn The Table SwitchOn, The Unit Of Work Switch Off, / / And Query The Settings Of The Other Switches) QroupStates[SQLM~UOW~SWl.input_state = SQLM-OFF; Groupstates [SQLM-STATEMEN-SW1 iUpUt-State = SQM-HOLD;
.
oroupStates[SQLM-T~LE-SWI .iIlpUt-State SQLM-ON; GroupStates[SQLM~B~FER_POOL~~].inpUt_state = SQLM-HOLD; GroupStates[SQLM~LOCK~SWl.input~state = SQLM-HOLD; GroupStates[SQLM-SORT-SW1.input-state = SQLM-HOLD; / / Set/Query The Database Monitor Switches s q l m o n ( S Q ~ - D B M O N ~ ~ R S I O N SNULL, , Groupstates, hSplCa);
/ / If The Database Monitor Switches Were Set/Queried, Display / / Their Current Values if (sqlca.sqlcode =a SQL-RC-OK)
tout << Turrent values of the Database Monitor Switches COUt << endl << endl;
cout << "nit Of Work Switch : ''; if (OroupStates[SQM~UOW~SWl.input~state == SQM-ON) cout << "ON" << endl; else cout << "OFF" << endl; cout << "SQL Statements Switch : "; if (Groupstates [SQM-STATEMENT-SW1 input-State == SQLM-ON) cout << "ON" << endl ; else
.
Part 3: Application Programming Interface Functions cout
"OFF" << endl;
cout << "Table Switch if (QroupStatestSQLM-TABLE-SWl. cout << "ON" << endl; else cout (( UOFF" << endl;
: ";
input-state5 - SQIX-ON)
--
: "; cout << "Buffer Pool Switch if ( O r o u p S t a t e s t S Q ~ B ~ F E R ~ P O O L ~ S l . i n p u t ~ s t a t SQLM-ON) e c a t << "ONtt << endl; else cout '#OFFn << endl; : "; cout << "Lock Switch if (QroupStatestSQLM-LOCK-SWl .input-state -= SQLM-ON) cout << "ON"endl; else cout << lsOFFn << endl;
cout << "Sort Switch : 1'; if (QroupStatestSQLM~S0RT-S~l.input-state =I SOW-ON) cout << #'ONn << endl; else cout UOFFU << endl; 1 / / Return The SQLCA Return return(sqlca.sqlcode)t
Code To The
Calling
Function
1
/* /* /*
*/ */ */
The xain Function
int main0 / / Declare The Local Memory Variables long rc SQL-RC-OK;
/ / Create An Instance Of The MI-Class Class API-ClassExample; / / (3et/Update Monitor Switch Values rc = Example.QetSetMonSwitches();
/ / Return TO The Operating return ( rc ) ;
System
1
l
.
'
Chapter 13:Database Monitor and Indoubt Transaction ProcessingAPIs I I
52 1
1
FW W4 RESETMONITOR Purpose
The RESET MONITOR function is used t o reset the internal database systemmonitor data monitor switchesof a specifieddatabase (or of all active databases) to zero.
syntax
int SQL--1-FN
Parameters
Version
char
Version, *Reserved, RersetAllIndicator, *DBAl.ias,
struct eqlca
*SPLCAI;
sqlmrset (unsigned long char unsigned
long
Specific version numberof the database monitor data switches to reset. T h i s parameter must be set to one of the following values: SQLM-DBMON-VERSIONS
DB2 Version 5.0 (or later) database monitor data switches are to be reset. SQLM-DBMON-VERSION2
DB2 Version 2.1 database monitor data switches are to be reset. SQLM-DBMON-VERSION1
DB2 Version 1.0 database monitor data switches are to be reset. Reserved ResetAllIndicator
A pointer that is currently reserved forlater use. For now, this parameter must always be set to NULL. Specifies whether to reset data monitor switches for a specific database or for all active databases. This parameter must be set to one of the following values: SQLM-OFF
Reset the datamonitor switchesand areas for a specific database. SQLM-ON
DBAlias
SQLCA
Reset the datamonitor switchesand areas for all active databases. A pointerto a locationin memory wherethe alias of the database whose data monitor switchesare t o be reset is stored. A pointerto a locationin memory wherea SQL Communications Area(SQLCA) data structurevariable is stored. This variable returns either status information (if the function executed successfully)or error information (if the function failed)to the calling application.
I
l
1 522 __ l
.
F 1
,
~
Part 3: Application Programming Interface Functions
Includes
#Include <eqlmon.h>
Description
The RESET MONITOR function is used to reset the internal database system monitordata monitor switchesof a specifieddatabase (or of all active databases) to zero. Whenthe data monitor switchesof a database are setto zero, the database's internal system monitor data areas are automatically cleared. These data areas include the dataareas that are used by each application connected to the database and by the database itself. Each applicationattached to a database has its own private view of database system monitordata. If an application resets or turns off a database system monitor switch, other applications are not affected.
Comments
If database monitor data switches are to be reset for earlier versions of DB2 (i.e., if the Version parameter is setto SQL~~DBW~N-VERSION~), this function cannotbe executed remotely. If this function is called with the ResetAllIndicator parameter set to SQM-ON, the value in the DBAlias parameter is ignored, and the datamonitor switches forall active databases are reset. To make global changesto a database system monitor switch, modify the settings of the monitor switch configuration parameters in the DB2 Database Manager configuration file. Referto the UPDATE DATABASE MANAGER CONFIQURATION function for more information. If all database system monitor switches forall active databases are reset, some DB2 Database Manager informationis also reset to maintain consistency withthe data thatis returned. This function cannot be used to selectively reset specific data items or monitor
groups. However,a specific monitor group can be reset by turning its switch off and then back on with the GETIUQDATE MONITOR SWITCHESfunction. For detailed information aboutusing the database system monitor,refer to the IBM DB2 Universal Database SystemMonitor Guide and Reference. This function can only be calledif a connectionto a DB2 Database Manager Connection Requirements instance exists. In order to obtain or set thedatabase monitor switchsettings for a remote instance (or for a different local instance), an application must first attachto that instance.
Authorization Only users with System Administrator (SYSADM) authority, System Control (SYSCTRL) authority, or System Maintenance (SYSMAIN")authority can execute this function call.
see Also
QET/UPDATE MONITOR SWITCHES, ESTIMATE DATAEASE SYSTEHI MONITOR BUFFER SIZE, GET SNAPSHOT
Example
"he following C++ program illustrates how to use the RESET MONITOR function to reset the database monitor group switches for the SAMPLE database:
Chapter 13: Database Monitor and Indoubt Transaction Processing APIs /* /* /* /* /*
1' 1 523 1
*/ CH13EX2.SQC PURPOSE: Illuetrate How To Use The Following DB2 API Function In A C++ P r o g r a m :
NAME:
/* /*
RESET MONITOR
/*
*/ */
*/ */ */ */ */
/ / Include The Appropriate Header Filee #include <windowe.h> #include #include <eqlmon.h> #include <eql.h> / / Define The API-Class Clase class API-Class {
/ / Attributes Public: etruct eqlca eqlca; / / Operations public : long ReeetMonitor () ;
1; / / Define The ReeetMod.tor() Member Function long API-Claes::ReeetMonitor() {
/ / Reset The Database System Monitor Data Areas For SAMPLE The / / Database eqlmreet(SQLM-D~ON-~SIONS,NULL, SQLM-OFF, "SAMPLE", breqlca); / / If The Database System Monitor Data Areas For The SAMPLE / / Database WereReset, Dieplay A Success Meeeage if (eqlca. eqlcode m= SQL-RC-OK) {
tout << "The Databaee Syetem Monitor Data Areas for "the 8 cout << "SAMPLE database have" << endl; cout << "been << endl; 1 / / Return The SQLCA Return return(eqlca.eqlcode);
CodeTo The
Calling
Function
1
/* /*
The Main Function
int main()
*/
*/
I 524 1
i l
Part 3 Application Programming Interface Functions c / / Declare The Local Memory Variables rc long = SQL-RC-OK; struct sqlca sqlca; / / Create An Instance API-ClassExample;
Of
The API-Class Class
/ / Attempt To Connect To The SAMPLE Database EXEC SQL CONNECT TO SAMPLE USER userID USING password; / / Reset The Monitors ForThe SAMPLE Database rc = Examp1e.ResetMonitor ( ) ;
/ / Issue A Rollback To Free EXEC SQL ROLLBACK;
All
Locks
/ / Disconnect FromThe SAMPLE Database EXEC SQL DISCONNECT CURRENT;
1
/ / Return TO The Operating return(rc) ;
System
ESTIMATE DATABASE SYSTEM MONITOR BUFFER SIZE The EsTImTE DATABASE SYSW MONITOR BUFFER s I m function is used to estimate the size of the buffer needed by the GET SNAPSHOT function. intSQL-API-FN
sqlmonsz
(unsignedlong char
Version, *Reserved,
*SP=, unsigned long struct sqlca
Parameters
Version
*Buffersire, *SPLCA)i
Specifies the version numberof the database monitordata to estimate the buffer sizefor. This parameter mustbe set to one of the following values: SQLM-DBMON-VERSION5
The buffer sizefor DB2 Version5.0 (or later) database monitor data ist o be estimated. SQLM-D€iIdONT_VgRSION2
The buffer sizefor DB2 Version 2.1database monitor data is to be estimated. SQLM-DBMON-VERSION1
The buffer sizefor DB2 Version1.0 database monitor data is to be estimated.
Chapter 13:Database Monitor and Indoubt Transaction ProcessingAPIs ; i I
Reserved SQLMA
Buffersize SQLCA
525
"
1
A pointer that is currently reservedfor later use. For now, this parameter must always be set to NULL. A pointer to a sqlma data structure that contains a list of objects that database monitor data is to be collected for. A pointer to a location in memory where this function is to store the estimated size of the buffer neededby the GET SNAPSHOT function. A pointer to a location in memory where a SQL Communications Area (SQLCA)data structurevariable is stored. This variable returns either statusinformation (ifthe function executed successfully)or error information (if the function failed)to the calling application.
Includes
#include <sqlmon.h>
Description
The ESTIMATE DATABASE SYSTEM MONITOR BUFFER function SIZE is used to estimate the size of the buffer needed by the GET SNAPSHOT function. You can manually calculate the size of the buffer needed by adding the sizes of the structures returned for each objectto be monitored, but you should usethis function instead, because the QET SNAPSHOT function canreturn an unknown number of data structures(if, for example, a snapshot of all active databases is requested). A special structure, sqlma, is used to pass information aboutthe list of objects that are to be monitoredto the DB2 Database System Monitor whenthis function is called. Thesqlma structure is defined in sq1mon.h as follows: typedef struct sqlma {
unsignedlong
obj-num;
sqlm-obj-struct obj-vartll;
1
/* Thenumberofobjectsthatare monitored /* to be /* An array of sqlm-obj-struct /* structures that contains /* descriptionsabout the objects /* that are to be monitored
*/ */ */ */ */ */
This structure contains an array of one or more sqlm-obj-struct structures that are used to store characteristics about each objectthat is to be monitored. Thesqlmobj-struct structure isdefined in sq1mon.h as follows: typedefstructsqlm-obj-struct {
unsigned long
agent-id;
/*
The ID of the agent that is to be monitored / * The type of objectthat is to be /* monitored /* The name of the object that is to / * be monitored
/* unsigned long
obj-typer
char
objectt361;
1 sqlm-obj-struct;
*/ */ */ */ */ */
I
i 526
g
Part 3: Application Programming Interface Functions
L _ _ _ _
Comments
B The obj-type field of each sqlm-obj-struct structure used must contain one of the
following values: SQLMA-DB2
DB2-related informationis to be monitored. SQLMA-DBASE
Database-related informationis to be monitored. B SQLWCAPPL
Application information, organized by the application ID, is to be monitored. SQLMA-AQENT-ID
Application information, organized by the agent ID, is t o be monitored. SQLMA-DBASE-TABLES
Table information fora database is to be monitored. SQLMA-DBASE-APPLS
Application information fora database is to be monitored. SQLMA-DBASE-APPLINFO
Summary application information for a database is to be monitored. SQLMA-DBASE-LOCKS
Locking information for a database is to be monitored. SQLMA-DBASE-ALL
Database related information forall active databases in the Database Manager instance is to be monitored. SQLMA-APPL-ALL
Application information forall active applicationsin theDatabase Manager instance is to be monitored. W SQLMA-APPLINFO-ALL Summary application information for all active applications in the Database Manager instance is to be monitored. B SQLW~PCS-APPLINFO-ALL
Summary DCS application information for all active applicationsin the Database Manager instance is t o be monitored. B If database monitor data ist o be collected forearlier versions of DB2 (i.e., if the
Version parameter is setto SQM-DBMON-VBRSIONI), this function cannotbe executed remotely. B Because this function generates a significant amountof overhead, you may findit more desirablet o allocate a buffer of a fixed size (than to call this function repeatedly) if the GET SNAPSHOT function is to be called several times. B If no active databases or applications are found, this function may return a buffer size of zero. Therefore, applications should verify that the estimated buffer size returned by this function is greater thanzero before allocating a buffer and calling the GET SNAPSHOT function. Ifthe QET SNAPSHOT function returns an errorbecause
P Chapter 13:Database Monitor and Indoubt Transaction ProcessingMIS
'
,
!i
! 52 7
of insuf€icient buffer space, callthis function again to determine the new buffer size requirements. W For detailed information on using the database system monitor,refer to the IBM DB2 Universal Database System Monitor Guide and Reference.
Connection This function can only be called a if connection to a DB2 Database Manager Requirements instance exists. In order to obtain buffer size information fora remote instance (or from a different local instance), an application must first attachto that instance. Authorization Only users with SystemAdministrator (SYSADM)authority, System Control (SYSCTRL) authority, or System Maintenance(SYSMAINT)authority can execute this function call.
see Also
QET SNAPSHOT,
Example
See the example provided forthe QET SNAPSHOTfunction on page 531.
QET/UPDATE
MONITOR
SWITCHES,
RESET
MONITOR
m m GET SNAPSHOT Purpose
The QET SNAPSHOT function is used to retrieve specific DB2 database monitor information and copy it t o a user-allocated data storage buffer.
syntax
int SQL-API-FN
Parameters
Version
sglmonss (unsigned long char , sqlm unsigned long void sglm-collected struct sglca
Version, *Reserved, *SQ=t
Buffersire, *Buffer, *Collected, *SQLCA);
Theversionnumber of the database monitor data to collect. T h i s parameter must be set to one of the following values: 111 SQLM-DBMON-VERSION5
DB2 Version5.0 (or later) databasemonitor data is to be collected. H SQLM-DBMON-VERSION2
DB2 Version 2.1 database monitor data i s to be collected. SQLM-DBMON-VERSION1
Reserved SQLMA Buffersize
DB2 Version 1.0database monitor data is to be collected. A pointer that is currently reservedfor later use. For now, this parameter must always be set to NULL. A pointer to a sqlma data structure that contains a list of objects that a snapshot of database monitor data is t o be collected for. The size, in bytes, of the memory storage bufferwhere this function is to store the database monitor data retrieved.
1
Part 3 Application Programming Interface Functions Buffer Collected
SQLCA
A pointer to a location in memory wherethis function is to store the database monitor data retrieved. A pointer t o the address of.ansqlm-collected structure where this function is to store summary information about each type of database monitor data thatis written to the memory storage area (Buffer). A pointer to a location in memory wherea SQL Communications Area (SQLCA)data structure variable is stored. This variable returns either status information (ifthe function executed successfully)or error information (ifthe function failed)to the calling application.
Includes
#include <sqlmon.h>
Description
The GET SNAPSHOTfunction is used to retrieve specific DB2 database monitor information and copy it to a user-allocated data storage buffer. Thedatabase monitor information returned represents a snapshot of the DB2 Database Manager's operational status at the time this function was executed. Therefore, you can only update this information by reexecuting the GET SNAPSHQT function call. A special structure ( s q l m )is used to pass information about the listof objects that are to be monitored to the DB2 Database System Monitor whenthis function is called. Refer to the ESTIMATE DATABASE SYSTEM MQNITQR BUFFER SIZE function for a detailed description of this structure. After this function is executed, summary statistics about the snapshot information that was collectedis stored in a sqlm-collected structure which is defined in sq1mon.h as follows: typedef struct sqlm-collected unsigned unsigned
unsigned
unsigned
unsigned
unsigned
long size;
/* /* /* /*
The size of the eqlm_collected
*/
structure */ Indicates whether DB2 Database long db2 : */ Manager instance information */ /* was collected in the snapshot (l), */ /* or not ( 0 ) . This field is obsolete */ */ /* in Version 5.0 and later. /* Thenumber ofdatabases */ long databases; /* that snapshot information was */ /* collected for. This field is obsolete */ /* in Version 5.0 and later. */ */ long tabledatabases; /* The number of databases /* that table snapshot information was */ /* collected for. This field is */ /* obsolete in Version 5.0 and later. */ long lock-databases; /* The number of databases */ */ /* that locking snapshot information was /* collected for. This field is */ */ / * obsolete in Version 5.0 and later. long applications; */ / * The number of applications /* that snapshot information was */
m
!
Chapter 13: Database Monitor and Indoubt Transaction Processing APIs
unsigned long applinfos; ’
unsigned long dcs-applinfos;
/* collected for. /* in Version 5.0 /* The number of
*/
/* /* /*
*/ */ */
/*
/* /*
/* unsigned long
server-&2-type;/*
/* /* /*
eqh-timestamp time-stamp; taken sq-recording-group group-~tates[61;
char
/* The current group switches /*monitoring /* servergrdid[201;
*/
char
This field is obsolete and later. applications that summary information was . collected for. This field is obsolete in Version 5.0 and later. The number of applications that DC9 eummnary information was collected for. This field ie obsolete in Version 5 .O and later. The DB2 Database Manager server type The date and timethesnapshot was
servernname
state of the information
*/ */ */
*/ */ */
*/
*/ */
*/ */ */
The product
name
and
/* number of the DB2 Database Manager the workstation / * onserver /* The workstation name 20I ; */
version
*/ */ stored in
the mente parameteroftheD82 */ Database Manager configuration */ */ /* fiie on the serverworkstation server-instance-name 1201 ; char /* The instance name of the */ Database Manager /* D82 */ reeerved[22]; /* Reserved future for use */ char unsigned shortnode-number8 / * The number o€ the node that sent the */ /*information snapshot */ long time-zone-disp; /* The difference, in eeconds. between */ /* Qreenwich Mean Time (GMT) and */ time /* local */ unsigned long nun-top-level-structs; /* Thetotalnumberofhigh-level */ /* structures returned in the snapshot */ /* output buffer. This counter replaces */ /* the individual countere (i.e.. fields /* 2 through 8 of this structure) which */ /* are obsoletein Version 5.0 and higher*/ unsigned long tablespace~databases; / * The number of databasee for which */ /* tablespaceenapshotinformation */ collected/* was */ unsigned long server-version; /* The version number of the server */ /* returning the snapshot data */ 1 sq-collected8
/* /*
“his structure contains referencesto t w o additional structures (sqlm-recordinggroup and sqlm-timestamp) that are usedto store information about the current state of specific group monitoring switches andthe exact date and time a group monitoring switch was turnedon. Refer to theQET MONITOR SWITCHESfunction for a
detailed descriptionof each of these structures. When snapshot information is collected,it is stored in a user-allocated buffer (whose address is stored in the Buffer parameter). Portions of this buffer must be typecast with specialstructures before the information collectedcan be extracted from it. For more information aboutthese structures, refer to the IBM DB2 Universal Database SystemMonitor Guide andReference.
Comments
The obj-type field of each sqlm-obj-stmt structure used in the array of structures referenced by the SQLMA parameter must contain oneof the following values: SQmDE2
DB2-related informationis to be monitored. SQLMA-DBASE
Database-related information is to be monitored. SQ-APPL
Application information, organized by the application ID, is to be monitored. SQLMAAQENl-ID
Application information, organized by the agent ID, is to be monitored.
m SQmDEASE-TABLES Table information for database a is to be monitored. SQLMA-DBASE-APPLS
Application information for database a is to be monitored. SQLMA-DBASE-APPLINFO
Summary application informationfor a database is to be monitored. SQ~-DBASE-LOCKS
Locking informationfor a database is to be monitored. SQI.t"DBASE-ALL
Database-related information forall active databases in theDatabase Manager instance is to be monitored.
m
m
SQLMA-APPL-ALL
Application informationfor all active applicationsin the Database Manager instance is to be monitored. SQLMA-APPLINFO-ALL
Summary application informationfor all active applicationsin theDatabase Manager instance is to be monitored.
m SQLMA-DCS~APPLINFO-ALL Summary DCS application information forall active applicationsin the Database Manager instance is to be monitored. If database monitor data isto be collected forearlier versions of DB2 (i.e.,if the Version parameter is setto SQLM-DEMON-VERSION~ or SQIX-DBMON-VERSIONI), this function cannotbe executed remotely.
Chapter 13: Database Monitor and Indoubt Transaction Processing MIS M
You can determine the amount of memory neededto store the snapshot information returned by this function by Calling the ESTIMATE DATABASE SYSTEM MONITOR BUFFER SIZE function. If one specific objectis being monitored, onlythe amount of memory neededto store the returned data structurefor that object needs to be allocated. Ifthe buffer storage area is not large enough to hold all the information returned by this function, awarning will be returned, and the information returned will be truncated to fit in the assigned storage buffer area. When this happens, you should resizethe memory storage buffer and call this function again.
M
No snapshot data will be returned by a request for table information if any of the following conditionsexist -The TABLE recording switchis turned off. -No tables have been accessed sincethe TABLE recording switch was turned on. -No tables have been accessed sincethe lasttime the RESET MONITOR function was called.
M If this function attempts to obtain database monitor data for a versionthat is
higher than thecurrent server version, only informationthat is valid forthe server's level will be returned.
For detailed informationabout using the database system monitor,refer to the IBM DB2 Universal Database System Monitor Guide and Reference. Connection This function can only be called if a connettionto a DB2 Database Manager Requirements instance exists. In order to obtain a snapshot of database monitor data settings for a remote instance (or for a different localinstance), an application must first attachto that instance. Authorization Only users with System Administrator (SYSADM) authority, System Control (SYSCTRL)authority, or System Maintenance(SYSMAJNT) authority are allowed to execute this function call.
see Also Example
SNAPSHOT
QET/UPDATE MONITOR SWITCRES, ESTIMATE DATABASE SYSTEM MONITOR BUFFER SIZE, RESET MONITOR
Thefollowing C++program illustrates how to use the GET SNAPSHOT function to collect snapshot information forthe SAMPLE database and the DB2 Database Manager:
/* /* /* /* /* /* /* /* /*
CH13EX3.CPP PURPOSE: Illustrate How To U s e The Following DE2 API.Functions In A C++ Program:
N A E I E :
ESTIMATE DATABASE GET
SYSTEM
MONITOR BUFFER SIZE
*/ */ */ */ */ */ */ */ */
ffer; ffePIndex;
Part 3: Application Programming Interface Functions / / Include The Appropriate #include <windows.h> #include #include #include <sqlmon.h> #include <sqlca.h>
Header
Files
/ / Define The API-Class Class class API-Class {
/ / Attributes public : struct aqlca sqlca;
1;
/ / Operations public : long GetMonSnapshotO; private : void Procese-DB2-Info(struct eqlm-ab2 *DB2Info); void Procees-DBase-Info(struct sql-abase *DBaseInfo);
/ / Define The QetMonSnapshot ( 1 Member long API-Class::OetMonSnapshot()
Function
{
/ / Declare The LocalMemory Variables char char Buffsize; unsigned long unsignedhhlDPStructs int m 0; StruCt eqlraa *eqlma; structeq-collectedCollected; sqlm-ab2 etruct *DB2Info; struct eqlm-dbase *DBaseInfo;
/ / Specify The Data Monitors To Collect Information For SUl- = (StruCt aqlma * ) malloc(SQLMASIZE(2)); sqlma->obj-num I 2; sqlma-~obj~var[01 .obj-type = SQm-DB2; etrcpy(sq1ma->obj-var[Ol.object, "SAMPLE"); sqlma->obj-var[ll .obj-type= SQLMA-DBASE; strcpy(sqlma-~obj~var[ll.object,"SAMPLE");
/ / Estimate The Size Of The Database Monitor Buffer Needed sqlmonez(SQIN~DBMON~VERSION5,NULL, sqlma, &Buffsize, &sqlca); / / If The
Database Monitor Buffer Size Was Estimated, Allocate / / Memory For It if (sqlca.sqlcode == SQL-RC-OK) Buffer = (char *) malloc(BuffSize); else goto EXIT; / / Collect
Monitor Snapshot Information
l .
,
,
/
Chapter 13: Database Monitor and Indoubt Transaction Processing APIs ,
533-
I ._-.
.~.
s q l m o n s s ( S Q ~ ~ D B M O N ~ V E R S I O NNULL, 5, sqlma, Buffsize, Buffer,
&Collected, &sqlca); / / If The Snapshot Information Was Collected, Display It if (sqlca.sqlcode == SQL-RC-OK)
i / / Add All NumStructs
P
Structures Returned In The Buffer Collected.db2 + Collected.databases + Collected.table-databases + Collected.lock-databases + Collected.applications + Collected.applinfos + Collected.dcs~applinfos+ Collected.tablespace~databasee;
/ / Loop Until All Data Structures Have Been Processed for (BufferIndex = Buffer; NumStructs > 0; NumStructs-) i
/ / Determine The StructureType switch ((unsigned char) *(BufferIndex + 4)) i / / Display Select DB2 Information Collected case SQLM-DB2-SS: DBZInfo = (struct sqlrq_dbZ * ) BufferIndex; Process~DB2~Info(DB2Info); BufferIndex +a DBZInfo->size; break;
/ / Display Select Database Information Collected case SQM-DBASE-SS: DBaseInfo = (struct sqlm-dbase *) BufferIndex; Procees-DBase-Info(DBase1nfo); BufferIndex +I DBaseInfo->size; break; / / If Anything Elee Was Collected, DisplayAn Error default : cout << "ERROR : Unexpected data in buffer." << endl; got0 EXIT; break;
EXIT : / / Free All Allocated Memory if (sqlma l = NULL) free(sqlma);
if (Buffer I = NULL)
i
j 534
,
Part 3: Application Programming Interface Functions
'
free(Buffer); / / Return The SQLCA Return return(eqlca.sqlcode);
Code To The
Calling
Function
1 / / Define The Procees-DB2-Info() Member Function void API-Class::Process-DB2-Info(struct sqlm-db2 *DB2Info) {
/ / Declare The Local Memory Variables longTime;
/ / DiSBlay The DB2 Statue Information cout << "DB2 DATABASE MANAGER STATUS INFORMATION" << endl; COUt << " cout << U " << endl; cout << "DB2 Database Manager Status 2 88 switch (DB2Info->db2-etatus)
"i
{
case SQLM-DB2-ACTIVE:
cout << "Active"endl; break; case SQI~~-DB~-QUIESCE-PEND: cout << "Quiesce Pending" << endl; break; case SQLM-DB2-QUIESCED: cout << "Quiesced" << endl; break;
1 / / Display Time Started Information Time = DB2Info->db2start~tirne.~econde; cout << "Time DB2 Database Manager Was Started : cout << ctime(&Time) << endl << endl;
'I;
/ / Display Select D82 Connection Information cout << "DB2 DATABASE MANAGER CONNECTION INFORMATION" << endlf cout << 'B cout << " << endl; cout << *#Remote Connections To The DB2 Instance : ": cout << DB2Info->rem-cons-in << endl; cout << "Local Connections To The DB2 Instance : " i cout << DB2Info-~local-cons << endl; cout << "Local Active Databases m cout << DB2Info-~con~local~dbases << endl;
. .
/ / Return To The return:
Calling
Function
1 / / Define The Process-DBase-Info() Member Function void API_Clase::Procesa_DBase-Info(struct sqlm-dbaee *DBaseInfo) {
/ / Declare The Local Memory Variables
".
F1 Chapter 13: Database Monitor and Indoubt Transaction Processing APIs
II
l
53 5 1
.- - -
..
-1
char TempStr [201; / / Display The Database Identification Information cout << "DATABASE IQOIWATIONn << endl; cout << " COUt << U << endl; cout << "Database Alias : "; etrncpy(TempStr, DBaeeInfo->input-Bb_alias, 19); TempStr[l9] = 0; cout << TempStr << endl; : 'a; cout << "Database Name etrncpy(TempStr, DBaseInfo->&name, 19); TempStr[l91 = 0; cout << TempStr << endl; : U; cout << "Database Path (Truncated) etrncpy(TempStr, DBaseInfo->&Bath, 19); TempStr[l9] = 0; cout << TempStr << endl;
/ / Display The DB2 Statue Information cout << "Current Databaee Status switch (DBaseInfo->Bb-etatus)
:
";
''1
case SQIX-DB-ACTIVE: cout << "Active1' << endl << endl << endl; break; . case SQLM-DB-QUIESCE-PEND: cout << "Quiesce Pending" << endl << endl << endl; break; case SQLM-DE-QUIESCED: cout << tlQuiescedn<< endl << endl << endl; break; 1 / / Return TO The return;
Calling
Function
1
/*
The Main Function
/*
*/
int main0
<
/ / Declare The LocalMemory Variables long rc = SQL-RC-OK; / / Create AU Instance Of The APT-Clase C l a m API-ClassExample;
/ / Collect Monitor Snapshot Information rc = Example.QetMonSnapehot ( ) ; / / Return To The operating System return(rc); 1
*/
P
I
ii
Part 3: Application Programming Interface Functions
PM
m LIST DRDA INDOUBT TRANSACTIONS
Purpose
The LIST DRDA INDOUBT TRANSACTIONS function is used to retrieve a list of all indoubt transactions that exist betweenpartner logical units (LUs) that are conneded by LU 6.2 protocol.
syntax
int SQL-API-FN sqlcepqy (SQLCSPQY-INDOUBT *TrMSaCtiOzIData, long struct sqlca
Parameters
*hQmTranrractione, *SQLCA):
TransactionData
Apointer to alocation in memorywhere this function is to store the address of a SQLCSPQY-INDOUBT structure that contains a list of DRDA indoubt transactions.
NumTransactions
Apointer to a location in memorywhere this function is to store the number of DRDA indoubt transactions found. pointer A to a location in memory where a SQL Communications Area (SQLCA) data structure variable is stored. This structure returns eitherstatus information (if the function executed successfully)or error information (if the function failed)to the calling application.
SQLCA
Includes
#include <sqlxa.h>
Description
The LIST DRDA INDOUBT TRANSACTIONS function is used to retrieve a list of all indoubt transactions that exist betweenpartner logical unites (LUs) that are connected by LU 6.2 protocol. DRDAindoubt transactions occur when communications between coordinatorsand participants in two-phase commit transactions is lost. Information obtained abouta DRDA indoubt transactionis stored in a sqlcspqyindoubt-t structure (type definedas SQLCSPQY-INDOUBT), which is defined in sqlxa.h as follows: typedef struct sqlcspw-indoubt-t
i struct eqlxa-xid-t
luwid[36] char corrtok[331; char char char char
xid;
/* The XA identifier assigned by the /* Transaction Manager that uniquely / * identifies the global transaction ; /* The logical unit workstation ID /* Coordinator token ; /* The partner [l81partner ID &name[9] ; /* The name of the database where transaction was found /* indoubt &alias L91 ; / * The alias of the database where transaction was found / * indoubt /* The rolerole; uow-status; /* Unit of work (transaction) status partner-status; /* Partner statue
char char char 1 SQLSCPQY-INDOUBT;
*/ */
*/
*/
*/ */
the */
*/
the */
*/ */ */ */
1 :
I
Chapter 13:Database Monitor and Indoubt Transaction ProcessingApIs j "
'
"
"
I
53 7
Q
This structure contains a reference to an additional structure, sqlmc_;rCid-t,which is used to store the unique XA identifier that is assigned to all transactions by the Transaction Manager. Thesqlxu-xid-t structure isdefined in s9lxu.h as follows: struct sqlxa-xid-t {
long long
formatID; gtrid-lengthj
long char data[l28]
mal-length;
>;
;
/* identifier XA format /* The length ofglobal the /* transaction identifier
/* /*
/* /*
The length of the branch identifier The global transaction identifier, followed by trailing blanks for a total of l28characters (bytes)
*/ */ */ */ */ */
*/
When this function is executed, a memory storage area that is sufficient to hold the listof DRDA indoubt transactions found is allocated and a pointer to this area is returned in theTransuctionDutu parameter.
Comments
W Before this function can be executed, an application must be connected to the Sync Point Manager (SPM)instance. This connection canbe established by using the
value of the spm-nume DB2 Database Manager configuration fileparameter in place of a database name in a CONNECT SQL statement.
Connection T h i s function can only be called if a connection to a DB2 Database Manager Requirements instance exists. Authorization Only users with System Administrator(SYSADM) authority are allowed to execute this function call. See Also
LIST INDOUBT TRANSACTIONS, COMMITAN INDOUBT TRANSACTION, ROLLBACKAN INDOUBT TRANSACTION,FORGET TRANSACTION STATUS
Example
Thefollowing C++ program illustrates how to use the LIST DRDA INDOUBT TRANSACTIONSfunction to retrieve a list of all DRDA indoubt transactions that exist for the MYDBl database:
/* /* /* /* /* /* /*
CH13EX4.SQC PURPOSE: Illustrate How To Use The Following DB2 API m c t i o n In A C++ Program:
NAME:
TRANSACTIONS INDOUBT DRDA LIST
/ / Include The Appropriate Header Files #include <windows.h> #include
*/ */ */ */ */ */ */
F1 538 1 1
Part 3: ApplicationProgrammingInterfaceFunctions
-.
#include <eqlxa.h> #include <eql.h> / / Define TheAPI-Claee Claee claee -1-Claes {
/ / Attributes public: struct eqlca sqlca;
1;
/ / Operatione public : long LietTraneactione();
/ / Define The LietTraneactioneO Member Function long API_Claee::LietTraneactione() {
/ / Declare The LocalM e m o r y Variables SQLCSPQY-INDOWT *IndoubtTrans = NULL; long MDTrane; / / Restart The MYDBl Database cout << "Reetarting the database. Please wait."<< endl << endl; eqleretd(18MYDBlw,*'ueerIDn, "paeewoda", keqlca);
/ / Retrieve AList Of All DRDA Indoubt Traneactione eqlcepqy(kIndoubtTrane, k#umIDTrans, keqlca); / / If
A Liet Of DRDA IndoubtTraneactione Wae Obtained, / / Dieplay It if (eqlca.sqlcde =I SQL-RC-OK)
c / / Dieplay InformationAbout All Indoubt TraneactioneFound for ( ; NumIDTrane 0; M D T r a n e - ) {
cout cout COUt cout cout cout cout cout cout
nTraneaction IDn << endl; Format ID : "1 IndoubtTrane->xid.formatID << -dl; QTRID Length : IndoubtTrane->xid.gtrid_length << endl; BQUAL Length : "; IndoubtTrane->xid.bqual_length << endl; e< Data : "; << IndoubtTrane->xid.data << endl << endl; << << << << << << <<
Chapter 13: Database Monitor and Indoubt Transaction Processing APIs }
." "
i I
539_1
COUt << "LUW ID : U; cout << IndoubtTrans-Pluwid << endl; COUt << 8Toordinator Token : 't; cout << IndoubtTrans-xorrtok << endl; COUt << "Partner : U; COUt << IndoubtTrane->partner << end11 cout << "Databas : 4'; COUt << IndoubtTrans->&name << endl; cout << "Alias : ": COUt << IndoubtTrane->&alias << endl; : U; COUt << "Role COUt << IndoubtTrans->role << endl; : 8'; COUt << "status cout << IndoubtTrans->uaw_statua << endl; Status : "; cout << "Partner COUt << IndoubtTrane->partner-status << endl << endl; IndoubtTrane++;
1
EXIT : / / Return The SQLCA Return return(sqlca.sqlcode);
Code To The Calling
Function
1
*/
/*
/*
*/
The Main Function
int main( )
E
/ / Declare The LocalMemory Variables rc = SQL-RC-OK; long strllct eqlca sqlca; / / Create An Inetance Of The MI-Class Class m ~ _ C l a s s Example:
/ / List All DRDA Indoubt TransactioneF O W d
rc
P
gxample.ListTransactions0;
/ / Issue A Rollback TO Free All Locks EXEC SQL ROLLBACK; / / Disconnect FromThe MYDBl Database CURRENT; EXEC SQL DISCONNECT
1
/ / Return To The Operating )(rc ; return
System
i l
p " "
Part 3: Application Programming Interface Functions
.. .
LIST INDOUBT TRANSACTIONS Purpose syntax
The LIST INDOUBT TRANSACTIONSfunction is used t o retieve a list of all indoubt transactions that exist for the current connected database. SQL-API-FN int
sqlxphqr (int SQ-RECOVER long structsqlca
Parameters
RequeBtNode, **TranBactionData, *NhmTranBactione, *SQLCA);
Specifies the node to list indoubt transactions for. This parameter must be set to one of the following values:
RequestNode
SQLXA-BXE-THIS-NODE
List indoubt transactions found on the node from which this function was called. SQLXA-EXE-ALL-NODES
L i s t indoubt transactions found in all nodes (in a multi-
node datatbase environment). A pointer to a location in memory wherethis function is to store the address of an sqlxa-recover-t structure that contains a list of indoubt transactions. A pointer to a location in memory wherethis function is to store the number of indoubt transactions found.
TkansactionData
Numl'kansactwns
A pointer to a location in memory wherea SQL Communications Area(SQLCA) data structurevariable is stored. T h i s variable returns either status information (if the function executed successfully)or error information (if the function failed) to the calling application.
SQLCA
Includes
#include <sqlxa.h>
Description
The LIST INDOUBT TRANSACTIONSfunction is used to retrieve a list of all indoubt transactions that exist for the currently connected database. Information obtained about an indoubt transaction is stored in an sqlxa-recover-t structure (type defined as SQLXA_RECOVER),which is defined in s9lxa.h as follows: typedef etruct sqlxa-recover-t
unsigned long timestamp:
struct sqlxa-xid-t xid;
char
dbalias[El ;
/* /* /*
The date and timewhen the transaction entered the indoubt state / * The XA identifier assignedby the /* Transaction Manager that uniquely /* identifies the global transaction /* The alias of the database where
*/ */
*/ */ */ */ */
I ,
Chapter 13: Database MonitorandIndoubtTransactionProcessing
APIs
I
I
54 1 . I. .
"
-
. ..
the indoubt transaction was found */ The application identifier assigned */ / * to thistransaction by the Dl32 */ Manager / * Database */ sequence-n0[4] ; */ /* The sequencenumberassigned as */ /* an extension to theapplication */ /* identifier by theDB2Database */ /* Manager */ auth-id [E]; /* The authorization ID o f the user */ /* who initiated this transaction */ log-full; /* Indicates whether the transaction */ /* caused a LOG FULL condition to occur */ /* (SQLXA-TRUE) or not (SQLXFALSE) */ connected; /* Indicates whether the transaction is */ /* undergoing nonnal syncpoint processing */ /* and is waiting for the second phaseof*/ /* a two-phase commit (SQLXA-TRUE) or the */ /* transaction was left indoubt by an */ /* earlier failure and is awaiting a */ /* resync from the Transaction Manager */ /* (SQLXA-FALSE) */ indoubt-status; */ /* Indicateswhether the transaction */ /* has been prepared (SQLXA-TS-PREP), */ /* heuristically colnmitted (SQLX?+-TS-HCOM),*/ /* heuristically rolled back */ /* (SQLXA-TS-HROL), idle (SQLXA-TS-END), */ /* missing commit acknowledgement */ /* (SQLXA-TS-MACK), prepared and */ /* heuristically committed (SQLXA-TS-PHC),*/ / * preparedand ( SQLXA-TS-PHR) , */ /* heuristically rolled back heurietically*/ /* committed and heuristically rolled */ /* back (SQLXA-TS-HCHR). or prepared, */ /* heuristically committed, and */ /* heuristically rolled back(SQLXA-TS-PHCHR) */ originator; /* Indicates whether the transaction was */ */ /* originated by XA (SQLXA-ORIG-XA) or */ / * by DB2 in a MPP / * environment (SQLXA-ORIG-PE) */ r e s e ~ ~ 9 1 ;/* The first byte o f this field */ /* indicatestheindoubttransaction */ /* type; the rest of this field is set */ / * to zeros */
/*
char
char
char char
char
char
char
char
applid[32];
/*
1 SQLXA-RECOVER;
This structure contains a reference to an additional structure, sqlxasid-t (type defined as sqlxa-tid) which is used to store the unique XA identifier that is assigned to all transactions by the Transaction Manager. Refert o the LIST DRDA INDOWT TRANSACTIONS function for a detailed description of the sqlxa_xid-t structure. When this function is executed, a memory storage area that is sufficient to hold the listof indoubt transactions found is allocated by DB2 and a pointer to this area is returned in the TransactionData parameter.
i I
Comments
H The memory that is allocated by this function is released automatically when the
application that called this function terminates. Do not use the FREE MEMORY function to free this memory, becausethis function contains pointersto other dynamically allocatedstructures that will not be freed by the FREE MEMORY function. H The maximum valuethat &c be specified for boththe &rid-length and bqual-length fields of the s q h s i d - t structure is6 4 . For detailed informationon using two-phasecommits and indoubttransaction recovery, refer to the IBM DB2 Universal Database Administration Guide.
Connection This function can only be called if a connection to a database exists. Requirements Authorization Only users with either System Administrator(SYSADM) authority or Database Administrator (DBADM) authority can executethis function call. See Also
C m I T AN INDOUBT TRANSACTION,ROLLBACK AN INDOUBT TRANSACTION,FOROET TRANSACTION STATUS
Example
Thefollowing C++ program illustrates how to use the LIST INDOUBT TRANSACTIONS function to retrieve a list of all indoubt transactions that exist forthe MYDBl database (this example was createdand tested on the AIX operating system):
/* /*
/* /* /*
/* /*
N m : CH13EX5.SQC PURPOSE: Illustrate How TO Use The Following DB2 API Function In A C++ Program: LIST
INDOUBT
TRANSACTIONS
*/ */
*/
*/ */ */
*/ */
/*
/ / Include The Appropriate #include 4ostream.b #include <sqlenv.h> #include <sqlxa.h> #include *sql.h,
Header
/ / Define The API-Class Class class -1-Clase / / Attributes public: struct sqlca eqlca; / / Operations public : long ListTraneactions();
Files
/ / Define The ListTransactionsO Member Function long API_Clase::ListTransactions()
i
/ / Declare The Local Memory Variables SQLXA_RECOVER *IndoubtTrans = NULL; long Nunumrans; / / Restart The MYDBl Database << endl << endl; cout << **Restarting the database. Please wait." sqleratd(94YDB1~1,"userID", "pass~ord"~srsqlca);
/ / Retrieve A ListOf All Indoubt Transactions sqlxphqr(SQLX9_EXE-THIS-NODE, sIndoubtTrans, BNumIDTrans, &sqlca); / / If A List of Indoubt Transactions wasObtained. Display It if (sqlca.sqlcode == SQL-RC-OK)
I / / Display Information About~ l Indoubt l Transactions Found for (; NunuDTrans > 0; NumImrans--)
tout << "Transaction ID" << endl; Format ID : m; cout << cout << IndoubtTrans->xid.formatID << endl; GTRIDLength : "; cout << cout << IndoubtTrans->xid.gtrid-length << endl; cout (< BQUALLength : ;*, cout << IndoubtTrans->xid.bqual-length << endl; cout << '8 Data : ; cout << IndoubtTrans->xid.data << endl << endli : tt; cout << '"Database cout << IndoubtTrans->dbalias << endl; : "; COUt << "AppliCatiOn ID cout << IndoubtTrans->applid << endl; cout << "Timestamp II . cout << IndoubtTrans->timestBmp << endl; : 'a; cout << "Sequence No. cout << IndoubtTrans->sequence-no << endl; cout << "Authorization ID : ' I ; cout << IndoubtTrans->auth-id << endl; COUt << "Log Full : U; if (IndoubtTrans->log-full == SQLXA-TRUE) cout << V a s " << endl; else cout << "No" << endl; I,
. .
Part 3: Application Programming Interface Functions
1
1
cout << UConnected : "; if (InUoubtTrans->connected == SQLXA-TRUE) cout originator m= SQLXA-ORICIPE) cout << "DB2" << endl; else cout << "XA" << enUl; cout << Ustatus : "; endl << endl; cout << IndoubtTrans->indoubt-status InddtTrans++;
EXIT :
/* /* /*
*/
*/
W e Main Function
*I
int main ( 1 i / / Declare The LocalMemory Variables rc long SQL-RC-OK; struct sqlca sqlca;
-
/ / Create An Instance Of The API-Class Class API-ClassExample;
-
/ / List ~ l Indoubt l Transactions Found rc Example.ListTransactions~); / / Issue A Rollback To Free EXEC SQL ROLLBACK;
All
Locks
/ / Disconnect From TheMYDBl Database EXEC SQL DISCONNECT CURRENT;
1
/ / Return To The Operating return(rc) ;
System
COMMIT A N INDOUBT TRANSACTION The COMMIT AN INDOUBT TRANSACTION function is used to heuristically commit an indoubt transaction.
Chapter 13:Database Monitor and Indoubt Transaction Processing APIs ; I syntax
Parameters
int SQL-API-FN
RequestNode
eqlxphcm (int
545
___ - _ -
1
ReweStNode,
SQLXl-XID
*TransactionID,
struct eglca
*SQLCA);
Specifies which node to heuristically commit indoubt transactions for. This parameter must be set to one of the following values: SQLXS_EXE_THIS-NODE
Heuristically commit indoubt transactions on the node from which this function was called. SQm-EXE-ALL-NODES
Heuristically commit indoubt transactions on all nodes (in a multi-node database environment). TransactionID A pointer to a location in memory where the XA identifier of the indoubt transaction to be heuristically committed is stored.
SQLCA
A pointer to a location in memory where a SQL Communications Area (SQLCA) data structure variable is stored. This variable returns either status information (if the function executed successfully) or error information (if the function failed) to the calling application.
Includes
#include <eplxa.h>
Description
The COMMIT AN INDOUBT TRANSACTIONfunction is used to heuristically commit an indoubt transaction. If this function is successfully executed, the specified transaction’s state becomes “Heuristically Committed.” When a transaction is initiated, the transaction is assigned a unique XA identifier by the Transaction Manager (which is then used to globally identify the transaction). This unique XA identifier is used to specify which indoubt transaction this function is to heuristically commit. Refer to the LIST DRDA INDOUBT TRANSACTIONS function for a detailed description of the XA identifier structure (sqlxa-xid-t).
Comments
W The maximum value that can be specified for both the gtrid-length and the
bqual-length fields of the sqlxajid-t structure is 64. W You can obtain sqlxajid-t structure information for a particular transaction by
calling the LIST INDOUBT TRANSACTIONS function. W Only transactions with a status of “Prepared”or ”Idle” can be placed in the ”Heuristically Committed” state. The Database Manager remembers the state of an indoubt transaction, even after the transaction has been heuristically committed, unless the FORGET TRANSACTION STATUS function is executed. Connection This function can only be called if a connection to a database exists. Requirements
L546 -___-
Part 3: Application Programming Interface Functions
Authorization Only users with either System Administrator (SYSADM)or Database Administrator (DBADM) authority are allowed to execute this function call. see Also
LIST INDOUBT TRANSACTIONS,ROLLBACK TRANSACTION STATUS
Example
The following C++ program illustrates how to use the COMMIT AN INDOUBT TRANSACTION function to heuristically commit an indoubt transaction (this example was created and tested on the AM operating system): /*
/*
/*
AN
INDOUBT TRANSACTION,FOROBT
CH13EX6.SQC PURPOSE: Illuetrate How To Wee The Following DB1 API Functione In A c++ Program:
NAMg:
/* /*
*/ */
*/
I*
/* /* /*
*/
COMMIT AN INDOUBT TRANSACTION FORGET TRANSACTION STATUS. OTAER DB2 APIe SHOWN: LIST INDOUBT TRANSACTIONS
*/ */ */ */
*/
*/
/*
*/
/ / Include The Appropriate Header Filee #include #include <eqlenv.h> #include <eqlxa.h> #include <eql.h> / / Define The API-Claee Claee claee -1-Claee i / / Attributes public: etruct eqlca eqlca; / / Operatione public: long CommbitIDTraneactionO;
1; / / Define The CommitIDTraneactionO Member Function long API_Claea::C~tIDTraneaction() {
/ / Declare The Local Memory Variables SQLXA_RECOVER *IndoubtTrane I NULL; long NumIDTrane; / / Restart The MYDBl Database cout ** YRestarting the databaee. Pleaee wait." <* endl << endl; aqleretd('%YDB1'8, "ueerIDtt,n 9 a ~ e ~ r d nsreqlca); .
/j
Chapter 13: Database Monitor and Indoubt Transaction Processing APIs / / If UnableTo Restart / / And Exit
The Database, Display An Error
if (sqlca.eqlcode I= SOL-RC-OK
h&
547
Meeaage
eqlca.eqlccn¶e I= 1061)
{
1
tout << UERROR : Unable to reetart the MYDBl databaee."; endl; cout goto EXIT;
/ / Retrieve AList Of All Indoubt Transactions eqlxphpr(SQLXA-~-TIIIS-NODE, hIndoubtTrane, hr?umIDTrane, heqlca) ;
/ / If A ListOf Indoubt Traneactione Wae Obtained if (eqlca.eqlcode = m SQL-RC-OK)
...
{
/ / Dieplay Information About The Firet Indoubt / / Found c a t << UTraneaction ID" << endl; cout << Format ID : a'; cout << IndoubtTrane->xid.formatID << endl; COut << U GTRID'Length : '); cout << IndoubtTrane->xid.gtrid-length << endl; cout << BQUAL Length : "; cout << IndoubtTrane->xid.bqual-length << endl; cout << Data : '; cout << IndoubtTrane->xid.data << endl << endl; / / Heuretically
Traneaction
Commit The Firet Indoubt Traneaction Found hIndoubtTrane->%id, heqlca);
eqlxphcm(SQW[ICgXE_TIIIS-NODE,
/ / If The Indoubt Traneaction Wae Heuretically / / Dieplay,A Succeee Meeeagea d Forget It if (eqlca.eqlcode == SQL-RC-OK)
Committed,
c cout << "Transaction hae been c a t << endl;
heureticallycommitted.";
/ / Forget The Heuretically Committed eqlxhfrg(hIndoubtTrane->xid, eeqlca);
1
1
Indoubt
/ / If The Indoubt TransactionWas Forgotten. Dieplay A / / Succeee Meeeage if (eqlca.eqlcode P= SQL-RC-OK) cout << "Transaction hae been forgotten.n<< endl;
EXIT :
1
Traneaction
/ / Return The SQLCA Return return(sqlca.eqlcode)i
Code To The
Calling
Function
Part 3: Application Programming Interface Functions ~_____
/*
*/
The min Function
*/
/* int main( )
c / / Declare The Local Memory Variables rc long = SQL-RC-OK; struct sqlca sqlca;
/ / Commit The First Indoubt Transaction Found rc = Example.CommitIDTransaction(); / / Issue A RollbackTo Free EXEC SQL ROLLBACK;
All
Locks
/ / Disconnect From The MYDBl Database EXEC SQL DISCONNECT CURRENT;
1
/ / Return To The return(rc) 1
Operating
system
ROLLBACK AN INDOUBT TRANSACTION purpose
syntax Parameters
The ROLLBACK AN INDOUBT TRANSACTIONfunction is used to heuristically roll back an indoubt transaction. SQL-API-FN int sqlxphrl (int
RequestNode
RequewtNdle, *TranaactionID, SQLXA-XID struct sqlca *SQLCA);
Specifies which node to heuristically roll back indoubt transactions for. T h i s parameter must be set to one of the following values: H SQLXA-EXE-THIS-NODE
Heuristically roll back indoubt transactions on the node from which this function was called. H SQLXA-EXEXL-NODES
Heuristically roll back indoubt transactions on all nodes (in a multi-node database environment).
TransactionID A pointert o a location in memory wherethe XA identifier of the indoubt transaction to be heuristically rolled backis stored. SQLCA Apointer to alocation in memorywherea SQL Communications Area (SQLCA) data structure variable is stored. This variable returns
Chapter 13:Database Monitor and Indoubt Transaction ProcessingAPIs ' i "
"
I
549 -
either statusinformation (if the function executed successfully)or error information (ifthe function failed)to the calling application.
Includes
#include <splxa.h>
Description
The ROLLBACK AN INDOUBT TRANSACTION function is used to heuristically roll back an indoubt transaction. If this function is successfully executed,the specified transaction's state becomes "Heuristically RolledBack." When a transaction is initiated, thetransaction is assigned a unique XA identifier by the Transaction Manager (whichis then used to globally identify the transaction). This unique XA identifier is used to specify which indoubt transaction this function is to roll back. Refer to the LIST DRDA INDOUBT TRANSACTIONSfunction for a detailed description of the XA identifier structure (sqlxu;cid_t).
Comments
R The maximum value that can be specified for both the gtrk-length and the bqual-length fields of the sqlxa-xid-t structure is64.
You can obtainsqlxu;2id-t structure information fora particular transaction by calling the LIST INDOUBT TWSACTIONS function. Only transactions with a statusof "Prepared" or "Idle" can be placed in the "Heuristically Rolled Back" state. The Database Manager remembers the stateof an indoubt transaction, even &r the transaction has been heuristically rolled back, unless the FORQET TRANSACTION STATUS function is executed.
Connection This function can only be called if a connection to a database exists. Requirements Authorization Only users with either System Administrator(SYSADM) authority or Database Administrator (DBADM) authority areallowed to execute this function call. See Also
COMMIT AN INDOUBT TRANSACTION,LIST INDOUBT TRANSACTIONS,FORGET TRANSACTION STATUS
Exkple
Thefollowing C++ program illustrates how to use the ROLLBACK AN INDOUBT TRANSACTION function to heuristically rollback an indoubt transaction (this example was created andtested on the AD(.operating system):
/* /* /* /* /* /* /* /* /* /* /* /*
NAMg : CH13EX7. SQC PURPOSE: Illustrate How To Use The Following DB2API Functions In A C++ Program: ROLL BACK A N INDOUBT TRANSACTION FORQET TRANSACTION STATUS
OTHER DB2 APIB SHOWN: LIST INDOWT TRANSACTIONS
*/
*/ */ */ */ */ */ */
*/
*/ */ */
Piles
%
/ / Operations
ollbac~ID~ran~action():
3: ::Rollbac~I~Transaction() %
a
Variables = NULL;
tart The Databaee, Display
3 Of TBI
%
<< Ind cout << cout << I cout << If tout
Chapter 13: Database Monitor and Indoubt Transaction Processing APIs I ,
'L 55" 1 I
cout << Data : "; cout << IndoubtTrans->xid.data << endl << endl; / / Heurstically Roll Back The First Indoubt Transaction Found Sqlxphrl(SQLxA-EXE-~IS_NODE, eIndoubtTrans->xi& &sqlca); / / If The Indoubt Transaction Was Heurstically Rolled Back, / / Display A Success Message And Forget It if (sqlca.sqlcode E= SQL-RC-OK) {
tout << UTraneaction
has
been
heurstically
rolled back.";
cout << endl; / / Forget The Heurstically / / Transaction
Rolled Back Indoubt
sqlxhfrg(&In~oubtTrans->xid,Psqlca); / / If The Indoubt
Transaction Was Forgotten, Display A / / Success Message if (sqlca.sqlcode == SQL-RC-OK) cout << atTransaction has been forgotten." << endl;
EXIT:
1
/ / Return TheSQLCA Return return(sqlca.sqlcode);
CodeTo The
Calling
Function
~ _ _ _ _
Main
/* /*
*/
The
*/
int main() {
/ / Declare The Local Memory Variables rc long = SQL-RC-OK; struct sqlca sqlca; / / Create An Instance Of The API-Class Class API-ClassExample;
/ / Roll Back The First Indoubt Transaction Found rc I Example.RollbackIDTransaction0; / / Issue EXEC SQL
A Rollback To Free ROLLBACK;
/ / Disconnect FromThe MYDBl EXEC SQL DISCONNECTCURRENT;
1
All
Locks
Database
/ / Return To The Operating System return(rc);
m
i
I
Part 3: Application Programming Interface Functions
FM !W FORGET TRANSACTION STATUS Purpose
The FORQET TRANSACTION STATUS function is used to tellthe Transaction Manager (or Resource Manager)to erase knowledge of an indoubt transaction that has been heuristically committed with the COMMIT AN INDOUBT TRANSACTIONfunction or heuristically rolled back withthe ROLLBACK AN INDOUBT TRANSACTION function.
Syntax
int SQL-API-FN
eqlxhfrg (eqlxa_xid-t struct eqlca
*TransactionID, *SQLCA);
Parameters
TkansactwnID A pointer to a location in memory where the XA identifier of the indoubt transaction to be erased is stored. SQLCA A pointer to a location in memorywhere a SQLCommunications Area (SQLCA)data structurevariable is stored. This variable returns either statusinformation (if the function executed successfully)or error information (if the function failed)t o the calling application.
Includes
# i n calqu1dxea . b
Description
The FORQET TRANSACTION STATUS function is used to tell the Transaction Manager (or Resource Manager)to erase knowledge of ai indoubt transaction that hasbeen placed in either the“Heuristically Committed” or “HeuristicallyRolled Back”state. Indoubt transactions can be placed in either of these states when the COMMIT AN INDOUBT TRANSACTIONfunction or the ROLLBACK AN INDOUBT TRANSACTION function is executed. When a transaction is initiated, the transaction is assigned a unique XA identifier by the Transaction Manager (whichis thenused to globally identify the transaction). This unique XA identifier is used to specify which indoubttransaction this function is to erase. Refer to the LIST DRDA INDOUBT TRANSACTIONSfunction for a detailed description of the XA identifier structure (sqlxa-xidt).
Comments
R Only transactions with a status of “Heuristically Committed”or “Heuristically
Rolled Back”can be processed by this function.
Connection This function can only be called if a connection to a database exists. Requirements Authorization Only users with either System Administrator(SYSADM) authority or Database Administrator (DBADM) authority can executethis function call. See Also
LIST INDOUBT TRANSACTIONS,COMMIT AN INDOUBT TRANSACTION,ROLLBACK AN
INDOUBT TRANSACTION
Example
See the examplesprovidedfor the COMMIT AN INDOUBT TRANSACTIONfunction on page 546 and ROLLBACK AN INDOUBT TRANSACTION function on page 549.
ext
By default, all DB2 database access acquired by threaded applications is serialized. That is, if one thread attempts to perform a database operation that is blockedforsome reason (usually because a requested table has beenlockedfor“exclusive”by another application), all other.threads are blocked as well-even if those threads access other unlocked tables. Additionally, by default, all threads within a process share a common commit scope. Thus,two or more threads can only accessa database concurrentlyif each thread runs under a different process-or if each thread runs under a Merent context. This chapter is designed to introduce you to the setof DB2API functionsthat are used to allocate andmanipulate separate contexts(environments) that enable two or more threads within an application to access a database concurrently. Thefirst part of this chapter provides a general discussionabout threads andcontexts.Then, a detailed reference sectioncovering each DB2 API function that can be used vided.
I 554 jj
Part 3: Application Programming Interface Functions
Contexts As mentioned earlier, a context is simply an environment that enables two or more threads to run concurrently. Each contextis a separate entity, and any connection or attachment made to a database or to a DB2 Database Manager instance within a context is isolated (and independent) from any connection or attachments made within other context&Once allocated, a context is virtually useless until thecontext has been associated with(attached to)a thread. Likewise a thread must be associated witha context before it can execute SQL statements or DB2 API function calls. By default, all threads within a process (the primary thread of the application)share thesame context and the same commit scope. However, if the CREATE AND ATTACH TO AN APPLICATION CONTEXT function is called fromwithin a thread, that thread will haveits own context and its own commit scope. Once created, contexts remain available for use until they are explicitly destroyed by the DETACH AND DESTROY APPLICATION CONTEXT function. In addition, contexts do not havet o be associated witha given thread for the duration of a connection to a database or an attachment to a DB2 Database Manager instance. In fact, one thread can attach to a context, establish a connection or instance attachment, and then detach from the context. Anotherthread can then attachto the same contextand begin doing work using the connection or instance attachment that was establishedby the first thread. In this manner, contexts canbe passed around among threads within a given process (but not among threads indifferent processes).
NOTE: Even when contextsare used, the followingDB2 API functions will continue to run serialized: PmzcomILE PROORAM, BIND, IMPORT, and EXPORT.
i!!!!! The DB2 Thread Context
Management Functions Table 14-1 lists the DB2 API functions that are used to allocate and manipulate separate contexts that enable threads within an application to access a database concurrently. Each of these functions are described in detail in theremainder of this chapter.
Chapter 14: Thread Context ManagementFunctions Table 14-1
SET
DB2 Thread ContextManagementFunctions
APPLICATION
CONTEXT
Identifies the type of context that amulti-threaded application willuse to process threads.
TYPE
CREATE AND ATTACH TO AN APPLICATION
CONTEXT Creates an application context, or creates and then
attaches to an application context. DETACH AND DESTROY APPLICATION CONTEXT
Makes thecurrentthread stop wing a specified context and frees all memorg associatedwith that context.
ATTACH CONTEXT TO
Makes a current thread use the
DETACH PROM CONTEXT
Makes the current thread stop using a specified context.
GET &JRRENT CONTEXT
Gets the context that the current thread ie attached
INTERRUPT CONTEXT
Sends interrupt an
specified context.
to.
to the specified context.
L556
!I
Part 3 Application Programming Interface Functions
!
SET APPLICATION CONTEXTTYPE Purpose
syntax Parameters
The SET APPLICATION CONTEXT TYPE function is used to identify the type of context a multi-threaded applicationis to use to process threads. eqleSetTypeCtx int
Contextnpe
(long
ContextType);
Specifies the type of context that all threads in an application are to use. This parameter must be set to one of the following values: SQL-CTX-ORIGINAL
All threads will usethe same context,and concurrent database access will not be allowed. This is thedefault value used. SQL-CTX-MULTI-MAL
All threads w l iuse separate contexts, and it is up to the application to manage the context for eachthread.
Includes
#include a q 1 . b
Description
The SET APPLICATION CONTEXT TYPE function is used to identify the type of context that a multi-threaded application will use to process threads. T h i s function shouldbe the f i r s t DB2 A P I function calledin a multi-thread application.
Comments
M The following restrictions apply when this function is called with the Conteztope
parameter set to SQL-CTX"ULTI"ANWAL: When termination is normal, automatic commit is disabled. Therefore, all commits must be done explicitly.At process termination, all outstanding transactions are rolled back. M The INTERRUPT function interrupts all contexts used. In order to interrupt a single context,the INTERRUPT CONTEXT function must be used instead. M The scopeof this function is limited to the currentprocess. W This function has no effect whenit is executed on platforms that do not support
application threading.
Connection This function can be called at any time.; a connection to a DB2 Database Manager Requirements instance or to a DB2 database does not haveto be established k t . Authorization No authorization is required to execute this function call. See Also
CREATE AND ATTACH M AN APPLICATION CONTEXT,ATTACH TO CONTEXT,DETACHAND DESTROY APPLICATION CONTEXT,DETACH FROM CONTEXT,INTERRUPT CONTEXT
Example
Thefollowing c++program illustrates how to use the SET APPLICATION CONTEXT TYPE function to identify the type of context a multi-threaded application willuse to process threads:
'
;
Chapter 14: Thread Context Management Functions
CH14EXl.CPP
,
/* /*
/* /*
I
; ! ~
.
557
NAME: PURPOSE: Illustrate How To Use The Following DB2 API Function In A C++ Program:
TYPE /*
*/
*/ */ */
*/
CONTEXT APPLICATION SET
*/ */
/*
/* / / Include The Appropriate Header Files #include <windows.h> #include <process.h> / / -beginthreadO, -endthread() #include <staaef.h> #include <stdlib.h> #include #include #include <sql.h> #include <splenv.h> #include <sqlca.h> / / Define The Thread Function Prototypes void CheckKey(voi8 *Dummy)# void QetInstance(v0id *Count);
/ / Declare The GlobalMemory Variables BOOLContinueThread = TRW; / / End ThreadFlag 191 ; / / Current Instance char Instance
/* /*
*/ The Main Function
/*
*/ */
int main() / / Declare long rc char Counter
The
LocalMemory Variables
= SQL-RC-OKI E 0;
/ / Set The Application Context / / Use The Same Context)
Type To N o m 1 (All Threads Will
eqleSetTypeCtx(SQL_CTX-ORIQINAL)# / / Launch TheChecMeyO Thread To Check / / Keystroke -beginthread(CheckKey, 0, NULL); / / Loop Until CheckKey( ) Thread while(C0ntinueThread =I T R W )
For
Terminates
A
The
Terminating
Program
{
/ / Launch np To Ten QetInatanceO Threads if (Counter < 10) -beginthread(QetInstance, 0, (void *) (Counter++))# / / Wait One Second s1eep(1000L)#
Between Loop Pasees
Part 3 Application Programming Interface Functions / / Display The Current Value Of The DB2INSTANCE Environment / / Variable cout << "Current value of the DB2INSTANCE environment << Instance << endl; cout << "variable :
1 / / Return TO The return(rc);
Operating
System
1 / / Define The CheckKey( ) Thread void CheckKey(void *Dummy)
Function
{
/ / Wait For A Keystroke -getch( 1 i / / Set The / / End
ContinueThread FlagSo The QetInstanceO Threads Will
ContinueThread = FALSE; / / Terminate This Thread gndthread ( ) t
1 / / Define The GetInstance() Thread Function void &tInstance(void *Count)
I
/ / Declare The LocalMemory Variables struct eqlca sqlca; / / Loop Until CheckKeyO Thread Terminates The Program while(ContinueThread I= T R W )
I / / Pause Between Loops Sleep(100L);
/ / Obtain The / / Variable
Current Value O f The DB2INSTANCE Environment
sqlegins(Inetance, Bsqlca); Instance[8] = 0; / / If The Current Value Of The DBSINSTANCE Environment / / variable WasNot Obtained, Clear The nemory Storage Area if (sqlca.eqlcode l = SQL-RC-OK) InstancetOl = 0;
/ / Beep To Signal The LoopIs Still Running Beep(1000, 175);
1 / / Terminate The Thread -endthread( ) ;
1.
Chapter 14: Thread Context Management Functions
CREATE AND ATTACH TO AN APPLICATION CONTEXT "he CREATE AND ATTACH TO AN APPLICATION CONTEXT function is used to either create an application contextor to create and then attach to an application context.
Purpose syntax
(void long void etruct eplca
eqleBeginCtx int
Parameters
Context
Action
**Context, Action, *Reserved, *SQLCA)i
A pointer to a location in memorywhere this function is to store the starting address of a datastorage area that is to be used to store context information. Specifies the action that this function is to perform. This parameter must be set to one of the following values: SQL-CTX-CREATE-ONLY
Allocate context memory withoutattaching to the currentthread. SQL-CTX-BEGIN-ALL
Allocate context memoryand attach to the currentthread. Reserved SQLCA
A pointer that, at this time, is reservedfor later use. For now, this parameter must always be set t o NULL. A pointer to a location in memorywhere a SQL Communications Area (SQLCA)data structurevariable is stored. T h i s structure returns either statusinformation (ifthe function executed successfully) or error information (if the function failed)to the calling application.
Includes
#include <epl.h>
Description
"he CREATE AND ATTACH TO AN APPLICATION CONTEXT function is used to either create an application contextor to create and then attachto an application context. Once a thread attachesto an application context, all subsequentdatabase operations performed on that thread areno longer serialized withother threads.
Comments
More than one application context can be created. Each contexthas its own commit scope. R Different threads can attach t o different contexts. 8 If this function is called withthe Action parameter set to SQL-CTX-BEGIN-ALL, the Context parameter can containa NULL pointer. B If this function is called withthe Action parameter set t o SQL-CTX-BEGIN-ALL when the current thread is already attached to a context, an error will occur.
Part 3: Application Programming Interface F'unctions M The scopeof this function is limited to the currentprocess. M This function has no effect whenit is executed on platforms that do not support application threading.
Connection This function can be called at any time; connection to a DB2 Database Manager Requirements instance or to a DB2 database does not haveto be established first.
Authorization No authorization is required to execute this function call. See Also
ATTACH TO COhlTEXT,DETACH AND DESTROY APPLICATION CONTEXT
Example
Thefollowing C++ program illustrates how to use the CREATE AND ATTACH TO APPLICATION CONTEXT function to create a new application context:
CHlQEX2.CPP
AN
*/
/*
/*
/* /* /* /* /* /* /*
*/ */ */
NAME: PURPOSE: Illustrate How To Use The Following DB2 API Function In A C++ Program:
*/
*/ */ */
CREATE AND ATTACH TO AN APPLICATION CONTEXT ATTACH TO CONTEXT
*/
/ / Include The Appropriate #include <windows.h* <process.h> #include #include <etdde€.h, #include *stdlib.h* #include *conio.h, #include #include <eqlenv.h> #include <splca.h*
Header
Files / / -beginthread , ( ) , -endthread.
o
/ / Define The Thread Function Prototypes void CheckRey(void *Dummy); void QetInetance(void *Count); / / Declare The QlobalMemory Variables BOOL ContinueThread = TRW; / / End Thread Flag char Instance 191 ; / / Current Instance void *ContextData P NULL; / / Context Data Storage Area
/* /* /*
*/ */ */
The Main Function
int main0
I / / Declare SQL-RC-OX; rc long char Counter
The
LocalMemory Variables = 0;
Chapter 14:Thread Context Management Functions / / Set The Application Thread Context Type To Manual sqleSetTypeCtx(SQL-CTX_~TI-~AL);
/ / Launch The CheckKey( ) Thread To Check / / Keystroke -beginthread(CheckKey, 0, NULL);
For
A
Terminating
/ / Loop Until The CheckKeyO Thread TerminatesThe Program while(ContinueThread == TRW)
c
/ / Launch np To Ten QetInstanceO Threads if (Counter < 10) -beginthread(OetInstance, 0, (void * ) (Counter++)); / / Wait One Second sleep(1000~); / / Display The / / Variable
1
BetweenLoop Passes
Current
Value Of The DBlINSTANCE Environment
cout << "Current value o f the DBlINSTANCE environment"; cout << Uvariable : #' << Instance << endl;
/ / Return TO The return(rc);
Operating
System
1 / / Defins The CheckKey( ) Thread void CheckKey (void *Dummy)
Function
{
/ / Declare The LocalMemory Variables struct sqlca sqlca; / / Create A New Application Context And Attach To It sqleBeginCtx(hContextData, SQL-CTX-BEGIN-ALL, NULL, Psqlca); / / If A New Context Waa Created, Display A Success MeSSage if (sqlca.sqlcode =m SQL-RC-OK) cout << "A new context ha8 been created." << endl;
/ / Set The / / End
ContinueThread FlagSo The OetInstance() Threads Will
ContinueThread / / Terminate
1
m
FALSE;
This Thread
-endthread ( ) ;
/ / Define The QetInstanceO Thread Function void &tInstance(void *Count) {
Part 3 Application Programming Interface Functions
:
/ / Declare The LocalMemory Variables etruct eqlca eqlca; / / Attach To The Context Created By CheckKeyO The Thread eqleAttachToCtx(ContextData, NULL, breqlca);
/ / If Attached ToThe New Context, Dieplay A Succeee if (eqlca. eqlcode =- SQL-RC-OK) cout *( "Attached to the new context e< endl;
Meeeage
."
/ / Loop Until CheckKeyO Thread Terminates The Program while(ContinueThread TRUE) I-
c / / Pause Between Loope Sleep(100L);
/ / Obtain The Current / / Variable
Value Of The DB2INSTANCE Environment
eqlegins(Inetance, &eqlca); Inetance[El C 0; / / If The Current ValueOf The DB2INSTANCE Environment / / Variable WasNot Obtained, Clear TheM e m o r y Storage Area
if (eqlca.aqlcode I = SQL-RC-OK) Inetance[Ol = 0;
1
1
/ / Beep To Signal The LOOP I6 Still Running Beep(1000, 175);
/ / Terminate The Thread -endthread ( ) ;
l"l DETACH AND DESTROY
APPLICATION CONTEXT
Purpose
The DETACH AND DESTROY APPLICATION CONTEXT function is used to make thecurrent thread stop using a specified contextand to free all memory associated withthat context.
Syntax
int eqleEndCtx (void **Context, long Action, void *Resfeme& struct eqlca *SQLcA);
Parameters
Context Action
A pointer to a location in memorywhere the starting address of a data storage area that is used to store context informationis stored. Specifies the action that this function is to perform. This parameter must be set to one of the following values:
9 Chapter 14: Thread Context Management Functions
i
i
i
j
f
,
i ! 563
I
SOL-CTX-FREE-ONLY
Only free context memory ifno thread iscurrently attached to the context. SQL-CTX-END-ALL
Free context memoryafter detaching the threadthat is currently attached it. Reserved
SQLCA
A pointer that, at this time, is reserved for later use.Fornow, this parameter must always be set to Nuu. A pointer to a location in memorywhere a SQLCommunications Area (SQLCA)data structurevariable is stored. T h i s structure returns either statusinformation (if the function executed successfully) or error information (if the function failed)to the calling application.
Includes
#include <sql.h>
Description
The DETACH AND DESTROY APPLICATION CONTEXT function is used to make the current thread stop usinga specified context and to free all memory associated with that context.
Comments
W If this function is called withthe Action parameter set to SQL-CTILENDALL,
the Context parameter can containa NULL pointer (in which case,the currentcontext will be used). Otherwise,the Context parameter must reference a valid context information storage area that was allocated by the CREATE AND ATTACH TO AN APPLICATION C0NTEXTfunCtiOl.l.
If this function is called whilea database connection exists or while the context is attached to other threads, an error will occur. W If a context is used by a thread that executes an API that establishes an attachment to a DB2 Database Manager instance, the thread mustdetach from the Database Manager instance (by callingthe DETACH function) before this function is called. W The scopeof this function is limited to the currentprocess. W This function has no effect whenit is executed on platforms that do not support application threading.
Connection This function canbe called at any time; a connection to a DB2 Database Manager Requirements instance or to a DB2 database does not haveto be established fist. Authorization No authorization is required to execute this function call. See Also
DETACH FROM CONTEXT, CREATE AND ATTACH TO AN APPLICATION CONTEXT
Example
Thefollowing C++ program illustrates how to use the DETACH AND DESTROY APPLICATION CONTEXT function to make the current threadstop usinga specified context and to free all memory associated withthat context:
i
I
n Part 3: Application Programming Interface Functions /*
/* /*
M:
CHlIEX3.CPP PURPOSE: Illustrate How To use The Following DB2 API Function /* In A C++ Program:
/* /*
DETACH FROM CONTEXT DETACH AND DESTROY APPLICATION
/*
*/ */ */ */
*/ */
*/
CONTEXT
/* /*
*/ */
/ / Include The Appropriate Header Files #include <windows.h> #include <process.h> / / -beginthread ( #include <stddef.h> #include <etdlib.h> #include #include #include <sql.h> #include <sqlenv.h> #include <sqlca.h>
, -endthread ( )
/ / Define The Thread Function Prototypes void CheckKey (void *-) ; void QetInstance(void *Count))
/ / Declare The GlobalMemory Variables a TRWp / / End Thread Flag BOOL ContinueThread char Instance [ 9I ; / / Current Instance void *ContextData NULL; / / Context Data Storage Area
/* Function
/* /*
The Main
*/
int main() {
/ / Declare rc long Counter char sqlca; struct sqlca / / Set The
The
LocalMemory Variables = SQL-RC-OK; E
Application
0;
Thread
Context
TVpe To Manual
sqleSetTypeCtx(SQL-CTX"cR,TI~~AL);
Launch TheCheckKeyO Thread TO Check / / Keystroke -beginthread(CheckKey, 0, NULL);
ForA TerIIliMting
/ / Loop Until The CheckKey() Thread TerminatesThe Program while(ContinueThread =E T R W ) / / Launch Up To Ten QetInstanceO Threads if (Counter < 10) -beginthread(QetInetance, 0, (void * ) (Counter++)))
*/ */
Chapter 14: Thread Context ManagementFunctions / / Wait One Second Sleep(1000L);
BetweenLoop Passes
/ / Dieplay The Current / / variable
ValueOf The
DB2INSTANCE
Environment
cout << Turrent value of the DB2INSTANCE environment cout << "variable : << Instance << endl;
1 / / Destroy The Application Context That Was Created By The / / CheckKey( ) Thread sqleEndCtx(&ContextData, SQL-CTX-FREE-ONLY, NULL, &sqlca); / / I€ The Context Was Destroyed, Display A Success Message if (eqlca.sqlcode == SQL-RC-OK) cout << "Context has been destroyed." << endl; / / Return To The return ( rc ) ;
Operating
System
1 / / Define The CheckKeyO Thread Function void CheckKey(void *Dummy) {
/ / Declare The LocalMemory Variables struct sqlca eqlca; / / Create A New Application Context And Attach To It sqleBeginCtx(&ContextData, SQL-CTX-BEGIN-ALL, NULL, Lsqlca); / / If A New Context Wae Created, Dieplay A Succeee Meeeage if (sqlca.eqlcode =m SQL-RC-OK) cout << "A new context has been created." << endl;
/ / Wait For A Keystroke
-getch ( ) 1 / / Set The ContinueThread / / End ContinueThread = FALSE;
/ / Detach From The The / / Of This Thread
Flag So The GetInstanceO Threads Will
New
Context
That
Was
Created At The
Start
eqleDetachFromCtx(ContextData, NULL, brsqlca); / / If Detached FromThe New Context, DisplayA Success if (sqlca.sqlcode =I SQL-RC-OK) cout << "Detached from the new context.w << endl;
/ / Terminate This Thread -endthread ( ) ;
1
Message
/ / Define The QetInetanceO Thread Function void QetInetance(void *Count) {
/ / Declare The LocalMemory Variables struct sqlca sqlca;
/ / Attach TO The Context Created ByThe CheckKey( ) Thread eqleAttachToCtx(ContextData, NULL, &eqlca); / / If Attached To The New Context, Display A Success if (SqlCa.SqlCOde == SQL-RC-OK) cout << "Attached to thenew context." << endl;
Message
while(ContinueThread == T R W ) {
/ / Pause Between Loops Sleep (1OOL) ; / / Obtain The / / Variable
Current Value Of The DB2INSTANCE Environment
eqlegins(1nstance. Gsqlca); Inetance[E] = 0; / / If The Current ValueOf The DB2INSTANCE Environment / / Variable WasNot Obtained, Clear TheMemory Storage Area
if (eqlca.sqlcode != SQL-RC-OK) Instance[OI = 0; / / Beep To Signal TheLOOP Is Still Running Beep(1000, 175);
1 / / Detach From The Context Created The By CheckKeyO Thread sqleDetachFromCtx(ContextData, NULL, Psqlca);
/ / If Detached From The New Context, Display A Success if (aq1ca.sqlcode =P SQL-RC-OK) cout << "Detached from the new context." << endl;
Message
/ / Terminate The Thread -endthread ( ) ;
1
PM !@WATTACHTOCONTEXT Purpose
The ATTACH TO CONTEXT function is used to make the current thread use a specified context.
Syntax
int sqleAttachToCtx (void *Reserved,
*Context,
void struct sqlca
*SQLCA);
Chapter 14: Thread Context Management Functions Parameters
Context
Reserved
SQLCA
A pointer to a location in memorywhere a validcontextinformation storage area that was allocated by the C ~ T AND E ATTACH TO AN APPLICATION CONTEXT function is stored. A pointer that, at this time, is reservedfor later use. For now, this parameter must always be set to NULL.
A pointer to a location in memorywhere a SQL Communications Area (SQLCA)data structurevariable is stored. This structure returns either status information (ifthe function executed successfully) or error information (ifthe function failed)to the calling application.
Includes
#include <sql.h,
Description
The ATTACH TO CONTEXT function is used to make the current threaduse a specified context. Oncethis function is called, all subsequent database operations performedby the calling thread will usethe context specified.
Comments
H If more than one thread isattached to a given context,data access is serialized for
each thread, and each thread shares acommon commit scope. H The scopeof this function is limited to the currentprocess. H This function has no effect when it is executed on platforms that do not support
application threading.
Connection This function canbe called at any time; a connection to a DB2 Database Manager Requirements instance or to a DB2 database does not haveto be established first. Authorization No authorization is required to execute this function call. See Also
CREATE AND ATTACH TO A N APPLICATION CONTEXT,DETACH
Example
See example for CREATE AND ATTACH
TO AN APPLICATION
FROMCONTEXT CONTEXT
on page 560.
m m DETACH FROM CONTEXT Purpose
The DETACH FROM specified context.
CONTEXT
function is used to make the current threadstop usinga
int SqleDetachFromCtx (void void struct sqlca
Parameters
Context
*Context, *Reserved, *SQLCA);
A pointer to a location in memorywhere a validcontextinformation storage area that was allocated by the CREATE AND ATTACH TO AN APPLICATION CONTEXT function is stored.
Part 3: Application Programming Interface Functions Reserved SQLCA
A pointer that, atthis time, is reserved forlater use. For now, this parameter must always beset to NULL. A pointer to a location in memory wherea SQL Communications Area (SQLCA) data structurevariable is stored. This structure returns either statusinformation (ifthe function executed successfully) or error information (ifthe function failed)to the calling application.
Includes
#include
Description
The DETACH FROM CONTEXT function is used to make the current threadstop using a specified context.
Comments
W The current threadwill not be detached from the context specified ifit has never
been attached to the context. B The scopeof this function is limited to the currentprocess.
This function has no effect whenit is executed on platforms that do not support application threading.
This function canbe called at any time: a connection to a DB2 Database Manager Connection Requirements instance or to a DB2 database does nothave to be established first. Authorization No authorization is required to execute this function call. See Also
DETACH AND DESTROY APPLICATION
Example
Seeexample for DETACH
M !!
CONTEXT,ATTACH
AND DESTROY APPLICATION
CONTEXT
on page 564.
GET CURRENT CONTEXT function is used to get the context that the current thread
Purpose
The QET CURRENT is attached to.
syntax
i n t aqleatCurrentCtx (void
CONTEXT
wid
a t r u c t eqlca
Parameters
TO CONTEXT
Context
Reserved SQLCA
**Context,
*Reserved, *SQLCn)/
A pointer to a location in memorywhere this function is to store the starting address of a data storage area that contains context information. A pointer that, at this time, is reservedfor later use. For now, this parameter must always be set to NULL. A pointer to a location in memorywhere a SQLCommunications Area (SQLCA)data structurevariable is stored. This structure
Chapter 1 4 Thread Context Management Functions returns either status information (ifthe function executed successfully) or error information (ifthe function failed)to the calling application.
Includes
#include <sql.h>
Description
The GET CURRENT CONTEXT function is used to get the context that the current thread is attached to.
Comments
H The scope of this function is limited to the currentprocess. B This function has no effect whenit is executed on platforms that do not support application threading.
This function canbe called at any time;a connection to a DB2 Database Manager Connection Requirements instance or to a DB2 database does not haveto be established first.
Authorization No authorization is required to execute this function call. See Also
ATTACH TO CONTEXT,DETACH
Example
Thefollowing C++program illustrates how to use the GET CURRENT CONTEXT function to get the context to which the current threadis attached
FROM CONTEXT
I*
/*
/* /* /* /*
* Il
NAME:
CH14EX4.CPP PURPOSE: Illustrate How To Use The Following DB2 API Function In A C++ Program: GET CURRENT CONTEXT
/*
/ / Include The Appropriate #include <windows.h> #include <process.h> #include <stdde€.h> #include <stdlib.h> #include #include #include <sql.h> #include <sqlenv.h> #include aq1ca.b / / Define The
Thread
Header
Function
Files
Prototypes
void CheckKey(void *Dummy);
void GetInstance(void *Count); / / Declare The Global Memory Variables ContinueThread = TRUE; / / End Thread Flag Instance char [9] ; / / Current Instance void *ContextData = NULL; / / Context Data Storage Area BOOL
*/ */
*/ */
*/ */
Part 3: Application Programming Interface Functions /* /*
The Main
*/ */
Function
/*
*/
int main() {
-
/ / Declare The Local long rc SOL-RC-OK; char Counter = 0;
Memory
Variables
/ / Set The Application
Thread
Context
Type To Manual
sqlesetTypectx(sQL~cTx~I_MAN[rAL); / / Launch TheCheckKeyO Thread To Check / / Keystroke -beginthread(CheckKey, 0, m&);
For
A
Terminating
/ / Loop Until CheckKey() ThreadTerm4.nates The Program while (ContinueThread -= ' l a w ) {
/ / Launch nP To Ten GetInetance( ) Threads if (Counter 10) -beginthread(QetInstance, 0, (void *) (Counter++)) ; / / Wait One Second Sleep (1OOOL) ;
1
1
Between Loop Passee ~
/ / Display The Current Value O f The DB2INSTANCE Environment / / Variable cout << "Current value of the DB2INSTANCE environment "; cout"variable : << Instance << endl;
/ / Return To The return(rc) ;
Operating
System
/ / Define The CheckKeyO Thread Function void CheckKey(void * D u m m y ) {
/ / Declare The Local struct eqlca eqlca;
Memory
Variables
/ / Create ANew Application ContextAnd Attach To It eqleBeginCtx(&ContextData, SQL-CTX-BEOIN_eLL, N U L L , hsqlca); / / If A New Context Was Created, Display A Success Meseage if (sqlca.sq1code =I SQL-RC-OK) cout << "A new context has h e n created.- e< endl;
/ / Wait For A detch( ) ;
Keystroke
Chapter 14: Thread Context Management Functions / / Terminate This Thread
-endthread ( ) ; 1 / / Define The GetInstanceO Thread Function void QetInstance (void *Count) {
/ / Declare The LocalM e m o r y Variables struct sqlca sqlca; / / Attach To The Context Created By The CheckKey( ) Thread sqleAttachToCtx(ContextData, NULL, hsqlca); / / If Attached To The New Context, Display A Success if (eqlca.sqlcode == SQL-RC-OK) cout "Attached to the new context." << endl;
Message
/ / Get Information About The Current Context sqleGetCurrentCtx(PContextData, NULL, &SqlCa);
/ / If The Information Bas Been Collected, Display Success A / / Message if (sqlca.sqlcoUe =P SQL-RC-OK) collected." << endl; cout << "Context information has been / / Loop Dntil CheckKeyO Thread Terminates The Program while(ContinueThread == TRUE) {
/ / Pause
BetweenLoops Sleep(l00L); / / Obtain The Current Value Of The / / variable sqlegins(1nstance. &sqlca); InstancetEl 0;
DB2INSTANCE Environment
-
/ / If The Current ValueOf The DB2INSTANCE Environment / / Variable Was Not Obtained, Clear TheMemory Storage Area if (sqlca. sqlcoUe l = SQL-RC-OK)
Instance[Ol = 0;
1
/ / Beep To Signal The Loop Is Still Running Beep(1000, 175);
/ / Terminate The Thread -endthread();
1
Part 3: Application Programming Interface Functions
INTERRUPT CONTEXT Purpose
The I m E R R m T CONTEXT function is used to send an interrupt to the specified context.
syntax
i n t eqleInterruptCtx (void
*context, void etruct eqlca
Parameters
Context
Reserved SQLCA
*R8.9eWed,
*SQLCAl;
A pointer to a location in memorywhere a validcontextinformation storage area that was allocated by the CREATE’ AND ATTACH TO AN APPLICATION CONTEXT function is stored. A pointer that, at this time, is reserved for later use. For now, this parameter must always be set to NULL. A pointer to a location in memorywhere a SQLCommunications Area (SQLCA)data structurevariable is stored. This structure returns either status information (if the function executed successfully) or error information (ifthe function failed)to the calling application.
Includes
#include <eql.h>
Description
The INTERRUPT CONTEXT function is used to send an interruptt o the specified context. When invoked,this function: 1. Switches to the specified context 2. Sends an interrupt signal 3. Switches backto the original context 4. Returns control to the current thread
Comments
U The scopeof this function is limited to the currentprocess.
U This function has no effect whenit is executed on platforms that do not support
application threading.
Connection This h c t i o n can be called at any time, a connection to a DB2 Database Manager Requirements instance or to a DB2 database does not haveto be established first. However, this function will not have any effect unless it is called whena connection to a DB2 database exists. Authorization No authorization is required to execute this function call. See Also
CREATE AND ATTACH
Example
The followingC++ program illustrates how to use the INTERRUPT CONTEXT function to send an interrupt to the specified context:
TOAN APPLICATION
CONTEXT
Chapter 14: Thread Context Management Functions /* ,/*
*/ NAME: CH14EXS.CPP PURPOSE: Illustrate How To Use The Following DBZ API Function In A C++ Program:
/* /* /* CONTEXT /* /*
INTERRUPT
/*
/ / Include The Appropriate #include <windows.h> #include <process.h> #include <stddef.h> #include <stdlib.h> #include #include #include <spl.h> #include <sqlenv.h> #include <splca.h>
Header
*/ */
*/ */ */ */ */
Files / / -beginthread(), -endthread()
/ / Define The Thread Function Prototypes void CheckRey(void *Dummy); void GetInstance(void*Count); / / Declare The Global Memory Variables BOOL ContinueThread = TRUE; / / End Thread Flag [g] ; / / Current Instance Instance char void *ContextData = NULL; / / Context Data Storage Area
/* /* /*
The Main Function
*/
int main()
I
/ / Declare The LocalMemory Variables long rc = SQL-RC-OK; char Counter = 0 ; / / Set The
Application
Thread
Context
Type To Manual
sqleSetTypeCtx(SQL~CTX~TI~M?iNUAL);
/ / Launch TheCheckKeyO Thread To Check / / Keystroke -beginthread(CheckKey, 0, NULL);
ForA Terminating
/ / Loop Until CheckKeyO Thread Terminates The Program while(ContinueThread I= TRW) {
/ / Launch Up To Ten QetInstanceO Threads if (Counter < 10) _beginthread(OetInstance, 0, (void * ) (Counter++)); / / Wait One Second Sleep(1000L);
Between
Loop
Passes
*/. */
iI Part 3: Application ProgrammingInterface Functions
1
1
/ / Display The Current Value Of The DB2INSTANCE Environment / / Variable tout UCUrrellt value of the DB2INSTANCE environment 11; cout << "variable : << Instance << endl;
/ / Return To The return(rc) ;
Operating
/ / Define The CheckKey( ) Thread void CheckKey(void * D u m m y )
System
Function
{
/ / Declare The Local Memory Variables struct sqlca sqlca,
/ / Create ANew Application ContextAnd Attach To It sqleBeginCtx(hContextData, SQL-CTX-BEGINALL, NULL, PSUlCa);
/ / If A New Context Was Created, Display A Success Meseage if (eqlca.sqlcode == SQL-RC-OK) << endl; cout << "A new context has been created.U / / Wait For xetch() ;
A
Keystroke
/ / Set The ContinueThread FlagSo The GetInetanceO Threads Will / / End
ContinueThread = FALSE1 / / Terminate This Thread
-endthread ( ) ; 1 / / Define The GetInstance() Thread Function void GetInstance(void *Count)
I: / / Declare The LocalMemory Variables struct sqlca sqlca; char ThreadNura (char) Count; / / Attach To The Context CreatedBy The CheckKeyO Thread sqleAttachToCtx(ContextData, NULL, Psqlca);
/ / If Attached TOThe New Context, Display A SuccessMewage if (sqlca.sqlcde == SQL-RC-OK) cout << "Attached to the new context . n end11
Chapter 14: Thread Context Management Functions
,
,
1
i 575
/ / If The Context Has Been Interrupted, Display A Success / / Message And Terminate The Thread if (sqlca.sqlcode == SQL-RC-OK) {
tout << Tontext has been interrupted." << endl;
-endthread ( ) ; return;
1
1
/ / Otherwise, Loop Until CheckKey() Thread Terminates The / / Program while(ContinueThread == T R W ) / / Pause Between Loops Sleep(100L); / / Obtain The Current Value Of The DB2INSTANCE / / Variable sqlegins(Instance, hsqlca); 1netance[81 = 0;
Environment
/ / If The Current Value Of The DB2INSTANCE Environment / / Variable WasNot Obtained, Clear TheM e m o r y Storage Area if (sqlca.sqlcode I = SQL-RC-OK)
Instance[Ol = 0;
1
/ / Beep To Signal The Loop Is Still Running Beep(1000, 1 7 5 ) ;
/ / Terminate The Thread -endthread ( ) ;
1
This Page Intentionally Left Blank
l!4!!4 IAPPENDIXA SQL Data Structures
IBM! The SQL Communications Area (SQLA) Structure The SQL communications area (SQLCA)structure isa collection of variables that are updated at the end of the execution of every SQL statement and DB2 API function call. Application programs that contain embedded SQL statements (other than embedded DECLARE, INCLUDE, and WHENEVER statements) or functioncalls must define at least one SQLCA data structurevariable (you can also place one SQLCA data structure variable in each thread of a multithreaded application).You can use the I N C L ~ ESQL statement t o provide the declaration of the SQLCA data structure in embedded SQL applications written in C and C++.The sqlca structure is defined in sq1ca.h as follows: etruct eqlca char eqlcaid
[el ;
eqlcabc; long eqlcoae; long
ehort eqlerrml;
char eqlerrmc [701;
char eqlerrp[81;
An "eye catchern for etoragedumpe. Thie */ field containe the value "SQLCA */ The size of the SQLCA etructure (136 bytee) */ The SQL return codevalue. A value of 0 */ meme "eucceeaful execution,n a poeitive */ with */ /* value meane "eucceeeful execution meane */ /* warnings," and a negative value /* %rror." Refer to the IBWlB2 miversa1 */ /* Database Messages Reference €or epecific */ /* meaninge of SQL return code values. */ /* The eize, in bytee, of the data etored in */ */ /* the sqlerrmc field of thie etructure. This /* value can be any number between 0 and 70. A */ /* value of 0 indicates that no data is stored */ /* in the eqlermc field. */ /* One or more error meeeagetokena, eeparated */ / * by OxFF, that are eubetituted for variable8 */ /* in the deacriptione of error conditione. */ /* Thie field ie aleo used when a eucceeeful */ /* connection ie eetablished. Refer to the IBM */ /* DE2 miversal Database Messages Reference for */ /* specific meaninge ofSQL return code values. */ /* A diagnoetic value thatbegin8 with a three-*/ /* letter code identifyingthe product followed */ /* by five digits that identify the vereion, */ /* releaee, and modification levelof the */ /* product. For example, "SQL05020" meane DB2 */ /* Universal Database, vereion5, release 2, */ /* modification level 0. If the sqlcode field */ /* containe a negative value, this field */
/* /* /* /* /*
1
57%
1j
Appendix A ODBC Scalar Functions l o n gs q l e r r d [ 6 ] char
;
sqlwarn[ll];
/* i d e n t i f i e s the module t h a t r e t u r n e d an error. /* An array of six i n t e g e rv a l u e e t h a t provide /* a dddiiaitngi ofnonorasmlt iact i o n indicators, each /* An array of warning
*/ */ */ */
c o n t a i n i n g a blank or the letter 'W'. If */ compound SQL w a s used, this f i e l d w i l l */ */ /* c o n t a i n an accumulation of the warning */ /* i n d i c a t o r es e t for a l l SQL sub-statements /* The SQLSTATE v a l u e t h a t i n d i c a t e s the outcame */ /* of the most r e c e n t l ye x e c u t e d 8QL statement */
/* /*
Table A-l describes the types of diagnostic informationthat can be returned in the sqlerrd array, and Table A-2 describes the types of warning information that can be returned in the sqlwarn array.
Table A-l Elements of the sqlcasqlerrd Array
sqlerrd[O]
If a CONNECT statementwas successfullyinvoked, this element will containthe maximum expected differencein lengthof mixed character data (CHAR data types) when converted from the application code page to the database code page.A value of 0 or 1 indicates no expansion; a value greater than1 indicates apossible expansionin length; a negative value indicates apossible contraction in length.
sqlerrd[l]
If the SQLCA data reflects a NOT ATOMIC compound SQL statement that encountered one or more errore, this element will contain a count of the number of SQL statements that failed.
sqlerrd[2]
Ifthe SQLCA data reflects a PREPARE statement that was successfullyinvoked, this element will contain an estimate of the number of rows that willbe returned. If the SQLCA data reflects an INSERT, UPDATE, or DELETE statement that waa successfully invoked, this element will contain acount of the number of rows that were affected by the operation. If the SQLCA data reflects a compound SQL statement thatwas successfully invoked,this element willcontain a count of the number of rows that were affected by all sub-statementa.
If the SQLCA data reflects a CONNECT statement that was successfully invoked,this element will contain 1 if the database can be updated, 2 if the database is read only. sqlerrd[3]
If the SQLCA data reflects a PREPARE statement that waa successfullyinvoked, this element will contain a relative cost estimate of the resources requiredto process the statement. If the SQLCA data reflects a compound SQL statement thatwas successfully invoked,this element will contain a count of the number of sub-statements that were successful.
: 1 579
Appendix A ODBC Functions Scalar
'
If the SQLCA data reflects a CONNECT statement thatwas successfully invoked,this element will contain 0 if a one-phase commitfrom a down-level client is being used; 1 if a one-phase commit is being used; 2 if a one-phase, read-only commitis being used; and3 if a two-phase commitis being used. sqlerrd[4]
This elementcontains thetotal number of rows that wereinserted,updated, or deleted as a result of: W The enforcement of constrainta after a successful delete operation. W The processing of triggered SQL statements from activated triggers. If the SQLCA data reflects a compound SQLstatement wassuccessfully invoked,this element will contain a count of all such rows for all SQL sub-statements processed.
If the SQLCA data reflects a CONNECT statement that was successfully invoked,this element will contain 0 if server authenticationis used; 1 if client authentication is used; 2 if authentication is handled by DB2 Connect; 3 if authentication is handled by DCE Security Services; 255 if authentication is not specified. that is In some cases,when an error is encountered this field contains a negative value used as an internal errorpointer. sqlerrd[5]
For a partitioneddatabase, this elementcontains the partition number of the partition that encountered the erroror warning. If no errors or warnings were encountered, this element containsthe partition number of the coordinator node(the number stored inthis element is the same as thatspecified forthe partition inthe db2nodescfg file).
SOLWARNO
This element is blank if all other indicators are blank it contains a W if at least one other indicator is not blank.
SQLWARN2
This elementcontainsa W if NULL valueswereeliminated from the argument of a function.
SOLWARN3
"his element contains a W if the number of columns is not equal to the number of host variables provided.
SQLWARNI
This elementcontains a W if a prepared UPDATE or DELETE statement does notinclude a WHEREclause.
SQLWARNS
Reserved for future use.
SOLWARN6
"his element contains a W if the result of a date calculation was adjusted to avoid an invalid date.
SQLWARN7
Reserved for
future use.
1 580 : L
" "
Appendix A ODBC Scalar Functions
-:
Table A 6 2 Elements of the sqlcasqlwarn Array (Continued) . . . ... . , ,,.. , .,- . .._ p?? ..,..__*I
. I
h
..
~
-.
I
.;
.
.
..
._.
,>
, . _ I. ,
. .
This elementcontains a W if acharacterthatcouldnotbeconvertedwasreplacedwith substitution character.
SQLWARNE SQLWARNS
This elementcontainsa W if arithmeticexpressionscontainingerrorswereignoredduring column function processing.
SQLWARNA
This elementcontainsa W if there was aconversionerrorwhileconvertingacharacter data valuein one of the fieldsin the SQLCA data structure.
BB!! F M
I.
,
h a
The SQLCHAR STRUCTURE The SQLCHAR structure i s a combination of a character string and a string length value. This structure works WithVARCHAR data types. The sqlchar structure i s defined in sqZ.h as follows: etruct eqlchar {
ehort length;
/* /* /* /*
The length of the character etring etored in the data field of thie etructure. A character etring.
*/ */ */ */
M APPENDIXB DB2 Log Records "his sectiondescribes the structure of the logrecords that are returned by the LOO function. log records begin with a 'log manager header". "his header contains generic information about the log record including the total log
ASYNCHRONOUS READ
record size, the log record type,and transaction-specific information."he structureof the log manager header i s shown in Table %l. Table 6-1
Log RecordHeader Structure
0
4
4
2
integer short integer
Length of the entire log record Type of log record The following log record types are valid
"a" Datalink Manager
"0"
"A"Normal Abort
"0"Backup End
"B" Backout Free
"p" Tablespace Roll Forward To Point-In-Time Start
"C"
MPP Coordinator Commit
"C" Compensation
Backup Start
"P" Table Quiesce "q" Tablespace Roll Forward To
Point-In-Time End "D" Tablespace Rolled Forward
"Q" Global Pending List
"E" Local Pending List
V"Redo
"F'' Forget Transaction
"a" MPP Subordinate Commit
"g" MPP Log Synchronization
"S" Compensation Required
"G" Load Pending List W Table LoadDelete Start
T Partial Abort V Undo
"iPropagate " Only
"v" Migration Start
T Heuristic Abort "PLoad Start
"W" Migration End
"K" Load Delete Start Compensation
Y' Heuristic Commit
T"Lock Description
"z" MPP Prepare
"M'' Normal Commit
"PXA Prepare
W Normal
T T M Prepare
I
jL
582
i
Appendix B: DB2 Log Records
" "
Table 5 1
Continued
A Propogate Only ("i") logrecord is an informational log record that will be ignored by DB2 during roll forward, roll back,and crash recovery operations. Note: When a transaction performs writable work against a table that hasDATA CATF'URE CHANGES turned on, or when a transaction invokes a DB2 API that generates log records, that transaction is said to be propagatable. 6
2
short integer
Log record general flag The following log record general flags are valid Always Redo
oxo001
8
6
SQLU-LSN
ox0002
Propagatable
ox0080
Conditionally Recoverable
Log Sequence Number of the previous log record written by this transaction. This value is used to chain log records by transaction. If the value is 0000 0000 0000, this is the first log record written by the transaction. The SQLU-LSN data type is defined as:
union { char[6]; short[3];
1; 14
6
SQLU-TID
Unique transaction identifier The SQLU-TID data type is defmed as:
union { char[6]; short[3]; 20
6
Sequence Number of the log record for this transaction prior
SQLU-LSNLog
to the log recordbeing compensated. This value is only used for Compensation ("C") and Backout Free ("B") log records 26
6
SQLU-LSN Log
Sequence Number of the log record for this transaction being compensated.
This value is only used for Propagatable compensation log . records. Total length of Log Manager Log Record Header : Non-Compensation: 20 bytes Compensation: 26bytes Propagatable-Compensation:32 bytes Adapted from Table90 on pages 529-531 of IBM DB2 Universal Database AFI' Reference
Appendix B: DB2 Log Records Each log record is iderltifiedby a unique log sequence number (LSN). The logr sequence number represents a relative byte address, within the database log file, for the firstbyte of the log record.In other words, the log sequence numbermarks the offset of the log record fromthe beginning of the database log file. Log records that are written as a result of the execution of a singletransaction can be identified by the value of the transaction identifier field in the log record header. These log recordsare assigned a uniquetransaction identifier, whichis a six-byte field that is incremented by one each time a new transaction is started.All log records that are generated by the same transaction are assigned the same transaction identifier. DB2 can generate up to forty different log records. The remaining pages in this appendix describethe structures of each log recordthat can be generated.
Data Manager Log Records Data Manager log records are generated whenever Data Definition Language (DDL) SQL statements, Data Manipulation Language(DML) SQL statements, or some Utility AF'Is are executed. " W O types of Data Manager log records exist:Data Managemknt System I D " ) log recordsand Data Object Manager @OM) log records. Data Management System log records contain the header information shown in Table B-2, along with additional, record-specific information.
1
1
unsigned char
Function identifier The following function identifier values are valid SQLl"INDP
(100)
Minimum DBMS Log Function ID
SQIJUfAX"P
(149)
Maximum DBMS Log Function ID
ADDCOLUMNS-DP (1021, Add
columns via ALTER TABLE
CRIWWPG-DP
(103)
Create new page
UNDOADDCOLUMNS-DP
(104)Undo
ALTERPROP-DP
(105)
Alter property flag Delete record on page
add columns
DELREC-DP
(106)
UNDOALTERPROP-DP
(107)Undo
ALTERPENDING-DP
(108)
Alter check pending flag
ALTERDEFAULTS-DP
(109)
Alter user defaults add flag
alter property flag
l
l Appendix B: DB2 Log Records
UNDOADD-DP
(110)
Undo add a record
UNDODEL-DP
(111)
Undo delete a record
UNDOUPDT-DP
(112)
Undo update a record
CRSYSPGR-DP
(114)
Initialize system page DTR
REORGPAGE-DP
(117)
Reorganize page
INSREC-DP
(118)
Insert record on page
UPDREC-DP
(120)
Update record on page
UPDCHGONLY-DP
(121)
Log only updated
CREATEPEFtM-DP
(128)
Initialize a DAT object
UNDOALTERDEFAULTS-DP (131) '
2
2
unsigned short
UNDOALTERPENDING-DP
(132)
Undo alter user default flag Undo alter pending flag
Table identifierfiblespace identifier
Total length of DMS Log RecordHeader :6 bytes Adapted from Table 91 on page 532 of IBM DB2 Universal Database API Reference
Data Object Manager log records contain the header information shown in Table
B-3, along with additional, record-specific information. Table 5 3
0
1
1
Data Object Manager (DOM)Log Record Header Structure
1
unsigned char
Component identifier (Always 4)
unsigned char
Function identifier
T h e following function identifier values are valid SQLD-MIN-DP SQLDMAXDP
(100) Maximum (149)
Minimum DBMS Log Function ID
DBMS Log Function ID
ADDCOLUMNS-DP (1021, Add
columns via ALTER TAEILE
CRNEWPG-DP
(103)
Create new page
UNDOADDCOLUMNS-DP
(104)
Undo add columns
ALTERPROP-DP
(105)
Alter property flag
DELREC-DP
(106)
Delete record on page
Appendix B: DB2 Log Records Table 5 3
Continued UNDOALTERPROP-DP
(107)
ALTERPENDING-DP
(108)
UNDOADD-DP
(110)
Undo add a record
(111)
Undo delete a record
UNDOUPDT-DP (112)
Undo update a record
CRSYSPGR-DP (114)
Initialize system DTR
REORGPAGE-DP (117)
Reorganize page
6
10 11
(118)
page
Insert record on page
UPDREC-DP
Update record on page
UPDCHGONLY-DP (121)
Log only updated
CREATEPEW-DP
2
check pending flag
UNDODELRP
INSREC-DP
2
. Alter
Alter user defaults add flag
ALTERDEFAULTS-DP (109)
(120)
Undo alter property flag
(128)
Initialize a DAT object
UNDOALTERDEFAULTS-DP (131)
Undo alter user default flag
UNDOALTERPENDING-DP (132)
Undo alter pending flag
unsigned short
Object identifiermablespace identifier
2
unsigned short
Table identifierfhblespace identifier
1
unsigned char
Object type
1
unsigned char
Flags
Total length of DOM Log Record Header : 12 bytes Adapted from Table92 on pages 632-633 of IBM DB2 Universal DatabaseAPI Reference
All Data Manager log records whose function identifier value begins with "UNDO" are written during the UNDO or ROLLBACK operation specified.A ROLLBACK operation can occur when: The ROLLBACK SQL statement is executed
A deadlock situation causes a selectedtransaction to be rolled back Uncommitted transactions are rolled backduring a crash recovery Uncommitted transactions are rolled back after a RESTORE ROLLFORWARD DATABASE operation has occurred.
DATABASE and
Appendix B: DB2 Log Records Table B-5
0
Column DescriptorArray Details
unsigned short
2
Field type The following fieldtype values are valid
(0x0002)
SMALLINT
(0x0000)
INTEGER
(0x0001)
DECIMAL
(0x0003)
DOUBLE
REAL
(0x0004)
BIGINT
(0x0006)
CHAR
(0x0100)
VARCHAR
(0x0101)
VARCHAR LONG
(0x0200)
(0x0203) 2
(0x0104)
DATE
(0x0105)
TIME
(0x0106)
TIMESTAMP
(0x0107)
BLOB
(0x0108)
CLOB
(0x0109)
GRAPHIC VARGRAPH
(0x0201)
LONG VARG
(0x0202)
DBCLOB short
Field length If fieldtype is BLOB, CLOB,or DBCLOB, field length is not used.
If field type is not DECIMAL,, field length is the maximum length of the field. If fieldtype is DECIMAL, field length is defined as follows: Byte 1(unsigned char) contains the precision (total width)and Byte 2 (unsigned char) contains the scale (fraction digits). 2
4
unsigned short
Null flag The following null flag valuesare valid
ISNULL
(0x01)
NONULLS
~0x02)
'IYPE-DEFAULT
(0x04)
USER-DEFAULT
(0x08)
blevariable
i
p? Appendix B: DB2 Log Records
Null flag values are mutually exclusive: a fieldcan either allow nulls, or not allow nulls (valid options: no default, type default, or user default). 2
6
Fieldshort unsigned
offset This is the offset fromthe start of the formatted record to where the field's fixedvalue canbe found.
Total length of Column DescriptorArray :(number of columns) * 8 bytes Adapted from"able 93 on pages 533-535 of IBM DB2 Universal DatabaseAPI Reference
Large Object (LOB) Descriptor Array Details . . . .. , . . ;. ...,.- * . ,.. . "-m,".7 O f f s Z z eCBytesj C 1
Table B-6 p-lwq:'
,,
,.
,
I
-,"-W?*.-~.x~<
~
0
4
unsigned long
Field length
4
4
unsigned long
Reserved
8
4
long unsigned
Log flag Indicates whetheror not the column is to generate log records when data is loaded.
The first LOB, CLOB, or DBCLOB encountered in the column descriptor array usesthe first element inthe LOB descriptor array The second LOB, CLOB, or DBCLOB encountered in the column descriptor array usesthe second element in the LOB descriptor array, and so on. Total length of LOBDescriptor Array:(numberof LOB, CLOB, and DBCLOB fields) * 12 bytes Adapted from"able 93 on pages 533-536 of IBM DB2 Universal DatabaseAPI Reference
Import Replace (Truncate)Log Record The import replace (truncate) log record is written whenever an IMPORT REPLACE operation is performed. Thestructure of the import replace log record is shown in Table B-7. Table 5 7
Import Replace (Truncate) Log Record Structure
. - , ...,
E%m?!m l
,
M s Z " 7 E e gfles0
12
. .
-
DOM RecordLog
. ~ ~ ~ , * ? = ~ , . ~ , ~ , . ~ ~ . Header Table(See
B-3)
12 Total length of Import Replace Log Record: 12 + size of Znternal bytes Adapted from Table94 on page 536 of IBM DB2 Universal DatabaseAPI Reference
ord
Appendix B: DB2 Log Records The secondset of pooland object IDS stored in the log record header identify the table being truncated."his is a Redo log record.
Rollback Insert Log Record The rollbackinsert log recordis written wheneveran insert row operation is rolled back. The structure of the rollback insert log recordis shown in Table M.
0
RecordLog DMS
6
6 long 8
Header Table(See
B-2)
Padding 4
identifier
12
2
unsigned short
14
2
spaceFreeunsigned short
Record length
Total length of Rollback Insert Log Record : 16 bytes Adapted from Table95 on page 536of IBM DB2 Universal DatabaseAPI Reference "his is aCompensation log record.
Reorganize Table Log Record The reorganizetable log recordis written whenever a reorganize table operation i s performed. Thestructure of the reorganize table log recordis shown in Table B-9.
2
0
12
12
252 Internal
RecordLog DOM
264
Header Table(See
B-3)
variable
Index unsigned short
token If the index tokenis not 0, it is the number that corresponds to the index that was used to cluster the reorganization (clustering index).
2 266
'
unsigned short
Temporary tablespace ID If the temporary tablespaceID is not 0, it is the number that corresponds to the tablespace that was usedto build the reorganized table.
:268 bytes Total length of Reorganize Table Log Record
Adapted from"able 96on page 536of IBM DB2 Universal DatabaseAPI Reference T h i s i s a Normal log record.
Appendix B: DB2 Log Records
CreateDrop IndexLog Record The creatddrop index log recordis written whenever an index is created or destroyed (dropped). Thestructure of the creatddrop index log recordis shown in Table B-10. Table B-l 0 Create/Drop Index Log Record Structure
. ~ . - ~ ~ ~ - ~ ” ~ ” ~ ~ ~ . ” ~ ~ ~ ~ ~ ~ ~ , . , - ~ ~ ’ . . ~ ~, ,, - .F .~ . .. :. ~ ~ - - ~ ~
*-+?‘c
I
Offset Size
(’bytes)
C Data Type
12
DOM Log RecordB-3) Header Table(See
char[2] 12
2
Padding
14
2
0
.
Description
Index unsigned short
token This token is equilivant to the m> column in the SYSIBM.SYSINDEXESsystem table. If the index tokenis 0, the log recordrepresents a meateldrop action that was performed on an internalindex (as opposed to a user index).
16
4
unsigned long
Index root page This is an internal indexidentifier.
Total length of Create/Drop Index Log Record : 20 bytes Adapted from Table97 on page 537 of IBM DB2 Universal DatabaseAPI ReferenceThis is an Undo log
record. This is an Undo log record.
CreateDrop Table, Rollback CreateDrop Table Log Record The creatddrop table, rollback creatddrop table log recordi s written whenever a table i s created or destroyed (dropped) or whenever a creatddrop table operation is rolled back. The structure of the creatddrop table, rollback create/drop table log record is shown in Table B-11. Table B-l 1 Create/Drop Table, Rollback Create/Drop Table Log Record Structure . ,,. .,... - ‘.&.‘J.. ,..<,,.....*-,q~.,,... offset Size (Bytes) C Data Type Description c-”” .m ”4“.”.
.,,.I
, , I
0
12
12
56
).“rl;-.,.’.r~.I.i-”~.~~.-~I,iUrrrri.:.-~rry~-(.Ue.....”~~.~u..r.,,runn
Record Log DOM Internal
Header Table (See
..
. ,
,
-..
“,mT
B-3)
variable
Total length of Create/Drop Table, RollbackCreatdDrop Table Log Record : 68 bytes Adapted from Table98 on page 537 of IBM DB2 Universal DatabaseAPI Reference
A creatddrop table log recordi s a Normal log record. A rollback creatddrop table log record is a Compensation log record.
P
!
1 !
I
511
Appendix B: DB2 Log Records
Alter PropagatiodCheck Pending, Rollback PropagatiodCheck Pending ChangeLog Record The alter propagatiodcheck pending, rollback propagatiodcheck pending changelog record is written whenever the stateof a table is changed as a result of adding or validating check constraints or whenever sucha table change operationis rolled back. The structure of the alter propagatiodcheck pending, rollback propagatiodcheck pending change log recordis shown in Table B-12. Table 5 1 2 Alter PropagationKheck Pending, Rollback PropagationICheck Pending Change Log Record ...., ..
,c : ,i ,~.,~,,, ,11
-
,,
Structure ._ , .., c
-.,"
,
-.-^...- ....-_. ~~
C Data &e
. . ~ . . ~ ~~,-.,..~."~,.~~.., .
..S
Offset
Size (Bytes)
0
6
6
2
char121
Padding
8
4
integer
Old flag value
e j l .
..
"_-.,....
/,.,
- . . . ,3..
i
.,;
,.:
I
,-,
,,A,>";7,:<;7*7+?*
.i.
Description
DMS Log Record Header (See Table B-2)
The following oldflag values are valid
12
4
integer
0 (FALSE)
Propagation Off
1 (TRTJE)
Propagation On
New flag value The following newflag values are valid 0 (FALSE)
Propagation Off
1 (TRUE)
Propagation On
Total length of Alter PropagatiodCheck Pending, Rollback PropagatiodCheck Pending Change Log Record : 16 bytes Adapted from Table 99 on page 538 of IJ3M DB2 Universal Database API Reference
An alter propagatiodcheck pending log record is a Normal log record. A rollback propagatiodcheck pending changelog record is aCompensation log record.
Appendix B: DB2 Log Records
Alter Table Add Columns, Rollback Add Columns Log Record The alter table add columns, rollback add columns log record is written whenever columns are added to an existing table with the ALTER TABLE SQL statement or whenever such a table change operation is rolled back. Thestructure of the alter table add columns, rollback add columns log record is shown in Table B-13.
0
DMS Log Record Header (See TableB-2)
6
char[2]
Padding
8
integer
Old column count The oldnumber of columns in thetable.
12
integer
New column count The new number of columns in thetable. The number of new or added columns is determined by subtracting the old column count fromthe new column count.
16
4
integer
Old LOBcount The old number of BLOB, CLOB,and DBCLOB columns in the table(used internally).
20
4
integer
New LOB count The new number of BLOB, CLOB, and DBCLOB columns in the table (used internally).
24
integer
Old LF count
28
integer
New LF count
32
integer
Old V
.flag value
The old number of variable lengthcolumns in the table (used internally). 36
4
integer
New VAR flag value The new number of variable lengthcolumns in the table (used internally).
40
variable
Old column array
Information aboutthe columns that were defined for the table before the ALTER TABLE SQL statement wasexecuted. Each element inthis array is 8 bytes long
Appendix B: DB2 Log Records
variable
variable
New column
array
Information about the columns that are defined for the table after the ALTER TABLE SQL statement is executed. Each element in this array i s 12 bytes long
Total length of Alter Table Add Columns, RollbackAdd Columns Log Record : 40 + (Number of old column arrays * 8) + (Number of new column arrays * 12) bytes Adapted from Table 100 on pages 63f2-639of IBM DB2 Universal Database API Reference This table contains one or more column descriptor arrays and/or one or more large object (LOB)descriptor arrays in both the old columnarray and the new column array. The structure of a column descriptor array is shown in Table B-5 and the structureof a LOB descriptor array is shown in Table B-6. An alter table add columns log record is a Normal log record.A rollback add columns log record is a Compensation log record.
Insert/Delete Record, Rollback Updatemelete Record Log Record The inseddelete record, rollbackupdatddelete record log record is written whenever a row of data is added t o (inserted) or removed from (deleted) a table or whenever a updatddelete record operation is rolled back(both an insert record and a delete record log recordis generated during an update operationif a row ofdata is altered).The structure of the inseddelete record, rollback updatddelete record log record is shown in Table B-14. Table 5 1 4 *uW;-a?..ps -.
Offset
InserVDelete Record, Rollback Update/Delete RecordLog Record Structure .,. '... . "W .v . .. . " ? ! T ? Y ,
,
I
DMS L o g Record Header Table(See
0
6
6
2
char[21
Padding
8
4
long
Record ID
12
2
unsigned short
Record length
14
2
unsigned short
Free space
16
2
unsigned short offset Record
18
variable
variable
B-2)
Record header data and
Total length of Insemelete Record, RollbackUpdatelDelete Record Log Record : 18 +Record length bytes Adapted from Table 101 on pages 639-640of IBM DB2 Universal Database API Reference
1
594 j 1I
Appendix B:DB2 Log Records
_i
This table contains oneor more data records. The structure of a data record header is shown in Table B-l5 and the structureof a data recordis shown in Table €3-16. Table 6-1 5 Data Record Header Details
0
1
unsigned char
Record type Records are classified as follows: Updatable Special Control Each class has threerecord types: Normal Pointer Overflow Record data can only be viewedif the record type is updatable.
1
1
char
Reserved
2
2
unsigned short
Record length
Total length of Data Record Header :4 bytes Adapted from “able 101 on pages 639-640 of IBM DB2 Universal Database API Reference
T
?
I 0
1
unsigned char
Record Type Records are classified as follows: Internal Control Formatted User Data A recordtype value of 1 indicates that the record is a formatted user data record.
1
1
2
char
Reserved
unsigned short
Fixed length Specifies the length of all fixed portions of the data. Note: If the record is an internal control record, this information cannot be viewed.
4
variable
unsigned short
Formatted record The formatted record can be a combination of fixed and variable length data. All fields contain a fixed length portion and, there are seven field types that have variable length parts.They are: VARCHAR LONGVARCHAR
i j
Appendix B: DB2 Log Records
' j
Table E 16 Continued
BLOB CLOB VARGRAPHIC LONG VARG DBCLOB The length of the fixed portion ofthe different field types can be determined as follows: DECIMAL
...
The lengthis a standardpacked decimal in the form: nnnnnn S. The length of the field is: (precision + 2)/2.The sign nibble (S) is XCfor positive (+), and xD or xB for negative (-1. SMALLINT INTEGER BIGINT DOUBLE
REAL
-
CHAR GRAPHIC The length is the fixed length size of the field. DATE The length is a 4byte packed decimal in the form: yyyymmdd where yyyy is year, mm is month, and dd is day. For example, April 3,1996 is represented as ~'19960403'.
TIME The length is a 3-byte packeddecimal in the form: hhmmss where hh is hour, mm is minute, andss i s seconds. For example, k32PM is representedaa 2133200'.
TIMESTAMP This field is a 10-byte packed decimal in the form: yyyymmddhhmmssuuuuuu where yyyy is year, mm is month, dd is day, hh is hour, mm is minute, SS is seconds, and uuuuuu is microseconds.
VARCHAR LONG VARCHAR BLOB CLOB VARGWHIC LONG VARG
I
Il
596_ _ I
, '
Table B-l 6
"nasazn. . mse? '
.
,
1
Appendix B: DB2 Log Records
'
Continued "-v->z'\v7*."w-::*
.I
i
SiZk'cByr
i
i
~
~
.
.
"
v
.
n
"
~
~
-
~
.-"mmmrU*r.q ~ ~ U ~
DBCLOB The lengthof the fixed portionof all variable lengthfields is 4. Note: Ifthe record is an internal control record,this information cannot be viewed.
Total length of Data Record Details: 4 bytes Adapted from Table 93 on pages 633-535 of B M DB2 Universal DatabaseAFI' Reference
An insertfdelete record log recordis a Normal log record.A rollback updaiddelete record log recordis a Compensation log record. The table descriptor record describes the column formatof the table. It contains an array of column structures, whose elements represent field type, field length, null flag, and field offset. The later is the offset, h m the beginning of the formatted record, where the fixed length portion of the field is located. For columns that are nullable (as specified bythe null flag), an additional bytefollows the fixed length portion of the field. This byte contains oneof the following values: NOT NULL
(0x00):There is a valid value in the fixed length data portion of the record.
NULL
(0x01):The data field value
is NULL.
The formatted user data record contains the table data that is visible to the user. It is formatted as a fixedlength record, followed bya variable length section. All variable field types have a 4-byte fixed data portion in the fixed length section (plus a null flag, if the column is nullable). Thefirst 2 bytes of the variable length section represent the offset fromthe beginning of the fixed length section, wherethe variable data is located. The next 2 bytes specifythe length of the variable data referenced by the offset value.
Update RecordLog Record .The update record log recordis written whenever arow is updated and its storage location is not affected. The structure of the update record log record is shown in Table B-17.
0
6
6
2
char[2]
8
4
long
Padding Record ID
12
2
unsigned short
New record length
14 unsigned short 2
DMS Log Record Header Table(See
Free space
B-2)
ad21
i
j
j j 597-
Appendix B: DB2 Log Records
" .
1 F
F
unsigned short
16
2
18
variable
Old recordheader and data
variable
6
DMS Log Record Header (See Table B-2)
&cord offset
variable
2
variable
4
long
Padding
variable
2
shortunsigned
Old record,length
variable
2
shortunsigned
Free space
variable
2
shortunsigned
Record offset
variable
variable
Record ID
New record header and data
Total length of Update Record Log Record: 36 + New record length + Old record length bytes Adapted from Table 104 on page 643 of IBM DB2Universal DatabaseAPI Reference
This is a Normal log record.
W! F4 Long Field Manager Log Records Long Field Manager log records are generated whenever long field data i s inserted, updated, or deleted and only if a database'slogretain andlor userexits configurationparameter has been turned on (enabled).To conserve log space, long field data inserted into tables is not logged if the database is configured for circular logging. In addition, when a long field valueis updated, the "before" imageis shadowed and not logged. Long Field Manager log records contain the header information shownin Table B-18, along with additional, record-specific information. Table E 18 Long Field Manager Log Record Header Structure
0
1
unsigned char
Originator code (Always3)
1
1
unsigned char
Operation type The following operation type values are valid
2
unsigned short
110
Add long field record
111
Delete long field record
112
Non-update long
field record
Pool identifier
4
2
unsigned short
Object identifier
6
2
unsigned short
Parent pool identifier (Pool ID of the dataobject)
8
2
unsigned short Parent
object identifier (Object ID of the data
'
Total length of Long Field Manager Log RecordHeader : 10 bytes Adapted from Table 105 on page 544 o f IBM DB2 Universal DatabaseAPI Reference
object)
A d d / ~ e l e t e / ~ o n - U ~ ~Long a t e Field Record Log Record Structure
Offset
Size (Bytes)
0
10
C Data Type
Description
Large Object (LOB) ~anagerLog Record Header Structure
Offset
Size (3i3ytes) C Data Type
0
1
unsigned char
1
1
signed short
2
2
~nsignedshort
4
Description O ~ ~ n a tcode o r (Always 5) Operation identifier Pool identifier
ed short
Object identifier Parent pool identifier
6
2
ed short
8
2
u n s i ~ e dshort
10
1
ed char
Parent object identifier Object type
Total length of Large Object (LO
Insert LOB Data (Logging On} Log Record Structure
Offset
Size (Bytes)
0
1
11
1
C Data Type char
Description
i "Ii
F
600__ . .
.
Appendix B: DB2 Log Records
~
12long unsigned4 16
8
length Data double
variable variable 24
address Byte
in object
LOB data
Total length of Insert LOB Data (Logging On) Log Record : 24 + Data length bytes Adapted from Table 108 on page 546 of IBM DB2 Universal DatabaseAPI Reference
Insert LOB Data (Logging Off) Log Record The insert LOB data (logging off) log recordis written whenever LOB data isinserted into a LOB column, or appended to existing data in a LOB column (and logging of the data hasbeen turned off). The structure of the insert LOB data (logging off) log record is shown in Table B-22. Table 6-22
U
11
Insert LOB Data (Logging OffJLog Record Structure
11
1 Padding
LOB Manager Log Record Header (See TableB-20) char
12
4
unsigned longlength Data
16
8
double
address Byte
in object
Total length of Insert LOB Data (Logging Off) Log Record : 24 bytes Adapted from Table 109 on page 546 of IBM DB2 Universal DatabaseAPI Reference
m
Transaction Manager Log Records The Transaction Manager generates log records that signify the completion of transaction events (i.e. commits and rollbacks). The timestamp values stored in these log records are inCoordinated Universal Time (CUT) format and mark the time, in seconds, since January 1,1970.
Normal CommitLog Record The normal commit log record is written whenever a COMMIT operation is performed. A COMMIT operation can occur when: The COMMIT SQL statement is executed An implicit COMMIT is performed during a CONNECT .RESEToperation. is shown in Table B-23. The structure of the normal commit log record
Appendix B: DB2 Log Records
1
601
~
__
Record Log
1
""
Header (See Table &l)
0
20
20
4
unsigned long
Time transaction committed
24
9
char[9]
Authorization ID of the application (if therecord log as propagatable)
is marked
Total length of Normal Commit Log Record : Propagatable:
33 bytes
Non-propagatable:
24 bytes
Adapted from Table110 on pages 546 -547of IBM DB2 Universal Database API Reference This log record is written for XA transactions in a single-node environment, oron the coordinator nodein a multi-node environment.
Heuristic CommitLog Record The heuristic commit log recordi s written whenever an indoubt transaction is committed. The structure of the heuristic commit log record is shown in Table €3-24. Heuristic Commit Log Record Structure
Table 5 2 4 :,
4
F.<.., .
:
I
-
J
,
.
.
"
:
l
.
.
ofPSet
Size (Bytes)
0
20
-
:
~
,
,
~
~
~
% W " T Z F & "
=
C Data Type
~
~
~
. , .
,
,_
\,
, ,>."".~..
L
.
,
,
Descripl
Log Record Header (See Table B-l)
20 24
n
9
unsigned long
Time transaction committed
char[9]
Authorization ID of the application (if therecord log propagatable)
is marked as
Total length of Heuristic Commit Log Record : Propagatable:
33 bytes
Non-propagatable:
24 bytes
Adapted from Table111 on page 547 of IBM DB2 Universal Database API Reference
MPP Coordinator CommitLog Record The MPP coordinator commit log recordis written on a coordinator node (in a multinode environment) wheneveran application performsupdates on oneor more subordinator nodes. Thestructure of the MPP coordinator commit log record is shown in Table B-25.
n
I
Appendix B: DB2 Log Records
~~
Table 5 2 5 MPP Coordinator Commit LC Dg Record Structure Log Record Header (See Table B-l)
0
20
20
SQLP-GXID 20
MPP Identifier of the transaction
unsigned short
40
2
42
variable
variable
9
Maximum node number
TNL ((Maximum node
number / 8) + 1)
Authorization ID of the application
chad91
Total length of MFP Coordinator Commit Log Record : 49 + (Maximum nook number 1 8 ) -+ 1bytes Adapted from Table 112 on page 647 of IBM DB2 Universal Database API Reference
MPP Subordinator Commit Log Record The MPP subordinator commit log recordis written on a subordinator node (in a multinode environment) whenever an application performs updates. The structure of the "PP subordinator commit log recordis shown in Table B-26. Table E 2 6 MPP Subordinator Commit Log Record Structure
0 20 20 40
Log Record Header (See Table B-l)
20
SQLP-GXID 9
chad91
.
MPP Identifier of the tramaction Authorization ID of the application
Total length of MPP Subordinator Commit Log Record :49 bytes Adapted from Table 113on pages 647-548 of IBM DB2Universal Database API Reference
Normal Abort Log Record The normal abort log recordis written whenever a transaction aborts after one of the following events occurs: The ROLLBACK SQL statement is executed A deadlock situation causes a selected transaction to be rolled back Uncommitted transactions are rolled back during a crash recovery Uncommitted transactions are rolled back after a STORE DATABASE and ROLLFORWARD DATABASE operation has occurred. The structure of the normal abort log recordis shown in Table B-27.
Appendix B: DB2 Log Records Table E 2 7 Normal Abort Log Record Structure ,
Offset
,
,
,,
"-r~~,~r...",,~~",~"
m & e s )
0
20
20
9
.
~~*~"""~~.,-~ri-"-
C Data Ty
.."~(....,
-.
.CI.-II..I-".."r^.."-~ r---....-,.n-.
iP Log Record Header (See Table B-l) Authorization ID of the application (if the logrecord i s marked as propagatable)
chad91
Total length of Normal Abort Log Record : F'ropagatable:
29 bytes
Non-propagatable:
20 bytes
Adapted from Table114 on page 548 of IBM DB2 Universal Database API Reference
Heuristic Abort Log Record The heuristic abort log record is written whenever an indoubt transaction is aborted. The structure of the heuristic abort log recordis shown in Table B-28.
Size (Bytes) 0
20
20
9
C Data Q p e
Description
, .
,
.~
Log Record Header (See Table B-l) chart91
Authorization ID of the application (if the logrecord is marked aa propagatable)
Total length of Heuristic Abort Log Record : Propagatable:
29 bytes
Non-propagatable: 20
bytes
Adapted from Table115 on page 548 of IBM DB2 Universal Database A P I Reference
Local Pending List Log Record The local pendinglist log record is written whenever a transaction is committed and a pending list exists. A pending list is a linked list of non-recoverable operations(for example, the deletion of a file) that can only be performed whenthe COMMIT SQL statement is executed. Thestructure of the local pendinglist log recordis shown in Table B-29.
0
20
20
4
Record Log unsigned long
Header (See Table B-l)
Time transaction committed
Appendix B: DB2 Log Records Table B 2 9
Continued
variable
33
variable
Pending list entries
Total length of Local Pending List Log Record : hpagatable:
33 + size of Pending list bytes
Non-propagatable:
24 + size of Pending list bytes
’
Adapted from Table 116 on pages 548-549 of IBM DB2 Universal Database A P I Reference
Global Pending List Log Record The global pending list log record is writtenwhenever a transaction using two-phase commit is committed and a pending list exists. A pending list is a linked list of nonrecoverable operations (for example,the deletion of a file) that can only be performed when the COMMIT-SQL statement is executed. Thestructure of the global pendinglist log recordis shown in Table B-30. Table B-30 B:’”-
”., ,
Global Pending List Record Structure
. , , , , r ~ , U , , ~ C ; . r ; r a l p M y , U r -,.-
O f f s e n e (Bytes) 0
20
20
4
33
variable
.14”
...-.
_...I _ y l -
“””._
Descripl
Record Log
9 24
.-..... -_..,.”....._,.,.,.
.__,.~” - ’ - ~ E ” Y , , ~ . ” ~ “ . ~ . . ” ~ r
C Data Type
Header (See Table B-l)
unsigned long
Time transaction committed
chad91
Authorization ID of the application (if the log record is marked as propagatable)
variable
Global pending list entries
Total length of Global Pending List Log Record : hpagatable:
33 + size of Global pending list bytes
Non-propagatable:
24 + size of Global Pending list bytes
Adapted from Table117 on page 549 of IBM DB2 Universal Database API Reference
XA Prepare Log Record The XA prepare log recordis written to mark thepreparation of a transaction as part of a two-phase commit. The structure of the XA prepare log record is shown in Table l3-31.
Appendix B: DB2 Log Records
Log Record Header Table (See
20
0
4 20 24 20
140
164 184
4
32
216 220
8
Log space used
variable
XA identifier of the transaction
char[20]
Application name
chad321
Application identifier
by transaction
chad41
Sequence number
char[8]
Authorization ID of the application
char[20] 20 228 4
used Database alias
248
unsigned page Code long
252
4
256
variable variable
El)
unsigned long
Time unsigned long
by client identifier
transaction prepared Log synchronization information
Total length of XA Prepare Log Record : 256 + size of Log synchronization infomation bytes Adapted from Table 118 on pages 548-549of IBM DB2 Universal DatabaseAPI Reference This log record is written for XA transactions in a single-node environment, or on the coordinator nodein a multi-node environment.This log record describesthe application that started thetransaction, and is used to recreate indoubt transactions.
MPP Subordinator PrepareLog Record The MPP subordinator prepare log recordis written on a coordinator node(in a multinode environment)to mark the preparation of a transaction as partof a two-phasecommit. "he structure of the XA subordinator prepare log recordis shown in Table B-32.
&sei
MPP Subordinator Prepare Log Record Structure ..__.~, . . , ~.~~~",~~""-".- - . - .Size (Bytes) C Data
0
20
20
4
unsigned long
24
6
unsigned char[6] Coordinator Log Sequence Number
30
20
SQLP-GXID
MF'P Identifier of the transaction
50
20
chad201
Application name
70
32
chad321
Application identifier
102
4
chart41
Sequence number
106
8
char181
Authorization ID of the application
114
20
chad201
Database alias used by client
Table 5 3 2 ""ym.,""
I
. * . . ~ , : ~ ~."~ "3 , . ~ ~ -..-
Log Record Header Table (See
..
B-l)
Log space usedby transaction
Continued Offset 138
Size (Bytes) 4
C Data Type
Description
unsigned long
Code page identifier
unsigned long
Time transaction prepared
s log record describes the application that started the transaction, and is used to recreate indoubt tr~sactions.
ackout free log record is written to mark the end of a backout fkee interval. The out fkee interval is a set of log records that are not to be compensated if a transaction is abo~ed. The structure of the bac~outfree log record is shown in Table
Backout Free Log Record Structure Offset
Size (Bytes)
C Data Type
Description Log Record Header (See Table I3-1)
unsigned char[91 Compensate Log Sequence Number
anager generates log records that are associated with the followin ctions:
and the end of the activities that nager log records mark the f ~ c t i o n sperform and all o records are pro~agatable,regardtables are affected when the ~ n c t i is o~ executed.
ion start log record is w structure of the mi
~igrationStart Log Record Structure
Offset
Size (Bytes)
0
20
C Data Type
20
10
ehar[lOl
30
2
unsigned short
Description
Migrate from release
' ation end log recor tion operation. The stru
letion of a catalog
~ i ~ r a t i End o n Log Record Structure
Offset
Size (Bytes)
0
20
C Data Type
Description
ad start log record is written wh load start log record is shown in Load Start Log Record Structure
Offset
Size (Bytes)
0
20
20
4
2
2
C Data Type
Description
unsigned long
Log r
he s t ~ c t ~ r e
Appendix B: DB2 Log Records Table 5 3 6 W " ?
Continued
Wset 26
c Data
; ~ " ~ - ~ - ~ ~ " ' ' ? ~ ~ r r - " ~ N 1 l . " - ~ ~ ~ - .
unsigned short
2
28
1
29
variable
n?:Tm=.-m
Descmptlon Object identifier
unsigned Flag char
.
Object pool list
variable
Total length of Load Start Log Record :29 + size of Object pool list bytes Adapted from Table 122 on page 552 of IBM DB2Universal Database AF'I Reference
Table LoadDelete Start Log Record The table load delete start log record is written whenever the delete phase of a load operation i s started (the delete phase is only started if duplicate primary keys are found). Thestructure of the table load deletestart log recordi s shown in Table B-37.
:
offset
Size (Bytes)
0
20
C Data "ype
Description
Record Log
Header Table (See
B-l)
Total length of Table Load DeleteStart Log Record : 20 bytes Adapted f%omTable 123 on page 552 of IBM DB2 Universal Database AF'I Reference
Load Delete Start Compensation Log Record The load deletestart compensation log record is writtenat the end of the delete phase of a load operation(the delete phaseis only started if duplicate primary keys are found). The structure of the load deletestart compensation log record is shown in "able B-38. Table 5 3 8 p-".nm.Cap;.
Load Delete Start Compensation Log Record Structure
-
~
Offset Size (Bytes) 0
20
~
,
B
l
C Data Type
,
'
",' ~ ~ - n, . . . . y ! . l * I ' Z l y " h ~ . ~ ~ ~ ~ ~ ~ ~ " - " , - ~ * ' .-.-7.--
*"v-.',. m"!."+
Description
Record Log
Header (See Table B-l)
Total length of Load Delete Start Compensation Log Record : 20 bytes Adapted from Table 124 on page 552 of IBM DB2 Universal Database API Reference
Load Pending List Log Record The road pending list log record is written whenever a transaction associated witha load operation is committed and a pending list exists. A pending list is alinked list of non-
Appendix B: DB2 Log Records recoverable operations (for example,the deletion of a file) that can only be performed when the transaction is committed. The structure of the load pendinglist log recordis shown in Table B-39. Load Pending List Record Structure
Table 5 3 9 ~
4
~
~
,
~
m
*
~
r
l
.
~
n
.
Offset
Size (Bytes)
0
20
-
r
-
.
.
'
:
C
'
.
~
N
:
.
~
~
~
~
:
"
-
~
.
~
~
Log Record Header Table (See
unsigned long
20
~
~
~
~
~
"
~
,
~
.
~
~
:
~
~
~
~
C Data Type Description
24
9
chad91
33
variable
variable
'
. Time transaction
B-l)
committed
Authorization ID of the application (if the log record is marked as propagatable) Pending list entries
Total length of Load Pending List Log Record : F'ropagatable:
33 + size of Pending list entries bytes
Non-propagatable:
24 -+ size of Pending list entries bytes
Adapted from Table125 on pages 552-553 of IBM DB2 Universal Database A P I Reference
A normal commit log record does not follow the load pendinglist log record.
Backup EndLog Record The backup end log recordis written upon the successful completion of a database or table space backup operation. Thestructure of the backup end log recordi s shown in Table M O . Table B 4 0 Backup End Log Record Structure )
r
r
Offset Size (Bytes) 0
20
20
4
r
l
.
n
=
~
C Data Type Description
~
,
Log Record Header Table (See
unsigned long
~""".~
~
~
"
"
~
~
I
B-l)
Backup timeend
Total length of Backup End Log Record : 24 bytes Adapted from Table 126 on page 553 of IBM DB2 Universal Database API Reference
Tablespace Rolled ForwardLog Record The tablespace rolled forward log record is written upon the successful completion ofa table space rollforward recovery operation. Thestructure of the tablespace rolled forward log record is shown in Table B-41.
~
L610 . ~
_I
1 t
4
j
Appendix B: DB2 Log Records
Table B 4 1 Tablespace Rolled ForwardLog Record Structure ~
F" 0
2
~~
9
Record Log
20
20
unsigned short
Header (See Table B-l)
Table space identifier
Total length of Tablespace Rolled Forward Log Record : 22 bytes Adapted from Table127 on page 553 of IBM DB2 Universal Database API Reference
Tablespace Roll ForwardTo Point-In-Time Start Log Record The tablespace roll forward to point-in-time Start log recordis written whenever a table space rollforward recovery to a specific point-in-time operation is started. The structure of the tablespace roll forwardto point-in-time Start log recordis shown in Table B-42. Table B 4 2 Tablespace Roll ForwardTo Point-In-TimeStart Log Record Structure
.
.
,. .?.. d m v m , . . . . . . i * ... , a . . ..
0 0
4
unsigned long
Timestamp for this log record
4
4
unsigned long
Timestamp to which table spaces are being rolled forward
8
2
unsigned short
Number pools of
10
variable
integer
*List of pool IDS that are being rolled forward
being rolled forward
Total length of Tablespace RollForward To Point-In-Time Start Log Record : 10 + size of Pool ID list bytes Adapted from Table 128 on pages 553-554 of IBM DB2 Universal Database API Reference
Tablespace Roll ForwardTo Point-In-Time End Log Record The tablespace roll forward to point-in-time end log record is written upon the successful completionof a table space rollforward recovery to a specific point-in-time operation. The structure of the tablespace roll forward to point-in-time end log record is shown in Table B-43. Tabie 6-43 Tablespace Roll Forward To Point-In-Time EndLog Record Structure
unsigned long
Timestamp for this record log
4
unsigned long
Timestamp to which table spaces were rolled forward
4
integer
A flag whose value is TRUE if the rollforward operation was
0
4
4 8
'
successful and FALSE if the rollforward operation was canceled.
Total length of Tablespace RollForward To Point-In-Time End Log Record: 12 bytes Adapted from Table129 on page 554 of IBM DB2 Universal Database API Reference
q
n 611! ' 1
1 1
Appendix B: DB2 Log Records
m
l
Farrrl Datalink Manager Log Records Datalink Manager log records are generated whenever DDL and DML operations involving DATALINK columns with the file link control attributes setare performed. Datalink Manager log records contain the header information shown in Table B-44, along with additional, record-specific information.
Table B 4 4 Datalink Manager Log Record Header Structure
0
1
unsigned char
Component identifier (Always 8)
1
1
unsigned char
Function identifier The following function identifier values are valid
2
LINK-FILE (33)
Link file
UNLINKJTLE
(33)
Unlink file
DELETE-GROUP (33)
Delete group
DELXTE-PGROUP
(33)
DLFM-PREPARB (33)
DLFM F'repare
Delete PGroup
Padding
Total length of Datalink ManagerLog RecordHeader :4 bytes Adapted from Table 130 on pages 554-555 of IBM DB2 Universal DatabaseAPI Reference
Link File Log Record The link filelogrecord i s written whenever an insert or update operation on a DATALINK c o l u m n creates alink to a He.The structure of the link file log recordis shown in TableM 5 . Table B 4 5 Link File Record structure
F&&e S&e t CByleij
:
,,
''
.
0
10
4
4
long
Server ID
8
4
integer
ReadOnly Flag
.
3
.
,
.
. , ) . . < , I
,
.
,
.
.,;
Datalink ManagerLog Record Header (See TableB-44)
12
8
chad81
Authorization ID
20
17
CharD71
Group ID
37
1
char[ll
Padding
38
2
unsigned short
Access Control
...j
..,(
Appendix B:DB2 Log Records
L "
'
Table B 4 5
Continued
y?Vn""z
,
Off'set 3 40
3
.
, ",,.C"
D
.
9
49
Recoverychar[71 52
,
'
Z
..,. ...
.
-
.
t
i
-TTf4l:T'".T
o
chad91
F'refk ID
char[3]
Padding
n
-":. ~
.
-
.
n
"
'
"
B
.
~
"
,
~
,
~
.
ID
7
59
1
chad11
60
4
unsigned long
64
variable
variable
Padding Stem name length
name Stem
Total length of Link File Log Record : 64 + Stem name length bytes Adapted from Table131on page 555 of IBM DB2 Universal Database API Reference
One link file log record is written for each new link to a file, This is an Undo log record.
Unlink FileLog Record The unlink file log record is written whenever an update or delete operation on a DATALINK columndestroys (drops) link a to a file. Thestructure of the unlink file log record is shown in Table -6. Table B 4 6 Unlink File Record Structure ~~~~m~i-msamcrrsan
.
. ...,.. ""!,.Fr""c"":,L.
Data &e
Offset
Size
0
10
4
4
long
Server ID
8
9
charbl
PrefkID
17
3
char[3]
Padding
20
7
chad71
Recovery ID
27
1
char[l]
Padding
28
4
unsigned long
32
variable
variable
~'C
'
"*"m ~ . : : : > ? ; , v , : ~ . . . . e : ,~L~,,:?:~
Description Datalink Manager Record Log
Header (See Table B 4 )
Stem name length
name Stem
Total length o f Unlink File Log Record:32 + Stem name length bytes Adapted from Table132 on page 556 of IBM DB2Universal Database API Reference
One link file log recordis written for each link that is dropped. This is an Undo log record.
~
,
~
.
Appendix B: DB2 Log Records
Delete GroupLog Record The delete grouplogrecord is written whenever a table containing one or more DATALINK columns (that have the file link control attribute) isdropped. Thestructure of the delete group log record is shown in Table B-47. Table B 4 7 Delete Group Record Structure ....... -. . . . ..,...... .... -.. ............ _..”
...........
” ”
Datalink Manager Log Record Header (See Table B-44)
0
10
4
4
long
Server ID
8
7
chad77
Recovery ID
15
1
charill
16
17
char[lfl
Padding Group ID
33
3
char[3]
Padding
Total length of Delete Group Log Record : 36 bytes Adapted from Table 133 on page 556of IBM DB2 Universal Database kpI Reference
Onedeletegrouplogrecord is written for each DATALIN’Kcolumn for each DataLinks File Manager (DLFM) configuredin the datalinks configuration file.A log record is only written for a given DLFM ifthat DLFM has thegroup defined onit when the table is dropped. T h i s is an Undo log record.
Delete PGroupLog Record The delete pgrouplog recordis written whenever a table space containing one or more DATALINK columns (that have the file link control attribute) isdropped. Thestructure of the delete pgroup log recordis shown in Table l3-48. Table B 4 8 Delete PGroup Record Structure
......... . . -~....
_%
..............,..
...
.Y..-..-...(I..V
... .r”m”””.
.....
Datalink Manager Log Record Header (See Table B-44)
U
10
4
4
long
Server ID
8
6
SQLU-LSN
Pool log life
sequence number
“he SQLU-LSN data type is defined as: union ( chart61;
short[3]; 14
2
unsigned short
1; Pool ID
Continued
Offset
Size (Bytes)
C Data Type
Description
ark the ~ r e ~ a r a t i oofna transactio~that he str~ctureof the
DLFM Prepare Log Record Structure
Offset
Size (Bytes)
0
10
C Data Type
Description
are log record is sh
+6 ith
of the example p r o ~ a m shown s in this book operating system, using the
To establish comm~icationsbetween a client ~orkstatio base server, perform the foll steps (after install in^ ~ l i e nAt ~ ~ l i ~ a~ nt ai b~ lne r( and the DB2 ~niversal s en^ K) software):
.Invoke the Client ~ o ~ f i ~ r a tAssistant ion by m for ~ i n d o w NT s Programs menu. no database connections have bee
The DBZ Client Con~gurati~fl Assistant Welcome Panel
tion has been made, press the ~ e xpush t butt ase page of the Add ~ a t a ~ a~s e ~ aa ~
~
~
i
d
~
Appendix C:How the Example Programs Were Developed
Figure C-2
The Source page of the DB2 Add Database SmartGuide
Figure C-3
The Target Database page of the D62 Add Database SrnartGuide
~~~~
..
.
.
Appendix C:How the Example Programs Were Developed
i 6 17
5. Once the database is selected, press the Next push button to move to the Alias
page of the Add Database SmurtGuide and enter a database alias and description (seeFigure C A ) .
Figure C 4 The Alias page of the D62 Add Database SrnartGuide
6. When an alias and a description have been entered, press the Next push button
to move to the ODBC page of the A& Database SrnartGuideand specify how the database is to be registered with ODBC (see Figure C-5). 7. Finally, press the Do& push button to complete the configuration setup. If everything has been entered correctly, the Confinnation dialog shownin Figure C-6 will be displayed you can test theconnection to make sure it is working properly by pressing the Test Connectionpush button (see Figure C-6).
A i
l
__618
1
Appendix C:How the Example Programs Were Developed I "
.".
'l Figure C-5
TheODBC page of the D62 Add Database SmartGuide
'l & A I
I,
Figure C-6
The configuration confirmation dialog
Testing The Connection 8. After the Tkst Connectionpush button on the Confirmation dialog is pressed, the
Connect 2% DB2 Database dialog shownin Figure G 7 will be displayedand you will be promptedfor a user ID and password. 9. When t h i s panel is displayed, providea valid user ID and password and press the OK push button. A DB2 Message dialog likethe one shownin Figure C-8 should appear. 10. After the connection has been configuredand tested, the Client Configuration Assistant panel similar to the one shownin Figure G 9 should replacethe Add Database SmartGuide and the newly configureddatabase should belisted in the Available DB2 Databases list control.
I
Appendix CHOWthe Example Programs Were Developed
Figure C-7
The DB2 connection information dialog
l' !:
!p, !
I
-
Databars product D82MT 5.20 SOL aulhaizatm ID I usnd Database allas I SAMPLE
1:
,
..
-
Figure C-8
The "connection test successful" message dialog.
'
!
\
" .
6 19."l
I
Appendix C:How the Example ProgramsWere Developed
m
How TheExamplesAreStored The Diskette
On
To aid in application development, each of the examples shownthroughout the book are provided, in electronicformat, on the CD that accompanies this book. T h i s CD contains both a 90 dayevaluation copy of DB2 Universal Database Personal Editionand a subdirectory that contains the example programs."his subdirectory (ewlmples) is divided into the following nine subdirectories: H Chapter-05
R Chapter-06 W Chapter-07
Chapter-08 W Chapter-09 W Chapter-l0 H Chapter-l1 W Chapter-l2 H Chapter-l3 R Chapter-l4 Each of these directories contains the examples that were presented in the corresponding chapters in the book.
Fnn(
How To Compile And Execute The Examples The followingsteps can be performedto recompile and execute any example program stored on the diskette: 1. Create a directoryon your hard drive and copy the example programinto it. 2. Invoke the Visual C++ 6.0 Developer Studio.
3. Select New from the Visual C++6.0 Developer Studio File menu. 4. When the New panel is displayed, highlightWin32 ConsoleApplication, enter the appropriate location (hard drive and directory),and a project namethat corresponds to the name of the directory that contains the example program (seeFigure (2-10). 6. When the Win32 Console Application wizard is displayed, selectthe Empty Project radio button and press the Finish button (see Figure C-11). 6. When the new projectis created, select the Project, Settings . . . menu item, choose All Configurations in the Settings For: combo box, and enter thelocation (path) of the DB2 SDK header files in the CIC++, Preprocessor, Additional include directories entry field (see FigureC-12).
Appendix C:How the Example Programs Were Developed ! "_ 62 1 ,
.
" "
Figure C-l 0 The New Projects panelof the VisualC++ 6.0 Developer Studio
' I
Figure C-l1
The first panel of the Win32 Console Application wizard
Figure C-l 2
The UC++Project Settings panelof the Visual C++6.0 Developer Studio.
f 622 ~- L""
" "
'
Appendix C:How the ExampleProgramsWereDeveloped 7. Next, enter thelocation (path) of the DB2 SDK library files in the Link, Input,
Additional library path entry field (see FigureC-13).
Figure C-l 3 The LinWlnput.Project Settings panelof the VisualC++ 6.0 Developer Studio.
8. Then, addthe DB2API.LIB and DB2APlE.LIB libraries to the listof library files shown in the Link, General, Objectllibrary modules entry field (see Figure(2-14).
Figure C-l 4 The LinWGeneral Project Settings panelof the Visual C++ 6.0 Developer Studio. 9. Once the new project settings have been saved, selectthe File Viiw tab in the
right-hand window, highlight the Source Files project files entry, press the right mouse button to display the pop-up menu, and selectthe Add Files to Folder . . . menu item (see Figure(2-15).
Appendix C:How the Example Programs Were Developed
Figure C-l 5 The Add New Files to Folder
~
623 .~
."
. . . menu item
10. Highlight the example file name shown in the Insert Files into Project dialog and press the OK push button (see Figure C-16).
Figure C-l 6 The file selection window. NOTE: All files with .SQC extensions must be precompiled before they will appear in the file selection window (and before they can be ad&d to a project). The following batch file (sqc-comp.bat) was used to precompile the .SQC examples:
Appendix C:How the Example Programs Were Developed REM
***
BUILD EbIBEDDED SQL-API
EXAMPLESCO-
FILE
***
echo o f f
REM *** CONNECT TO THE SAMPLE DATABASE*** db2 connect to sample user userid using password REM *** PRECOMPILE THE.SQC SOURCE CODE FILE *** db2 prep %l.sqc target cplusplus bindfile using %l.bnd
m *** RENAME
FILE***
THE QENERATED copy %l.cXx %l.cpp del%l.cxx
*** BIND THE APPLICATION TO THE db2 bind %l.bnd
SAMPLE
*** DISCONNECT FROM THE db2 connect reset
DATABASE ***
REM
REM
SAMPLE
DATABASE ***
11. Compile and execute the program.
NOTE: An appropriate User ID, and Password must be provided in the SQLConnect( function calls that are used to connect to the DB2 SAMPLE database. Also, if the user ID specified is not the same as the user ID of the creator of the SAMPLEdatabase, SQL statements that interact with tables in the SAMPLE database may have to be qualified. If this isthe case, contact the System Administratorfor information about the appropriate qualifier to use.
BIBLIOGRAPHY International Business Machines Corporation.1997.IBM DB2 Universal Database Administration: Getting Started,Version 5. SlOJ-8154-00.IBM Corporation. International Business Machines Corporation.1998.IBM DB2 Universal Database Administration Guide,Version 5.2. SlOJ-8157-01.IBM Corporation. International Business Machines Corporation.1997.IBM DB2 Universal Database API Reference, Version5. SlOJ-8167-01.IBM Corporation. International Business Machines Corporation.1998.IBM DB2 Universal Database Command Reference, Version5.2. SlOJ-8166-01.IBM Corporation. International Business Machines Corporation.1997.IBM DB2 Universal Database Embedded SQL Programming Guide, Version 5.SlOJ-8158-00.IBM Corporation.
This Page Intentionally Left Blank
mI Index Note: Boldfacenumbers indicate illustrations. access plans (See packages) accounting strings, 79-80, 188-189
ACTIVATE DATABASE, 135, 136
activation time, triggers, 13 ADD NODE, 67,476 aliases, 5, 14,15,515 ALTER TABLE, 10 APPC, 67 application development, 43-59
application programming interface (API), 48,49, 52-54,64,59 arithmetic, 46 binding, 57,58-59
call level interface (CLI), 48,49,51-52,63,59
Client Application Enabler (CAE), 55 COMMITLROLLBACK, 58 compilers, 55 database management systems (DBMS), 52 Database Manager, 57 design of applications, 46-48
distributed units of work (DUOW),48 elements of an application, 46,47
EndTransO, 58 environment for development, 55 input, 46 inputloutput (YO), 46 libraries, 49,52 linking databases,55 logic, 46,48 memory, 46
MicrosoR Foundation Class (MFC),49 open database connectivity (ODBC),52 output, 46 precompilers, 49-50,55, 58-59
Presentation Manager, 49 programming languages, 48,49,66
remote units of work (RUOW), 48 schema, 57 Software Developers Kit (SDK), 55 source code files, 58-59 SQL statements, 48,49-50, 61
static vs. dynamic SQL, 49-50,61
stored procedures,55 test data generationfor applications, 57 testing applications,56-57 transaction logging, 48 transactions, 48,57-58 user interfaces,49 volatility of data, 48 application preparationAPIs, 65
application programming interface (API), 48,49, 52-54,64,59,61-73,75-82
accounting strings,77, 79-80
API function return codes, 70
application preparation APIs, 65 BACKUP API, 54,64 backuphecovery APIs, 65
basic structure,62,63 binding, 77,78 body of API source code files, 62 call level interface (CLI) vs., 61-62
categories of API, 52-54, 62-66
C-language versionof APIs, 66
clientlserver diredory management APIs, 64 data handlingAPIs, 415470,415
data structuresused in API functions, 67 data utilityAPIs, 65 database configuration
APIs, 64,187-233 database connection services (DCS), 237 database controlAPIs, 64, 133-185
database directory management APIs, 64, 235-289
Database Manager configurationM I S , 64, 187-233
Database Managercontrol H I S , 64,133-185 database migrationM I S , 329-414
Database SystemMonitor APIs, 65,505-552 debugging APIs, 71 disaster recovery APIs, 329-414
dynamic link library (DLL), 71
embedded SQL vs., 77,78
atabase connection
setting values, 135 setting connection settin values, 135
c o ~ ~ i t ~cont~o ent concu~enc
eter values, s t o r ~ ~ e ,
9
ata~ase~irect
ase ~ r c ~ i t e c t ~ r e
Index API function returncodes, 70 first-phase errors,511 GET ERROR MESSAGE,
70,81 GET SQLSTATE, 71,81 manually resolving indoubt transactions, 512-514 second-phase errors,512 SQLCA return codes, 70,81 SQLSTATE codes, 71,81 Transaction Manager database errors,512 two-phase commit, 511-512 escalation of locks, 32,37-38 ESTIMATE DATABASE SYSTEM MONITOR BUFFER SIZE, 508,515 event monitors,5,14,15 event, triggers,13 exception handling, 77,79,
188-189
exclusive 6 lock, 31,34 executable applications,APIs, creating, 71,72 executable load module (EXE)
FORGET TRANSACTION STATUS, 513-514,513,515 FORTRAN, 49,66,79 function returncodes, 70 functions, data structures used in API functions,
67-69 general application programming APIs, 65 GET ADDRESS, 79 GET CURRENT CONTEXT, GET DATABASE CONFIGURATION, 189,
190,475,476 GET DATABASE CONFIGURATION DEFAULTS, 189,190 GET DATABASE MANAGER CONFIGURATION, 188,
190,475,476
71,81 292 FETCH TABLESPACE QUERY, 290,291 fields, 7 file formats supportedfor import, export,load,
419-420 file naming conventions, 3 first-phase errors,511 flags, 67 float (real) datatypes, 8 FORCE APPLICATION,136 foreign keys, 11
HAVING, 46 header of API source code, 62 history files, recovery, 16-17,
16,333-335,334
555
GET DATABASE MANAGER CONFIGURATION DEFAULTS, 189,190 GET DCS DIRECTORY APIs, 71 ENTRIES, 237,238,239 EXPORT, 69,57,67,416,420, GET DCS DIRECTORY 554 ENTRY FOR DATABASE, supported file formats, 237,238,239 419-420 GET ERROR MESSAGE,70, FETCH TABLESPACE CONTAINER QUERY,290,
GET TABLE PARTITIONING INFORMATION, 472,476 GET/UPDATE MONITOR SWITCHES, 507,515 granularity, triggers,13 graphic datatypes, 9 GROUP BY, 46
GET NEXT DATABASE DIRECTORY ENTRY,236,
238 GET NEXT NODE DIRECTORY SCAN,237,
238
GET NEXT RECOVERY FILE HISTORY ENTRY,
335,336 GET ROW PARTITIONING INFORMATION, 476 GET ROW PARTITIONING NUMBER, 472 GET SNAPSHOT,508,515 GET SQLSTATE,71,81
I/O parallelism, 473 IBM, 4 IMPORT, 57,67,69,416,420, 554 LOAD vs. IMPORT, 416-417 supported file formats,
419-420 inconsistent data,problems,
330,331 indexes, 5,lO-11,15 binary trees,10 columns, 11 composite keys, 11 foreign keys, 11 keys, 10,ll primary keys, 11 records, 11 rows, 11 unique keys, 11 indoubt transactions,65,69,
505,512 COMMIT ANINDOUBT TRANSACTION,
513-514,515 FORGET TRANSACTION STATUS, 513-514,515 LIST DRDA INDOUBT TRANSACTIONS, 515 LIST INDOUBT TRANSACTION WITH PROMPTING, 513-514,
515 LIST INDOUBTTRANSACTIONS, 512,515
1
Index manually resolving indoubt transactions, 512-514 ROLLBACK A N INDOUBT TRANSACTION, 513-514,515 input, 46 input/output (WO), 46 V 0 parallelism, 473 INSERT, 13,31,38,57,418 INSTALL SIGNAL HANDLER, 79 integer (INT) data types, 8 intent exclusive (K)locks, 32 intent none (IN) locks, 32 intent share (IS)locks, 32 intention, locking, 32 interleaved transactions,25 inter-partition parallelism, 473,474,475 INTERRUPT, 79 INTERRUPT CONTEXT, 555 interrupts, 77,188-189 Intersection operation, 4 intra-partition parallelism, 473,474,475 IPWSPX, 68 isolation levels, 25-29 ISOLATION option, 29 Join operation, 4 keys, 1 0 , l l large objects (LOB),5 libraries, 49 CL1 and, 52 linking databases, 55 LIST DRDA INDOUBT TRANSACTIONS, 515 LIST INDOUBTTRANSACTION WITH PROMF'TING, 513414,515 LIST INDOUBT TRANSACTIONS, 512,515 LOAD, 57,69,417-419,420 IMPORT vs. LOAD, 416-417
LOAD QUERY, 420 supported file formats, 419-420 LOAD QUERY, 420 LOCK TABLE, 37-38 lock wait, 29 locking, 23,29-39,30 attributes of locks, 30 COMMIT, 31 compatibility of locks, 32, 35-36,36 concurrency, 32,33-34 conversion of locks, 32,37 Database SystemMonitor, 506 deadlocks, 32,34-35,34 duration of lock, 30 escalation of locks, 32,37-38 exclusive (X) lock, 31,34 intent exclusive (K)locks, 32 intent none (IN) locks, 32 intent share(IS) locks, 32 intention, 32 lock wait, 29 mode of lock, 30 next keyexclusive (M) lock, 31 next key share (NS) lock, 31 next key weak exclusive ( N W )lock, 31 object of lock, 30 performance vs. locking, 32-38 ROLLBACK, 31 share (S) lock, 31 share with intentexclusive (SIX)locks, 32 size of lock, 30 states, lock states, 30-32 super exclusive (Z)lock, 31 update (U)lock, 31 weak exclusive (W) lock, 31 Locks group, Database System Monitor, 506-507 log files (See also transaction logging), 16-17,69
633
ASYNCHRONOUS READ LOG, 336 space management,39 synchronization of databases, 38-39 Log Manager, 39 extract specific logrecord, ASYNCHRONOUS READ LOG, 336 logic, 46,48 logical drives, 19 long varchar datatypes, 9 long vargraphic datatypes, 9 map, partitioning, 472 memory, 46 synchronization of databases, 38-39 memory copy functions, 79, 188-189 Microsoft, 52 Microsoft Foundation Class ( W C ) , 49 MIGRATE DATABASE, 330, 336 migration, 330,336 database migrationMIS, 329-414 MIGRATE DATABASE, 330,336 multipartition nodegroups, 472 named pipes,68 naming conventions H I S , 66 database names,20 directories and subdirectories, 18 . NetBIOS, 68 NetWare, 68,235 registeringlderegistering DB2 servers with, 237-238,239 network supportAPIs, 65 next key exclusive (M)lock, 31
Index next key share(NS) lock,
31
overlapping transactions,39 packages (access plans),5,13,
next key weakexclusive 0 15 lock, 31 parallelism (See also nodes and nodegroups, 68 Partitioning),472-475 coordinator node, 472 U 0 parallelism, 473 enabling database inter-partition parallelism, partitioning, 475-476 . 473,474,475 multipartition nodegroups, intra-partition Parallelism,
472 node management APIs, 64 partition management
MIS,471-504 workstation directories,20 nondelimited ASCII files supported for import, export, load,419-420 nonrepeatable reads,27,28 Novel1 NetWare (See NetWare) numeric datatypes, 8-9 objects, 4,5 open databaseconnectivity (ODBC) CL1 and, 52 transactions, 25 OPEN DATABASE DIRECTORY SCAN,236,
237,238 OPEN DCS DIRECTORY SCAN, 237,238,239 OPEN NODE DIRECTORY SCAN, 237,238 OPENRECOVERY HISTORY FILE SCAN, 335,
336 OPEN TABLESPACE CONTAINER QUERY,290,
291 OPEN TABLESPACE QUERY, 290,291 operating system(OS), 17 operational utilityAPIs, 65 ORDER BY, 46 output, 46
473,474,475 query parallelism,473,475 partitioning, 69,471-504 ADD NODE, 476 coordinator node, 472 CREATE DATABASE AT NODE, 476 DROP DATABASE AT NODE, 476 DROP NODE VERIFY,476 enabling database partitioning, 475-476 GET ROW PARTITIONING INFORMATION, 476 GET ROW PARTITIONING NUMBER, 472 GET TABLE PARTITIONING INFORMATION, 472,476 V 0 parallelism, 473 inter-partition parallelism,
473,474,475 intra-partition parallelism,
473,474,475 map of partitioning, 472 multipartition nodegroups,
472 parallelism, 472-475 partitioned databases,472 query parallelism,473,475 REDISTRIBUTE NODEGROUP, 476 SET RUNTIME DEGREE,
476 single-partition databases,
472 partitioned databases,472
PC integrated exchange format supportedfor import, export, load, 420 performance compatibility of locks, 32,
35-36,36 concurrency and lock size,
32,33-34 conversion deadlocks, 35 conversion of locks, 32,37 deadlocks, 32,34-35,34 escalation of locks, 32,
37-38 locking vs. performance,
3238 phantom reads, 27,28 physical directories, 17,18-l9 pointers, 77,79,188-l89 PRECOMPILE PROGRAM,
69,78,554 precompiling, 49-50,55,
58-59,69,188-l89 PREPARE, 29,510 Presentation Manager, 49 primary and secondarylog files, 39 primary keys, 11 Product operation,4 programming languages,48,
49,66 Projection operation, 4 PRUNE RECOVERY HISTORY FILE, 335,336 qualifiers, 14-15,15 QUERY CLIENT, 135,136 QUERY CLIENT INFORMATION, 136 query parallelism,473,475 QUIESCETABLESPACES FOR TABLE,419,420 read stability,27,28 REBIND, 78 RECONCILE, 336 records, 7,11
Index recovery, 16-17,23,67,4041 autorestart parameters, 330 backuphecovery APIs, 65 commit'operations, 40-41 disaster recovery APIs, 329-414
inconsistent data,problems, 330,331
recovery history files, 333-335,334
redirected restore operations, 332 RESTART DATABASE, 330,336
RESTORE DATABASE, 332,336
roll forward recovery, ROLLFORWARD DATABASE, 333,336 rollback operations, 40-41 SET TABLESPACE CONTAINER, 332,336 recovery history file, 16-17, 69,329,333-335,334
CLOSE RECOVERY HISTORY FILE SCAN, 335,336
GET NEXT RECOVERY FILE HISTORY ENTRY, 335,336
OPEN RECOVERY HISTORY FILE SCAN, 335,336
PRUNE RECOVERY HISTORY FILE, 335,336 sqluhinfo structures,335, 336
UPDATE RECOVERY HISTORY FILE, 335,336 recovery log, 16-17 redirected restore operations, 332
REDISTRIBUTE NODEGROUP, 476 referential constraint,10 REGISTER, 238,239
relational algebra,4 relational databases,3,4 remote server connection M I S , 65 remote units of work (RUOW), 48 REORGANIZE TABLE,290 updating statisticson table, 292
repeatable reads,27 RESET DATABASE CONFIGURATION, 189, 190
RESET DATABASE MANAGER CONFIGURATION, 189, 190
RESET MONITOR, 508,515 resetting configuration values, 188-189 RESTART DATABASE, 330, 336
RESTORE, 69 restore (See recovery) RESTORE DATABASE, 332, 336
result tables, 7 REXX, 49,66 roll back operation, 28 recovery and data and, 4041
transactions, 25 roll forward recovery, 333,336 ROLLBACK, 31,34,38,79 ROLLBACK AN INDOUBT TRANSACTION, 513-514, 513,515
ROLLFORWARD DATABASE, 67,69,333, 336
sections, 13 SELECT, 28,46,57,416,420 Selection operation, 4 serializable transactions, 2627,553
SET ACCOUNTING STRING, 80
SET APPLICATION CONTEXT TYPE,555 SET CLIENT, 135,136 SET CLIENT INFORMATION, 136 SET CONNECTION, 510 SET CONSTRAINTS, 10 SET RUNTIME DEGREE, 476
SET TABLESPACE CONTAINER, 332,336 share (S) lock, 3 1 share with intentexclusive (SIX)locks, 32 shared libraries,APIs, 71 signals, 77, 79, 188-189 simple (unqualified) name, 15 single-partition databases, 472 smallint datatypes, 8 snapshot monitor, 507-508 Software Developers Kit (SDK), 55 Sorts group, Database System Monitor, 506-507 source code files, 58-59,62 SQL, 5,13,48,49-50,61 embedded SQL statements vs. CLI, 52 embedded SQL vs.APIs, 77, 78
SQLCA, 510 static vs. dynamic SQL, 49-50,61
rows, 4,7, 1 1 RUN STATISTICS,291,292 running APIs, 71
SQL AccessGroup (SAG), 51 SQL statements group, Database SystemMonitor,
schema, 14-15,15,57 second-phase errors, 512
SQLCA return codes, 70,81,
506-507
510
j 636
Index
L " "
SQLSTATE codes, 71,81 sqluhinfo structures,335,336 START DATABASE MANAGER, 68,134,136 start-up, 68 state, 17 static vs. dynamic SQL, 49-50,61
STOP DATABASE MANAGER, 68,134,136 stored procedures,55 strings, accounting strings, 77,79-80
structured query language (See SQL) super exclusive (Z) lock, 3 1 support objects, 4 synchronization of databases, 38-39
system catalog, system catalog view, 15-16 system databasedirectory, 18, 19,236 APIs, 236
CATALOG DATABASE, 236,238
CLOSE DATABASE DIRECTORY SCAN,236, 238
GET NEXT DATABASE DIRECTORY ENTRY, 236,238
OPEN DATABASE DIRECTORY SCAN,236, 238
UNCATALOG DATABASE, 236,238
system managed spaces (SMS), 5 system resources,17 table check constraint, 10 table spaces,5-6,7,67,68, 69,290
CLOSE TABLESPACE CONTAINER QUERY, 290,292
CLOSE TABLESPACE QUERY, 290,291 containers in table spaces, 290,291,332,336
database managed spaces (DMS), 5,290,291 FETCH TABLESPACE CONTAINER QUERY, 290,292
FETCH TABLESPACE QUERY, 290,291 management APIs, 65 OPEN TABLESPACE CONTAINER QUERY, 290,291
OPEN TABLESPACE QUERY, 290,291 QUIESCE TABLESPACES FOR TABLE,419,420 recovery history files, 333-335,334
redirected restore operations, 332 restoring, RESTORE DATABASE, 332,336 retrieve information,290 roll forward recovery, ROLLFORWARD DATABASE, 333,336 SET TABLESPACE CONTAINER, 332,336 system managed spaces
(SMS),5,290,291 table space management
APIs, 289-329 TABLESPACE CONTAINER QUERY, 290,291
TABLESPACE QUERY, 290,291
290,292
reorganizing fragmented data in tables, 290,292 result tables,7 rows, 7 RUN STATISTICS, 291, 292
statistics on tables, 291,292 table managementAPIs, 289-329
testing applications,56-57 updating statisticson table, 291
values, 7 views, 12-13,12 Tables group, Database System Monitor, 506-507 TABLESPACE CONTAINER QUERY, 290,291 TABLESPACE QUERY, 290, 291
TCPDP, 68 test data generationfor applications, 57 testing, APIs, 7 1 testing applications,56-57 threaded applications (See contexts and threaded applications) time datatypes, 9 timestamp datatypes, 9 transaction logging, 23, 38-41,48
validate external references, RECONCILE, 336 tables, 5,7-10,
data types, 8-10 fields, 7 indexes, 10-11,11 QUIESCE TABLESPACES FOR TABLE,419,420 records, 7 REORGANIZE TABLE,
15
base tables,7 check constraints, 10 columns, 7
commit operations, 40-41 lengthy transactions,39 Log Manager, 39 managing log file space, 39 overlapping transactions,39 primary and secondary log files, 39
p
1
I 637
Index
L-
" ""
recovery, database recovery, 40-41
rollback operations, 40-41 synchronization of databases, 38-39 Transaction Manager, 509-510
errors, error handling, 512 indoubt transactions,512 transactions, 25 two-phase commit, 509-512, 611
XA-compliant, two-phase commit, 514-515 transactions (See also indoubt transactions), 23,24-25,48, 57-58,69
call level interface (CLI) and, 25 COMMIT and commit operations, 25,28,31,34, 38,40-41,79,505,510
commitment control,25 compatibility of locks, 32, 3536,36
concurrency, 25-29 conversion deadlocks, 35 conversion of locks, 32,37 cursor stability, 27,28 deadlocks, 32,34-35,34 dirty reads,27 distributed unitof work (DUOW), 509 EndTransO, 58 escalation of locks, 32, 37-38
fist-phase errors,511 indoubt transactions(See indoubt transactions) interleaved transactions,25 isolation levels, 25-29 lengthy transactions,39 manually resolving indoubt transactions, 512-514 nonrepeatable reads,27,28 open database connectivity (ODBC) and, 25
overlapping transactions,39 phantom reads, 27,28 read stability,27,28 repeatable reads,27 roll back operations, 25,28 ROLLBACK, 58 second-phase errors,512 serializable transactions, 25-27
synchronization of databases, 38-39 transaction APIs,, 65 transaction logging, 38-41 Transaction Manager, 25, 509-510
two-phase commit with XAcompliant Transaction Manager., 514-515 two-phase commit, 509-512, 611
uncommitted read,27,28 Transactions (Unitsof Work) group, Database System Monitor, 506-507 transition tables, 14 transition variables,14 triggers, 5,13-14,15 action tobe triggered, 14 activation time,13 cascading, 14 event, 13 granularity, 13 set of affected rows, 13 subject table, 13 two-phase commit, 509-512, 611
XA-compliant Transaction Manager, 514-515
UNCATmOG, 236 UNCATALOG DATABASE, 236,237,238
UNCATALOG DCS DATABASE, 237,238 UNCATALOG NODE,237, 238
uncommitted read,27,28
Union operation, 4 unique constraints,10 unique keys, 1 1 unit of work (See transactions) Universal Database(UDB) architecture, 3 UPDATE, 13,31,33,38 update (U)lock, 31 UPDATE DATABASE CONFIGURATION, 189, 190
UPDATE DATl3ASE MANAGER CONFIGURATION, 189, 190
UPDATE RECOVERY HISTORY FILE,335,336 user defined data types (UDT), 5,15 user defined functions (UDF), 5, 15 user interfaces,49 validate external references, RECONCILE, 336 values, 7 varchar datatypes, 9 vargraphic datatypes, 9 variables, transition variables, 14 viewing configuration values, 188-189
views, 5,12-13,12,15 testing applications,56-57 Visual BASIC, 49 volatility of data, 48 volume directories, 17,19, 236-237
APIs, 237 CATALOG, 236 CATALOG DATABASE,237 OPEN DATABASE DIRECTORY SCAN,237 UNCATALOG, 236 UNCATALOG DATABASE, 237
Index
63% wait, lock wait, 29 WAV files, 10 weak exclusive (W) lock, 31 WHERE clause, 33,46 work sheet format supported for import, export, load, 419-420 workstation (node) directories, 18,20,236 M I S , 237 CATALOG NODE, 237,238
CLOSE NODE DIRECTORY SCAN, 237, 238 GET NEXT NODE DIRECTORY SCAN, 237, 238 OPEN NODE DIRECTORY SCAN, 237,238 UNCATALOG NODE, 237, 238
WOpen Call Level Interface (WOpen CLI), 51-52 WOpen, 51-52 XA-compliant Transaction Manager, two-phase commit processing, 514-515
API INDEX ACTIVATE DATABASE ADD NODE ASYNCHRONOUS READ LOG AllACH AlTACH AND CHANGE PASSWORD AllACH TO CONTEXT BACKUP DATABASE BIND CATALOG DATABASE CATALOG DCS DATABASE CATALOG NODE CHANGE DATABASE COMMENT CLOSE DATABASE DIRECTORY SCAN CLOSE DCS DIRECTORY SCAN CLOSE NODE DIRECTORY SCAN CLOSE RECOVERY HISTORY FILE SCAN CLOSE TABLESPACE CONTAINER QUERY CLOSE TABLESPACE QUERY COMMIT AN INDOUBT TRANSACTION COPY MEMORY CREATE AND AllACH TO AN APPLICATION CONTEXT CREATE DATABASE CREATE DATABASE AT NODE DEACTIVATE DATABASE DEREFERENCEADDRESS DEREGISTER DETACH DETACH AND DESTROY APPLICATION CONTEXT DETACH FROM CONTEXT DROP DATABASE DROP DATABASE AT NODE DROP NODE VERIFY ESTIMATE DATABASE SYSTEM MONITOR BUFFER SIZE EXPORT FETCH TABLESPACE CONTAINER QUERY FETCH TABLESPACE QUERY FORCE APPLICATION
160 477 387 165 169 566 342 99 240 270 256 247 255 28 1 269 404 316 300 545 1 I7 559 150 482 163 118 286 173 562 567 159 485 480 524 42 1 314 296 146
FORGET TRANSACTION STATUS FREE MEMORY GET ADDRESS GET AUTHORIZATIONS GET CURRENT CONTEXT GET DATABASE CONFIGURATION GET DATABASE CONFIGURATION DEFAULTS GET DCS DIRECTORY ENTRIES GET DCS DIRECTORY ENTRYFOR DATABASE GET ERROR MESSAGE GET INSTANCE GET NEXf DATABASEDIRECTORY ENTRY GET NEXT NODE DIRECTORY ENTRY GET NEXT RECOVERY HISTORY FILE ENTRY GET ROW PARTITIONING NUMBER GET SNAPSHOT GET SQLSTATE MESSAGE GET TABLE PARTITIONING INFORMATION GET TABLESPACE STATISTICS GETNPDATE MONITOR SWITCHES IMPORT INSTALL SIGNAL HANDLER INTERRUPT INTERRUPT CONTEXT LIST DRDA INDOUBT TRANSACTIONS LIST INDOUBT TRANSACTIONS LOAD LOAD QUERY MIGRATE DATABASE OPEN DATABASE DIRECTORY SCAN OPEN DCS DIRECTORY SCAN OPEN NODE DIRECTORY SCAN OPEN RECOVERY HISTORY FILE SCAN OPEN TABLESPACE CONTAINER QUERY OPEN TABLESPACE QUERY PRECOMPILE PROGRAM PRUNE RECOVERY HISTORY FILE QUERY CLIENT QUERY CLIENT INFORMATION
552 320 116 128 568 213 225 278 280 122 107 253 267 399 494 527 125 490 307 516 430 109 112 572 536 540 446 464 337 250 276 264 394 310 293 82 409 174 180
API Index QUIESCE TABLESPACES FOR TABLE REBIND RECONCILE REDISTRIBUTE NODEGROUP REGISTER REORGANIZE TABLE RESET DATABASE CONFIGURATION RESET DATABASE MANAGER CONFIGURATION RESET MONITOR RESTART DATABAE RESTORE DATABASE ROUBACK AN INDOUBT TRANSACTION ROLLFORWARD DATABASE RUN STATISTICS SET ACCOUNTING STRING SET APPLICATION CONTEXT TYPE SET CLIENT
466 103 36 1 500 28 1 320 233 212 52 l 339 35 1 548 372 324
1 l9 555 179
SET CLIENT INFORMATION SET RUNTIME DEGREE SET TABLESPACE CONTAINERS SINGLE TABLESPACE QUERY START DATABASE MANAGER START DATABASE MANAGER STOP DATABAE MANAGER TABLESPACE CONTAINER QUERY TABLESPACE QUERY UNCATALOG DATABASE UNCATNOG DCS DATABASE UNCATALOG NODE UPDATE DATABASE CONFIGURATION UPDATE DATABASE MANAGER CONFIGURATION UPDATE RECOVERY HISTORY FILE
185 487 365 304 136 137 142 316 300 244 273 262 228 207 405
F M Pmna ABOUTTHE AUTHOR Roger Sanders is an Educational’Multimedia Assets Specialist with SAS inSchooP, a division of SAS Institute, Inc. focusingon school technologies. He has been ,designing and programming sofhvare applications for the IBM Personal Computer for more than 15 years and specializes in system programmingin C, C++, and 80 X 86 Assembly Language. Hehas written several computer magazinearticles, and he is the author of The Developer’s Handbook to DB2 for Common Servers, ODBC 3.5Developer’s Guide, and DB2 Universal Database Application Programming Interface Developer’s Guide. His background in database application design and development is extensive. It includes experience with DB2 Universal Database, DB2 for Common Servers, DB2 for MVS, INGRES,dBASE, and Microsoft ACCESS.