view sqlex/main.py @ 4:b440206930ac

stub table optional positional argument
author Jeff Hammel <k0scist@gmail.com>
date Sat, 01 Apr 2017 09:28:49 -0700
parents 5f1e1ac96aa7
children 3a7f515571dc
line wrap: on
line source

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
sql(ite) explorer/exporter
"""

# imports
import argparse
import os
import sys
from .model import SQLEx


def ensure_dir(directory):
    """ensure a directory exists"""
    if os.path.exists(directory):
        if not os.path.isdir(directory):
            raise OSError("Not a directory: '{}'".format(directory))
        return directory
    os.makedirs(directory)
    return directory


class SQLExParser(argparse.ArgumentParser):
    """CLI option parser"""

    def __init__(self, **kwargs):
        kwargs.setdefault('formatter_class', argparse.RawTextHelpFormatter)
        kwargs.setdefault('description', __doc__)
        argparse.ArgumentParser.__init__(self, **kwargs)
        self.add_argument('db',
                          help="sqlite `.db` file")
        self.add_argument('table', nargs='?',
                          help="table to operate on")
        self.add_argument('--tables', '--list-tables', dest='list_tables',
                          action='store_true', default=False,
                          help="list tables and exit")
        self.options = None

    def parse_args(self, *args, **kw):
        options = argparse.ArgumentParser.parse_args(self, *args, **kw)
        self.validate(options)
        self.options = options
        return options

    def validate(self, options):
        """validate options"""

        try:
            open(options.db).close()
        except Exception as e:
            self.error("Could not open '{}': {}".format(options.db, e))


def main(args=sys.argv[1:]):
    """CLI"""

    # parse command line options
    parser = SQLExParser()
    options = parser.parse_args(args)

    # connect to database
    db = SQLEx(options.db)

    if options.list_tables:
        # list tables and return
        # if `table` argument is provided, exit 1
        # if not available.  Otherwise exit 0
        tables = db.tables()
        print ('\n'.join(tables))
        retval = 0
        if options.table:
            retval = int(options.table not in tables)
        return retval

if __name__ == '__main__':
    main()