1. Introduction to Oracle Packages
- Packages group related PL/SQL objects into a single unit.
- Provide modular programming for better code organization.
- Support encapsulation and information hiding.
- Allow code reusability across applications.
- Improve performance by loading once into memory.
2. Benefits of Using Packages
- Modular design reduces code duplication.
- Encapsulation protects data and internal logic.
- Improves performance due to session-level caching.
- Simplifies maintenance and debugging.
- Enables overloading of procedures and functions.
3. Package Structure Overview
- Consists of Package Specification and Package Body.
- Specification declares public components.
- Body contains implementation of procedures/functions.
- Body can include private objects hidden from users.
- Optional initialization section executes when first called.
4. Package Specification
- Declares public procedures, functions, variables, constants, cursors.
- Acts as the interface for other PL/SQL blocks.
- Hides the implementation details from users.
- Cannot contain executable code except constants/defaults.
- Essential for compiling dependent PL/SQL objects.
5. Package Body
- Implements all procedures/functions declared in spec.
- Can contain private procedures, functions, variables, constants.
- Can have an initialization section executed once per session.
- Provides the logic for package operations.
- Body must exist for package usability if spec has procedures/functions.
6. Creating Packages
- Use CREATE PACKAGE for spec and CREATE PACKAGE BODY for body.
- Define public objects in the spec.
- Implement functionality in the body.
- Compile packages using SQL*Plus or SQL Developer.
- Packages can depend on tables, views, or other objects.
7. Replacing and Dropping Packages
- CREATE OR REPLACE PACKAGE updates an existing package.
- DROP PACKAGE deletes spec and body together.
- Dropping invalidates dependent objects.
- Replacement preserves dependent objects if spec signature unchanged.
- Use carefully in production to avoid breaking code.
8. Public vs Private Components
- Public components declared in spec.
- Private components declared in body.
- Public components accessible outside package.
- Private components hidden for encapsulation.
- Separates interface from implementation.
9. Variables in Packages
- Can be public (spec) or private (body).
- Persist for session duration.
- Store temporary values across procedure calls.
- Useful for counters, flags, caching data.
- Initialized once per session unless changed.
10. Constants in Packages
- Declared with CONSTANT in spec or body.
- Value cannot change during session.
- Useful for fixed values like tax rates.
- Improves readability and maintainability.
- Can be public or private.
11. Cursors in Packages
- Public cursors declared in spec for reuse.
- Private cursors defined in body.
- Supports queries returning multiple rows.
- Can use parameters to make cursors flexible.
- Improve performance by avoiding repeated SQL compilation.
12. Procedures in Packages
- Stored in body, declared in spec.
- Can be public or private.
- Perform actions but do not return values directly.
- Can call other procedures/functions inside package.
- Supports modular and reusable code.
13. Functions in Packages
- Return a single value, usable in SQL/PLSQL.
- Declared in spec, implemented in body.
- Can be public or private.
- Can be overloaded with different parameter lists.
- Useful for calculations or derived data.
14. Overloading in Packages
- Same procedure/function name, different parameters.
- Declared in package spec.
- Increases code readability and flexibility.
- Oracle determines correct method at runtime.
- Applies to procedures and functions.
15. Package Initialization Section
- Optional block at end of package body.
- Executes once per session, first time package referenced.
- Used to initialize variables or set environment.
- Maintains package state across calls.
- Cannot accept parameters or return values.
16. Statefulness of Packages
- Package variables retain values for session.
- Track counters, user context, temporary data.
- Each user session has its own copy.
- Reduces repeated queries or recalculations.
- Can lead to memory issues if not managed.
17. Package Variables and Session Scope
- Persist for duration of user session.
- Can be public or private.
- Initialized once on first reference.
- Useful for caching frequently accessed data.
- Changes in one session do not affect others.
18. Using Packages in SQL and PL/SQL
- Public functions can be called in SQL statements.
- Procedures/functions called in PL/SQL blocks.
- Reduces code repetition in applications.
- Encapsulates business logic for reuse.
- Can improve SQL performance when using packaged functions.
19. Calling Packaged Procedures
- Syntax: package_name.procedure_name(parameters);
- Can call public procedures/functions.
- Supports input and output parameters.
- Reduces standalone procedure calls.
- Improves modularity and maintainability.
20. Calling Packaged Functions
- Syntax: variable := package_name.function_name(parameters);
- Can be used in PL/SQL expressions.
- Public functions usable in SQL queries.
- Supports returning values of any type.
- Encourages reusable business logic.
21. Exception Handling in Packages
- Use EXCEPTION block in procedures/functions.
- Handles runtime errors gracefully.
- Can define user-friendly error messages.
- Supports logging and debugging.
- Prevents abrupt application termination.
22. User-Defined Exceptions in Packages
- Use EXCEPTION_INIT or RAISE_APPLICATION_ERROR.
- Define exceptions in spec or body.
- Enforces business rules.
- Improves clarity and maintainability.
- Can be handled locally or propagated.
23. Packages and Transactions
- Procedures can perform multiple SQL operations.
- Can commit or rollback transactions.
- Package state persists across multiple operations.
- Maintains consistency and integrity.
- Supports complex business logic with multiple steps.
24. Packages with Cursors and REF CURSORs
- REF CURSOR allows dynamic SQL and flexible queries.
- Can pass cursors between procedures/functions.
- Useful for returning result sets to applications.
- Supports strong and weak typing.
- Improves modularity and query reuse.
25. Packages with Collections
- Collections: VARRAY, Nested Tables, Associative Arrays.
- Can store multiple values in a single variable.
- Useful for bulk operations and caching.
- Can be passed between procedures/functions.
- Improves performance for batch processing.
26. Packages with RECORD Types
- RECORDs store related fields in a single variable.
- Can be used as procedure/function parameters.
- Helps model complex data structures.
- Can be nested in collections.
- Enhances readability and organization.
27. Performance Advantages of Packages
- Reduces parsing overhead by loading once.
- Session-level caching improves speed.
- Supports bulk operations with collections/cursors.
- Minimizes network round-trips.
- Modular design improves maintainability and performance.
28. Security and Privileges for Packages
- Grants applied to packages, not individual objects.
- Limits access to sensitive logic.
- Supports roles and user-based privileges.
- Protects underlying tables.
- Implements multi-tiered application security.
29. Definer Rights vs Invoker Rights in Packages
- Definer rights: execute with owner’s privileges.
- Invoker rights: execute with caller’s privileges.
- Default is definer rights.
- Affects access to objects in other schemas.
- Important for multi-user applications and security.
30. Recompiling Invalid Packages
- Packages become invalid when dependent objects change.
- Use ALTER PACKAGE … COMPILE to recompile.
- Invalid packages cannot be used until compiled.
- SQL Developer/SQL*Plus show invalid packages.
- Regular recompilation is part of maintenance.
31. Viewing Package Metadata
- ALL_OBJECTS, USER_OBJECTS, DBA_OBJECTS show package info.
- ALL_PROCEDURES shows procedures/functions.
- DBMS_METADATA.GET_DDL extracts DDL.
- Useful for auditing and versioning.
- Helps track dependencies and usage.
32. Debugging Packages
- Use DBMS_OUTPUT.PUT_LINE for output debugging.
- SQL Developer has step-through debugging tools.
- Check for invalid objects and compilation errors.
- Test multiple inputs to identify issues.
- Handle exceptions carefully for proper tracing.
33. Testing Package Components
- Unit test each procedure/function individually.
- Use test tables or mock data.
- Validate output against expected results.
- Test public and private components via public interface.
- Automate testing for repeated verification.
34. Dependency Management in Packages
- Packages depend on tables, views, other packages.
- Oracle tracks dependencies automatically.
- Changes in dependent objects can invalidate packages.
- Helps manage complex applications.
- Use ALL_DEPENDENCIES to view relationships.
35. Using Packages in Applications
- Encapsulates business logic for front-end apps.
- Reduces SQL code in application layer.
- Enhances maintainability and modularity.
- Provides reusable API for multiple apps.
- Improves security by restricting direct table access.
36. Package Versioning Strategies
- Maintain version numbers in header constants.
- Use DDL scripts with version control.
- Test backward compatibility before deployment.
- Keep historical scripts for rollback.
- Avoid breaking dependent applications.
37. Best Practices for Package Design
- Separate public interface from private implementation.
- Keep packages small and focused.
- Use meaningful names for procedures/functions/variables.
- Avoid unnecessary global variables.
- Document purpose, inputs, outputs, exceptions.
38. Common Package Pitfalls
- Overuse of package variables causing memory issues.
- Exposing sensitive internal logic publicly.
- Ignoring exception handling.
- Large packages with unrelated functionality.
- Not managing dependencies properly.
39. Packages vs Standalone Procedures
- Packages group related procedures; standalone are independent.
- Packages improve performance via session caching.
- Packages allow overloading; standalone do not.
- Packages support encapsulation; standalone are public.
- Packages are better for modular, reusable code.
40. Real-World Package Use Cases
- Banking: transaction management, account operations.
- E-commerce: order processing, inventory updates.
- HR systems: payroll calculations, employee data.
- Reporting tools: reusable data queries.
- ERP systems: centralized business logic for modules.
No comments:
Post a Comment