Sub topic 1
What a package is and why you use one
Prerequisites
This chapter assumes you already know the following:
- Basic SQL:
SELECT,INSERTandUPDATE. - PL/SQL anonymous blocks, variables and control flow.
- How to create standalone stored procedures and functions.
- The basics of exception handling in PL/SQL.
You also need access to an Oracle schema with the employees table, such as the HR sample schema, and a tool that can run PL/SQL, such as SQL*Plus, SQL Developer or SQLcl.
What a package is
A package is a schema object that groups related PL/SQL items under one name. The items can be procedures, functions, constants, variables, types, cursors and exceptions. You store the package in the database, like a table or a view. You call its contents through the package name.
A package has two parts:
- The specification (spec) declares the public interface. It lists what callers are allowed to use. It holds no implementation code for subprograms.
- The body holds the implementation. It contains the code for every subprogram the spec declares. It can also hold private items that exist only inside the body.
The two parts are stored as separate objects. They are created with separate statements, CREATE PACKAGE and CREATE PACKAGE BODY.
A first example
The next two statements create a small package named emp_api. The spec declares a constant, a named exception and two subprograms.
CREATE OR REPLACE PACKAGE emp_api AS
c_max_raise_pct CONSTANT NUMBER := 20;
e_raise_too_large EXCEPTION;
PRAGMA EXCEPTION_INIT(e_raise_too_large, -20001);
FUNCTION get_salary(p_employee_id IN employees.employee_id%TYPE)
RETURN employees.salary%TYPE;
PROCEDURE raise_salary(
p_employee_id IN employees.employee_id%TYPE,
p_pct IN NUMBER);
END emp_api;
/The body implements both subprograms. It also adds a private helper, is_valid_pct, which is not in the spec.
CREATE OR REPLACE PACKAGE BODY emp_api AS
-- Private: not declared in the specification, so callers cannot see it.
FUNCTION is_valid_pct(p_pct IN NUMBER) RETURN BOOLEAN IS
BEGIN
RETURN p_pct > 0 AND p_pct <= c_max_raise_pct;
END is_valid_pct;
FUNCTION get_salary(p_employee_id IN employees.employee_id%TYPE)
RETURN employees.salary%TYPE IS
l_salary employees.salary%TYPE;
BEGIN
SELECT salary INTO l_salary
FROM employees
WHERE employee_id = p_employee_id;
RETURN l_salary;
END get_salary;
PROCEDURE raise_salary(
p_employee_id IN employees.employee_id%TYPE,
p_pct IN NUMBER) IS
BEGIN
IF NOT is_valid_pct(p_pct) THEN
RAISE e_raise_too_large;
END IF;
UPDATE employees
SET salary = salary * (1 + p_pct / 100)
WHERE employee_id = p_employee_id;
END raise_salary;
END emp_api;
/Callers use dot notation: package_name.item_name. They can reach everything the spec declares, which here is the constant, the exception and both subprograms.
BEGIN
emp_api.raise_salary(100, 10);
DBMS_OUTPUT.PUT_LINE('New salary: ' || emp_api.get_salary(100));
EXCEPTION
WHEN emp_api.e_raise_too_large THEN
DBMS_OUTPUT.PUT_LINE('Raise exceeds ' || emp_api.c_max_raise_pct || '%');
END;
/Run with SET SERVEROUTPUT ON to see the output. If you call emp_api.is_valid_pct(10) from outside the package, the compiler rejects it. The compiler reports PLS-00302: component 'IS_VALID_PCT' must be declared, because the spec does not declare that name.
Why use a package instead of standalone subprograms
You can write the same logic as separate standalone procedures and functions. Packages give you several things that standalone subprograms do not.
Encapsulation
The spec is a contract. Everything not in the spec is private. You can restructure private code freely, and callers cannot depend on it. In emp_api, the rule for a valid raise lives in is_valid_pct. If the rule changes, you edit one private function and no caller needs to change.
Organization and naming
Related code lives under one name. Instead of get_salary, raise_salary, terminate_employee and transfer_employee as loose objects in the schema, you have one emp_api object. Your schema listing stays short, and a developer finds related code in one place. Names inside a package also cannot collide with other schema objects.
Shared declarations
Constants, types and exceptions declared in the spec are shared by every caller. A caller can write WHEN emp_api.e_raise_too_large without redefining the exception or its error number. This keeps magic numbers and duplicated type definitions out of your code.
Overloading
A package can hold several subprograms with the same name and different parameter lists. A later chapter covers this. Standalone subprograms cannot be overloaded.
Session state
Variables declared at package level keep their values for the life of a database session. Standalone subprograms start fresh on every call. Packages let you cache values or keep counters between calls. A later chapter covers the rules and the risks.
Fewer invalidation problems
Callers depend on the spec, not the body. If you change only the body, code that calls the package usually does not need to be recompiled. With standalone subprograms, a change to one procedure's definition can invalidate everything that calls it. A later chapter covers dependencies in detail.
Loading behavior
When any item in a package is first used in a session, Oracle loads the whole package into memory. Later calls to other items in the same package do not need another load. This is a minor benefit compared with the design advantages above.
Standalone subprograms and packages compared
| Aspect | Standalone subprogram | Package |
|---|---|---|
| Stored as | One schema object per subprogram | One spec object and one body object |
| Hidden helpers | Not possible | Private items in the body |
| Overloading | Not allowed | Allowed |
| Shared constants, types, exceptions | Not available | Declared in the spec |
| State kept between calls | None | Package-level variables, per session |
| Effect of changing the implementation | Dependents may be invalidated | Body-only change usually leaves dependents valid |
| Call syntax | `proc_name(args)` | `pkg_name.proc_name(args)` |
Specification and body are separate objects
Because the spec and the body are different objects, they have different states. You can see this in the data dictionary:
SELECT object_name, object_type, status
FROM user_objects
WHERE object_name = 'EMP_API'
ORDER BY object_type;You get two rows: one with PACKAGE and one with PACKAGE BODY. Each has its own STATUS, which is VALID or INVALID. If the body has a compile error, the spec can still be valid.
You can create a spec without a body. If the spec declares only constants, types and exceptions, no body is needed, because nothing needs an implementation. If the spec declares a subprogram, the body must implement it. If you create the spec and then call a subprogram before creating the body, the call fails at run time with ORA-04068 or ORA-06508, because the body cannot be found.
To see compile errors, use SHOW ERRORS in SQL*Plus or SQLcl, or query the dictionary:
SELECT line, position, text
FROM user_errors
WHERE name = 'EMP_API'
AND type = 'PACKAGE BODY'
ORDER BY sequence;Rules that the body must follow
The compiler checks the body against the spec. When you write the body, keep these rules in mind:
- Every subprogram in the spec must appear in the body.
- The header in the body must match the header in the spec. The names, the parameter names, the modes (
IN,OUT,IN OUT), the datatypes and the return type must be the same. Default values are written only in the spec. - Items declared in the spec must not be declared again in the body. Redeclaring a constant in the body creates a second, private item, which causes confusion.
- Private subprograms in the body must be declared before they are used, or you must write a forward declaration. A later chapter explains this.
If a header differs, you get PLS-00323: subprogram or cursor is declared in a package specification and must be defined in the package body.
Replacing a package
CREATE OR REPLACE PACKAGE replaces the spec. Oracle then marks the body and every dependent object as invalid. The body must be compiled again. CREATE OR REPLACE PACKAGE BODY replaces only the body, and normally leaves dependents valid. Keep this in mind when you deploy, because changing the spec is the more disruptive step.
To compile again without changing the source, use:
ALTER PACKAGE emp_api COMPILE;
ALTER PACKAGE emp_api COMPILE BODY;The first statement compiles both the spec and the body. The second compiles only the body.
Common mistakes
- Putting the
/terminator on the same line as code. In SQL*Plus and SQLcl, the/must be alone on its own line to run the statement. - Forgetting the closing name.
END emp_api;is optional but helps you match blocks in long packages. - Calling a subprogram without the package prefix from outside the package. Inside the package, you can call an item by its plain name. Outside, you must write
emp_api.get_salary. - Granting access to the wrong thing. You grant
EXECUTEon the package as a whole, not on individual subprograms. A user who can run one public subprogram can run all of them. - Putting everything in the spec. Declare in the spec only what callers must use. Anything else belongs in the body.
What the rest of this tutorial covers
This chapter introduced the idea. The next chapters go through the spec, public items, the body, visibility, forward declarations, overloading, state, the initialization section, dependencies, invoker rights, SERIALLY_REUSABLE packages and design practices.
Exercise
A package spec declares PROCEDURE log_msg(p_text IN VARCHAR2);. In the body, you write PROCEDURE log_msg(p_message IN VARCHAR2) IS .... Will the body compile, and why?
Show answer
No. The header in the body must match the spec, including parameter names. Here p_text and p_message differ, so the compiler raises PLS-00323. Rename the body parameter to p_text.
Exercise
You change only the code inside one subprogram in the package body, and then run CREATE OR REPLACE PACKAGE BODY. The spec does not change. Why are the other schema objects that call the package usually still valid afterwards?
Show answer
Callers depend on the spec, which has not changed. Replacing only the body leaves the public interface the same, so dependent objects stay valid. Replacing the spec would invalidate them.
Exercise
Give two reasons to put a validation function such as is_valid_pct in the body only and not in the spec.
Show answer
First, callers cannot depend on it, so you can change or remove it without breaking them. Second, it keeps the public interface small and clear. The spec lists only what callers should use.