Bullet Proof Your PL/SQL



Similar documents
Making the Most of Oracle PL/SQL Error Management Features

Error Management in Oracle PL/SQL

OPP ODTUG Kaleidoscope. An ODTUG SP* Oracle PL/SQL Programming Conference. WOW-Wide Open World, Wide Open Web!

6b Continuing Past Exceptions


ORACLE 9I / 10G / 11G / PL/SQL COURSE CONTENT

Handling Exceptions. Schedule: Timing Topic. 45 minutes Lecture 20 minutes Practice 65 minutes Total

Oracle PL/SQL Best Practices

Handling Exceptions. Copyright 2008, Oracle. All rights reserved.

Handling Exceptions. Schedule: Timing Topic 45 minutes Lecture 20 minutes Practice 65 minutes Total

Handling Exceptions. Copyright 2006, Oracle. All rights reserved. Oracle Database 10g: PL/SQL Fundamentals 8-1

Best Practices For PL/SQL Development in Oracle Application Express

Handling PL/SQL Errors

Review your answers, feedback, and question scores below. An asterisk (*) indicates a correct answer.

Review your answers, feedback, and question scores below. An asterisk (*) indicates a correct answer.

Triggers & Packages. {INSERT [OR] UPDATE [OR] DELETE}: This specifies the DML operation.

Oracle Database 10g: Program with PL/SQL

Oracle Database: Develop PL/SQL Program Units

Oracle 11g PL/SQL training

Handling PL/SQL Errors

Database Programming with PL/SQL: Learning Objectives

Oracle Database: SQL and PL/SQL Fundamentals NEW

Training Guide. PL/SQL for Beginners. Workbook

Oracle Database: SQL and PL/SQL Fundamentals

When an exception occur a message which explains its cause is received. PL/SQL Exception message consists of three parts.

Best Practices for Dynamic SQL

Oracle For Beginners Page : 1

Introduction to PL/SQL Programming

Topics Advanced PL/SQL, Integration with PROIV SuperLayer and use within Glovia

Oracle Database: SQL and PL/SQL Fundamentals

PL/SQL Coding Style Guidelines Introducing Error Handling, Tracing and Coding Standards. Author: Vishal Gupta

PL/SQL Practicum #2: Assertions, Exceptions and Module Stability

Oracle 10g PL/SQL Training

Duration Vendor Audience 5 Days Oracle End Users, Developers, Technical Consultants and Support Staff

PL/SQL Overview. Basic Structure and Syntax of PL/SQL

1 Copyright 2011, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 8

14 Triggers / Embedded SQL

Oracle Database: Program with PL/SQL

Oracle Database: Program with PL/SQL

An Introduction to PL/SQL. Mehdi Azarmi

The Sins of SQL Programming that send the DB to Upgrade Purgatory Abel Macias. 1 Copyright 2011, Oracle and/or its affiliates. All rights reserved.

Darshan Institute of Engineering & Technology PL_SQL

PL/SQL (Cont d) Let s start with the mail_order database, shown here:

Oracle Database 11g: Program with PL/SQL

Oracle Database: SQL and PL/SQL Fundamentals NEW

Oracle PL/SQL Programming

Oracle Database: Program with PL/SQL

1 Triggers. 2 PL/SQL Triggers

Duration Vendor Audience 5 Days Oracle Developers, Technical Consultants, Database Administrators and System Analysts

Nested Blocks and Variable Scope. Copyright 2007, Oracle. All rights reserved.

Oracle Forms Developer 10g: Build Internet Applications

Oracle Database: Program with PL/SQL

Automated Testing Options for PL/SQL Steven Feuerstein PL/SQL Evangelist, Quest Software

Oracle Database 12c: Introduction to SQL Ed 1.1

Presented by Martin Giffy D Souza Martin@ClariFit.com Blog: Web:

NEW AND IMPROVED: HACKING ORACLE FROM WEB. Sumit sid Siddharth 7Safe Limited UK

Oracle Database: Program with PL/SQL

Elena Baralis, Silvia Chiusano Politecnico di Torino. Pag. 1. Active database systems. Triggers. Triggers. Active database systems.

An Oracle White Paper June RESTful Web Services for the Oracle Database Cloud - Multitenant Edition

Fine Grained Auditing In Oracle 10G

UltraLog HSPI User s Guide

Getting Started with Oracle Data Miner 11g R2. Brendan Tierney

D61830GC30. MySQL for Developers. Summary. Introduction. Prerequisites. At Course completion After completing this course, students will be able to:

Creating PL/SQL Blocks. Copyright 2007, Oracle. All rights reserved.

STUDY OF PL/SQL BLOCK AIM: To Study about PL/SQL block.

Oracle Database Security

Oracle Database 11g: Advanced PL/SQL

SQL/PSM. Outline. Database Application Development Oracle PL/SQL. Why Stored Procedures? Stored Procedures PL/SQL. Embedded SQL Dynamic SQL

CS346: Database Programming.

How To Understand The Error Codes On A Crystal Reports Print Engine

Course Objectives. Database Applications. External applications. Course Objectives Interfacing. Mixing two worlds. Two approaches

Database programming 20/08/2015. DBprog news. Outline. Motivation for DB programming. Using SQL queries in a program. Using SQL queries in a program

Writing Control Structures

<Insert Picture Here> Edition-based redefinition: the key to online application upgrade

Virtual Private Database Features in Oracle 10g.

Fixing Common Problems in Data Storage - A Review

Course -Oracle 10g SQL (Exam Code IZ0-047) Session number Module Topics 1 Retrieving Data Using the SQL SELECT Statement

Instant SQL Programming

INFORMATION BROCHURE Certificate Course in Web Design Using PHP/MySQL

Oracle PL/SQL Language. CIS 331: Introduction to Database Systems

Efficient database auditing

Oracle Total Recall with Oracle Database 11g Release 2

1 Copyright 2011, Oracle and/or its affiliates. All rights reserved.

Oracle9i: Develop PL/SQL Program Units

Using Oracle Data Integrator with Essbase, Planning and the Rest of the Oracle EPM Products

1 Stored Procedures in PL/SQL 2 PL/SQL. 2.1 Variables. 2.2 PL/SQL Program Blocks

High-Performance Oracle: Proven Methods for Achieving Optimum Performance and Availability

TECHNOLOGY Computer Programming II Grade: 9-12 Standard 2: Technology and Society Interaction

SQL Databases Course. by Applied Technology Research Center. This course provides training for MySQL, Oracle, SQL Server and PostgreSQL databases.

Collaborative Forecasts Implementation Guide

Oracle Database 12c Enables Quad Graphics to Quickly Migrate from Sybase to Oracle Exadata

What is the value of SQL%ISOPEN immediately after the SELECT statement is executed? Error. That attribute does not apply for implicit cursors.

Programming Database lectures for mathema

Designing with Exceptions. CSE219, Computer Science III Stony Brook University

NEOAUG. Custom Web ADI Integrators

Costing In Oracle HRMS CONCEPTS

PL/SQL MOCK TEST PL/SQL MOCK TEST I

Database Management System Choices. Introduction To Database Systems CSE 373 Spring 2013

Transcription:

Oracle PL/SQL Best Practices Bullet Proof Your PL/SQL For those few times when something doesn't go as planned... Audio will be available through your computer/headset. You do not need to dial in (and access that way is limited). If you do dial in, security code is 1111. Download this PPT from oracle.com/oll, search for PL/SQL, visit the PL/SQL Learning Library. Steven Feuerstein Architect, Applied PL/SQL email: steven.feuerstein@oracle.com blog: stevenfeuersteinonplsql.blogspot.com twitter: sfonplsql Copyright 2014 Oracle and/or its affiliates. All rights reserved.

Bullet Proof PL/SQL The #1 fantasy in sopware development: everything goes as planned. Users gave us accurate specificatons Users use the applicaton properly There are no bugs in our code, etc., etc., etc. As with most fantasies, not much connecton with reality. So if you want to write high quality, popular applicatons, you need to antcipate problems and make your code "bullet proof". Let's take a whirlwind trip through features in and techniques with PL/SQL to achieve that. All referenced code available in my demo.zip file from the PL/SQL Learning Library: oracle.com/oll, search on "PL/SQL". 2

All that we can talk about Handling exceptons Built in functonality in DBMS_UTILITIES and UTL_CALL_STACK Where and how to best handle FORALL with SAVE EXCEPTIONS: suppress errors at statement level LOG ERRORS for DML: suppress errors at row level AFTER SERVERERROR trigger: instance wide error handling ValidaTng assumptons with assertons: no surprises! Tracing executon to help diagnose bugs: how did that surprise happen? Wow! That's a lot...let's get going 3

Handling ExcepTons The EXCEPTION secton consolidates all error handling logic in a block. But only traps errors raised in the executable secton of the block. SQLCODE and SQLERRM: Oracle suggests that you not use SQLERRM. DBMS_UTILITY.FORMAT_CALL_STACK: "how did I get here?" DBMS_UTILITY.FORMAT_ERROR_STACK: "what was the error?" DBMS_UTILITY.FORMAT_ERROR_BACKTRACE: "where in my code was the error raised?" And, new to 12.1, UTL_CALL_STACK backtrace.sql bt.pkg Copyright 2000-2008 Steven Feuerstein - Page 4 Copyright 2014 Oracle and/or its affiliates. All rights reserved.

UTL_CALL_STACK (12.1 only) This new package provides a granular API to the call stack and back trace. It also now provides complete name informaton, down to the nested subprogram. But the bomom line is that generally you will call your functons in the excepton secton (thru a generic error logging procedure, I hope!) and then write that informaton to your error log. When you need to diagnose an error, go to the log, grab the string, and analyze. utl_call_stack*.* 5

Where to use all those functons NOT in each excep,on handler. Instead, put them inside a generic error logger. Call the logger in each handler, passing applicaton- specific informaton. Inside the procedure, call all the built- in functons and throw it all in a table. And at what level should you trap those exceptons? Some trap exceptons at top- most block simpler and easier. I suggest trapping exceptons in block where they are raised. It's more work, but then you can log the values of local variables. 6

FORALL and DML Errors FORALLs typically execute a large number of DML statements. When an excepton occurs in one of those DML statement, the default behavior is: That statement is rolled back and the FORALL stops. All (previous) successful statements are not rolled back. What if you want the FORALL processing to contnue, even if an error occurs in one of the statements? Just add the EXCEPTIONS clause! forall_examples.sql Copyright 2014 Oracle and/or its affiliates. All rights reserved.

FORALL with SAVE EXCEPTIONS PROCEDURE upd_for_dept (newsal_in IN NUMBER, list_of_emps_in IN pkg.array_type) IS BEGIN FORALL indx IN list_of_emps_in.first.. list_of_emps_in.last SAVE EXCEPTIONS UPDATE employees SET salary = newsal_in WHERE employee_id = list_of_emps_in (indx); END; FORALL is key feature for improving performance of DML inside loops. Add SAVE EXCEPTIONS so that Oracle saves excepton informaton and contnue processing all of the DML statements. When the FORALL statement completes, if at least one excepton occurred, Oracle then raises ORA- 24381. You then check the contents of SQL%BULK_EXCEPTIONS. bulkexc.sql Copyright 2014 Oracle and/or its affiliates. All rights reserved.

Row level suppression of errors with LOG ERRORS Default behavior: each DML statement is "all or nothing". If an error occurs on any row, changes to all rows are rolled back. Add the LOG ERRORS clause to your DML statement to preserve changes to rows. Errors are wrimen out to table defined through call to DBMS_ERRLOG. Things to keep in mind: No excepton is raised when statement finishes! Error log table missing key informaton, but you can add it! dbms_errlog.* dbms_errlog_helper.sql save_exc_vc_dbms_errlog.sql cfl_to_bulk7.sql Copyright 2000-2008 Steven Feuerstein - Page 9 Copyright 2014 Oracle and/or its affiliates. All rights reserved.

The AFTER SERVERERROR trigger Provides a relatvely simple way to use a single table and single procedure for excepton handling in an entre instance. Drawbacks: Error must go unhandled out of your PL/SQL block for the trigger to kick in. Does not fire for all errors (NO: - 600, - 1403, - 1422...) Most useful for non- PL/SQL front ends executng SQL statements directly. afterservererror.sql Copyright 2000-2008 Steven Feuerstein - Page 10 Copyright 2014 Oracle and/or its affiliates. All rights reserved.

Bullet proof your blocks Every block of PL/SQL code has the same structure: DeclaraTon, ExecuTon, ExcepTon I suggest that to write high quality, bullet proof code, you should write blocks with a slightly more elaborate "structure". Key technique: nested subprograms. DECLARE/IS <declarations> PROCEDURE initialize IS BEGIN <validate assumptions> <other start up code> END; PROCEDURE cleanup... BEGIN initialize; <your code> cleanup; EXCEPTION WHEN <error> OTHERS THEN <log error> cleanup; END: 11

ValidaTng assumptons with asserton routnes Every program makes assumptons. "The department ID will never be NULL." "There will always be a row of data for that value." When an assumpton is violated, programs can break in ways that are difficult to diagnose. "No problem!" you might say. I'll just write an IF statement: BEGIN IF dept_id_in IS NULL THEN RAISE_APPLICATION_ERROR ( -20000, 'Dept ID cannot be NULL); END IF; <"normal" code> END: Copyright 2000-2008 Steven Feuerstein - Page 12 Copyright 2014 Oracle and/or its affiliates. All rights reserved.

Making assertons practcal We are not going to write all that code. And if we do, we expose the mechanism for assertng best to hide the internal mechanics. Instead, use pre- defined asserton routnes. DeclaraTve, quick to insert, easier to integrate into error logging, etc. BEGIN assert.is_not_null (dept_id_in, 'Dept ID cannot be NULL'); <"normal" code> END: assert.pkg 13

Tracing executon of your code Something is going to go wrong. And if it happens in producton, you will most likely find: You can't even believe it's happening. "That shouldn't be possible." You can't reproduce it in dev or test. "Oh well, let us know if it happens again." What's a developer to do? UTlize built- in tracing and profiling, but these are not "applicaton aware". So in additon: Trace (or instrument) your code! You must insert calls to grab applicaton state and save it to a table/file/screen. 14

Key Tps for tracing Never put calls to DBMS_OUTPUT.PUT_LINE in your applicaton code. Always put calls to trace inside a Boolean expression to minimize overhead in producton. Do not comment out tracing when you move to producton. Make it easy to "switch" between sending trace info to table, screen, etc. Build in the ability to turn on/off tracing in your app without modifying code. Consider using the DBMS_APPLICATION_INFO package, the Logger utlity, or build your own. 15

Bullet Proof PL/SQL It's not that hard! Oracle PL/SQL offers many features to help you manage how errors are both raised and handled. The key step for you is to set up guidelines about how these features should be applied. Decide where and when and how you will handle exceptons. Decide standards for executon tracing: parameter values, key algorithmic steps, etc. Build or install error logging and executon tracing utlites. Establish a new standard for block structure. Use nested subprograms to isolate and routnely build initalizaton, cleanup and asserton "sectons". 16