diff --git a/datasette/database.py b/datasette/database.py index dfca179c..d8043c24 100644 --- a/datasette/database.py +++ b/datasette/database.py @@ -338,6 +338,12 @@ class Database: ) return bool(results.rows) + async def view_exists(self, table): + results = await self.execute( + "select 1 from sqlite_master where type='view' and name=?", params=(table,) + ) + return bool(results.rows) + async def table_names(self): results = await self.execute( "select name from sqlite_master where type='table'" diff --git a/docs/internals.rst b/docs/internals.rst index cc6de867..00e82cbf 100644 --- a/docs/internals.rst +++ b/docs/internals.rst @@ -909,6 +909,9 @@ The ``Database`` class also provides properties and methods for introspecting th ``await db.table_exists(table)`` - boolean Check if a table called ``table`` exists. +``await db.view_exists(view)`` - boolean + Check if a view called ``view`` exists. + ``await db.table_names()`` - list of strings List of names of tables in the database. diff --git a/tests/test_internals_database.py b/tests/test_internals_database.py index 20ae0753..647ae7bd 100644 --- a/tests/test_internals_database.py +++ b/tests/test_internals_database.py @@ -78,6 +78,19 @@ async def test_table_exists(db, tables, exists): assert exists == actual +@pytest.mark.parametrize( + "view,expected", + ( + ("not_a_view", False), + ("paginated_view", True), + ), +) +@pytest.mark.asyncio +async def test_view_exists(db, view, expected): + actual = await db.view_exists(view) + assert actual == expected + + @pytest.mark.parametrize( "table,expected", (