DB2 Stored Procedures and UDFs: A Primer

Slides:



Advertisements
Similar presentations
MQ Series Cross Platform Dominant Messaging sw – 70% of market Messaging API same on all platforms Guaranteed one-time delivery Two-Phase Commit Wide EAI.
Advertisements

Yokogawa Network Solutions Presents:
Security Pertemuan 7 Matakuliah: T0413 Tahun: 2009.
Oracle9i Database Administrator: Implementation and Administration 1 Chapter 2 Overview of Database Administrator (DBA) Tools.
1 DB2 Access Recording Services Auditing DB2 on z/OS with “DBARS” A product developed by Software Product Research.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13 Introduction to SQL Programming Techniques.
--What is a Database--1 What is a database What is a Database.
Fundamentals, Design, and Implementation, 9/e Chapter 11 Managing Databases with SQL Server 2000.
1 - Oracle Server Architecture Overview
Harvard University Oracle Database Administration Session 2 System Level.
Hands-On Microsoft Windows Server 2003 Networking Chapter 7 Windows Internet Naming Service.
Database Management Systems (DBMS)
Chapter 9 Overview  Reasons to monitor SQL Server  Performance Monitoring and Tuning  Tools for Monitoring SQL Server  Common Monitoring and Tuning.
Module 8: Monitoring SQL Server for Performance. Overview Why to Monitor SQL Server Performance Monitoring and Tuning Tools for Monitoring SQL Server.
Overview SAP Basis Functions. SAP Technical Overview Learning Objectives What the Basis system is How does SAP handle a transaction request Differentiating.
Performance and Capacity Experiences with Websphere on z/OS & OS/390 CMG Canada April 24, 2002.
SEMESTER 1, 2013/2014 DB2 APPLICATION DEVELOPMENT OVERVIEW.
Advance Computer Programming Java Database Connectivity (JDBC) – In order to connect a Java application to a database, you need to use a JDBC driver. –
1 Section 6 Embedded SQL. 6-2 CA306 Embedded SQL Section Content 6.1Embedded SQL 6.2Java Database Connectivity 6.3Web Databases.
Getting connected.  Java application calls the JDBC library.  JDBC loads a driver which talks to the database.  We can change database engines without.
Database Security and Auditing: Protecting Data Integrity and Accessibility Chapter 3 Administration of Users.
Overview of JDBC and Pro*C 1 Overview of JDBC,Pro*C and Oracle connectivity on Omega CSE 5330 – Database Systems.
Native Support for Web Services  Native Web services access  Enables cross platform interoperability  Reduces middle-tier dependency (no IIS)  Simplifies.
Database Systems: Design, Implementation, and Management Tenth Edition Chapter 11 Database Performance Tuning and Query Optimization.
Chapter Oracle Server An Oracle Server consists of an Oracle database (stored data, control and log files.) The Server will support SQL to define.
Understanding the CORBA Model. What is CORBA?  The Common Object Request Broker Architecture (CORBA) allows distributed applications to interoperate.
Java Stored Procedures in DB2 for OS/390 Open, Portable Application Logic Julian Stuhler DB2/CICS/IMS GUIDE May 2000.
Announcements Read JDBC Project Step 5, due Monday.
By Lecturer / Aisha Dawood 1.  You can control the number of dispatcher processes in the instance. Unlike the number of shared servers, the number of.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM. 5.1 © Copyright IBM Corporation 2008 DB2 9 Fundamentals.
CICS-Int1 Introduction to On-Line BATCH – Transactions are accumulated into groups (batches) before processing. ON-LINE – Interactive Transactions entered.
Database Systems Slide 1 Database Systems Lecture 5 Overview of Oracle Database Architecture - Concept Manual : Chapters 1,8 Lecturer : Dr Bela Stantic.
Overview of JDBC and Pro*C 1 CSE 5330 – Database Systems.
Computer Emergency Notification System (CENS)
Oracle 10g Database Administrator: Implementation and Administration Chapter 2 Tools and Architecture.
Introduction to the Adapter Server Rob Mace June, 2008.
Oracle Data Integrator Procedures, Advanced Workflows.
Triggers and Stored Procedures in DB 1. Objectives Learn what triggers and stored procedures are Learn the benefits of using them Learn how DB2 implements.
Introduction to the new mainframe © Copyright IBM Corp., All rights reserved. Chapter 12 Understanding database managers on z/OS.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM. 5.1 © Copyright IBM Corporation 2008 DB2 9 Fundamentals.
Database Design and Management CPTG /23/2015Chapter 12 of 38 Functions of a Database Store data Store data School: student records, class schedules,
F15 Philip K. Gunning, DGI Anaheim, CA Sept , 2002 Fundamentals of DB2 SQL Procedures.
ICS 321 Fall 2010 SQL in a Server Environment (i) Asst. Prof. Lipyeow Lim Information & Computer Science Department University of Hawaii at Manoa 11/1/20101Lipyeow.
Programmatic SQL Shaista Khan CS 157B. Topic Embedded SQL statements in high-level programming languages.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
Data Sharing. Data Sharing in a Sysplex Connecting a large number of systems together brings with it special considerations, such as how the large number.
Process Architecture Process Architecture - A portion of a program that can run independently of and concurrently with other portions of the program. Some.
Dr Gordon Russell, Napier University Unit Embedde SQL - V2.0 1 Embedded SQL Unit 5.1.
JS (Java Servlets). Internet evolution [1] The internet Internet started of as a static content dispersal and delivery mechanism, where files residing.
Database Access Using JDBC BCIS 3680 Enterprise Programming.
CSI 3125, Preliminaries, page 1 SERVLET. CSI 3125, Preliminaries, page 2 SERVLET A servlet is a server-side software program, written in Java code, that.
Chapter 5 Introduction To Form Builder. Lesson A Objectives  Display Forms Builder forms in a Web browser  Use a data block form to view, insert, update,
Development Overview Pertemuan 11 Matakuliah: T0413 Tahun: 2009.
Stored Procedures / Session 4/ 1 of 41 Session 4 Module 7: Introducing stored procedures Module 8: More about stored procedures.
Text TCS INTERNAL Oracle PL/SQL – Introduction. TCS INTERNAL PL SQL Introduction PLSQL means Procedural Language extension of SQL. PLSQL is a database.
SQL Triggers, Functions & Stored Procedures Programming Operations.
Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe.
7.5 Using Stored-Procedure and Triggers NAME MATRIC NUM GROUP Muhammad Azwan Bin Khairul Anwar CS2305A Muhammad Faiz Bin Badrol Shah CS2305B.
Oracle Database Architectural Components
MQ Series Cross Platform Dominant Messaging sw – 70% of market
DEPTT. OF COMP. SC & APPLICATIONS
1 DB2 Access Recording Services Auditing DB2 on z/OS with “DBARS” A product developed by Software Product Research.
Chapter 14: System Protection
Web Technologies IT230 Dr Mohamed Habib.
Chapter 5: Advanced SQL Database System concepts,6th Ed.
Introduction What is a Database?.
DB2.
MQ Series Cross Platform Dominant Messaging sw – 70% of market
Chapter 8 Advanced SQL.
Chapter 11 Managing Databases with SQL Server 2000
Presentation transcript:

DB2 Stored Procedures and UDFs: A Primer Quest Software

Agenda Why Use DB2 Stored Procedures? Why Use UDFs? Setting up the Environment. Performance Tuning. References.

DB2 Stored Procedures Benefits Secure access to DB2 data. Access non-DB2 data if necessary – VSAM, IMS, etc. Code business logic once Maintenance is simpler Performance improvement? Instead of multiple SQL statements being sent Lots of languages to choose from.

DB2 Stored Procedures 2 types of Stored Procedures to choose from: SQL Procedures External Procedure

DB2 SQL Stored Procedures Benefits Programmer productivity – Familiar standard SQL. Only SQL statements and procedural control-flow statements. Portable. Compile and register into DB2 tables. Not interpreted, but compiled as C code. Member of a schema (dependencies). External stored procedures, those written in COBOL, C, FORTRAN, etc. can get out of sync with schema objects because executables are stored at the system level, not in the database.

DB2 SQL Stored Procedures CREATE PROCEDURE UPDATE_SALARY (IN EMPLOYEE_NUMBER CHAR(10), IN RATE DECIMAL(6,2)) LANGUAGE SQL WLM ENVIRONMENT SAMP1 COMMIT ON RETURN YES IF RATE <= 0.50 THEN UPDATE EMP SET SALARY = SALARY * RATE WHERE EMPNO = EMPLOYEE_NUMBER; ELSE UPDATE EMP SET SALARY = SALARY * 0.50 END IF SQL stored procedures are stored in the database, and written exclusively in SQL procedure language, making them fast to develop and maintain.

DB2 External Stored Procedures As name Implies the code for external stored procedure is stored outside the database. Multiple threads can call and reuse the same stored procedure by defining as reentrant.

DB2 Stored Procedures Benefits To define the SP as reentrant... Specify STAY RESIDENT YES on the CREATE PROCEDURE statement. The default is STAY RESIDENT NO. Then, the SP is deleted from memory as soon as it has completed executing. The SP will not need to be loaded into memory each time, so wait time is reduced. Multiple threads will be able to share one copy of the SP in memory. To prepare your stored procedure as reentrant, you must compile it as reentrant and link-edit it as reentrant and reusable. To compile the program as reentrant, you must use the appropriate compiler option: w For COBOL, use the RENT compiler option. w For C, use the RENT compiler option and invoke the C/370 prelink utility. Refer to the C/370 manuals for more information on the prelink utility. w For PL/I, use PROC OPTIONS(REENTRANT). Besides compiling the program as reentrant, you must specify the RENT and REUS options for the linkage editor. This specification is also necessary to produce reentrant and reusable load modules. Here is sample JCL for compiling and link-editing a reentrant stored procedure: //PREPS01 EXEC DSNHCOB2, .... // PARM.COB=(RENT, .... // PARM.LKED=(RENT, REUS, ...

DB2 External Stored Procedure - CREATE CREATE PROCEDURE SYSPROC.MYPROC(IN INT, OUT INT, OUT2 DECIMAL(7,2)) LANGUAGE COBOL EXTERNAL NAME MYMODULE PARAMETER STYLE GENERAL WLM ENVIRONMENT PARTSA STAY RESIDENT YES RESULT SETS 1; This is the CREATE for a SQL stored procedure: CREATE PROCEDURE UPDATE_SALARY_1 (IN EMPLOYEE_NUMBER CHAR(10), IN RATE DECIMAL(6,2)) LANGUAGE SQL MODIFIES SQL DATA UPDATE EMP SET SALARY = SALARY * RATE WHERE EMPNO = EMPLOYEE_NUMBER

Stored Procedures/UDFs External Languages COBOL – LE/370 environment required. C – LE/370 environment required. V6 addition Assembler, PL/I C++, REXX and FORTRAN for stored procedures only – not for UDFs User Defined Functions can be written in Assembler, C, COBOL, or PL/I.. LE/370 is Language Environment 370. It’s a run-time library that DB2 OS/390 uses for stored procedure run-time environments. Services like storage management and exception handling are provided.

DB2 Stored Procedures SQL API’s EXEC SQL/SQLJ CLI/JDBC SQL is embedded, e.g. C code Static & Dynamic SQL Translate SQL and create package. Authorization by Binder/Invoker SQL via API calls Dynamic SQL No precompiling Code is portable. Authorization by User

DB2 Stored Procedures Program Prep Basic steps. Precompile SQL source into byte-code that DB2 will recognize (this step is not needed for JDBC Java programs). Bind extracted SQL into DB2 packages. Compile/Link-edit. Java, package the Java .class files for deployment platform.

DB2 Stored Procedures Program Prep

DB2 User Defined Functions What are they? Program code that can be called as a function in a SQL statement. Two types Sourced: Based on another UDF or built-in function. Usually to enable a function for a user-defined data type. External: Written in a supported language. Environment setup the same as for stored procedures. Run in WLM address spaces.

DB2 User Defined Functions Benefits A UDF in DB2 is like a host language subprogram, but can be invoked in a SQL statement (like a built-in function). Another way to share standard code for ease of use. Maintenance is done in one place.

DB2 User Defined Functions CREATE statement Sourced: CREATE FUNCTION AVE (HATSIZE) RETURNS HATSIZE SOURCE SYSIBM.AVG (INTEGER); This UDF will enable the use of a user-defined data type HATSIZE with a built-in function, INTEGER.

DB2 User Defined Functions CREATE statement External: CREATE FUNCTION CENTER (INTEGER, FLOAT) RETURNS FLOAT EXTERNAL NAME 'MIDDLE' LANGUAGE C DETERMINISTIC NO SQL FENCED PARAMETER STYLE DB2SQL NO EXTERNAL ACTION STAY RESIDENT YES;

DB2 User Defined Functions External Table functions, A special kind of UDF that returns a table. Invoked in the FROM clause of a SELECT. Can access non-DB2 data, including external data, in a SQL query. A file on the Web, a flat file on a system, etc. will be returned as a relational table from the function. Then can be INSERTed into a DB2 table, for example: INSERT INTO global_temp_table SELECT <column names> FROM TABLE(DOCMATCH(d:\prod\data\filename)) … CREATE statement for a Table Function is on next slide.

DB2 User Defined Functions External CREATE FUNCTION DOCMATCH (VARCHAR(255)) RETURNS TABLE (DOC_ID CHAR(16)) EXTERNAL NAME ABC LANGUAGE C PARAMETER STYLE DB2SQL NO SQL DETERMINISTIC NO EXTERNAL ACTION FENCED SCRATCHPAD FINAL CALL DISALLOW PARALLEL CARDINALITY 20; The output of the DOCMATCH function is a table, with one column named DOC_ID.

DB2 Stored Procedures Coding Global Temporary Tables Handle like a regular table, but it is temporary…rows deleted at COMMIT. CREATE GLOBAL TEMPORARY TABLE temp_quest. CREATE …. LIKE quest_tb. Authority required same as for CREATE TABLE; or grant CREATEMTAB. Not associated with a tablespace or database. Rows are written to work tablespaces on DSNDB07. No logging or locks - efficient processing. A Global Temporary Table, once created with the CREATE statement results in an entry on SYSTABLES with a TYPE of ‘G’. An empty instance of the table is created on the first reference in an OPEN, SELECT FROM, DELETE, or INSERT.

Stored Procedures/UDFs Environment Setup First step – Assemble an implementation SWAT team! MVS and DB2 System Programmers May need Unix skills for UNIX System Services on OS/390 (for JAVA). DBA. Developer. Then, get the IBM Redbooks (more on this toward the end)!

Stored Procedures/UDFs Environment Overview Big Picture – sequence of events: Client -> Function -> DB2 -> WLM ->AE-> RRS -> DB2 -> Client The life cycle of the transaction looks like this: Client -> Stored Procedure -> DB2 -> WLM -> AE -> RRS -> DB2 -> Client

Stored Procedures/UDFs Environment Setup Tying it all together – sequence of events: A client application connects to an OS/390 DB2 subsystem. A CALL is issued for a stored procedure. DB2 searches SYSROUTINES to locate the SP. IF a WLM application environment is named in the WLM AE column, DB2 will ask WLM to initiate that WLM AE. WLM takes over. The PROC associated with the AE is invoked with an MVS Start command for the PROC. The life cycle of the transaction looks like this: Client -> Stored Procedure -> DB2 -> WLM -> AE -> RRS -> DB2 -> Client

Stored Procedures/UDFs Environment Setup Tying it all together – sequence of events: The AE Address Space is created and begins running program DSNX9WLM, DB2’s WLM application program. The first task of DSNX9WLM is to establish a connection back to the DB2 subsystem using the RRS Attach Facility (RRSAF). Once the communication path is established back to DB2, the WLM AE will fetch the SP program and run it. The life cycle of the transaction looks like this: Client -> Stored Procedure -> DB2 -> WLM -> AE -> RRS -> DB2 -> Client

Stored Procedures/UDFs Environment Setup Tying it all together – sequence of events: Results of the executed SP program are returned to DB2 via the RRSAF communication link. The client receives the results from DB2. The life cycle of the transaction looks like this: Client -> Stored Procedure -> DB2 -> WLM -> AE -> RRS -> DB2 -> Client

Stored Procedures/UDFs Environment Setup WLM (Workload Manager) Address Spaces Balance workloads dynamically – automatically routing requests to the least-busy address space available. Starts up new address spaces if needed. Inherit the dispatching priority of the DB2 thread that issued the CALL. So, high-priority work gets its SPs/UDFs executed ahead of lower-priority work. Required for JAVA. Required for all in V8. Dispatching control like you get in WLM address spaces is not available in DB2-established address spaces. In V8, the SPAS is going away, so WLM is your only choice for stored procedure address spaces.

Stored Procedures/UDFs Environment Setup WLM Compatibility Mode Before WLM, MVS controlled its dispatching priorities using two PARMLIB members… installation performance specification (IPS) installation control specification (ICS) Manual effort to make changes as new applications came along. Cumbersome, error-prone, and required IPL. The procs for Application Environment address spaces must be started by operator

Stored Procedures/UDFs Environment Setup WLM Goal Mode Goal Mode uses service polices and class periods to control dispatching. Each service class is given a goal. Response Goal: “TSO transactions should complete in .5 seconds”. WLM will try to achieve this goal by asking OS/390 to provide more resources. In Goal Mode, WLM starts and stops address spaces as needed. No operator intervention Compatibility Mode can be a backup processing method if a problem is encountered with a WLM policy, etc.

Stored Procedures/UDFs Environment Setup WLM Address Spaces Application Environments are groups of address spaces started by the same PROC and used to help meet performance goals by dynamically changing the number of address spaces used for the workload. Each AE definition represents one or more stored procedures & UDF’s.

Stored Procedures/UDFs Environment Errors How do I know when a WLM application environment is down? D WLM,APPLENV=* will display the current status of each application environment. RESPONSE=QSD1 IWM029I 12.57.37 WLM DISPLAY 364 APPLICATION ENVIRONMENT NAME STATE STATE DATA DSD6CBMT AVAILABLE DSD6CBST AVAILABLE DSD6ENVW AVAILABLE DSD6ENWT AVAILABLE DSD6JBMT STOPPED The Display command (D WLM…) should indicate AVAILABLE on all WLM application environments. If one is STOPPED, try V WLM,APPLENV=appname,RESUME to make it available.

Stored Procedures/UDFs Security w/RACF Each AE definition must have a Server class policy defined by RACF. DB2 uses the RACF resource name “DB2.<subsystem_id>.<wlm_appl_env>” to control which userids have rights to create a routine in a WLM environment. Running stored procedures: You can use the WLM ENVIRONMENT clause to identify the MVS address space in which a stored procedure or function is to run. Using different WLM environments lets you isolate one group of programs from another. For example, you might choose to isolate programs based on security requirements and place all payroll applications in one WLM environment because those applications deal with sensitive data, such as employee salaries. DB2 invokes RACF to determine whether you have appropriate authorization to create a procedure or function (regardless of where the routine is to run). For example, the following RACF command authorizes DB2 user USER1 to define stored procedures on DB2 subsystem DSNP that run in the WLM environment named ROSTER: PERMIT DSNP.WLMENV.ROSTER CLASS(DSNR) ID(USER1) ACCESS(READ)

Stored Procedures/UDFs Environment Setup Resource Recovery Services (RRS) If you have a SYSPLEX, RRS enables dynamic shifting of resources. Also, enables communication between DB2 and applications via RRSAF (attach facility).

Stored Procedures/UDFs Environment Errors If RRS is not running, or not configured: The communication error will look like: SSID:DSNQ - Error during IDENTIFY, Return Code: 8 Reason Code: F30091 …and the error in the application environment will look like this: DSNX967I DSNX9WLM ATTEMPT TO PERFORM WLM FUNCTION IWMCOMM FAILED WITH WLM RC = 00000008 RSN = 1104085C SSN = D999 PROC=… The error is the result of the procedure/function not having a way to communicate back to DB2 – no RRSAF path to send the message on.

Stored Procedures/UDFs EXECUTE Authority in DB2 Authorizations to CALL a stored procedure or invoke a User Defined Function: EXECUTE privilege on the routine (sp or udf). Who must have the privilege for an SP depends on whether the SP name in the CALL is a variable or a literal. If SP name is a literal, the owner of the client app package must have EXECUTE authority on the SP. DYNAMICRULES bind option, if used, dictates who needs EXECUTE authority. DYNAMICRULES(RUN) The primary or secondary authid of the client application process will be used for execute authorization checking. DYNAMICRULES(BIND) The owner of the DB2 package or plan of the client app will be used for execute authorization checking. DYNAMICRULES(DEFINE) The routine’s owner is used for table authorization checking if nested SP. For other SPs and UDFs, the owner of the package/plan of the client app is used. DYNAMICRULES(INVOKE) If nested SP, the invoker of the SP will be checked for authorization. Otherwise, the primary or secondary authid of the client application process will be used for execute authorization checking.

Stored Procedures/UDFs DISPLAY command -DISPLAY PROCEDURE(ROSTER.*, PROD.*) Lists stored procedures that have been CALLed since DB2 was last started. Information includes: Schema WLM_ENV name Status of SP (Started, Stopped/why) Number of active threads using the load module, queued threads waiting for SP, and timed out CALLs.

Stored Procedures/UDFs DISPLAY command -DISPLAY FUNCTION SPECIFIC (*.*) Lists functions that have been CALLed since DB2 was last started. Information includes: Schema WLM_ENV name Status of function (started, stopped/why) Number of active threads currently running the function, queued threads waiting for the function to be scheduled, and timed-out waits.

Stored Procedures/UDFs START command -START/STOP FUNCTION SPECIFIC (*.*) Activates a UDF that is stopped. -START/STOP PROCEDURE (*.*) Activates the definition of a stored procedure that is stopped or refreshes one that is cached.

DB2 Stored Procedures Performance Tuning DISPLAY THREAD (*) to see current status of threads calling stored procedures: ST = SP means that the tread is executing in a stored procedure. ST = SW means that the thread is waiting for a stored proc to be scheduled. The “ST” column on DISPLAY THREAD command output is the “status” column.

DB2 Stored Procedures Performance Tuning If DISPLAY THREAD (*) output’s status indicates too much waiting, investigate: WLM service policies. WLM application environment status and TCB’s defined. Application problems (locking, badly tuned SQL, long-running tasks). System tuning possibilities (buffer pools, etc.)

DB2 Stored Procedures Performance Tuning If DB2 runs out of TCBs for your SP, and delays the start of the SP after a request, you won’t see any SQLCODEs. You can investigate further with traces… -START TRACE(PERFM) DEST(??) CLASS(??) IFCID(233,242,243) TDATA(CPU,DIST) 233: generated when a SP is called or completes. 242: generated when a SP has to wait for a TCB (max TCBs hit). 243: generated when a waiting SP can now run (max TCBs hit).

Performance Tuning Tune the USS environment. Tune TCP/IP. See www-1.ibm.com/servers/eserver/zseries/zos/unix/ Tune TCP/IP. Tune your SP and client code. Cache objects, etc. Lots of recommendations: www-1.ibm.com/servers/eserver/zseries/software

References IBM Redbooks: SG24-5945, DB2 Java Stored Procedures: Learning by Example. SG24-5619, Java Programming Guide for OS/390. SG24-4693, Getting Started with DB2 Stored Procedures: Give Them a Call through the Network. SG24-5485-01, Cross Platform DB2 Stored Procedures REDP0183 Setup of the DB2 Application Development Environment for Stored Procedures

Conclusion Successful implementation of DB2 Stored Procedures and UDFs takes: A team of the right people. LOTS of planning. Important environmental decisions. Application requirements knowledge. Use of reference material available. Performance monitoring and tuning of system.

THANK YOU FOR LISTENING