21
Sat, Dec
3 New Articles

TechTip: Automatically Generate an SQE Plan Cache Snapshot

Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

If you use SQL to access your database objects, you may be aware of the SQL Query Engine (SQE) introduced in V5R2. SQE offers algorithms and features that give it distinct performance advantages over its predecessor, the Classic Query Engine (CQE).

One of SQE's most powerful features is the SQE plan cache, an internal matrix-like repository that holds the access plans for queries optimized by SQE. The primary purpose of the plan cache is to facilitate reuse: Whenever SQE encounters a query that is the same as or similar to one stored in the plan cache, it reuses the plans associated with that query, regardless of the user or interface. That way, the optimizer does not have to create new access plans, thereby saving time and resources. In addition, the plan cache contains valuable feedback information about the execution of the queries, including elapsed run time, access methods used, Open Data Path (ODP) creation, and index advisories.

In V5R4, IBM provided an interface to the plan cache through iSeries Navigator, giving administrators direct access to a vast and useful source of database information. They can view the statements in the plan cache, perform analysis using the provided reports, compare statements, and even launch Visual Explain to view a graphical representation of any statement resident in the plan cache. In many cases, problem queries can be captured and analyzed in the plan cache. This eliminates the need to collect performance data using the much more resource-intensive database monitors.

Due to the complexities involved with maintaining the plan cache data through an IPL process, IBM has chosen to implement it as an internal object that is deleted during the IPL shutdown phase and then recreated at startup. While this may seem reasonable, it can be a source of frustration if you want to keep the data in the plan cache for future analysis and comparison.

In addition, the active plan cache is fixed in size. In V5R2 and V5R3, the maximum size was 256 MB, a limitation that was increased to 512 MB in V5R4. The number of plans held in the plan cache obviously depends on the complexity of the SQL statements, but you should expect the capacity to be in the range of 10,000 to 20,000 unique access plans for a V5R4 system. To maintain this capacity, the database constantly monitors the plan cache size and removes plans based on an aging algorithm. Once a plan is determined to be "old" and kicked out of the plan cache, that information is lost and cannot be recovered.

All must not be lost, however. In V5R4, IBM also introduced plan cache snapshots, a feature designed to provide a mechanism to periodically capture statement information. Snapshots represent the data in the plan cache captured at some point in time and then store this information in a single database table. This provides the following:

  • A means for plan cache data to persist across IPLs
  • A way to capture plans before they are aged and cast out of the plan cache

Perhaps the best thing about snapshots is this: All the features available in the iSeries Navigator interface for the active plan cache are also supported for plan cache snapshots. And because the plan cache snapshot is a table, you can run your own custom queries against the data, something unavailable for the active plan cache data. In fact, the snapshot table format is identical to a detailed database monitor collection (a nice feature if you consider that custom-built queries and reports that analyze database monitor data can also be used to analyze plan cache snapshot data).

Capturing a plan cache snapshot is not an automated process. It must be done either manually through iSeries Navigator interface or programmatically by calling the system-supplied stored procedure QSYS2/DUMP_PLAN_CACHE. In either case, remembering to perform a plan cache dump prior to every IPL can be problematic: If this step in the shutdown process is forgotten or bypassed, all plan cache data is lost. A method of automation can be quite useful, and this is where exit points come in.

By definition, an exit point is a specific point in a system function or program where control can be passed to one or more specified exit programs. In other words, when a specific event occurs on the system, a user-written program can be called to perform a specific task. One of the supported exit points on the System i is QIBM_QWC_PWRDWNSYS, an exit point that is invoked whenever the PWRDWNSYS or ENDSYS command is issued. The program registered under this exit point is called before the system actually powers down.

By now, you probably see where this is going: Combine this exit point with the ability to programmatically dump the plan cache and voila! Plan cache snapshot automation is in place! No longer do you need to worry about doing it manually. Set it up once, and let the system handle the rest.

Here are the steps involved in setting up this automated behavior:

  1. Write the exit point program.
  2. Compile the exit point program.
  3. Register the program to the exit point.
  4. Import the snapshot (after an IPL).

Write the Exit Point Program

The exit point program can be written in any System i–supported language. Here's a source code example written in free-format RPG:

h dftactgrp(*no) actgrp(*caller)                            
d currentDate     s               d                         
d snapshotName    s             10a                         
 /free                                                      
   currentDate = %date();                                   
   snapshotName = 'PC' +                                    
                 %char ( %subdt(currentDate:*YEARS)) +      
                 %char ( %subdt(currentDate:*MONTHS)) +     
                 %char ( %subdt(currentDate:*DAYS));        
   exec sql                                                 
     CALL QSYS2/DUMP_PLAN_CACHE('QGPL', :snapshotName);     
                                                            
   // Did an error occur?                                   
   if %subst(sqlstate:1:2)<> '00';                          
      // do something...like send a message to QSYSOPR      
   endif;                                                   
   return;                                                  
 /end-free                                                  

Notice that the program uses embedded SQL to call the system-supplied stored procedure DUMP_PLAN_CACHE in library QSYS2. This is important to note because a stored procedure can be called only from an SQL interface.

This stored procedure accepts two input parameters:

  • Snapshot table library—The 10-character system object name of the library to hold the specified snapshot table
  • Snapshot table—The 10-character system object name of the table to dump the plan cache data into

Note: This procedure itself does not clear the plan cache. It only dumps the contents of the plan cache into the specified snapshot table. As mentioned, the plan cache is deleted and recreated during IPL.

In this example, the current date is used to assign a dynamic name to the snapshot table, which helps to easily determine when the snapshot was taken. However, if this example is used and more than one IPL is performed per day, subsequent calls to the DUMP_PLAN_CAHCE stored procedure will fail with the SQL error SQL0601 (file already exists). Therefore, you should consider a naming scheme with more granularity, such as appending a counter to the end of the name or using a sequence object to generate a unique name.

Compile the Program

Now, issue the command to create the program:

CRTSQLRPGI OBJ(QGPL/IPLEXIT) SRCFILE(QGPL/QRPGLESRC)

Once the program object has been created, it is recommended that you perform a simple test to verify that the program works and that a plan cache dump can be generated. To do this, simply call the program from a command line:

CALL QGPL/IPLEXIT

To make sure that the snapshot contains data, use your favorite database viewing tool to examine the contents of the table.

Register the Program to the Exit Point

The next step is to register the exit program to the exit point. To use this registration facility, issue the following command from a command line:

ADDEXITPGM EXITPNT(QIBM_QWC_PWRDWNSYS) FORMAT(PWRD0100) PGMNBR(*LOW) PGM(QGPL/IPLEXIT)               

This will cause the system to invoke the program IPLEXIT in library QGPL whenever a user issues the PWRDWNSYS or ENDSYS command.

The exit point is now configured and ready to dump the plan cache into the specified snapshot table.

Import the Snapshot

One last step: You must import the plan cache snapshot before it appears in iSeries Navigator. To do this, open a connection and select Databases -> SQL Plan Cache Snapshots. From the right-mouse-click menu, select Import, as shown in Figure 1.

http://www.mcpressonline.com/articles/images/2002/Tip%20-%20capture%20plan%20cache%20snapshot%20at%20IPL%203%20V4--11170600.jpg

Figure 1: Import the snapshot.

The Import SQL Performance Data dialogue window is displayed. Enter a brief description, schema, and table name of the snapshot table, as shown in Figure 2.

http://www.mcpressonline.com/articles/images/2002/Tip%20-%20capture%20plan%20cache%20snapshot%20at%20IPL%203%20V4--11170601.jpg

Figure 2: Specify the snapshot table to import.

Click OK to complete the import process. The snapshot now appears in the SQE Plan Cache Snapshots list and is ready to be viewed, compared, and analyzed.

Feel the Power

The SQE plan cache and exit points are two very powerful features available on the System i. Use them together to capture valuable database performance information in an automated, worry-free manner.

Gene Cobb is a DB2 Technology Specialist on IBM's ISV Enablement team for System i. He has worked on IBM midrange systems since 1988, with 10 years in the IBM Client Technology Center (CTC), IBM Rochester. While in the CTC, he assisted customers with application design and development using RPG, DB2 for i5/OS, CallPath/400, and Lotus Domino. His current responsibilities include providing consulting services to System i developers, with special emphasis in application and database modernization.

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: