Skip to content

Commit b008848

Browse files
john-bodleyebyhr
authored andcommitted
Improve the performance of get_view_names in SQLAlchemy
1 parent 3b154b7 commit b008848

File tree

2 files changed

+44
-1
lines changed

2 files changed

+44
-1
lines changed

tests/integration/test_sqlalchemy_integration.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -409,3 +409,43 @@ def test_get_table_names_raises(trino_connection):
409409

410410
with pytest.raises(sqla.exc.NoSuchTableError):
411411
sqla.inspect(engine).get_table_names(None)
412+
413+
414+
@pytest.mark.parametrize('trino_connection', ['memory/test'], indirect=True)
415+
@pytest.mark.parametrize('schema', [None, 'test'])
416+
def test_get_view_names(trino_connection, schema):
417+
engine, conn = trino_connection
418+
name = schema or engine.dialect._get_default_schema_name(conn)
419+
metadata = sqla.MetaData(schema=name)
420+
421+
if not engine.dialect.has_schema(conn, name):
422+
engine.execute(sqla.schema.CreateSchema(name))
423+
424+
try:
425+
create_view(
426+
'test_get_view_names',
427+
sqla.select(
428+
[
429+
sqla.Table(
430+
'my_table',
431+
metadata,
432+
sqla.Column('id', sqla.Integer),
433+
),
434+
],
435+
),
436+
metadata,
437+
cascade_on_drop=False,
438+
)
439+
440+
metadata.create_all(engine)
441+
assert sqla.inspect(engine).get_view_names(schema) == ['test_get_view_names']
442+
finally:
443+
metadata.drop_all(engine)
444+
445+
446+
@pytest.mark.parametrize('trino_connection', ['memory'], indirect=True)
447+
def test_get_view_names_raises(trino_connection):
448+
engine, _ = trino_connection
449+
450+
with pytest.raises(sqla.exc.NoSuchTableError):
451+
sqla.inspect(engine).get_view_names(None)

trino/sqlalchemy/dialect.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -215,11 +215,14 @@ def get_view_names(self, connection: Connection, schema: str = None, **kw) -> Li
215215
schema = schema or self._get_default_schema_name(connection)
216216
if schema is None:
217217
raise exc.NoSuchTableError("schema is required")
218+
219+
# Querying the information_schema.views table is subpar as it compiles the view definitions.
218220
query = dedent(
219221
"""
220222
SELECT "table_name"
221-
FROM "information_schema"."views"
223+
FROM "information_schema"."tables"
222224
WHERE "table_schema" = :schema
225+
AND "table_type" = 'VIEW'
223226
"""
224227
).strip()
225228
res = connection.execute(sql.text(query), schema=schema)

0 commit comments

Comments
 (0)