Skip to content

Commit

Permalink
Make .indexes compatible with older SQLite versions (#1)
Browse files Browse the repository at this point in the history
Older SQLite versions return a different set of columns from the PRAGMA we are using.
  • Loading branch information
Simon Willison committed Aug 2, 2018
1 parent 0aa2829 commit 741e8f7
Showing 1 changed file with 19 additions and 3 deletions.
22 changes: 19 additions & 3 deletions sqlite_utils/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,11 @@ def table_names(self):
def tables(self):
return [self[name] for name in self.table_names]

def execute_returning_dicts(self, sql, params=None):
cursor = self.conn.execute(sql, params or tuple())
keys = [d[0] for d in cursor.description]
return [dict(zip(keys, row)) for row in cursor.fetchall()]

def create_table(self, name, columns, pk=None, foreign_keys=None):
foreign_keys = foreign_keys or []
foreign_keys_by_name = {fk[0]: fk for fk in foreign_keys}
Expand Down Expand Up @@ -127,12 +132,23 @@ def schema(self):
def indexes(self):
sql = 'PRAGMA index_list("{}")'.format(self.name)
indexes = []
for row in list(self.db.conn.execute(sql).fetchall()):
column_sql = 'PRAGMA index_info("{}")'.format(row[1])
for row in self.db.execute_returning_dicts(sql):
index_name = row["name"]
index_name_quoted = (
'"{}"'.format(index_name)
if not index_name.startswith('"')
else index_name
)
column_sql = "PRAGMA index_info({})".format(index_name_quoted)
columns = []
for seqno, cid, name in self.db.conn.execute(column_sql).fetchall():
columns.append(name)
indexes.append(Index(*(row + (columns,))))
row["columns"] = columns
# These coluns may be missing on older SQLite versions:
for key, default in {"origin": "c", "partial": 0}.items():
if key not in row:
row[key] = default
indexes.append(Index(**row))
return indexes

def create(self, columns, pk=None, foreign_keys=None):
Expand Down

0 comments on commit 741e8f7

Please sign in to comment.