#
# Read a file that was generated by the wrapper script that has the following
# format:
#
#    tablename <TAB> primaryKey
#
# Produce a report that shows the following fields for each input line:
#
#    table name
#    primary key
#    current maximum primary kay
#    remaining primary keys (max allowed by postgres minus the current max)
#

import sys 
import os
import db
import re

MAXINT = 2147483647

#db.setTrace()

inFileName = os.getenv('TEMPFILE')
outFileName = os.getenv('RPTFILE')

fpIn = open(inFileName, 'r')
fpOut = open(outFileName, 'w')

fpOut.write ('%-30s %-30s %-15s %-15s\n' % ('Table Name', 'Primary Key', 'Max Key', 'Keys Remaining'))
fpOut.write ('-'*30 + ' ' + '-'*30 + ' ' + '-'*15 + ' ' + '-'*15 + '\n')

line = fpIn.readline()
while line:
    [table, key] = re.split('\t', line[:-1])
    results = db.sql('select max(%s) from %s' % (key, table))
    if results[0]['max'] != None:
        maxKey = results[0]['max']
        fpOut.write('%-30s %-30s %15d %15d\n' % (table, key, maxKey, MAXINT-maxKey))
    line = fpIn.readline()

fpIn.close()
fpOut.close()
