Mercurial > hg > sqlex
comparison sqlex/model.py @ 5:3a7f515571dc
can list column names
author | Jeff Hammel <k0scist@gmail.com> |
---|---|
date | Sat, 01 Apr 2017 11:11:28 -0700 |
parents | 5f1e1ac96aa7 |
children | 22fbe50d92e8 |
comparison
equal
deleted
inserted
replaced
4:b440206930ac | 5:3a7f515571dc |
---|---|
1 import sqlite3 | 1 import sqlite3 |
2 from collections import OrderedDict | |
3 | |
4 class NoTableException(Exception): | |
5 def __init__(self, table): | |
6 Exception.__init__(self, "Table '{}' does not exist".format(table)) | |
7 | |
2 | 8 |
3 class SQLEx(object): | 9 class SQLEx(object): |
4 """ | 10 """ |
5 sqlite model | 11 sqlite model |
6 https://docs.python.org/2/library/sqlite3.html | 12 https://docs.python.org/2/library/sqlite3.html |
29 # http://stackoverflow.com/questions/82875/how-to-list-the-tables-in-an-sqlite-database-file-that-was-opened-with-attach | 35 # http://stackoverflow.com/questions/82875/how-to-list-the-tables-in-an-sqlite-database-file-that-was-opened-with-attach |
30 | 36 |
31 sql = "SELECT name FROM sqlite_master WHERE type='table';" | 37 sql = "SELECT name FROM sqlite_master WHERE type='table';" |
32 tables = self(sql) | 38 tables = self(sql) |
33 return sum([list(item) for item in tables], []) | 39 return sum([list(item) for item in tables], []) |
40 | |
41 def ensure_table(self, table): | |
42 """ | |
43 ensure that `table` exists; | |
44 if not, raise 1NoTableException | |
45 """ | |
46 | |
47 if table not in self.tables(): | |
48 raise NoTableException(table) | |
49 | |
50 def columns(self, table): | |
51 """ | |
52 returns columns for `table` | |
53 """ | |
54 | |
55 self.ensure_table(table) | |
56 | |
57 sql = "PRAGMA table_info({})".format(table) | |
58 data = self(sql) | |
59 # (Pdb) pp(columns) | |
60 # [(0, u'ROWID', u'INTEGER', 0, None, 1), | |
61 # (1, u'address', u'TEXT', 0, None, 0), | |
62 # (2, u'date', u'INTEGER', 0, None, 0), | |
63 NAME_INDEX = 1 | |
64 TYPE_INDEX = 2 | |
65 return OrderedDict([(row[NAME_INDEX], row[TYPE_INDEX]) | |
66 for row in data]) | |
67 |