Sub topic 3
Public constants, types and exceptions in the specification
This chapter assumes you can write a basic package specification and body, as covered in the previous chapters. It also assumes you know how PL/SQL exceptions are raised and handled. Here you will look at the items a specification can declare besides subprograms: constants, types and exceptions. These items define the vocabulary that callers and the body share.
What a specification can declare
A specification is the public contract of a package. Beyond subprogram headers, it can hold these declarations:
- Constants, such as limits and status codes.
- Subtypes, record types, collection types and REF CURSOR types.
- Named exceptions, optionally mapped to an error number.
- Variables and cursors. Variables are legal but usually a poor choice, as the warning later in this chapter explains.
Everything declared in the specification is visible to any caller with EXECUTE privilege on the package. The body can use these items without repeating them, so the specification is the single place where a name is defined.
Public constants
A constant is declared with the keyword CONSTANT and must have an initial value. It cannot be assigned afterward. Constants remove magic numbers and strings from your code and give every caller the same value.
CREATE OR REPLACE PACKAGE shipping_api AS
c_status_new CONSTANT VARCHAR2(10) := 'NEW';
c_status_shipped CONSTANT VARCHAR2(10) := 'SHIPPED';
c_max_weight_kg CONSTANT NUMBER := 30;
END shipping_api;
/The initial value can be an expression, not only a literal. A value such as SYSDATE is computed when the package is first used in a session. The value is fixed from then until the session ends or the package state is reset.
Constants can also serve as parameter defaults in the same specification:
CREATE OR REPLACE PACKAGE pricing_api AS
c_default_discount_pct CONSTANT NUMBER := 5;
FUNCTION discounted(
p_price IN NUMBER,
p_discount_pct IN NUMBER DEFAULT c_default_discount_pct)
RETURN NUMBER;
END pricing_api;
/A package constant is a PL/SQL item, not a SQL item. You can use it inside PL/SQL code, including static SQL statements written in PL/SQL, where it acts as a bind value. You cannot reference it in a plain SQL statement run from a client:
-- Fails with ORA-06553 (PLS-221): not a procedure or is undefined.
SELECT shipping_api.c_max_weight_kg FROM dual;If SQL needs the value, wrap it in a function and call the function instead.
Public types
You can declare types in the specification so that callers can declare variables of that type and so that subprogram signatures can use it. A type declared only in the body cannot appear in a public signature, because callers could never name it.
CREATE OR REPLACE PACKAGE shipping_api AS
c_status_new CONSTANT VARCHAR2(10) := 'NEW';
c_max_weight_kg CONSTANT NUMBER := 30;
SUBTYPE status_t IS VARCHAR2(10);
TYPE parcel_rt IS RECORD (
parcel_id NUMBER,
weight_kg NUMBER,
status status_t
);
TYPE parcel_tt IS TABLE OF parcel_rt INDEX BY PLS_INTEGER;
FUNCTION new_parcel(p_parcel_id IN NUMBER, p_weight_kg IN NUMBER)
RETURN parcel_rt;
FUNCTION total_weight(p_parcels IN parcel_tt) RETURN NUMBER;
END shipping_api;
/Three kinds of type are common here.
- A SUBTYPE gives a constrained or renamed type a meaningful name, such as
status_t. If the length of a status code changes, you change one line. - A record type groups related fields. Records can be returned from functions and passed as parameters.
- A collection type such as an associative array lets you pass sets of values in one call.
A common naming convention uses suffixes: _t for subtypes, _rt for records and _tt for collections. Pick a convention and keep it across the schema.
You can also anchor a type to a table column with %TYPE or %ROWTYPE. For example, employees.salary%TYPE follows the column if its definition changes, which keeps the interface in step with the data model.
Package types versus schema types
A type declared in a package is a PL/SQL type. It lives and works inside PL/SQL. A type created with CREATE TYPE is a schema-level type, which SQL can also use, for example as a column type or in a TABLE() query. If a collection must cross the boundary into SQL, prefer a schema-level type. Support for package-level collection types in SQL varies by database version, so check your version's documentation before relying on it.
Public exceptions
An exception declared in the specification can be handled by name from any caller. This is the main reason to make one public. Without it, callers would have to match on error numbers or catch WHEN OTHERS.
CREATE OR REPLACE PACKAGE shipping_api AS
c_max_weight_kg CONSTANT NUMBER := 30;
e_too_heavy EXCEPTION;
PRAGMA EXCEPTION_INIT(e_too_heavy, -20010);
END shipping_api;
/PRAGMA EXCEPTION_INIT ties the exception name to an error number. Two rules apply:
- The pragma must appear in the same declarative part as the exception, after its declaration.
- For your own application errors, use numbers from -20999 to -20000. Oracle reserves all other numbers for the database.
The mapping matters when the error leaves PL/SQL. An exception without the pragma that goes unhandled reaches the client as ORA-06510, a generic "unhandled user-defined exception" error. With the pragma, the client sees your number, such as ORA-20010, which the application can test for.
The mapping also works in the other direction. If code somewhere calls RAISE_APPLICATION_ERROR(-20010, 'Parcel too heavy'), a handler written as WHEN shipping_api.e_too_heavy catches it, because the numbers match. This lets you attach a message to the error while callers still handle it by name.
CREATE OR REPLACE PACKAGE BODY shipping_api AS
FUNCTION new_parcel(p_parcel_id IN NUMBER, p_weight_kg IN NUMBER)
RETURN parcel_rt IS
l_parcel parcel_rt;
BEGIN
IF p_weight_kg > c_max_weight_kg THEN
RAISE_APPLICATION_ERROR(-20010,
'Parcel ' || p_parcel_id || ' exceeds ' || c_max_weight_kg || ' kg');
END IF;
l_parcel.parcel_id := p_parcel_id;
l_parcel.weight_kg := p_weight_kg;
l_parcel.status := c_status_new;
RETURN l_parcel;
END new_parcel;
FUNCTION total_weight(p_parcels IN parcel_tt) RETURN NUMBER IS
l_total NUMBER := 0;
l_i PLS_INTEGER := p_parcels.FIRST;
BEGIN
WHILE l_i IS NOT NULL LOOP
l_total := l_total + p_parcels(l_i).weight_kg;
l_i := p_parcels.NEXT(l_i);
END LOOP;
RETURN l_total;
END total_weight;
END shipping_api;
/The version of shipping_api that combines all the pieces above (constants, subtype, types, exception and the two function headers) is the specification this body implements. Put them together in one CREATE OR REPLACE PACKAGE statement before you compile the body.
A caller then uses dot notation for every public item:
SET SERVEROUTPUT ON
DECLARE
l_parcels shipping_api.parcel_tt;
BEGIN
l_parcels(1) := shipping_api.new_parcel(1, 12.5);
l_parcels(2) := shipping_api.new_parcel(2, 4);
DBMS_OUTPUT.PUT_LINE('Total: ' || shipping_api.total_weight(l_parcels) || ' kg');
l_parcels(3) := shipping_api.new_parcel(3, 45);
EXCEPTION
WHEN shipping_api.e_too_heavy THEN
DBMS_OUTPUT.PUT_LINE('Limit is ' || shipping_api.c_max_weight_kg || ' kg');
END;
/This prints Total: 16.5 kg and then Limit is 30 kg. The third call raises ORA-20010, and the handler matches it by name.
Specifications that need no body
A package whose specification holds only constants, types and exceptions needs no body. This is a common way to share definitions across an application:
CREATE OR REPLACE PACKAGE app_errors AS
e_invalid_input EXCEPTION;
PRAGMA EXCEPTION_INIT(e_invalid_input, -20001);
e_not_found EXCEPTION;
PRAGMA EXCEPTION_INIT(e_not_found, -20002);
END app_errors;
/Keeping error numbers in one package prevents two modules from using the same number for different problems. Each exception gets one number, and one name stands for it everywhere.
What changing the specification costs
Because other code compiles against the specification, a change to it has consequences. The next chapters cover dependencies in detail. For now, remember these points:
- Adding or changing a constant, type or exception recompiles the specification and invalidates dependent objects. Oracle revalidates them on next use or when you recompile them.
- Changing a constant's value therefore affects callers even though no subprogram changed. Treat a specification edit as an interface change.
- Changing only the body leaves dependents valid. This is why you keep as much as possible in the body.
Summary of declarations
| Item | Declared in specification | Callers can | Notes |
|---|---|---|---|
| Constant | `c_name CONSTANT type := value;` | Read it | Not usable in plain SQL |
| Subtype | `SUBTYPE name IS base;` | Declare variables of it | Centralizes size and precision |
| Record or collection type | `TYPE name IS ...;` | Declare variables, pass parameters | PL/SQL only unless schema-level |
| Exception | `name EXCEPTION;` plus pragma | Handle by name | Use a number from -20999 to -20000 |
| Variable | `name type;` | Read and write | Avoid; use a getter and setter |
Design guidance
- Declare in the specification only what callers need. Anything else belongs in the body, where you can change it freely.
- Name items so the prefix shows the kind:
c_for constants,e_for exceptions,_t,_rtand_ttfor types. - Prefer exposing exceptions over exposing error numbers. Callers should write
WHEN shipping_api.e_too_heavy, notWHEN OTHERSfollowed by a check ofSQLCODE. - Group exceptions shared across modules in one specification-only package.
Exercise
A package declares e_stock_low EXCEPTION; in its specification with no PRAGMA EXCEPTIONINIT. The body raises it with `RAISE estock_low;`, and no caller handles it. What error does a client application receive, and what would you change so the client sees a specific application error number instead?
Show answer
The client receives ORA-06510, the generic unhandled user-defined exception error. To fix it, add PRAGMA EXCEPTION_INIT(e_stock_low, -20020); (or another number from -20999 to -20000) directly after the declaration in the specification. The client then sees ORA-20020, and callers can still handle it by name with WHEN pkg.e_stock_low.
Exercise
Why does SELECT shipping_api.c_max_weight_kg FROM dual; fail, and how would you make the value available to SQL?
Show answer
A package constant is a PL/SQL item, and plain SQL cannot reference it, so the statement fails with ORA-06553 (PLS-221). Add a function to the package, for example FUNCTION max_weight_kg RETURN NUMBER;, whose body returns c_max_weight_kg, and call the function from SQL instead.
Exercise
You change c_max_weight_kg from 30 to 40 in the specification and recompile it. Explain what happens to other objects that use the package, and name one change you could make in the body that would not have this effect.
Show answer
Objects that depend on the specification are invalidated, because they were compiled against the old specification. Oracle revalidates them on next use or when they are recompiled. A change that touches only the body, such as fixing the logic inside total_weight, leaves the specification unchanged and does not invalidate dependents.