Skip to content

Commit

Permalink
table.use_rowid introspection property, closes #285
Browse files Browse the repository at this point in the history
  • Loading branch information
simonw committed Jun 19, 2021
1 parent dc94f4b commit 5b25794
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 0 deletions.
13 changes: 13 additions & 0 deletions docs/python-api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1549,6 +1549,19 @@ The ``.pks`` property returns a list of strings naming the primary key columns f
>>> db["PlantType"].pks
['id']
If a table has no primary keys but is a `rowid table <https://www.sqlite.org/rowidtable.html>`__, this property will return ``['rowid']``.
.. _python_api_introspection_use_rowid:
.use_rowid
----------
Almost all SQLite tables have a ``rowid`` column, but a table with no explicitly defined primary keys must use that ``rowid`` as the primary key for identifying individual rows. The ``.use_rowid`` property checks to see if a table needs to use the ``rowid`` in this way - it returns ``True`` if the table has no explicitly defined primary keys and ``False`` otherwise.
>>> db["PlantType"].use_rowid
False
.. _python_api_introspection_foreign_keys:
.foreign_keys
Expand Down
4 changes: 4 additions & 0 deletions sqlite_utils/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -809,6 +809,10 @@ def pks(self):
names = ["rowid"]
return names

@property
def use_rowid(self):
return not any(column for column in self.columns if column.is_pk)

def get(self, pk_values):
if not isinstance(pk_values, (list, tuple)):
pk_values = [pk_values]
Expand Down
8 changes: 8 additions & 0 deletions tests/test_introspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -237,3 +237,11 @@ def test_virtual_table_using(sql, expected_name, expected_using):
db = Database(memory=True)
db.execute(sql)
assert db[expected_name].virtual_table_using == expected_using


def test_use_rowid():
db = Database(memory=True)
db["rowid_table"].insert({"name": "Cleo"})
db["regular_table"].insert({"id": 1, "name": "Cleo"}, pk="id")
assert db["rowid_table"].use_rowid
assert not db["regular_table"].use_rowid

0 comments on commit 5b25794

Please sign in to comment.