Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(sql-editor): show a retry when the schema load fails (#75775)

posthog[bot]8249abe7ae0d
diff --git a/frontend/src/scenes/data-management/database/databaseTableListLogic.ts b/frontend/src/scenes/data-management/database/databaseTableListLogic.ts
index debf2cd189c1..70ae8e4d4c30 100644
--- a/frontend/src/scenes/data-management/database/databaseTableListLogic.ts
+++ b/frontend/src/scenes/data-management/database/databaseTableListLogic.ts
@@ -55,6 +55,7 @@ export interface databaseTableListLogicValues {
dataWarehouseTablesMap: Record<string, DatabaseSchemaDataWarehouseTable | DatabaseSchemaViewTable>
dataWarehouseTablesMapById: Record<string, DatabaseSchemaDataWarehouseTable | DatabaseSchemaViewTable>
database: Required<DatabaseSchemaQueryResponse> | null
+ databaseLoadError: string | null
databaseLoading: boolean
endpointTables: DatabaseSchemaEndpointTable[]
externalDataSourceTables: DatabaseSchemaDataWarehouseTable[]
@@ -243,6 +244,16 @@ export const databaseTableListLogic = kea<databaseTableListLogicType>([
})),
reducers({
searchTerm: ['', { setSearchTerm: (_, { searchTerm }) => searchTerm }],
+ // Without this the logic settles on `database: null, databaseLoading: false` after a failed
+ // load, which every consumer reads as "loaded, and the project has no tables".
+ databaseLoadError: [
+ null as string | null,
+ {
+ loadDatabase: () => null,
+ loadDatabaseSuccess: () => null,
+ loadDatabaseFailure: (_, { error }) => error || 'Unknown error',
+ },
+ ],
connectionId: [
null as string | null,
{ setConnection: (_, { connectionId }) => connectionId, resetConnectionScope: () => null },
diff --git a/frontend/src/scenes/data-warehouse/editor/sidebar/queryDatabaseLogic.test.ts b/frontend/src/scenes/data-warehouse/editor/sidebar/queryDatabaseLogic.test.ts
index 1365b832275a..656e5e598a84 100644
--- a/frontend/src/scenes/data-warehouse/editor/sidebar/queryDatabaseLogic.test.ts
+++ b/frontend/src/scenes/data-warehouse/editor/sidebar/queryDatabaseLogic.test.ts
@@ -1,7 +1,12 @@
+import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'
+
+import { initKeaTests } from '~/test/init'
+
import {
getDefaultExpandedRootIds,
getInitialExpandedFolders,
groupDirectConnectionTableNodesBySchema,
+ queryDatabaseLogic,
shouldInitializeDirectConnectionExpandedFolders,
} from './queryDatabaseLogic'
@@ -199,4 +204,43 @@ describe('queryDatabaseLogic', () => {
)
).toEqual(false)
})
+
+ describe('failed schema load', () => {
+ let logic: ReturnType<typeof queryDatabaseLogic.build>
+
+ const childNames = (sectionType: string): (string | undefined)[] =>
+ logic.values.treeData
+ .find((item) => item.record?.type === sectionType)
+ ?.children?.map((child) => child.name) ?? []
+
+ beforeEach(() => {
+ initKeaTests()
+ logic = queryDatabaseLogic()
+ logic.mount()
+ })
+
+ afterEach(() => {
+ logic.unmount()
+ })
+
+ it('shows the failure and a retry instead of an empty tree', () => {
+ databaseTableListLogic.findMounted()?.actions.loadDatabaseFailure('A server error occurred.')
+
+ expect(childNames('sources')).toEqual(["Couldn't load your schema", 'Try again'])
+ expect(childNames('managed-views')).toEqual(["Couldn't load your schema", 'Try again'])
+ })
+
+ it('retries the schema load when the retry node is clicked', () => {
+ databaseTableListLogic.findMounted()?.actions.loadDatabaseFailure('A server error occurred.')
+
+ const retryNode = logic.values.treeData
+ .find((item) => item.record?.type === 'sources')
+ ?.children?.find((child) => child.record?.type === 'schema-load-retry')
+
+ retryNode?.onClick?.()
+
+ expect(logic.values.databaseLoadError).toEqual(null)
+ expect(childNames('sources')).not.toContain("Couldn't load your schema")
+ })
+ })
})
diff --git a/frontend/src/scenes/data-warehouse/editor/sidebar/queryDatabaseLogic.tsx b/frontend/src/scenes/data-warehouse/editor/sidebar/queryDatabaseLogic.tsx
index c17bb214dad2..79eaa6576732 100644
--- a/frontend/src/scenes/data-warehouse/editor/sidebar/queryDatabaseLogic.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/sidebar/queryDatabaseLogic.tsx
@@ -2,7 +2,17 @@ import { MakeLogicType, actions, connect, events, kea, listeners, path, reducers
import { loaders } from 'kea-loaders'
import { subscriptions } from 'kea-subscriptions'
-import { IconBolt, IconDatabase, IconDocument, IconEndpoints, IconFolder, IconPlug, IconPlus } from '@posthog/icons'
+import {
+ IconBolt,
+ IconDatabase,
+ IconDocument,
+ IconEndpoints,
+ IconFolder,
+ IconPlug,
+ IconPlus,
+ IconRefresh,
+ IconWarning,
+} from '@posthog/icons'
import { LemonMenuItem } from '@posthog/lemon-ui'
import { Spinner } from '@posthog/lemon-ui'
@@ -359,6 +369,31 @@ const createLazyTablePlaceholderNode = (lazyNodeId: string): TreeDataItem => {
}
}
+// A failed schema load must not look like an empty project: say it failed and offer the retry.
+const createSchemaErrorNodes = (prefix: string, onRetry: () => void): TreeDataItem[] => [
+ {
+ id: `${prefix}-error/`,
+ name: "Couldn't load your schema",
+ displayName: <span className="text-danger">Couldn't load your schema</span>,
+ icon: <IconWarning className="text-danger" />,
+ disableSelect: true,
+ type: 'node',
+ record: {
+ type: 'schema-load-error',
+ },
+ },
+ {
+ id: `${prefix}-error-retry/`,
+ name: 'Try again',
+ displayName: <>Try again</>,
+ icon: <IconRefresh />,
+ onClick: onRetry,
+ record: {
+ type: 'schema-load-retry',
+ },
+ },
+]
+
const createLazyTableEmptyNode = (lazyNodeId: string): TreeDataItem => {
return {
id: `${lazyNodeId}-empty/`,
@@ -1342,6 +1377,7 @@ export interface queryDatabaseLogicValues {
connectionId: string | null // databaseTableListLogic
dataWarehouseTables: DatabaseSchemaDataWarehouseTable[] // databaseTableListLogic
dataWarehouseTablesMap: Record<string, DatabaseSchemaDataWarehouseTable | DatabaseSchemaViewTable> // databaseTableListLogic
+ databaseLoadError: string | null // databaseTableListLogic
databaseLoading: boolean // databaseTableListLogic
latestEndpointTables: DatabaseSchemaEndpointTable[] // databaseTableListLogic
managedViews: DatabaseSchemaManagedViewTable[] // databaseTableListLogic
@@ -1474,6 +1510,9 @@ export interface queryDatabaseLogicActions {
types?: string[][]
}
} // dataWarehouseViewsLogic
+ refreshDatabaseSchema: () => {
+ value: true
+ } // databaseTableListLogic
loadDrafts: () => any // draftsLogic
loadMoreDrafts: () => any // draftsLogic
renameDraft: (
@@ -1712,6 +1751,7 @@ export interface queryDatabaseLogicMeta {
treeData: (
treeDataContext: TreeDataContext,
databaseLoading: boolean,
+ databaseLoadError: string | null,
dataWarehouseSavedQueriesLoading: boolean,
drafts: DataWarehouseSavedQueryDraft[],
draftsResponseLoading: boolean,
@@ -1809,6 +1849,7 @@ export const queryDatabaseLogic = kea<queryDatabaseLogicType>([
'viewsMapById',
'managedViews',
'databaseLoading',
+ 'databaseLoadError',
'systemTables',
'systemTablesMap',
'allTablesMap',
@@ -1846,6 +1887,8 @@ export const queryDatabaseLogic = kea<queryDatabaseLogicType>([
],
draftsLogic,
['loadDrafts', 'renameDraft', 'loadMoreDrafts'],
+ databaseTableListLogic,
+ ['refreshDatabaseSchema'],
],
})),
reducers({
@@ -2473,6 +2516,7 @@ export const queryDatabaseLogic = kea<queryDatabaseLogicType>([
(s) => [
s.treeDataContext,
s.databaseLoading,
+ s.databaseLoadError,
s.dataWarehouseSavedQueriesLoading,
s.drafts,
s.draftsResponseLoading,
@@ -2485,6 +2529,7 @@ export const queryDatabaseLogic = kea<queryDatabaseLogicType>([
(
treeDataContext: TreeDataContext,
databaseLoading: boolean,
+ databaseLoadError: string | null,
dataWarehouseSavedQueriesLoading: boolean,
drafts: DataWarehouseSavedQueryDraft[],
draftsResponseLoading: boolean,
@@ -2516,9 +2561,12 @@ export const queryDatabaseLogic = kea<queryDatabaseLogicType>([
})
const expandedLazyNodeIds = new Set(expandedFolders.filter(isLazyNodeId))
const tableNodeOptions = { expandedLazyNodeIds }
+ const schemaFailedWithNoTables =
+ !!databaseLoadError && !databaseLoading && Object.keys(allTablesMap).length === 0
- // Add loading indicator for sources if still loading
- if (databaseLoading && posthogTables.length === 0 && dataWarehouseTables.length === 0) {
+ if (schemaFailedWithNoTables) {
+ sourcesChildren.push(...createSchemaErrorNodes('sources', () => actions.refreshDatabaseSchema()))
+ } else if (databaseLoading && posthogTables.length === 0 && dataWarehouseTables.length === 0) {
sourcesChildren.push({
id: 'sources-loading/',
name: 'Loading...',
@@ -2640,6 +2688,15 @@ export const queryDatabaseLogic = kea<queryDatabaseLogicType>([
viewsChildren.sort((a, b) => a.name.localeCompare(b.name))
managedViewsChildren.sort((a, b) => a.name.localeCompare(b.name))
+ // Managed views come from the same schema request as sources, so they're missing for
+ // the same reason. Replaces the saved-query spinner, which tracks a different request.
+ if (schemaFailedWithNoTables && managedViews.length === 0) {
+ managedViewsChildren.length = 0
+ managedViewsChildren.push(
+ ...createSchemaErrorNodes('managed-views', () => actions.refreshDatabaseSchema())
+ )
+ }
+
const states = queryTabState?.state?.editorModelsStateKey
const unsavedChildren: TreeDataItem[] = []
let i = 1
diff --git a/posthog/api/services/query.py b/posthog/api/services/query.py
index 65ea529bf68b..3ad9a7482296 100644
--- a/posthog/api/services/query.py
+++ b/posthog/api/services/query.py
@@ -4,7 +4,7 @@ from typing import Literal, Optional, overload
import structlog
import pydantic_core
from pydantic import BaseModel
-from rest_framework.exceptions import ValidationError
+from rest_framework.exceptions import APIException, ValidationError
from posthog.schema import (
DashboardFilter,
@@ -24,16 +24,18 @@ from posthog.hogql.compiler.bytecode import execute_hog
from posthog.hogql.constants import LimitContext
from posthog.hogql.context import HogQLContext
from posthog.hogql.direct_connection import resolve_database_for_connection
+from posthog.hogql.errors import ExposedHogQLError, ResolutionError
from posthog.hogql.metadata import get_hogql_metadata
from posthog.hogql.modifiers import create_default_modifiers_for_team
from posthog.clickhouse.query_tagging import tag_queries
from posthog.cloud_utils import is_cloud
from posthog.event_usage import AnalyticsProps
+from posthog.exceptions import DatabaseSchemaUnavailable
from posthog.exceptions_capture import capture_exception
from posthog.hogql_queries.query_runner import CacheMissResponse, ExecutionMode, QueryResponse, get_query_runner_or_none
from posthog.models import Team, User
-from posthog.rbac.user_access_control import UserAccessControl
+from posthog.rbac.user_access_control import UserAccessControl, UserAccessControlError
from posthog.schema_migrations.upgrade import upgrade
from products.data_tools.backend.models.join import DataWarehouseJoin
@@ -177,6 +179,54 @@ def process_query_dict(
)
+def process_database_schema_query(
+ team: Team, query: DatabaseSchemaQuery, *, user: Optional[User] = None
+) -> DatabaseSchemaQueryResponse:
+ try:
+ _, database = resolve_database_for_connection(
+ team,
+ query.connectionId,
+ user=user,
+ error_factory=ValidationError,
+ modifiers=create_default_modifiers_for_team(team),
+ )
+ context = HogQLContext(team_id=team.pk, team=team, database=database, user=user)
+ serialized_tables = database.serialize(context, include_hidden_posthog_tables=True)
+ except (APIException, ExposedHogQLError, ResolutionError, UserAccessControlError):
+ # These already carry an actionable message, and the query view maps them to a 4xx.
+ raise
+ except Exception as e:
+ # This request backs the SQL editor's table list. Untyped, it surfaces as a bare 500 with
+ # "A server error occurred.", which the sidebar can't tell apart from an empty project.
+ logger.exception(
+ "database_schema_query_failed", team_id=team.pk, connection_id=query.connectionId, error=str(e)
+ )
+ capture_exception(e, {"team_id": team.pk, "query_kind": "DatabaseSchemaQuery"})
+ raise DatabaseSchemaUnavailable() from e
+
+ table_names = set(serialized_tables.keys())
+ joins = DataWarehouseJoin.objects.filter(team_id=team.pk).exclude(deleted=True)
+ joins = joins.filter(source_table_name__in=table_names, joining_table_name__in=table_names)
+
+ join_models: list[DataWarehouseViewLink] = []
+ for join in joins.iterator():
+ join_models.append(
+ DataWarehouseViewLink.model_validate(
+ {
+ "id": str(join.id),
+ "source_table_name": join.source_table_name,
+ "source_table_key": join.source_table_key,
+ "joining_table_name": join.joining_table_name,
+ "joining_table_key": join.joining_table_key,
+ "field_name": join.field_name,
+ "created_at": join.created_at.isoformat(),
+ }
+ )
+ )
+
+ return DatabaseSchemaQueryResponse(tables=serialized_tables, joins=join_models)
+
+
@overload
def process_query_model(
team: Team,
@@ -257,39 +307,7 @@ def process_query_model(
return get_hogql_metadata(query=metadata_query, team=team, user=user)
if isinstance(query, DatabaseSchemaQuery):
- _, database = resolve_database_for_connection(
- team,
- query.connectionId,
- user=user,
- error_factory=ValidationError,
- modifiers=create_default_modifiers_for_team(team),
- )
- context = HogQLContext(team_id=team.pk, team=team, database=database, user=user)
- serialized_tables = database.serialize(context, include_hidden_posthog_tables=True)
- table_names = set(serialized_tables.keys())
- joins = DataWarehouseJoin.objects.filter(team_id=team.pk).exclude(deleted=True)
- joins = joins.filter(source_table_name__in=table_names, joining_table_name__in=table_names)
-
- join_models: list[DataWarehouseViewLink] = []
- for join in joins.iterator():
- join_models.append(
- DataWarehouseViewLink.model_validate(
- {
- "id": str(join.id),
- "source_table_name": join.source_table_name,
- "source_table_key": join.source_table_key,
- "joining_table_name": join.joining_table_name,
- "joining_table_key": join.joining_table_key,
- "field_name": join.field_name,
- "created_at": join.created_at.isoformat(),
- }
- )
- )
-
- return DatabaseSchemaQueryResponse(
- tables=serialized_tables,
- joins=join_models,
- )
+ return process_database_schema_query(team, query, user=user)
query_runner = get_query_runner_or_none(
query, team, limit_context=limit_context, user=user, user_access_control=user_access_control
diff --git a/posthog/api/test/test_query_service.py b/posthog/api/test/test_query_service.py
index 4fe3af3bf0eb..b471d4c6df35 100644
--- a/posthog/api/test/test_query_service.py
+++ b/posthog/api/test/test_query_service.py
@@ -30,6 +30,7 @@ from posthog.hogql.direct_connection import INVALID_CONNECTION_ID_ERROR
from posthog.hogql.errors import ResolutionError
from posthog.api.services.query import process_query_model
+from posthog.exceptions import DatabaseSchemaUnavailable
from products.warehouse_sources.backend.facade.models import (
DataWarehouseCredential,
@@ -152,6 +153,28 @@ class TestQueryService(APIBaseTest):
joining_table_name__in={"selected_table", "selected_table_2"},
)
+ @parameterized.expand(
+ [
+ ("resolve", "resolve_database_for_connection"),
+ ("serialize", "serialize"),
+ ]
+ )
+ @patch("posthog.api.services.query.resolve_database_for_connection")
+ def test_database_schema_query_failure_is_typed_not_a_bare_500(
+ self, _label: str, failing_step: str, mock_resolve_database_for_connection: MagicMock
+ ):
+ if failing_step == "resolve":
+ mock_resolve_database_for_connection.side_effect = RuntimeError("boom")
+ else:
+ mock_database = MagicMock()
+ mock_database.serialize.side_effect = RuntimeError("boom")
+ mock_resolve_database_for_connection.return_value = (None, mock_database)
+
+ with self.assertRaises(DatabaseSchemaUnavailable) as error:
+ process_query_model(self.team, DatabaseSchemaQuery())
+
+ self.assertEqual(error.exception.get_codes(), "database_schema_unavailable")
+
@patch("posthog.api.services.query.DataWarehouseJoin.objects.filter")
@patch("posthog.api.services.query.resolve_database_for_connection")
def test_database_schema_query_preserves_serialized_join_fields(
diff --git a/posthog/exceptions.py b/posthog/exceptions.py
index 7461fc5a2fd9..2dba8ac14542 100644
--- a/posthog/exceptions.py
+++ b/posthog/exceptions.py
@@ -60,6 +60,15 @@ class Conflict(APIException):
default_code = "conflict"
+class DatabaseSchemaUnavailable(APIException):
+ # The schema request backs the SQL editor's table list, so a bare 500 leaves the sidebar looking
+ # like an empty project. A stable code lets the client tell "we couldn't read your schema" apart
+ # from any other server error.
+ status_code = 503
+ default_detail = "Couldn't load your project's schema. Try again, and if it keeps happening contact support."
+ default_code = "database_schema_unavailable"
+
+
class ClickHouseAtCapacity(APIException):
status_code = 503
default_detail = (