Monday, June 8, 2009

grails jtopen plugin 0.2 is out: groovy record level access

GORM is a fantastic tool, it's especially good with tables it creates. When you have legacy tables (without generated IDs, without version field, with composite keys), it's not that good.
Of course, you can fall back to groovy sql support which is very good, but, once again, with legacy tables, SQL is not always the ideal tool.
If you spent several years coding in RPG, you probably sometimes miss the classical but so efficient traditional RPG file access, as I do. Of course it's possible to use the toolbox record level access, but it needs even more boilerplate code than bare metal JDBC.
That's where the jtopen grails plugin 0.2 new feature comes in handy: "groovy record level access".
You can now access files from groovy almost like you would do from RPG:
def file = ibmI.getFile(name:"FILE")
file.setll("KEY1","SKEY1")
def rec = file.reade("KEY1")
while(rec != null){
// Do something with rec...
rec = file.reade("KEY1")
}

Let's have a closer look:
def file = ibmI.getFile(name:"FILE")
This will create a file object, reading the file "FILE". By default, the file will be opened read only, it will be accessed by key if it has a key, otherwise, it will be accessed by arrival order.

file.setll("KEY1","SKEY1")
As the RPG SETLL opcode, this will set the cursor position with the given composite key.

def rec = file.reade("KEY1")
This will read the next record with the partial key equals to "KEY1".

while(rec != null){
// Do something with rec...
rec = file.reade("KEY1")
}
These lines will iterate through the records with the partial key equals to "KEY1".

RPG coders will be happy to have the read, readp, chain, setll, setgt, reade, readpe, write, update and delete methods that are almost identical to the RPG opcodes.

The record object returned by the read* and chain are dynamic POGO with properties from the file fields (case insensitive). For example, if your file has an ITEMCOD field, it can be accessed by rec.itemcode, rec.ItemCod or rec.ITEMCOD or even rec.iTeMcOd.

You can also use groovy iteration methods (each, eachWithIndex, collect, any...) on file objects. In this case, the iteration will process the next records from the current cursor position. It's possible to process the previous records from the current position with:
file.reverse.each { // Do something with the record }

If the file is accessed by key, it is also possible to process a subset of the file based on the key, for example:
file.setll("KEY1") // Iteration function always start from the current cursor position
file.key("KEY1").each { // Do something with the record }

To process the records in reverse order:
file.setgt("KEY1")
file.reverseKey("KEY1").each { // Do something with the record }

For the latest jtopen plugin release, please go to the plugin page.

No comments:

Post a Comment