27
Fri, Dec
0 New Articles

Practical RPG: BLOBs, CLOBs, and XML Part 2

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

You want to use LOBs in your RPG program but don't know where to start; read this article to find out how!

 

In the first article in this series, I identified situations where it is preferable to store stream data in a database rather than in the IFS. Specifically in my case, I had literally millions of stream files proliferating in the IFS and causing some real processing issues. My alternative was to store the stream files in the database. Implementing LOBs is not difficult, but it does require a number of steps, many of which may be unfamiliar to most of us.

Getting Started: Creating the Database

You need to do two separate things: define the database and access the data. I know this sounds simplistic, but they really are two different steps. The first step, creating a database in which to store the data, is relatively straightforward, but it does mean you have to use DDL to create the file rather than traditional DDS; this is the first break from tradition for many RPG programmers. If you're unfamiliar with SQL or DDL, you can find tons of articles right here on this site, including one or two of my own. Those and many more excellent SQL-related articles can be found in the Programming / SQL articles section.

 

Let's take a look at the DDL for a very simple file:

 

CREATE TABLE MYLIB/MYCLOBS

(MCKEY CHAR (20) NOT NULL WITH DEFAULT,

   MCDATA CLOB(1G) NOT NULL WITH DEFAULT)

 

Nothing to it! This creates a file with a 20-character key and a data field. The data field in this case is CLOB, and the length is nominally set to one gigabyte (1G). Don't worry too much about the size of the field; DB2 will allocate only the size of the data that you write. If you write a bunch of little CLOBs to the file, it won't get very big. On the other hand, one of my applications adds another gigabyte to its CLOB file every two or three days.

 

You may be wondering why I chose CLOB as my data type. Today, we have three data types available for large objects: BLOB, CLOB, and XML. In many ways, CLOBs are a subset of BLOBs: while BLOBs can contain any data type (including binary data like images), CLOBs are intended for pure character data and because of that they have a CCSID associated with them. This allows the data to be translated when it's accessed (especially between EBCDIC and ASCII or Unicode). XML data is an even more restrictive type: it expects the data to be well-formed XML and if it's not, you'll get an error when attempting to write to the database. An interesting thing about XML: you don't specify the length when you define the file:

 

CREATE TABLE MYLIB/MYXML

(MXKEY CHAR (20) NOT NULL WITH DEFAULT,

   MXXML XML NOT NULL WITH DEFAULT)

 

Okay, that's the database. One last thing: files with LOB data columns (that is, either BLOB, CLOB, or XML data types) must be journaled. No exceptions. You will get an error if you try to write to a file with LOBs and it's not journaled.

Adding a Record

When adding a record to a LOB database, you need to have your LOB data. There are two basic options: either the data is in a stream file on the IFS or the data is in memory. Interestingly enough, it's actually a little easier to add the data when it's already in a file on the IFS. You'll use an embedded SQL statement that looks something like this:

 

d iUnique       s             20a          

d iFileName     s           128a varying

 

/free

exec sql                                  

insert into MYLIB/MYCLOBS              

   (MCKEY, MCDATA)                        

values(                                

     :iUnique, get_clob_from_file(:iFileName))

with ur;
/end-free

 

In the code above, iUnique is the field used to store the unique key for the new record, while iFileName is the full qualified name of the data file in the IFS. The function get_clob_from_file is a built-in function provided by DB2, and corresponding functions exist for both BLOBs and XML. "But Joe," you might be saying, "don't you still have an IFS file?" And you would be correct! But in many cases you'll start with an IFS file. An example might be an EDI package in which the EDI communication portion just drops a file into your IFS. In that case, you would take the received file, write it to your database file, and then delete it from the IFS. Your IFS is de-cluttered, and the data is available to your application.

 

Adding data from memory is a little trickier, but only because you have to use the built-in SQL data type CLOB. Here's an example:

 

d iUnique       s             20a          

d iBufferPtr   s              *          

d iBufferLen   s             10i 0        

 

d MsgObj       s                  SQLTYPE( CLOB: 16000000)    

d Buffer       s               a len(16000000) based(pBuffer)

/free

pBuffer = iBufferPtr;                    

MsgObj_Data = %subst(Buffer:1:iBufferLen);

MsgObj_Len = iBufferLen;                

                                        

exec sql                                

   insert into MYLIB/MYCLOBS              

     (MCKEY, MCDATA)                        

   values(                              

     :wUnique,:MsgObj)    

   with ur;
/end-free

 

In this case, rather than passing in a file name, we instead pass in a pointer to the data and the length. This way, the data can be anywhere: in a variable in your RPG program, in a user space, whatever makes sense for your application. You build the LOB data however you want and then just pass in a pointer to the data and the data length. The first three lines of /free code then use those parameters to stuff the data into the CLOB variable.

 

SQLTYPE variables are a little unusual; when you define an SQLTYPE variable, it ends up creating a data structure with subfields that have odd naming conventions. Basically, it takes the name you define and then appends a suffix to identify the subfields. In the case above, the declaration of SQLTYPE MsgObj generates two variables, MsgObj_Data and MsgObj_Len. It's the program's responsibility to fill those generated fields with the CLOB data and the length. Personally, I would have preferred that the data structure be generated as a qualified data structure with subfields, but what's done works as long as you don't create your own fields ending in _Data or _Len (if you do, you'll get compile errors).

 

So, if you review the code, you'll see that I use a variable Buffer with a basing pointer pBuffer. I set the basing pointer to the address passed in and then use the %subst built-in function to extract the calling program's data and put it into the CLOB data field MsgObj_Data. I also store the length and then execute the SQL insert statement, which will perform the functional equivalent of the previous example. In both cases, you'll end up with a record in the file, and if you dump the file using DSPPFM, you'll see something like this:

 

MYKEYVAL           *POINTER

 

The first 20 characters are the key value, while the CLOB field is represented by the word *POINTER. One annoyance for green-screen programmers is that you cannot directly see CLOB data using traditional tools like DSPPFM or even DBU. Instead, you'll need to use either STRSQL and the CAST function or else view it through the IBM i Navigator. Generally speaking, as you move more into LOBs and SQL in general, I recommend getting acquainted with Navigator.

 

That's it for creating LOB data. In the next installment, we'll look at using that data and building an infrastructure for a practical application of the technology.

 

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: