1.1 The Power of Built−in Packages 1.3 Using Built−in Packages[Appendix A] What's on the Companion Disk?... Here is aportion of the specification of that package: CREATE OR REPLACE PACKA
Trang 1[Appendix A] What's on the Companion Disk?
Trang 2Table of Contents
A What's on the Companion Disk? 2
A.1 Installing the Guide 2
3
A.2 Using the Guide 3
4
1 Introduction 5
1.1 The Power of Built−in Packages 5
1.1.1 A Kinder , More Sharing Oracle 6
7
1.2 Built−in Packages Covered in This Book 7
1.2.1 Application Development Packages 10
1.2.2 Server Management Packages 11
1.2.3 Distributed Database Packages 12
14
1.3 Using Built−in Packages 14
1.3.1 What Is a Package? 14
1.3.2 Controlling Access with Packages 15
1.3.3 Referencing Built−in Package Elements 17
1.3.4 Exception Handling and Built−in Packages 18
1.3.5 Encapsulating Access to the Built−in Packages 24
1.3.6 Calling Built−in Packaged Code from Oracle Developer/2000 Release 1 27
1.3.7 Accessing Built−in Packaged Technology from Within SQL 30
38
1.4 Examining Built−in Package Source Code 38
1.4.1 The STANDARD Package 39
1.4.2 The DBMS_STANDARD Package 40
42
2 Executing Dynamic SQL and PL/SQL 43
2.1 Examples of Dynamic SQL 43
46
2.2 Getting Started with DBMS_SQL 46
2.2.1 Creating the DBMS_SQL Package 46
2.2.2 Security and Privilege Issues 46
2.2.3 DBMS_SQL Programs 46
2.2.4 Types of Dynamic SQL 47
2.2.5 DBMS_SQL Exceptions 49
2.2.6 DBMS_SQL Nonprogram Elements 49
52
2.3 The DBMS_SQL Interface 52
2.3.1 Processing Flow of Dynamic SQL 52
2.3.2 Opening the Cursor 54
2.3.3 Parsing the SQL Statement 55
2.3.4 Binding Values into Dynamic SQL 58
2.3.5 Defining Cursor Columns 63
2.3.6 Executing the Cursor 66
2.3.7 Fetching Rows 66
2.3.8 Retrieving Values 69
2.3.9 Closing the Cursor 76
2.3.10 Checking Cursor Status 77
2.3.11 Describing Cursor Columns 80
85
[Appendix A] What's on the Companion Disk?
i
Trang 3Table of Contents
2.4 Tips on Using Dynamic SQL 85
2.4.1 Some Restrictions 85
2.4.2 Privileges and Execution Authority with DBMS_SQL 85
2.4.3 Combining Operations 87
2.4.4 Minimizing Memory for Cursors 88
2.4.5 Improving the Performance of Dynamic SQL 89
2.4.6 Problem−Solving Dynamic SQL Errors 91
2.4.7 Executing DDL in PL/SQL 94
2.4.8 Executing Dynamic PL/SQL 94
97
2.5 DBMS_SQL Examples 97
2.5.1 A Generic Drop_Object Procedure 97
2.5.2 A Generic Foreign Key Lookup Function 98
2.5.3 A Wrapper for DBMS_SQL DESCRIBE_COLUMNS 104
2.5.4 Displaying Table Contents with Method 4 Dynamic SQL 107
2.5.5 Indirect Referencing in PL/SQL 116
2.5.6 Array Processing with DBMS_SQL 121
2.5.7 Using the RETURNING Clause in Dynamic SQL 134
138
3 Intersession Communication 139
3.1 DBMS_PIPE: Communicating Between Sessions 139
3.1.1 Getting Started with DBMS_PIPE 140
3.1.2 How Database Pipes Work 141
3.1.3 Managing Pipes and the Message Buffer 143
3.1.4 Packing and Unpacking Messages 149
3.1.5 Sending and Receiving Messages 158
3.1.6 Tips on Using DBMS_PIPE 161
3.1.7 DBMS_PIPE Examples 164
184
3.2 DBMS_ALERT: Broadcasting Alerts to Users 184
3.2.1 Getting Started with DBMS_ALERT 184
3.2.2 The DBMS_ALERT Interface 185
3.2.3 DBMS_ALERT Examples 191
202
4 User Lock and Transaction Management 203
4.1 DBMS_LOCK: Creating and Managing Resource Locks 203
4.1.1 Getting Started with DBMS_LOCK 203
4.1.2 The DBMS_LOCK Interface 205
4.1.3 Tips on Using DBMS_LOCK 211
4.1.4 DBMS_LOCK Examples 213
221
4.2 DBMS_TRANSACTION: Interfacing to SQL Transaction Statements 221
4.2.1 Getting Started with DBMS_TRANSACTION 221
4.2.2 Advising Oracle About In−Doubt Transactions 223
4.2.3 Committing Data 224
4.2.4 Rolling Back Changes 225
4.2.5 Setting Transaction Characteristics 227
4.2.6 Cleaning Up Transaction Details 229
4.2.7 Returning Transaction Identifiers 231
234
[Appendix A] What's on the Companion Disk?
ii
Trang 4Table of Contents
5 Oracle Advanced Queuing 235
5.1 Oracle AQ Concepts 236
5.1.1 General Features 236
5.1.2 Enqueue Features 237
5.1.3 Dequeue Features 238
5.1.4 Propagation Features 238
5.1.5 A Glossary of Terms 240
5.1.6 Components of Oracle AQ 243
5.1.7 Queue Monitor 244
5.1.8 Data Dictionary Views 244
245
5.2 Getting Started with Oracle AQ 245
5.2.1 Installing the Oracle AQ Facility 245
5.2.2 Database Initialization 246
5.2.3 Authorizing Accounts to Use Oracle AQ 247
249
5.3 Oracle AQ Nonprogram Elements 249
5.3.1 Constants 249
5.3.2 Object Names 250
5.3.3 Queue Type Names 251
5.3.4 Agents Object Type 251
5.3.5 Recipient and Subscriber List Table Types 252
5.3.6 Message Properties Record Type 252
5.3.7 Enqueue Options Record Type 254
5.3.8 Dequeue Options Record Type 255
5.3.9 Oracle AQ Exceptions 257
259
5.4 DBMS_AQ: Interfacing to Oracle AQ (Oracle8 only) 259
5.4.1 Enqueuing Messages 259
5.4.2 Dequeuing Messages 262
268
5.5 DBMS_AQADM: Performing AQ Administrative Tasks (Oracle8 only) 268
5.5.1 Creating Queue Tables 269
5.5.2 Creating and Starting Queues 272
5.5.3 Managing Queue Subscribers 276
5.5.4 Stopping and Dropping Queues 278
5.5.5 Managing Propagation of Messages 280
5.5.6 Verifying Queue Types 282
5.5.7 Starting and Stopping the Queue Monitor 283
284
5.6 Oracle AQ Database Objects 284
5.6.1 Objects Per Queue Table 284
5.6.2 Data Dictionary Objects 287
290
5.7 Oracle AQ Examples 290
5.7.1 Improving AQ Ease of Use 291
5.7.2 Working with Prioritized Queues 293
5.7.3 Building a Stack with AQ Using Sequence Deviation 297
5.7.4 Browsing a Queue's Contents 299
5.7.5 Searching by Correlation Identifier 303
5.7.6 Using Time Delay and Expiration 307
5.7.7 Working with Message Groups 313
[Appendix A] What's on the Companion Disk?
iii
Trang 5Table of Contents
5.7.8 Working with Multiple Consumers 316
322
6 Generating Output from PL/SQL Programs 323
6.1 DBMS_OUTPUT: Displaying Output 323
6.1.1 Getting Started with DBMS_OUTPUT 323
6.1.2 Enabling and Disabling Output 326
6.1.3 Writing to the DBMS_OUTPUT Buffer 328
6.1.4 Retrieving Data from the DBMS_OUTPUT Buffer 329
6.1.5 Tips on Using DBMS_OUTPUT 332
6.1.6 DBMS_OUTPUT Examples 333
337
6.2 UTL_FILE: Reading and Writing Server−side Files 337
6.2.1 Getting Started with UTL_FILE 337
6.2.2 Opening Files 343
6.2.3 Reading from Files 345
6.2.4 Writing to Files 346
6.2.5 Closing Files 350
6.2.6 Tips on Using UTL_FILE 351
6.2.7 UTL_FILE Examples 358
365
7 Defining an Application Profile 366
7.1 Getting Started with DBMS_APPLICATION_INFO 366
7.1.1 DBMS_APPLICATION_INFO Programs 366
7.1.2 The V$ Virtual Tables 367
7.1.3 DBMS_APPLICATION_INFO Nonprogram Elements 367
369
7.2 DBMS_APPLICATION_INFO Interface 369
7.2.1 The DBMS_APPLICATION_INFO.READ_CLIENT_INFO procedure 369
7.2.2 The DBMS_APPLICATION_INFO.READ_MODULE procedure 369
7.2.3 The DBMS_APPLICATION_INFO.SET_ACTION procedure 370
7.2.4 The DBMS_APPLICATION_INFO.SET_CLIENT_INFO procedure 372
7.2.5 The DBMS_APPLICATION_INFO.SET_MODULE procedure 373
7.2.6 The DBMS_APPLICATION_INFO.SET_SESSION_LONGOPS procedure 374
377
7.3 DBMS_APPLICATION_INFO Examples 377
7.3.1 About the register_app Package 377
7.3.2 The action Procedure 378
7.3.3 The set_stats Procedure 378
7.3.4 The Information Procedures 380
7.3.5 Using the register_app Package 381
7.3.6 Covering DBMS_APPLICATION_INFO 382
7.3.7 Monitoring Application SQL Resource Consumption 384
7.3.8 Session Monitoring and Three−Tier Architectures 384
7.3.9 Tracking Long−Running Processes 385
389
8 Managing Large Objects 390
8.1 Getting Started with DBMS_LOB 390
8.1.1 DBMS_LOB Programs 390
8.1.2 DBMS_LOB Exceptions 392
[Appendix A] What's on the Companion Disk?
iv
Trang 6Table of Contents
8 Managing Large Objects
8.1.3 DBMS_LOB Nonprogram Elements 392
8.1.4 About the Examples 392
395
8.2 LOB Concepts 395
8.2.1 LOB Datatypes 395
8.2.2 BFILE Considerations 398
8.2.3 Internal LOB Considerations 399
402
8.3 DBMS_LOB Interface 402
8.3.1 Working with BFILEs 402
8.3.2 Reading and Examining LOBs 415
8.3.3 Updating BLOBs, CLOBs, and NCLOBs 424
433
9 Datatype Packages 434
9.1 DBMS_ROWID: Working with the ROWID Pseudo−Column (Oracle8 only) 434
9.1.1 Getting Started with DBMS_ROWID 434
9.1.2 ROWID Concepts 436
9.1.3 The DBMS_ROWID Interface 437
444
9.2 UTL_RAW: Manipulating Raw Data 444
9.2.1 Getting Started with UTL_RAW 444
9.2.2 Raw Data Manipulation Concepts 446
9.2.3 The UTL_RAW Interface 447
9.2.4 UTL_REF: Referencing Objects (Oracle8.0.4) 463
9.2.5 UTL_REF Interface 465
9.2.6 UTL_REF Example 468
471
10 Miscellaneous Packages 472
10.1 DBMS_UTILITY: Performing Miscellaneous Operations 472
10.1.1 Getting Started with DBMS_UTILITY 472
10.1.2 The DBMS_UTILITY Interface 475
493
10.2 DBMS_DESCRIBE: Describing PL/SQL Program Headers 493
10.2.1 Getting Started with DBMS_DESCRIBE 493
10.2.2 Explaining DBMS_DESCRIBE Results 496
10.2.3 DBMS_DESCRIBE Example 499
504
10.3 DBMS_DDL: Compiling and Analyzing Objects 504
10.3.1 Getting Started with DBMS_DDL 504
10.3.2 Compiling PL/SQL Objects 505
10.3.3 Computing Statistics for an Object 508
10.3.4 Setting Referenceability of Tables 510
514
10.4 DBMS_RANDOM: Generating Random Numbers (Oracle8 Only) 514
10.4.1 Getting Started with DBMS_RANDOM 514
10.4.2 DBMS_RANDOM Interface 515
517
[Appendix A] What's on the Companion Disk?
v
Trang 7Table of Contents
11 Managing Session Information 518
11.1 DBMS_SESSION: Managing Session Information 518
11.1.1 Getting Started with DBMS_SESSION 518
11.1.2 Modifying Session Settings 519
11.1.3 Obtaining Session Information 523
11.1.4 Managing Session Resources 525
11.1.5 DBMS_SESSION Examples 530
540
11.2 DBMS_System: Setting Events for Debugging 540
11.2.1 Getting Started with DBMS_SYSTEM 540
11.2.2 DBMS_SYSTEM Interface 541
11.2.3 DBMS_SYSTEM Examples 543
547
12 Managing Server Resources 548
12.1 DBMS_SPACE: Obtaining Space Information 548
12.1.1 Getting Started with DBMS_SPACE 548
12.1.2 The DBMS_SPACE Interface 549
12.1.3 DBMS_SPACE Examples 553
563
12.2 DBMS_SHARED_POOL: Pinning Objects 563
12.2.1 Getting Started with DBMS_SHARED_POOL 563
12.2.2 Pinning and Unpinning Objects 564
12.2.3 Monitoring and Modifying Shared Pool Behavior 566
12.2.4 DBMS_SHARED_POOL Examples 568
573
13 Job Scheduling in the Database 574
13.1 Getting Started with DBMS_ JOB 574
13.1.1 DBMS_JOB Programs 574
13.1.2 Job Definition Parameters 575
13.2.1 INIT.ORA Parameters and Background Processes 578
13.2.2 Job Execution and the Job Execution Environment 578
13.2.3 Miscellaneous Notes 578
13.2.4 DBMS_JOB Interface 579
13.2.5 Submitting Jobs to the Job Queue 580
13.2.6 Modifying Job Characteristics 580
13.2.7 Removing Jobs and Changing Job Execution Status 581
13.2.8 Transferring Jobs 583
586
13.2 Job Queue Architecture 588
591
13.3 Tips on Using DBMS_JOB 591
13.3.1 Job Intervals and Date Arithmetic 591
13.3.2 Viewing Job Information in the Data Dictionary 592
13.3.3 DBMS_IJOB: Managing Other Users' Jobs 595
597
13.4 DBMS_JOB Examples 597
13.4.1 Tracking Space in Tablespaces 597
13.4.2 Fixing Broken Jobs Automatically 598
13.4.3 Self−Modifying and Self−Aware Jobs 599
602
[Appendix A] What's on the Companion Disk?
vi
Trang 8Table of Contents
14 Snapshots 603
14.1 DBMS_SNAPSHOT: Managing Snapshots 603
14.1.1 Getting Started with DBMS_SNAPSHOT 603
14.1.2 Using the I_AM_A_REFRESH Package State Variable 604
14.1.3 Refreshing Snapshots 606
14.1.4 Purging the Snapshot Log 610
14.1.5 Reorganizing Tables 611
14.1.6 Registering Snapshots 613
14.2.1 Getting Started with DBMS_REFRESH 617
14.2.2 Creating and Destroying Snapshot Groups 617
14.2.3 Adding and Subtracting Snapshots from Snapshot Groups 618
14.2.4 Altering Properties of a Snapshot Group 619
14.2.5 Manually Refreshing Snapshot Groups 623
624
14.2 DBMS_REFRESH: Managing Snapshot Groups 624
626
14.3 DBMS_OFFLINE_SNAPSHOT: Performing Offline Snapshot Instantiation 626
14.3.1 Getting Started with DBMS_OFFLINE_SNAPSHOT 626
14.3.2 DBMS_OFFLINE_SNAPSHOT Interface 627
629
14.4 DBMS_REPCAT: Managing Snapshot Replication Groups 629
14.4.1 Getting Started with DBMS_REPCAT 629
14.4.2 Creating and Dropping Snapshot Replication Groups 630
14.4.3 Adding and Removing Snapshot Replication Group Objects 633
14.4.4 Altering a Snapshot Replication Group's Propagation Mode 635
14.4.5 Manually Refreshing a Snapshot Replication Group 637
14.4.6 Switching the Master of a Snapshot Replication Group 638
641
15 Advanced Replication 642
15.1 DBMS_REPCAT_AUTH: Setting Up Administrative Accounts 642
15.1.1 Getting Started with DBMS_REPCAT_AUTH 642
15.1.2 Granting and Revoking Surrogate SYS Accounts 643
15.1.3 Granting and Revoking Propagator Accounts (Oracle8) 644
645
15.2 DBMS_REPCAT_ADMIN: Setting Up More Administrator Accounts 645
15.2.1 Getting Started with DBMS_REPCAT_ADMIN 645
15.2.2 Creating and Dropping Replication Administrator Accounts 646
649
15.3 DBMS_REPCAT: Replication Environment Administration 649
15.3.1 Getting Started with DBMS_REPCAT 649
15.3.2 Replication Groups with DBMS_REPCAT 651
15.3.3 Replicated Objects with DBMS_REPCAT 656
15.3.4 Replication Support with DBMS_REPCAT 665
15.3.5 Adding and Removing Master Sites with DBMS_REPCAT 676
15.3.6 Maintaining the Repcatlog Queue with DBMS_REPCAT 682
15.3.7 Quiescence with DBMS_REPCAT 686
15.3.8 Miscellaneous DBMS_REPCAT Procedures 688
693
15.4 DBMS_OFFLINE_OG: Performing Site Instantiation 693
15.4.1 Getting Started with DBMS_OFFLINE_OG 693
15.4.2 DBMS_OFFLINE_OG Interface 694
699
[Appendix A] What's on the Companion Disk?
vii
Trang 9Table of Contents
15.5 DBMS_RECTIFIER_DIFF: Comparing Replicated Tables 699
15.5.1 Getting Started with DBMS_RECTIFIER_DIFF 699
15.5.2 DBMS_RECTIFIER_DIFF Interface 699
705
15.6 DBMS_REPUTIL: Enabling and Disabling Replication 705
15.6.1 Getting Started with DBMS_REPUTIL 705
15.6.2 DBMS_REPUTIL Interface 705
707
16 Conflict Resolution 708
16.1 Getting Started with DBMS_REPCAT 708
16.1.1 DBMS_REPCAT Programs 708
16.1.2 DBMS−REPCAT Exceptions 710
16.1.3 DBMS−REPCAT Nonprogram Elements 711
16.1.4 Data Dictionary Views 711
716
16.2 Column Groups with DBMS_REPCAT 716
16.2.1 About Column Groups 716
16.2.2 Creating and Dropping Column Groups 717
16.2.3 Modifying Existing Column Groups 720
724
16.3 Priority Groups with DBMS_REPCAT 724
16.3.1 About Priority Groups 724
16.3.2 Creating, Maintaining, and Dropping Priority Groups 725
16.3.3 Creating and Maintaining Priorities Within a Priority Group 729
16.3.4 Dropping Priorities from a Priority Group 734
738
16.4 Site Priority Groups with DBMS_REPCAT 738
16.4.1 About Site Priority Groups 738
16.4.2 Creating, Maintaining, and Dropping Site Priorities 738
16.4.3 Maintaining Site Priorities 741
749
16.5 Assigning Resolution Methods with DBMS_REPCAT 749
16.5.1 About Resolution Methods 749
759
16.6 Monitoring Conflict Resolution with DBMS_REPCAT 759
16.6.1 About Monitoring 759
762
17 Deferred Transactions and Remote Procedure Calls 763
17.1 About Deferred Transactions and RPCs 763
17.1.1 About Remote Destinations 763
17.1.2 Data Dictionary Views 764
767
17.2 DBMS_DEFER_SYS: Managing Deferred Transactions 767
17.2.1 Getting Started with DBMS_DEFER_SYS 767
17.2.2 Adding and Deleting Default Destinations 769
17.2.3 Copying Deferred Transactions to New Destinations 770
17.2.4 Maintenance Procedures 771
17.2.5 Propagating Deferred RPCs 775
17.2.6 Scheduling Propagation (Oracle8 only) 779
786
[Appendix A] What's on the Companion Disk?
viii
Trang 10Table of Contents
17.3 DBMS_DEFER: Building Deferred Calls 786
17.3.1 Getting Started with DBMS_DEFER 786
17.3.2 Basic RPCs 788
17.3.3 Parameterized RPCs 793
798
17.4 DBMS_DEFER_QUERY: Performing Diagnostics and Maintenance 798
17.4.1 Getting Started with DBMS_DEFER_QUERY 798
Index 805
Table of Contents 805
Part I: Overview 805
Part II: Application Development Packages 805
Part III: Server Management Packages 805
Part IV: Distributed Database Packages 805
805
807
Part I: Overview 808
809
Part II: Application Development Packages 810
812
Part III: Server Management Packages 813
814
Part IV: Distributed Database Packages 815
816
Dedication 817
818
Preface 819
Structure of This Book 820
822
Conventions Used in This Book 822
824
Versions of Oracle 824
825
About the Disk 825
826
About PL/Vision 826
827
About Q 827
828
How to Contact Us 828
829
Acknowledgments 829
Steven 829
From Charles 830
From John 831
[Appendix A] What's on the Companion Disk?
ix
Trang 11Appendix A
1
Trang 12A What's on the Companion Disk?
Contents:
Installing the Guide
Using the Guide
The content of the companion Windows disk that accompanies this book has been included on this CD, in the
/bipack/disk/ directory It contains the Oracle Built−in Packages Companion Guide, an online tool designed
by RevealnNet, Inc., to help you find additional resources The guide offers point−and−click access to
approximately 175 files of source code and documentation prepared by the authors The goal of providing thismaterial in electronic form is to give you a leg up on the development of your own PL/SQL programs
Providing material on disk also helps us keep the size of this book under (some) control
A.1 Installing the Guide
In a Microsoft Windows environment, you begin installation by double−clicking on the setup.exe file to run
the installation program If you are working in a non−Windows environment, please visit the RevealNetPL/SQL Pipeline Archives (http://www.revealnet.com/plsql−pipeline) to obtain a compressed file containingthe examples on this disk
The installation script will lead you through the necessary steps The first screen you will see is the installscreen shown in Figure A−1
Figure A.1: Installing the Companion Guide
You can change the default directory in which the files will be placed Once this step is complete and thesoftware has been copied to your drive, an icon will appear in the folder you specified Double−click on theicon to start using the Companion Guide You will then see the main menu shown in Figure A−2
Figure A.2: The main menu
IV Distributed Database
Packages
A.2 Using the Guide
Copyright (c) 2000 O'Reilly & Associates All rights reserved.
Trang 13Appendix AWhat's on the Companion
Disk?
A.2 Using the Guide
The four buttons on the main menu take you to the companion information for this book
About the Companion Guide
A brief description of the contents of this disk
About the Indexes
An explanation of the information provided for each file: name, chapter reference, and description.Filenames highlighted in blue indicate that the files are encapsulations of underlying packages orprograms (Chapter 1, Introduction explains encapsulation.) The displayed information also explains
the meaning of the various file extensions (e.g., spp, sp, sql).
Source Code Index by Filename
The guide fives you point−and−click access to each of the files on the companion disk Here the filesare listed alphabetically Source code listings in the book begin with comment lines keyed to thesefilenames on the disk Figure A.3 shows a portion of the Source Code Index by Filename
Figure A.3: The Source Code Index by Filename
Source Code Index by Chapter
Here the files are listed in chapter order to make it easy for you to move between the book and theguide Figure A−4 shows a portion of the Source Code Index by Chapter
Figure A.4: The Source Code Index by Chapter
A.1 Installing the Guide
Copyright (c) 2000 O'Reilly & Associates All rights reserved.
3
Trang 14Chapter 1
4
Trang 151 Introduction
Contents:
The Power of Built−in Packages
Built−in Packages Covered in This Book
Using Built−in Packages
Examining Built−in Package Source Code
Ah, for the good old days of Version 1.0 of PL /SQL! Life was so simple then No stored procedures orfunctions −− and certainly no packages You had your set of built−in functions, like SUBSTR and
TO_DATE You had the IF statement and various kinds of loops With these tools at hand, you built yourbatch−processing scripts for execution in SQL*Plus, and you coded your triggers in SQL*Forms 3.0, and youwent home at night content with a good day's work done
Of course, there was an awful lot you couldn't do with PL /SQL 1.0 −− such as build complex, robust,
large−scale applications, or read and write operating system files, or manipulate data in array structures, ordebug your code effectively, or store your business formulas in reusable program units
Sure, life was simpler back when you were stuck with PL /SQL 1.0 You just too frequently told your
manager or your users that what they wanted done was, well, impossible Fortunately, Oracle recognized that
it would be so much nicer for both its users and its bottom line if its bedrock technology (most importantly,the Oracle RDBMS and PL /SQL) could actually meet user needs So it came out with PL /SQL Version 2(which works with Version 7 of the Oracle Server) and then, most recently, PL /SQL Version 8.0 (to
accompany Oracle8) In each major version and its sub−releases (2.1, 2.2, 2.3, and, sometime in 1998, 8.1),Oracle has added major new functionality As a result, hundreds of thousands of software programmers nowuse PL /SQL to implement sophisticated applications
Easily the most important new feature of PL /SQL2 was the introduction of packages Packages (explored inmore detail in the next section) allow you to collect together related program elements and control access tothose elements Anyone who develops PL /SQL applications should employ packages at the very core of theirlayers of reusable code −− and Oracle Corporation itself is no exception Starting with PL /SQL 2.0 andcontinuing through every subsequent release, Oracle has made available to PL /SQL developers a series of
built−in packages, which extend the functionality of PL /SQL in many fascinating and important directions.
It is no longer sufficient to be aware of and expert in only the core elements of PL /SQL Getting a handle on
IF statements, loops, and the built−in functions like INSTR and TO_CHAR is now only the first phase in yourjourney towards PL /SQL expertise To take full advantage of the PL /SQL language, developers must nowalso learn how to use the programs contained in the built−in packages And, believe me, once you make a fewdiscoveries in these built−in packages, you will be amazed −− and you will be addicted You will eagerlytroll this book for features you can apply in new and creative ways to solve your problems
This first chapter introduces you to basic concepts of package usage in PL /SQL, shows you how to usebuilt−in packaged functionality in your programs, and explains how to find and learn from the source code forthese packages
1.1 The Power of Built−in Packages
Most of the built−in packages extend the PL /SQL language to support features that would otherwise beunavailable to you This is possible because when Oracle Corporation builds a package, they have the luxury
of writing elements of the package in C, giving them full access to the underlying operating system and otherareas of technology that are off−limits to the rest of us poor PL /SQL programmers The result is that Oracle ismaking something available to us which we could not get ourselves, no matter how proficient a PL /SQLprogrammer we become.[1]
Trang 16[1] With Oracle8 and its support for external programs in PL /SQL, this is no longer quite
true With PL /SQL8, you will be able to build your own packages that, in turn, call C
programs See Chapter 21 of Oracle PL /SQL Programming, Second Edition, for more
information about this feature
However, I don't want to sound as if I'm complaining I'm very glad Oracle took advantage of packages and Cand whatever else they could (and not just because it gave me the excuse to write another book!) The result is
a much more powerful and useful PL /SQL Let's look at an example to give you a feeling for the way Oracleused the package structure to revolutionize the code you write
Consider Oracle7 Server Version 7.1: the "Parallel Everything" database, as Oracle Corporation called it in itsmarketing materials Oracle 7.1 offered parallel query, parallel index update, and many other features that takeadvantage of the symmetric multiprocessors widely available today This parallelization of the RDBMSoffered significant improvements in database performance, and we should all be glad for that But there is,fortunately, so much more for which to be thankful
1.1.1 A Kinder , More Sharing Oracle
Oracle Corporation didn't simply utilize this parallelization technology inside its own code It also made thissame technology available to us in a "safe" way: through the specification of the DBMS_PIPE package WhileDBMS_PIPE is probably not used by the Oracle Server itself, that built−in package certainly accesses thesame parallelization technology used by the RDBMS The advantages for a PL /SQL developer are
far−reaching
Even if DBMS_PIPE originally grew out of a need by Oracle Corporation to enhance its own performance,the advantages of DBMS_PIPE are not confined to the Oracle RDBMS Any developer can use DBMS_PIPE
in all sorts of new and creative ways You can parallelize your own programs You can communicate between
a client program in Oracle Forms and a server−based process, without having to commit any data You canbuild a debugger for your server−side PL /SQL programs
And, given the fact that the technology accessed by DBMS_PIPE is also used by the Oracle Server, you areall but guaranteed that DBMS_PIPE will be very efficient and (relatively) bug−free
The DBMS_PIPE package is just one of many such mind− and functionality−expanding new resources madeavailable through the built−in packages Do you need to issue your own locks? Do you need to detect whetheranother process in your current session has committed data? Use the DBMS_LOCK package Do you want toissue messages from within your PL /SQL programs to help trace and debug your program? Check out theDBMS_OUTPUT package Would you like to schedule jobs within the RDBMS itself? Explore the DBMS_JOB package The list goes on and on, and is constantly growing With the Oracle−supplied packages, youhave at your disposal many of the same tools available to the internal Oracle product developers With thesetools, you can do things never before possible!
Covered in This Book
Copyright (c) 2000 O'Reilly & Associates All rights reserved.
[Appendix A] What's on the Companion Disk?
Trang 17Chapter 1Introduction
1.2 Built−in Packages Covered in This Book
Oracle Corporation provides many built−in packages, in a variety of its products You may find it hard to
believe, but even this large book cannot document all of those packages Oracle Developer/2000 contains a set
of built−in packages, including DDE and TEXT_IO Oracle WebServer offers its own built−in packages, from
HTP to OWA_UTIL, for use in web−based development This book does not discuss those packages Instead,
its focus is on the core database built−in packages, generally those with a DBMS_ or UTL_ prefix
Within that context, this book discusses all of the built−in packages that you are likely to use Although (asnoted above) it does not offer descriptions for every single package ever created by Oracle Corporation andstored in the database, I would be very surprised if you ever needed to use one of the few packages not found
in these pages The rest of this section introduces you to the packages covered in this book; I have organizedthese packages into three general areas:
Application development packages
Used primarily by developers as they build applications
Server management packages
Used mostly by database administrators to manage their database servers
Distributed database packages
Used by database administrators and developers to manage data across a distributed enterprise
It is, of course, quite possible and not uncommon for a DBA to use a package we have designated in this book
as an "application developer package." In addition, a single package may contain both administrative anddevelopment programs These categories are not meant to restrict your use of the built−in packages; instead,
we hope to give some structure to a long, complex list of functional areas so that you will be able to access thetechnology with more ease and minimal confusion
The following sections briefly describe each of the packages found in the chapters of this book Table 1.1provides a quick summary Some of these packages, or the programs within them, are available only undercertain Oracle versions, as explained in the following chapters
Table 1.1: Oracle Built−in Packages
DBMS_AQ Creates messages in, and consumes
messages from, specific queuesprovided by the Oracle AdvancedQueuing facility
5
DBMS_AQADM Performs Oracle Advanced Queueing
administrative tasks such as creatingand dropping queue tables and
5
7
Trang 18altering queues.
DBMS_APPLICATION_INFO Monitors the execution of an
application
7
DBMS_ALERT Broadcasts notification to multiple
users that specific database eventshave occurred
3
DBMS_DDL Recompiles stored code, analyzes
objects in a schema, and modifiesreferenceability of object identifiers inOracle8
10
DBMS_DEFER Queues deferred remote procedure
calls (RPCs)
17
DBMS_DEFER_QUERY Provides access to parameters passed
to deferred calls, primarily fordiagnostic purposes
17
DBMS_DEFER_SYS Performs administrative tasks such as
scheduling, executing, and deletingqueued
DBMS_JOB Provides an interface to Oracle's job
scheduler (for noninteractiveexecution of PL/SQL programs)
13
DBMS_LOB Acesses and manipulates large objects
(LOBs) from within PL/SQLprograms
8
DBMS_LOCK Helps you manage contention for
resources used by complex multiuserapplications
4
DBMS_OFFLINE_OG Instantiates sites (i.e., exports data
from an existing master site andimports it into the new master site)
15
SNAPSHOT Instantiates a new snapshot using an
export of a master table
14DBMS_OUTPUT Displays information to your screen 6
DBMS_PIPE Lets applications communicate with
routines external to the database
3
DBMS_RANDOM Provides a random number generator 10
DBMS_RECTIFIER_DIFF Compares replicated tables at two
master sites and synchronizes them ifnecessary
15
DBMS_REFRESH Administers snapshot groups at a
snapshot site
14DBMS_REPCAT Performs many advanced replication 14 15 16
[Appendix A] What's on the Companion Disk?
8
Trang 19operations, including maintenance,snapshots, and conflict resolution.
DBMS_REPCAT_ADMIN Creates administrator accounts for
replication
15
DBMS_REPCAT_AUTH Grants and revokes "surrogate SYS"
privileges for administrator accounts,and grants and revokes propagatoraccounts for Oracle8
15
DBMS_REPUTIL Enables and disables replication at the
session level
15
DBMS_ROWID Works with ROWID formats, both
extended (Oracle8 only) and restricted(traditional Oracle7)
9
DBMS_SESSION Modifies and inspects session roles
and settings, and manipulates sessionmemory and package states
11
DBMS_SHARED_POOL Allows PL/SQL objects and SQL
cursors to be pinned (kept) in theOracle shared pool; used mainly formemory management
12
DBMS_SNAPSHOT Maintains snapshots and snapshot
logs
14
DBMS_SPACE Analyzes space in tables, indexes, and
clusters, and provides informationabout segment free list sizes
12
DBMS_SQL Executes dynamically constructed
SQL statements and PL/SQL blocks
of code
2
DBMS_SYSTEM Lets administrators set trace events in
other users' sessions (for debugging)
11
DBMS_TRANSACTION Provides a programmatic interface to
a number of transaction−oriented SQLstatements
4
DBMS_UTILITY Performs miscellaneous operations
such as freeing unused memory,calculating elapsed program time, etc
10
UTL_FILE Reads and writes information in
server−side files
6
UTL_RAW Works with raw data, performing such
operations as concatenation, bytetranslation, etc
9
UTL_REF Provides a PL/SQL interface to select
and modify objects in an object table(Oracle8 only)
9[Appendix A] What's on the Companion Disk?
9
Trang 201.2.1 Application Development Packages
This part of the book collects together packages that are used predominantly by application developers
However, this designation should most definitely not keep DBAs away from these packages The
DBMS_SQL package, for example, can be and has been used by DBAs to construct powerful, efficient scriptsfor maintaining database objects and extracting information about a database
Chapter 2, Executing Dynamic SQL and PL/SQL
The DBMS_SQL package offers the ability to execute dynamically (at runtime) constructed SQLstatements, including DDL, and PL /SQL blocks of code DBMS_SQL is simultaneously one of themost complex, useful, and rewarding of the built−in packages It may take some time for you to getcomfortable with the way to apply this technology Once you are up and running, however, you will
be amazed at the feats you will be able to perform!
Chapter 3, Intersession Communication
It seems that everything these days has something to do with communication Messaging technologiesare consequently receiving lots of attention, but they are nothing new for Oracle Oracle has alreadyprovided, through the DBMS_PIPE and DBMS_ALERT packages, mechanisms for communicationbetween database sessions For instance, using database pipes with DBMS_PIPE, an application cancommunicate with a service routine external to the database Or, debuggers that capture PL /SQLerrors can utilize the fact that DBMS_PIPE is asynchronous with database transactions, getting theerrors logged whether the transaction issued a COMMIT or a ROLLBACK DBMS_ALERT is a littledifferent in that it allows synchronous notification to multiple users that specific database events haveoccurred
Chapter 4, User Lock and Transaction Management
Complex, multiuser applications managing new types of resources (objects, BLOBs, etc.) will requirethe ability to manage contention for those resources The Oracle database manages concurrent,
multiuser contention for data using sophisticated locking mechanisms Well, Oracle has now provideddevelopers with the "keys" to those locking mechanisms through the DBMS_LOCK package Watchout, though This deceptively powerful package might also put your applications to "sleep"!
DBMS_TRANSACTION provides a programmatic interface to a number of transaction−orientedSQL statements
Chapter 5, Oracle Advanced Queuing
Oracle8 offers a new capability called Oracle Advanced Queuing, which will make it much easier fordevelopers to build applications requiring deferred execution of activity Oracle is positioning Oracle
AQ as an alternative to the queuing mechanisms of teleprocessing monitors and messaging interfaces.Oracle AQ will serve as a foundation technology for workflow management applications, both thosedelivered by Oracle Corporation itself and those implemented by third parties Two packages,
DBMS_AQ and DBMS_AQADM, make Advanced Queuing available from within PL /SQL
programs
Chapter 6, Generating Output from PL/SQL Programs
The built−in packages offer a number of ways to generate output from within your PL /SQL program.While updating a database table is, of course, a form of "output" from PL /SQL, this chapter showsyou how to use DBMS_OUTPUT to display information to your screen and UTL_FILE to read andwrite information in server−side files
Chapter 7, Defining an Application Profile
It can be difficult to tell what is going on while an application is running Wouldn't it be nice to knowthat the big performance problem was because users were spending 90% of their time in a module thatsomeone else wrote? Seriously, though, one key to providing accurate, quantitative information aboututilization and resource consumption is to instrument applications such that they can be tracked
[Appendix A] What's on the Companion Disk?
Trang 21externally The DBMS_APPLICATION_INFO package lets an application register itself in a way thatcan be monitored at runtime through the V$SESSION and V$SQLAREA virtual tables.
Chapter 8, Managing Large Objects
With Oracle8, Oracle finally offers native, robust support for large objects Oracle LOBs can bestored in a column in a table or as an attribute of an object type The database supports objects of up
to four gigabytes of data, including character text, graphic images, video, or "raw" data The
DBMS_LOB package provides procedures and functions to access and manipulate LOBs within PL/SQL programs
Chapter 9, Datatype Packages
This chapter introduces you to several packages that specialize in working with specific types ofOracle data The DBMS_ROWID package allows you to work with the two different ROWID formatsavailable in Oracle8: extended (new to Oracle8) and restricted (traditional Oracle7 ROWIDs) TheUTL_RAW package offers a set of functions allowing you to perform concatenation, substring,bit−wise logical analysis, byte translation, and length operations on RAW data The UTL_REFpackage, new in Oracle8 Release 8.1, provides a PL /SQL interface to select and modify objects(instances of an object type) in an object table without having to specify or know about the underlyingdatabase table
Chapter 10, Miscellaneous Packages
You can't find a neat category for eveything, can you? This chapter collects together a variety ofuseful packages you are sure to dip into on a regular basis DBMS_UTILITY is the actual
"miscellaneous" package It offers programs to free unused user memory, parse comma−delimitedlists, calculate the elapsed time of PL /SQL programs, and much more You never know what you'llfind popping up next in DBMS_UTILITY! DBMS_DESCRIBE contains a single procedure,
DESCRIBE_PROCEDURE, which you can use to get information about the parameters of a storedprogram DBMS_DDL contains programs to recompile stored code, analyze objects in your schema,and modify the referenceability of object identifiers in Oracle8 DBMS_RANDOM supplies PL /SQLdevelopers with a random number generator
This part of the book groups together packages used to monitor, modify, or manage server−side resources invarious ways These packages will be of definite interest to DBAs; however, developers will also benefit frombecoming familiar with them The packages include facilities for managing session and shared pool memory,monitoring internal space utilization in segments, and executing PL/SQL procedures automatically in
background processes
Chapter 11, Managing Session Information
Oracle technologies allow for a great deal of user customization and security Language preferencescan be specified at the session level using the NLS options of the ALTER SESSION command Rolescan be used to distinguish groups of users from each other and to modify application behavior
accordingly The DBMS_SESSION package contains programs that can modify and inspect sessionroles and settings from within PL /SQL This package also contains programs for manipulatingsession memory and package states; these programs are very instructive to understand, even if notoften used This chapter also describes the DBMS_SYSTEM package, which lets administrators setvarious trace events in other users' sessions This can be invaluable when tracking down difficultapplication performance or database issues
Chapter 12, Managing Server Resources
With the built−in packages, Oracle is exposing information about database internals −− informationthat is not directly visible in the catalog The DBMS_SPACE package gives DBAs an analysis of theamount of space both used and free within a table, index, or cluster segment It also provides
[Appendix A] What's on the Companion Disk?
Trang 22information about segment free list sizes, of special interest to Oracle parallel server administrators.
On the memory side, the DBMS_SHARED_POOL package gives DBAs some measure of controlover the Oracle System Global Area's (SGA's) shared pool By pinning large packages into the sharedpool, expensive runtime memory management (and even errors) can be avoided
Chapter 13, Job Scheduling in the Database
The job queue is a powerful facility introduced with Version 7.2 of Oracle that gives DBAs anddevelopers the ability to schedule noninteractive execution of PL /SQL programs It's ideal for
handling regular administrative tasks like analyzing tables and for automatically kicking off
long−running batch jobs without requiring operator attention The DBMS_JOB package is yourinterface to this facility, and it's a little tricky to use This chapter explains how the job queue worksand how to get it to work for you
This part of the book describes the packages used for simple and advanced replication It provides detailsabout each package's procedures and functions, and explains how to use them together to create a replicatedenvironment
Chapter 14, Snapshots
The packages DBMS_SNAPSHOT, DBMS_REFRESH, and DBMS_OFFLINE_SNAPSHOT, andsome of the programs in DBMS_REPCAT, embody the functionality to maintain snapshots, snapshotgroups, and snapshot logs This includes refreshing snapshots, changing refresh intervals, adding andremoving snapshots from snapshot groups, and purging uneccessary data from snapshot logs You canuse DBMS_OFFLINE_SNAPSHOT to instantiate a new snapshot using an export of a master tableinstead of using the CREATE SNAPSHOT command In some cases, this type of instantiation isquicker because of network constraints
Chapter 15, Advanced Replication
This chapter explains how to use the DBMS_REPCAT, DBMS_REPUTIL, DBMS_OFFLINE_OG,DBMS_REPCAT_ADMIN, DBMS_REPCAT_AUTH, and DBMS_RECTIFIER_DIFF packages tocreate and administer your replicated databases DBMS_REPCAT and DBMS_REPUTIL contain thebulk of the procedures required to use the advanced replication option (formerly referred to as
"symmetric replication") Use these procedures to define and modify replication groups, replicatedobjects, master sites, and snapshot sites
Chapter 16, Conflict Resolution
Inevitably, conflicts will arise in a replicated environment You can configure Oracle to automaticallydetect, correct, and report many of the forseeable conflicts by using procedures in DBMS_REPCAT
to create and maintain resolution methods
Chapter 17, Deferred Transactions and Remote Procedure Calls
The advanced replication option relies heavily on DBMS_DEFER to propagate data changes amongmaster sites, but you can also use it yourself to queue deferred remote procedure calls (RPCs)
DBMS_DEFER_QUERY is primarily a diagnostic tool that reports on queued RPCs Use this
package to determine the values of passed parameters and more DBMS_DEFER_SYS contains theprocedures you will need to add and remove default destinations for your RPCs, schedule
propagation, and manage transactions
1.1 The Power of Built−in
Packages
1.3 Using Built−in
Packages[Appendix A] What's on the Companion Disk?
Trang 23Copyright (c) 2000 O'Reilly & Associates All rights reserved.
[Appendix A] What's on the Companion Disk?
Trang 24Chapter 1Introduction
1.3 Using Built−in Packages
There are several steps involved in using a built−in package:
1
Install the built−in package into the database In most cases, this will be done for you automatically.However, some packages, such as UTL_RAW, are not automatically installed or made publiclyaccessible, at least in the most recent version of Oracle as this book went to press The individualchapters in this book will tell you about any special steps you need to take to ensure that the package
A package is a collection of PL /SQL elements that are "packaged" or grouped together within a special
BEGIN−END syntax, a kind of "meta−block" of code Here is a partial list of the kinds of elements you canplace in a package:
Procedures and functions
Packages are among the least understood and most underutilized features of PL /SQL That's a shame, becausethe package structure is also one of the most useful constructs for building well−designed PL /SQL−based
14
Trang 25applications Packages provide a structure in which you can organize your modules and other PL /SQL
elements They encourage proper structured programming techniques in an environment that often befuddlesthe implementation of structured programming When you place a program unit into a package, you
automatically create a "context" for that program By collecting related PL /SQL elements in a package, you
express that relationship in the very structure of the code itself Packages are often called "the poor man's
objects" because they support some, but not all, object−oriented rules
The PL /SQL package is a deceptively simple yet powerful construct It consists of up to two distinct parts:
the specification and the body The package specification defines the public interface or API (Application
Programming Interface) of the package: those elements that can be referenced outside of the package The
package body contains the implementation of the package In just a few hours you can learn the basic
elements of package syntax and rules; there's not all that much to it You can spend weeks and months,
however, uncovering all the nuances and implications of the package structure
Of course, if you are working with built−in packages, you can leave those details to Oracle You just have tofigure out how to make the best use of the packages provided
1.3.2 Controlling Access with Packages
Probably the most important implication of package structure is how the builder of the package has completecontrol over what you can see or do The users of a package can do either of the following:
•
Execute programs listed in the package specification
•
Reference elements (variables, constants, exceptions, etc.) listed in the package specification
What can't a user of a package do? You can't look inside the package and see how the code was implemented.
You can't bypass the programs in the package specification in order to modify (corrupt) data structures
managed inside the package body.
These restrictions are closely tied to the power and usefulness of the package structure To illustrate this point,consider the following simple timer package First, the specification:
last_timing NUMBER := NULL;
[Appendix A] What's on the Companion Disk?
Trang 26Notice that there is another code element defined inside the package body besides the capture and
show_elapsed procedures: the last_timing variable This variable holds the timing value from the last call totmr.capture Since last_timing does not appear in the package specification, an external program (i.e., one that
is not defined in this package) cannot directly reference that variable This restriction is illustrated in theBooch diagram[2] Figure 1.1
[2] This diagram is named after Grady Booch, who pioneered many of the ideas of the
package, particularly in the context of object−oriented design
Figure 1.1: Booch diagram of tmr package
So if I try to access the last_timing variable from outside the tmr package, I get an error This is shown asfollows:
SQL> exec tmr.last_timing := 100;
begin tmr.last_timing := 100; end;
*
ERROR at line 1:
ORA−06550: line 1, column 14:
PLS−00302: component 'LAST_TIMING' must be declared
Why should you or anyone else care about where you define the last_timing variable? Because it illustrates acritical aspect of a package's value: integrity If I had placed the variable in the specification, then a user of thepackage could write over the value of last_timing −− and completely invalidate the integrity of the package.Suppose my package specification looked like this:
[Appendix A] What's on the Companion Disk?
Trang 27available in a highly controlled fashion As long as its developers write their code properly, there will never be
any danger that we can disrupt Oracle Server internals by calling built−in packaged functionality
1.3.3 Referencing Built−in Package Elements
As noted earlier, a package can have up to two parts: the specification and the body When it comes to
built−in packages, you really don't need to concern yourself with the package body That is the
implementation of the package, and something that is the responsibility of Oracle Corporation With very few
exceptions, those package bodies are "wrapped," which means that they are distributed in an encrypted formatthat you cannot read This is just as well, because what you really need to do is study the specification to learnabout the capabilities offered in that package
There are two ways to use a built−in package in your own code:
1
Run a function or procedure defined in the package specification
2
Reference a nonprogram element defined in the package specification
Notice that you never actually execute a package itself The package is simply a "container" for the variouscode elements defined in the package Let's take a look at an example to make all this very clear The
DBMS_SQL package (examined at great length in Chapter 2) allows you to execute dynamic SQL (SQLstatements constructed at runtime), a feature previously unavailable in the PL /SQL language Here is aportion of the specification of that package:
CREATE OR REPLACE PACKAGE DBMS_SQL
IS
−− CONSTANTS
−−
v6 constant integer := 0;
[Appendix A] What's on the Companion Disk?
Trang 28native constant integer := 1;
So if I want to open a dynamic cursor, I use this:
DECLARE
dyncur PLS_INTEGER;
BEGIN
dyncur := DBMS_SQL.OPEN_CURSOR;
And if I want to parse a string using the "native" database method, I would write the following code:
PROCEDURE showemps (where_in IN VARCHAR2)
a constant, passed as the third argument in my call to DBMS_SQL.PARSE
1.3.4 Exception Handling and Built−in Packages
Programs in built−in packages can raise exceptions You will often want to write code to check for and handlethese exceptions You should know about the different ways that exceptions can be defined and raised byprograms in the built−in packages This will affect the way you write your exception handlers
At the beginning of each package's coverage, you will find a description of the exceptions defined within thatpackage Within the documentation of many of the programs within a package, you will also find an
explanation of the specific exceptions that may be raised by those individual programs When references aremade to named exceptions in these explanations, they will appear in one of two forms:
[Appendix A] What's on the Companion Disk?
Trang 29In the package currently under discussion, or
•
In the STANDARD package; examples are VALUE_ERROR and NO_DATA_FOUND
In this section, I will review the four types of exceptions you may encounter when working with built−in
packages I will then show you the kind of code you will need to write to handle exceptions properly when
they propagate out from built−in packages The following sections demonstrate how to write code to work
with these different types of exceptions
Table 1.2 summarizes these types
Table 1.2: Types of Exceptions
Defined
How Exception Is Raised SQLCODE Behavior SQLERRM Behavior How to
HandleExceptionPackage−named system
exception
The package gives aname to a specificOracle error numberusing the PRAGMAEXCEPTION_INITstatement
The packaged program issues aRAISE statement
Returns the Oracleerror number
Returns the standard Oracle errormessage text
You canhandle it
by numberwithin aWHENOTHERSclause, or
by namewith itsownexceptionhandler;the latterimprovesthereadability
of yourcode.Package−defined exception The package
declares one or moreexceptions; theseexceptions havenames, but nomessage text and nounique number
The packaged program RAISEsthat exception by name
Returns 1 Returns "Unhandled user−defined
exception" message
You canonly handle
it by name
or with aWHENOTHERSclause, inwhich case
it isimpossible
to tellwhichexceptionwas raised.Standard system exception It is previously
given a name in the
The packaged program issues aRAISE statement
Returns the Oracleerror number
Returns the standard Oracle errormessage text
You canhandle it[Appendix A] What's on the Companion Disk?
Trang 30STANDARDpackage or it issimply an errornumber.
by name inits ownexceptionhandler, if
a name hasbeenassociatedwith thaterrornumber.Otherwise,you handlethe
exception
by number
in aWHENOTHERSclause.Package−specific exception In this case, Oracle
has rudelyappropriated foritself one or more ofthe
application−specificerror numbersbetween −20,999and −20,000 setaside for customers
The packaged program callsRAISE_APPLICATION_ERROR
Returns the number
in the −20NNNrange
Returns the message text provided
in the call toRAISE_APPLICATION_ERROR
You canhandletheseexceptions
by numberwithin aWHENOTHERSclause
1.3.4.1 Package−named system exception
In this scenario, the package gives a name to a specific Oracle error number using the PRAGMA
EXCEPTION_INIT statement You can then handle the exception by name with its own exception handler or
by number within a WHEN OTHERS clause Let's look at an example
The DBMS_DEFER package associates names with a number of Oracle errors Here is an example of one
such association:
updateconflict EXCEPTION;
PRAGMA EXCEPTION_INIT (updateconflict, −23303);
If a program in DBMS_DEFER raises this exception, you can handle it in either of the following ways:
EXCEPTION
WHEN DBMS_DEFER.UPDATECONFLICT
THEN
/* SQLCODE returns −23303 and SQLERRM returns the standard
Oracle error message */
[Appendix A] What's on the Companion Disk?
Trang 31/* SQLERRM returns the standard Oracle error message */
NOTE: You will not be able to write a statement like WHEN
DBMS_DEFER.UPDATECONFLICT in the Oracle Developer/2000 Release 1 environment
See Section 1.3.6, "Calling Built−in Packaged Code from Oracle Developer/2000 Release 1""
for more information on this restriction
1.3.4.2 Package−defined exception
In this scenario, the package declares one or more exceptions by name only; these exceptions do not havemessage text or a unique number associated with them When this exception has been raised, SQLCODE willalways return 1 and SQLERRM will always return the "Unhandled user−defined exception" message As aconsequence, you have two basic options for handling these exceptions:
The UTL_FILE.FOPEN function can raise the INVALID_MODE, INVALID_OPERATION, or
INVALID_PATH exceptions I can write an exception section for a program using UTL_FILE.FOPEN in one
[Appendix A] What's on the Companion Disk?
Trang 32When working with this kind of exception, always use the first approach With the WHEN OTHERS clause,
there is no way for you to know which of the three UTL_FILE exceptions was raised SQLCODE returns the
same value of 1 regardless of the specific exception raised
NOTE: You will not be able to write a statement like WHEN UTL_FILE.INVALID_MODE
in the Oracle Developer/2000 Release 1 environment See Section 1.3.6" for more
information on this restriction
1.3.4.3 Standard system exception
In this scenario, the package does not contain any statements that define new exceptions, nor does it givenames to existing Oracle error numbers Instead, a program in the package simply raises one of the errorsdefined in the Oracle documentation You can then handle this exception by its name (if there is one) or by itsnumber within a WHEN OTHERS clause Let's look at an example
The UTL_FILE.GET LINE procedure raises the NO_DATA_FOUND exception (ORA−01403, but
SQLCODE actually returns a value of 100) if you try to read past the end of a file You can handle this error
in either of the following ways:
Of course, if you need to handle an exception that does not have a name associated with it, you can only rely
on the WHEN OTHERS clause and an IF statement with SQLCODE to handle that error specifically
1.3.4.4 Package−specific exception
In some packages, Oracle developers decided to appropriate for their own use error numbers in the range setaside by Oracle Corporation for customer use (−20999 through −20000) This is very poor practice, as it cancause conflicts with your ownuse of these values Unfortunately, it does happen and you need to know what to
do about it
For example, the DBMS_OUTPUT package uses the −20000 error number to communicate back to thecalling program either one of these errors:
[Appendix A] What's on the Companion Disk?
Trang 33ORU−10027: buffer overflow, limit of <buf_limit> bytes.
ORU−10028: line length overflow, limit of 255 bytes per line.
Here is a attempt to call DBMS_OUTPUT.PUT_LINE that raises an unhandled exception in a SQL*Plussession:
SQL> exec dbms_output.put_line (rpad ('abc', 300, 'def'))
*
ERROR at line 1:
ORA−20000: ORU−10028: line length overflow, limit of 255 bytes per line
ORA−06512: at "SYS.DBMS_OUTPUT", line 99
ORA−06512: at "SYS.DBMS_OUTPUT", line 65
ORA−06512: at line 1
I can handle this error if I call the built−in procedure from within a PL /SQL block as follows:
/* Filename on companion disk: myput.sp /*
CREATE OR REPLACE PROCEDURE myput (str IN VARCHAR2)
The myput procedure implements the following logic: try to display the string If an exception is raised, check
to see if it is a −20000 error If so, see if the error message indicates that it is a "buffer too small" error If so,expand the buffer to the maximum size and try again to display the string If the error message indicates a
"string too long" error, display the first 255 bytes and then call myput again recursively to display the rest ofthe string
1.3.4.5 Same exception, different causes
One interesting situation you may run into when working with some of the built−in packages is that the sameexception can be raised from different circumstances Specifically, the NO_DATA_FOUND exception israised by the PL /SQL runtime engine under any of these conditions:
[Appendix A] What's on the Companion Disk?
Trang 34You read past the end of a large object with DBMS_LOB.READ.
If you are writing code that could raise NO_DATA_FOUND for different reasons, you may not be able to get
by with a single exception handler like this:
else If you face this problem, you may want to use a technique I call exception aliasing Consider the very
short program below:
CREATE OR REPLACE PROCEDURE just_a_demo
(file IN UTL_FILE.FILE_TYPE, empno_in IN emp.empno%TYPE)
I have embedded the call to UTL_FILE.GET_LINE inside its own block If that program reads past the end of
a file and raises NO_DATA_FOUND, that block's exception section "translates" NO_DATA_FOUND intoanother, distinct exception: end_of_file (declared in the procedure itself ) The exception section of the
procedure as a whole can then distinguish between the two different NO_DATA_FOUND scenarios
1.3.5 Encapsulating Access to the Built−in Packages
You will discover (both through reading this book and through your own experience) that there are manyreasons to avoid directly accessing built−in packaged functionality In a number of cases, you will want to
build your own package on top of the built−in package This process is usually referred to as encapsulation.
Why would you bother with an encapsulation package? Any of the following reasons will do:
•
[Appendix A] What's on the Companion Disk?
Trang 35The built−in packages offer lots of interesting technology, but they are not always very easy to use.You can hide the complexity, or in some cases, the poor design, and make it much easier for yourselfand others to reap the benefits.
•
Some of the packages contain programs that you would not want to make generally or widely
available Conversely, other programs in that same package might be very useful for the "general
public." An encapsulation package can offer only those programs that should be available, while
hiding the others (In this case, you will want to revoke any EXECUTE privileges on the underlyingpackage.)
Roughly speaking, there are two types of encapsulation to consider when working with the built−in packages:
Extension encapsulation
This is the most common type of encapsulation for built−in packages In this case, you provide one or
more programs that extend the functionality or usability of the underlying package.
Covering encapsulation
When you create a cover for a built−in package, you create a package with a specification that
matches that of the built−in package (same program names, same parameter lists) You can even giveyour package the same name as the built−in package, but you install it in a schema other than SYS.When you revoke EXECUTE authority on the built−in package and grant EXECUTE authority onyour package, users of the built−in package will automatically be directed to your replacement Oraclerecommends this technique, for example, with the DBMS_APPLICATION_INFO package
1.3.5.1 Examples of encapsulation packages
This book (and the accompanying disk) contains many packages that encapsulate or cover an underlyingbuilt−in package (or, in some cases, a subset of the package) Table 1.3 shows the encapsulation packages inthe book
Table 1.3: Encapsulation Packages for Built−ins
Built−in Package/
Program
EncapsulationPackage Name
File Description
DBMS_AQ
DBMS_AQADM
aq aq.spp Hides details of creating, starting, stopping, and
dropping queues and queue tables The packageallows you to write less code and also handles[Appendix A] What's on the Companion Disk?
Trang 36common errors.
DBMS_APPLICATION_
INFO
register_app register.sql Allows developers to easily register applications
and track resource usage statistics
dbparm dbparm.spp Makes it easier to obtain specific initialization
values from the database instance
DBMS_UTILITY
DB_VERSION
db dbver.spp Converts through encapsulation the
DB_VERSION procedure into two separatefunctions, so you can ask for the version or thecompatibility value, as desired
DBMS_SQL.PARSE dynconst dynconst.spp Hides the need to provide a DBMS_SQL
database mode when you parse a SQL statement.This technique is especially useful when you arewriting code in Oracle Developer/2000 Release
1 (See the next section for details.)DBMS_DESCRIBE psdesc psdesc.spp Hides the need to declare a dozen different PL
/SQL tables just so you can useDBMS_DESCRIBE
DBMS_LOCK dblock dblock.sql Simplifies the use of user−named locks, as well
as maximizing their efficiency
DBMS_IJOB.BROKEN break_all_jobs
(procedure)
job3.sql Allows the DBA to set the broken flag in all jobs
regardless of owner
DBMS_PIPE dbpipe dbpipe.sql Provides some useful and interesting pipe
utilities, including generic message pack/unpackand message forwarding
DBMS_SESSION my_session mysess.sql Simplifies use of some of the programs and adds
some additional conveniences
DBMS_SHARED_POOL object_keeper keeper.sql Allows configurable auto−keeping of packages
in database startup scripts
[Appendix A] What's on the Companion Disk?
Trang 37KEEP (procedure)
DBMS_SPACE segspace segspace.sql Transforms the unwieldy procedure calls into
simple, SQL−callable functions
DBMS_SYSTEM
SET_SQL_TRACE_
IN_SESSION
trace trace.sql Allows the DBA to set SQL tracing on or off in
other sessions by username or session id
1.3.6 Calling Built−in Packaged Code from Oracle Developer/2000
You can reference only packaged procedures and functions You cannot, for example, make reference
in your client−side code to DBMS_SQL.NATIVE (a constant) or
UTL_FILE.INVALID_OPERATION (an exception)
The following sections explore these restrictions in more detail and suggest work−arounds for making full use
of the built−in packages from within products like Oracle Forms and Oracle Reports
1.3.6.1 Referencing packaged constants and variables
Consider the DBMS_SQL.PARSE procedure Here is the header for this program:
Now, if you try to execute this program in an Oracle Forms program unit, as in the following,
[Appendix A] What's on the Companion Disk?
Trang 38DBMS_SQL.PARSE (cur, 'SELECT ', DBMS_SQL.NATIVE);
.
you will receive this error:
Error 302: component NATIVE must be declared
Oracle Forms simply does not know how to interpret anything but procedures and functions in stored
packages So what's a developer to do? You have several options:
Create a stored procedure that calls DBMS_SQL.PARSE and hides the use of the constant
The first option would result in code like this:
The second option (encapsulating the constant inside a function) is better I could, for example, create a tinypackage as follows:
/* Filename on companion disk: dynconst.spp */*
CREATE OR REPLACE PACKAGE dynsql_value
IS
FUNCTION v6 RETURN INTEGER;
FUNCTION v7 RETURN INTEGER;
FUNCTION native RETURN INTEGER;
END;
/
CREATE OR REPLACE PACKAGE BODY dynsql_value
IS
FUNCTION v6 RETURN INTEGER
IS BEGIN RETURN DBMS_SQL.V6; END;
FUNCTION v7 RETURN INTEGER
IS BEGIN RETURN DBMS_SQL.V7; END;
FUNCTION native RETURN INTEGER
IS BEGIN RETURN DBMS_SQL.NATIVE; END;
[Appendix A] What's on the Companion Disk?
Trang 39This code is almost identical to my first example, but I am calling a function rather than referencing a literal,and that makes all the difference.
The third option, encapsulating the call to DBMS_SQL.PARSE, is perhaps the optimal solution Why shouldyou even have to bother passing the database mode? You might as well just always make it "native." Here issome code that hides this argument entirely:
*Filename on companion disk: dynconst.spp */
CREATE OR REPLACE PACKAGE dynsql_value
1.3.6.2 Handling exceptions in Oracle Developer/2000 Release 1
An earlier section in this chapter ("Exception Handling and Built−in Packages") explored the different types
of exceptions that can be raised from within built−in packages One type in particular, the package−specificexception, presents a challenge to Oracle Developer/2000 programmers
Consider once again the UTL_FILE package It declares a number of exceptions and, as noted previously, theonly way to handle those exceptions (and know which exception was raised) is to create an explicit exceptionhandler, as in:
Instead of calling UTL_FILE.FOPEN directly, for example, and risk raising an exception you cannot interpretaccurately, you might want to consider something like this:
/* Filename on companion disk: myfile.spp */
CREATE OR REPLACE PACKAGE myfile
IS
[Appendix A] What's on the Companion Disk?
Trang 40/* Document in the package specification that:
I translate the package−specific exceptions to −20NNN exceptions Therefore, my UTL_FILE
exception now has a number I can check for that number within my client−side application and takeappropriate action
2
I hide the UTL_FILE.FILE_TYPE record From Oracle Forms, I cannot even declare a record of thistype (it is not a program, so UTL_FILE.FILE_TYPE cannot be referenced from within Oracle
Developer/2000 Release 1)
With this wrapper approach, you can build a package that allows you to read and write a particular
server−side file from Oracle Forms You would still need to build read, write, and close procedures, but thetechnique should be clear
1.3.7 Accessing Built−in Packaged Technology from Within SQL
Throughout this book, you will find documentation indicating whether a particular packaged function can becalled from within an SQL statement, or whether a packaged procedure can be called by a function that, inturn, is called from within SQL This section explains the significance of that capability
If you are running a version of Oracle Server 7.1 and beyond, you can call PL /SQL functions from withinSQL statements (If you are not running at least Oracle Server 7.1, you can skip this section −− but youshould also certainly upgrade your database software as soon as possible!) Let's take a look at an example togive you a feel for this capability
[Appendix A] What's on the Companion Disk?