diff sqlex/model.py @ 6:22fbe50d92e8

can now export a table
author Jeff Hammel <k0scist@gmail.com>
date Sat, 01 Apr 2017 12:35:28 -0700
parents 3a7f515571dc
children 834b920ae345
line wrap: on
line diff
--- 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)
+