21
Sat, Dec
3 New Articles

TechTip: Using SQL with IFS Text Files, Part 2

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

In Part 1 of this series, I began a discussion on the growing need to have programmatic mechanisms to access the text data within IFS files. I illustrated a scalar user-defined function (UDF) called FileToClob that returns the contents of an IFS file as a single character large object (CLOB) column. While this method has the advantage of granting access to the stream file's entire contents in a single column, there may be occasions when you'd want to process a file one line at a time. A user-defined table function (UDTF) is a perfect fit for this task (V5R2 is required).

Table functions offer the ability to return a two-dimensional array structure as though it were a set of rows and columns from a table. The column structure of a table function must be pre-defined, but there is no limit to the number of rows that may be returned. RPG program ReadIFSFR is designed to serve as a table function that reads an IFS text file and returns its contents one row at a time.

Here is a sample Select statement using ReadIFSFR:

Select *
  From Table(ReadIFSFR('/home/mytextfile.txt',
                       X'0D25')) As Text


Here is the CREATE FUNCTION statement required to register the program with SQL:

Create Function xxxxx/ReadIFSFR
 (FileName  VarChar(128),
  EOL_Delim VarChar(10))
Returns Table
 (Line_No   Integer,
  Cont_No   Integer,
  LineText  VarChar(2048))
External
Language RPGLE
Disallow Parallel
Returns Null On Null Input
Parameter Style DB2SQL


Table function ReadIFSFR accepts two parameters: file name and row delimiter. Parameter "file name" is a fully qualified file name to a particular file on the IFS. (If you're using the QNTC file system, this can even include reading text files directly from a Windows share.) The "row delimiter" parameter is a value that informs the program how to parse the data into rows. The following table shows a list of the three most common row delimiters used in a text file:

Common Line Delimiters
EBCDIC Value
CR
X'0D'
LF
X'25'
CRLF
X'0D25'


In case you're wondering why I've shown the EBCDIC delimiter values rather than the ASCII values (since most IFS text files will probably be encoded in some form of ASCII), the answer is because the IFS APIs will automatically return the data to the RPG program in EBCDIC format. Therefore, the RPG program will need to know the EBCDIC value for the required delimiter.

When executed in a Select, the table function returns three columns: line number (Line_No), continuation number (Cont_No), and line text (LineText). The line number is a simple counter indicating where particular data is located in a file. The actual file data is returned in column line text. A maximum width of 2048 characters per line is allowed. If a single line exceeds this limit, the data will be "wrapped" to a second line. The continuation number column is used to indicate if a line has been wrapped so that the line counter column remains accurate.

How It Works

Programs designed to act as SQL table functions have logic that can be divided into three phases: open, fetch, and close. Each phase is done in response to a request from the database manager.

During the open phase, an IFS file is opened using the Open API. During the fetch phase, the table function calls the Read API to read the data. The function's output columns are populated with data representing a single row being returned. The fetch phase is repeated until the program indicates to SQL that there is no more data. It does this by setting the SQL state variable to '02000' (end of data). Finally, during the close phase, the IFS file is closed, and the LR indicator is set on so that the program will end.

I often use this table function for easily reading import files and application setting (INI) files. For example, a user may create a simple text file containing a list of item numbers to be updated in a file. Rather than creating a temporary table and copying the IFS file into the table, I simply query the text file directly:

Update ItemMaster
   Set Price=0
 Where Item In 
      (Select Left(LineText,20) As Item
         From Table(ReadIFSFR('/tmp/Bad_Items.txt')) A)


Don't forget that a table function needs to be assigned a correlation name (A).

Interestingly, a source member can be read like a text file using the qsys.lib file system and specifying a CR/LF delimiter:

Select *
  From Table(ReadIFSFR(
  '/qsys.lib/sourcelib.lib/qsource.file/readifsfr.mbr',
  X'0D25')) A


Note that table functions are read only so you can't issue an update against this member!
When using multi-membered source files with SELECT statements, this method provides an alternative to using the CREATE ALIAS command or issuing an OVRDBF command.

Don't stop with this example. UDTFs can be designed to work with other types of text files--such as fixed record length or markup (XML, HTML) files--and return the data in a tabular format. A further complement to these text functions would be a directory API wrapped with a table function so that SQL has dynamic access to all the entries on the IFS.

The IFS' growing popularity will cause programmers to seek easier ways to access its data. Indeed, Microsoft has long offered the Windows world programmatic access to many kinds of text files with its ODBC text driver. The ability to extend SQL with scalar and table functions allows iSeries programmers to join the game by applying SQL's searching, joining, and sorting capabilities to IFS data.

References

For a detailed explanation of how to write an external table function, see "Query Remote Database Tables from the iSeries using SQL and Java." Although the article uses Java, the programming concepts are the same, and explanations of the SQL keywords are relevant to other languages.

Also see chapter 13, "Writing User-Defined Functions," of the SQL Programming Concepts guide.

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: