# HG changeset patch # User Jeff Hammel # Date 1491075328 25200 # Node ID 22fbe50d92e8f811ef17715e13f2949964bbf995 # Parent 3a7f515571dca13576efca014d3d404ff2b7e96b can now export a table diff -r 3a7f515571dc -r 22fbe50d92e8 README.txt --- a/README.txt Sat Apr 01 11:11:28 2017 -0700 +++ b/README.txt Sat Apr 01 12:35:28 2017 -0700 @@ -1,8 +1,17 @@ sqlex -=========== +===== sql(ite) explorer/exporter + +Examples +-------- + +Listing all columns in all tables:: + + # sqlex --tables ~/docs/sms.db | while read line; do echo "# ${line}"; sqlex --columns ~/docs/sms.db ${line}; echo; done + + ---- Jeff Hammel diff -r 3a7f515571dc -r 22fbe50d92e8 sqlex/main.py --- a/sqlex/main.py Sat Apr 01 11:11:28 2017 -0700 +++ b/sqlex/main.py Sat Apr 01 12:35:28 2017 -0700 @@ -40,6 +40,8 @@ self.add_argument('--columns', '--list-columns', dest='list_columns', action='store_true', default=False, help="list columns in `table` and exit") + self.add_argument('-o', '--output', + help="output to directory (if `table` not given), or filename or stdout by default") self.options = None def parse_args(self, *args, **kw): @@ -56,6 +58,11 @@ except Exception as e: self.error("Could not open '{}': {}".format(options.db, e)) + if not any((options.output, + options.list_tables, + options.table)): + self.error("`--output` directory must be specified to output entire database") + if options.list_columns and not options.table: self.error("`--list-columns` requires `table`") @@ -90,5 +97,18 @@ print ('\n'.join(db.columns(options.table).keys())) return + if options.table: + # output table + + if options.output: + with open(options.output, 'w') as f: + db.table2csv(options.table, f) + else: + db.table2csv(options.table, sys.stdout) + sys.stdout.flush() + else: + # output entire db to CSV files in directory + raise NotImplementedError('TODO') + if __name__ == '__main__': main() diff -r 3a7f515571dc -r 22fbe50d92e8 sqlex/model.py --- a/sqlex/model.py Sat Apr 01 11:11:28 2017 -0700 +++ b/sqlex/model.py Sat Apr 01 12:35:28 2017 -0700 @@ -1,3 +1,4 @@ +import csv import sqlite3 from collections import OrderedDict @@ -65,3 +66,26 @@ return OrderedDict([(row[NAME_INDEX], row[TYPE_INDEX]) for row in data]) + + def table2csv(self, table, fp): + """ + export `table` to `fp` file object in CSV format + """ + # TODO: option to add column headers + + # sanity + self.ensure_table(table) + + # get whole table + sql = 'select * from {table}'.format(table=table) + rows = self(sql) + + # decode unicde because the CSV module won't + # http://stackoverflow.com/questions/22733642/how-to-write-a-unicode-csv-in-python-2-7 + rows = [[unicode(s).encode("utf-8") for s in row] + for row in rows] + + # write + writer = csv.writer(fp) + writer.writerows(rows) +