# HG changeset patch # User Jeff Hammel # Date 1491063562 25200 # Node ID 5f1e1ac96aa7b94e30f7d2c98f2db1dd39106eaa # Parent 63a75d318b06d20d1ef9d93a69ed53eb0ad03bfd stub works with SELECT diff -r 63a75d318b06 -r 5f1e1ac96aa7 sqlex/main.py --- a/sqlex/main.py Sat Apr 01 08:44:42 2017 -0700 +++ b/sqlex/main.py Sat Apr 01 09:19:22 2017 -0700 @@ -8,8 +8,9 @@ # imports import argparse import os -import sqlite3 import sys +from .model import SQLEx + def ensure_dir(directory): """ensure a directory exists""" @@ -30,7 +31,9 @@ argparse.ArgumentParser.__init__(self, **kwargs) self.add_argument('db', help="sqlite `.db` file") - self.add_argument( + 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): @@ -43,7 +46,7 @@ """validate options""" try: - open(options.db) + open(options.db).close() except Exception as e: self.error("Could not open '{}': {}".format(options.db, e)) @@ -55,7 +58,13 @@ parser = SQLExParser() options = parser.parse_args(args) + # connect to database + db = SQLEx(options.db) + + if options.list_tables: + tables = db.tables() + print ('\n'.join(tables)) + return + if __name__ == '__main__': main() - - diff -r 63a75d318b06 -r 5f1e1ac96aa7 sqlex/model.py --- a/sqlex/model.py Sat Apr 01 08:44:42 2017 -0700 +++ b/sqlex/model.py Sat Apr 01 09:19:22 2017 -0700 @@ -11,9 +11,13 @@ self.conn = sqlite3.connect(self.db) def __call__(self, sql, *args): - c = conn.cursor() + c = self.conn.cursor() c.execute(sql, args) - c.commit() + self.conn.commit() + try: + return c.fetchall() + except Exception as e: + raise e def __del__(self): self.conn.close() @@ -24,7 +28,6 @@ """ # http://stackoverflow.com/questions/82875/how-to-list-the-tables-in-an-sqlite-database-file-that-was-opened-with-attach - sql = "SELECT name FROM dbname.sqlite_master WHERE type='table';" + sql = "SELECT name FROM sqlite_master WHERE type='table';" tables = self(sql) - return tables - + return sum([list(item) for item in tables], [])