pgtoolkit/tools/tablediff.py
changeset 100 d6088dba8fea
parent 93 b72591087495
child 101 2a2d0d5df03b
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pgtoolkit/tools/tablediff.py	Tue May 06 18:37:41 2014 +0200
@@ -0,0 +1,55 @@
+from pgtoolkit import toolbase, pgmanager, pgdatadiff
+from pgtoolkit.toolbase import SrcDstTablesTool
+from pycolib.ansicolor import highlight, BOLD, YELLOW
+
+
+class TableDiffTool(toolbase.SrcDstTablesTool):
+
+    """
+    Print differencies between data in tables.
+
+    Requirements:
+    * Source table must have defined PRIMARY KEY.
+    * Destination table must contain all columns from source table.
+      Order is not important.
+
+    """
+
+    def __init__(self):
+        SrcDstTablesTool.__init__(self, name='tablediff', desc=self.__doc__, allow_reverse=True)
+        self.parser.add_argument('--sql', action='store_true', help='Output is SQL script.')
+        self.parser.add_argument('--rowcount', action='store_true', help='Compare number of rows.')
+
+    def main(self):
+        srcconn = self.pgm.get_conn('src')
+        dstconn = self.pgm.get_conn('dst')
+
+        dd = pgdatadiff.PgDataDiff(srcconn, dstconn)
+
+        for srcschema, srctable, dstschema, dsttable in self.tables():
+            print('-- Diff from [%s] %s.%s to [%s] %s.%s' % (
+                self.args.src, srcschema, srctable,
+                self.args.dst, dstschema, dsttable))
+
+            if self.args.rowcount:
+                with self.pgm.cursor('src') as curs:
+                    curs.execute('''SELECT count(*) FROM "%s"."%s"''' % (srcschema, srctable))
+                    srccount = curs.fetchone()[0]
+                with self.pgm.cursor('dst') as curs:
+                    curs.execute('''SELECT count(*) FROM "%s"."%s"''' % (dstschema, dsttable))
+                    dstcount = curs.fetchone()[0]
+                if srccount != dstcount:
+                    print(highlight(1, BOLD | YELLOW), "Row count differs: src=%s dst=%s" % (srccount, dstcount), highlight(0), sep='')
+                continue
+
+            dd.settable1(srctable, srcschema)
+            dd.settable2(dsttable, dstschema)
+
+            if self.args.sql:
+                dd.print_patch()
+            else:
+                dd.print_diff()
+
+
+cls = TableDiffTool
+