Sub topic 10
Dependencies: why the body can change without breaking callers
This chapter assumes you can write a package specification and body, and that you can read a SELECT against a data dictionary view. It explains why you can replace a package body while the code that calls the package keeps working. It also shows what happens when you change the specification instead.
How Oracle records dependencies
Whenever you compile a stored object, Oracle records which other objects it references. These records are the dependencies. The compiler writes them to the data dictionary, and you can read them in USER_DEPENDENCIES.
A package has two parts, and they are separate objects with separate dependencies:
- The specification (object type
PACKAGE) depends on the types and tables its declarations mention, such asemployees.employee_id%TYPE. - The body (object type
PACKAGE BODY) depends on its own specification, and on every table, view and other package its code references. - A caller is a procedure, function, trigger, view or another package. It depends on the specification of the package it calls. It does not depend on the body.
That last point explains the chapter title. The caller was compiled against the declarations in the specification: names, parameter lists and datatypes. The body is only needed when the call runs.
Seeing it in the data dictionary
Create a small package and a caller:
CREATE OR REPLACE PACKAGE price_api AS
FUNCTION net_price(p_gross IN NUMBER) RETURN NUMBER;
END price_api;
/
CREATE OR REPLACE PACKAGE BODY price_api AS
FUNCTION net_price(p_gross IN NUMBER) RETURN NUMBER IS
BEGIN
RETURN p_gross / 1.20;
END net_price;
END price_api;
/
CREATE OR REPLACE PROCEDURE show_price IS
BEGIN
DBMS_OUTPUT.PUT_LINE(price_api.net_price(120));
END show_price;
/Now ask the dictionary what depends on what:
SELECT name, type, referenced_name, referenced_type
FROM user_dependencies
WHERE name IN ('PRICE_API', 'SHOW_PRICE')
AND referenced_owner = USER
ORDER BY name, type;You should get two rows:
| NAME | TYPE | REFERENCED_NAME | REFERENCED_TYPE |
|---|---|---|---|
| PRICE_API | PACKAGE BODY | PRICE_API | PACKAGE |
| SHOW_PRICE | PROCEDURE | PRICE_API | PACKAGE |
The referenced_owner = USER filter hides rows that point to SYS objects such as STANDARD and DBMS_OUTPUT. The body points at the specification. The procedure points at the specification. Nothing points at the body.
You can also check validity. Every stored object has a status of VALID or INVALID:
SELECT object_name, object_type, status
FROM user_objects
WHERE object_name IN ('PRICE_API', 'SHOW_PRICE')
ORDER BY object_name, object_type;At this point all three objects are VALID.
Changing the body
Replace the body with a different tax divisor:
CREATE OR REPLACE PACKAGE BODY price_api AS
FUNCTION net_price(p_gross IN NUMBER) RETURN NUMBER IS
BEGIN
RETURN p_gross / 1.25;
END net_price;
END price_api;
/Run the USER_OBJECTS query again. The body is VALID because it was just recompiled. SHOW_PRICE is still VALID, and nobody had to recompile it. When you run it, it calls the new code and prints 96.
This works because the caller depends only on the specification. The specification did not change, so the contract the caller was compiled against is intact. Oracle has no reason to invalidate anything that depends on it.
Compare this with a standalone function. It has no separate body, so any CREATE OR REPLACE changes the one object its callers depend on. Oracle marks those callers invalid and recompiles them on next use. Packages let you separate the contract from the implementation, so only a change to the contract invalidates callers.
Changing the specification
The specification is the contract, so changing it has consequences:
- The specification is recompiled.
- The body depends on the specification, so the body becomes
INVALID. - Callers may become
INVALID, depending on what changed.
Since Oracle Database 11g Release 1, dependency tracking is fine-grained. Oracle records which elements of the specification a dependent actually uses. It invalidates a dependent only when something it uses changed, or when a change could alter how its call resolves.
| Change to the specification | Package body | Callers |
|---|---|---|
| None, only the body is replaced | Valid after the replace | Stay valid |
| A new subprogram with a new name is added | Invalid until it is recompiled with an implementation | Normally stay valid |
| A new overload of an existing name is added | Invalid until recompiled | May be invalidated, because a call to that name could now resolve differently |
| A parameter or return datatype of a used subprogram changes | Invalid | Invalid, and recompiling fails if the call no longer fits |
| A subprogram that callers use is removed | Invalid | Invalid, and recompiling fails with a "must be declared" error |
The second row has a catch. If you add a function to the specification and do not add it to the body, the body will fail to compile. Try it:
CREATE OR REPLACE PACKAGE price_api AS
FUNCTION net_price(p_gross IN NUMBER) RETURN NUMBER;
FUNCTION vat_amount(p_gross IN NUMBER) RETURN NUMBER;
END price_api;
/The specification compiles, and PRICE_API (the specification) is VALID. The body is now INVALID. The next call to price_api.net_price makes Oracle try to recompile the body automatically. That attempt fails with PLS-00323: subprogram or cursor 'VAT_AMOUNT' is declared in a package specification and must be defined in its package body. The caller then gets an error such as ORA-04068 or ORA-06508, even though the code it calls is unchanged. Always deploy the new body immediately after a specification change.
Recompilation: automatic and manual
An invalid object is not a permanent failure. When a session calls an invalid object, Oracle tries to recompile it, along with whatever it needs, and retries the call. If the compile succeeds, the caller never notices anything except a brief delay. If it fails, the caller gets an error.
Automatic recompilation at run time has costs. The first user to hit the invalid object pays for the compile. Compiling takes locks on the objects involved, so it can queue behind other sessions. For that reason, recompile deliberately after a deployment instead of leaving it to the first user.
You can compile the pieces of a package separately:
ALTER PACKAGE price_api COMPILE SPECIFICATION;
ALTER PACKAGE price_api COMPILE BODY;
ALTER PACKAGE price_api COMPILE; -- bothCOMPILE SPECIFICATION invalidates the body and the affected dependents. COMPILE BODY does not touch callers. When a compile fails, read the errors:
SELECT line, position, text
FROM user_errors
WHERE name = 'PRICE_API'
AND type = 'PACKAGE BODY'
ORDER BY sequence;In SQL*Plus or SQLcl, SHOW ERRORS PACKAGE BODY price_api prints the same information.
To recompile everything invalid in a schema after a release, use a utility:
BEGIN
DBMS_UTILITY.COMPILE_SCHEMA(schema => USER, compile_all => FALSE);
END;
/compile_all => FALSE compiles only invalid objects. UTL_RECOMP.RECOMP_SERIAL and RECOMP_PARALLEL do the same job, and the parallel version helps on large schemas.
Package state and recompiling the body
Replacing a body can still disturb sessions that are running. The previous chapter showed that package variables live for the session. When you recompile a body, the old values in sessions that already used the package are no longer valid for the new code. Those sessions get this error on their next call to the package:
ORA-04068: existing state of packages has been discardedThe call that raised the error did not run. Oracle has already discarded the old state, so calling again succeeds, and the initialization section runs again for that session. Code that holds a connection pool or a long-lived batch session must be ready to catch this error and retry once.
A package with no state, meaning no variables, cursors or constants declared in the body, does not raise this error. This is one more reason to keep state out of packages unless you need it.
Related errors
| Error | Meaning |
|---|---|
| `ORA-04067: not executed, package body does not exist` | The specification exists but no body was compiled |
| `PLS-00323` | The specification declares something the body does not define |
| `PLS-00302: component must be declared` | A caller names something the specification does not expose, for example a private helper |
| `ORA-04068` | The body was recompiled while this session held state |
| `ORA-06508: PL/SQL: could not find program unit being called` | The called unit is invalid and could not be recompiled |
Dependencies on other objects
The body also depends on the tables and other packages it uses. Changing a table the body reads, such as dropping a column, invalidates the body. The specification is unaffected unless its declarations mention that table through %TYPE or %ROWTYPE. Callers of the package then survive, because they depend on the specification.
Declaring %TYPE in the specification does tie the contract to the table. Altering the datatype of employees.salary invalidates the specification of emp_api, because its signatures mention employees.salary%TYPE. That makes the whole chain of callers invalid, though fine-grained tracking spares callers that do not use the affected elements. Prefer %TYPE in specifications when you want parameters to follow the column, and plain datatypes when you want the contract to stay fixed.
Practical rules from this
- Keep the specification small and stable. Put changing logic in the body.
- Deploy in order: specification, then body, then a check that nothing in
USER_OBJECTSis invalid. - Do not put a body-only helper in the specification just to share it. Every public name becomes a contract you cannot change freely.
- Avoid adding overloads to a specification that is already in use. They can change how existing calls resolve.
- Handle
ORA-04068in long-lived sessions.
Exercise
A package specification acct_api has the function balance(p_id NUMBER) RETURN NUMBER. You fix a rounding bug inside the body and run CREATE OR REPLACE PACKAGE BODY acct_api. A stored procedure nightly_close calls acct_api.balance. What status does nightly_close have afterwards, and why? Then you add a new function statement_text to the specification and do not touch the body. What is the status of the body, and what happens when nightly_close runs?
Show answer
nightly_close stays VALID after the body fix, because it depends on the specification, which did not change. After adding statement_text to the specification, the body becomes INVALID. When nightly_close runs, Oracle tries to recompile the body, and that fails with PLS-00323 because statement_text is declared but not defined. The caller therefore gets an error even though it does not use the new function. Fix it by adding statement_text to the body and recompiling.
Exercise
Write the query that lists everything in your schema that depends on the specification of price_api, showing the dependent's name and type.
Show answer
SELECT name, type FROM userdependencies WHERE referencedname = 'PRICEAPI' AND referencedtype = 'PACKAGE' AND referencedowner = USER ORDER BY name, type; The result includes the PACKAGE BODY of `priceapi itself and show_price`.