Sub topic 2
Writing the package specification
The package specification is the part of a package that other code can see. This chapter covers what belongs in it, the syntax rules, how Oracle compiles and stores it, and how to check what it exposes. It assumes you can write standalone procedures and functions, use %TYPE, and handle exceptions. It also assumes you have the HR sample schema or an equivalent employees table. The body, private elements and state get their own chapters.
What the specification is
The specification (often called the spec) is the contract of a package. It lists the items that callers may use and says nothing about how they work. Oracle stores it as its own schema object of type PACKAGE. The body is a separate object of type PACKAGE BODY with the same name.
A spec can contain:
- Subprogram declarations: the name, parameters and return type, but no implementation.
- Constants and variables.
- Type and subtype declarations.
- Exception declarations, with an optional
PRAGMA EXCEPTION_INIT. - Cursor declarations.
- Pragmas such as
SERIALLY_REUSABLE.
A spec cannot contain executable statements. There is no BEGIN section in a spec, and a subprogram declared there has no IS ... BEGIN ... END. If you write one, the compiler rejects the spec.
Basic syntax
A specification has this shape:
CREATE [OR REPLACE] PACKAGE package_name [AUTHID CURRENT_USER | DEFINER] AS
-- declarations only
END [package_name];
/IS and AS mean the same thing here. The closing name after END is optional, but writing it makes long specs easier to read and lets the compiler catch a mismatched name. The / on its own line tells SQL*Plus, SQLcl and similar clients to send the block to the database. Without it, the client waits for more input.
Here is a complete specification for an employee API. It is the example this tutorial builds on.
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;
/Each part has a job:
c_max_raise_pctis a constant. Callers can read it asemp_api.c_max_raise_pct, and nobody can change it.e_raise_too_largeis a named exception. The pragma ties it to error number -20001, soWHEN emp_api.e_raise_too_largecatches anORA-20001raised by the package.get_salaryandraise_salaryare declarations that end in a semicolon right after the signature. Their implementations live in the body.
Parameter declarations
A subprogram declaration in a spec uses the same parameter syntax as a standalone subprogram, with one difference. A parameter cannot carry a size constraint. You can write p_name IN VARCHAR2, but not p_name IN VARCHAR2(30). To get a size, anchor the parameter with %TYPE or use a named subtype.
Anchoring with %TYPE has a side effect. The spec now depends on the employees table, so changing the column definition can invalidate the spec. That is usually what you want, because the parameter then follows the column, but it is a dependency.
Parameter modes and defaults work as in standalone code:
CREATE OR REPLACE PACKAGE dept_api AS
FUNCTION dept_name(p_department_id IN departments.department_id%TYPE)
RETURN departments.department_name%TYPE;
PROCEDURE rename_dept(
p_department_id IN departments.department_id%TYPE,
p_new_name IN departments.department_name%TYPE,
p_log IN BOOLEAN DEFAULT FALSE);
END dept_api;
/A caller can leave out p_log or pass it by name: dept_api.rename_dept(p_department_id => 10, p_new_name => 'Admin', p_log => TRUE). The default value belongs to the spec. If you change a default, callers that omit the argument change behavior without being recompiled, so treat defaults as part of the contract.
The spec must repeat exactly in the body
When you write the body, each subprogram that the spec declares must appear there with a matching signature. Oracle compares parameter names, modes, datatypes and the return type. The compiler does not reconcile a mismatch. You get an error such as PLS-00323: subprogram or cursor is declared in a package specification and must be defined in the package body. Because of this, keep the specification the authoritative copy and copy signatures from it, not the other way around.
Declaration order
PL/SQL requires an identifier to be declared before you use it. This applies inside a spec too. A constant that is used as a default value, in another constant's expression, or in a type definition must appear above that use.
CREATE OR REPLACE PACKAGE limits AS
c_base_limit CONSTANT PLS_INTEGER := 100;
c_double_limit CONSTANT PLS_INTEGER := c_base_limit * 2;
END limits;
/If you swap the two constants, the compiler reports PLS-00320 or PLS-00201 (identifier must be declared). Check the errors with SHOW ERRORS in SQL*Plus or SQLcl, or query USER_ERRORS.
A specification without a body
A body is required only when the spec declares something that needs an implementation. That means a subprogram, or a cursor declared with a RETURN clause. A spec that holds only constants, types, variables and exceptions needs no body. This is a common pattern for shared constants.
CREATE OR REPLACE PACKAGE app_constants AS
c_status_active CONSTANT VARCHAR2(10) := 'ACTIVE';
c_status_closed CONSTANT VARCHAR2(10) := 'CLOSED';
END app_constants;
/
SET SERVEROUTPUT ON
BEGIN
DBMS_OUTPUT.PUT_LINE(app_constants.c_status_active);
END;
/The block prints ACTIVE. In contrast, if you create dept_api above and call dept_api.dept_name(10) before creating a body, the call fails with ORA-04067: not executed, package body "HR.DEPT_API" does not exist. The spec compiles on its own. The error only appears when something tries to run code that is not there yet.
Compiling and what Oracle stores
Running CREATE OR REPLACE PACKAGE compiles the spec and stores both the source text and the compiled form. You can see them in the data dictionary. These queries use the USER_ views, which show only your own schema's objects.
SELECT object_name, object_type, status
FROM user_objects
WHERE object_name = 'EMP_API'
ORDER BY object_type;
SELECT text
FROM user_source
WHERE name = 'EMP_API'
AND type = 'PACKAGE'
ORDER BY line;
SELECT object_name, argument_name, in_out, data_type
FROM user_arguments
WHERE package_name = 'EMP_API'
ORDER BY object_name, position;The first query shows one row for the spec and, once it exists, one for the body. STATUS is VALID or INVALID. The second returns the specification text. The third lists every public subprogram and its parameters. Private subprograms never appear in USER_ARGUMENTS because they are not in the spec.
In SQL*Plus and SQLcl you can also run DESCRIBE emp_api. It reads the spec and prints the same public interface in a compact form.
Name rules and privileges
A package shares a namespace with tables, views, procedures and other objects in the schema. You cannot create a package called employees in a schema that already has a table with that name. Spec and body must share one name, because Oracle pairs them by it.
Privileges apply to the package as a whole. You do not grant on individual subprograms:
GRANT EXECUTE ON emp_api TO hr_reader;After this grant, hr_reader can call every public subprogram and read every public constant. That is one reason to keep the spec small. Anything you put in it is available to everyone who holds EXECUTE.
Choosing what goes in the spec
Put an item in the spec only if callers need it. Some guidance:
- Declare subprograms that form your API. Leave helper routines for the body.
- Use public constants for values callers must share, such as limits or status codes.
- Declare exceptions in the spec, not the body, so callers can name them in a
WHENclause. - Avoid public variables. Any caller can change them, which makes bugs harder to trace. Expose a getter and setter function if you need controlled access.
- Write a short comment above each subprogram describing what it does, what it raises, and what its parameters mean. Callers read the spec, not the body.
Common errors at a glance
| Symptom | Likely cause |
|---|---|
| `PLS-00103` while compiling a spec | An implementation or executable statement in the spec |
| `PLS-00323` while compiling the body | The spec declares a subprogram the body does not define |
| `PLS-00201: identifier must be declared` | Use before declaration, or a missing privilege on a referenced table |
| `ORA-04067` at run time | The spec exists but the body does not |
| `ORA-06508` at run time | The body is missing or invalid when the call happens |
Exercise
A colleague adds p_name IN VARCHAR2(30) to a procedure declaration in a package spec, and the spec fails to compile. Why does it fail, and how can you give the parameter an effective length?
Show answer
PL/SQL does not allow a size constraint on a formal parameter's datatype. The parameter accepts whatever length the caller passes. To tie it to a length, anchor it with %TYPE (for example employees.last_name%TYPE) or use a named subtype that has the length.
Exercise
You create CREATE OR REPLACE PACKAGE shop_api AS FUNCTION total(p_order_id IN NUMBER) RETURN NUMBER; END shop_api; and no body. The spec compiles with status VALID. What happens when you run SELECT shop_api.total(1) FROM dual, and what fixes it?
Show answer
The call fails at run time with ORA-04067: not executed, package body "SHOP_API" does not exist. The spec alone is valid, but the function has no implementation. Create a PACKAGE BODY shop_api that defines total with a matching signature.