# HG changeset patch # User Jeff Hammel # Date 1491070288 25200 # Node ID 3a7f515571dca13576efca014d3d404ff2b7e96b # Parent b440206930ac1a33b1eb6255360cc83fd1b119d3 can list column names diff -r b440206930ac -r 3a7f515571dc sqlex/main.py --- a/sqlex/main.py Sat Apr 01 09:28:49 2017 -0700 +++ b/sqlex/main.py Sat Apr 01 11:11:28 2017 -0700 @@ -7,6 +7,7 @@ # imports import argparse +import csv import os import sys from .model import SQLEx @@ -36,6 +37,9 @@ self.add_argument('--tables', '--list-tables', dest='list_tables', action='store_true', default=False, help="list tables and exit") + self.add_argument('--columns', '--list-columns', dest='list_columns', + action='store_true', default=False, + help="list columns in `table` and exit") self.options = None def parse_args(self, *args, **kw): @@ -52,6 +56,8 @@ except Exception as e: self.error("Could not open '{}': {}".format(options.db, e)) + if options.list_columns and not options.table: + self.error("`--list-columns` requires `table`") def main(args=sys.argv[1:]): """CLI""" @@ -74,5 +80,15 @@ retval = int(options.table not in tables) return retval + if options.table: + # ensure selected table exists + if options.table not in db.tables(): + parser.error("No table '{}' in {} tables:\n{}".format(options.table, options.db, ', '.join(db.tables()))) + + if options.list_columns: + # list columns and return + print ('\n'.join(db.columns(options.table).keys())) + return + if __name__ == '__main__': main() diff -r b440206930ac -r 3a7f515571dc sqlex/model.py --- a/sqlex/model.py Sat Apr 01 09:28:49 2017 -0700 +++ b/sqlex/model.py Sat Apr 01 11:11:28 2017 -0700 @@ -1,4 +1,10 @@ import sqlite3 +from collections import OrderedDict + +class NoTableException(Exception): + def __init__(self, table): + Exception.__init__(self, "Table '{}' does not exist".format(table)) + class SQLEx(object): """ @@ -31,3 +37,31 @@ sql = "SELECT name FROM sqlite_master WHERE type='table';" tables = self(sql) return sum([list(item) for item in tables], []) + + def ensure_table(self, table): + """ + ensure that `table` exists; + if not, raise 1NoTableException + """ + + if table not in self.tables(): + raise NoTableException(table) + + def columns(self, table): + """ + returns columns for `table` + """ + + self.ensure_table(table) + + sql = "PRAGMA table_info({})".format(table) + data = self(sql) + # (Pdb) pp(columns) + # [(0, u'ROWID', u'INTEGER', 0, None, 1), + # (1, u'address', u'TEXT', 0, None, 0), + # (2, u'date', u'INTEGER', 0, None, 0), + NAME_INDEX = 1 + TYPE_INDEX = 2 + return OrderedDict([(row[NAME_INDEX], row[TYPE_INDEX]) + for row in data]) +