Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions docs/static/resources/openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -24344,6 +24344,9 @@
"404": {
"$ref": "#/components/responses/404"
},
"422": {
"$ref": "#/components/responses/422"
},
"500": {
"$ref": "#/components/responses/500"
}
Expand Down
26 changes: 25 additions & 1 deletion superset/databases/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -1197,6 +1197,8 @@ def table_metadata(self, pk: int) -> FlaskResponse:
$ref: '#/components/responses/401'
404:
$ref: '#/components/responses/404'
422:
$ref: '#/components/responses/422'
500:
$ref: '#/components/responses/500'
"""
Expand Down Expand Up @@ -1228,8 +1230,30 @@ def table_metadata(self, pk: int) -> FlaskResponse:
# Partition info is engine-agnostic at this layer: the generic dispatch
# passes it to the engine spec, which decides whether to use it. Non-ODPS
# specs ignore the parameter.
payload = database.db_engine_spec.get_table_metadata(database, table, partition)
try:
payload = database.db_engine_spec.get_table_metadata(
database, table, partition
)
Comment on lines +1235 to +1236

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Optional: a missing table could return 404

NoSuchTableError is also a SQLAlchemyError, so a missing table returns 422 here. Mapping it to the existing TableNotFoundException gives the same 404 "No such table" as the access-denied branch above, so the response doesn't reveal whether the table exists.

Suggested change
database, table, partition
)
database, table, partition
)
except NoSuchTableError as ex:
raise TableNotFoundException("No such table") from ex

except SQLAlchemyError as ex:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: This also catches OperationalError during a database outage, returning 422 instead of the 500 used for connection failures and making transient failures look permanent.

Assessment: 🟠 Major · 🔁 Occurrence: Rarely · 🏷️ Api mismatch

Use CodeAnt Skill Fix in Cursor Fix in VSCode Claude

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** superset/databases/api.py
**Line:** 1236:1236
**Comment:**
	*Api Mismatch: This also catches `OperationalError` during a database outage, returning 422 instead of the 500 used for connection failures and making transient failures look permanent.

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
👍 | 👎

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed: a refused connection raises OperationalError inside this try (SQLAlchemy 2.0.55), so an outage becomes a 422 + WARNING, not the 500 that handle_api_exception and the schemas endpoint return. The reported Binder Error is an InternalError and keeps its 422.

Suggested change
except SQLAlchemyError as ex:
except OperationalError:
# A connection-level failure is a server fault, not a dialect gap.
raise
except SQLAlchemyError as ex:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Outages now return 422 instead of 500

A refused or dropped connection now returns 422 with a WARNING, so 5xx alerting no longer sees outages on this endpoint. get_inspector uses NullPool, so a server that is down always fails at connect time with statement=None. A connection dropped mid-query sets connection_invalidated. Re-raising only those keeps dialect gaps (MySQL 1054, sqlite no such table, Postgres 42703, statement timeouts) at 422. Checked with unit probes: connect refused → 500, dropped → 500, mysql-1054/sqlite/pg-42703/InternalError → 422. Trino and other HTTP drivers only fail when the query runs, so their outages stay 422 either way.

Suggested change
except SQLAlchemyError as ex:
except SQLAlchemyError as ex:
if isinstance(ex, OperationalError) and (
ex.statement is None or ex.connection_invalidated
):
# Failed to connect, or the connection dropped mid-reflection:
# an outage rather than a dialect gap, so keep the 500.
raise

# Reflection (get_pk_constraint/get_foreign_keys/get_indexes/
# get_table_comment) issues catalog queries tailored to the
# declared dialect. A customer database that only partially
# implements that dialect (e.g. a postgres-wire-protocol engine
# missing pg_catalog.pg_index columns SQLAlchemy's postgres
# dialect now queries) raises here - that's the target
Comment thread
aminghadersohi marked this conversation as resolved.
Resolved
# database's limitation, not a Superset bug: answer with a
# typed 422 and a warning instead of an unhandled 500 + ERROR,
# matching the sibling table_metadata_deprecated endpoint above.
self.incr_stats("error", self.table_metadata.__name__)
Comment thread
aminghadersohi marked this conversation as resolved.
Resolved
logger.warning(
"table_metadata: reflection failed for database=%s table=%s",
pk,
table_name,
exc_info=True,
)
return self.response_422(error_msg_from_exception(ex))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Optional: guest error sanitization is skipped on this path

On master the 500 handler gives guests the generic "An error occurred while fetching the data.". response_422 returns the raw engine error, including the [SQL: ...] text. A guest only reaches this route if the operator grants it access, so this is hardening, not a vulnerability. Fix: return self.response_422(sanitize_error_message(error_msg_from_exception(ex), 422)), with sanitize_error_message imported from superset.utils.error_sanitization. The import is outside the diff, so there's no applyable suggestion here.


self.incr_stats("success", self.table_metadata.__name__)
return self.response(200, **payload)
Comment thread
aminghadersohi marked this conversation as resolved.
Resolved

@expose("/<int:pk>/table_metadata/extra/", methods=["GET"])
Expand Down
21 changes: 21 additions & 0 deletions tests/integration_tests/databases/api_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -2069,6 +2069,27 @@ def test_get_table_metadata_no_db_permission(self):
rv = self.client.get(uri)
assert rv.status_code == 404

def test_get_table_metadata_reflection_error(self):
"""
Database API: Test get table metadata returns 422, not 500, when the
target database's reflection (pk/fk/index/comment introspection) raises
a SQLAlchemyError, e.g. a postgres-wire-protocol engine missing catalog
columns SQLAlchemy's postgres dialect queries.
"""
example_db = get_example_database()
self.login(ADMIN_USERNAME)
uri = (
f"api/v1/database/{example_db.id}/table_metadata/"
"?name=birth_names&schema=null"
)
with mock.patch.object(
example_db.db_engine_spec,
"get_table_metadata",
side_effect=SQLAlchemyError("Binder Error: Referenced table not found"),
):
rv = self.client.get(uri)
assert rv.status_code == 422

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Optional: also assert the response body, so the test pins the message as well as the status.

Suggested change
assert rv.status_code == 422
assert rv.status_code == 422
assert rv.json == {"message": "Binder Error: Referenced table not found"}


@pytest.mark.usefixtures("load_birth_names_dashboard_with_slices")
def test_get_table_extra_metadata_deprecated(self):
"""
Expand Down
Loading