Sub topic 12
Organizing subprograms in packages and overloading them
This chapter assumes you can already write standalone procedures and functions with CREATE OR REPLACE, use IN, OUT and IN OUT parameters, and read compilation errors from USER_ERRORS. It builds on those skills by grouping subprograms into packages, then reusing one name for several subprograms with overloading.
Why use packages
A standalone procedure or function is one object in the schema. A package groups related subprograms, constants, types and variables under one name. It has two parts:
- The specification (spec) is the public interface. It lists what callers may use.
- The body holds the implementation. It can also contain private subprograms and variables that callers cannot see.
Packages give you four things standalone subprograms do not:
- Encapsulation. Callers depend only on the spec, so you can change the body freely.
- Fewer dependency invalidations. Dependent code is tied to the spec, not the body (see below).
- Session state. Package-level variables keep their values for the life of a session.
- Overloading. Only subprograms in a package, or declared locally inside a block, can share a name.
A package with public and private parts
The spec below exposes one procedure, one function and one constant. Callers see only these.
CREATE OR REPLACE PACKAGE emp_api AS
c_max_percent CONSTANT NUMBER := 50;
PROCEDURE raise_salary (
p_employee_id IN employees.employee_id%TYPE,
p_percent IN NUMBER DEFAULT 10
);
FUNCTION get_name (
p_employee_id IN employees.employee_id%TYPE
) RETURN VARCHAR2;
END emp_api;
/The body implements them. It also defines a private function, employee_exists, and a private counter, g_calls.
CREATE OR REPLACE PACKAGE BODY emp_api AS
g_calls PLS_INTEGER; -- private state, one copy per session
FUNCTION employee_exists (
p_employee_id IN employees.employee_id%TYPE
) RETURN BOOLEAN IS
v_dummy PLS_INTEGER;
BEGIN
SELECT 1 INTO v_dummy
FROM employees
WHERE employee_id = p_employee_id;
RETURN TRUE;
EXCEPTION
WHEN NO_DATA_FOUND THEN
RETURN FALSE;
END employee_exists;
PROCEDURE raise_salary (
p_employee_id IN employees.employee_id%TYPE,
p_percent IN NUMBER DEFAULT 10
) IS
BEGIN
IF p_percent > c_max_percent THEN
RAISE_APPLICATION_ERROR(-20002, 'Percent too large: ' || p_percent);
END IF;
IF NOT employee_exists(p_employee_id) THEN
RAISE_APPLICATION_ERROR(-20001, 'Employee not found: ' || p_employee_id);
END IF;
UPDATE employees
SET salary = salary * (1 + p_percent / 100)
WHERE employee_id = p_employee_id;
g_calls := g_calls + 1;
END raise_salary;
FUNCTION get_name (
p_employee_id IN employees.employee_id%TYPE
) RETURN VARCHAR2 IS
v_name VARCHAR2(100);
BEGIN
SELECT first_name || ' ' || last_name
INTO v_name
FROM employees
WHERE employee_id = p_employee_id;
RETURN v_name;
EXCEPTION
WHEN NO_DATA_FOUND THEN
RETURN NULL;
END get_name;
BEGIN
g_calls := 0; -- initialization section
END emp_api;
/Callers use dot notation, and the same notations you already know apply:
BEGIN
emp_api.raise_salary(p_employee_id => 100, p_percent => 5);
DBMS_OUTPUT.PUT_LINE(emp_api.get_name(100));
END;
/Calling emp_api.employee_exists(100) from outside fails with PLS-00302: component 'EMPLOYEE_EXISTS' must be declared, because the spec does not list it.
Rules that cause common errors
- A subprogram declared in the spec must appear in the body with a matching header. Parameter names, modes, types and return type must all match. A mismatch gives
PLS-00323orPLS-00328, and the body is created with errors. - Private subprograms must be declared before they are used in the body. Either define them earlier in the body, as above, or add a forward declaration (the header followed by
;). - The spec and body are separate objects. Query
USER_OBJECTSand you see both:
SELECT object_name, object_type, status
FROM user_objects
WHERE object_name = 'EMP_API'
ORDER BY object_type;- Check
USER_ERRORSwithTYPE = 'PACKAGE BODY'to see body errors. The spec has its ownTYPE = 'PACKAGE'. - The initialization section (the final
BEGIN ... END) runs once per session, the first time anything in the package is referenced. Keep it short, and do not put code in it that can fail often.
Package state and its cost
Package variables live in the session's memory. Two sessions each get their own copy of g_calls. This is useful for caches and counters, but it has a cost. If you recompile the body while a session has instantiated the package, that session's next call fails with ORA-04068: existing state of packages has been discarded. A second call then works, because the package is re-initialized. Packages that have no variables, cursors or other state avoid this problem. You can also declare PRAGMA SERIALLY_REUSABLE to avoid keeping state across calls, but the state then resets after every top-level call.
Packages and dependencies
Code that calls emp_api.get_name depends on the package spec. So:
- Recompiling only the body normally leaves dependents valid, because the public interface did not change.
- Changing the spec can invalidate dependents. Since Oracle Database 11g, dependency tracking is fine-grained, so adding an unrelated function usually does not invalidate callers of other functions. Do not rely on this for overloaded names, because a new overload can change which subprogram an existing call resolves to.
- Invalid objects are recompiled automatically on next use. You can also compile them on purpose with
ALTER PACKAGE emp_api COMPILE BODY;.
This is the main practical argument for packages in large systems: the spec is stable, and the body changes often.
Overloading
Overloading means two or more subprograms in the same scope with the same name but different parameter lists. The compiler picks one at compile time by matching the actual parameters in the call.
The package from the topic plan shows this. Both functions are named to_label, one takes NUMBER and the other takes DATE.
CREATE OR REPLACE PACKAGE fmt AS
FUNCTION to_label (p_value IN NUMBER) RETURN VARCHAR2;
FUNCTION to_label (p_value IN DATE) RETURN VARCHAR2;
END fmt;
/
CREATE OR REPLACE PACKAGE BODY fmt AS
FUNCTION to_label (p_value IN NUMBER) RETURN VARCHAR2 IS
BEGIN
RETURN TO_CHAR(p_value, 'FM999G999G990D00');
END to_label;
FUNCTION to_label (p_value IN DATE) RETURN VARCHAR2 IS
BEGIN
RETURN TO_CHAR(p_value, 'YYYY-MM-DD');
END to_label;
END fmt;
/Each call picks its version from the argument type:
BEGIN
DBMS_OUTPUT.PUT_LINE(fmt.to_label(1234.5)); -- NUMBER version
DBMS_OUTPUT.PUT_LINE(fmt.to_label(SYSDATE)); -- DATE version
END;
/What makes two overloads distinct
| Difference | Allowed as the only difference? |
|---|---|
| Number of parameters | Yes |
| Data type family of a parameter (for example NUMBER versus DATE) | Yes |
| Parameter names, when callers use named notation | Yes, but only if the calls can still be resolved |
| Parameter mode (IN versus OUT) | No |
| Return type of a function | No |
| Subtypes of the same family (for example NUMBER and INTEGER, or CHAR and VARCHAR2) | No |
The compiler checks these rules when it resolves a call, not when it compiles the spec. A spec that breaks them may compile, and the first ambiguous call then fails.
Ambiguous calls
If the compiler cannot choose one overload, the call fails with PLS-00307: too many declarations of 'TO_LABEL' match this call. A bare NULL is a typical cause, because it matches every parameter type:
BEGIN
DBMS_OUTPUT.PUT_LINE(fmt.to_label(NULL)); -- PLS-00307
END;
/Fix it by giving the value a type, for example fmt.to_label(CAST(NULL AS NUMBER)). String literals can fail the same way when implicit conversion to more than one parameter type is possible, so pass the correct type explicitly.
Defaults and named notation make this worse. If one overload is (a NUMBER) and another is (a NUMBER, b NUMBER DEFAULT 0), then f(1) matches both. Avoid overloads whose calls can overlap through default values.
When to use packages
- Group subprograms that serve one area, such as
emp_apifor employee operations. - Put constants, exceptions and types that several subprograms share in the spec.
- Keep helper code private in the body.
- Prefer overloading for type or arity variants of one operation, as with
to_label. - Avoid package variables for data that must be consistent across sessions. Use a table instead.
Exercise
A package spec declares FUNCTION area (p_side IN NUMBER) RETURN NUMBER; and FUNCTION area (p_side IN INTEGER) RETURN NUMBER;. Why is this a problem, and how would you fix it so callers can pass a square's side or a circle's radius?
Show answer
NUMBER and INTEGER belong to the same type family, so a call such as area(3) cannot be resolved to one overload, and it fails with PLS-00307. Overloads must differ in number of parameters or in type family. Give them different names, such as square_area and circle_area, or add a differing parameter such as a shape-code VARCHAR2.
Exercise
You change only the body of emp_api and recompile it. Procedures that call emp_api.get_name stay valid, but a user's open session gets ORA-04068 on its next call. Why?
Show answer
Dependents are tied to the spec, which did not change, so they stay valid. The open session had instantiated the package and held its state in memory. Recompiling the body discards that state, so the session's next call raises ORA-04068. The package re-initializes on the call after that.