#!/usr/bin/env python3
# script to count records in each table in an sql database
import pymysql as mysql

def parse_arguments():
    from argparse import ArgumentParser
    import getpass as gp

    parser = ArgumentParser(description='''
            count the records in each table of a mysql database
            and print the result in the form TABLE: COUNT''')

    parser.add_argument('-H', '--host',
                        help='connect to host.',
                        default='localhost',
                        type=str)
    parser.add_argument('-P', '--port',
                        help='port number to use for connection.',
                        default=3306,
                        type=int)
    parser.add_argument('-u', '--user',
                        help='username login if not the current user',
                        default=gp.getuser(),
                        type=str)
    parser.add_argument('-p',
                        action='store_true',
                        help='prompt the user for password')
    parser.add_argument('databases',
                        help='database to connect.',
                        default=None,
                        nargs='*')

    args = parser.parse_args()
    if args.p:
        args.passwd = gp.getpass(
            prompt='Password for mysql://%s@%s: ' % (args.user, args.host))
    else:
        args.passwd = None
    return args


def get_connection(host, user, port, passwd):
    try:
        return mysql.connect(host=host,
                             user=user,
                             port=port,
                             passwd=passwd)
    except mysql.err.OperationalError:
        exit('Error: Incorrect Password')


def table_count(connection, db):
    counts = {}
    try:
        crsr = connection.cursor()
        crsr.execute('use %s' % db)
        crsr.execute('show tables')
        tables = crsr.fetchall()
        for table in tables:
            crsr.execute('select count(*) from %s' % table[0])
            counts[table[0]] = crsr.fetchone()[0]
        return counts
    except Exception as err:
        exit('Error: %s' % str(err))


### Main Thread ###
if __name__ == '__main__':
    args = parse_arguments()
    connection = get_connection(host=args.host,
                                user=args.user,
                                port=args.port,
                                passwd=args.passwd)
    try:
        for database in args.databases:
            counts = table_count(connection, database)
            for table in counts.keys():
                print('%s.%s: %s' % (database, table, counts[table]))

    finally:
        connection.close()
