Database to HL7

Test: Code for the diff Module

This is a utility module called ‘diff’ that returns a nice human readable list of differences between two trees.

If you have not already done so you need to create a “diff” module in your project, and paste this code into it.

diff={}

local function trace(a,b,c,d) return end

local function DisplayParent(Parent)
   local P = ''
   local Root = Parent.Root
   local i = 1
   while i <= #Parent.Address do
      if Root:nodeType() == 'segment_repeated' then
         P = P..Root:nodeName()..'['..Parent.Address[i]..']'
         Root = Root[Parent.Address[i]][Parent.Address[i+1]]
         i = i + 2
      else
         if Root:nodeType() == 'segment'  then
            P = P..Root:nodeName()
         elseif Root:nodeType() == 'message' then
            P = P..Root:nodeName()..'.'
         else
            P = P..'['..Parent.Address[i-1]..']'
         end
         Root = Root[Parent.Address[i]] 
         i = i + 1
      end
   end
   return P
end

local function Compare(Orig, New, List, Parent)
   trace(List)
   if #Orig ~= #New then
      List[#List+1] = DisplayParent(Parent)..Orig:nodeName()..' has different number of children.'
   end
   for i=1,#Orig do
      Parent.Address[#Parent.Address+1] = i
      if #Orig[i] == 0 then
         trace(Orig[i]:nodeName())
         if Orig[i]:isNull() then
            if New[i]:childCount() == 0 then
               if not New[i]:isNull() then
                  List[#List+1] = New[i]:nodeName()..' should be empty but it is now '..New[i]
               end
            end
         elseif Orig[i]:nodeValue() ~= New[i]:nodeValue() then
            List[#List+1] = DisplayParent(Parent)..'['..i..'] was |'..
               Orig[i]:nodeValue()..'| but is now |'..New[i]:nodeValue().."|"
         end
      else
         Compare(Orig[i], New[i], List, Parent)
      end
      Parent.Address[#Parent.Address] = nil
   end
   return List
end

local function CheckHl7Message(P, Usage)
   if type(P) ~= 'userdata' or P:nodeType() ~= 'message'  then
      error(Usage,3)   
   end   
end

local DiffUsage=[[
Compares two HL7 messages for differences

Expects two HL7 strings and a VMD as 
arguments and returns a table listing
differences - if any.

 e.g. local List = diff.Compare(Orig, New)
]]

function diff.Compare(Orig, New, Vmd)
   Orig = hl7.parse{data=Orig, vmd=Vmd}    
   New  = hl7.parse{data=New, vmd=Vmd}    
   CheckHl7Message(Orig, DiffUsage)
   CheckHl7Message(New, DiffUsage)
   return Compare(Orig, New, {}, {Root=Orig, Address={}})
end

Next Step?

The final step is to tweak the code and the VMD file to cope with the last two errors.

Leave A Comment?