20
Fri, Sep
3 New Articles

Export and Import Database Files

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

One of the shortcomings of RPG IV is the inability to access the input buffer of a database file between *MODULE objects. Of course, since modules are created from source code, this means there is no mechanism in RPG IV to export and import database files.

To solve this problem, IBM would need to add EXPORT and IMPORT keywords to the File description specification. Then, in MODULE-A, you would declare and then EXPORT the file, whereas in MODULE-B, you would declare and then IMPORT the file.

But first, let's review a little information about exporting and importing and what it means to us as RPG IV programmers.

Occasionally, it's necessary to make a field value available to other modules in a program. This may be required for a number of reasons. For example, when a field is used by many procedures, it's more practical to make it available via EXPORT than to pass it to a number of procedures as parameters.

What about when a file is shared between modules? What if I want to read a record from a file, call a procedure to manipulate the data in that file, and then return to the original main procedure?

If I declare the file in MODULE-A and MODULE-B and then do a read to the file in MODULE-A, when I call a procedure in MODULE-B, the input buffer in MODULE-A contains the record I just read, but the input buffer in MODULE-B is unchanged.

So if I want the current data from the input buffer in MODULE-A to be represented in MODULE-B, I would need to pass the key to the file to every procedure in MODULE-B and then access the database record using READ or CHAIN.

This can cause its own set of issues, such as a record lock conditions (the "deadly embrace") and latency problems with the data itself.

To resolve this problem, I came up with a workaround that seems to work in most cases. Since we are allowed to export only fields and data structures, we need to be able to move the data from the input buffer into a data structure and then EXPORT that data structure.

An easy way to do this is by declaring a data structure based on the database file in question. Use the EXTNAME keyword on the data structure declaration to ensure that the data structure is the same format as the database file. The EXTNAME keyword allows you to declare an externally described data structure based on a specific database file name, as shown below.

.....DName+++++++++++EUDS.......Length+TDc.Functions++++++++++++
     D myDS          E DS                  EXTNAME( myFile )

The E in column 22 and the EXTNAME keyword indicate that the data structure is externally described. This causes all the subfields in the data structure to be the same name, data type, and length as the fields in the external file.

Since the field names are the same as the external file, if we use the same name on the EXTNAME keyword as we do on the File specification, we will get a duplicate of the input buffer for that file in the form of a data structure.

Once the fields are part of a data structure, we can use the EXPORT keyword to make it available to other modules in this program:

.....DName+++++++++++EUDS.......Length+TDc.Functions++++++++++++
     D myDS          E DS                  EXTNAME( myFile )
     D                                     EXPORT

Since this data structure is exported, we can now import it into other modules. To do this, we declare the data structure exactly the way it is declared in the examples above; however, we use the IMPORT keyword instead of EXPORT, as shown below:

.....DName+++++++++++EUDS.......Length+TDc.Functions++++++++++++
     D myDS          E DS                  EXTNAME( myFile )
     D                                     IMPORT

To use this in a program, the program would be made up of multiple modules. The Entry module would contain the file declaration and an externally described file based on that same file. You may also want to consider using the PREFIX keyword on both the File and Data Structure declarations to avoid field name collisions in the secondary modules.

Figure 1 illustrates the source member for an Entry module of a program. The file CUSTSALES (line 5) is externally described and uses the PREFIX(CS_) keyword. This renames all the fields of that file to CS_xxxxxx, where xxxxxx is the original field name.

On line 8, the SALES data structure is declared as an externally described data structure based on the CUSTSALES file. I've also included the PREFIX(CS_) keyword to force all the subfield names to be renamed in that data structure.

The subfields of the SALES data structure will have the same names and attributes as those in the CUSTSALES file. Therefore, when a record is read from CUSTSALES, the fields in the SALES data structure will be populated with that information.

0001 H OPTION(*NODEBUGIO : *SRCSTMT)
0002  /IF DEFINED(*CRTBNDRPG)
0003 H DFTACTGRP(*NOACTGRP('COZZI')
0004  /ENDIF
0005 FCustSales UF   E             DISK    PREFIX(CS_)
     
0006 D DoSomething     PR    
0007 D  nOption                       5I 0 Const OPTIONS(*NOPASS)

0008 D Sales         E DS                  EXTNAME(CUSTSALES)
0009 D                                     PREFIX(CS_)
0010 D                                     EXPORT

0011 C                   READ      SALESREC
0012 C                   DOW       NOT %EOF
0013 C                   callp     DoSomething(0)
0014 C                   Update    SALESREC
0015 C                   READ      SALESREC
0016 C                   ENDDO
0017 C                   eval      *INLR = *ON

Figure 1: This Entry module exports the database field names.

To import that SALES data structure and thus the database fields into a secondary module, the data structure SALES needs to be declared and imported, like so:

D Sales         E DS                  EXTNAME(CUSTSALES)
D                                     PREFIX(CS_)
D                                     IMPORT

We use the PREFIX(CS_) keyword in this example not because it is required, but to be consistent. The full source for a secondary module is listed in Figure 2.

0001 H NOMAIN OPTION(*NODEBUGIO : *SRCSTMT)
0002  /IF DEFINED(*CRTBNDRPG)
0003 H DFTACTGRP(*NOACTGRP('COZZI')
0004  /ENDIF
     
0005 D DoSomething     PR    
0006 D  nOption                       5I 0 Const OPTIONS(*NOPASS)

0007 D Sales         E DS                  EXTNAME(CUSTSALES)
0008 D                                     PREFIX(CS_)
0009 D                                     IMPORT
     
0010 P DoSomething     B                   EXPORT 
0011 D DoSomething     PI    
0012 D  nOption                       5I 0 Const OPTIONS(*NOPASS)
       
0013 C                   eval      CS_AmtDue = CS_QTYORD * CS_UNITPRC
0014 C                   return
0015 P DoSomething     E

Figure 2: The secondary module imports the SALES data structure.

You can use the two source members from Figures 1 and 2 to test this technique. Compile those source members using the CRTRPGMOD command (PDM option 15). Then, use the CRTPGM command as illustrated below to create the program object.

CRTPGM  PGM(EXTEST)  MODULE(EXFILE  EXPROC)

To see if the program is working, start debug mode and set a breakpoint at line 15 in the EXFILE source member (Figure 1) or at line 13 or 14 in the EXPROC source member (Figure 2).

To compile the EXFILE module, you will need the CUSTSALES database file. Its DDS is listed below:

A          R SALESREC                  TEXT('Customer Sales') 
A            CUSTNO         7P 0
A            ITEMNO         5A
A            QTYORD         5P 0
A            UNITPRC        7P 2
A            AMTDUE         9P 2

Of course, you will need to add some data to the file using DFU or DBU/400.

Exporting an externally described data structure can help provide an easy way to share the input buffer of a database file between separately compiled modules.

Holiday Greetings

As we close 2003 with this issue and end our second full year of Midrange Developer, I'd like to thank all of our readers, who keep this job interesting and exciting. I'd also like to thank our advertisers for being so supportive this year, thereby allowing us to continue to deliver this publication to our readers free of charge. Next year, we are moving to a twice-monthly format. We will publish on the first and third Wednesdays of each month. You'll see tips from the group at RPG World and perhaps a surprise or two. In the meantime, have a safe and happy holiday season and a very happy new year.

Bob Cozzi has been programming in RPG since 1978. Since then, he has written many articles and several books, including The Modern RPG Language--the most widely used RPG reference manual in the world. Bob is also a very popular speaker at industry events such as RPG World and is the author of his own Web site and of the RPG ToolKit, an add-on library for RPG IV programmers.

BOB COZZI

Bob Cozzi is a programmer/consultant, writer/author, and software developer. His popular RPG xTools add-on subprocedure library for RPG IV is fast becoming a standard with RPG developers. His book The Modern RPG Language has been the most widely used RPG programming book for more than a decade. He, along with others, speaks at and produces the highly popular RPG World conference for RPG programmers.


MC Press books written by Robert Cozzi available now on the MC Press Bookstore.

RPG TnT RPG TnT
Get this jam-packed resource of quick, easy-to-implement RPG tips!
List Price $65.00

Now On Sale

The Modern RPG IV Language The Modern RPG IV Language
Cozzi on everything RPG! What more could you want?
List Price $99.95

Now On Sale

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: