Sub topic 9
The initialization section
This chapter covers the optional block at the end of a package body that sets up package state. It assumes you can write a package specification and body, and that you know package variables keep their values for the length of a session. It also assumes you have read the earlier chapter on package state.
What the initialization section is
A package body can end with a BEGIN ... END block that sits after the last subprogram. This block is the initialization section. It is ordinary PL/SQL with no parameters, and you cannot call it by name.
CREATE OR REPLACE PACKAGE BODY some_pkg AS
-- declarations and subprograms ...
BEGIN
-- initialization section: statements run once per session
END some_pkg;
/Only a package body can have one. A package with no body has nowhere to put it. If a package has no setup to do, leave out the BEGIN entirely.
When it runs
Oracle runs the section when a session first references the package. A reference can be a call to a public subprogram, or a read or write of a public variable. The section runs once per session. It does not run at compile time, and it does not run when the package is created.
The order inside the first reference is:
- Oracle gives declared variables their default values. Variables in the specification are set first, then variables in the body.
- Oracle runs the initialization section.
- Oracle runs the subprogram you called.
The following example prints a message from the initialization section, so you can see when it runs.
CREATE OR REPLACE PACKAGE session_info AS
FUNCTION login_user RETURN VARCHAR2;
FUNCTION started_at RETURN TIMESTAMP;
END session_info;
/
CREATE OR REPLACE PACKAGE BODY session_info AS
g_login_user VARCHAR2(128);
g_started_at TIMESTAMP;
FUNCTION login_user RETURN VARCHAR2 IS
BEGIN
RETURN g_login_user;
END login_user;
FUNCTION started_at RETURN TIMESTAMP IS
BEGIN
RETURN g_started_at;
END started_at;
BEGIN
DBMS_OUTPUT.PUT_LINE('session_info: initializing');
g_login_user := SYS_CONTEXT('USERENV', 'SESSION_USER');
g_started_at := LOCALTIMESTAMP;
END session_info;
/Enable server output in your client, then run this block:
BEGIN
DBMS_OUTPUT.PUT_LINE('Before first call');
DBMS_OUTPUT.PUT_LINE(session_info.login_user);
DBMS_OUTPUT.PUT_LINE(session_info.login_user);
END;
/You see Before first call, then session_info: initializing, then your user name twice. The initialization message appears once, before the first value, and not again on the second call. If you run the block a second time in the same session, the message does not appear at all.
When the section runs again
Each session has its own copy of the package state, so each session runs the section once. Two users connected at the same moment each trigger their own run. Their values can differ, as g_started_at does above.
Three things make a session lose its state, so that the next reference runs the section again:
- Recompilation. If the package body is recompiled while your session holds state for it, your next call fails with
ORA-04068: existing state of packages has been discarded. The call after that works, and it runs the initialization section again. - An explicit reset.
DBMS_SESSION.RESET_PACKAGEdiscards the state of every package in the session.DBMS_SESSION.MODIFY_PACKAGE_STATE(DBMS_SESSION.REINITIALIZE)does the same job for the packages that need it. - A new session. Disconnecting and reconnecting starts from nothing.
With a connection pool, the "session" is the pooled database connection, not the application user. State set up for one user's request can still be there when another user's request borrows the connection. Do not store per-user data in package variables unless your code sets it at the start of every request.
Initial values: declaration or section?
A simple starting value belongs in the declaration. Use the initialization section when the value needs more than one statement, a query, or a call to a function that you cannot use in a declaration.
| Approach | Example | Best for |
|---|---|---|
| Default in declaration | `g_hits PLS_INTEGER := 0;` | Constants and fixed starting values |
| Initialization section | `g_started_at := LOCALTIMESTAMP;` | Several related values, queries, validation |
| Lazy initialization | A private `init` procedure and a flag | Costly setup that many sessions never need |
Assigning in the declaration is less code and easier to read. The call_counter package from the earlier chapter uses a section only to show the mechanism. Writing g_hits PLS_INTEGER := 0; would do the same job.
Example: loading a lookup table
A common use is to load a small, rarely changing table into a collection. Later lookups then read memory instead of running a query. The body below reuses its own refresh procedure from the initialization section. The table is departments from the HR sample schema.
CREATE OR REPLACE PACKAGE dept_cache AS
FUNCTION name_of(p_department_id IN departments.department_id%TYPE)
RETURN departments.department_name%TYPE;
PROCEDURE refresh;
END dept_cache;
/
CREATE OR REPLACE PACKAGE BODY dept_cache AS
TYPE t_names IS TABLE OF departments.department_name%TYPE
INDEX BY PLS_INTEGER;
g_names t_names;
PROCEDURE refresh IS
BEGIN
g_names.DELETE;
FOR r IN (SELECT department_id, department_name FROM departments) LOOP
g_names(r.department_id) := r.department_name;
END LOOP;
END refresh;
FUNCTION name_of(p_department_id IN departments.department_id%TYPE)
RETURN departments.department_name%TYPE IS
BEGIN
IF g_names.EXISTS(p_department_id) THEN
RETURN g_names(p_department_id);
END IF;
RETURN NULL;
END name_of;
BEGIN
refresh;
END dept_cache;
/The first call to dept_cache.name_of in a session pays for one query. Later calls cost a collection lookup. The initialization section calls refresh, which is declared above it in the body, so no forward declaration is needed.
The cache has a cost. It is a snapshot taken when the session first touched the package. If someone renames a department, a session that already loaded the cache keeps the old name until it calls dept_cache.refresh or loses its state. Cache only data that changes rarely, or give callers a way to refresh, as refresh does here.
Errors in the initialization section
The section can have its own EXCEPTION handler, placed before the final END:
BEGIN
refresh;
EXCEPTION
WHEN OTHERS THEN
g_names.DELETE;
RAISE;
END dept_cache;The handler covers only the statements in the section. An error in a variable declaration, such as g_x NUMBER := 1/0;, is raised before the section starts, so the handler cannot catch it.
If an error leaves the section unhandled, it reaches whoever made the first call. That caller sees an error stack that includes ORA-06512 lines naming the package body, and not only the subprogram they called. Failures that look like "my call to name_of failed with an unrelated error" often come from here.
Handle errors you can recover from inside the section. For example, set a safe default value and continue. Re-raise the ones you cannot recover from, after cleaning up, so the package never runs in a half-set-up state.
Lazy initialization
The section runs on the first reference of any kind, even a call that needs none of the setup. If setup is costly and many callers never need it, use a flag and a private procedure:
CREATE OR REPLACE PACKAGE BODY dept_cache AS
TYPE t_names IS TABLE OF departments.department_name%TYPE
INDEX BY PLS_INTEGER;
g_names t_names;
g_loaded BOOLEAN := FALSE;
PROCEDURE ensure_loaded IS
BEGIN
IF NOT g_loaded THEN
FOR r IN (SELECT department_id, department_name FROM departments) LOOP
g_names(r.department_id) := r.department_name;
END LOOP;
g_loaded := TRUE;
END IF;
END ensure_loaded;
PROCEDURE refresh IS
BEGIN
g_names.DELETE;
g_loaded := FALSE;
ensure_loaded;
END refresh;
FUNCTION name_of(p_department_id IN departments.department_id%TYPE)
RETURN departments.department_name%TYPE IS
BEGIN
ensure_loaded;
IF g_names.EXISTS(p_department_id) THEN
RETURN g_names(p_department_id);
END IF;
RETURN NULL;
END name_of;
END dept_cache;
/This version has no initialization section. Work happens only when a caller needs a name. The trade-off is that every public subprogram that reads the cache must call ensure_loaded, and forgetting one is a bug that shows up only on some call orders.
What to avoid
Other things to keep out of the section:
- Slow work. Every new session pays for it on first use. Large queries, network calls and file access make logins feel slow.
- Dependence on another package's section. If package A's section calls package B, and B's section calls A, you create a circular reference. Calling into a package from another package's section also makes the order of setup hard to predict.
- Per-user data. As noted above, pooled sessions can carry the values to the next user.
- Output that matters. The
DBMS_OUTPUTline insession_infois only for demonstration. Real code should not depend on messages printed during setup.
Related feature: SERIALLY_REUSABLE
A package marked with PRAGMA SERIALLY_REUSABLE in both the specification and body behaves differently. Its state lasts only for one server call, not for the session. Oracle runs the initialization section at the start of each server call that uses the package. That makes the section runs-per-call, not runs-per-session. The pragma saves memory in large systems with many sessions. It also means you cannot count on values surviving between calls, so most packages should not use it.
Exercise
A package body has a variable g_ready BOOLEAN := FALSE; and an initialization section that sets g_ready := TRUE;. A session calls one of its public functions three times. How many times does the section run, and what happens to it if another developer recompiles the package body between the second and third calls?
Show answer
The section runs once, before the first call's subprogram executes. The second call finds the package already initialized. After the recompilation, the third call raises ORA-04068 because the session's state was discarded. The next call after that works, and it runs the initialization section again, so g_ready is set from scratch.
Exercise
You need a package that stores a list of valid status codes read from a table that changes about once a month. The package is used by hundreds of sessions, and most of them never check status codes. Would you use an initialization section or lazy initialization? Name one drawback of your choice.
Show answer
Use lazy initialization with a private ensure_loaded procedure and a flag, because most sessions would never need the data and an initialization section would make every one of them run the query on first use of the package. The drawback is that each public subprogram that reads the list must remember to call ensure_loaded. Also, as with any session cache, a session keeps its loaded list until it calls a refresh procedure or loses its package state, so it may not see a monthly change until then.