Mercurial > hg > sqlex
changeset 3:5f1e1ac96aa7
stub works with SELECT
author | Jeff Hammel <k0scist@gmail.com> |
---|---|
date | Sat, 01 Apr 2017 09:19:22 -0700 |
parents | 63a75d318b06 |
children | b440206930ac |
files | sqlex/main.py sqlex/model.py |
diffstat | 2 files changed, 22 insertions(+), 10 deletions(-) [+] |
line wrap: on
line diff
--- 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() - -
--- 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], [])