Repository navigation
feat(studio): logs snippets in SQL editor nav, search, and tabs - #48457
Conversation
|
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. |
📝 WalkthroughWalkthroughAdds ChangesSQL logs navigation
Estimated code review effort: 4 (Complex) | ~45 minutes Possibly related PRs
Suggested labels: Suggested reviewers: Sequence Diagram(s)sequenceDiagram
participant SQLPage
participant TabsState
participant SQLEditorNav
participant LogsSnippetsSection
participant ContentAPI
SQLPage->>TabsState: create or backfill sqlSource
SQLEditorNav->>LogsSnippetsSection: render gated Logs section
LogsSnippetsSection->>ContentAPI: fetch log_sql snippets
ContentAPI-->>LogsSnippetsSection: return paginated snippets
LogsSnippetsSection-->>SQLEditorNav: report loaded snippets
SQLEditorNav->>TabsState: cleanup stale tabs with logs pruning guard
🚥 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 |
|
@coderabbitai review |
✅ Action performedReview finished.
|
🎭 Playwright Test Results (next)Details
Flaky testsFeatures › realtime-inspector.spec.ts › Realtime Inspector › Basic Inspector UI › can join and leave a channel 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: 3
🧹 Nitpick comments (2)
apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SearchList.tsx (1)
110-118: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winFlatten the nested count-state ternary.
Render the loading and loaded count states with mutually exclusive
&&guards.As per coding guidelines, “never nest ternaries” and “render fetch states with top-level early returns or a flat chain of mutually exclusive
&&guards.”Proposed change
- {isLoadingCounts ? ( + {isLoadingCounts && ( <div className="px-4 py-1 pb-2.5"> <Loader2 className="animate-spin" size={14} /> </div> - ) : hasCounts ? ( + )} + {!isLoadingCounts && hasCounts && ( <p className="px-4 pb-2 text-sm text-foreground-lighter"> {totalNumber} result{totalNumber === 1 ? '' : 's'} found </p> - ) : null} + )}🤖 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/layouts/SQLEditorLayout/SQLEditorNavV2/SearchList.tsx` around lines 110 - 118, Update the count-state rendering in SearchList to remove the nested ternary. Use mutually exclusive && guards so the loading indicator renders when isLoadingCounts is true, and the result count renders only when loading is false and hasCounts is true; preserve the existing content and styling.Source: Coding guidelines
apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SqlSnippetTree.tsx (1)
60-65: 📐 Maintainability & Code Quality | 🔵 Trivial | 🏗️ Heavy liftType the tree metadata instead of casting it.
The new shared component relies on
as Snippetand additional string casts. MakeTreeViewItemProps/the tree component preserveSnippetmetadata so invalid nodes fail at compile time.As per coding guidelines, “Avoid TypeScript
ascasts.”Also applies to: 74-94
🤖 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/layouts/SQLEditorLayout/SQLEditorNavV2/SqlSnippetTree.tsx` around lines 60 - 65, Update the tree component and its TreeViewItemProps typing so metadata is parameterized as Snippet throughout, including the nodeRenderer callback, instead of using `as Snippet` or string casts. Ensure the shared tree preserves this metadata type and rejects incompatible nodes at compile time while keeping the existing snippet navigation behavior unchanged.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/layouts/SQLEditorLayout/SQLEditorNavV2/SearchList.tsx`:
- Around line 60-105: Prevent stale placeholder results from being rendered as
current search results in the SearchList query flow. Track isPlaceholderData
from both useSqlSnippetsQuery calls and both useContentCountQuery calls, then
treat those values as loading and exclude their data from displayed trees,
counts, and totals until the active search queries resolve; alternatively remove
keepPreviousData for these searches while preserving the existing enabled
behavior.
In
`@apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorNav.tsx`:
- Around line 75-83: Update the auto-expansion effect in SQLEditorNav to check
getSnippetSource(snippet) before the visibility-based branching, and set the
logs section visibility to true for an active log_sql snippet. Preserve the
existing visibility behavior for all other snippet sources.
- Around line 485-492: The logs-tab cleanup in SQLEditorNav must wait until the
logs infinite query has fetched every page before allowing pruning. Update the
condition or canPruneLogsTabs value around logsSnippetsInView and its
hasNextPage/loading state so sqlEditorTabsCleanup receives canPruneLogsTabs only
when no pages remain unfetched; preserve cleanup for non-logs tabs and the
existing failure handling.
---
Nitpick comments:
In
`@apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SearchList.tsx`:
- Around line 110-118: Update the count-state rendering in SearchList to remove
the nested ternary. Use mutually exclusive && guards so the loading indicator
renders when isLoadingCounts is true, and the result count renders only when
loading is false and hasCounts is true; preserve the existing content and
styling.
In
`@apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SqlSnippetTree.tsx`:
- Around line 60-65: Update the tree component and its TreeViewItemProps typing
so metadata is parameterized as Snippet throughout, including the nodeRenderer
callback, instead of using `as Snippet` or string casts. Ensure the shared tree
preserves this metadata type and rejects incompatible nodes at compile time
while keeping the existing snippet navigation behavior unchanged.
🪄 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: 1790d9e4-8645-43dc-b91f-1b2923eddaed
📒 Files selected for processing (18)
apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/LogsSnippetsSection.tsxapps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorNav.constants.tsapps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorNav.tsxapps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorNav.utils.tsapps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorTreeViewItem.tsxapps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SearchList.tsxapps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SqlSnippetTree.tsxapps/studio/components/layouts/Tabs/RecentItems.tsxapps/studio/components/layouts/Tabs/SortableTab.tsxapps/studio/components/layouts/Tabs/TabPreview.tsxapps/studio/components/layouts/Tabs/Tabs.utils.test.tsxapps/studio/components/layouts/Tabs/Tabs.utils.tsapps/studio/components/ui/EntityTypeIcon.tsxapps/studio/data/content/keys.tsapps/studio/data/content/sql-snippets-query.tsapps/studio/pages/project/[ref]/sql/[id].tsxapps/studio/state/tabs.test.tsapps/studio/state/tabs.tsx
3ae7d7a to
bb92c9b
Compare
There was a problem hiding this comment.
Actionable comments posted: 3
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorNav.tsx (1)
430-445: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winActive logs snippet never opens the Logs section.
This effect only checks
snippet.visibility('project'/'user') to auto-open Shared/Private. Alog_sqlactive snippet hasvisibility: 'user', so it will flipprivate: trueinstead oflogs: true, leaving the Logs section collapsed even though the snippet is force-injected into it viaactiveSnippet. CheckgetSnippetSource(snippet) === 'logs'first.This was flagged in a prior review on this same effect and doesn't appear to have been addressed yet.
🐛 Proposed fix
useEffect(() => { if (snippet !== undefined && isSuccess) { - if (snippet.visibility === 'project') { + if (getSnippetSource(snippet) === 'logs') { + setSectionVisibility({ ...sectionVisibility, logs: true }) + } else if (snippet.visibility === 'project') { setSectionVisibility({ ...sectionVisibility, shared: true }) } else if (snippet.visibility === 'user') { setSectionVisibility({ ...sectionVisibility, private: true }) }🤖 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/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorNav.tsx` around lines 430 - 445, Update the visibility handling in the useEffect around getSnippetSource so snippets whose source is 'logs' set the logs section open before checking snippet.visibility. Keep the existing shared/private behavior for non-logs snippets, while preserving the folder expansion logic.
♻️ Duplicate comments (1)
apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SearchList.tsx (1)
60-96: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winStale search results/counts can render without a loading indicator.
None of the four queries here (
sqlresults,sqlcount,log_sqlcount,log_sqlresults) destructureisPlaceholderData, even though all useplaceholderData: keepPreviousData.isPending/isSearchLoading/isLoadingCountsstayfalseonce any previous-search data exists, so whensearchchanges, the UI keeps showing the previous search's results and "N results found" count as if they were current, then swaps abruptly once the new data resolves.This reproduces a past review finding on this file that was marked addressed on an earlier commit — it looks like the addressed fix didn't carry over through the refactor that split this into separate
sql/log_sqlqueries.🤖 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/layouts/SQLEditorLayout/SQLEditorNavV2/SearchList.tsx` around lines 60 - 96, Update all four queries in the SearchList query block to destructure isPlaceholderData and incorporate it into the loading-state calculations. Ensure stale placeholder results and counts are treated as loading after search changes, including the combined isSearchLoading, isLoadingCounts, and log-section loading paths, so previous-search data is not presented as current.
🧹 Nitpick comments (1)
apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorNav.tsx (1)
78-84: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winLogs feature-flag gating duplicated across two files. The identical
sqlEditorLogsSource && otelLegacyLogscombination is computed independently in both files; extracting a shared hook keeps them from drifting if the gating logic changes.
apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorNav.tsx#L78-L84: replace with a shareduseCanShowLogsSection()hook (e.g. placed alongsideSQLEditorNav.utils.ts).apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SearchList.tsx#L54-L56: consume the same shared hook instead of re-deriving the flags.🤖 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/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorNav.tsx` around lines 78 - 84, Extract the duplicated logs feature-flag gating into a shared useCanShowLogsSection hook. In apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorNav.tsx lines 78-84, replace the local flag combination with the hook; in apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SearchList.tsx lines 54-56, consume the same hook instead of re-deriving sqlEditorLogsSource and otelLegacyLogs.
🤖 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/layouts/SQLEditorLayout/SQLEditorNavV2/LogsSnippetsSection.tsx`:
- Around line 88-91: Prevent log-tab pruning until every logs page has been
fetched: update LogsSnippetsSection.tsx lines 88-91 to include hasNextPage or an
equivalent fully-loaded flag in the onSnippetsLoaded payload, then update
SQLEditorNav.tsx lines 485-501 to set canPruneLogsTabs only when the query is
successful and hasNextPage is false.
In
`@apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SearchList.tsx`:
- Around line 110-118: Replace the nested ternary in the fetch-state rendering
around isLoadingCounts and hasCounts with mutually exclusive flat conditional
rendering: show the loader when isLoadingCounts is true, show the result count
only when loading is false and hasCounts is true, and render nothing otherwise.
Preserve the existing Loader2 and totalNumber display behavior.
In `@apps/studio/components/layouts/Tabs/Tabs.utils.test.tsx`:
- Around line 60-72: Extend the test case around cleanup({ snippets: [],
canPruneLogsTabs: false }) to assert recent-item behavior as well as open tabs:
verify the logs entry sql-logs remains in recent items and the stale database
entry sql-db-stale is removed. Use the store’s existing recent-items state or
accessor created by addTab, without changing the cleanup setup.
---
Outside diff comments:
In
`@apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorNav.tsx`:
- Around line 430-445: Update the visibility handling in the useEffect around
getSnippetSource so snippets whose source is 'logs' set the logs section open
before checking snippet.visibility. Keep the existing shared/private behavior
for non-logs snippets, while preserving the folder expansion logic.
---
Duplicate comments:
In
`@apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SearchList.tsx`:
- Around line 60-96: Update all four queries in the SearchList query block to
destructure isPlaceholderData and incorporate it into the loading-state
calculations. Ensure stale placeholder results and counts are treated as loading
after search changes, including the combined isSearchLoading, isLoadingCounts,
and log-section loading paths, so previous-search data is not presented as
current.
---
Nitpick comments:
In
`@apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorNav.tsx`:
- Around line 78-84: Extract the duplicated logs feature-flag gating into a
shared useCanShowLogsSection hook. In
apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorNav.tsx
lines 78-84, replace the local flag combination with the hook; in
apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SearchList.tsx
lines 54-56, consume the same hook instead of re-deriving sqlEditorLogsSource
and otelLegacyLogs.
🪄 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: bf9558ee-b797-4282-8eab-5e337676cc9a
📒 Files selected for processing (16)
apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/LogsSnippetsSection.tsxapps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorNav.constants.tsapps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorNav.tsxapps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorNav.utils.tsapps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorTreeViewItem.tsxapps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SearchList.tsxapps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SqlSnippetTree.tsxapps/studio/components/layouts/Tabs/RecentItems.tsxapps/studio/components/layouts/Tabs/SortableTab.tsxapps/studio/components/layouts/Tabs/TabPreview.tsxapps/studio/components/layouts/Tabs/Tabs.utils.test.tsxapps/studio/components/layouts/Tabs/Tabs.utils.tsapps/studio/components/ui/EntityTypeIcon.tsxapps/studio/data/content/keys.tsapps/studio/data/content/sql-snippets-query.tsapps/studio/pages/project/[ref]/sql/[id].tsx
🚧 Files skipped from review as they are similar to previous changes (3)
- apps/studio/components/layouts/Tabs/TabPreview.tsx
- apps/studio/components/layouts/Tabs/SortableTab.tsx
- apps/studio/data/content/keys.ts
joshenlim
left a comment
There was a problem hiding this comment.
Preview test — ✅ all pass
This PR didn't have an explicit "To test" section, so I inferred the checklist from the summary + diff (dual-flag-gated logs snippets support in the SQL editor nav, search, and tabs) and ran through it on the studio-staging preview, toggling sqlEditorLogsSource + otelLegacyLogs via the dev-toolbar flag-override cookie (both flags are off by default, so none of this is visible without it).
| # | Test | Result |
|---|---|---|
| 1 | Baseline, flags off — no Logs section in nav | ✅ nav shows only Private/Shared/Favorites/Reference |
| 2 | Flags on — Logs section appears | ✅ collapsible "Logs" section shows up, empty state: "No logs queries" / "Create a logs query from the toolbar to explore your project's logs with SQL." |
| 3 | Create a logs snippet (/sql/new?skip=true&source=logs, type to materialize) |
✅ saves as log_sql on first keystroke (URL flips from /sql/new to /sql/<uuid>) — see note on a console warning here |
| 4 | Nav reflects the new snippet | ✅ section label bumps to "Logs (1)", snippet renders with the ScrollText icon, distinct from the normal SQL icon |
| 5 | Search — logs-only match | ✅ "1 result found", flat list, no group heading (correct — only one group matched) |
| 6 | Search — mixed DB + Logs match | ✅ "2 results found", "Database" and "Logs" headings both appear with the right snippet under each |
| 7 | Tabs — logs tab icon | ✅ active logs tab shows the ScrollText icon |
| 8 | Tabs — DB tab regression | ✅ normal DB tab keeps its usual SQL icon, no bleed-over |
| 9 | Tab persistence across reload | ✅ both tabs survive a full reload, nothing pruned |
| 10 | Flags off again — regression | ✅ Logs section disappears, toolbar reverts to the old source toggle, search drops the logs snippet, previously-open tabs stay open |
| 11 | Console errors throughout | ✅ no JS errors across the whole run |
Notes:
- Worth a look: right when the logs snippet is first materialized (step 3), the console logs a
"Tabs is changing from controlled to uncontrolled"warning immediately followed by the reverse"...uncontrolled to controlled", from the tabs component, during thenew→ real-snippet-id transition. Nothing visibly broke, but it smells like theTabsvalue passes throughundefinedmomentarily and might be worth a quick look. - Created one throwaway
log_sqlsnippet and one throwaway DB snippet to get real search-grouping coverage (steps 5/6); both deleted afterward via the nav's delete action. No pre-existing projects, orgs, or snippets touched. - Didn't touch the actual logs SQL execution path (running a query against ClickHouse) — that's PR #48452/#48414 territory, out of scope here.
- No screenshots — everything was verifiable via DOM/class checks with nothing visually broken.
UI issues foundCaught some stuff that weren't covered by the automated review
|
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 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/layouts/SQLEditorLayout/SQLEditorNavV2/LogsSnippetsSection.tsx`:
- Around line 33-42: Update the useSqlSnippetsQuery result handling in
LogsSnippetsSection to destructure isPlaceholderData and prevent placeholder
results from being reported as complete. Require !isPlaceholderData when
calculating isComplete, and apply the same guard to isSettled so the parent only
treats current-query data as settled.
🪄 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: 97000b5e-c84a-4cd6-8759-45f4cb84ce73
📒 Files selected for processing (5)
apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/LogsSnippetsSection.tsxapps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorNav.tsxapps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SearchList.tsxapps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SqlSnippetTree.tsxapps/studio/components/layouts/Tabs/Tabs.utils.test.tsx
🚧 Files skipped from review as they are similar to previous changes (4)
- apps/studio/components/layouts/Tabs/Tabs.utils.test.tsx
- apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SqlSnippetTree.tsx
- apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SearchList.tsx
- apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorNav.tsx
| onSnippetsLoaded: (info: { | ||
| snippets: Snippet[] | ||
| /** | ||
| * Whether `snippets` is the complete set of logs snippets. Only true once every | ||
| * page has been fetched — cleanup prunes tabs whose snippet is absent from the | ||
| * list, and a snippet on an unfetched page would otherwise look deleted. | ||
| */ | ||
| isComplete: boolean | ||
| isSettled: boolean | ||
| }) => void |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/usr/bin/env bash
set -euo pipefail
rg -n -C 8 \
'useSqlSnippetsQuery|placeholderData|keepPreviousData|isPlaceholderData|canPruneLogsTabs' \
apps/studio/data/content/sql-snippets-query.ts \
apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/LogsSnippetsSection.tsx \
apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorNav.tsxRepository: supabase/supabase
Length of output: 24328
Do not report placeholder data as a complete logs set.
useSqlSnippetsQuery uses placeholderData: keepPreviousData. After a query-key change, the previous pages can remain visible while isSuccess is already true, and !hasNextPage can report isComplete: true before the current query finishes. The parent cleanup can compare tabs against that stale snapshot and prune a valid logs tab. Destructure isPlaceholderData and require a non-placeholder result before reporting isComplete; apply the same guard to isSettled if the parent treats it as current-query completion status.
🤖 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/layouts/SQLEditorLayout/SQLEditorNavV2/LogsSnippetsSection.tsx`
around lines 33 - 42, Update the useSqlSnippetsQuery result handling in
LogsSnippetsSection to destructure isPlaceholderData and prevent placeholder
results from being reported as complete. Require !isPlaceholderData when
calculating isComplete, and apply the same guard to isSettled so the parent only
treats current-query data as settled.
joshenlim
left a comment
There was a problem hiding this comment.
Changes LGTM! Verified on preview
Surface log_sql snippets as a distinct query source across the SQL editor sidebar, following the toolbar/creation flow work: - Nav: a flag-gated "Logs" section (LogsSnippetsSection) backed by its own log_sql query; the active snippet is injected only into the section it belongs to via a shared withActiveSnippet helper. - Search: a "Logs" result group and correct combined result counts, with the tree rendering extracted into a reusable SqlSnippetTree. - Tabs: an immutable sqlSource tab metadata field (backfilled once the snippet loads) and a distinct ScrollText icon via a shared LogsSnippetIcon; tab cleanup treats log_sql tabs as live and only prunes them when logs data is authoritative. - Parameterize useSqlSnippetsQuery with a content type so logs reuse the same SnippetWithContent shape (no casts). Both sqlEditorLogsSource and otelLegacyLogs flags gate the entry points.
- Open the Logs section, not Private, when the active snippet is a logs snippet. The auto-expansion effect branched on visibility first, so opening or renaming a log_sql snippet expanded a section it isn't in. - Only prune logs tabs once every logs page has been fetched. useInfiniteQuery flips isSuccess after the first page, so a tab whose snippet lived on an unfetched page could be pruned as stale; the bubbled-up flag is now isComplete (isSuccess && !hasNextPage). - Label logs search results "Logs" instead of "Private" — the visibility axis doesn't distinguish them from the database results beside them. - Flatten the search result-count nested ternary into mutually exclusive guards, and assert recent-item preservation in the canPruneLogsTabs test.
91fd667 to
facb525
Compare
…ckHouse (#48501) ## I have read the [CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md) file. YES ## What kind of change does this PR introduce? Feature, plus a refactor of the shared logs-rewrite flow. PR 8 of the SQL editor query-source series. Stacked on #48457 — review that one first, and merge this after it. ## What is the current behavior? A `log_sql` snippet runs against the ClickHouse-backed analytics endpoint, but the SQL editor's AI still writes Postgres: inline edits get Postgres system prompts, and the result is run through `sql-formatter`, which mangles ClickHouse backticks and `log_attributes` map lookups. Legacy Logs Explorer saved queries open in the editor as `log_sql` snippets. Those are BigQuery dialect and error against the ClickHouse endpoint the editor runs them on, with no in-editor way out — only the Logs Explorer offered a rewrite. The completion route was also asymmetric. It assembled a schema/code/instruction message for Postgres but forwarded `prompt` verbatim for ClickHouse, so a client wanting ClickHouse had to hand-build the equivalent string. ## What is the new behavior? **Inline AI speaks ClickHouse for logs snippets.** `sqlSourceToDialect` maps a snippet's source to `postgres`/`clickhouse` and `buildCompletionRequestBody` threads it through. For ClickHouse, `useSqlEditorAi` strips code fences from the response and skips `formatSql`. Execution and dialect both follow the snippet type, so a snippet's valid dialect never flips. **Rewrite to ClickHouse in the editor.** A banner offers the rewrite for a logs snippet whose text trips `looksLikeLegacyLogsQuery`, and proposes the result through the editor's existing AI diff view rather than replacing the snippet, so it's accepted or discarded like any other AI edit. Gated on `otelLegacyLogs`: on a non-migrated org the BigQuery text is still correct, so rewriting it would break a working query. The offer is a state machine (`offered` / `rewriting` / `failed` / `noRewriteNeeded` / `dismissed`) with a declarative table of valid transitions, so the states are mutually exclusive by construction and dismissal is terminal. A failure keeps its message and offers a retry; a response identical to the input is reported rather than opening an empty diff. **One place assembles completion prompts.** The route now uses a single template for both dialects, branching only the schema section and — for `intent: 'rewrite'` — the instruction. `lib/ai/clickhouse-logs.ts` is the single home for ClickHouse-logs prompt content, replacing two independently maintained descriptions of the same table. Clients carry no prompt text. **The rewrite flow is shared with the Logs Explorer.** Both surfaces previously hand-rolled the same sequence and had drifted: only one detected a no-op rewrite, they sourced `log_attributes` keys differently, and the Explorer formatted errors with an `as Error` cast. Both now use `useLegacyLogsRewrite` and the same state-driven banner, so the Explorer picks up no-op detection and typed error extraction. **Attribute keys are fetched on submit, not while typing.** The detected source would otherwise feed a reactive query key, making every edit that changed it cost another network call. `useLogsAttributeKeys` is imperative and goes through `queryClient.fetchQuery`, so a source already cached — including by the Explorer header and query panel, which subscribe reactively — is reused. This also closes a gap where inline edits never received keys at all, unlike full rewrites. `getErrorMessage` gains an optional typed fallback and no longer stringifies a bare object into `'[object Object]'`; every existing caller already hand-rolled a fallback, except `QueueSettings`, which interpolated the raw result and now passes one. Nothing here is user-visible until the `sqlEditorLogsSource` flag is enabled. Tests: dialect selection and request-body shape, the ClickHouse prompt content (including that the schema section does not restate the dialect rules), the reducer's valid and invalid transitions, `shouldOfferLegacyLogsRewrite`, on-submit key discovery with cache reuse, and `getErrorMessage`. ## Additional context <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Added an Assistant banner to help rewrite legacy BigQuery-style logs queries into ClickHouse SQL. * SQL assistance now adapts to the selected query type, including relevant log attribute context. * Rewrite suggestions can be reviewed as editor diffs before being applied. * **Bug Fixes** * Improved rewrite failure handling, retry options, dismissal behavior, and “no rewrite needed” messaging. * Error notifications now provide a clearer fallback message when details are unavailable. <!-- end of auto-generated comment: release notes by coderabbit.ai -->


What
PR 7 of the SQL-editor query-source (Database vs Logs) stack. Surfaces
log_sqlsnippets as a distinct query source across the SQL editor sidebar. Stacked oncharislam/toolbar-ui-creation-flow(PR 6 — toolbar UI + creation flow); review/merge that first.Nothing is user-visible until the flags roll out — every entry point requires both
sqlEditorLogsSourceandotelLegacyLogs.Changes
LogsSnippetsSection) backed by its own single-typelog_sqlquery. The active snippet is injected only into the section it belongs to, via a sharedwithActiveSnippet(snippets, active, belongsPredicate)helper (also DRYs the private/favorites/shared injections).SearchList) — a Logs result group with a shared, extractedSqlSnippetTree; the "N results found" count now sums database + logs, with loading/empty states covering both queries.sqlSourcefield on tab/recent-item metadata (set at tab creation, lazily backfilled once the snippet loads viauseEffectEvent), and a distinctScrollTexticon via a sharedLogsSnippetIcon. Tab cleanup treatslog_sqltabs as live and only prunes them when logs data is authoritative (canPruneLogsTabs), so a disabled/erroring logs query never wrongly deletes logs tabs or blocks database-tab cleanup.useSqlSnippetsQuerygains an optionaltypeparam so logs reuse the sameSnippetWithContentshape as the other sections (no casts).Tests
state/tabs.test.ts—sqlSourcebackfill + creation-time carry-through.components/layouts/Tabs/Tabs.utils.test.tsx— cleanup prunes stale database/logs snippets, keeps live ones, and preserves logs tabs when logs data isn't authoritative.Verification
pnpm --filter studio typecheck✓pnpm --filter studio run lint:ratchet✓pnpm test:studio(affected suites) ✓Summary by CodeRabbit