Search code examples
pythonsqldifflib

How to compare SQL files and Packages in Python and return True or False?


So, I've tried using Differ from difflib and also filecmp. Here's what I've done so far:

def comparesqlpkg(pkg1Name, pkg2Name):
    d = Differ()
    if d.compare(open(pkg1Name, 'r').readlines(), open(pkg2Name, 'r').readlines()):
    #if filecmp.cmp(pkg1Name, pkg2Name):
        print("SAME content.")
        return True
    else:
        print("DIFFERENT content.")
        return False

I want the code to check the two files and see if they are the same and return True/False. The thing is that some reformatting can occur at Oracle's end that would modify the formatting of the second file. I need it to be in such a way that it would ignore that so that both scripts that run the same code (different tab spaces,etc) would still produce the same result.

Sample SQL1 (local repo):

function fn_get_number(
 in_src_amt in varchar2)
RETURN NUMBER;

Sample SQL2 (reformatted by ORACLE db):

FUNCTION FN_GET_NUMBER
(
     IN_SCR_AMT        IN        VARCHAR2
)
RETURN NUMBER;

Solution

  • Remove all spaces and newlines, convert to lower case, and compare.

    def transform(s):
        return s.replace(' ','').replace('\n','').lower()
    ...
    if transform(open(pkg1name,'r').read()) == transform(open(pkg2name,'r').read()):