Repository navigation
refactor(studio): centralize query sources - #49027
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
5 Skipped Deployments
|
|
This pull request has been ignored for the connected project Preview Branches by Supabase. |
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (2)
🚧 Files skipped from review as they are similar to previous changes (2)
📝 WalkthroughWalkthroughThe SQL editor now uses a shared query-source registry and ChangesQuery source and log range migration
Estimated code review effort: 4 (Complex) | ~45 minutes Mergeability Score: 🔵 Low · up to The shared database source selector may fail to place the primary database first when results arrive in a different order, creating a bounded selection experience issue. The PR is otherwise mergeable with explicit owner awareness or follow-up for this ordering behavior. Sequence Diagram(s)sequenceDiagram
participant User
participant QuerySourceMenu
participant LogsTimeRangeSubMenu
participant useLogsCustomRange
participant SQLExecution
User->>QuerySourceMenu: open source menu
QuerySourceMenu->>LogsTimeRangeSubMenu: provide selected LogTimeRange
User->>LogsTimeRangeSubMenu: select preset or custom range
LogsTimeRangeSubMenu->>useLogsCustomRange: validate custom range
useLogsCustomRange->>QuerySourceMenu: return range or upgrade state
QuerySourceMenu->>SQLExecution: execute query with source parameters
Possibly related PRs
Suggested reviewers: 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 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 |
🎭 Playwright Test Results (next)Details
Flaky testsFeatures › database.spec.ts › Database › Schema Visualizer › table actions work as expected Skipped testsFeatures › auth-users.spec.ts › should show web3 users as enabled when the matching web3 provider is enabled |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (6)
apps/studio/components/interfaces/QuerySources/LogTimeRange.utils.ts (1)
14-14: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winRemove the unnecessary type assertion.
LogTimeRangestores absolute values asstring. TheIsoDateTimeStringreturn annotation is not needed here. Remove theas IsoDateTimeStringassertion.Proposed fix
-import { isoDateTimeString, type IsoDateTimeString } from '`@/lib/iso-datetime`' +import { isoDateTimeString } from '`@/lib/iso-datetime`' -const nowIsoDateTime = (): IsoDateTimeString => dayjs().toISOString() as IsoDateTimeString +const nowIsoDateTime = () => dayjs().toISOString()As per coding guidelines: “Avoid TypeScript
ascasts.”🤖 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/QuerySources/LogTimeRange.utils.ts` at line 14, Update nowIsoDateTime to return the dayjs().toISOString() result directly, removing the unnecessary IsoDateTimeString annotation and as IsoDateTimeString assertion while preserving the existing ISO timestamp behavior.Source: Coding guidelines
apps/studio/components/interfaces/SQLEditor/UtilityPanel/QuerySourceMenu/QuerySourceMenu.tsx (2)
87-97: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueRename the internal handlers to the
handleXform.
switchSourceandupdateDatabaseIdentifierare internal event handlers. The studio guidelines requirehandleXfor internal handlers and reserveonXfor prop callbacks.♻️ Optional rename
- const switchSource = (target: SqlSnippetSource) => { + const handleSwitchSource = (target: SqlSnippetSource) => { const next = resolveSourceSwitch({ ref, target, currentSource, isBlankNewTab }) if (next === null) return router[next.method](next.url) } - const updateDatabaseIdentifier = (identifier: string) => { + const handleDatabaseIdentifierChange = (identifier: string) => { databaseSelector.setSelectedDatabaseId(identifier) setLastSelectedDatabase(identifier) sessionSnap.resetResult(id) }Update the call sites on lines 119 and 144.
As per coding guidelines: "Name prop callbacks
onXand internal event handlershandleX".🤖 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/UtilityPanel/QuerySourceMenu/QuerySourceMenu.tsx` around lines 87 - 97, Rename the internal handlers switchSource and updateDatabaseIdentifier to handleSwitchSource and handleUpdateDatabaseIdentifier, respectively, and update all corresponding call sites, including the usages near lines 119 and 144.Source: Coding guidelines
59-63: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚖️ Poor tradeoffTwo stores hold the selected database, and local storage always wins.
databaseSelector.selectedDatabaseIdand theSQL_EDITOR_LAST_SELECTED_DBlocal-storage entry both hold the selection. Line 79 prefers local storage. If another surface updatesdatabaseSelector.selectedDatabaseId, this menu keeps showing the stale local-storage value until the user picks a database here. Consider treating the global selector as the source of truth and using local storage only to seed it on mount.Also applies to: 78-81
🤖 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/UtilityPanel/QuerySourceMenu/QuerySourceMenu.tsx` around lines 59 - 63, Update QuerySourceMenu’s selected-database resolution to treat databaseSelector.selectedDatabaseId as the source of truth instead of always preferring lastSelectedDatabase. Use SQL_EDITOR_LAST_SELECTED_DB only to initialize or seed the global selector on mount, then keep the menu synchronized with subsequent databaseSelector changes.apps/studio/components/interfaces/SQLEditor/querySource.ts (1)
11-11: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueConsider importing
QuerySourceIddirectly in consumers.
SqlSnippetSourceis now a pure alias of the registry type. Consumers such asQuerySourceMenu.tsximport it from this module instead of from the registry, which keeps an indirection to the moved contract. If the alias exists only for compatibility, remove it and importQuerySourceIdat the call sites. Keep it only if the SQL-editor-specific name carries domain meaning forgetSnippetSourceandresolveSnippetSource.As per coding guidelines: "When moving or extracting code, update every importer to the new module directly; do not leave backward-compatibility re-export shims."
🤖 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/querySource.ts` at line 11, Remove the pure SqlSnippetSource alias from querySource.ts and update consumers such as QuerySourceMenu.tsx, getSnippetSource, and resolveSnippetSource to import and use QuerySourceId directly from the registry module. Ensure all importers reference the moved contract directly without retaining a compatibility shim.Source: Coding guidelines
apps/studio/components/interfaces/QuerySources/QuerySourceIcon.tsx (1)
12-14: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueConsider an exhaustive icon map keyed by
QuerySourceId.The ternary treats every non-
logsid asDatabase. When a third source is added to the registry, it silently gets the database icon. ARecord<QuerySourceId, ...>makes the compiler require an entry.♻️ Optional refactor
- const props = { className, size: 16, strokeWidth: 2 } - - return source === 'logs' ? <ScrollText {...props} /> : <Database {...props} /> + const Icon = QUERY_SOURCE_ICONS[source] + + return <Icon className={className} size={16} strokeWidth={2} />Add alongside the component:
const QUERY_SOURCE_ICONS: Record<QuerySourceId, typeof Database> = { database: Database, logs: ScrollText, }🤖 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/QuerySources/QuerySourceIcon.tsx` around lines 12 - 14, Replace the fallback ternary in QuerySourceIcon with an exhaustive QUERY_SOURCE_ICONS map typed as Record<QuerySourceId, typeof Database>, mapping database to Database and logs to ScrollText. Use the map entry for rendering so adding a new QuerySourceId requires an explicit icon.apps/studio/components/interfaces/QuerySources/LogsTimeRangeSubMenu.test.tsx (1)
38-57: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd a test for the allowed preset path.
The suite covers the locked preset and the custom-range action. It does not cover the main path: selecting a preset inside the retention window must call
onRangeChangewith the matchingLogTimeRange. Add that case so a regression indatePickerValueToLogTimeRangeor in the click handler is caught.♻️ Suggested additional test
+ it('applies a preset inside the retention window', async () => { + const { onRangeChange, onShowUpgrade } = renderSubMenu() + + await userEvent.hover(await screen.findByText('Time range')) + await userEvent.click(await screen.findByText('Last hour')) + + expect(onRangeChange).toHaveBeenCalledWith({ type: 'relative', amount: 1, unit: 'hour' }) + expect(onShowUpgrade).not.toHaveBeenCalled() + })Adjust the preset label and expected range to match
EXPLORER_DATEPICKER_HELPERS.🤖 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/QuerySources/LogsTimeRangeSubMenu.test.tsx` around lines 38 - 57, Add a test in the LogsTimeRangeSubMenu suite for selecting an allowed preset within retention, using a label and expected LogTimeRange from EXPLORER_DATEPICKER_HELPERS; verify onRangeChange is called with the matching range and the upgrade prompt is not shown, covering datePickerValueToLogTimeRange and the click handler.
🤖 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/QuerySources/DatabaseParametersSubMenu.tsx`:
- Around line 33-36: Update the two sort comparators in the databases ordering
chain to return negative, zero, or positive results for all ordering cases:
compare inserted_at values in both directions, then compare identifier against
projectRef using both database arguments so the primary database is
deterministically first. Preserve the existing data fallback and ordering
priority.
In `@apps/studio/data/query-sources/query-source-registry.ts`:
- Around line 82-97: Update the absolute branch of logTimeRangeSchema so
validation requires to to be strictly later than from, while preserving
independent ISO datetime validation. Add rejection tests in
query-source-registry.test.ts covering equal and earlier to values, and verify
resolveLogTimeRange does not accept inverted ranges.
---
Nitpick comments:
In
`@apps/studio/components/interfaces/QuerySources/LogsTimeRangeSubMenu.test.tsx`:
- Around line 38-57: Add a test in the LogsTimeRangeSubMenu suite for selecting
an allowed preset within retention, using a label and expected LogTimeRange from
EXPLORER_DATEPICKER_HELPERS; verify onRangeChange is called with the matching
range and the upgrade prompt is not shown, covering
datePickerValueToLogTimeRange and the click handler.
In `@apps/studio/components/interfaces/QuerySources/LogTimeRange.utils.ts`:
- Line 14: Update nowIsoDateTime to return the dayjs().toISOString() result
directly, removing the unnecessary IsoDateTimeString annotation and as
IsoDateTimeString assertion while preserving the existing ISO timestamp
behavior.
In `@apps/studio/components/interfaces/QuerySources/QuerySourceIcon.tsx`:
- Around line 12-14: Replace the fallback ternary in QuerySourceIcon with an
exhaustive QUERY_SOURCE_ICONS map typed as Record<QuerySourceId, typeof
Database>, mapping database to Database and logs to ScrollText. Use the map
entry for rendering so adding a new QuerySourceId requires an explicit icon.
In `@apps/studio/components/interfaces/SQLEditor/querySource.ts`:
- Line 11: Remove the pure SqlSnippetSource alias from querySource.ts and update
consumers such as QuerySourceMenu.tsx, getSnippetSource, and
resolveSnippetSource to import and use QuerySourceId directly from the registry
module. Ensure all importers reference the moved contract directly without
retaining a compatibility shim.
In
`@apps/studio/components/interfaces/SQLEditor/UtilityPanel/QuerySourceMenu/QuerySourceMenu.tsx`:
- Around line 87-97: Rename the internal handlers switchSource and
updateDatabaseIdentifier to handleSwitchSource and
handleUpdateDatabaseIdentifier, respectively, and update all corresponding call
sites, including the usages near lines 119 and 144.
- Around line 59-63: Update QuerySourceMenu’s selected-database resolution to
treat databaseSelector.selectedDatabaseId as the source of truth instead of
always preferring lastSelectedDatabase. Use SQL_EDITOR_LAST_SELECTED_DB only to
initialize or seed the global selector on mount, then keep the menu synchronized
with subsequent databaseSelector changes.
🪄 Autofix
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: 0bde7c23-e09f-4f1e-a2df-b9b26921b418
📒 Files selected for processing (21)
apps/studio/components/interfaces/QuerySources/DatabaseParametersSubMenu.tsxapps/studio/components/interfaces/QuerySources/LogTimeRange.utils.test.tsapps/studio/components/interfaces/QuerySources/LogTimeRange.utils.tsapps/studio/components/interfaces/QuerySources/LogsCustomRangeDialog.tsxapps/studio/components/interfaces/QuerySources/LogsTimeRangeSubMenu.test.tsxapps/studio/components/interfaces/QuerySources/LogsTimeRangeSubMenu.tsxapps/studio/components/interfaces/QuerySources/QuerySourceIcon.tsxapps/studio/components/interfaces/QuerySources/useLogsCustomRange.tsapps/studio/components/interfaces/SQLEditor/UtilityPanel/QuerySourceMenu/QuerySourceMenu.tsxapps/studio/components/interfaces/SQLEditor/querySource.test.tsapps/studio/components/interfaces/SQLEditor/querySource.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/data/query-sources/query-source-registry.test.tsapps/studio/data/query-sources/query-source-registry.tsapps/studio/data/sql/execute-sql-mutation.tsapps/studio/state/sql-editor/sql-editor-session-state.tsapps/studio/tests/components/SQLEditor/QuerySourceMenu.test.tsxapps/studio/tests/features/logs/Logs.Datepickers.test.tsx
e648a8c to
f331cab
Compare
There was a problem hiding this comment.
Preview test — ⚠️ issue found
Ran through the "To test" steps plus two regression checks on the studio-staging preview, reusing an existing project.
| # | Test | Result |
|---|---|---|
| 1 | Run an existing query against the database | ✅ select * from pg_catalog.pg_tables limit 5; executed cleanly, 5 rows returned. |
| 2 | Switch source to Logs, change time range, run a query | ✅ Legacy Logs-Explorer syntax correctly errors with a message pointing at the new ClickHouse-backed engine; modern ClickHouse-style syntax ran fine and returned results. Time range ("Last 24 hours") sent correctly on the wire. |
| 3 | (addition) Switch back to Database, confirm routing/content intact | ✅ Snippet content and "Query source: Database" label unchanged; re-run hit the database query endpoint, not logs — no leftover Logs-mode state. |
| 4 | (addition) Custom/absolute log time range + retention-aware upgrade prompt | |
| 5 | Source icon consistency (16px/2px claim) | ✅ Database and Logs icons in the selector menu are visually consistent in size and stroke weight. |
Issue on #4: The out-of-retention case works correctly — selecting a range ~66-73 days back on a 28-day (Team plan) project correctly shows a "Log retention" dialog with the plan/duration table and an Upgrade CTA. But the custom time-range picker doesn't reset its internal state cleanly: after that prompt is dismissed, reopening "Custom range…" and picking a perfectly valid in-retention range re-triggers the same retention dialog — a stale start-date anchor from the earlier rejected selection carries over. It only clears after a full page reload. Screenshots attached below.
Notes:
- Minor observation on #2: clicking "Logs" in the source selector opens a new browser tab rather than switching the current tab in place — didn't verify if that's intentional, flagging in case it isn't.
- No console errors tied to source-switching, logs queries, or the retention dialog beyond pre-existing baseline noise (unrelated 404 and a Radix a11y warning).
- Side effects: one new saved snippet ("Untitled query"), and a pre-existing Logs snippet had its content edited during testing but never saved. No projects created or deleted.
- Skipped:
pnpm --filter studio typecheck, Vitest, and lint — local commands, out of scope here.
joshenlim
left a comment
There was a problem hiding this comment.
minimally verified sql editor query source works
code changes are just decoupling the query source menu from the sql editor state
Braintrust eval report
|
## Stack Depends on #49027. Followed by #49038. ## Summary - extract a controlled `QueryEditor` from the existing notebook query cell - reuse it from `QueryCell`, leaving notebook persistence and sortable-block behavior in the adapter - make table/chart result settings controlled so other query surfaces can share them - persist notebook SQL on editor blur and query execution ## To test 1. Open a notebook query cell, edit and rename it, then run the query and confirm results appear. 2. Switch between table and chart results and confirm notebook move/delete actions still work. ## Why Notebooks, query tabs, and future chat tabs need consistent query actions and result rendering without duplicating the notebook implementation. ## Impact This is primarily a refactor of the existing notebook query experience. It introduces no new query-tab routes or source-selection behavior. ## Validation - fresh non-incremental Studio TypeScript check - focused NotebookEditor component tests <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Added a shared query editor with SQL editing, execution, validation, visibility controls, editable titles, row limits, and loading/error states. * Added table and chart result views, including customizable bar and line charts. * Added support for switching display modes and updating chart settings. * **Improvements** * Improved query result handling and display-setting updates. * Repositioned the logarithmic-scale tooltip for better visibility. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Joshen Lim <[email protected]>
Summary
To test
Why
Explorer queries and notebook query cells need to select an execution source without coupling that source to SQL snippets. This provides the shared registry and controlled UI foundation for those consumers.
Impact
Existing SQL snippets retain their current database/logs routing and session behavior. The registry documents the SQL editor legacy database-selector adapter while new consumers own their identifier inline. The shared Logs date picker remains unchanged; query ranges support its existing minute, hour, and day units. This PR does not add the Explorer query tab itself.
Validation
Component and state tests cover this change per the Studio testing guidance; no E2E test is added.
Summary by CodeRabbit
New Features
Bug Fixes
Tests