The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Joshen/depr 170 analytics buckets hook up connect tables functionality (#40217)
Joshen Lim833441801bfd
diff --git a/apps/studio/components/interfaces/Database/ETL/Destinations.tsx b/apps/studio/components/interfaces/Database/ETL/Destinations.tsxindex 7432e6cd173..dca4d6fdd74 100644--- a/apps/studio/components/interfaces/Database/ETL/Destinations.tsx+++ b/apps/studio/components/interfaces/Database/ETL/Destinations.tsx@@ -117,8 +117,6 @@ export const Destinations = () => {</div><div className="w-full overflow-hidden overflow-x-auto">- {(isSourcesLoading || isDestinationsLoading) && <GenericSkeletonLoader />}-{(isSourcesError || isDestinationsError) && (<AlertErrorerror={sourcesError || destinationsError}@@ -126,7 +124,9 @@ export const Destinations = () => {/>)}- {replicationNotEnabled ? (+ {isSourcesLoading || isDestinationsLoading ? (+ <GenericSkeletonLoader />+ ) : replicationNotEnabled ? (<div className="border rounded-md p-4 md:p-12 flex flex-col gap-y-4"><div className="flex flex-col gap-y-1"><h3>Stream data to external destinations in real-time</h3>diff --git a/apps/studio/components/interfaces/Database/ETL/NewPublicationPanel.tsx b/apps/studio/components/interfaces/Database/ETL/NewPublicationPanel.tsxindex a83ce63f42d..72d8d7e7194 100644--- a/apps/studio/components/interfaces/Database/ETL/NewPublicationPanel.tsx+++ b/apps/studio/components/interfaces/Database/ETL/NewPublicationPanel.tsx@@ -5,7 +5,7 @@ import { toast } from 'sonner'import { z } from 'zod'import { useParams } from 'common'-import { useCreatePublicationMutation } from 'data/etl/create-publication-mutation'+import { useCreatePublicationMutation } from 'data/etl/publication-create-mutation'import { useReplicationTablesQuery } from 'data/etl/tables-query'import {Button,@@ -139,7 +139,7 @@ export const NewPublicationPanel = ({ visible, sourceId, onClose }: NewPublicati</MultiSelector.Trigger><MultiSelector.Content><MultiSelector.List>- {tables?.tables.map((table) => (+ {tables?.map((table) => (<MultiSelector.Itemkey={`${table.schema}.${table.name}`}value={`${table.schema}.${table.name}`}diff --git a/apps/studio/components/interfaces/Storage/AnalyticsBuckets/AnalyticsBucketDetails/ConnectTablesDialog.tsx b/apps/studio/components/interfaces/Storage/AnalyticsBuckets/AnalyticsBucketDetails/ConnectTablesDialog.tsxindex 95ef50311d9..1ec27e28f3e 100644--- a/apps/studio/components/interfaces/Storage/AnalyticsBuckets/AnalyticsBucketDetails/ConnectTablesDialog.tsx+++ b/apps/studio/components/interfaces/Storage/AnalyticsBuckets/AnalyticsBucketDetails/ConnectTablesDialog.tsx@@ -1,29 +1,31 @@import { zodResolver } from '@hookform/resolvers/zod'+import { AnimatePresence, motion } from 'framer-motion'import { snakeCase } from 'lodash'-import { Plus } from 'lucide-react'-import { useState } from 'react'+import { Loader2, Plus } from 'lucide-react'+import { useEffect, useMemo, useState } from 'react'import { SubmitHandler, useForm } from 'react-hook-form'import { toast } from 'sonner'import z from 'zod'-import { useParams } from 'common'+import { useFlag, useParams } from 'common'import { convertKVStringArrayToJson } from 'components/interfaces/Integrations/Wrappers/Wrappers.utils'-import { getCatalogURI } from 'components/interfaces/Storage/StorageSettings/StorageSettings.utils'import { ButtonTooltip } from 'components/ui/ButtonTooltip'import { getKeys, useAPIKeysQuery } from 'data/api-keys/api-keys-query'import { useProjectSettingsV2Query } from 'data/config/project-settings-v2-query'import { useCreateDestinationPipelineMutation } from 'data/etl/create-destination-pipeline-mutation'-import { useCreatePublicationMutation } from 'data/etl/create-publication-mutation'+import { useCreateTenantSourceMutation } from 'data/etl/create-tenant-source-mutation'+import { useCreatePublicationMutation } from 'data/etl/publication-create-mutation'+import { useUpdatePublicationMutation } from 'data/etl/publication-update-mutation'import { useReplicationSourcesQuery } from 'data/etl/sources-query'import { useStartPipelineMutation } from 'data/etl/start-pipeline-mutation'-import { useIcebergNamespaceCreateMutation } from 'data/storage/iceberg-namespace-create-mutation'-import { useTablesQuery } from 'data/tables/tables-query'+import { useReplicationTablesQuery } from 'data/etl/tables-query'import { getDecryptedValues } from 'data/vault/vault-secret-decrypted-value-query'import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'import {Button,Dialog,DialogContent,+ DialogDescription,DialogFooter,DialogHeader,DialogSection,@@ -33,10 +35,13 @@ import {Form_Shadcn_,FormControl_Shadcn_,FormField_Shadcn_,+ Progress,} from 'ui'+import { Admonition } from 'ui-patterns'import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'import { MultiSelector } from 'ui-patterns/multi-select'import { getAnalyticsBucketPublicationName } from './AnalyticsBucketDetails.utils'+import { useAnalyticsBucketAssociatedEntities } from './useAnalyticsBucketAssociatedEntities'import { useAnalyticsBucketWrapperInstance } from './useAnalyticsBucketWrapperInstance'/**@@ -52,24 +57,100 @@ import { useAnalyticsBucketWrapperInstance } from './useAnalyticsBucketWrapperIn* - Error handling due to multiple async processes*/+const formId = 'connect-tables-form'const FormSchema = z.object({- tables: z.array(z.string()).min(1, 'At least one table is required'),+ tables: z.array(z.string()).min(1, 'Select at least one table'),})-const formId = 'connect-tables-form'-const isEnabled = false // Kill switch if we wanna hold off supporting connecting tables-type ConnectTablesForm = z.infer<typeof FormSchema>-export const ConnectTablesDialog = ({ bucketId }: { bucketId?: string }) => {+enum PROGRESS_STAGE {+ CREATE_PUBLICATION = 'CREATE_PUBLICATION',+ CREATE_PIPELINE = 'CREATE_PIPELINE',+ START_PIPELINE = 'START_PIPELINE',+ UPDATE_PUBLICATION = 'CREATE_REPLICATION',+}++const PROGRESS_INDICATORS = {+ CREATE: [+ {+ step: PROGRESS_STAGE.CREATE_PUBLICATION,+ getDescription: (numTables: number) =>+ `Creating replication publication with ${numTables} table${numTables > 1 ? 's' : ''}...`,+ },+ { step: PROGRESS_STAGE.CREATE_PIPELINE, description: `Creating replication pipeline` },+ { step: PROGRESS_STAGE.START_PIPELINE, description: `Starting replication pipeline` },+ ],+ UPDATE: [+ {+ step: PROGRESS_STAGE.UPDATE_PUBLICATION,+ getDescription: (numTables: number) =>+ `Updating replication publication with ${numTables} table${numTables > 1 ? 's' : ''}...`,+ },+ { step: PROGRESS_STAGE.START_PIPELINE, description: 'Restarting replication pipeline...' },+ ],+}++interface ConnectTablesDialogProps {+ onSuccessConnectTables: (tables: { schema: string; name: string }[]) => void+}++export const ConnectTablesDialog = ({ onSuccessConnectTables }: ConnectTablesDialogProps) => {+ const { ref: projectRef, bucketId } = useParams()+ const [visible, setVisible] = useState(false)++ const isEnabled = useFlag('storageAnalyticsVector') // Kill switch if we wanna hold off supporting connecting tables++ const { sourceId, pipeline, publication } = useAnalyticsBucketAssociatedEntities({+ projectRef,+ bucketId,+ })+ const isEditingExistingPublication = !!publication && !!pipeline++ return (+ <Dialog open={visible} onOpenChange={setVisible}>+ <DialogTrigger asChild>+ <ButtonTooltip+ disabled={!isEnabled}+ size="tiny"+ type="primary"+ icon={<Plus />}+ onClick={() => setVisible(true)}+ tooltip={{ content: { side: 'bottom', text: !isEnabled ? 'Coming soon' : undefined } }}+ >+ {isEditingExistingPublication ? 'Add tables' : 'Connect tables'}+ </ButtonTooltip>+ </DialogTrigger>++ {!sourceId ? (+ <EnableReplicationDialogContent onClose={() => setVisible(false)} />+ ) : (+ <ConnectTablesDialogContent+ visible={visible}+ onClose={() => setVisible(false)}+ onSuccessConnectTables={onSuccessConnectTables}+ />+ )}+ </Dialog>+ )+}++export const ConnectTablesDialogContent = ({+ visible,+ onClose,+ onSuccessConnectTables,+}: ConnectTablesDialogProps & { visible: boolean; onClose: () => void }) => {+ const { ref: projectRef, bucketId } = useParams()+ const { data: project } = useSelectedProjectQuery()++ const [isConnecting, setIsConnecting] = useState(false)+ const [connectingStep, setConnectingStep] = useState<PROGRESS_STAGE>()+const form = useForm<ConnectTablesForm>({resolver: zodResolver(FormSchema),defaultValues: { tables: [] },})-- const [visible, setVisible] = useState(false)- const { ref: projectRef } = useParams()- const { data: project } = useSelectedProjectQuery()+ const { tables: selectedTables } = form.watch()const { data: wrapperInstance } = useAnalyticsBucketWrapperInstance({ bucketId: bucketId })const wrapperValues = convertKVStringArrayToJson(wrapperInstance?.server_options ?? [])@@ -78,52 +159,54 @@ export const ConnectTablesDialog = ({ bucketId }: { bucketId?: string }) => {const { data: apiKeys } = useAPIKeysQuery({ projectRef, reveal: true })const { serviceKey } = getKeys(apiKeys)- const { data: tables } = useTablesQuery({+ const { sourceId, pipeline, publication } = useAnalyticsBucketAssociatedEntities({projectRef,- connectionString: project?.connectionString,- includeColumns: false,+ bucketId,})+ const isEditingExistingPublication = !!publication && !!pipeline- const { data: sourcesData } = useReplicationSourcesQuery({ projectRef })- const sourceId = sourcesData?.sources.find((s) => s.name === projectRef)?.id-- const { mutateAsync: createNamespace, isLoading: isCreatingNamespace } =- useIcebergNamespaceCreateMutation()-- const { mutateAsync: createPublication, isLoading: isCreatingPublication } =- useCreatePublicationMutation()-- const { mutateAsync: createDestinationPipeline, isLoading: creatingDestinationPipeline } =- useCreateDestinationPipelineMutation({- onSuccess: () => {},- })+ const { data: tables } = useReplicationTablesQuery({ projectRef, sourceId })+ const { mutateAsync: createPublication } = useCreatePublicationMutation()+ const { mutateAsync: updatePublication } = useUpdatePublicationMutation()+ const { mutateAsync: createDestinationPipeline } = useCreateDestinationPipelineMutation()const { mutateAsync: startPipeline } = useStartPipelineMutation()- const isConnecting = isCreatingNamespace || creatingDestinationPipeline || isCreatingPublication-- const onSubmit: SubmitHandler<ConnectTablesForm> = async (values) => {- // [Joshen] Currently creates the destination for the analytics bucket here- // Which also involves creating a namespace + publication- // Publication name is automatically generated as {bucketId}_publication- // Destination name is automatically generated as {bucketId}_destination+ const progressIndicator = useMemo(+ () => (isEditingExistingPublication ? PROGRESS_INDICATORS.UPDATE : PROGRESS_INDICATORS.CREATE),+ // [Joshen] This is to prevent the progressIndicator from flipping to UPDATE in the middle of CREATE+ // since the publication and pipelines are getting created in the middle of CREATE+ // eslint-disable-next-line react-hooks/exhaustive-deps+ [isConnecting]+ )+ const totalProgressSteps = progressIndicator.length+ const currentStep = progressIndicator.findIndex((x) => x.step === connectingStep) + 1+ const progressDescription = progressIndicator.find((x) => x.step === connectingStep)+ const onSubmitNewPublication: SubmitHandler<ConnectTablesForm> = async (values) => {if (!projectRef) return console.error('Project ref is required')- if (!sourceId) return toast.error('Source ID is required')if (!bucketId) return toast.error('Bucket ID is required')+ if (!sourceId) return toast.error('Replication has not been enabled for your project')try {+ setIsConnecting(true)++ // Step 1: Create publication+ setConnectingStep(PROGRESS_STAGE.CREATE_PUBLICATION)const publicationName = getAnalyticsBucketPublicationName(bucketId)+ const publicationTables = values.tables.map((table) => {+ const [schema, name] = table.split('.')+ return { schema, name }+ })await createPublication({projectRef,sourceId,name: publicationName,- tables: values.tables.map((table) => {- const [schema, name] = table.split('.')- return { schema, name }- }),+ tables: publicationTables,})+ // Step 2: Create destination pipeline+ setConnectingStep(PROGRESS_STAGE.CREATE_PIPELINE)const keysToDecrypt = Object.entries(wrapperValues).filter(([name]) =>['vault_aws_access_key_id', 'vault_aws_secret_access_key'].includes(name)@@ -141,29 +224,15 @@ export const ConnectTablesDialog = ({ bucketId }: { bucketId?: string }) => {const s3SecretAccessKey = decryptedValues[wrapperValues['vault_aws_secret_access_key']]const s3Region = projectSettings?.region ?? ''- const protocol = projectSettings?.app_config?.protocol ?? 'https'- const endpoint =- projectSettings?.app_config?.storage_endpoint || projectSettings?.app_config?.endpoint- const catalogUri = getCatalogURI(project?.ref ?? '', protocol, endpoint)- const namespace = `${bucketId}_namespace`- await createNamespace({- catalogUri,- warehouse: warehouseName,- token: catalogToken,- namespace,- })-const icebergConfiguration = {projectRef,warehouseName,- namespace,catalogToken,s3AccessKeyId,s3SecretAccessKey,s3Region,}const destinationName = `${snakeCase(bucketId)}_destination`-const { pipeline_id: pipelineId } = await createDestinationPipeline({projectRef,destinationName,@@ -172,104 +241,241 @@ export const ConnectTablesDialog = ({ bucketId }: { bucketId?: string }) => {pipelineConfig: { publicationName },})- // Pipeline can start behind the scenes, don't need to await- startPipeline({ projectRef, pipelineId })+ // Step 3: Start the destination pipeline+ setConnectingStep(PROGRESS_STAGE.START_PIPELINE)+ await startPipeline({ projectRef, pipelineId })++ onSuccessConnectTables?.(publicationTables)toast.success(`Connected ${values.tables.length} tables to Analytics bucket!`)form.reset()- setVisible(false)+ onClose()} catch (error: any) {// [Joshen] JFYI there's several async processes here so if something goes wrong midway - we need to figure out how to roll back cleanly// e.g publication gets created, but namespace creation fails -> should the old publication get deleted?// Another question is probably whether all of these step by step logic should be at the API level instead of client level// Same issue present within DestinationPanel - it's alright for now as we do an Alpha but this needs to be addressed before GAtoast.error(`Failed to connect tables: ${error.message}`)+ } finally {+ setIsConnecting(false)+ setConnectingStep(undefined)}}- const handleClose = () => {- form.reset()- setVisible(false)+ const onSubmitUpdatePublication: SubmitHandler<ConnectTablesForm> = async (values) => {+ if (!projectRef) return console.error('Project ref is required')+ if (!sourceId) return toast.error('Replication has not been enabled on this project')+ if (!bucketId) return toast.error('Bucket ID is required')+ if (!publication) return toast.error('Unable to find existing publication')+ if (!pipeline) return toast.error('Unable to find existing pipeline')++ try {+ setIsConnecting(true)++ const tablesToBeAdded = values.tables.map((table) => {+ const [schema, name] = table.split('.')+ return { schema, name }+ })+ setConnectingStep(PROGRESS_STAGE.UPDATE_PUBLICATION)+ const publicationTables = publication.tables.concat(tablesToBeAdded)+ await updatePublication({+ projectRef,+ sourceId,+ publicationName: publication.name,+ tables: publicationTables,+ })++ setConnectingStep(PROGRESS_STAGE.START_PIPELINE)+ await startPipeline({ projectRef, pipelineId: pipeline.id })++ onSuccessConnectTables?.(tablesToBeAdded)+ toast.success('Successfully updated connected tables! Pipeline is being restarted')+ onClose()+ } catch (error: any) {+ toast.error(`Failed to update tables: ${error.message}`)+ } finally {+ setIsConnecting(false)+ setConnectingStep(undefined)+ }}- return (- <Dialog- open={visible}- onOpenChange={(open) => {- if (!open) handleClose()- }}- >- <DialogTrigger asChild>- <ButtonTooltip- disabled={!isEnabled}- size="tiny"- type="primary"- icon={<Plus size={14} />}- onClick={() => setVisible(true)}- tooltip={{ content: { side: 'bottom', text: !isEnabled ? 'Coming soon' : undefined } }}- >- Connect tables- </ButtonTooltip>- </DialogTrigger>+ const onSubmit: SubmitHandler<ConnectTablesForm> = async (values) => {+ if (isEditingExistingPublication) {+ onSubmitUpdatePublication(values)+ } else {+ onSubmitNewPublication(values)+ }+ }- <DialogContent>- <DialogHeader>- <DialogTitle>Connect tables</DialogTitle>- </DialogHeader>+ useEffect(() => {+ form.reset()+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [visible])- <DialogSectionSeparator />+ return (+ <DialogContent>+ <DialogHeader>+ <DialogTitle>+ {isEditingExistingPublication ? 'Connect more tables' : 'Connect tables'}+ </DialogTitle>+ </DialogHeader>- <Form_Shadcn_ {...form}>- <form id={formId} onSubmit={form.handleSubmit(onSubmit)}>- <DialogSection className="flex flex-col gap-y-4">- <p className="text-sm">- Select the database tables to send data from. A destination analytics table will be- created for each, and data will replicate automatically.- </p>- </DialogSection>- <DialogSectionSeparator />- <DialogSection className="overflow-visible">- <FormField_Shadcn_- control={form.control}- name="tables"- render={({ field }) => (- <FormItemLayout label="Tables">- <FormControl_Shadcn_>- <MultiSelector- values={field.value}- onValuesChange={field.onChange}- disabled={isConnecting}- >- <MultiSelector.Trigger label="Select tables..." badgeLimit="wrap" />- <MultiSelector.Content>- <MultiSelector.List>- {tables?.map((table) => (+ <DialogSectionSeparator />++ <Form_Shadcn_ {...form}>+ <form id={formId} onSubmit={form.handleSubmit(onSubmit)}>+ <DialogSection className="flex flex-col gap-y-4">+ <p className="text-sm">+ Select the database tables to send data from. A destination analytics table will be+ created for each, and data will replicate automatically.+ </p>+ </DialogSection>+ <DialogSectionSeparator />+ <DialogSection className="overflow-visible">+ <FormField_Shadcn_+ control={form.control}+ name="tables"+ render={({ field }) => (+ <FormItemLayout label="Tables">+ <FormControl_Shadcn_>+ <MultiSelector+ values={field.value}+ onValuesChange={field.onChange}+ disabled={isConnecting}+ >+ <MultiSelector.Trigger+ deletableBadge+ badgeLimit="wrap"+ mode="inline-combobox"+ label="Select tables..."+ />+ <MultiSelector.Content>+ <MultiSelector.List>+ {tables?.map((table) => {+ const alreadyConnected = (publication?.tables ?? []).some(+ (x) => x.schema === table.schema && x.name === table.name+ )+ return (<MultiSelector.Item+ disabled={alreadyConnected}+ className="[&>div]:flex [&>div]:items-center [&>div]:justify-between"key={`${table.schema}.${table.name}`}value={`${table.schema}.${table.name}`}>- {`${table.schema}.${table.name}`}+ <span>{`${table.schema}.${table.name}`}</span>+ {alreadyConnected && <span>Connected to analytics bucket</span>}</MultiSelector.Item>- ))}- </MultiSelector.List>- </MultiSelector.Content>- </MultiSelector>- </FormControl_Shadcn_>- </FormItemLayout>- )}- />+ )+ })}+ </MultiSelector.List>+ </MultiSelector.Content>+ </MultiSelector>+ </FormControl_Shadcn_>+ </FormItemLayout>+ )}+ />+ </DialogSection>+ </form>+ </Form_Shadcn_>++ <AnimatePresence mode="wait">+ {isConnecting && !!progressDescription && (+ <motion.div+ initial={{ height: 0, opacity: 0 }}+ animate={{ height: 'auto', opacity: 1 }}+ exit={{ height: 0, opacity: 0 }}+ transition={{ duration: 0.2, ease: 'easeOut' }}+ >+ <DialogSectionSeparator />+ <DialogSection>+ <div className="flex items-center gap-x-2 mb-2">+ <p className="text-sm text-foreground-light">+ {'getDescription' in progressDescription+ ? progressDescription.getDescription?.(selectedTables.length)+ : progressDescription.description}+ </p>+ <Loader2 size={14} className="animate-spin" />+ </div>+ <Progress value={(currentStep / (totalProgressSteps + 1)) * 100} /></DialogSection>- </form>- </Form_Shadcn_>+ </motion.div>+ )}+ </AnimatePresence>- <DialogFooter>- <Button type="default" disabled={isConnecting} onClick={() => setVisible(false)}>- Cancel- </Button>- <Button form={formId} htmlType="submit" loading={isConnecting} disabled={isConnecting}>- Connect+ <DialogFooter>+ <Button type="default" disabled={isConnecting} onClick={onClose}>+ Cancel+ </Button>+ <Button form={formId} htmlType="submit" disabled={isConnecting}>+ Connect+ </Button>+ </DialogFooter>+ </DialogContent>+ )+}++const EnableReplicationDialogContent = ({ onClose }: { onClose: () => void }) => {+ const { ref: projectRef } = useParams()+ const enablePgReplicate = useFlag('enablePgReplicate')+ const { error } = useReplicationSourcesQuery({ projectRef })+ const noAccessToReplication =+ !enablePgReplicate || error?.message.includes('feature flag is required')++ const { mutateAsync: createTenantSource, isLoading: creatingTenantSource } =+ useCreateTenantSourceMutation()++ const onEnableReplication = async () => {+ if (!projectRef) return console.error('Project ref is required')+ await createTenantSource({ projectRef })+ }++ return (+ <DialogContent>+ <DialogHeader>+ <DialogTitle>Database replication needs to be enabled</DialogTitle>+ <DialogDescription>+ Replication is used to sync data from your Postgres tables+ </DialogDescription>+ </DialogHeader>+ <DialogSectionSeparator />+ <DialogSection className="flex flex-col gap-y-2 !p-0">+ <Admonition+ type="warning"+ className="rounded-none border-0 mb-0"+ title={+ noAccessToReplication+ ? 'Replication is currently unavailable for your project'+ : 'Replication is currently in Alpha'+ }+ >+ {noAccessToReplication ? (+ <p className="text-sm !leading-normal">+ Access to database replication is currently not available yet for public use. If+ you're interested, do reach out to us via support!+ </p>+ ) : (+ <>+ <p className="text-sm !leading-normal">+ This feature is in active development and may change as we gather feedback.+ Availability and behavior can evolve while in Alpha.+ </p>+ <p className="text-sm !leading-normal">+ Pricing has not been finalized yet. You can enable replication now; we’ll announce+ pricing later and notify you before any charges apply.+ </p>+ </>+ )}+ </Admonition>+ </DialogSection>+ <DialogFooter>+ <Button type="default" disabled={creatingTenantSource} onClick={() => onClose()}>+ {noAccessToReplication ? 'Understood' : 'Cancel'}+ </Button>+ {!noAccessToReplication && (+ <Button type="primary" loading={creatingTenantSource} onClick={onEnableReplication}>+ Enable replication</Button>- </DialogFooter>- </DialogContent>- </Dialog>+ )}+ </DialogFooter>+ </DialogContent>)}diff --git a/apps/studio/components/interfaces/Storage/AnalyticsBuckets/AnalyticsBucketDetails/NamespaceRow.tsx b/apps/studio/components/interfaces/Storage/AnalyticsBuckets/AnalyticsBucketDetails/NamespaceRow.tsxdeleted file mode 100644index a64264be2b1..00000000000--- a/apps/studio/components/interfaces/Storage/AnalyticsBuckets/AnalyticsBucketDetails/NamespaceRow.tsx+++ /dev/null@@ -1,130 +0,0 @@-import { RefreshCw, SquareArrowOutUpRight } from 'lucide-react'-import { useMemo, useState } from 'react'--import type { WrapperMeta } from 'components/interfaces/Integrations/Wrappers/Wrappers.types'-import { FormattedWrapperTable } from 'components/interfaces/Integrations/Wrappers/Wrappers.utils'-import { ImportForeignSchemaDialog } from 'components/interfaces/Storage/ImportForeignSchemaDialog'-import { ButtonTooltip } from 'components/ui/ButtonTooltip'-import { useFDWImportForeignSchemaMutation } from 'data/fdw/fdw-import-foreign-schema-mutation'-import { FDW } from 'data/fdw/fdws-query'-import { useIcebergNamespaceTablesQuery } from 'data/storage/iceberg-namespace-tables-query'-import { BASE_PATH } from 'lib/constants'-import { Button, cn, TableCell, TableRow } from 'ui'-import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'--type NamespaceRowProps = {- bucketName: string- namespace: string- schema: string- tables: (FormattedWrapperTable & { id: number })[]- token: string- wrapperInstance: FDW- wrapperValues: Record<string, string>- wrapperMeta: WrapperMeta-}--export const NamespaceRow = ({- bucketName,- namespace,- schema,- tables,- token,- wrapperInstance,- wrapperValues,- wrapperMeta,-}: NamespaceRowProps) => {- const { data: project } = useSelectedProjectQuery()- const [importForeignSchemaShown, setImportForeignSchemaShown] = useState(false)-- const { data: tablesData, isLoading: isLoadingNamespaceTables } = useIcebergNamespaceTablesQuery(- {- catalogUri: wrapperValues.catalog_uri,- warehouse: wrapperValues.warehouse,- token: token,- namespace: namespace,- },- { enabled: !!token }- )-- const { mutateAsync: importForeignSchema, isLoading: isImportingForeignSchema } =- useFDWImportForeignSchemaMutation()-- const rescanNamespace = async () => {- await importForeignSchema({- projectRef: project?.ref,- connectionString: project?.connectionString,- serverName: wrapperInstance.server_name,- sourceSchema: namespace,- targetSchema: schema,- })- }-- const missingTables = useMemo(() => {- return (tablesData || []).filter(- (t) => !tables.find((table) => table.table.split('.')[1] === t)- )- }, [tablesData, tables])-- let scanTooltip = useMemo(() => {- if (isImportingForeignSchema) return 'Scanning for new tables...'- if (isLoadingNamespaceTables) return 'Loading tables...'- if (missingTables.length > 0) return `Found ${missingTables.length} new tables`- if (tables.length === 0) return 'No tables found'- return 'All tables are up to date'- }, [isImportingForeignSchema, isLoadingNamespaceTables, missingTables.length, tables.length])-- return (- <TableRow key={namespace}>- <TableCell>{namespace}</TableCell>- <TableCell className={cn(!schema ? 'text-foreground-lighter' : '')}>- {schema ?? 'No schema'}- </TableCell>- <TableCell>- {tablesData ? `${tables.length}/${tablesData.length} connected tables` : ``}- </TableCell>- <TableCell className="text-right">- <div className="flex gap-2 justify-end">- <ButtonTooltip- type={missingTables.length > 0 ? 'primary' : 'default'}- icon={<RefreshCw className="h-3 w-3" />}- loading={isImportingForeignSchema || isLoadingNamespaceTables}- onClick={() => (schema ? rescanNamespace() : setImportForeignSchemaShown(true))}- disabled={missingTables.length === 0}- tooltip={{ content: { text: scanTooltip } }}- >- Sync- </ButtonTooltip>- {schema ? (- <Button asChild type="default" icon={<SquareArrowOutUpRight />}>- <a- target="_blank"- rel="noreferrer"- href={`${BASE_PATH}/project/${project?.ref}/editor?schema=${schema}`}- >- Open in Table Editor- </a>- </Button>- ) : (- <ButtonTooltip- type="default"- icon={<SquareArrowOutUpRight />}- disabled- tooltip={{- content: { text: 'There are no tables connected.' },- }}- >- Open in Table Editor- </ButtonTooltip>- )}- </div>- </TableCell>- <ImportForeignSchemaDialog- bucketName={bucketName}- namespace={namespace}- wrapperMeta={wrapperMeta}- visible={importForeignSchemaShown}- onClose={() => setImportForeignSchemaShown(false)}- />- </TableRow>- )-}diff --git a/apps/studio/components/interfaces/Storage/AnalyticsBuckets/AnalyticsBucketDetails/NamespaceWithTables/TableRowComponent.tsx b/apps/studio/components/interfaces/Storage/AnalyticsBuckets/AnalyticsBucketDetails/NamespaceWithTables/TableRowComponent.tsxnew file mode 100644index 00000000000..6a1f43de7af--- /dev/null+++ b/apps/studio/components/interfaces/Storage/AnalyticsBuckets/AnalyticsBucketDetails/NamespaceWithTables/TableRowComponent.tsx@@ -0,0 +1,240 @@+import { snakeCase } from 'lodash'+import { MoreVertical, Pause, Play } from 'lucide-react'+import Link from 'next/link'+import { useState } from 'react'+import { toast } from 'sonner'++import { useParams } from 'common'+import { useUpdatePublicationMutation } from 'data/etl/publication-update-mutation'+import { useStartPipelineMutation } from 'data/etl/start-pipeline-mutation'+import { useReplicationTablesQuery } from 'data/etl/tables-query'+import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'+import { SqlEditor } from 'icons'+import {+ Button,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+ TableCell,+ TableRow,+} from 'ui'+import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'+import { useAnalyticsBucketAssociatedEntities } from '../useAnalyticsBucketAssociatedEntities'++export const TableRowComponent = ({+ index,+ table,+ schema,+ isLoading,+}: {+ index: number+ table: { id: number; name: string; isConnected: boolean }+ schema: string+ isLoading?: boolean+}) => {+ const { ref: projectRef, bucketId } = useParams()+ const { data: project } = useSelectedProjectQuery()++ const [showStopReplicationModal, setShowStopReplicationModal] = useState(false)+ const [showStartReplicationModal, setShowStartReplicationModal] = useState(false)+ const [isUpdatingReplication, setIsUpdatingReplication] = useState(false)++ const { sourceId, publication, pipeline } = useAnalyticsBucketAssociatedEntities({+ projectRef,+ bucketId,+ })++ const { data: tables } = useReplicationTablesQuery({ projectRef, sourceId })++ const { mutateAsync: updatePublication } = useUpdatePublicationMutation()+ const { mutateAsync: startPipeline } = useStartPipelineMutation()++ const isReplicating = publication?.tables.find(+ (x) => table.name === snakeCase(`${x.schema}.${x.name}_changelog`)+ )++ const onConfirmStopReplication = async () => {+ if (!projectRef) return console.error('Project ref is required')+ if (!bucketId) return console.error('Bucket ID is required')+ if (!sourceId) return toast.error('Source ID is required')+ if (!publication) return toast.error('Unable to find existing publication')+ if (!pipeline) return toast.error('Unable to find existing pipeline')++ try {+ setIsUpdatingReplication(true)+ // [Joshen ALPHA] Assumption here is that all the namespace tables have _changelog as suffix+ // May need to update if that assumption falls short (e.g for those dealing with iceberg APIs directly)+ const updatedTables = publication.tables.filter(+ (x) => table.name !== snakeCase(`${x.schema}.${x.name}_changelog`)+ )+ await updatePublication({+ projectRef,+ sourceId,+ publicationName: publication.name,+ tables: updatedTables,+ })+ await startPipeline({ projectRef, pipelineId: pipeline.id })+ setShowStopReplicationModal(false)+ toast.success('Successfully stopped replication for table! Pipeline is being restarted.')+ } catch (error: any) {+ toast.error(`Failed to stop replication for table: ${error.message}`)+ } finally {+ setIsUpdatingReplication(false)+ }+ }++ const onConfirmStartReplication = async () => {+ if (!projectRef) return console.error('Project ref is required')+ if (!bucketId) return console.error('Bucket ID is required')+ if (!sourceId) return toast.error('Source ID is required')+ if (!publication) return toast.error('Unable to find existing publication')+ if (!pipeline) return toast.error('Unable to find existing pipeline')++ // [Joshen ALPHA] This has potential to be flaky - we should see how we can get the table name and schema better+ const pgTable = tables?.find((t) => snakeCase(`${t.schema}.${t.name}_changelog`) === table.name)+ if (!pgTable) return toast.error('Unable to find corresponding Postgres table')++ try {+ setIsUpdatingReplication(true)+ const updatedTables = publication.tables.concat([+ { schema: pgTable.schema, name: pgTable.name },+ ])+ await updatePublication({+ projectRef,+ sourceId,+ publicationName: publication.name,+ tables: updatedTables,+ })+ await startPipeline({ projectRef, pipelineId: pipeline.id })+ setShowStartReplicationModal(false)+ toast.success('Successfully stopped replication for table! Pipeline is being restarted.')+ } catch (error: any) {+ toast.error(`Failed to stop replication for table: ${error.message}`)+ } finally {+ setIsUpdatingReplication(false)+ }+ }++ return (+ <>+ <TableRow>+ <TableCell className="min-w-[120px]">{table.name}</TableCell>+ {!!publication && (+ <TableCell colSpan={table.isConnected ? 1 : 2} className="min-w-[150px]">+ <div className="flex flex-row items-center text-foregroung-lighter">+ <div className="relative mr-2 align-middle w-3 h-3">+ <span+ className={`absolute inset-0 rounded-full ${+ isReplicating+ ? isLoading+ ? 'bg-brand/20 animate-ping'+ : 'bg-brand/20 animate-ping'+ : isLoading+ ? 'bg-selection/20 animate-ping'+ : 'hidden'+ }`}+ style={{+ animationDelay: `${1 + index * 0.15}s`,+ animationDuration: '2s',+ }}+ />+ <span+ className={`absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 inline-block w-2 h-2 rounded-full ${+ isReplicating ? 'bg-brand' : 'bg-selection'+ }`}+ />+ </div>+ <span className="text-foreground-lighter">+ {isLoading && !isReplicating+ ? '-'+ : isReplicating+ ? 'Replicating'+ : 'Not replicating'}+ </span>+ </div>+ </TableCell>+ )}++ {table.isConnected && (+ <TableCell className="text-right flex flex-row items-center gap-x-2 justify-end">+ <>+ <Button asChild type="default" size="tiny">+ <Link href={`/project/${project?.ref}/editor/${table.id}?schema=${schema}`}>+ <p>View table</p>+ </Link>+ </Button>+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button type="default" className="px-1" icon={<MoreVertical />} />+ </DropdownMenuTrigger>++ <DropdownMenuContent side="bottom" align="end" className="w-fit min-w-[180px]">+ <DropdownMenuItem asChild className="flex items-center gap-x-2">+ <Link+ href={`/project/${project?.ref}/sql/new?content=${encodeURIComponent(`select * from ${schema}.${table.name};`)}`}+ >+ <SqlEditor size={12} className="text-foreground-lighter" />+ <p>Query in SQL Editor</p>+ </Link>+ </DropdownMenuItem>++ <DropdownMenuSeparator />++ {isReplicating ? (+ <DropdownMenuItem+ className="flex items-center gap-x-2"+ onClick={() => setShowStopReplicationModal(true)}+ >+ <Pause size={12} className="text-foreground-lighter" />+ <p>Stop replication</p>+ </DropdownMenuItem>+ ) : (+ <DropdownMenuItem+ className="flex items-center gap-x-2"+ onClick={() => setShowStartReplicationModal(true)}+ >+ <Play size={12} className="text-foreground-lighter" />+ <p>Start replication</p>+ </DropdownMenuItem>+ )}+ </DropdownMenuContent>+ </DropdownMenu>+ </>+ </TableCell>+ )}+ </TableRow>+ <ConfirmationModal+ size="medium"+ variant="warning"+ visible={showStopReplicationModal}+ loading={isUpdatingReplication}+ title="Confirm to stop replication for table"+ confirmLabel="Stop replication"+ onCancel={() => setShowStopReplicationModal(false)}+ onConfirm={() => onConfirmStopReplication()}+ >+ <p className="text-sm text-foreground-light">+ Data within the "{table.name}" table will stop replicating. However do note that,+ restarting replication on the table will clear and re-sync all data in it. Are you sure?+ </p>+ </ConfirmationModal>+ <ConfirmationModal+ size="medium"+ variant="warning"+ visible={showStartReplicationModal}+ loading={isUpdatingReplication}+ title="Confirm to start replication for table"+ confirmLabel="Start replication"+ onCancel={() => setShowStartReplicationModal(false)}+ onConfirm={() => onConfirmStartReplication()}+ >+ <p className="text-sm text-foreground-light">+ Restarting replication on the "{table.name}" table will clear and re-sync all data in it.+ Are you sure?+ </p>+ </ConfirmationModal>+ </>+ )+}diff --git a/apps/studio/components/interfaces/Storage/AnalyticsBuckets/AnalyticsBucketDetails/NamespaceWithTables.tsx b/apps/studio/components/interfaces/Storage/AnalyticsBuckets/AnalyticsBucketDetails/NamespaceWithTables/index.tsxsimilarity index 52%rename from apps/studio/components/interfaces/Storage/AnalyticsBuckets/AnalyticsBucketDetails/NamespaceWithTables.tsxrename to apps/studio/components/interfaces/Storage/AnalyticsBuckets/AnalyticsBucketDetails/NamespaceWithTables/index.tsxindex 0d7e433b598..e8a6637537d 100644--- a/apps/studio/components/interfaces/Storage/AnalyticsBuckets/AnalyticsBucketDetails/NamespaceWithTables.tsx+++ b/apps/studio/components/interfaces/Storage/AnalyticsBuckets/AnalyticsBucketDetails/NamespaceWithTables/index.tsx@@ -1,7 +1,7 @@-import { ChevronRight, Code, Info, MoreVertical, Plus, Replace, Trash2 } from 'lucide-react'-import Link from 'next/link'+import { ChevronRight, Info, Loader2, Plus, RefreshCw } from 'lucide-react'import { useMemo, useState } from 'react'+import { useParams } from 'common'import type { WrapperMeta } from 'components/interfaces/Integrations/Wrappers/Wrappers.types'import { FormattedWrapperTable } from 'components/interfaces/Integrations/Wrappers/Wrappers.utils'import { ImportForeignSchemaDialog } from 'components/interfaces/Storage/ImportForeignSchemaDialog'@@ -14,10 +14,7 @@ import {Card,CardHeader,CardTitle,- DropdownMenu,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuTrigger,+ LoadingLine,Table,TableBody,TableCell,@@ -26,9 +23,10 @@ import {TableRow,Tooltip,TooltipContent,- TooltipProvider,TooltipTrigger,} from 'ui'+import { useAnalyticsBucketAssociatedEntities } from '../useAnalyticsBucketAssociatedEntities'+import { TableRowComponent } from './TableRowComponent'type NamespaceWithTablesProps = {bucketName?: string@@ -40,108 +38,9 @@ type NamespaceWithTablesProps = {wrapperInstance: FDWwrapperValues: Record<string, string>wrapperMeta: WrapperMeta-}--// Component for individual table rows within a namespace-const TableRowComponent = ({- index,- tableName,- isConnected,- isLoading,-}: {- index: number- tableName: string- isConnected: boolean- isLoading?: boolean-}) => {- const { data: project } = useSelectedProjectQuery()-- const handleQueryTable = () => {- // TODO: Implement query table functionality- console.log('Query table:', tableName)- }-- const handleDeleteTable = () => {- // TODO: Implement delete table functionality- console.log('Delete table:', tableName)- }-- return (- <TableRow>- <TableCell className="min-w-[120px]">{tableName}</TableCell>- <TableCell colSpan={isConnected ? 1 : 2} className="min-w-[150px]">- <div className="flex flex-row items-center text-foregroung-lighter">- <div className="relative mr-2 align-middle w-3 h-3">- {/* Outer faded dot with pulsing background */}- <span- className={`absolute inset-0 rounded-full ${- isConnected- ? isLoading- ? 'bg-brand/20 animate-ping'- : 'bg-brand/20 animate-ping'- : isLoading- ? 'bg-warning-500/20 animate-ping'- : 'hidden'- }`}- style={{- // Stagger the animation delay for each table- animationDelay: `${1 + index * 0.15}s`,- // Slow the animation- animationDuration: '2s',- }}- />- {/* Inner colored dot */}- <span- className={`absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 inline-block w-2 h-2 rounded-full ${- isConnected ? 'bg-brand' : 'bg-warning-500'- }`}- />- </div>- <span className="text-foreground-lighter">- {isLoading && !isConnected- ? 'Connecting...'- : isConnected- ? 'Connected'- : 'Not connected'}- </span>- </div>- </TableCell>- {isConnected && (- <TableCell className="text-right flex flex-row items-center gap-x-2 justify-end">- <>- <Button asChild type="default" size="tiny">- <Link href={`/project/${project?.ref}/editor/${tableName}`}>- <p>View table</p>- </Link>- </Button>- <DropdownMenu>- <DropdownMenuTrigger asChild>- <Button type="default" className="px-1" icon={<MoreVertical />} />- </DropdownMenuTrigger>-- <DropdownMenuContent side="bottom" align="end" className="w-fit min-w-[180px]">- <DropdownMenuItem className="flex items-center gap-x-2" onClick={handleQueryTable}>- <Code size={12} className="text-foreground-lighter" />- <p>Query in SQL Editor</p>- </DropdownMenuItem>- <DropdownMenuItem asChild className="flex items-center gap-x-2">- <Link href={`/project/${project?.ref}/database/etl/${tableName}`}>- <Replace size={12} className="text-foreground-lighter" />- <p>View replication status</p>- </Link>- </DropdownMenuItem>-- <DropdownMenuItem className="flex items-center gap-x-2" onClick={handleDeleteTable}>- <Trash2 size={12} className="text-foreground-lighter" />- <p>Delete table</p>- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>- </>- </TableCell>- )}- </TableRow>- )+ tablesToPoll: { schema: string; name: string }[]+ pollIntervalNamespaceTables: number+ setPollIntervalNamespaceTables: (value: number) => void}export const NamespaceWithTables = ({@@ -154,10 +53,16 @@ export const NamespaceWithTables = ({wrapperInstance,wrapperValues,wrapperMeta,+ tablesToPoll,+ pollIntervalNamespaceTables,+ setPollIntervalNamespaceTables,}: NamespaceWithTablesProps) => {+ const { ref: projectRef, bucketId } = useParams()const { data: project } = useSelectedProjectQuery()const [importForeignSchemaShown, setImportForeignSchemaShown] = useState(false)+ const { publication } = useAnalyticsBucketAssociatedEntities({ projectRef, bucketId })+const { data: tablesData, isLoading: isLoadingNamespaceTables } = useIcebergNamespaceTablesQuery({catalogUri: wrapperValues.catalog_uri,@@ -165,7 +70,23 @@ export const NamespaceWithTables = ({token: token,namespace: namespace,},- { enabled: !!token }+ {+ enabled: !!token,+ refetchInterval: (data) => {+ if (pollIntervalNamespaceTables === 0) return false+ if (tablesToPoll.length > 0) {+ const hasMissingTables =+ (data ?? []).filter((t) => !tables.find((table) => table.table.split('.')[1] === t))+ .length > 0++ if (hasMissingTables) {+ setPollIntervalNamespaceTables(0)+ return false+ }+ }+ return pollIntervalNamespaceTables+ },+ })const { mutateAsync: importForeignSchema, isLoading: isImportingForeignSchema } =@@ -187,21 +108,13 @@ export const NamespaceWithTables = ({)}, [tablesData, tables])- let scanTooltip = useMemo(() => {- if (isImportingForeignSchema) return 'Looking for new tables...'- if (isLoadingNamespaceTables) return 'Loading new tables...'- if (missingTables.length > 0)- return `${missingTables.length} new table${missingTables.length > 1 ? 's' : ''} found`- if (tables.length === 0) return 'No new tables found'- return 'All tables are up to date'- }, [isImportingForeignSchema, isLoadingNamespaceTables, missingTables.length, tables.length])-// Get all tables (connected + missing) for displayconst allTables = useMemo(() => {const connectedTableNames = tables.map((table) => table.table.split('.')[1])const allTableNames = [...new Set([...connectedTableNames, ...missingTables])]return allTableNames.map((tableName) => ({+ id: tables.find((t) => t.table_name === tableName)?.id ?? 0,name: tableName,isConnected: connectedTableNames.includes(tableName),}))@@ -234,19 +147,17 @@ export const NamespaceWithTables = ({<Card><CardHeader className="flex flex-row justify-between items-center px-4 py-5 space-y-0"><CardTitle className="text-sm font-normal font-sans normal-case leading-none flex flex-row items-center gap-x-1">- <TooltipProvider>- <Tooltip>- <TooltipTrigger asChild>- <span className="flex flex-row items-center gap-x-1 text-foreground-lighter">- {sourceType === 'direct' ? namespace : 'public'}- <ChevronRight size={12} className="text-foreground-muted" />- </span>- </TooltipTrigger>- <TooltipContent>- <p>{sourceType === 'direct' ? 'Analytics' : 'Postgres'} schema</p>- </TooltipContent>- </Tooltip>- </TooltipProvider>+ <Tooltip>+ <TooltipTrigger asChild>+ <span className="flex flex-row items-center gap-x-1 text-foreground-lighter">+ {sourceType === 'direct' ? namespace : 'public'}+ <ChevronRight size={12} className="text-foreground-muted" />+ </span>+ </TooltipTrigger>+ <TooltipContent side="bottom">+ <p>{sourceType === 'direct' ? 'Analytics' : 'Postgres'} schema</p>+ </TooltipContent>+ </Tooltip>{validSchema && (<Tooltip><TooltipTrigger@@ -264,7 +175,7 @@ export const NamespaceWithTables = ({{tables.length === 0 && <Info size={12} />}</span></TooltipTrigger>- <TooltipContent>+ <TooltipContent side="bottom"><p>Postgres schema{tables.length === 0 && ' that will be created'}</p></TooltipContent></Tooltip>@@ -272,29 +183,41 @@ export const NamespaceWithTables = ({</CardTitle><div className="flex flex-row gap-x-2">- {/* [Joshen] Temporarily commented out, will be introduced once language and UI details are finalized */}- {/* {tables.length > 0 && <p className="text-sm text-foreground-muted">{scanTooltip}</p>} */}- {/* {scanTooltip && <p className="text-sm text-foreground-muted">{scanTooltip}</p>} */}+ {tablesToPoll.length > 0 && (+ <div className="flex items-center gap-x-2 ml-6 text-foreground-lighter">+ <Loader2 size={14} className="animate-spin" />+ <p className="text-sm">+ Connecting {tablesToPoll.length} table{tablesToPoll.length > 1 ? 's' : ''}+ </p>+ </div>+ )}{missingTables.length > 0 && (<Button- type={missingTables.length > 0 ? 'warning' : 'default'}+ type={schema ? 'default' : 'warning'}size="tiny"- icon={<Plus size={14} />}+ icon={schema ? <RefreshCw /> : <Plus size={14} />}onClick={() => (schema ? rescanNamespace() : setImportForeignSchemaShown(true))}loading={isImportingForeignSchema || isLoadingNamespaceTables}>- Connect to table{missingTables.length > 1 ? 's' : ''}+ {schema ? 'Sync tables' : `Connect to table${missingTables.length > 1 ? 's' : ''}`}</Button>)}</div></CardHeader>++ {tablesToPoll.length > 0 && <LoadingLine loading />}+<Table><TableHeader><TableRow><TableHead className={allTables.length === 0 ? 'text-foreground-muted' : undefined}>Table name</TableHead>- <TableHead className={allTables.length === 0 ? 'hidden' : undefined}>Status</TableHead>+ {!!publication && (+ <TableHead className={allTables.length === 0 ? 'hidden' : undefined}>+ Replication Status+ </TableHead>+ )}<TableHead /></TableRow></TableHeader>@@ -311,11 +234,11 @@ export const NamespaceWithTables = ({</TableCell></TableRow>) : (- allTables.map(({ name, isConnected }, index) => (+ allTables.map((table, index) => (<TableRowComponent- key={name}- tableName={name}- isConnected={isConnected}+ key={table.name}+ table={table}+ schema={displaySchema}isLoading={isImportingForeignSchema || isLoadingNamespaceTables}index={index}/>diff --git a/apps/studio/components/interfaces/Storage/AnalyticsBuckets/AnalyticsBucketDetails/index.tsx b/apps/studio/components/interfaces/Storage/AnalyticsBuckets/AnalyticsBucketDetails/index.tsxindex d01c01c5581..a9efb065f22 100644--- a/apps/studio/components/interfaces/Storage/AnalyticsBuckets/AnalyticsBucketDetails/index.tsx+++ b/apps/studio/components/interfaces/Storage/AnalyticsBuckets/AnalyticsBucketDetails/index.tsx@@ -1,8 +1,8 @@import { uniq } from 'lodash'-import { SquarePlus } from 'lucide-react'+import { Loader2, SquarePlus } from 'lucide-react'import Link from 'next/link'import { useRouter } from 'next/router'-import { useMemo, useState } from 'react'+import { useEffect, useMemo, useState } from 'react'import { useParams } from 'common'import { INTEGRATIONS } from 'components/interfaces/Integrations/Landing/Integrations.constants'@@ -38,6 +38,7 @@ import { DeleteAnalyticsBucketModal } from '../DeleteAnalyticsBucketModal'import { ConnectTablesDialog } from './ConnectTablesDialog'import { NamespaceWithTables } from './NamespaceWithTables'import { SimpleConfigurationDetails } from './SimpleConfigurationDetails'+import { useAnalyticsBucketAssociatedEntities } from './useAnalyticsBucketAssociatedEntities'import { useAnalyticsBucketWrapperInstance } from './useAnalyticsBucketWrapperInstance'import { useIcebergWrapperExtension } from './useIcebergWrapper'@@ -55,14 +56,38 @@ export const AnalyticBucketDetails = () => {const bucket = _bucket as undefined | AnalyticsBucketconst [modal, setModal] = useState<'delete' | null>(null)+ // [Joshen] Namespaces are now created asynchronously when the pipeline is started, so long poll after+ // updating connected tables until namespaces are updated+ // Namespace would just be the schema (Which is currently limited to public)+ // Wrapper table would be {schema}_{table}_changelog+ const [tablesToPoll, setTablesToPoll] = useState<{ schema: string; name: string }[]>([])+ const [pollIntervalNamespaces, setPollIntervalNamespaces] = useState(0)+ const [pollIntervalNamespaceTables, setPollIntervalNamespaceTables] = useState(0)/** The wrapper instance is the wrapper that is installed for this Analytics bucket. */const { data: wrapperInstance, isLoading } = useAnalyticsBucketWrapperInstance({bucketId: bucket?.id,})+ const { pipeline } = useAnalyticsBucketAssociatedEntities({+ projectRef,+ bucketId: bucket?.id,+ })+const wrapperValues = convertKVStringArrayToJson(wrapperInstance?.server_options ?? [])const integration = INTEGRATIONS.find((i) => i.id === 'iceberg_wrapper' && i.type === 'wrapper')const wrapperMeta = (integration?.type === 'wrapper' && integration.meta) as WrapperMeta+ const state = isLoading+ ? 'loading'+ : extensionState === 'installed'+ ? wrapperInstance+ ? 'added'+ : 'missing'+ : extensionState++ const wrapperTables = useMemo(() => {+ if (!wrapperInstance) return []+ return formatWrapperTables(wrapperInstance, wrapperMeta!)+ }, [wrapperInstance, wrapperMeta])const { data: extensionsData } = useDatabaseExtensionsQuery({projectRef: project?.ref,@@ -85,14 +110,23 @@ export const AnalyticBucketDetails = () => {warehouse: wrapperValues.warehouse,token: token!,},- { enabled: isSuccessToken }- )-- const wrapperTables = useMemo(() => {- if (!wrapperInstance) return []+ {+ enabled: isSuccessToken,+ refetchInterval: (data) => {+ if (pollIntervalNamespaces === 0) return false+ if (tablesToPoll.length > 0) {+ const schemas = [...new Set(tablesToPoll.map((x) => x.schema))]+ const hasSchemaMissingFromNamespace = !schemas.some((x) => (data ?? []).includes(x))- return formatWrapperTables(wrapperInstance, wrapperMeta!)- }, [wrapperInstance, wrapperMeta])+ if (!hasSchemaMissingFromNamespace) {+ setPollIntervalNamespaces(0)+ return false+ }+ }+ return pollIntervalNamespaces+ },+ }+ )const namespaces = useMemo(() => {const fdwNamespaces = wrapperTables.map((t) => t.table.split('.')[0]) as string[]@@ -110,13 +144,11 @@ export const AnalyticBucketDetails = () => {})}, [wrapperTables, namespacesData])- const state = isLoading- ? 'loading'- : extensionState === 'installed'- ? wrapperInstance- ? 'added'- : 'missing'- : extensionState+ useEffect(() => {+ if (pollIntervalNamespaces === 0 && pollIntervalNamespaceTables === 0) {+ setTablesToPoll([])+ }+ }, [pollIntervalNamespaces, pollIntervalNamespaceTables])return (<>@@ -160,22 +192,68 @@ export const AnalyticBucketDetails = () => {Analytics tables stored in this bucket</ScaffoldSectionDescription></div>- {namespaces.length > 0 && <ConnectTablesDialog bucketId={bucket?.id} />}+ <div className="flex items-center gap-x-2">+ {!!pipeline && (+ <Button asChild type="default">+ <Link+ href={`/project/${projectRef}/database/etl/${pipeline.replicator_id}`}+ >+ View replication+ </Link>+ </Button>+ )}+ {namespaces.length > 0 && (+ <ConnectTablesDialog+ onSuccessConnectTables={(tables) => {+ setTablesToPoll(tables)+ setPollIntervalNamespaces(4000)+ setPollIntervalNamespaceTables(4000)+ }}+ />+ )}+ </div></ScaffoldHeader>{isLoadingNamespaces || isLoading ? (<GenericSkeletonLoader />) : namespaces.length === 0 ? (- <aside className="border border-dashed w-full bg-surface-100 rounded-lg px-4 py-10 flex flex-col gap-y-3 items-center text-center gap-1 text-balance">- <SquarePlus size={24} strokeWidth={1.5} className="text-foreground-muted" />- <div className="flex flex-col items-center text-center">- <h3>Connect database tables</h3>- <p className="text-foreground-light text-sm">- Stream data from tables for archival, backups, or analytical queries.- </p>- </div>- <ConnectTablesDialog bucketId={bucket?.id} />- </aside>+ <>+ {tablesToPoll.length > 0 ? (+ <aside className="border border-dashed w-full bg-surface-100 rounded-lg px-4 py-10 flex flex-col gap-y-3 items-center text-center gap-1 text-balance">+ <Loader2+ size={24}+ strokeWidth={1.5}+ className="animate-spin text-foreground-muted"+ />+ <div className="flex flex-col items-center text-center">+ <h3>+ Connecting {tablesToPoll.length} table+ {tablesToPoll.length > 1 ? 's' : ''} to bucket+ </h3>+ <p className="text-foreground-light text-sm">+ Tables will be shown here once the connection is complete+ </p>+ </div>+ </aside>+ ) : (+ <aside className="border border-dashed w-full bg-surface-100 rounded-lg px-4 py-10 flex flex-col gap-y-3 items-center text-center gap-1 text-balance">+ <SquarePlus size={24} strokeWidth={1.5} className="text-foreground-muted" />+ <div className="flex flex-col items-center text-center">+ <h3>Connect database tables</h3>+ <p className="text-foreground-light text-sm">+ Stream data from tables for archival, backups, or analytical queries.+ </p>+ </div>+ <ConnectTablesDialog+ onSuccessConnectTables={(tables) => {+ setTablesToPoll(tables)+ setPollIntervalNamespaces(4000)+ setPollIntervalNamespaceTables(4000)+ }}+ />+ </aside>+ )}+ </>) : (<div className="flex flex-col gap-y-10">{namespaces.map(({ namespace, schema, tables }) => (@@ -190,6 +268,9 @@ export const AnalyticBucketDetails = () => {wrapperInstance={wrapperInstance}wrapperValues={wrapperValues}wrapperMeta={wrapperMeta}+ tablesToPoll={tablesToPoll}+ pollIntervalNamespaceTables={pollIntervalNamespaceTables}+ setPollIntervalNamespaceTables={setPollIntervalNamespaceTables}/>))}</div>diff --git a/apps/studio/components/interfaces/Storage/AnalyticsBuckets/AnalyticsBucketDetails/useAnalyticsBucketAssociatedEntities.tsx b/apps/studio/components/interfaces/Storage/AnalyticsBuckets/AnalyticsBucketDetails/useAnalyticsBucketAssociatedEntities.tsxindex c869502e2b0..41a3c6aa334 100644--- a/apps/studio/components/interfaces/Storage/AnalyticsBuckets/AnalyticsBucketDetails/useAnalyticsBucketAssociatedEntities.tsx+++ b/apps/studio/components/interfaces/Storage/AnalyticsBuckets/AnalyticsBucketDetails/useAnalyticsBucketAssociatedEntities.tsx@@ -1,13 +1,14 @@import { PermissionAction } from '@supabase/shared-types/out/constants'import { WrapperMeta } from 'components/interfaces/Integrations/Wrappers/Wrappers.types'-import { useFDWDeleteMutation } from 'data/fdw/fdw-delete-mutation'-import { FDW } from 'data/fdw/fdws-query'+import { useReplicationPipelinesQuery } from 'data/etl/pipelines-query'import {ReplicationPublication,useReplicationPublicationsQuery,} from 'data/etl/publications-query'import { useReplicationSourcesQuery } from 'data/etl/sources-query'+import { useFDWDeleteMutation } from 'data/fdw/fdw-delete-mutation'+import { FDW } from 'data/fdw/fdws-query'import { useS3AccessKeyDeleteMutation } from 'data/storage/s3-access-key-delete-mutation'import { S3AccessKey, useStorageCredentialsQuery } from 'data/storage/s3-access-key-query'import { useAsyncCheckPermissions } from 'hooks/misc/useCheckPermissions'@@ -57,7 +58,10 @@ export const useAnalyticsBucketAssociatedEntities = ((p) => p.name === getAnalyticsBucketPublicationName(bucketId ?? ''))- return { icebergWrapper, icebergWrapperMeta, s3AccessKey, publication }+ const { data: pipelines } = useReplicationPipelinesQuery({ projectRef })+ const pipeline = pipelines?.pipelines.find((x) => x.config.publication_name === publication?.name)++ return { icebergWrapper, icebergWrapperMeta, s3AccessKey, sourceId, publication, pipeline }}export const useAnalyticsBucketDeleteCleanUp = () => {diff --git a/apps/studio/components/interfaces/Storage/AnalyticsBuckets/AnalyticsBucketDetails/useAnalyticsBucketWrapperInstance.tsx b/apps/studio/components/interfaces/Storage/AnalyticsBuckets/AnalyticsBucketDetails/useAnalyticsBucketWrapperInstance.tsxindex b685e212e87..39e3f234c9c 100644--- a/apps/studio/components/interfaces/Storage/AnalyticsBuckets/AnalyticsBucketDetails/useAnalyticsBucketWrapperInstance.tsx+++ b/apps/studio/components/interfaces/Storage/AnalyticsBuckets/AnalyticsBucketDetails/useAnalyticsBucketWrapperInstance.tsx@@ -6,12 +6,12 @@ import {getWrapperMetaForWrapper,wrapperMetaComparator,} from 'components/interfaces/Integrations/Wrappers/Wrappers.utils'-import { useFDWsQuery } from 'data/fdw/fdws-query'+import { type FDW, useFDWsQuery } from 'data/fdw/fdws-query'import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'export const useAnalyticsBucketWrapperInstance = ({ bucketId }: { bucketId?: string },- options?: { enabled?: boolean }+ options?: { enabled?: boolean; refetchInterval?: (data: FDW[] | undefined) => number | false }) => {const { data: project, isLoading: isLoadingProject } = useSelectedProjectQuery()@@ -21,7 +21,11 @@ export const useAnalyticsBucketWrapperInstance = (projectRef: project?.ref,connectionString: project?.connectionString,},- { enabled: defaultEnabled && !!bucketId }+ {+ enabled: defaultEnabled && !!bucketId,+ refetchInterval: (data) =>+ !!options?.refetchInterval ? options.refetchInterval(data) : false,+ })const icebergWrapper = useMemo(() => {diff --git a/apps/studio/components/interfaces/Storage/AnalyticsBuckets/CreateAnalyticsBucketModal.tsx b/apps/studio/components/interfaces/Storage/AnalyticsBuckets/CreateAnalyticsBucketModal.tsxindex 2e2afe50d13..54210e35902 100644--- a/apps/studio/components/interfaces/Storage/AnalyticsBuckets/CreateAnalyticsBucketModal.tsx+++ b/apps/studio/components/interfaces/Storage/AnalyticsBuckets/CreateAnalyticsBucketModal.tsx@@ -164,8 +164,8 @@ export const CreateAnalyticsBucketModal = ({groups: { project: ref ?? 'Unknown', organization: org?.slug ?? 'Unknown' },})- toast.success(`Created bucket “${values.name}”`)form.reset()+ toast.success(`Created bucket “${values.name}”`)setVisible(false)router.push(`/project/${ref}/storage/analytics/buckets/${values.name}`)} catch (error: any) {diff --git a/apps/studio/components/interfaces/Storage/ImportForeignSchemaDialog.tsx b/apps/studio/components/interfaces/Storage/ImportForeignSchemaDialog.tsxindex 6efe28e4835..17f536eef04 100644--- a/apps/studio/components/interfaces/Storage/ImportForeignSchemaDialog.tsx+++ b/apps/studio/components/interfaces/Storage/ImportForeignSchemaDialog.tsx@@ -36,11 +36,14 @@ export const ImportForeignSchemaDialog = ({onClose,circumstance = 'fresh',}: ImportForeignSchemaDialogProps) => {- const { data: project } = useSelectedProjectQuery()const { ref } = useParams()+ const { data: project } = useSelectedProjectQuery()const [loading, setLoading] = useState(false)const [createSchemaSheetOpen, setCreateSchemaSheetOpen] = useState(false)+ const { data: schemas } = useSchemasQuery({ projectRef: project?.ref! })++ const { mutateAsync: createSchema } = useSchemaCreateMutation()const { mutateAsync: importForeignSchema } = useFDWImportForeignSchemaMutation({})const { mutateAsync: updateFDW } = useFDWUpdateMutation({onSuccess: () => {@@ -49,8 +52,6 @@ export const ImportForeignSchemaDialog = ({},})- const { data: schemas } = useSchemasQuery({ projectRef: project?.ref! })-const FormSchema = z.object({bucketName: z.string().trim(),sourceNamespace: z.string().trim(),@@ -73,12 +74,10 @@ export const ImportForeignSchemaDialog = ({defaultValues: {bucketName,sourceNamespace: namespace,- targetSchema: '',+ targetSchema: `fdw_analytics_${namespace}`,},})- const { mutateAsync: createSchema } = useSchemaCreateMutation()-const onSubmit: SubmitHandler<z.infer<typeof FormSchema>> = async (values) => {const serverName = `${snakeCase(values.bucketName)}_fdw_server`@@ -150,7 +149,7 @@ export const ImportForeignSchemaDialog = ({form.reset({bucketName,sourceNamespace: namespace,- targetSchema: '',+ targetSchema: `fdw_analytics_${namespace}`,})}}, [visible, form, bucketName, namespace])diff --git a/apps/studio/data/etl/create-destination-pipeline-mutation.ts b/apps/studio/data/etl/create-destination-pipeline-mutation.tsindex a313280119d..78476e137d7 100644--- a/apps/studio/data/etl/create-destination-pipeline-mutation.ts+++ b/apps/studio/data/etl/create-destination-pipeline-mutation.ts@@ -16,7 +16,7 @@ export type BigQueryDestinationConfig = {export type IcebergDestinationConfig = {projectRef: stringwarehouseName: string- namespace: string+ namespace?: stringcatalogToken: strings3AccessKeyId: strings3SecretAccessKey: string@@ -59,6 +59,7 @@ async function createDestinationPipeline(if ('bigQuery' in destinationConfig) {const { projectId, datasetId, serviceAccountKey, maxStalenessMins } = destinationConfig.bigQuery+destination_config = {big_query: {project_id: projectId,@@ -70,19 +71,20 @@ async function createDestinationPipeline(} else if ('iceberg' in destinationConfig) {const {projectRef: icebergProjectRef,- warehouseName,namespace,+ warehouseName,catalogToken,s3AccessKeyId,s3SecretAccessKey,s3Region,} = destinationConfig.iceberg+destination_config = {iceberg: {supabase: {+ namespace,project_ref: icebergProjectRef,warehouse_name: warehouseName,- namespace: namespace,catalog_token: catalogToken,s3_access_key_id: s3AccessKeyId,s3_secret_access_key: s3SecretAccessKey,diff --git a/apps/studio/data/etl/destinations-query.ts b/apps/studio/data/etl/destinations-query.tsindex 9c73561f751..961c49ebc7a 100644--- a/apps/studio/data/etl/destinations-query.ts+++ b/apps/studio/data/etl/destinations-query.ts@@ -3,6 +3,7 @@ import { useQuery } from '@tanstack/react-query'import { get, handleError } from 'data/fetchers'import type { ResponseError, UseCustomQueryOptions } from 'types'import { replicationKeys } from './keys'+import { checkReplicationFeatureFlagRetry } from './utils'type ReplicationDestinationsParams = { projectRef?: string }@@ -36,5 +37,8 @@ export const useReplicationDestinationsQuery = <TData = ReplicationDestinationsDqueryKey: replicationKeys.destinations(projectRef),queryFn: ({ signal }) => fetchReplicationDestinations({ projectRef }, signal),enabled: enabled && typeof projectRef !== 'undefined',+ refetchOnMount: false,+ refetchOnWindowFocus: false,+ retry: checkReplicationFeatureFlagRetry,...options,})diff --git a/apps/studio/data/etl/pipelines-query.ts b/apps/studio/data/etl/pipelines-query.tsindex 5e9ed35d57a..7d1074409e1 100644--- a/apps/studio/data/etl/pipelines-query.ts+++ b/apps/studio/data/etl/pipelines-query.ts@@ -3,6 +3,7 @@ import { useQuery } from '@tanstack/react-query'import { get, handleError } from 'data/fetchers'import type { ResponseError, UseCustomQueryOptions } from 'types'import { replicationKeys } from './keys'+import { checkReplicationFeatureFlagRetry } from './utils'type ReplicationPipelinesParams = { projectRef?: string }@@ -16,10 +17,8 @@ async function fetchReplicationPipelines(params: { path: { ref: projectRef } },signal,})- if (error) {- handleError(error)- }+ if (error) handleError(error)return data}@@ -37,5 +36,8 @@ export const useReplicationPipelinesQuery = <TData = ReplicationPipelinesData>(queryKey: replicationKeys.pipelines(projectRef),queryFn: ({ signal }) => fetchReplicationPipelines({ projectRef }, signal),enabled: enabled && typeof projectRef !== 'undefined',+ refetchOnMount: false,+ refetchOnWindowFocus: false,+ retry: checkReplicationFeatureFlagRetry,...options,})diff --git a/apps/studio/data/etl/create-publication-mutation.ts b/apps/studio/data/etl/publication-create-mutation.tssimilarity index 100%rename from apps/studio/data/etl/create-publication-mutation.tsrename to apps/studio/data/etl/publication-create-mutation.tsdiff --git a/apps/studio/data/etl/publication-update-mutation.ts b/apps/studio/data/etl/publication-update-mutation.tsnew file mode 100644index 00000000000..7eb3789895e--- /dev/null+++ b/apps/studio/data/etl/publication-update-mutation.ts@@ -0,0 +1,66 @@+import { useMutation, useQueryClient } from '@tanstack/react-query'+import { toast } from 'sonner'++import { handleError, post } from 'data/fetchers'+import type { ResponseError, UseCustomMutationOptions } from 'types'+import { replicationKeys } from './keys'++export type UpdatePublicationParams = {+ projectRef: string+ sourceId: number+ publicationName: string+ tables: { schema: string; name: string }[]+}++async function updatePublication(+ { projectRef, sourceId, publicationName, tables }: UpdatePublicationParams,+ signal?: AbortSignal+) {+ if (!projectRef) throw new Error('projectRef is required')++ const { data, error } = await post(+ '/platform/replication/{ref}/sources/{source_id}/publications/{publication_name}',+ {+ params: { path: { ref: projectRef, source_id: sourceId, publication_name: publicationName } },+ body: { tables },+ signal,+ }+ )+ if (error) {+ handleError(error)+ }++ return data+}++type UpdatePublicationData = Awaited<ReturnType<typeof updatePublication>>++export const useUpdatePublicationMutation = ({+ onSuccess,+ onError,+ ...options+}: Omit<+ UseCustomMutationOptions<UpdatePublicationData, ResponseError, UpdatePublicationParams>,+ 'mutationFn'+> = {}) => {+ const queryClient = useQueryClient()++ return useMutation<UpdatePublicationData, ResponseError, UpdatePublicationParams>({+ mutationFn: (vars) => updatePublication(vars),+ async onSuccess(data, variables, context) {+ const { projectRef, sourceId } = variables+ await queryClient.invalidateQueries({+ queryKey: replicationKeys.publications(projectRef, sourceId),+ })+ await onSuccess?.(data, variables, context)+ },+ async onError(data, variables, context) {+ if (onError === undefined) {+ toast.error(`Failed to update publication: ${data.message}`)+ } else {+ onError(data, variables, context)+ }+ },+ ...options,+ })+}diff --git a/apps/studio/data/etl/sources-query.ts b/apps/studio/data/etl/sources-query.tsindex 8561af72a1d..54e5a942980 100644--- a/apps/studio/data/etl/sources-query.ts+++ b/apps/studio/data/etl/sources-query.ts@@ -3,6 +3,7 @@ import { useQuery } from '@tanstack/react-query'import { get, handleError } from 'data/fetchers'import type { ResponseError, UseCustomQueryOptions } from 'types'import { replicationKeys } from './keys'+import { checkReplicationFeatureFlagRetry } from './utils'type ReplicationSourcesParams = { projectRef?: string }@@ -36,5 +37,8 @@ export const useReplicationSourcesQuery = <TData = ReplicationSourcesData>(queryKey: replicationKeys.sources(projectRef),queryFn: ({ signal }) => fetchReplicationSources({ projectRef }, signal),enabled: enabled && typeof projectRef !== 'undefined',+ refetchOnMount: false,+ refetchOnWindowFocus: false,+ retry: checkReplicationFeatureFlagRetry,...options,})diff --git a/apps/studio/data/etl/tables-query.ts b/apps/studio/data/etl/tables-query.tsindex 0635055aba3..bcfa3a9f79e 100644--- a/apps/studio/data/etl/tables-query.ts+++ b/apps/studio/data/etl/tables-query.ts@@ -21,7 +21,7 @@ async function fetchReplicationTables(handleError(error)}- return data+ return data.tables}export type ReplicationTablesData = Awaited<ReturnType<typeof fetchReplicationTables>>diff --git a/apps/studio/data/etl/utils.ts b/apps/studio/data/etl/utils.tsnew file mode 100644index 00000000000..76d48cda2b1--- /dev/null+++ b/apps/studio/data/etl/utils.ts@@ -0,0 +1,22 @@+import { MAX_RETRY_FAILURE_COUNT } from 'data/query-client'+import { ResponseError } from 'types'++export const checkReplicationFeatureFlagRetry = (+ failureCount: number,+ error: ResponseError+): boolean => {+ const isFeatureFlagRequiredError =+ error instanceof ResponseError &&+ error.code === 503 &&+ error.message.includes('feature flag is required')++ if (isFeatureFlagRequiredError) {+ return false+ }++ if (failureCount < MAX_RETRY_FAILURE_COUNT) {+ return true+ }++ return false+}diff --git a/apps/studio/data/query-client.ts b/apps/studio/data/query-client.tsindex e539a31e24e..3587efc7948 100644--- a/apps/studio/data/query-client.ts+++ b/apps/studio/data/query-client.ts@@ -18,6 +18,8 @@ const SKIP_RETRY_PATHNAME_MATCHERS = ['/v1/projects/:ref/analytics/endpoints/logs.all',].map((pathname) => match(pathname))+export const MAX_RETRY_FAILURE_COUNT = 3+let queryClient: QueryClient | undefinedexport function getQueryClient() {@@ -55,7 +57,7 @@ export function getQueryClient() {return false}- if (failureCount < 3) {+ if (failureCount < MAX_RETRY_FAILURE_COUNT) {return true}diff --git a/apps/studio/data/storage/buckets-query.ts b/apps/studio/data/storage/buckets-query.tsindex 581c4e64d90..158777e2e7b 100644--- a/apps/studio/data/storage/buckets-query.ts+++ b/apps/studio/data/storage/buckets-query.ts@@ -2,6 +2,7 @@ import { useQuery } from '@tanstack/react-query'import { components } from 'api-types'import { get, handleError } from 'data/fetchers'+import { MAX_RETRY_FAILURE_COUNT } from 'data/query-client'import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'import { PROJECT_STATUS } from 'lib/constants'import { ResponseError, type UseCustomQueryOptions } from 'types'@@ -45,7 +46,7 @@ export const useBucketsQuery = <TData = BucketsData>(return false}- if (failureCount < 3) {+ if (failureCount < MAX_RETRY_FAILURE_COUNT) {return true}diff --git a/apps/studio/data/storage/iceberg-namespace-create-mutation.ts b/apps/studio/data/storage/iceberg-namespace-create-mutation.tsindex ce1a74696f3..9181128a1b5 100644--- a/apps/studio/data/storage/iceberg-namespace-create-mutation.ts+++ b/apps/studio/data/storage/iceberg-namespace-create-mutation.ts@@ -90,7 +90,7 @@ export const useIcebergNamespaceCreateMutation = ({await onSuccess?.(data, variables, context)},async onError(data, variables, context) {- if ((data.message = 'Request failed with status code 409')) {+ if (data.message === 'Request failed with status code 409') {toast.error(`A namespace named ${variables.namespace} already exists in the catalog.`)return}