Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

feat: refresh db connections (#4834)

Shahmir Varqhad80de72213e6
diff --git a/frontend/src/components/datasources/datasources.tsx b/frontend/src/components/datasources/datasources.tsx
index 7f61db4be7..75730b34b7 100644
--- a/frontend/src/components/datasources/datasources.tsx
+++ b/frontend/src/components/datasources/datasources.tsx
@@ -8,6 +8,7 @@ import {
XIcon,
Table2Icon,
EyeIcon,
+ RefreshCwIcon,
} from "lucide-react";
import { Command, CommandInput, CommandItem } from "@/components/ui/command";
import { CommandList } from "cmdk";
@@ -26,7 +27,10 @@ import { useLastFocusedCellId } from "@/core/cells/focus";
import { atom, useAtomValue, useSetAtom } from "jotai";
import { Tooltip } from "@/components/ui/tooltip";
import { PanelEmptyState } from "../editor/chrome/panels/empty-state";
-import { previewDatasetColumn } from "@/core/network/requests";
+import {
+ previewDataSourceConnection,
+ previewDatasetColumn,
+} from "@/core/network/requests";
import { prettyNumber } from "@/utils/numbers";
import { Events } from "@/utils/events";
import { CopyClipboardIcon } from "@/components/icons/copy-icon";
@@ -231,11 +235,22 @@ const Engine: React.FC<{
children: React.ReactNode;
hasChildren?: boolean;
}> = ({ connection, children, hasChildren }) => {
- const hasEngine = connection.databases.length > 0;
- // If the connection has no engine, it's the internal duckdb engine
- const engineName = hasEngine
- ? connection.databases[0]?.engine || "In-Memory"
- : connection.name;
+ // The internal DuckDB engine may have no engine name, so we provide one.
+ // The connection is also updated automatically, so we do not need to refresh.
+ const internalEngine =
+ connection.databases.length === 0 || !connection.databases[0]?.engine;
+ const engineName = internalEngine ? "In-Memory" : connection.name;
+
+ const [isSpinning, setIsSpinning] = React.useState(false);
+
+ const handleRefreshConnection = async () => {
+ setIsSpinning(true);
+ await previewDataSourceConnection({
+ engine: connection.name,
+ });
+ // Artificially spin the icon if the request is really fast
+ setTimeout(() => setIsSpinning(false), 500);
+ };
return (
<>
@@ -248,6 +263,23 @@ const Engine: React.FC<{
<span className="text-xs text-muted-foreground">
(<EngineVariable variableName={engineName as VariableName} />)
</span>
+ {!internalEngine && (
+ <Tooltip content="Refresh connection">
+ <Button
+ variant="ghost"
+ size="icon"
+ className="ml-auto hover:bg-transparent hover:shadow-none"
+ onClick={handleRefreshConnection}
+ >
+ <RefreshCwIcon
+ className={cn(
+ "h-4 w-4 text-muted-foreground hover:text-foreground",
+ isSpinning && "animate-[spin_0.5s]",
+ )}
+ />
+ </Button>
+ </Tooltip>
+ )}
</DatasourceLabel>
{hasChildren ? (
children
diff --git a/frontend/src/core/islands/bridge.ts b/frontend/src/core/islands/bridge.ts
index be4e0d4c85..ddaef460e5 100644
--- a/frontend/src/core/islands/bridge.ts
+++ b/frontend/src/core/islands/bridge.ts
@@ -146,6 +146,7 @@ export class IslandsPyodideBridge implements RunRequests, EditRequests {
previewDatasetColumn = throwNotImplemented;
previewSQLTable = throwNotImplemented;
previewSQLTableList = throwNotImplemented;
+ previewDataSourceConnection = throwNotImplemented;
openFile = throwNotImplemented;
sendListFiles = throwNotImplemented;
sendPdb = throwNotImplemented;
diff --git a/frontend/src/core/network/requests-network.ts b/frontend/src/core/network/requests-network.ts
index d29f64c2ad..4075f89dc3 100644
--- a/frontend/src/core/network/requests-network.ts
+++ b/frontend/src/core/network/requests-network.ts
@@ -173,6 +173,13 @@ export function createNetworkRequests(): EditRequests & RunRequests {
})
.then(handleResponseReturnNull);
},
+ previewDataSourceConnection: (request) => {
+ return marimoClient
+ .POST("/api/datasources/preview_datasource_connection", {
+ body: request,
+ })
+ .then(handleResponseReturnNull);
+ },
openFile: async (request) => {
await marimoClient
.POST("/api/files/open", {
diff --git a/frontend/src/core/network/requests-static.ts b/frontend/src/core/network/requests-static.ts
index 4564cb23ee..296b790894 100644
--- a/frontend/src/core/network/requests-static.ts
+++ b/frontend/src/core/network/requests-static.ts
@@ -52,6 +52,7 @@ export function createStaticRequests(): EditRequests & RunRequests {
previewDatasetColumn: throwNotInEditMode,
previewSQLTable: throwNotInEditMode,
previewSQLTableList: throwNotInEditMode,
+ previewDataSourceConnection: throwNotInEditMode,
openFile: throwNotInEditMode,
getUsageStats: throwNotInEditMode,
sendListFiles: throwNotInEditMode,
diff --git a/frontend/src/core/network/requests-toasting.ts b/frontend/src/core/network/requests-toasting.ts
index f2bcda5601..ae9921eaf1 100644
--- a/frontend/src/core/network/requests-toasting.ts
+++ b/frontend/src/core/network/requests-toasting.ts
@@ -33,6 +33,7 @@ export function createErrorToastingRequests(
previewDatasetColumn: "Failed to fetch data sources",
previewSQLTable: "Failed to fetch SQL table",
previewSQLTableList: "Failed to fetch SQL table list",
+ previewDataSourceConnection: "Failed to preview data source connection",
openFile: "Failed to open file",
getUsageStats: "", // No toast
sendListFiles: "Failed to list files",
diff --git a/frontend/src/core/network/requests.ts b/frontend/src/core/network/requests.ts
index 20a14e347b..0cf61cd4a5 100644
--- a/frontend/src/core/network/requests.ts
+++ b/frontend/src/core/network/requests.ts
@@ -51,6 +51,7 @@ export const {
previewDatasetColumn,
previewSQLTable,
previewSQLTableList,
+ previewDataSourceConnection,
openFile,
getUsageStats,
sendPdb,
diff --git a/frontend/src/core/network/types.ts b/frontend/src/core/network/types.ts
index e7627d1869..0cdfd51c17 100644
--- a/frontend/src/core/network/types.ts
+++ b/frontend/src/core/network/types.ts
@@ -55,6 +55,8 @@ export type PreviewDatasetColumnRequest =
schemas["PreviewDatasetColumnRequest"];
export type PreviewSQLTableRequest = schemas["PreviewSQLTableRequest"];
export type PreviewSQLTableListRequest = schemas["PreviewSQLTableListRequest"];
+export type PreviewDataSourceConnectionRequest =
+ schemas["PreviewDataSourceConnectionRequest"];
export type PdbRequest = schemas["PdbRequest"];
export type ReadCodeResponse = schemas["ReadCodeResponse"];
export type RecentFilesResponse = schemas["RecentFilesResponse"];
@@ -126,6 +128,9 @@ export interface EditRequests {
previewDatasetColumn: (request: PreviewDatasetColumnRequest) => Promise<null>;
previewSQLTable: (request: PreviewSQLTableRequest) => Promise<null>;
previewSQLTableList: (request: PreviewSQLTableListRequest) => Promise<null>;
+ previewDataSourceConnection: (
+ request: PreviewDataSourceConnectionRequest,
+ ) => Promise<null>;
openFile: (request: { path: string }) => Promise<null>;
getUsageStats: () => Promise<UsageResponse>;
// Debugger
diff --git a/frontend/src/core/wasm/bridge.ts b/frontend/src/core/wasm/bridge.ts
index 15958ac495..c49898cb30 100644
--- a/frontend/src/core/wasm/bridge.ts
+++ b/frontend/src/core/wasm/bridge.ts
@@ -478,6 +478,12 @@ export class PyodideBridge implements RunRequests, EditRequests {
return null;
};
+ previewDataSourceConnection: EditRequests["previewDataSourceConnection"] =
+ async (request) => {
+ await this.putControlRequest(request);
+ return null;
+ };
+
syncCellIds = () => Promise.resolve(null);
getUsageStats = throwNotImplemented;
openTutorial = throwNotImplemented;
diff --git a/marimo/_cli/development/commands.py b/marimo/_cli/development/commands.py
index ef3fbfdd31..b079f47330 100644
--- a/marimo/_cli/development/commands.py
+++ b/marimo/_cli/development/commands.py
@@ -196,6 +196,7 @@ def _generate_server_api_schema() -> dict[str, Any]:
requests.PdbRequest,
requests.PreviewDatasetColumnRequest,
requests.PreviewSQLTableListRequest,
+ requests.PreviewDataSourceConnectionRequest,
requests.PreviewSQLTableRequest,
requests.RenameRequest,
requests.SetCellConfigRequest,
diff --git a/marimo/_entrypoints/ids.py b/marimo/_entrypoints/ids.py
index f208155ecc..066eb6c253 100644
--- a/marimo/_entrypoints/ids.py
+++ b/marimo/_entrypoints/ids.py
@@ -1,3 +1,4 @@
+# Copyright 2025 Marimo. All rights reserved.
from typing import Literal
# Internal entrypoints. Not user-facing as the API is not stable.
diff --git a/marimo/_entrypoints/registry.py b/marimo/_entrypoints/registry.py
index 6a4b42bae0..f923312e10 100644
--- a/marimo/_entrypoints/registry.py
+++ b/marimo/_entrypoints/registry.py
@@ -1,3 +1,4 @@
+# Copyright 2025 Marimo. All rights reserved.
from importlib.metadata import entry_points
from typing import TYPE_CHECKING, Generic, Optional, TypeVar, cast
diff --git a/marimo/_runtime/requests.py b/marimo/_runtime/requests.py
index 9a06ee790c..7786b203af 100644
--- a/marimo/_runtime/requests.py
+++ b/marimo/_runtime/requests.py
@@ -341,6 +341,13 @@ class PreviewSQLTableListRequest:
schema: str
+@dataclass
+class PreviewDataSourceConnectionRequest:
+ """Fetch a datasource connection"""
+
+ engine: str
+
+
@dataclass
class ListSecretKeysRequest:
request_id: RequestId
@@ -363,6 +370,7 @@ ControlRequest = Union[
PdbRequest,
PreviewDatasetColumnRequest,
PreviewSQLTableListRequest,
+ PreviewDataSourceConnectionRequest,
PreviewSQLTableRequest,
RefreshSecretsRequest,
RenameRequest,
diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.py
index 4a0d9ecdae..b5925c5cd5 100644
--- a/marimo/_runtime/runtime.py
+++ b/marimo/_runtime/runtime.py
@@ -56,6 +56,7 @@ from marimo._messaging.ops import (
CellOp,
CompletedRun,
DataColumnPreview,
+ DataSourceConnections,
FunctionCallResult,
HumanReadableStatus,
InstallingPackageAlert,
@@ -126,6 +127,7 @@ from marimo._runtime.requests import (
ListSecretKeysRequest,
PdbRequest,
PreviewDatasetColumnRequest,
+ PreviewDataSourceConnectionRequest,
PreviewSQLTableListRequest,
PreviewSQLTableRequest,
RefreshSecretsRequest,
@@ -163,7 +165,10 @@ from marimo._secrets.secrets import get_secret_keys
from marimo._server.model import SessionMode
from marimo._server.types import QueueType
from marimo._sql.engines.types import SQLEngine
-from marimo._sql.get_engines import get_engines_from_variables
+from marimo._sql.get_engines import (
+ engine_to_data_source_connection,
+ get_engines_from_variables,
+)
from marimo._tracer import kernel_tracer
from marimo._types.ids import CellId_t, UIElementId, VariableName
from marimo._types.lifespan import Lifespan
@@ -2083,6 +2088,10 @@ class Kernel:
PreviewSQLTableListRequest,
self.datasets_callbacks.preview_sql_table_list,
)
+ handler.register(
+ PreviewDataSourceConnectionRequest,
+ self.datasets_callbacks.preview_datasource_connection,
+ )
# Secrets
handler.register(
ListSecretKeysRequest, self.secrets_callbacks.list_secrets
@@ -2184,20 +2193,22 @@ class DatasetCallbacks:
return
def _get_sql_engine(
- self, engine_name: str
+ self, variable_name: str
) -> tuple[Optional[SQLEngine], Optional[str]]:
- """Find the SQL engine associated with the given name. Returns the engine and the error message if any."""
- engine_name = cast(VariableName, engine_name)
+ """Find the SQL engine associated with the given variable name. Returns the engine and the error message if any."""
+ variable_name = cast(VariableName, variable_name)
try:
# Should we find the existing engine instead?
- engine_val = self._kernel.globals.get(engine_name)
- engines = get_engines_from_variables([(engine_name, engine_val)])
+ engine_val = self._kernel.globals.get(variable_name)
+ engines = get_engines_from_variables([(variable_name, engine_val)])
if engines is None or len(engines) == 0:
return None, "Engine not found"
return engines[0][1], None
except Exception as e:
- LOGGER.warning("Failed to get engine %s", engine_name, exc_info=e)
+ LOGGER.warning(
+ "Failed to get engine %s", variable_name, exc_info=e
+ )
return None, str(e)
@kernel_tracer.start_as_current_span("preview_sql_table")
@@ -2211,12 +2222,12 @@ class DatasetCallbacks:
- schema: Name of the schema
- table_name: Name of the table
"""
- engine_name = cast(VariableName, request.engine)
+ variable_name = cast(VariableName, request.engine)
database_name = request.database
schema_name = request.schema
table_name = request.table_name
- engine, error = self._get_sql_engine(engine_name)
+ engine, error = self._get_sql_engine(variable_name)
if error is not None or engine is None:
SQLTablePreview(
request_id=request.request_id, table=None, error=error
@@ -2257,11 +2268,11 @@ class DatasetCallbacks:
- database: Name of the database
- schema: Name of the schema
"""
- engine_name = cast(VariableName, request.engine)
+ variable_name = cast(VariableName, request.engine)
database_name = request.database
schema_name = request.schema
- engine, error = self._get_sql_engine(engine_name)
+ engine, error = self._get_sql_engine(variable_name)
if error is not None or engine is None:
SQLTableListPreview(
request_id=request.request_id, tables=[], error=error
@@ -2287,6 +2298,28 @@ class DatasetCallbacks:
error="Failed to get table list: " + str(e),
)
+ @kernel_tracer.start_as_current_span("preview_datasource_connection")
+ async def preview_datasource_connection(
+ self, request: PreviewDataSourceConnectionRequest
+ ) -> None:
+ """Broadcasts a datasource connection for a given engine"""
+ variable_name = cast(VariableName, request.engine)
+ engine, error = self._get_sql_engine(variable_name)
+ if error is not None or engine is None:
+ LOGGER.error("Failed to get engine %s", variable_name)
+ return
+
+ data_source_connection = engine_to_data_source_connection(
+ variable_name, engine
+ )
+
+ LOGGER.debug(
+ "Broadcasting datasource connection for %s engine", variable_name
+ )
+ DataSourceConnections(
+ connections=[data_source_connection],
+ ).broadcast()
+
class SecretsCallbacks:
def __init__(self, kernel: Kernel):
diff --git a/marimo/_server/api/endpoints/datasources.py b/marimo/_server/api/endpoints/datasources.py
index a0f1acdc98..8ec84bc609 100644
--- a/marimo/_server/api/endpoints/datasources.py
+++ b/marimo/_server/api/endpoints/datasources.py
@@ -8,6 +8,7 @@ from starlette.authentication import requires
from marimo import _loggers
from marimo._runtime.requests import (
PreviewDatasetColumnRequest,
+ PreviewDataSourceConnectionRequest,
PreviewSQLTableListRequest,
PreviewSQLTableRequest,
)
@@ -104,3 +105,29 @@ async def preview_sql_table_list(request: Request) -> BaseResponse:
from_consumer_id=ConsumerId(app_state.require_current_session_id()),
)
return SuccessResponse()
+
+
[email protected]("/preview_datasource_connection")
+@requires("edit")
+async def preview_datasource_connection(request: Request) -> BaseResponse:
+ """
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/PreviewDataSourceConnectionRequest"
+ responses:
+ 200:
+ description: Broadcasts a datasource connection
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/SuccessResponse"
+ """
+ app_state = AppState(request)
+ body = await parse_request(request, PreviewDataSourceConnectionRequest)
+ app_state.require_current_session().put_control_request(
+ body,
+ from_consumer_id=ConsumerId(app_state.require_current_session_id()),
+ )
+ return SuccessResponse()
diff --git a/marimo/_server/registry.py b/marimo/_server/registry.py
index b8771cd828..bb8b052db3 100644
--- a/marimo/_server/registry.py
+++ b/marimo/_server/registry.py
@@ -1,3 +1,4 @@
+# Copyright 2025 Marimo. All rights reserved.
from typing import TYPE_CHECKING
from marimo._entrypoints.registry import EntryPointRegistry
diff --git a/marimo/_types/lifespan.py b/marimo/_types/lifespan.py
index a613511c9c..4388f9ce05 100644
--- a/marimo/_types/lifespan.py
+++ b/marimo/_types/lifespan.py
@@ -1,3 +1,4 @@
+# Copyright 2025 Marimo. All rights reserved.
from collections.abc import (
Callable,
Mapping,
diff --git a/openapi/api.yaml b/openapi/api.yaml
index 33ff05faa8..8db2ea1e83 100644
--- a/openapi/api.yaml
+++ b/openapi/api.yaml
@@ -1848,6 +1848,13 @@ components:
required:
- cellId
type: object
+ PreviewDataSourceConnectionRequest:
+ properties:
+ engine:
+ type: string
+ required:
+ - engine
+ type: object
PreviewDatasetColumnRequest:
properties:
columnName:
@@ -2512,7 +2519,7 @@ components:
type: object
info:
title: marimo API
- version: 0.13.4
+ version: 0.13.6
openapi: 3.1.0
paths:
/@file/{filename_and_length}:
@@ -2589,6 +2596,20 @@ paths:
schema:
$ref: '#/components/schemas/SuccessResponse'
description: Preview a column in a dataset
+ /api/datasources/preview_datasource_connection:
+ post:
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/PreviewDataSourceConnectionRequest'
+ responses:
+ 200:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/SuccessResponse'
+ description: Broadcasts a datasource connection
/api/datasources/preview_sql_table:
post:
requestBody:
diff --git a/openapi/src/api.ts b/openapi/src/api.ts
index b95e4f57a5..807ada9942 100644
--- a/openapi/src/api.ts
+++ b/openapi/src/api.ts
@@ -200,6 +200,45 @@ export interface paths {
patch?: never;
trace?: never;
};
+ "/api/datasources/preview_datasource_connection": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ get?: never;
+ put?: never;
+ post: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ requestBody?: {
+ content: {
+ "application/json": components["schemas"]["PreviewDataSourceConnectionRequest"];
+ };
+ };
+ responses: {
+ /** @description Broadcasts a datasource connection */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["SuccessResponse"];
+ };
+ };
+ };
+ };
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
"/api/datasources/preview_sql_table": {
parameters: {
query?: never;
@@ -3167,6 +3206,9 @@ export interface components {
cellId: string;
request?: components["schemas"]["HTTPRequest"];
};
+ PreviewDataSourceConnectionRequest: {
+ engine: string;
+ };
PreviewDatasetColumnRequest: {
columnName: string;
fullyQualifiedTableName?: string | null;
diff --git a/tests/_server/api/endpoints/test_datasources.py b/tests/_server/api/endpoints/test_datasources.py
index 0fe2c4a132..c04646f3cd 100644
--- a/tests/_server/api/endpoints/test_datasources.py
+++ b/tests/_server/api/endpoints/test_datasources.py
@@ -67,6 +67,20 @@ def test_preview_sql_table_list(client: TestClient) -> None:
assert content["success"] is True
+@with_session(SESSION_ID)
+def test_preview_datasource_connection(client: TestClient) -> None:
+ response = client.post(
+ "/api/datasources/preview_datasource_connection",
+ headers=HEADERS,
+ json={
+ "engine": "test_engine",
+ },
+ )
+ assert response.status_code == 200, response.text
+ content = response.json()
+ assert content["success"] is True
+
+
@with_read_session(SESSION_ID)
def test_fails_in_read_mode(client: TestClient) -> None:
response = client.post(
@@ -105,3 +119,12 @@ def test_fails_in_read_mode(client: TestClient) -> None:
},
)
assert response.status_code == 401
+
+ response = client.post(
+ "/api/datasources/preview_datasource_connection",
+ headers=HEADERS,
+ json={
+ "engine": "test_engine",
+ },
+ )
+ assert response.status_code == 401