Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 50 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
50
Dung lượng
232,12 KB
Nội dung
END;
/* The total_cost function uses net_profit. */
FUNCTION total_cost (. . .) RETURN NUMBER
IS
BEGIN
IF net_profit (. . .) < 0
THEN
RETURN 0;
ELSE
RETURN . . .;
END IF;
END;
BEGIN
. . .
END;
Here are some rules to remember concerning forward declarations:
● You cannot make forward declarations of a variable or cursor. This technique works only with
modules (procedures and functions).
● The definition for a forwardly-declared program must be contained in the declaration section
of the same PL/SQL block (anonymous block, procedure, function, or package) in which you
code the forward declaration.
In some situations, you absolutely require forward declarations; in most situations, they just help
make your code more readable and presentable. As with every other advanced or unusual feature of
the PL/SQL language, use forward declarations only when you really need the functionality.
Otherwise, the declarations simply add to the clutter of your program, which is the last thing you
want.
Previous: 15.8 Module
Overloading
Oracle PL/SQL
Programming, 2nd Edition
Next: 15.10 Go Forth and
Modularize!
15.8 Module Overloading
Book Index
15.10 Go Forth and
Modularize!
The Oracle Library
Navigation
Copyright (c) 2000 O'Reilly & Associates. All rights reserved.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Previous: 15.9 Forward
Declarations
Chapter 15
Procedures and Functions
Next: 16. Packages
15.10 Go Forth and Modularize!
As the PL/SQL language and Oracle tools mature, you will find that you are being asked to
implement increasingly complex applications with this technology. To be quite frank, you don't have
much of a chance of success in implementing such large-scale projects without an intimate familiarity
with the modularization techniques available in PL/SQL.
While this book could not possibly provide a full treatment of modularization in PL/SQL, it should
give you some solid pointers and a foundation from which to work. There is still much more for you
to learn the full capabilities of packages, the awesome range of package extensions Oracle
Corporation now provides with the tools and database, and the various options for code reusability
and more.
Behind all of that technology, however, you must develop an instinct, a sixth sense, for
modularization. Develop a deep and abiding allergy to code redundancy and the hardcoding of values
and formulas. Apply a fanatic's devotion to the modular construction of true black boxes which easily
plug-and-play in and across applications.
You will find yourself spending more time in the design phase and less time in debug mode. Your
programs will be more readable and maintainable. They will stand as elegant testimonies to your
intellectual integrity. You will be the most popular kid in your class and but enough already. I am
sure you are properly motivated.
Go forth and modularize!
Previous: 15.9 Forward
Declarations
Oracle PL/SQL
Programming, 2nd Edition
Next: 16. Packages
15.9 Forward Declarations
Book Index
16. Packages
The Oracle Library
Navigation
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Copyright (c) 2000 O'Reilly & Associates. All rights reserved.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Previous: 15.10 Go Forth
and Modularize!
Chapter 16
Next: 16.2 Overview of
Package Structure
16. Packages
Contents:
The Benefits of Packages
Overview of Package Structure
The Package Specification
The Package Body
Package Data
Package Initialization
A package is a collection of PL/SQL objects that are packaged or grouped together within a special
BEGIN-END syntax, a kind of "meta-block." Here is a partial list of the kinds of objects you can
place in a package:
● Cursors
● Variables (scalars, records, tables, etc.)
● Constants
● Exception names
● PL/SQL table and record TYPE statements
● Procedures
● Functions
Packages are among the least understood and most underutilized features of PL/SQL. That is a
shame, because the package structure is also one of the most useful constructs for building well-
designed PL/SQL-based applications. 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 befuddles the implementation of structured programming.
Oracle Corporation itself uses the package construct to extend the PL/SQL language.
Appendix C,
Built-In Packages, contains descriptions of many of these predefined packages. In fact, the most basic
operators of the PL/SQL language, such as the + and LIKE operators and the INSTR function, are all
defined in a special package called STANDARD. If Oracle believes that packages are the way to go
when it comes to building both fundamental and complex programs, don't you think that you could
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
benefit from the same?
Packages are, by nature, highly modular. 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. For example,
packages allow you to encapsulate and abstract your data and functions.
The PL/SQL package is a deceptively simple, powerful construct. You can in just a few hours learn
the basic elements of package syntax and rules; there's not all that much to it. You can spend days
and weeks, however, uncovering all the nuances and implications of the package structure. This
chapter and the next one filled with examples of packages will help you absorb the features and
benefits of the PL/SQL package more rapidly.
16.1 The Benefits of Packages
Before we explore all the aspects of working with packages, let's review some of the most important
benefits of the package:
16.1.1 Enforced Information Hiding
When you build a package, you decide which of the package elements are public (can be referenced
outside of the package) and which are private (available only within the package itself). You also can
restrict access to the package to only the specification. In this way, you use the package to hide the
implementational details of your programs. This is most important when you want to isolate the most
volatile aspects of your application, such as platform dependencies, frequently changing data
structures, and temporary workarounds.
16.1.2 Object-Oriented Design
While PL/SQL does not yet offer full object-oriented capabilities, packages do offer the ability to
follow many object-oriented design principles. The package gives developers very tight control over
how the modules and data structures inside the package can be accessed.
You can, therefore, embed all the rules about and access to your entities (whether they are database
tables or memory-based structures) in the package. Because this is the only way to work with that
entity, you have in essence created an abstracted and encapsulated object.
16.1.3 Top-Down Design
A package's specification can be written before its body. You can, in other words, design the interface
to the code hidden in the package (the modules, their names, and their parameters) before you have
actually implemented the modules themselves. This feature dovetails nicely with top-down design, in
which you move from high-level requirements to functional decompositions to module calls.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Of course, you can design the names of standalone modules just as you can the names of packages
and their modules. The big difference with the package specification is that you can compile it even
without its body. Furthermore, and most remarkably, programs that call packaged modules will
compile successfully as long as the specification compiles.
16.1.4 Object Persistence
PL/SQL packages offer the ability to implement global data in your application environment. Global
data is information that persists across application components; it isn't just local to the current
module. If you designed screens with SQL*Forms or Oracle Forms, you are probably familiar with
its GLOBAL variables, which allow you to pass information between screens. Those globals have
their limitations (GLOBAL variables are always represented as fixed-length CHAR variables with a
length of 254), but they sure can be useful.
Objects declared in a package specification (that is, visible to anyone with EXECUTE authority on
that package) act as global data for all PL/SQL objects in the application. If you have access to the
package, you can modify package variables in one module and then reference those changed
variables in another module. This data persists for the duration of a user session (connection to the
database).
If a packaged procedure opens a cursor, that cursor remains open and is available to other packaged
routines throughout the session. You do not have to explicitly define the cursor in each program. You
can open it in one module and fetch it in another module. In addition, package variables can carry
data across the boundaries of transactions, because they are tied to the session itself and not to a
transaction.
16.1.5 Performance Improvement
When an object in a package is referenced for the first time, the entire package (already compiled and
validated) is loaded into memory (the Shared Global Area [SGA] of the RDBMS). All other package
elements are thereby made immediately available for future calls to the package. PL/SQL does not
have to keep retrieving program elements or data from disk each time a new object is referenced.
This feature is especially important in a distributed execution environment. You may reference
packages from different databases across a local area or even a wide area network. You want to
minimize the network traffic involved in executing your code.
Packages also offer performance advantages on the development side (with potential impact on
overall database performance). The Oracle RDBMS automatically tracks the validity of all program
objects (procedures, functions, packages) stored in the database. It determines what other objects that
program is dependent on, such as tables. If a dependent object such as a table's structure changes, for
example, then all programs that rely on that object are flagged as invalid. The database then
automatically recompiles these invalid programs before they are used.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
You can limit automatic recompiles by placing functions and procedures inside packages. If program
A calls packaged module B, it does so through the package's specification. As long as the
specification of a packaged module does not change, any program that calls the module is not flagged
as invalid and will not have to be recompiled.
This chapter should provide you with all the information and examples you need to put packages to
work immediately in your applications. If you are still unsure about packages after reading it, try out
a couple of small packages. Test those hard-to-believe features like global package data to prove to
yourself that they really work as advertised. Examine carefully the examples in
Chapter 18, Object
Types. Do whatever you need to do to incorporate packages into every level of your application, from
database server to client applications.
Previous: 15.10 Go Forth
and Modularize!
Oracle PL/SQL
Programming, 2nd Edition
Next: 16.2 Overview of
Package Structure
15.10 Go Forth and
Modularize!
Book Index
16.2 Overview of Package
Structure
The Oracle Library
Navigation
Copyright (c) 2000 O'Reilly & Associates. All rights reserved.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Previous: 16.1 The Benefits
of Packages
Chapter 16
Packages
Next: 16.3 The Package
Specification
16.2 Overview of Package Structure
A package provides an extra layer of code and structure over that of an individual module. Many of
the concepts needed to understand a package's structure will be familiar to you. In fact, a package is
very similar in structure to a PL/SQL module that has local modules defined within it.
Whereas a module has a header and a body, a package has a specification and a body. Just as the
module's header explains to a developer how to call that module, the package specification describes
the different elements of the package that can be called. Beyond that, however, there are key
differences between the constructs in the module and in the package.
A module's specification and body are connected by the IS keyword; both are required and one
cannot be written without the other. The specification determines how you call the module. The body,
after the IS keyword, contains the code that is executed when the function is used. These two
components of a module are coded together and are completely inseparable.
A package also has a specification and a body, but the package's two parts are structured differently,
and have a different significance, from those for a single module. With a package, the specification
and body are completely distinct objects. You can write and compile the specification independently
of the body. When you create and replace stored packages in the database, you perform this action
separately for each of the specification and body.
This separation of specification and body allows you to employ top-down design techniques in a
powerful way. Don't worry about the details of how a procedure or function is going to do its job. Just
concentrate on the different modules you need and how they should be connected together.
16.2.1 The Specification
The package specification contains the definition or specification of all elements in the package that
may be referenced outside of the package. These are called the public elements of the package (see
the section entitled Section 16.2.4, "Public and Private Package Elements"" for more information).
Figure 16.1 shows an example of a package specification containing two module definitions.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Figure 16.1: The specification of sp_timer package
Like the module, the package specification contains all the code that is needed for a developer to
understand how to call the objects in the package. A developer should never have to examine the
code behind the specification (which is the body) in order to understand how to use and benefit from
the package.
16.2.2 The Body
The body of the package contains all the code behind the package specification: the implementation
of the modules, cursors, and other objects. Figure 16.2 illustrates the body required to implement the
specification of the sp_timer package shown in
Figure 16.1.
Figure 16.2: The body of sp_timer package
The body may also contain elements that do not appear in the specification. These are called the
private elements of the package. A private element cannot be referenced outside of the package, since
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
it does not appear in the specification.
The body of the package resembles a standalone module's declaration section. It contains both
declarations of variables and the definitions of all package modules. The package body may also
contain an execution section, which is called the initialization section because it is only run once, to
initialize the package.
16.2.3 Package Syntax
The general syntax for the two parts of a package follows:
● The package specification:
PACKAGE package_name
IS
[ declarations of variables and types ]
[ specifications of cursors ]
[ specifications of modules ]
END [ package_name ];
You can declare variables and include specifications of both cursors and modules (and only
the specifications). You must have at least one declaration or specification statement in the
package specification.
Notice that the package specification has its own BEGIN-END block syntax. This enables its
independent existence and compilation from the package body.
● The package body:
PACKAGE BODY package_name
IS
[ declarations of variables and types ]
[ specification and SELECT statement of cursors ]
[ specification and body of modules ]
[ BEGIN
executable statements ]
[ EXCEPTION
exception handlers ]
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
[...]... structures will not match those used by the form It is a different Oracle connection and a new instantiation of the data structures Figure 16.5: Two Oracle connections between Oracle Forms and Oracle Reports Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark Just as there are two types of data structures in the package (public and private), there are also two types of global... environments Previous: 16.2 Overview of Package Structure 16.2 Overview of Package Structure Oracle PL/SQL Programming, 2nd Edition Book Index Next: 16.4 The Package Body 16.4 The Package Body The Oracle Library Navigation Copyright (c) 2000 O'Reilly & Associates All rights reserved Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark Previous: 16.3 The Package Specification Chapter 16... in both places Previous: 16.3 The Package Specification 16.3 The Package Specification Oracle PL/SQL Programming, 2nd Edition Book Index Next: 16.5 Package Data 16.5 Package Data The Oracle Library Navigation Copyright (c) 2000 O'Reilly & Associates All rights reserved Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark Previous: 16.4 The Package Body Chapter 16 Packages Next:... single Oracle connection The form then uses the RUN_PRODUCT built-in to kick off a report using Oracle Reports By default, Oracle Reports uses a second connection to the database (same user name and password) to run the report So even if this report accesses the same package and its data structures, the values in those data structures will not match those used by the form It is a different Oracle connection... at each package component Previous: 16.1 The Benefits Oracle PL/SQL of Packages Programming, 2nd Edition 16.1 The Benefits of Packages Book Index Next: 16.3 The Package Specification 16.3 The Package Specification The Oracle Library Navigation Copyright (c) 2000 O'Reilly & Associates All rights reserved Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark Previous: 16.2 Overview... structure is protected Previous: 16.4 The Package Body 16.4 The Package Body Oracle PL/SQL Programming, 2nd Edition Book Index Next: 16.6 Package Initialization 16.6 Package Initialization The Oracle Library Navigation Copyright (c) 2000 O'Reilly & Associates All rights reserved Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark Previous: 16.5 Package Data Chapter 16 Packages... structures as well 16.5.2 Global Within a Single Oracle Session As a result of the SGA-based architecture, package data structures act as globals within the PL/SQL environment Remember, however, that they are globals only within a single Oracle session or connection Package data is not shared across sessions If you need to share data between different Oracle sessions, you must use the DBMS_PIPE package... a specification and has no body at all, as you will see in the next section The specification is the API (Application Programmatic Interface) into the package's contents A Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark developer should never have to look at the actual code in a package in order to use an object in the specification The pets_inc package specification shown... EXCEPTION; PRAGMA EXCEPTION_INIT (exc_must_be_eighteen, -20001); max_error_number_used NUMBER := -20001; TYPE error_msg_tabtype IS TABLE OF VARCHAR2 (240) INDEX BY BINARY_INTEGER; Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark error_msg_table error_msg_tabtype; END exchdlr; Because this package does not specify any cursors or modules, I do not need to create a body for the exception... a package! The bodiless package shown in the next example contains all the magic values in my application: PACKAGE config_pkg IS closed_status CONSTANT VARCHAR2(1) := 'C'; Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark open_status active_status inactive_status CONSTANT VARCHAR2(1) := 'O'; CONSTANT VARCHAR2(1) := 'A'; CONSTANT VARCHAR2(1) := 'I'; min_difference max_difference . PDF Split-Merge on www.verypdf.com to remove this watermark.
Copyright (c) 2000 O'Reilly & Associates. All rights reserved.
Please purchase PDF.
Structure
The Oracle Library
Navigation
Copyright (c) 2000 O'Reilly & Associates. All rights reserved.
Please purchase PDF Split-Merge on www.verypdf.com