Repository navigation
feat(studio): logs SQL execution wiring + source-aware run gestures - #48414
Conversation
- Add useRunSource(id): QuerySource, deriving the run backend from the
snippet type and pairing logs runs with their session time range.
- Add useLogsSqlExecution: runs a promoted SafeLogSqlFragment against the
analytics OTEL endpoint (pinned to ClickHouse) with the resolved range as
request params; success/structured-error write to the session result store.
- Extend the Run context with runSource, executeLogsQuery, and
readEditorLogsSql; the toolbar and Cmd+Enter gestures branch on the source
and promote with the matching acceptUntrusted* at the user action.
- Gate pg intellisense off for logs snippets via useAddDefinitions({ enabled }).
- Add a required { source: 'database' | 'logs' } property to the run-button
telemetry event and fire it from both execution paths.
- Tests: useRunSource routing + useLogsSqlExecution endpoint/range/error.
A log_sql snippet is reachable by direct URL regardless of the entry-point flag gating, so a project still on legacy (BigQuery) logs could reach the run gesture. Short-circuit executeLogsQuery when otelLegacyLogs is off, recording a clear "not available yet" result-pane message instead of firing a request that would only return an opaque backend error. This is a capability guard on the gesture, not endpoint selection — the endpoint stays pinned to OTEL. Extend renderSqlEditorHook with a `flags` option so tests can set feature flags, and cover the guard.
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
This pull request has been ignored for the connected project Preview Branches by Supabase. |
📝 WalkthroughWalkthroughThe SQL editor now identifies database and logs snippets, routes each to its corresponding execution pipeline, sends logs SQL with an active time range, stores OTEL results in session state, and records the execution source in telemetry. ChangesSQL Editor Execution
Estimated code review effort: 4 (Complex) | ~45 minutes Possibly related PRs
Suggested reviewers: 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (2)
apps/studio/components/interfaces/SQLEditor/useLogsSqlExecution.test.tsx (1)
34-34: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winParse the mocked request payload instead of asserting it.
request.json()isunknown; validate it with a local Zod schema before pushing it intocapturedrather than bypassing the shape check withas CapturedBody. As per coding guidelines, “Avoid TypeScriptascasts; parse external data with zod usingparseorsafeParse.”🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/studio/components/interfaces/SQLEditor/useLogsSqlExecution.test.tsx` at line 34, Replace the CapturedBody type assertion in the mocked request handler with a local Zod schema that validates request.json() using parse or safeParse, then push the validated result into captured. Keep the existing captured payload behavior unchanged while removing the unsafe cast.Source: Coding guidelines
apps/studio/components/interfaces/SQLEditor/SQLEditorLayout.tsx (1)
73-93: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winExtract the source-branching run logic into a shared hook. Both the toolbar and the editor's Cmd+Enter gesture independently implement the same
runSource.type === 'logs'branch → read matching SQL → promote via matchingacceptUntrusted*→ call matching execute function. Centralizing this into a single hook (e.g.,useRunQueryGesture()) would prevent the two call sites from silently diverging as sources evolve.
apps/studio/components/interfaces/SQLEditor/SQLEditorLayout.tsx#L73-L93: extract this branching body (plus its refocus calls) into a shared hook that both this toolbar and the editor panel consume.apps/studio/components/interfaces/SQLEditor/SQLEditorEditorPanel.tsx#L140-L149: replace this near-duplicate branching body with a call into the same shared hook (optionally parameterized to skip the refocus calls this call site doesn't use).🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/studio/components/interfaces/SQLEditor/SQLEditorLayout.tsx` around lines 73 - 93, The duplicated source-specific query execution logic should be centralized in a shared hook such as useRunQueryGesture. In apps/studio/components/interfaces/SQLEditor/SQLEditorLayout.tsx lines 73-93, move the runSource branching, SQL reads, trust promotion, execution calls, and refocus handling into the hook; in apps/studio/components/interfaces/SQLEditor/SQLEditorEditorPanel.tsx lines 140-149, replace the duplicate branching with the same hook, allowing refocus behavior to be disabled for this call site if needed.Source: Coding guidelines
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@apps/studio/components/interfaces/SQLEditor/useLogsSqlExecution.test.tsx`:
- Line 36: Remove the explicit any generic from both HttpResponse.json calls in
the test handlers, allowing MSW to infer the response type; if inference is
insufficient, use a concrete response type instead.
---
Nitpick comments:
In `@apps/studio/components/interfaces/SQLEditor/SQLEditorLayout.tsx`:
- Around line 73-93: The duplicated source-specific query execution logic should
be centralized in a shared hook such as useRunQueryGesture. In
apps/studio/components/interfaces/SQLEditor/SQLEditorLayout.tsx lines 73-93,
move the runSource branching, SQL reads, trust promotion, execution calls, and
refocus handling into the hook; in
apps/studio/components/interfaces/SQLEditor/SQLEditorEditorPanel.tsx lines
140-149, replace the duplicate branching with the same hook, allowing refocus
behavior to be disabled for this call site if needed.
In `@apps/studio/components/interfaces/SQLEditor/useLogsSqlExecution.test.tsx`:
- Line 34: Replace the CapturedBody type assertion in the mocked request handler
with a local Zod schema that validates request.json() using parse or safeParse,
then push the validated result into captured. Keep the existing captured payload
behavior unchanged while removing the unsafe cast.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: 0ff2dc33-53c0-40a0-8f21-c0df9754d124
📒 Files selected for processing (15)
apps/studio/components/interfaces/SQLEditor/SQLEditor.types.tsapps/studio/components/interfaces/SQLEditor/SQLEditor.utils.tsapps/studio/components/interfaces/SQLEditor/SQLEditorContext.tsxapps/studio/components/interfaces/SQLEditor/SQLEditorControllers.tsxapps/studio/components/interfaces/SQLEditor/SQLEditorEditorPanel.tsxapps/studio/components/interfaces/SQLEditor/SQLEditorLayout.tsxapps/studio/components/interfaces/SQLEditor/querySource.tsapps/studio/components/interfaces/SQLEditor/useAddDefinitions.tsapps/studio/components/interfaces/SQLEditor/useLogsSqlExecution.test.tsxapps/studio/components/interfaces/SQLEditor/useLogsSqlExecution.tsapps/studio/components/interfaces/SQLEditor/useRunSource.test.tsxapps/studio/components/interfaces/SQLEditor/useRunSource.tsapps/studio/components/interfaces/SQLEditor/useSqlEditorExecution.tsapps/studio/tests/lib/sql-editor-test-utils.tsxpackages/common/telemetry-constants.ts
| response: async ({ request }) => { | ||
| const body = (await request.json()) as CapturedBody | ||
| captured.push(body) | ||
| return HttpResponse.json<any>({ result: rows }) |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== file excerpt =="
sed -n '1,120p' apps/studio/components/interfaces/SQLEditor/useLogsSqlExecution.test.tsx || true
echo
echo "== occurrences of HttpResponse.json<any> in tracked files =="
rg -n "HttpResponse\\.json<any>|HttpResponse\\.json<" apps/studio || true
echo
echo "== lint:ratchet config/scripts if present =="
if [ -f package.json ]; then jq -r '.scripts["lint:ratchet"] // empty' package.json; fi
if [ -f apps/studio/package.json ]; then jq -r '.scripts["lint:ratchet"] // empty' apps/studio/package.json || true; fi
echo
echo "== eslint any relevant configs =="
rg -n "no-explicit-any|`@typescript-eslint/`.*any|ratchet|allowUnused" .github apps/studio package.json apps/studio/package.json 2>/dev/null || trueRepository: supabase/supabase
Length of output: 50374
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== target test file excerpts =="
sed -n '1,110p' apps/studio/components/interfaces/SQLEditor/useLogsSqlExecution.test.tsx
echo
echo "== targeted HttpResponse.json<any> count =="
python3 - <<'PY'
from pathlib import Path
import re
p=Path('apps/studio/components/interfaces/SQLEditor/useLogsSqlExecution.test.tsx')
text=p.read_text()
print(len(re.findall(r'HttpResponse\.json<any>', text)))
for i,line in enumerate(text.splitlines(),1):
if 'HttpResponse.json<any>' in line:
print(f'{i}: {line.strip()}')
PY
echo
echo "== lint:ratchet scripts =="
for f in package.json apps/studio/package.json; do
if [ -f "$f" ]; then
echo "-- $f --"
node -e "const fs=require('fs'); const pkg=JSON.parse(fs.readFileSync('$f','utf8')); console.log(JSON.stringify(pkg.scripts?.['lint:ratchet']??null,null,2))"
fi
done
echo
echo "== any count relevant config mentions =="
rg -n --hidden --glob '!node_modules' --glob '!dist' --glob '!build' "lint:ratchet|no-explicit-any|explicit-any|allowUnsafe|allowUnnecessary|`@typescript-eslint`" .github apps/studio package.json apps/studio/package.json .eslintrc* eslint.config.* 2>/dev/null | head -200 || trueRepository: supabase/supabase
Length of output: 8985
Remove the explicit any response types.
apps/studio/components/interfaces/SQLEditor/useLogsSqlExecution.test.tsx now adds explicit any, which is tracked by the studio ratcheted @typescript-eslint/no-explicit-any baseline. Let MSW infer the response type at both HttpResponse.json<any> calls, or replace them with concrete response types.
Proposed fix
- return HttpResponse.json<any>({ result: rows })
+ return HttpResponse.json({ result: rows })
...
- HttpResponse.json<any>({
+ HttpResponse.json({📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| return HttpResponse.json<any>({ result: rows }) | |
| return HttpResponse.json({ result: rows }) |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@apps/studio/components/interfaces/SQLEditor/useLogsSqlExecution.test.tsx` at
line 36, Remove the explicit any generic from both HttpResponse.json calls in
the test handlers, allowing MSW to infer the response type; if inference is
insufficient, use a concrete response type instead.
Source: Coding guidelines
🎭 Playwright Test Results (next)Details
Flaky testsFeatures › table-editor.spec.ts › table editor › should show rls accordingly Skipped testsFeatures › auth-users.spec.ts › should show web3 users as enabled when the matching web3 provider is enabled |
| if (!isOtelLogsEnabled) { | ||
| getSqlEditorSessionSnapshot().addResultError(id, { | ||
| message: "Querying logs from the SQL editor isn't available for this project yet.", | ||
| }) | ||
| return | ||
| } |
There was a problem hiding this comment.
Do we want to track or log the error here? This looks like the only code path where we're not sending an event.
There was a problem hiding this comment.
This is just a failsafe while the feature flag is being rolled out, there is a very niche way in which users can manually reach this screen which requires bypassing the rest of the UI, I think it's safe to not track it.
There was a problem hiding this comment.
SGTM! Thanks for following up!
Braintrust eval report
|
…8452) ## What PR 6 of the SQL-editor "query source (Database vs Logs)" stack (builds on the merged PR 5, #48414). Adds the user-facing toolbar surface for the logs query source and consolidates the SQL-editor toolbar into a single **source menu**. Everything stays behind `sqlEditorLogsSource` + `otelLegacyLogs` (dual-flag gated); with the flags off the toolbar is unchanged. ## Changes - **Consolidated source menu** (`QuerySourceMenu`) — one `Database ▾` / `Logs ▾` dropdown that both labels the snippet's source and hosts the source-specific controls as flyout submenus: - Database: database selector (`Primary` / read replicas), `Run as` (role impersonation), and `Row limit`. - Logs: `Time range` — the same relative presets as the Logs Explorer plus a `Custom range…` calendar dialog. - **Source is immutable** — the Database/Logs rows aren't a toggle. An existing (materialized) snippet opens a *fresh* tab of the target source (never reinterpreting a query against the wrong backend); a blank new tab re-flavors in place. Extracted as the pure, unit-tested `resolveSourceSwitch`. - **New-snippet-with-source** threaded through `/sql/new?source=`, the nav "Create a new logs query" entry, and the duplicate flow. Logs snippets hide the (db-dialect) Export action. - **Run-affordance guard** — the Run button is disabled + annotated for a logs snippet on a non-ClickHouse org (sits above PR 5's execution short-circuit). - **Retention entitlement gating** — both preset and custom logs ranges past `log.retention_days` surface the upgrade prompt instead of applying silently. Prettify is disabled for logs (sql-formatter mangles ClickHouse). ## Tests - `querySource.test.ts` — `logDateRangesEqual` (structural relative/absolute matching, incl. the "Last hour" vs "Last 1 hour" label case). - `QuerySourceMenu.utils.test.ts` — `resolveSourceSwitch` push-vs-replace / no-op behavior. `pnpm --filter studio typecheck` · `lint:ratchet` · Prettier · SQL editor suite (307 tests) all green. ## For reviewers To test manually, enable the `sqlEditorLogsSource` feature flag for yourself on local/staging. There is no nav for Log SQL snippets currently (that is by design, this PR is big enough as-is), so to check an existing logs snippet, you can create one using the existing Logs Explorer, copy its UUID, and force navigate to that snippet in the SQL editor via URL. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Added support for creating and switching between database and logs queries. * Added log time-range presets and custom date-range selection. * Added database, run-as role, and row-limit controls. * Added read-replica selection, including options to create a new replica when available. * **Improvements** * Added clearer explanations when query execution is unavailable. * Disabled SQL formatting and query export where unsupported for logs queries. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Joshen Lim <[email protected]>
I have read the CONTRIBUTING.md file.
YES
What kind of change does this PR introduce?
Feature (SQL editor: execution wiring for logs-source snippets). Part of the stacked SQL-editor "Database vs Logs" query-source series.
What is the current behavior?
The SQL editor only ever runs queries against the user's Postgres database. There is no execution path for a logs (
log_sql) snippet, and the run-button telemetry event carries no backend discriminator.What is the new behavior?
useRunSource(id)derives the run backend from the snippet type; alog_sqlsnippet resolves to{ type: 'logs', dateRange }, pairing the run with its session time range (default: last hour).useLogsSqlExecutionruns a promotedSafeLogSqlFragmentagainst the analytics OTEL (ClickHouse) endpoint with the resolved time range asiso_timestamp_start/iso_timestamp_endrequest params. The endpoint is pinned to OTEL — a snippet's dialect must not flip with org migration.acceptUntrusted*right at the user action, preserving the auditable promotion-at-gesture boundary. pg intellisense is gated off for logs snippets.sql_editor_query_run_button_clickedtelemetry event gains a required{ source: 'database' | 'logs' }property, fired from both execution paths.log_sqlsnippet is reachable by direct URL regardless of the (later) entry-point flag gating, soexecuteLogsQueryshort-circuits whenotelLegacyLogsis off — recording a clear "not available yet" result message instead of firing a request that would only return an opaque backend error on a non-ClickHouse project. This is a guard on the gesture, not endpoint selection.useRunSourcerouting,useLogsSqlExecutionendpoint/range/structured-error/capability-guard, and a reusableflagsoption onrenderSqlEditorHook.No UI entry points are added — the feature runs dark until the flag-gated creation/nav PRs later in the stack.
Additional context
Stacked on the query-source series; base branch is
masternow that PR 4 (log date range domain + session state, #48401) is merged. Follow-ups in the stack add the toolbar/creation UI (with a run-affordance gate onotelLegacyLogs), nav section, AI dialect support, and reports guard.Summary by CodeRabbit
New Features
Tests