Skip to content

Commit

Permalink
Improve the performance of get_view_names in SQLAlchemy
Browse files Browse the repository at this point in the history
  • Loading branch information
john-bodley authored and ebyhr committed Nov 2, 2022
1 parent 3b154b7 commit b008848
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 1 deletion.
40 changes: 40 additions & 0 deletions tests/integration/test_sqlalchemy_integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -409,3 +409,43 @@ def test_get_table_names_raises(trino_connection):

with pytest.raises(sqla.exc.NoSuchTableError):
sqla.inspect(engine).get_table_names(None)


@pytest.mark.parametrize('trino_connection', ['memory/test'], indirect=True)
@pytest.mark.parametrize('schema', [None, 'test'])
def test_get_view_names(trino_connection, schema):
engine, conn = trino_connection
name = schema or engine.dialect._get_default_schema_name(conn)
metadata = sqla.MetaData(schema=name)

if not engine.dialect.has_schema(conn, name):
engine.execute(sqla.schema.CreateSchema(name))

try:
create_view(
'test_get_view_names',
sqla.select(
[
sqla.Table(
'my_table',
metadata,
sqla.Column('id', sqla.Integer),
),
],
),
metadata,
cascade_on_drop=False,
)

metadata.create_all(engine)
assert sqla.inspect(engine).get_view_names(schema) == ['test_get_view_names']
finally:
metadata.drop_all(engine)


@pytest.mark.parametrize('trino_connection', ['memory'], indirect=True)
def test_get_view_names_raises(trino_connection):
engine, _ = trino_connection

with pytest.raises(sqla.exc.NoSuchTableError):
sqla.inspect(engine).get_view_names(None)
5 changes: 4 additions & 1 deletion trino/sqlalchemy/dialect.py
Original file line number Diff line number Diff line change
Expand Up @@ -215,11 +215,14 @@ def get_view_names(self, connection: Connection, schema: str = None, **kw) -> Li
schema = schema or self._get_default_schema_name(connection)
if schema is None:
raise exc.NoSuchTableError("schema is required")

# Querying the information_schema.views table is subpar as it compiles the view definitions.
query = dedent(
"""
SELECT "table_name"
FROM "information_schema"."views"
FROM "information_schema"."tables"
WHERE "table_schema" = :schema
AND "table_type" = 'VIEW'
"""
).strip()
res = connection.execute(sql.text(query), schema=schema)
Expand Down

0 comments on commit b008848

Please sign in to comment.