comparison 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
comparison
equal deleted inserted replaced
5:3a7f515571dc 6:22fbe50d92e8
1 import csv
1 import sqlite3 2 import sqlite3
2 from collections import OrderedDict 3 from collections import OrderedDict
3 4
4 class NoTableException(Exception): 5 class NoTableException(Exception):
5 def __init__(self, table): 6 def __init__(self, table):
63 NAME_INDEX = 1 64 NAME_INDEX = 1
64 TYPE_INDEX = 2 65 TYPE_INDEX = 2
65 return OrderedDict([(row[NAME_INDEX], row[TYPE_INDEX]) 66 return OrderedDict([(row[NAME_INDEX], row[TYPE_INDEX])
66 for row in data]) 67 for row in data])
67 68
69
70 def table2csv(self, table, fp):
71 """
72 export `table` to `fp` file object in CSV format
73 """
74 # TODO: option to add column headers
75
76 # sanity
77 self.ensure_table(table)
78
79 # get whole table
80 sql = 'select * from {table}'.format(table=table)
81 rows = self(sql)
82
83 # decode unicde because the CSV module won't
84 # http://stackoverflow.com/questions/22733642/how-to-write-a-unicode-csv-in-python-2-7
85 rows = [[unicode(s).encode("utf-8") for s in row]
86 for row in rows]
87
88 # write
89 writer = csv.writer(fp)
90 writer.writerows(rows)
91