comparison sqlex/main.py @ 5:3a7f515571dc

can list column names
author Jeff Hammel <k0scist@gmail.com>
date Sat, 01 Apr 2017 11:11:28 -0700
parents b440206930ac
children 22fbe50d92e8
comparison
equal deleted inserted replaced
4:b440206930ac 5:3a7f515571dc
5 sql(ite) explorer/exporter 5 sql(ite) explorer/exporter
6 """ 6 """
7 7
8 # imports 8 # imports
9 import argparse 9 import argparse
10 import csv
10 import os 11 import os
11 import sys 12 import sys
12 from .model import SQLEx 13 from .model import SQLEx
13 14
14 15
34 self.add_argument('table', nargs='?', 35 self.add_argument('table', nargs='?',
35 help="table to operate on") 36 help="table to operate on")
36 self.add_argument('--tables', '--list-tables', dest='list_tables', 37 self.add_argument('--tables', '--list-tables', dest='list_tables',
37 action='store_true', default=False, 38 action='store_true', default=False,
38 help="list tables and exit") 39 help="list tables and exit")
40 self.add_argument('--columns', '--list-columns', dest='list_columns',
41 action='store_true', default=False,
42 help="list columns in `table` and exit")
39 self.options = None 43 self.options = None
40 44
41 def parse_args(self, *args, **kw): 45 def parse_args(self, *args, **kw):
42 options = argparse.ArgumentParser.parse_args(self, *args, **kw) 46 options = argparse.ArgumentParser.parse_args(self, *args, **kw)
43 self.validate(options) 47 self.validate(options)
50 try: 54 try:
51 open(options.db).close() 55 open(options.db).close()
52 except Exception as e: 56 except Exception as e:
53 self.error("Could not open '{}': {}".format(options.db, e)) 57 self.error("Could not open '{}': {}".format(options.db, e))
54 58
59 if options.list_columns and not options.table:
60 self.error("`--list-columns` requires `table`")
55 61
56 def main(args=sys.argv[1:]): 62 def main(args=sys.argv[1:]):
57 """CLI""" 63 """CLI"""
58 64
59 # parse command line options 65 # parse command line options
72 retval = 0 78 retval = 0
73 if options.table: 79 if options.table:
74 retval = int(options.table not in tables) 80 retval = int(options.table not in tables)
75 return retval 81 return retval
76 82
83 if options.table:
84 # ensure selected table exists
85 if options.table not in db.tables():
86 parser.error("No table '{}' in {} tables:\n{}".format(options.table, options.db, ', '.join(db.tables())))
87
88 if options.list_columns:
89 # list columns and return
90 print ('\n'.join(db.columns(options.table).keys()))
91 return
92
77 if __name__ == '__main__': 93 if __name__ == '__main__':
78 main() 94 main()