Skip to content

Shift ETL destination components into a separate folder - #41457

Merged
joshenlim merged 2 commits into
masterfrom
joshen/fe-2294-break-up-destinationpanel-form-into-a-separate-component
Dec 18, 2025
Merged

joshenlim merged 2 commits into
masterfrom
joshen/fe-2294-break-up-destinationpanel-form-into-a-separate-component

Conversation

@joshenlim

@joshenlim joshenlim commented Dec 18, 2025 •

Copy link
Copy Markdown
Member

Context

This is another groundwork for unifying read replicas into the database replication section.

Changes here are mainly shifting all the ETL destination related form stuff into a separate folder, so that in the next PR we can dynamically render a separate form for read replicas (instead of adding more fields into the ETL destination form which already has a lot of properties - ideally should be broken down into 2 separate forms, one for big query and another for analytics buckets)

It's also why there's lot of LOC changes but it's mainly shifting code around

Project: https://linear.app/supabase/project/dashboard-replication-ui-32556f2d3e60/updates
Ticket: https://linear.app/supabase/issue/FE-2294/break-up-destinationpanel-form-into-a-separate-component

Changes involved

  • Shift ETL destination form into a DestinationForm folder, and shift all relevant UI components into that folder
  • Remove type from DestinationPanelFormSchema -> have that handled simply in DestinationPanel as a useState
  • Fix a number of type warnings RE the use of any
  • Added read replicas scaffold into DestinationPanel, behind a feature flag

To test

I've only scaffolded the read replicas destination option in this PR, and it's behind a feature flag that's off for prod. So just need to test that the existing ETL destinations work

  • Can create a big query destination
  • Can create an analytics bucket destination

Summary by CodeRabbit

  • New Features

    • Added Read Replica as a replication destination option.
    • New standalone Destination form component for creating/editing destinations.
  • Improvements

    • Dynamic, feature-aware destination selection UI (1–3 option layout).
    • Improved form validation, clearer fields for BigQuery, Analytics Bucket, and S3 credentials.
    • Simplified panel flow and guidance in Infrastructure when unified replication is enabled.

✏️ Tip: You can customize this high-level summary in your review settings.

@joshenlim
joshenlim requested a review from a team as a code owner December 18, 2025 10:05
@vercel

vercel Bot commented Dec 18, 2025 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Review Updated (UTC)
studio-self-hosted Ready Ready Preview, Comment Dec 18, 2025 10:29am
studio-staging Ready Ready Preview, Comment Dec 18, 2025 10:29am
6 Skipped Deployments
Project Deployment Review Updated (UTC)
studio Ignored Ignored Dec 18, 2025 10:29am
cms Skipped Skipped Dec 18, 2025 10:29am
design-system Skipped Skipped Dec 18, 2025 10:29am
docs Skipped Skipped Dec 18, 2025 10:29am
ui-library Skipped Skipped Dec 18, 2025 10:29am
zone-www-dot-com Skipped Skipped Dec 18, 2025 10:29am

@supabase

supabase Bot commented Dec 18, 2025

Copy link
Copy Markdown

This pull request has been ignored for the connected project xguihxuzqibwxjnimxev because there are no changes detected in supabase directory. You can change this behaviour in Project Integrations Settings ↗︎.


Preview Branches by Supabase.
Learn more about Supabase Branching ↗︎.

@coderabbitai

coderabbitai Bot commented Dec 18, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Reorganizes the Database Replication UI: moves form schema to DestinationForm.schema.ts, extracts shared types, adds a new DestinationForm component, simplifies DestinationPanel (removes sourceId), and converts type-selection and several components to prop-driven APIs with updated imports.

Changes

Cohort / File(s) Summary
Form schema moved & split
apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/DestinationForm.schema.ts, apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationPanel.schema.ts
Added DestinationPanelFormSchema (Zod) and DestinationPanelSchemaType in DestinationForm.schema.ts; removed old DestinationPanel.schema.ts.
New DestinationForm component & subcomponents updated
apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/index.tsx, .../AdvancedSettings.tsx, .../DestinationNameInput.tsx, .../DestinationPanelFields.tsx, .../PublicationSelection.tsx
Introduced DestinationForm component (create/update flows, validation, data fetching, namespace/S3 handling); AdvancedSettings now accepts type: DestinationType prop; multiple imports updated to use DestinationForm.schema.
Panel / type extraction & selection refactor
apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationPanel.tsx, .../DestinationPanel.types.ts, .../DestinationTypeSelection.tsx
DestinationPanel simplified (removed sourceId prop) and delegates to DestinationForm; new DestinationType union type file; DestinationTypeSelection converted from form-driven to prop-driven API and adds Read Replica option.
Call-site and list updates
apps/studio/components/interfaces/Database/Replication/DestinationRow.tsx, apps/studio/components/interfaces/Database/Replication/Destinations.tsx
Updated to use DestinationType and stop passing sourceId into DestinationPanel; adjusted imports.
Mutation type consolidation
apps/studio/data/replication/create-destination-pipeline-mutation.ts, apps/studio/data/replication/update-destination-pipeline-mutation.ts
Extracted DestinationConfig and BatchConfig types; updated create/update mutation param types to use shared types; removed per-file BigQuery/Iceberg config types.
Feature-flagged UI change
apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureInfo.tsx
Added unifiedReplication flag; conditionally shows a NoticeBar linking to replication management instead of InstanceConfiguration when flag enabled.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant DestinationPanel
    participant DestinationTypeSelection
    participant DestinationForm
    participant APIs
    participant Mutations

    User->>DestinationPanel: Open panel
    DestinationPanel->>DestinationTypeSelection: Render selector (prop-driven)
    User->>DestinationTypeSelection: Select type
    DestinationTypeSelection->>DestinationPanel: setSelectedType
    DestinationPanel->>DestinationForm: Render with selectedType

    DestinationForm->>APIs: Fetch publications / source / pipeline / keys
    APIs-->>DestinationForm: Return data
    DestinationForm->>DestinationForm: Initialize form (Zod + react-hook-form)
    User->>DestinationForm: Fill & submit
    DestinationForm->>DestinationForm: Validate form

    alt Create flow
        DestinationForm->>APIs: Create S3 key (if needed)
        APIs-->>DestinationForm: Key
        DestinationForm->>Mutations: Create destination pipeline (DestinationConfig + BatchConfig)
        Mutations-->>DestinationForm: Success
        DestinationForm->>Mutations: Start pipeline
    else Update flow
        DestinationForm->>Mutations: Update destination pipeline (DestinationConfig)
        Mutations-->>DestinationForm: Success
        DestinationForm->>Mutations: Optionally restart pipeline
    end

    DestinationForm->>User: Show toast / close panel
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

  • Areas needing extra attention:
    • DestinationForm (dense logic: mutations, branching create vs update, S3/namespace handling).
    • Cross-file import/type updates (ensure no stale imports of DestinationPanel.schema).
    • DestinationTypeSelection API change and all call-sites to ensure correct prop wiring.
    • Mutation type consolidation compatibility with backend payload expectations.

Possibly related PRs

Suggested reviewers

  • alaister
  • avallete
  • ivasilov

Poem

🐰 I hopped through code, moved schemas with care,
New forms and types now dance in the air.
SourceId has vanished — a lighter delight,
Panels delegated, selections take flight,
A carrot-toast for deployments tonight! 🎉

Pre-merge checks and finishing touches

❌ Failed checks (1 inconclusive)
Check name Status Explanation Resolution
Description check ❓ Inconclusive The PR description is comprehensive and includes context, objectives, detailed changes, and testing instructions. However, it does not follow the required template structure with sections like 'Kind of change', 'Current behavior', and 'New behavior'. Consider restructuring the description to follow the template: explicitly state the kind of change (refactoring), current behavior, new behavior, and align sections with the required format.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and accurately describes the primary change: moving ETL destination components into a separate folder, which is the main organizational restructuring in this PR.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch joshen/fe-2294-break-up-destinationpanel-form-into-a-separate-component

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
apps/studio/data/replication/create-destination-pipeline-mutation.ts (1)

72-72: Incorrect null check for optional field.

maxStalenessMins is typed as number | undefined (via ?:), but the check uses !== null. When maxStalenessMins is undefined, this condition is true, causing { max_staleness_mins: undefined } to be spread into the object.

Use loose equality or check for undefined:

🔎 Suggested fix
-        ...(maxStalenessMins !== null ? { max_staleness_mins: maxStalenessMins } : {}),
+        ...(maxStalenessMins != null ? { max_staleness_mins: maxStalenessMins } : {}),

Alternatively: maxStalenessMins !== undefined or maxStalenessMins ? { ... } : {} if 0 is not a valid value.

apps/studio/data/replication/update-destination-pipeline-mutation.ts (1)

47-47: Same null check issue as in create mutation.

Apply the same fix here for consistency:

🔎 Suggested fix
-        ...(maxStalenessMins !== null ? { max_staleness_mins: maxStalenessMins } : {}),
+        ...(maxStalenessMins != null ? { max_staleness_mins: maxStalenessMins } : {}),
🧹 Nitpick comments (3)
apps/studio/data/replication/update-destination-pipeline-mutation.ts (1)

40-75: Consider extracting shared destination config builder.

The destination config building logic (lines 40-75) is nearly identical to the create mutation. Consider extracting a shared helper function to reduce duplication:

// In a shared file or at the top of one of these files
export function buildDestinationConfig(
  destinationConfig: DestinationConfig
): components['schemas']['...']['destination_config'] {
  if ('bigQuery' in destinationConfig) { ... }
  else if ('iceberg' in destinationConfig) { ... }
  ...
}

This would make future changes easier to maintain consistently.

apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationTypeSelection.tsx (1)

37-46: Consider runtime validation instead of type casting.

The as DestinationType cast on line 40 works because the RadioGroupStackedItem values are constrained to DestinationType literals. However, per coding guidelines, type casting should be avoided in favor of runtime validation. Consider validating the value at runtime:

🔎 Optional: Add runtime validation
+const isDestinationType = (value: string): value is DestinationType =>
+  ['Read Replica', 'BigQuery', 'Analytics Bucket'].includes(value)
+
 <RadioGroupStacked
   disabled={editMode}
   value={selectedType}
-  onValueChange={(value) => setSelectedType(value as DestinationType)}
+  onValueChange={(value) => {
+    if (isDestinationType(value)) {
+      setSelectedType(value)
+    }
+  }}
apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/index.tsx (1)

77-83: Consider grouping related state.

While the current approach with separate useState calls is functional, consider grouping related modal visibility states using a single state object or discriminated union for better maintainability:

const [modals, setModals] = useState({
  disclaimer: false,
  publicationPanel: false,
  newBucketSheet: false,
})

However, this is a minor optimization and the current approach is acceptable.

As per coding guidelines, group related state using objects or reducers instead of multiple useState calls.

📜 Review details

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8c5ec85 and 6d95b54.

📒 Files selected for processing (15)
  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/AdvancedSettings.tsx (1 hunks)
  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/DestinationForm.schema.ts (1 hunks)
  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/DestinationNameInput.tsx (1 hunks)
  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/DestinationPanelFields.tsx (3 hunks)
  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/PublicationSelection.tsx (1 hunks)
  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/index.tsx (1 hunks)
  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationPanel.schema.ts (0 hunks)
  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationPanel.tsx (2 hunks)
  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationPanel.types.ts (1 hunks)
  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationTypeSelection.tsx (2 hunks)
  • apps/studio/components/interfaces/Database/Replication/DestinationRow.tsx (2 hunks)
  • apps/studio/components/interfaces/Database/Replication/Destinations.tsx (0 hunks)
  • apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureInfo.tsx (4 hunks)
  • apps/studio/data/replication/create-destination-pipeline-mutation.ts (2 hunks)
  • apps/studio/data/replication/update-destination-pipeline-mutation.ts (1 hunks)
💤 Files with no reviewable changes (2)
  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationPanel.schema.ts
  • apps/studio/components/interfaces/Database/Replication/Destinations.tsx
🧰 Additional context used
📓 Path-based instructions (2)
apps/studio/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/studio-best-practices.mdc)

apps/studio/**/*.{ts,tsx}: Assign complex conditions to descriptive variables instead of using multiple conditions in a single expression
Use consistent naming conventions for boolean variables: is prefix for state/identity, has prefix for possession, can prefix for capability/permission, should prefix for conditional behavior
Derive boolean state from existing state instead of storing it separately
Use early returns for guard clauses instead of deeply nested conditionals
Extract complex logic into custom hooks when logic becomes reusable or complex
Return objects from custom hooks instead of arrays for better extensibility and clearer API
Use discriminated unions for complex state management instead of multiple independent state fields
Avoid type casting (e.g., as any, as Type); instead validate values at runtime using zod schemas

Files:

  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationPanel.types.ts
  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/DestinationForm.schema.ts
  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/PublicationSelection.tsx
  • apps/studio/components/interfaces/Database/Replication/DestinationRow.tsx
  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/DestinationNameInput.tsx
  • apps/studio/data/replication/update-destination-pipeline-mutation.ts
  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/AdvancedSettings.tsx
  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/index.tsx
  • apps/studio/data/replication/create-destination-pipeline-mutation.ts
  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationPanel.tsx
  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationTypeSelection.tsx
  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/DestinationPanelFields.tsx
  • apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureInfo.tsx
apps/studio/**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/studio-best-practices.mdc)

apps/studio/**/*.tsx: Components should ideally be under 200-300 lines; break down large components with multiple distinct UI sections, complex conditional rendering, or multiple unrelated useState hooks
Extract repeated JSX patterns into reusable components instead of copying similar JSX blocks
Use consistent loading/error/success pattern: handle loading state first with early returns, then error state, then empty state, then render success state
Keep state as local as possible and only lift up when needed
Group related state using objects or reducers instead of multiple useState calls, preferring react-hook-form for form state management
Name event handlers consistently: use on prefix for prop callbacks and handle prefix for internal handlers
Avoid inline arrow functions for expensive operations; use useCallback to maintain stable function references
Use appropriate conditional rendering patterns: && for simple show/hide, ternary for binary choice, early returns or extracted components for multiple conditions
Avoid nested ternaries in JSX; use separate conditions or early returns instead
Use useMemo for expensive computations when the computation is genuinely expensive and the value is passed to memoized children
Define prop interfaces explicitly for React components with proper typing of props and callback handlers

Files:

  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/PublicationSelection.tsx
  • apps/studio/components/interfaces/Database/Replication/DestinationRow.tsx
  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/DestinationNameInput.tsx
  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/AdvancedSettings.tsx
  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/index.tsx
  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationPanel.tsx
  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationTypeSelection.tsx
  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/DestinationPanelFields.tsx
  • apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureInfo.tsx
🧠 Learnings (26)
📚 Learning: 2025-12-12T05:20:17.409Z
Learnt from: joshenlim
Repo: supabase/supabase PR: 41258
File: apps/studio/pages/project/[ref]/storage/vectors/buckets/[bucketId].tsx:9-9
Timestamp: 2025-12-12T05:20:17.409Z
Learning: In apps/studio/**/*.{ts,tsx}, use named imports for DefaultLayout: import { DefaultLayout } from 'components/layouts/DefaultLayout' instead of default import. This is the new practice being adopted across the studio app.

Applied to files:

  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationPanel.types.ts
  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/DestinationForm.schema.ts
  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/PublicationSelection.tsx
  • apps/studio/components/interfaces/Database/Replication/DestinationRow.tsx
  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/DestinationNameInput.tsx
  • apps/studio/data/replication/update-destination-pipeline-mutation.ts
  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/AdvancedSettings.tsx
  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/index.tsx
  • apps/studio/data/replication/create-destination-pipeline-mutation.ts
  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationPanel.tsx
  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationTypeSelection.tsx
  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/DestinationPanelFields.tsx
  • apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureInfo.tsx
📚 Learning: 2025-12-11T02:39:45.951Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/docs-graphql.mdc:0-0
Timestamp: 2025-12-11T02:39:45.951Z
Learning: Applies to apps/docs/resources/**/[!Model]*Schema.ts : All GraphQL fields and types must include descriptions in their definitions

Applied to files:

  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/DestinationForm.schema.ts
📚 Learning: 2025-12-11T17:04:40.037Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T17:04:40.037Z
Learning: Applies to apps/studio/components/**/*.{ts,tsx} : Build forms with react-hook-form and zod for validation

Applied to files:

  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/DestinationForm.schema.ts
  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/PublicationSelection.tsx
  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/DestinationNameInput.tsx
  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/AdvancedSettings.tsx
  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/index.tsx
📚 Learning: 2025-12-11T17:04:40.037Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T17:04:40.037Z
Learning: Applies to apps/studio/components/**/*.{ts,tsx} : Always wrap form inputs with FormControl_Shadcn_ to ensure proper form integration

Applied to files:

  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/PublicationSelection.tsx
  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/DestinationNameInput.tsx
  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/AdvancedSettings.tsx
📚 Learning: 2025-12-11T17:04:40.037Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T17:04:40.037Z
Learning: Applies to apps/studio/components/**/*.{ts,tsx} : Use Select_Shadcn_ with SelectTrigger_Shadcn_, SelectContent_Shadcn_, and SelectItem_Shadcn_ for select form fields

Applied to files:

  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/PublicationSelection.tsx
  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationTypeSelection.tsx
📚 Learning: 2025-12-11T17:04:40.037Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T17:04:40.037Z
Learning: Applies to apps/studio/components/**/*.{ts,tsx} : Use Checkbox_Shadcn_ with label for checkbox form fields, and multiple checkboxes for checkbox groups

Applied to files:

  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/PublicationSelection.tsx
  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationTypeSelection.tsx
📚 Learning: 2025-12-11T17:04:40.037Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T17:04:40.037Z
Learning: Applies to apps/studio/components/**/*.{ts,tsx} : Use MultiSelector component from ui-patterns/multi-select for multi-select form fields

Applied to files:

  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/PublicationSelection.tsx
  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/AdvancedSettings.tsx
  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationTypeSelection.tsx
📚 Learning: 2025-12-11T17:04:40.037Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T17:04:40.037Z
Learning: Applies to apps/studio/components/**/*.{ts,tsx} : Use Input_Shadcn_ with placeholder for text input form fields

Applied to files:

  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/PublicationSelection.tsx
  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/DestinationNameInput.tsx
  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/AdvancedSettings.tsx
📚 Learning: 2025-12-11T17:04:40.037Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T17:04:40.037Z
Learning: Applies to apps/studio/**/*.{ts,tsx} : Use _Shadcn_ suffixed components (e.g., Input_Shadcn_, Button_Shadcn_) from the ui package where possible

Applied to files:

  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/PublicationSelection.tsx
  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/DestinationNameInput.tsx
📚 Learning: 2025-12-11T17:04:40.037Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T17:04:40.037Z
Learning: Applies to apps/studio/components/**/*.{ts,tsx} : Always use FormItemLayout instead of manually composing FormItem, FormLabel, FormMessage, and FormDescription

Applied to files:

  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/PublicationSelection.tsx
  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/DestinationNameInput.tsx
  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/AdvancedSettings.tsx
📚 Learning: 2025-12-11T17:04:40.037Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T17:04:40.037Z
Learning: Applies to apps/studio/components/**/*.{ts,tsx} : Use Input component from ui-patterns/DataInputs/Input with copy and readOnly props for copyable input form fields

Applied to files:

  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/PublicationSelection.tsx
  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/DestinationNameInput.tsx
  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/DestinationPanelFields.tsx
📚 Learning: 2025-12-11T17:04:40.037Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T17:04:40.037Z
Learning: Applies to apps/studio/components/**/*.{ts,tsx} : Use FormItemLayout with layout='horizontal' for side panel forms in wide panels (size='lg')

Applied to files:

  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/PublicationSelection.tsx
  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/DestinationNameInput.tsx
  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/AdvancedSettings.tsx
📚 Learning: 2025-12-11T17:04:40.037Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T17:04:40.037Z
Learning: Applies to apps/studio/components/**/*.{ts,tsx} : Use Input_Shadcn_ with type='password' for password input form fields

Applied to files:

  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/DestinationNameInput.tsx
  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/AdvancedSettings.tsx
📚 Learning: 2025-12-11T17:04:40.037Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T17:04:40.037Z
Learning: Applies to apps/studio/components/**/*.{ts,tsx} : Use Input_Shadcn_ with type='number' and onChange handler for number input form fields

Applied to files:

  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/DestinationNameInput.tsx
  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/AdvancedSettings.tsx
📚 Learning: 2025-12-11T17:04:40.037Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T17:04:40.037Z
Learning: Applies to apps/studio/components/**/*.{ts,tsx} : Wrap Input_Shadcn_ with PrePostTab component to add unit labels to input fields

Applied to files:

  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/DestinationNameInput.tsx
📚 Learning: 2025-12-11T16:46:18.701Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-best-practices.mdc:0-0
Timestamp: 2025-12-11T16:46:18.701Z
Learning: Applies to apps/studio/**/*.tsx : Define prop interfaces explicitly for React components with proper typing of props and callback handlers

Applied to files:

  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/AdvancedSettings.tsx
  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationTypeSelection.tsx
📚 Learning: 2025-12-11T17:04:40.037Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T17:04:40.037Z
Learning: Applies to apps/studio/components/**/*.{ts,tsx} : Use FormItemLayout with layout='vertical' for side panel forms in narrow panels (size='sm' or below)

Applied to files:

  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/AdvancedSettings.tsx
📚 Learning: 2025-12-11T17:04:40.037Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T17:04:40.037Z
Learning: Applies to apps/studio/components/**/*.{ts,tsx} : Use sheets when revealing complicated forms or information relating to an object where context switching to a new page would be disruptive

Applied to files:

  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationPanel.tsx
📚 Learning: 2025-12-11T17:04:40.037Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T17:04:40.037Z
Learning: Applies to apps/studio/components/**/*.{ts,tsx} : Place submit/cancel buttons in SheetFooter for forms in sheets

Applied to files:

  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationPanel.tsx
📚 Learning: 2025-12-11T17:04:40.037Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T17:04:40.037Z
Learning: Applies to apps/studio/components/**/*.{ts,tsx} : Use SheetHeader, SheetTitle, SheetSection, and SheetFooter for consistent sheet structure

Applied to files:

  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationPanel.tsx
📚 Learning: 2025-12-11T16:46:18.701Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-best-practices.mdc:0-0
Timestamp: 2025-12-11T16:46:18.701Z
Learning: Applies to apps/studio/**/*.{ts,tsx} : Use discriminated unions for complex state management instead of multiple independent state fields

Applied to files:

  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationTypeSelection.tsx
📚 Learning: 2025-12-11T17:04:40.037Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T17:04:40.037Z
Learning: Applies to apps/studio/components/**/*.{ts,tsx} : Use Switch component with checked and onCheckedChange props for toggle form fields

Applied to files:

  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationTypeSelection.tsx
📚 Learning: 2025-12-11T17:04:40.037Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T17:04:40.037Z
Learning: Applies to apps/studio/components/**/*.{ts,tsx} : Use RadioGroupStacked with RadioGroupStackedItem for stacked radio options with descriptions

Applied to files:

  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationTypeSelection.tsx
📚 Learning: 2025-12-11T17:04:40.037Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T17:04:40.037Z
Learning: Applies to apps/studio/components/**/*.{ts,tsx} : Use Admonition component to alert users of important actions or restrictions

Applied to files:

  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/DestinationPanelFields.tsx
  • apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureInfo.tsx
📚 Learning: 2025-12-11T17:04:40.037Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T17:04:40.037Z
Learning: Applies to apps/studio/**/*.{ts,tsx} : Use ScaffoldSection, ScaffoldSectionTitle, and ScaffoldSectionDescription for pages with multiple sections

Applied to files:

  • apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureInfo.tsx
📚 Learning: 2025-12-11T17:04:40.037Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T17:04:40.037Z
Learning: Applies to apps/studio/**/*.{ts,tsx} : Use ScaffoldContainer for center-aligned page content in a container

Applied to files:

  • apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureInfo.tsx
🧬 Code graph analysis (5)
apps/studio/components/interfaces/Database/Replication/DestinationRow.tsx (1)
apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationPanel.types.ts (1)
  • DestinationType (1-1)
apps/studio/data/replication/update-destination-pipeline-mutation.ts (1)
apps/studio/data/replication/create-destination-pipeline-mutation.ts (2)
  • DestinationConfig (9-15)
  • BatchConfig (34-36)
apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/AdvancedSettings.tsx (2)
apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationPanel.types.ts (1)
  • DestinationType (1-1)
apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/DestinationForm.schema.ts (1)
  • DestinationPanelSchemaType (25-25)
apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationTypeSelection.tsx (4)
apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationPanel.types.ts (1)
  • DestinationType (1-1)
packages/common/feature-flags.tsx (1)
  • useFlag (165-180)
blocks/vue/registry/default/lib/utils.ts (1)
  • cn (5-7)
apps/studio/data/storage/analytics-buckets-query.ts (1)
  • AnalyticsBucket (12-12)
apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureInfo.tsx (4)
packages/common/feature-flags.tsx (1)
  • useFlag (165-180)
apps/studio/components/layouts/Scaffold.tsx (3)
  • ScaffoldContainer (18-45)
  • ScaffoldSection (86-101)
  • ScaffoldDivider (106-110)
apps/studio/components/interfaces/DiskManagement/ui/NoticeBar.tsx (1)
  • NoticeBar (14-34)
apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/InstanceConfiguration.tsx (1)
  • InstanceConfiguration (379-385)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: test (1)
  • GitHub Check: typecheck
  • GitHub Check: test
🔇 Additional comments (13)
apps/studio/data/replication/create-destination-pipeline-mutation.ts (1)

9-36: Good use of discriminated unions and shared types.

The DestinationConfig discriminated union and extracted BatchConfig type improve reusability and type safety across create/update mutations. This aligns well with the coding guideline to use discriminated unions for complex state management.

apps/studio/data/replication/update-destination-pipeline-mutation.ts (1)

7-7: Good consolidation of shared types.

Importing DestinationConfig and BatchConfig from the create mutation ensures consistency and reduces duplication across create/update operations.

apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/DestinationNameInput.tsx (1)

1-25: LGTM!

The import path update aligns with the schema relocation to DestinationForm.schema. The component correctly follows the coding guidelines: using FormItemLayout, wrapping input with FormControl_Shadcn_, and using Input_Shadcn_ with a placeholder.

apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationPanel.types.ts (1)

1-1: LGTM!

Clean, focused type definition that serves as a single source of truth for destination types across the UI components.

apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/PublicationSelection.tsx (1)

12-13: LGTM!

Import path updates align with the schema and component relocation to the DestinationForm folder. The component correctly follows coding guidelines for form composition.

apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/DestinationPanelFields.tsx (2)

30-31: LGTM!

Import path updates align with the schema and constants relocation to the DestinationForm folder.


155-158: Verify the simplified enabled condition is intentional.

The enabled condition for useIcebergNamespacesQuery was simplified to only check !!serviceApiKey, removing what was previously a type === 'Analytics Bucket' check. Since AnalyticsBucketFields is only rendered when the destination type is 'Analytics Bucket', this should be safe. However, confirm this doesn't cause unnecessary API calls if the component ever gets rendered in a different context.

apps/studio/components/interfaces/Database/Replication/DestinationRow.tsx (2)

24-24: LGTM!

Import updated to use the centralized DestinationType from DestinationPanel.types.


31-41: LGTM!

The type prop correctly uses the new DestinationType union with an 'Other' fallback for unknown destination types. The interface is well-defined with explicit typing.

apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/DestinationForm.schema.ts (1)

1-25: LGTM!

Well-structured Zod schema following the coding guidelines for form validation. The comment on lines 3-4 appropriately acknowledges the trade-off of a flat schema structure and suggests splitting if more types are added. Type derivation using z.infer is the correct pattern.

apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/AdvancedSettings.tsx (1)

15-24: LGTM!

The component signature update to accept type as a prop (instead of extracting from form.watch()) aligns with the refactor where type is now managed via useState in the parent. Import paths updated correctly.

apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationTypeSelection.tsx (1)

7-11: LGTM!

The prop interface is explicitly defined, following coding guidelines. The switch from form-based to controlled props (selectedType, setSelectedType) provides a cleaner API for this selection component.

apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationPanel.tsx (1)

1-83: Excellent simplification and separation of concerns.

The refactoring successfully delegates form logic to DestinationForm and type selection to DestinationTypeSelection, significantly improving maintainability. The component is now focused on orchestration rather than implementation details, which aligns well with React best practices.

Comment on lines +63 to +546
export const DestinationForm = ({
selectedType,
visible,
existingDestination,
onClose,
}: DestinationFormProps) => {
const { ref: projectRef } = useParams()
const { data: project } = useSelectedProjectQuery()
const { setRequestStatus } = usePipelineRequestStatus()

const etlEnableBigQuery = useFlag('etlEnableBigQuery')
const etlEnableIceberg = useFlag('etlEnableIceberg')
const { can: canReadAPIKeys } = useAsyncCheckPermissions(PermissionAction.SECRETS_READ, '*')

const [isFormInteracting, setIsFormInteracting] = useState(false)
const [showDisclaimerDialog, setShowDisclaimerDialog] = useState(false)
const [publicationPanelVisible, setPublicationPanelVisible] = useState(false)
const [newBucketSheetVisible, setNewBucketSheetVisible] = useState(false)
const [pendingFormValues, setPendingFormValues] = useState<z.infer<typeof FormSchema> | null>(
null
)

const editMode = !!existingDestination

// Compute available destinations based on feature flags
const availableDestinations = useMemo(() => {
const destinations = []
if (etlEnableBigQuery) destinations.push({ value: 'BigQuery', label: 'BigQuery' })
if (etlEnableIceberg)
destinations.push({ value: 'Analytics Bucket', label: 'Analytics Bucket' })
return destinations
}, [etlEnableBigQuery, etlEnableIceberg])
const hasNoAvailableDestinations = availableDestinations.length === 0

const { data: sourcesData } = useReplicationSourcesQuery({ projectRef })
const sourceId = sourcesData?.sources.find((s) => s.name === projectRef)?.id

const {
data: publications = [],
isSuccess: isSuccessPublications,
refetch: refetchPublications,
} = useReplicationPublicationsQuery({ projectRef, sourceId })

const { data: destinationData } = useReplicationDestinationByIdQuery({
projectRef,
destinationId: existingDestination?.destinationId,
})

const { data: pipelineData } = useReplicationPipelineByIdQuery({
projectRef,
pipelineId: existingDestination?.pipelineId,
})

const { data: apiKeys } = useAPIKeysQuery(
{ projectRef, reveal: true },
{ enabled: canReadAPIKeys }
)
const { serviceKey } = getKeys(apiKeys)
const catalogToken = serviceKey?.api_key ?? ''

const { data: projectSettings } = useProjectSettingsV2Query({ projectRef })

const { mutateAsync: createDestinationPipeline, isPending: creatingDestinationPipeline } =
useCreateDestinationPipelineMutation({
onSuccess: () => form.reset(defaultValues),
})

const { mutateAsync: updateDestinationPipeline, isPending: updatingDestinationPipeline } =
useUpdateDestinationPipelineMutation({
onSuccess: () => form.reset(defaultValues),
})

const { mutateAsync: startPipeline, isPending: startingPipeline } = useStartPipelineMutation()
const { restartPipeline } = useRestartPipelineHelper()

const { mutateAsync: createS3AccessKey, isPending: isCreatingS3AccessKey } =
useS3AccessKeyCreateMutation()

const { mutateAsync: createNamespace, isPending: isCreatingNamespace } =
useIcebergNamespaceCreateMutation()

const defaultValues = useMemo(() => {
const config = destinationData?.config
const isBigQueryConfig = config && 'big_query' in config
const isIcebergConfig = config && 'iceberg' in config

return {
// Common fields
name: destinationData?.name ?? '',
publicationName: pipelineData?.config.publication_name ?? '',
maxFillMs: pipelineData?.config?.batch?.max_fill_ms,
// BigQuery fields
projectId: isBigQueryConfig ? config.big_query.project_id : '',
datasetId: isBigQueryConfig ? config.big_query.dataset_id : '',
serviceAccountKey: isBigQueryConfig ? config.big_query.service_account_key : '',
maxStalenessMins: isBigQueryConfig ? config.big_query.max_staleness_mins : undefined,
// Analytics Bucket fields
warehouseName: isIcebergConfig ? config.iceberg.supabase.warehouse_name : '',
namespace: isIcebergConfig ? config.iceberg.supabase.namespace : '',
newNamespaceName: '',
catalogToken: isIcebergConfig ? config.iceberg.supabase.catalog_token : catalogToken,
s3AccessKeyId: isIcebergConfig ? config.iceberg.supabase.s3_access_key_id : '',
s3SecretAccessKey: isIcebergConfig ? config.iceberg.supabase.s3_secret_access_key : '',
s3Region:
projectSettings?.region ?? (isIcebergConfig ? config.iceberg.supabase.s3_region : ''),
}
}, [destinationData, pipelineData, catalogToken, projectSettings])

const form = useForm<z.infer<typeof FormSchema>>({
mode: 'onChange',
reValidateMode: 'onChange',
resolver: zodResolver(
FormSchema.superRefine((data, ctx) => {
const addRequiredFieldError = (path: string, message: string) => {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message,
path: [path],
})
}

if (selectedType === 'BigQuery') {
if (!data.projectId?.length) addRequiredFieldError('projectId', 'Project ID is required')
if (!data.datasetId?.length) addRequiredFieldError('datasetId', 'Dataset ID is required')
if (!data.serviceAccountKey?.length)
addRequiredFieldError('serviceAccountKey', 'Service Account Key is required')
} else if (selectedType === 'Analytics Bucket') {
if (!data.warehouseName?.length)
addRequiredFieldError('warehouseName', 'Bucket is required')

const hasValidNamespace =
(data.namespace?.length && data.namespace !== 'create-new-namespace') ||
(data.namespace === 'create-new-namespace' && data.newNamespaceName?.length)

if (!hasValidNamespace) {
const isCreatingNew = data.namespace === 'create-new-namespace'
addRequiredFieldError(
isCreatingNew ? 'newNamespaceName' : 'namespace',
isCreatingNew ? 'Namespace name is required' : 'Namespace is required'
)
}

if (!data.s3Region?.length) addRequiredFieldError('s3Region', 'S3 Region is required')

if (!data.s3AccessKeyId?.length)
addRequiredFieldError('s3AccessKeyId', 'S3 Access Key ID is required')

if (data.s3AccessKeyId !== 'create-new' && !data.s3SecretAccessKey?.length) {
addRequiredFieldError('s3SecretAccessKey', 'S3 Secret Access Key is required')
}
}
})
),
defaultValues,
})

const { publicationName, warehouseName } = form.watch()

const publicationNames = useMemo(() => publications?.map((pub) => pub.name) ?? [], [publications])
const isSelectedPublicationMissing =
isSuccessPublications && !!publicationName && !publicationNames.includes(publicationName)
const selectedPublication = publications.find((pub) => pub.name === publicationName)

const { data: checkPrimaryKeysExistsData, isPending: isLoadingCheck } = useCheckPrimaryKeysExists(
{
projectRef: project?.ref,
connectionString: project?.connectionString,
tables: selectedPublication?.tables ?? [],
},
{ enabled: visible && !!selectedPublication }
)
const hasTablesWithNoPrimaryKeys = (checkPrimaryKeysExistsData?.offendingTables ?? []).length > 0

// Helper function to handle namespace creation if needed
const resolveNamespace = async (data: z.infer<typeof FormSchema>) => {
if (data.namespace === CREATE_NEW_NAMESPACE) {
if (!data.newNamespaceName) throw new Error('New namespace name is required')

await createNamespace({
projectRef,
warehouse: data.warehouseName!,
namespace: data.newNamespaceName,
})

return data.newNamespaceName
}
return data.namespace
}

// [Joshen] I reckon this function can be refactored to be a bit more modular, it's currently pretty
// complicated with 4 different types of flows -> edit bigquery/analytics, and create bigquery/analytics
// At first glance we could try grouping as edit / create bigquery, edit / create analytics
// since the destination config seems rather similar between edit and create for the same type
const submitPipeline = async (data: z.infer<typeof FormSchema>) => {
if (!projectRef) return console.error('Project ref is required')
if (!sourceId) return console.error('Source id is required')
if (isSelectedPublicationMissing) {
return toast.error('Please select another publication before continuing')
}

try {
if (editMode && existingDestination) {
if (!existingDestination.pipelineId) return console.error('Pipeline id is required')

let destinationConfig: DestinationConfig | undefined = undefined

if (selectedType === 'BigQuery') {
const bigQueryConfig: BigQueryDestinationConfig = {
projectId: data.projectId ?? '',
datasetId: data.datasetId ?? '',
serviceAccountKey: data.serviceAccountKey ?? '',
}
if (!!data.maxStalenessMins) {
bigQueryConfig.maxStalenessMins = data.maxStalenessMins
}
destinationConfig = { bigQuery: bigQueryConfig }
} else if (selectedType === 'Analytics Bucket') {
let s3Keys = { accessKey: data.s3AccessKeyId, secretKey: data.s3SecretAccessKey }

if (data.s3AccessKeyId === CREATE_NEW_KEY) {
const newKeys = await createS3AccessKey({
projectRef,
description: `Autogenerated key for replication to ${snakeCase(warehouseName)}`,
})
s3Keys = { accessKey: newKeys.access_key, secretKey: newKeys.secret_key }
}

// Resolve namespace (create if needed)
const finalNamespace = await resolveNamespace(data)

const icebergConfig: IcebergDestinationConfig = {
projectRef: projectRef,
warehouseName: data.warehouseName ?? '',
namespace: finalNamespace,
catalogToken: data.catalogToken ?? '',
s3AccessKeyId: s3Keys.accessKey ?? '',
s3SecretAccessKey: s3Keys.secretKey ?? '',
s3Region: data.s3Region ?? '',
}
destinationConfig = { iceberg: icebergConfig }
}

const batchConfig: BatchConfig | undefined = !!data.maxFillMs
? { maxFillMs: data.maxFillMs }
: undefined
const hasBatchFields = batchConfig !== undefined

if (!destinationConfig) throw new Error('Destination configuration is missing')

await updateDestinationPipeline({
destinationId: existingDestination.destinationId,
pipelineId: existingDestination.pipelineId,
projectRef,
destinationName: data.name,
destinationConfig,
pipelineConfig: {
publicationName: data.publicationName,
...(hasBatchFields ? { batch: batchConfig } : {}),
},
sourceId,
})
// Set request status only right before starting, then fire and close
const snapshot =
existingDestination.statusName ?? (existingDestination.enabled ? 'started' : 'stopped')
if (existingDestination.enabled) {
setRequestStatus(
existingDestination.pipelineId,
PipelineStatusRequestStatus.RestartRequested,
snapshot
)
toast.success('Settings applied. Restarting the pipeline...')
restartPipeline({ projectRef, pipelineId: existingDestination.pipelineId })
} else {
setRequestStatus(
existingDestination.pipelineId,
PipelineStatusRequestStatus.StartRequested,
snapshot
)
toast.success('Settings applied. Starting the pipeline...')
startPipeline({ projectRef, pipelineId: existingDestination.pipelineId })
}
onClose()
} else {
let destinationConfig: DestinationConfig | undefined = undefined

if (selectedType === 'BigQuery') {
const bigQueryConfig: BigQueryDestinationConfig = {
projectId: data.projectId ?? '',
datasetId: data.datasetId ?? '',
serviceAccountKey: data.serviceAccountKey ?? '',
}
if (!!data.maxStalenessMins) {
bigQueryConfig.maxStalenessMins = data.maxStalenessMins
}
destinationConfig = { bigQuery: bigQueryConfig }
} else if (selectedType === 'Analytics Bucket') {
let s3Keys = { accessKey: data.s3AccessKeyId, secretKey: data.s3SecretAccessKey }

if (data.s3AccessKeyId === CREATE_NEW_KEY) {
const newKeys = await createS3AccessKey({
projectRef,
description: `Autogenerated key for replication to ${snakeCase(warehouseName)}`,
})
s3Keys = { accessKey: newKeys.access_key, secretKey: newKeys.secret_key }
}

// Resolve namespace (create if needed)
const finalNamespace = await resolveNamespace(data)

const icebergConfig: IcebergDestinationConfig = {
projectRef: projectRef,
warehouseName: data.warehouseName ?? '',
namespace: finalNamespace,
catalogToken: data.catalogToken ?? '',
s3AccessKeyId: s3Keys.accessKey ?? '',
s3SecretAccessKey: s3Keys.secretKey ?? '',
s3Region: data.s3Region ?? '',
}
destinationConfig = { iceberg: icebergConfig }
}
const batchConfig: BatchConfig | undefined = !!data.maxFillMs
? { maxFillMs: data.maxFillMs }
: undefined
const hasBatchFields = batchConfig !== undefined

if (!destinationConfig) throw new Error('Destination configuration is missing')

const { pipeline_id: pipelineId } = await createDestinationPipeline({
projectRef,
destinationName: data.name,
destinationConfig,
sourceId,
pipelineConfig: {
publicationName: data.publicationName,
...(hasBatchFields ? { batch: batchConfig } : {}),
},
})
// Set request status only right before starting, then fire and close
setRequestStatus(pipelineId, PipelineStatusRequestStatus.StartRequested, undefined)
toast.success('Destination created. Starting the pipeline...')
startPipeline({ projectRef, pipelineId })
onClose()
}
} catch (error) {
const action = editMode ? 'apply and run' : 'create and start'
toast.error(`Failed to ${action} destination`)
}
}

const isSaving =
creatingDestinationPipeline ||
updatingDestinationPipeline ||
startingPipeline ||
isCreatingS3AccessKey ||
isCreatingNamespace

const isSubmitDisabled =
isSaving ||
isSelectedPublicationMissing ||
(!!selectedPublication && isLoadingCheck) ||
hasTablesWithNoPrimaryKeys ||
(!editMode && hasNoAvailableDestinations)

const onSubmit = async (data: z.infer<typeof FormSchema>) => {
if (!editMode) {
setPendingFormValues(data)
setShowDisclaimerDialog(true)
return
}

await submitPipeline(data)
}

const handleDisclaimerDialogChange = (open: boolean) => {
setShowDisclaimerDialog(open)
if (!open) {
setPendingFormValues(null)
}
}

const handleDisclaimerConfirm = async () => {
if (!pendingFormValues) return

const values = pendingFormValues
setPendingFormValues(null)
setShowDisclaimerDialog(false)
await submitPipeline(values)
}

useEffect(() => {
if (editMode && destinationData && pipelineData && !isFormInteracting) {
form.reset(defaultValues)
}
}, [destinationData, pipelineData, editMode, defaultValues, form, isFormInteracting])

// Ensure the form always reflects the freshest data whenever the panel opens
useEffect(() => {
if (visible) {
form.reset(defaultValues)
setIsFormInteracting(false)
}
}, [visible, defaultValues, form])

useEffect(() => {
if (visible && projectRef && sourceId) {
refetchPublications()
}
}, [visible, projectRef, sourceId, refetchPublications])

return (
<>
<SheetSection className="flex-grow overflow-auto px-0 py-0">
{hasNoAvailableDestinations && !editMode ? (
<NoDestinationsAvailable />
) : (
<Form_Shadcn_ {...form}>
<form id={formId} onSubmit={form.handleSubmit(onSubmit)}>
<div className="p-5 flex flex-col gap-y-6">
<p className="text-sm font-medium text-foreground">Destination details</p>

<div className="space-y-4">
<DestinationNameInput form={form} />
<PublicationSelection
form={form}
sourceId={sourceId}
visible={visible}
onSelectNewPublication={() => setPublicationPanelVisible(true)}
/>
</div>
</div>

<DialogSectionSeparator />

{selectedType === 'BigQuery' && etlEnableBigQuery ? (
<BigQueryFields form={form} />
) : selectedType === 'Analytics Bucket' && etlEnableIceberg ? (
<AnalyticsBucketFields
form={form}
setIsFormInteracting={setIsFormInteracting}
onSelectNewBucket={() => setNewBucketSheetVisible(true)}
/>
) : null}

<DialogSectionSeparator />

<AdvancedSettings type={selectedType} form={form} />
</form>
</Form_Shadcn_>
)}
</SheetSection>

<SheetFooter>
<Button disabled={isSaving} type="default" onClick={onClose}>
Cancel
</Button>
<Button disabled={isSubmitDisabled} loading={isSaving} form={formId} htmlType="submit">
{editMode
? existingDestination?.enabled
? 'Apply and restart'
: 'Apply and start'
: 'Create and start'}
</Button>
</SheetFooter>

<NewPublicationPanel
sourceId={sourceId}
visible={publicationPanelVisible}
onClose={() => setPublicationPanelVisible(false)}
/>

<CreateAnalyticsBucketSheet
open={newBucketSheetVisible}
onOpenChange={setNewBucketSheetVisible}
/>

<ReplicationDisclaimerDialog
open={showDisclaimerDialog}
onOpenChange={handleDisclaimerDialogChange}
isLoading={isSaving}
onConfirm={handleDisclaimerConfirm}
/>
</>
)
}

@coderabbitai coderabbitai Bot Dec 18, 2025 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion | 🟠 Major

Component exceeds size guideline.

This component is 546 lines, significantly exceeding the 200-300 line guideline for studio components. Consider extracting distinct sections into separate components, such as:

  • Form field rendering logic (BigQuery/Analytics Bucket fields are already extracted, which is good)
  • The complex submitPipeline logic into a custom hook (e.g., useDestinationPipelineSubmit)
  • Modal/dialog management into a separate component

This would improve maintainability and testability.

As per coding guidelines, components should ideally be under 200-300 lines and should be broken down when they have multiple distinct UI sections, complex conditional rendering, or multiple unrelated useState hooks.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yup i know - but probably one for another PR, as this is more focused on just shifting stuff for now

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@joshenlim, understood! That makes sense given the PR's focus on reorganization.

If you'd like, I can create a follow-up issue to track the refactoring work for breaking down this component in a future PR. Just let me know!


🧠 Learnings used
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-best-practices.mdc:0-0
Timestamp: 2025-12-11T16:46:18.701Z
Learning: Applies to apps/studio/**/*.tsx : Components should ideally be under 200-300 lines; break down large components with multiple distinct UI sections, complex conditional rendering, or multiple unrelated useState hooks

Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-best-practices.mdc:0-0
Timestamp: 2025-12-11T16:46:18.701Z
Learning: Applies to apps/studio/**/*.tsx : Extract repeated JSX patterns into reusable components instead of copying similar JSX blocks

Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-best-practices.mdc:0-0
Timestamp: 2025-12-11T16:46:18.701Z
Learning: Applies to apps/studio/**/*.tsx : Group related state using objects or reducers instead of multiple useState calls, preferring react-hook-form for form state management

Comment on lines +256 to +410
const submitPipeline = async (data: z.infer<typeof FormSchema>) => {
if (!projectRef) return console.error('Project ref is required')
if (!sourceId) return console.error('Source id is required')
if (isSelectedPublicationMissing) {
return toast.error('Please select another publication before continuing')
}

try {
if (editMode && existingDestination) {
if (!existingDestination.pipelineId) return console.error('Pipeline id is required')

let destinationConfig: DestinationConfig | undefined = undefined

if (selectedType === 'BigQuery') {
const bigQueryConfig: BigQueryDestinationConfig = {
projectId: data.projectId ?? '',
datasetId: data.datasetId ?? '',
serviceAccountKey: data.serviceAccountKey ?? '',
}
if (!!data.maxStalenessMins) {
bigQueryConfig.maxStalenessMins = data.maxStalenessMins
}
destinationConfig = { bigQuery: bigQueryConfig }
} else if (selectedType === 'Analytics Bucket') {
let s3Keys = { accessKey: data.s3AccessKeyId, secretKey: data.s3SecretAccessKey }

if (data.s3AccessKeyId === CREATE_NEW_KEY) {
const newKeys = await createS3AccessKey({
projectRef,
description: `Autogenerated key for replication to ${snakeCase(warehouseName)}`,
})
s3Keys = { accessKey: newKeys.access_key, secretKey: newKeys.secret_key }
}

// Resolve namespace (create if needed)
const finalNamespace = await resolveNamespace(data)

const icebergConfig: IcebergDestinationConfig = {
projectRef: projectRef,
warehouseName: data.warehouseName ?? '',
namespace: finalNamespace,
catalogToken: data.catalogToken ?? '',
s3AccessKeyId: s3Keys.accessKey ?? '',
s3SecretAccessKey: s3Keys.secretKey ?? '',
s3Region: data.s3Region ?? '',
}
destinationConfig = { iceberg: icebergConfig }
}

const batchConfig: BatchConfig | undefined = !!data.maxFillMs
? { maxFillMs: data.maxFillMs }
: undefined
const hasBatchFields = batchConfig !== undefined

if (!destinationConfig) throw new Error('Destination configuration is missing')

await updateDestinationPipeline({
destinationId: existingDestination.destinationId,
pipelineId: existingDestination.pipelineId,
projectRef,
destinationName: data.name,
destinationConfig,
pipelineConfig: {
publicationName: data.publicationName,
...(hasBatchFields ? { batch: batchConfig } : {}),
},
sourceId,
})
// Set request status only right before starting, then fire and close
const snapshot =
existingDestination.statusName ?? (existingDestination.enabled ? 'started' : 'stopped')
if (existingDestination.enabled) {
setRequestStatus(
existingDestination.pipelineId,
PipelineStatusRequestStatus.RestartRequested,
snapshot
)
toast.success('Settings applied. Restarting the pipeline...')
restartPipeline({ projectRef, pipelineId: existingDestination.pipelineId })
} else {
setRequestStatus(
existingDestination.pipelineId,
PipelineStatusRequestStatus.StartRequested,
snapshot
)
toast.success('Settings applied. Starting the pipeline...')
startPipeline({ projectRef, pipelineId: existingDestination.pipelineId })
}
onClose()
} else {
let destinationConfig: DestinationConfig | undefined = undefined

if (selectedType === 'BigQuery') {
const bigQueryConfig: BigQueryDestinationConfig = {
projectId: data.projectId ?? '',
datasetId: data.datasetId ?? '',
serviceAccountKey: data.serviceAccountKey ?? '',
}
if (!!data.maxStalenessMins) {
bigQueryConfig.maxStalenessMins = data.maxStalenessMins
}
destinationConfig = { bigQuery: bigQueryConfig }
} else if (selectedType === 'Analytics Bucket') {
let s3Keys = { accessKey: data.s3AccessKeyId, secretKey: data.s3SecretAccessKey }

if (data.s3AccessKeyId === CREATE_NEW_KEY) {
const newKeys = await createS3AccessKey({
projectRef,
description: `Autogenerated key for replication to ${snakeCase(warehouseName)}`,
})
s3Keys = { accessKey: newKeys.access_key, secretKey: newKeys.secret_key }
}

// Resolve namespace (create if needed)
const finalNamespace = await resolveNamespace(data)

const icebergConfig: IcebergDestinationConfig = {
projectRef: projectRef,
warehouseName: data.warehouseName ?? '',
namespace: finalNamespace,
catalogToken: data.catalogToken ?? '',
s3AccessKeyId: s3Keys.accessKey ?? '',
s3SecretAccessKey: s3Keys.secretKey ?? '',
s3Region: data.s3Region ?? '',
}
destinationConfig = { iceberg: icebergConfig }
}
const batchConfig: BatchConfig | undefined = !!data.maxFillMs
? { maxFillMs: data.maxFillMs }
: undefined
const hasBatchFields = batchConfig !== undefined

if (!destinationConfig) throw new Error('Destination configuration is missing')

const { pipeline_id: pipelineId } = await createDestinationPipeline({
projectRef,
destinationName: data.name,
destinationConfig,
sourceId,
pipelineConfig: {
publicationName: data.publicationName,
...(hasBatchFields ? { batch: batchConfig } : {}),
},
})
// Set request status only right before starting, then fire and close
setRequestStatus(pipelineId, PipelineStatusRequestStatus.StartRequested, undefined)
toast.success('Destination created. Starting the pipeline...')
startPipeline({ projectRef, pipelineId })
onClose()
}
} catch (error) {
const action = editMode ? 'apply and run' : 'create and start'
toast.error(`Failed to ${action} destination`)
}
}

@coderabbitai coderabbitai Bot Dec 18, 2025 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion | 🟠 Major

Refactor submitPipeline to eliminate duplication.

As noted in your comment at line 252, this function handles 4 different flows and contains significant code duplication. Lines 269-303 (edit mode config building) are nearly identical to lines 348-382 (create mode config building).

Extract the destination config building logic into separate helper functions:

🔎 Suggested refactoring approach
const buildBigQueryConfig = (data: z.infer<typeof FormSchema>): BigQueryDestinationConfig => {
  const config: BigQueryDestinationConfig = {
    projectId: data.projectId ?? '',
    datasetId: data.datasetId ?? '',
    serviceAccountKey: data.serviceAccountKey ?? '',
  }
  if (data.maxStalenessMins) {
    config.maxStalenessMins = data.maxStalenessMins
  }
  return config
}

const buildIcebergConfig = async (
  data: z.infer<typeof FormSchema>,
  s3Keys: { accessKey: string; secretKey: string }
): Promise<IcebergDestinationConfig> => {
  const finalNamespace = await resolveNamespace(data)
  return {
    projectRef: projectRef,
    warehouseName: data.warehouseName ?? '',
    namespace: finalNamespace,
    catalogToken: data.catalogToken ?? '',
    s3AccessKeyId: s3Keys.accessKey,
    s3SecretAccessKey: s3Keys.secretKey,
    s3Region: data.s3Region ?? '',
  }
}

const resolveS3Keys = async (data: z.infer<typeof FormSchema>) => {
  if (data.s3AccessKeyId === CREATE_NEW_KEY) {
    const newKeys = await createS3AccessKey({
      projectRef,
      description: `Autogenerated key for replication to ${snakeCase(warehouseName)}`,
    })
    return { accessKey: newKeys.access_key, secretKey: newKeys.secret_key }
  }
  return { accessKey: data.s3AccessKeyId, secretKey: data.s3SecretAccessKey }
}

Then in submitPipeline, call these helpers instead of duplicating the logic.

As per coding guidelines, extract complex logic into custom hooks when logic becomes reusable or complex, and avoid duplicate code by extracting abstractions.

🤖 Prompt for AI Agents
In
apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/index.tsx
around lines 256 to 410, the destination-config construction for BigQuery and
Analytics Bucket is duplicated between the edit and create branches; extract
that logic into three helpers (synchronous buildBigQueryConfig, async
resolveS3Keys, async buildIcebergConfig) that accept the form data and required
context (projectRef, warehouseName) and return the appropriate DestinationConfig
pieces, then replace the duplicated blocks in both branches with calls to these
helpers (await where needed), preserve the existing batchConfig handling and
error throw when destinationConfig is missing, and ensure helper signatures are
async if they call resolveNamespace or createS3AccessKey so callers await them.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

also agree - these all need refactoring really but am focusing on shifting stuff around in this PR
will address separately

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@joshenlim, sounds good! Separating the organizational changes from the refactoring work makes sense for keeping the PR focused.

Would you like me to create a GitHub issue to track the refactoring of the submitPipeline function? I can include the context about extracting the duplicated BigQuery and Analytics Bucket config-building logic into helper functions.

Comment on lines +257 to +258
if (!projectRef) return console.error('Project ref is required')
if (!sourceId) return console.error('Source id is required')

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Replace console.error with proper error handling.

Using console.error and returning early silently can mask critical issues. These guard conditions should either throw an error or display a user-facing toast notification.

🔎 Apply this diff
-    if (!projectRef) return console.error('Project ref is required')
-    if (!sourceId) return console.error('Source id is required')
+    if (!projectRef) {
+      toast.error('Project reference is missing')
+      return
+    }
+    if (!sourceId) {
+      toast.error('Source ID is missing')
+      return
+    }

Apply the same pattern to line 265.

📝 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.

Suggested change
if (!projectRef) return console.error('Project ref is required')
if (!sourceId) return console.error('Source id is required')
if (!projectRef) {
toast.error('Project reference is missing')
return
}
if (!sourceId) {
toast.error('Source ID is missing')
return
}
🤖 Prompt for AI Agents
In
apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/index.tsx
around lines 257-258 (and also apply to line 265), replace the console.error +
early return with proper error handling: show a user-facing notification (e.g.,
toast.error('Project ref is required') / toast.error('Source id is required'))
so the user sees the problem, then throw a new Error('Project ref is required')
/ throw new Error('Source id is required') to stop execution and surface the
failure programmatically; apply the same pattern at line 265 for the analogous
guard.

}, [etlEnableBigQuery, etlEnableIceberg])

const hasNoAvailableDestinations = availableDestinations.length === 0
const [selectedType, setSelectedType] = useState<DestinationType>('Read Replica')

@coderabbitai coderabbitai Bot Dec 18, 2025 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Find the DestinationPanel.tsx file and check its content
find . -type f -name "DestinationPanel.tsx" | head -5

Repository: supabase/supabase

Length of output: 155


🏁 Script executed:

#!/bin/bash
# Search for destination type patterns in the codebase
rg -n "destination.*type|DestinationType" --type=tsx --type=ts -A 2 -B 2 | head -100

Repository: supabase/supabase

Length of output: 88


🏁 Script executed:

#!/bin/bash
# Read the DestinationPanel.tsx file
wc -l ./apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationPanel.tsx

Repository: supabase/supabase

Length of output: 158


🏁 Script executed:

#!/bin/bash
# Read the first 100 lines to see the props interface and line 36
head -n 100 ./apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationPanel.tsx

Repository: supabase/supabase

Length of output: 2465


🏁 Script executed:

#!/bin/bash
# Search for DestinationType definition and destination type patterns using glob patterns
rg -g '*.ts' -g '*.tsx' 'DestinationType|type.*destination|destinationData.*type' -A 2 -B 2 | head -150

Repository: supabase/supabase

Length of output: 10377


🏁 Script executed:

#!/bin/bash
# Find where DestinationPanel is used and how it's called
rg -g '*.tsx' -g '*.ts' 'DestinationPanel' -A 5 -B 2 | grep -A 10 "DestinationRow\|onEdit\|openEdit"

Repository: supabase/supabase

Length of output: 6546


🏁 Script executed:

#!/bin/bash
# Check DestinationRow component to see how it uses DestinationPanel
cat -n ./apps/studio/components/interfaces/Database/Replication/DestinationRow.tsx | head -150

Repository: supabase/supabase

Length of output: 6899


🏁 Script executed:

#!/bin/bash
# Read more of DestinationRow to see the complete DestinationPanel usage
sed -n '150,250p' ./apps/studio/components/interfaces/Database/Replication/DestinationRow.tsx

Repository: supabase/supabase

Length of output: 3634


🏁 Script executed:

#!/bin/bash
# Check if there's any reference to destination data queries that might contain type info
rg -g '*.tsx' -g '*.ts' 'useReplicationDestination|destination.*config|big_query|analytics.*bucket' apps/studio/data/replication -A 3 -B 1 | head -100

Repository: supabase/supabase

Length of output: 6468


🏁 Script executed:

#!/bin/bash
# Check if there's a useEffect in DestinationPanel that derives selectedType from existingDestination
cat -n ./apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationPanel.tsx

Repository: supabase/supabase

Length of output: 3046


🏁 Script executed:

#!/bin/bash
# Check the Destinations component to see how it passes data to DestinationRow
rg -g '*.tsx' 'DestinationRow' apps/studio/components/interfaces/Database/Replication/Destinations.tsx -A 10 -B 5

Repository: supabase/supabase

Length of output: 1474


🏁 Script executed:

#!/bin/bash
# Check DestinationTypeSelection to see how it handles editMode
cat -n ./apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationTypeSelection.tsx

Repository: supabase/supabase

Length of output: 4700


Add type field to existingDestination prop to fix edit mode rendering.

When editing an existing BigQuery or Analytics Bucket destination, selectedType defaults to 'Read Replica' because the existingDestination prop lacks type information. This causes DestinationTypeSelection to only render the "Read Replica" option in edit mode (line 48), and the form displays "Coming soon" instead of the actual destination form.

Add the type: DestinationType field to the existingDestination prop interface, and pass it from DestinationRow when opening the edit panel. Then use a useEffect in DestinationPanel to initialize selectedType from existingDestination.type.

🤖 Prompt for AI Agents
In
apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationPanel.tsx
around line 36, the edit flow lacks destination type info so selectedType always
defaults to 'Read Replica'; add type: DestinationType to the existingDestination
prop/interface, ensure DestinationRow passes the destination.type when opening
the edit panel, and in DestinationPanel add a useEffect that, when
existingDestination is present, calls setSelectedType(existingDestination.type)
(import DestinationType if needed) so the UI renders the correct selection and
form for BigQuery/Analytics Bucket edit mode.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ahh yes ignore for now - i'll hook things up properly in a follow up PR, am just scaffolding the read replicas stuff for now. Changes are behind a feature flag as well so changes won't be publicly visible

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@joshenlim Thanks for the clarification! Makes sense to scaffold this incrementally, especially with the feature flag protection in place.

Would you like me to create a follow-up issue to track hooking up the destination type properly for edit mode once the read replicas work is complete? I can link back to this PR and comment for context.


🧠 Learnings used
Learnt from: ignaciodob
Repo: supabase/supabase PR: 41291
File: packages/api-types/types/platform.d.ts:7128-7128
Timestamp: 2025-12-12T11:28:04.537Z
Learning: In supabase/supabase, use the existing 'do-not-merge' label to block merges for entitlement-gated UI changes until the backend entitlement is live and API types are regenerated.

Comment on lines +48 to +66
{((!editMode && unifiedReplication) || (editMode && selectedType === 'Read Replica')) && (
<RadioGroupStackedItem
label=""
showIndicator={false}
id="Read Replica"
value="Read Replica"
>
<div className="flex flex-col gap-y-2">
<Database size={20} />
<div className="flex flex-col gap-y-0.5 text-sm text-left">
<p>Read Replica</p>
<p className="text-foreground-lighter">
Deploy read-only databases across multiple regions for lower latency and better
resource management
</p>
</div>
</div>
</RadioGroupStackedItem>
)}

@coderabbitai coderabbitai Bot Dec 18, 2025 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

# First, locate the file and examine its content
find . -name "DestinationTypeSelection.tsx" -type f 2>/dev/null

Repository: supabase/supabase

Length of output: 163


🏁 Script executed:

# Search for selectedType initialization patterns
rg -n "selectedType.*useState|useState.*selectedType" --type=tsx -A 2 -B 2

Repository: supabase/supabase

Length of output: 88


🏁 Script executed:

# Look for the component's props and parent context
rg -n "DestinationTypeSelection" --type=tsx -A 3 -B 3

Repository: supabase/supabase

Length of output: 88


🏁 Script executed:

# Read the component file to examine selectedType initialization
cat -n ./apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationTypeSelection.tsx

Repository: supabase/supabase

Length of output: 4700


🏁 Script executed:

# Search for the parent component and usage patterns
find . -name "DestinationPanel.tsx" -o -name "*Replication*.tsx" | head -20

Repository: supabase/supabase

Length of output: 593


🏁 Script executed:

# Read the parent component file
cat -n ./apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationPanel.tsx

Repository: supabase/supabase

Length of output: 3046


🏁 Script executed:

# Check if there's any useEffect that resets selectedType based on flags
grep -n "setSelectedType\|useEffect" ./apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationPanel.tsx

Repository: supabase/supabase

Length of output: 198


🏁 Script executed:

# Also check the types to understand DestinationType
cat -n ./apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationPanel.types.ts

Repository: supabase/supabase

Length of output: 146


Ensure selectedType defaults to a visible option based on enabled feature flags.

The component hardcodes selectedType to 'Read Replica' on line 36 of DestinationPanel.tsx, but this option only renders if the unifiedReplication flag is true or in edit mode. When creating a new destination with unifiedReplication disabled and other destination types also hidden by their flags, the radio group will have no visible options despite having a selected value, creating a broken UI state. Initialize selectedType to the first enabled destination type instead of a fixed default.

🤖 Prompt for AI Agents
In
apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationTypeSelection.tsx
around lines 48-66, selectedType is hardcoded to 'Read Replica' in
DestinationPanel.tsx (line ~36) which can be hidden by feature flags causing an
invisible-selected radio; change initialization to compute the list of visible
destination types using the same unifiedReplication/editMode flag logic used for
rendering, then set selectedType to the first enabled option (use useState(() =>
firstOption || null) or a safe fallback). Also add an effect to update
selectedType when feature flags or editMode change (preserve current selection
in edit mode), so the initial and dynamic states always point to a visible
option.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

great catch - thanks!

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@joshenlim You're welcome! Happy to help catch these edge cases. 😊


🧠 Learnings used
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T17:04:40.037Z
Learning: Applies to apps/studio/components/**/*.{ts,tsx} : Use RadioGroupStacked with RadioGroupStackedItem for stacked radio options with descriptions

Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T17:04:40.037Z
Learning: Applies to apps/studio/components/**/*.{ts,tsx} : Use Select_Shadcn_ with SelectTrigger_Shadcn_, SelectContent_Shadcn_, and SelectItem_Shadcn_ for select form fields

Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T17:04:40.037Z
Learning: Applies to apps/studio/components/**/*.{ts,tsx} : Use MultiSelector component from ui-patterns/multi-select for multi-select form fields

Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T17:04:40.037Z
Learning: Applies to apps/studio/components/**/*.{ts,tsx} : Use Checkbox_Shadcn_ with label for checkbox form fields, and multiple checkboxes for checkbox groups

Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-best-practices.mdc:0-0
Timestamp: 2025-12-11T16:46:18.701Z
Learning: Applies to apps/studio/**/*.tsx : Define prop interfaces explicitly for React components with proper typing of props and callback handlers

Comment on lines +91 to +115
{project?.cloud_provider !== 'FLY' &&
(unifiedReplication ? (
<ScaffoldContainer>
<ScaffoldSection isFullWidth>
<NoticeBar
visible={true}
type="default"
title="Management of read replicas has moved"
description="Read replicas is now managed under Replication in the Database section."
actions={
<Button type="default" asChild>
<Link href={`/project/${ref}/database/replication`} className="!no-underline">
Go to Replication
</Link>
</Button>
}
/>
</ScaffoldSection>
</ScaffoldContainer>
) : (
<>
<InstanceConfiguration />
<ScaffoldDivider />
</>
))}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion | 🟠 Major

Refactor nested ternary to improve readability.

The nested ternary conditional violates the coding guideline to avoid nested ternaries in JSX. Additionally, the complex condition should be extracted to a descriptive variable for clarity.

🔎 Apply this refactor to improve readability:
+  const shouldShowInfrastructure = project?.cloud_provider !== 'FLY'
+
   return (
     <>
       <ScaffoldDivider />
-      {project?.cloud_provider !== 'FLY' &&
-        (unifiedReplication ? (
-          <ScaffoldContainer>
-            <ScaffoldSection isFullWidth>
-              <NoticeBar
-                visible={true}
-                type="default"
-                title="Management of read replicas has moved"
-                description="Read replicas is now managed under Replication in the Database section."
-                actions={
-                  <Button type="default" asChild>
-                    <Link href={`/project/${ref}/database/replication`} className="!no-underline">
-                      Go to Replication
-                    </Link>
-                  </Button>
-                }
-              />
-            </ScaffoldSection>
-          </ScaffoldContainer>
-        ) : (
-          <>
-            <InstanceConfiguration />
-            <ScaffoldDivider />
-          </>
-        ))}
+      {shouldShowInfrastructure && unifiedReplication && (
+        <ScaffoldContainer>
+          <ScaffoldSection isFullWidth>
+            <NoticeBar
+              visible
+              type="default"
+              title="Management of read replicas has moved"
+              description="Read replicas is now managed under Replication in the Database section."
+              actions={
+                <Button type="default" asChild>
+                  <Link href={`/project/${ref}/database/replication`} className="!no-underline">
+                    Go to Replication
+                  </Link>
+                </Button>
+              }
+            />
+          </ScaffoldSection>
+        </ScaffoldContainer>
+      )}
+      {shouldShowInfrastructure && !unifiedReplication && (
+        <>
+          <InstanceConfiguration />
+          <ScaffoldDivider />
+        </>
+      )}

As per coding guidelines, this approach:

  • Eliminates the nested ternary for better readability
  • Extracts the complex condition into a descriptive variable
  • Simplifies visible={true} to just visible
📝 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.

Suggested change
{project?.cloud_provider !== 'FLY' &&
(unifiedReplication ? (
<ScaffoldContainer>
<ScaffoldSection isFullWidth>
<NoticeBar
visible={true}
type="default"
title="Management of read replicas has moved"
description="Read replicas is now managed under Replication in the Database section."
actions={
<Button type="default" asChild>
<Link href={`/project/${ref}/database/replication`} className="!no-underline">
Go to Replication
</Link>
</Button>
}
/>
</ScaffoldSection>
</ScaffoldContainer>
) : (
<>
<InstanceConfiguration />
<ScaffoldDivider />
</>
))}
const shouldShowInfrastructure = project?.cloud_provider !== 'FLY'
return (
<>
<ScaffoldDivider />
{shouldShowInfrastructure && unifiedReplication && (
<ScaffoldContainer>
<ScaffoldSection isFullWidth>
<NoticeBar
visible
type="default"
title="Management of read replicas has moved"
description="Read replicas is now managed under Replication in the Database section."
actions={
<Button type="default" asChild>
<Link href={`/project/${ref}/database/replication`} className="!no-underline">
Go to Replication
</Link>
</Button>
}
/>
</ScaffoldSection>
</ScaffoldContainer>
)}
{shouldShowInfrastructure && !unifiedReplication && (
<>
<InstanceConfiguration />
<ScaffoldDivider />
</>
)}
</>
)
🤖 Prompt for AI Agents
In
apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureInfo.tsx
around lines 91 to 115, replace the nested ternary in the JSX with clearer
conditional rendering: extract the condition (project?.cloud_provider !== 'FLY'
&& unifiedReplication) into a descriptive boolean (e.g., showReplicationNotice)
and use simple if/else-style JSX branches (or two separate && checks) to render
either the NoticeBar wrapped in ScaffoldContainer/Section or the
InstanceConfiguration + ScaffoldDivider. Also simplify NoticeBar prop
visible={true} to visible. Ensure imports and variable names are consistent and
keep the original link/ref behavior.

@github-actions

github-actions Bot commented Dec 18, 2025 •

Copy link
Copy Markdown
Contributor

🎭 Playwright Test Results

passed  66 passed
flaky  1 flaky
skipped  4 skipped

Details

stats  71 tests across 12 suites
duration  7 minutes, 57 seconds
commit  bd6d251

Flaky tests

Features › database.spec.ts › Database › Schema Visualizer › actions works as expected

Skipped tests

Features › sql-editor.spec.ts › SQL Editor › snippet favourite works as expected
Features › sql-editor.spec.ts › SQL Editor › share with team works as expected
Features › sql-editor.spec.ts › SQL Editor › folders works as expected
Features › sql-editor.spec.ts › SQL Editor › other SQL snippets actions work as expected

@alaister alaister left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM!

  • Tested on preview

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationPanel.tsx (1)

42-84: Remove unnecessary fragment wrapper.

The empty fragment (<>...</>) on lines 43 and 83 is redundant since Sheet is the only child element. This is a minor cleanup.

🔎 Suggested fix:
  return (
-    <>
-      <Sheet open={visible} onOpenChange={onClose}>
+    <Sheet open={visible} onOpenChange={onClose}>
        <SheetContent
          size="default"
          showClose={false}
          className={cn(unifiedReplication ? 'md:!w-[850px]' : 'md:!w-[700px]')}
        >
          <div className="flex flex-col h-full" tabIndex={-1}>
            ...
          </div>
        </SheetContent>
-      </Sheet>
-    </>
+    </Sheet>
  )
📜 Review details

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6d95b54 and bd6d251.

📒 Files selected for processing (1)
  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationPanel.tsx (2 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
apps/studio/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/studio-best-practices.mdc)

apps/studio/**/*.{ts,tsx}: Assign complex conditions to descriptive variables instead of using multiple conditions in a single expression
Use consistent naming conventions for boolean variables: is prefix for state/identity, has prefix for possession, can prefix for capability/permission, should prefix for conditional behavior
Derive boolean state from existing state instead of storing it separately
Use early returns for guard clauses instead of deeply nested conditionals
Extract complex logic into custom hooks when logic becomes reusable or complex
Return objects from custom hooks instead of arrays for better extensibility and clearer API
Use discriminated unions for complex state management instead of multiple independent state fields
Avoid type casting (e.g., as any, as Type); instead validate values at runtime using zod schemas

Files:

  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationPanel.tsx
apps/studio/**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/studio-best-practices.mdc)

apps/studio/**/*.tsx: Components should ideally be under 200-300 lines; break down large components with multiple distinct UI sections, complex conditional rendering, or multiple unrelated useState hooks
Extract repeated JSX patterns into reusable components instead of copying similar JSX blocks
Use consistent loading/error/success pattern: handle loading state first with early returns, then error state, then empty state, then render success state
Keep state as local as possible and only lift up when needed
Group related state using objects or reducers instead of multiple useState calls, preferring react-hook-form for form state management
Name event handlers consistently: use on prefix for prop callbacks and handle prefix for internal handlers
Avoid inline arrow functions for expensive operations; use useCallback to maintain stable function references
Use appropriate conditional rendering patterns: && for simple show/hide, ternary for binary choice, early returns or extracted components for multiple conditions
Avoid nested ternaries in JSX; use separate conditions or early returns instead
Use useMemo for expensive computations when the computation is genuinely expensive and the value is passed to memoized children
Define prop interfaces explicitly for React components with proper typing of props and callback handlers

Files:

  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationPanel.tsx
🧠 Learnings (6)
📚 Learning: 2025-12-12T05:20:17.409Z
Learnt from: joshenlim
Repo: supabase/supabase PR: 41258
File: apps/studio/pages/project/[ref]/storage/vectors/buckets/[bucketId].tsx:9-9
Timestamp: 2025-12-12T05:20:17.409Z
Learning: In apps/studio/**/*.{ts,tsx}, use named imports for DefaultLayout: import { DefaultLayout } from 'components/layouts/DefaultLayout' instead of default import. This is the new practice being adopted across the studio app.

Applied to files:

  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationPanel.tsx
📚 Learning: 2025-12-11T16:46:18.701Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-best-practices.mdc:0-0
Timestamp: 2025-12-11T16:46:18.701Z
Learning: Applies to apps/studio/**/*.tsx : Define prop interfaces explicitly for React components with proper typing of props and callback handlers

Applied to files:

  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationPanel.tsx
📚 Learning: 2025-12-12T11:28:04.537Z
Learnt from: ignaciodob
Repo: supabase/supabase PR: 41291
File: packages/api-types/types/platform.d.ts:7128-7128
Timestamp: 2025-12-12T11:28:04.537Z
Learning: In supabase/supabase, use the existing 'do-not-merge' label to block merges for entitlement-gated UI changes until the backend entitlement is live and API types are regenerated.

Applied to files:

  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationPanel.tsx
📚 Learning: 2025-12-11T17:04:40.037Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T17:04:40.037Z
Learning: Applies to apps/studio/components/**/*.{ts,tsx} : Use sheets when revealing complicated forms or information relating to an object where context switching to a new page would be disruptive

Applied to files:

  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationPanel.tsx
📚 Learning: 2025-12-11T17:04:40.037Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T17:04:40.037Z
Learning: Applies to apps/studio/components/**/*.{ts,tsx} : Place submit/cancel buttons in SheetFooter for forms in sheets

Applied to files:

  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationPanel.tsx
📚 Learning: 2025-12-11T17:04:40.037Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T17:04:40.037Z
Learning: Applies to apps/studio/components/**/*.{ts,tsx} : Use SheetHeader, SheetTitle, SheetSection, and SheetFooter for consistent sheet structure

Applied to files:

  • apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationPanel.tsx
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: test (1)
  • GitHub Check: test
  • GitHub Check: typecheck
🔇 Additional comments (4)
apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationPanel.tsx (4)

1-15: LGTM!

Imports are clean and follow the named import convention. The new modular structure with DestinationForm, DestinationType, and DestinationTypeSelection aligns well with the refactoring goals.


17-27: Props interface is well-defined.

The interface follows conventions with explicit typing. The onClose callback correctly uses the on prefix per coding guidelines.


34-40: Good use of derived state.

editMode is correctly derived from existingDestination rather than stored separately, which aligns with the coding guidelines. The feature flag controls the default type selection appropriately for the scaffolding phase.


68-79: LGTM!

The ternary conditional rendering is the appropriate pattern for this binary choice. The "Coming soon" placeholder for Read Replica is reasonable given the feature flag protection, and the DestinationForm delegation cleanly separates concerns.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants