Sub topic 3
The initialization section
This chapter assumes you can write a package specification and body, declare package variables, and call standalone procedures.
The initialization section
A package body can end with a BEGIN ... END block. This block is the initialization section. Oracle runs it once per session, the first time that session references the package, so it can set up package state before any subprogram runs.
CREATE OR REPLACE PACKAGE call_counter AS
PROCEDURE hit;
FUNCTION hits RETURN PLS_INTEGER;
END call_counter;
/
CREATE OR REPLACE PACKAGE BODY call_counter AS
g_hits PLS_INTEGER;
PROCEDURE hit IS
BEGIN
g_hits := g_hits + 1;
END hit;
FUNCTION hits RETURN PLS_INTEGER IS
BEGIN
RETURN g_hits;
END hits;
BEGIN
g_hits := 0;
END call_counter;
/Without the initialization section, g_hits starts as NULL, and g_hits + 1 yields NULL.
Dependencies: why the body can change without breaking callers
Objects that call a package depend on its specification. Changing the body does not invalidate those callers, because the public interface stays the same. Changing the specification marks dependent objects invalid, and Oracle recompiles them on their next use.
Invoker-rights packages with AUTHID CURRENT_USER
By default, a package runs with its owner's privileges (definer rights). Adding AUTHID CURRENT_USER to the specification makes the package run with the caller's privileges and name resolution instead.
CREATE OR REPLACE PACKAGE emp_api AUTHID CURRENT_USER AS
FUNCTION get_salary(p_employee_id IN employees.employee_id%TYPE)
RETURN employees.salary%TYPE;
END emp_api;
/Use this when one schema hosts shared code that should act on each caller's own tables.
SERIALLY_REUSABLE packages
PRAGMA SERIALLY_REUSABLE tells Oracle to reset package state at the end of each server call instead of keeping it for the whole session. The state lives in shared memory rather than per-session memory, which saves memory when many sessions use the package. Its trade-off is that a value set in one call does not survive to the next call.
Designing packages well
- Keep the specification small, and expose only what callers need.
- Put implementation details in the body, so you can change them without invalidating callers.
- Group related subprograms by purpose, such as one package per business area.
- Avoid public package variables. Use functions to read state so callers cannot change it directly.
Exercise
Exercise
A package body sets g_hits := 0 in its initialization section. A session calls hit three times, then ends. A new session calls hits. What does it return, and why?
Show answer
It returns 0. Package state is per session, so the new session runs the initialization section again and starts with g_hits set to 0.