The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
feat: Analytic storage bucket (#37003)
Ivan Vasilov89c803551b3d
diff --git a/apps/studio/components/grid/components/grid/Grid.tsx b/apps/studio/components/grid/components/grid/Grid.tsxindex 116cbf70455..fe907cabf8a 100644--- a/apps/studio/components/grid/components/grid/Grid.tsx+++ b/apps/studio/components/grid/components/grid/Grid.tsx@@ -6,12 +6,13 @@ import { formatForeignKeys } from 'components/interfaces/TableGridEditor/SidePanimport { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'import AlertError from 'components/ui/AlertError'import { useForeignKeyConstraintsQuery } from 'data/database/foreign-key-constraints-query'+import { ENTITY_TYPE } from 'data/entity-types/entity-type-constants'import { useSendEventMutation } from 'data/telemetry/send-event-mutation'import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'import { useTableEditorStateSnapshot } from 'state/table-editor'import { useTableEditorTableStateSnapshot } from 'state/table-editor-table'import { Button, cn } from 'ui'-import { GenericSkeletonLoader } from 'ui-patterns'+import { GenericSkeletonLoader } from 'ui-patterns/ShimmeringLoader'import type { Filter, GridProps, SupaRow } from '../../types'import { useOnRowsChange } from './Grid.utils'import RowRenderer from './RowRenderer'@@ -67,6 +68,7 @@ export const Grid = memo(}const table = snap.table+ const tableEntityType = snap.originalTable?.entity_typeconst { mutate: sendEvent } = useSendEventMutation()const org = useSelectedOrganization()@@ -82,13 +84,13 @@ export const Grid = memo(table?.columns.find((x) => x.name == columnName)?.foreignKey ?? {}const fk = data?.find(- (key: any) =>+ (key) =>key.source_schema === table?.schema &&key.source_table === table?.name &&key.source_columns.includes(columnName) &&key.target_schema === targetTableSchema &&key.target_table === targetTableName &&- key.target_columns.includes(targetColumnName)+ key.target_columns.includes(targetColumnName ?? ''))return fk !== undefined ? formatForeignKeys([fk])[0] : undefined@@ -141,11 +143,15 @@ export const Grid = memo({(filters ?? []).length === 0 ? (<div className="flex flex-col items-center justify-center col-span-full h-full"><p className="text-sm text-light">This table is empty</p>- <p className="text-sm text-light mt-1">- Add rows to your table to get started.- </p>- <div className="flex items-center space-x-2 mt-4">- {+ {tableEntityType === ENTITY_TYPE.FOREIGN_TABLE ? (+ <div className="flex items-center space-x-2 mt-4">+ <p className="text-sm text-light">+ This table is a foreign table. Add data to the connected source to get+ started.+ </p>+ </div>+ ) : (+ <div className="flex items-center space-x-2 mt-4"><Buttontype="default"className="pointer-events-auto"@@ -163,8 +169,8 @@ export const Grid = memo(>Import data from CSV</Button>- }- </div>+ </div>+ )}</div>) : (<div className="flex flex-col items-center justify-center col-span-full">diff --git a/apps/studio/components/interfaces/Integrations/Wrappers/EditWrapperSheet.tsx b/apps/studio/components/interfaces/Integrations/Wrappers/EditWrapperSheet.tsxindex 87703801cc5..041c2c518b9 100644--- a/apps/studio/components/interfaces/Integrations/Wrappers/EditWrapperSheet.tsx+++ b/apps/studio/components/interfaces/Integrations/Wrappers/EditWrapperSheet.tsx@@ -58,7 +58,9 @@ export const EditWrapperSheet = ({},})- const [wrapperTables, setWrapperTables] = useState(formatWrapperTables(wrapper, wrapperMeta))+ const [wrapperTables, setWrapperTables] = useState(() =>+ formatWrapperTables(wrapper, wrapperMeta)+ )const [isEditingTable, setIsEditingTable] = useState(false)const [selectedTableToEdit, setSelectedTableToEdit] = useState<FormattedWrapperTable | undefined>(undefined@@ -93,7 +95,8 @@ export const EditWrapperSheet = ({const { wrapper_name } = valuesif (wrapper_name.length === 0) errors.name = 'Please provide a name for your wrapper'- if (wrapperTables.length === 0) errors.tables = 'Please add at least one table'+ if (!wrapperMeta.canTargetSchema && wrapperTables.length === 0)+ errors.tables = 'Please add at least one table'if (!isEmpty(errors)) return setFormErrors(errors)updateFDW({diff --git a/apps/studio/components/interfaces/Integrations/Wrappers/Wrappers.utils.ts b/apps/studio/components/interfaces/Integrations/Wrappers/Wrappers.utils.tsindex 92f2101a570..63786de027c 100644--- a/apps/studio/components/interfaces/Integrations/Wrappers/Wrappers.utils.ts+++ b/apps/studio/components/interfaces/Integrations/Wrappers/Wrappers.utils.ts@@ -109,7 +109,7 @@ export const formatWrapperTables = (})}-export const convertKVStringArrayToJson = (values: string[]) => {+export const convertKVStringArrayToJson = (values: string[]): Record<string, string> => {return Object.fromEntries(values.map((value) => value.split('=')))}diff --git a/apps/studio/components/interfaces/Storage/CreateBucketModal.tsx b/apps/studio/components/interfaces/Storage/CreateBucketModal.tsxindex 552e59f16e8..1d5f0fa8236 100644--- a/apps/studio/components/interfaces/Storage/CreateBucketModal.tsx+++ b/apps/studio/components/interfaces/Storage/CreateBucketModal.tsx@@ -1,10 +1,15 @@+import { zodResolver } from '@hookform/resolvers/zod'+import { snakeCase } from 'lodash'import { ChevronDown } from 'lucide-react'import Link from 'next/link'import { useRouter } from 'next/router'import { useEffect, useState } from 'react'+import { SubmitHandler, useForm } from 'react-hook-form'import { toast } from 'sonner'+import z from 'zod'import { useParams } from 'common'+import { useIcebergWrapperExtension } from 'components/to-be-cleaned/Storage/AnalyticBucketDetails/useIcebergWrapper'import { StorageSizeUnits } from 'components/to-be-cleaned/Storage/StorageSettings/StorageSettings.constants'import {convertFromBytes,@@ -12,94 +17,145 @@ import {} from 'components/to-be-cleaned/Storage/StorageSettings/StorageSettings.utils'import { useProjectStorageConfigQuery } from 'data/config/project-storage-config-query'import { useBucketCreateMutation } from 'data/storage/bucket-create-mutation'-import { IS_PLATFORM } from 'lib/constants'-import { Button, Collapsible, Form, Input, Listbox, Modal, Toggle, cn } from 'ui'-import { Admonition } from 'ui-patterns'+import { useIcebergWrapperCreateMutation } from 'data/storage/iceberg-wrapper-create-mutation'+import { BASE_PATH, IS_PLATFORM } from 'lib/constants'+import {+ Alert_Shadcn_,+ AlertDescription_Shadcn_,+ AlertTitle_Shadcn_,+ Button,+ cn,+ Collapsible,+ Form_Shadcn_,+ FormControl_Shadcn_,+ FormField_Shadcn_,+ Input_Shadcn_,+ Label_Shadcn_,+ Listbox,+ Modal,+ RadioGroupStacked,+ RadioGroupStackedItem,+ Toggle,+ WarningIcon,+} from 'ui'+import { Admonition } from 'ui-patterns/admonition'+import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'export interface CreateBucketModalProps {visible: booleanonClose: () => void}+const FormSchema = z.object({+ name: z+ .string()+ .trim()+ .min(1, 'Please provide a name for your bucket')+ .regex(+ /^[a-z0-9.-]+$/,+ 'The name of the bucket must only contain lowercase letters, numbers, dots, and hyphens'+ )+ .refine((value) => !value.endsWith(' '), 'The name of the bucket cannot end with a whitespace')+ .refine(+ (value) => value !== 'public',+ '"public" is a reserved name. Please choose another name'+ ),+ type: z.enum(['STANDARD', 'ANALYTICS']).default('STANDARD'),+ public: z.boolean().default(false),+ has_file_size_limit: z.boolean().default(false),+ formatted_size_limit: z.coerce+ .number()+ .min(0, 'File size upload limit has to be at least 0')+ .default(0),+ allowed_mime_types: z.string().trim().default(''),+})++export type CreateBucketForm = z.infer<typeof FormSchema>+const CreateBucketModal = ({ visible, onClose }: CreateBucketModalProps) => {const { ref } = useParams()const router = useRouter()- const { mutate: createBucket, isLoading: isCreating } = useBucketCreateMutation({- onSuccess: (res) => {- toast.success(`Successfully created bucket ${res.name}`)- router.push(`/project/${ref}/storage/buckets/${res.name}`)- onClose()- },- })+ const { mutateAsync: createBucket, isLoading: isCreating } = useBucketCreateMutation()+ const { mutateAsync: createIcebergWrapper, isLoading: isCreatingIcebergWrapper } =+ useIcebergWrapperCreateMutation()- const { data } = useProjectStorageConfigQuery(- { projectRef: ref },- { enabled: IS_PLATFORM && visible }- )+ const { data } = useProjectStorageConfigQuery({ projectRef: ref }, { enabled: IS_PLATFORM })const { value, unit } = convertFromBytes(data?.fileSizeLimit ?? 0)const formattedGlobalUploadLimit = `${value} ${unit}`const [selectedUnit, setSelectedUnit] = useState<StorageSizeUnits>(StorageSizeUnits.BYTES)const [showConfiguration, setShowConfiguration] = useState(false)- const initialValues = {- name: '',- public: false,- file_size_limit: 0,- allowed_mime_types: '',- has_file_size_limit: false,- formatted_size_limit: 0,- }+ const form = useForm<CreateBucketForm>({+ resolver: zodResolver(FormSchema),+ defaultValues: {+ name: '',+ public: false,+ type: 'STANDARD',+ has_file_size_limit: false,+ formatted_size_limit: 0,+ allowed_mime_types: '',+ },+ })- const validate = (values: any) => {- const errors = {} as any+ const bucketName = snakeCase(form.watch('name'))+ const isPublicBucket = form.watch('public')+ const isStandardBucket = form.watch('type') === 'STANDARD'+ const hasFileSizeLimit = form.watch('has_file_size_limit')+ const formattedSizeLimit = form.watch('formatted_size_limit')+ const icebergWrapperExtensionState = useIcebergWrapperExtension()- if (!values.name) {- errors.name = 'Please provide a name for your bucket'- }+ const onSubmit: SubmitHandler<CreateBucketForm> = async (values) => {+ if (!ref) return console.error('Project ref is required')- if (values.name && !/^[a-z0-9.-]+$/.test(values.name)) {- errors.name =- 'The name of the bucket must only container lowercase letters, numbers, dots, and hyphens'+ if (values.type === 'ANALYTICS' && !icebergCatalogEnabled) {+ toast.error(+ 'The Analytics catalog feature is not enabled for your project. Please contact support to enable it.'+ )+ return}- if (values.name && values.name.endsWith(' ')) {- errors.name = 'The name of the bucket cannot end with a whitespace'- }+ try {+ const fileSizeLimit = values.has_file_size_limit+ ? convertToBytes(values.formatted_size_limit, selectedUnit)+ : undefined- if (values.has_file_size_limit && values.formatted_size_limit < 0) {- errors.formatted_size_limit = 'File size upload limit has to be at least 0'- }- if (values.name === 'public') {- errors.name = '"public" is a reserved name. Please choose another name'- }- return errors- }+ const allowedMimeTypes =+ values.allowed_mime_types.length > 0+ ? values.allowed_mime_types.split(',').map((x) => x.trim())+ : undefined- const onSubmit = async (values: any) => {- if (!ref) return console.error('Project ref is required')+ await createBucket({+ projectRef: ref,+ id: values.name,+ type: values.type,+ isPublic: values.public,+ file_size_limit: fileSizeLimit,+ allowed_mime_types: allowedMimeTypes,+ })- createBucket({- projectRef: ref,- id: values.name,- isPublic: values.public,- file_size_limit: values.has_file_size_limit- ? convertToBytes(values.formatted_size_limit, selectedUnit)- : null,- allowed_mime_types:- values.allowed_mime_types.length > 0- ? values.allowed_mime_types.split(',').map((x: string) => x.trim())- : null,- })+ if (values.type === 'ANALYTICS' && icebergWrapperExtensionState === 'installed') {+ await createIcebergWrapper({ bucketName: values.name })+ }+ toast.success(`Successfully created bucket ${values.name}`)+ router.push(`/project/${ref}/storage/buckets/${values.name}`)+ onClose()+ } catch (error) {+ console.error(error)+ toast.error('Failed to create bucket')+ }}useEffect(() => {if (visible) {+ form.reset()setSelectedUnit(StorageSizeUnits.BYTES)setShowConfiguration(false)}- }, [visible])+ }, [visible, form])++ const icebergCatalogEnabled = data?.features?.icebergCatalog?.enabledreturn (<Modal@@ -109,36 +165,115 @@ const CreateBucketModal = ({ visible, onClose }: CreateBucketModalProps) => {header="Create storage bucket"onCancel={() => onClose()}>- <Form- validateOnBlur={false}- initialValues={initialValues}- validate={validate}- onSubmit={onSubmit}- >- {({ values }: { values: any }) => {- const isPublicBucket = values.public-- return (- <>- <Modal.Content className={cn('!px-0', isPublicBucket && '!pb-0')}>- <Input- id="name"- name="name"- type="text"- className="w-full px-5"- layout="vertical"+ <Form_Shadcn_ {...form}>+ <form onSubmit={form.handleSubmit(onSubmit)}>+ <Modal.Content>+ <FormField_Shadcn_+ control={form.control}+ name="name"+ render={({ field }) => (+ <FormItemLayoutlabel="Name of bucket"labelOptional="Buckets cannot be renamed once created."- descriptionText="Only lowercase letters, numbers, dots, and hyphens"- />- <div className="flex flex-col gap-y-2 mt-6">- <Toggle- id="public"+ description="Only lowercase letters, numbers, dots, and hyphens"+ layout="vertical"+ >+ <FormControl_Shadcn_>+ <Input_Shadcn_ {...field} placeholder="Enter bucket name" />+ </FormControl_Shadcn_>+ </FormItemLayout>+ )}+ />++ <div className="flex flex-col gap-y-2 mt-6">+ <FormField_Shadcn_+ control={form.control}+ name="type"+ render={({ field }) => (+ <FormItemLayout>+ <FormControl_Shadcn_>+ <RadioGroupStacked+ id="type"+ onValueChange={(v) => field.onChange(v)}+ value={field.value}+ >+ <RadioGroupStackedItem+ value="STANDARD"+ id="STANDARD"+ label="Standard bucket"+ showIndicator={false}+ >+ <div className="flex gap-x-5">+ <div className="flex flex-col">+ <p className="text-foreground-light text-left">+ Compatible with S3 buckets.+ </p>+ </div>+ </div>+ </RadioGroupStackedItem>+ {IS_PLATFORM && (+ <RadioGroupStackedItem+ value="ANALYTICS"+ id="ANALYTICS"+ label="Analytics bucket"+ showIndicator={false}+ disabled={!icebergCatalogEnabled}+ >+ <div className="flex gap-x-5">+ <div className="flex flex-col">+ <p className="text-foreground-light text-left">+ Stores Iceberg files and is optimized for analytical workloads.+ </p>+ </div>+ </div>+ {icebergCatalogEnabled ? null : (+ <div className="w-full flex gap-x-2 py-2 items-center">+ <WarningIcon />+ <span className="text-xs text-left">+ This feature is currently in alpha and not yet enabled for your+ project. Sign up{' '}+ <a+ className="underline"+ target="_blank"+ rel="noreferrer"+ href="https://forms.supabase.com/analytics-buckets"+ >+ here+ </a>+ </span>+ </div>+ )}+ </RadioGroupStackedItem>+ )}+ </RadioGroupStacked>+ </FormControl_Shadcn_>+ </FormItemLayout>+ )}+ />+ </div>+ </Modal.Content>+ <Modal.Separator />+ {isStandardBucket ? (+ <>+ <Modal.Content className="!px-0 !pb-0">+ <div className="flex flex-col gap-y-2">+ <FormField_Shadcn_+ control={form.control}name="public"- layout="flex"- className="px-5"- label="Public bucket"- descriptionText="Anyone can read any object without any authorization"+ render={({ field }) => (+ <FormItemLayout className="px-5">+ <FormControl_Shadcn_>+ <Toggle+ id="public"+ checked={field.value}+ onChange={field.onChange}+ layout="flex"+ label="Public bucket"+ descriptionText="Anyone can read any object without any authorization"+ />+ </FormControl_Shadcn_>+ </FormItemLayout>+ )}/>{isPublicBucket && (<Admonition@@ -157,13 +292,14 @@ const CreateBucketModal = ({ visible, onClose }: CreateBucketModalProps) => {)}</div></Modal.Content>+ <Modal.Separator /><Collapsibleopen={showConfiguration}onOpenChange={() => setShowConfiguration(!showConfiguration)}><Collapsible.Trigger asChild>- <div className="w-full cursor-pointer py-3 px-5 flex items-center justify-between border-t border-default">- <p className="text-sm">Additional configuration</p>+ <div className="w-full cursor-pointer py-3 px-5 flex items-center justify-between">+ <p className="text-sm">Additional restrictions</p><ChevronDownsize={18}strokeWidth={2}@@ -174,37 +310,59 @@ const CreateBucketModal = ({ visible, onClose }: CreateBucketModalProps) => {<Collapsible.Content className="py-4"><div className="w-full space-y-5 px-5"><div className="space-y-5">- <Toggle- id="has_file_size_limit"+ <FormField_Shadcn_+ control={form.control}name="has_file_size_limit"- layout="flex"- label="Restrict file upload size for bucket"- descriptionText="Prevent uploading of file sizes greater than a specified limit"+ render={({ field }) => (+ <FormItemLayout>+ <FormControl_Shadcn_>+ <Toggle+ id="has_file_size_limit"+ checked={field.value}+ onChange={field.onChange}+ layout="flex"+ label="Restrict file upload size for bucket"+ descriptionText="Prevent uploading of file sizes greater than a specified limit"+ />+ </FormControl_Shadcn_>+ </FormItemLayout>+ )}/>- {values.has_file_size_limit && (+ {hasFileSizeLimit && (<div className="grid grid-cols-12 col-span-12 gap-x-2 gap-y-1"><div className="col-span-8">- <Input- type="number"- step={1}- id="formatted_size_limit"+ <FormField_Shadcn_+ control={form.control}name="formatted_size_limit"- disabled={false}- onKeyPress={(event) => {- if (event.charCode < 48 || event.charCode > 57) {- event.preventDefault()- }- }}- descriptionText={`Equivalent to ${convertToBytes(- values.formatted_size_limit,- selectedUnit- ).toLocaleString()} bytes.`}+ render={({ field }) => (+ <FormItemLayout>+ <FormControl_Shadcn_>+ <Input_Shadcn_+ type="number"+ step={1}+ {...field}+ onKeyPress={(event) => {+ if (event.charCode < 48 || event.charCode > 57) {+ event.preventDefault()+ }+ }}+ />+ </FormControl_Shadcn_>+ <span className="text-foreground-light text-xs">+ Equivalent to{' '}+ {convertToBytes(+ formattedSizeLimit,+ selectedUnit+ ).toLocaleString()}{' '}+ bytes.+ </span>+ </FormItemLayout>+ )}/></div><div className="col-span-4"><Listboxid="size_limit_units"- disabled={false}value={selectedUnit}onChange={setSelectedUnit}>@@ -232,36 +390,122 @@ const CreateBucketModal = ({ visible, onClose }: CreateBucketModalProps) => {</div>)}</div>- <Input- id="allowed_mime_types"+ <FormField_Shadcn_+ control={form.control}name="allowed_mime_types"- layout="vertical"- label="Allowed MIME types"- placeholder="e.g image/jpeg, image/png, audio/mpeg, video/mp4, etc"- labelOptional="Comma separated values"- descriptionText="Wildcards are allowed, e.g. image/*. Leave blank to allow any MIME type."+ render={({ field }) => (+ <FormItemLayout+ label="Allowed MIME types"+ labelOptional="Comma separated values"+ description="Wildcards are allowed, e.g. image/*. Leave blank to allow any MIME type."+ layout="vertical"+ >+ <FormControl_Shadcn_>+ <Input_Shadcn_+ {...field}+ placeholder="e.g image/jpeg, image/png, audio/mpeg, video/mp4, etc"+ />+ </FormControl_Shadcn_>+ </FormItemLayout>+ )}/></div></Collapsible.Content></Collapsible>- <Modal.Separator />- <Modal.Content className="flex items-center space-x-2 justify-end">- <Button- type="default"- htmlType="button"- disabled={isCreating}- onClick={() => onClose()}- >- Cancel- </Button>- <Button type="primary" htmlType="submit" loading={isCreating} disabled={isCreating}>- Save- </Button>- </Modal.Content></>- )- }}- </Form>+ ) : (+ <Modal.Content>+ {icebergWrapperExtensionState === 'installed' ? (+ <Label_Shadcn_ className="text-foreground-lighter leading-1 flex flex-col gap-y-2">+ <p>+ <span>Supabase will setup a </span>+ <a+ href={`${BASE_PATH}/project/${ref}/integrations/iceberg_wrapper/overview`}+ target="_blank"+ className="underline text-foreground-light"+ >+ foreign data wrapper+ {bucketName && <span className="text-brand"> {`${bucketName}_fdw`}</span>}+ </a>+ <span>+ {' '}+ for easier access to the data. This action will also create{' '}+ <a+ href={`${BASE_PATH}/project/${ref}/storage/access-keys`}+ target="_blank"+ className="underline text-foreground-light"+ >+ S3 Access Keys+ {bucketName && (+ <>+ {' '}+ named <span className="text-brand"> {`${bucketName}_keys`}</span>+ </>+ )}+ </a>+ <span> and </span>+ <a+ href={`${BASE_PATH}/project/${ref}/integrations/vault/secrets`}+ target="_blank"+ className="underline text-foreground-light"+ >+ four Vault Secrets+ {bucketName && (+ <>+ {' '}+ prefixed with{' '}+ <span className="text-brand"> {`${bucketName}_vault_`}</span>+ </>+ )}+ </a>+ .+ </span>+ </p>+ <p>+ As a final step, you'll need to create an{' '}+ <span className="text-foreground-light">Iceberg namespace</span> before you+ connect the Iceberg data to your database.+ </p>+ </Label_Shadcn_>+ ) : (+ <Alert_Shadcn_ variant="warning">+ <WarningIcon />+ <AlertTitle_Shadcn_>+ You need to install the Iceberg wrapper extension to connect your Analytic+ bucket to your database.+ </AlertTitle_Shadcn_>+ <AlertDescription_Shadcn_ className="flex flex-col gap-y-2">+ <p>+ You need to install the <span className="text-brand">wrappers</span> extension+ (with the minimum version of <span>0.5.3</span>) if you want to connect your+ Analytics bucket to your database.+ </p>+ </AlertDescription_Shadcn_>+ </Alert_Shadcn_>+ )}+ </Modal.Content>+ )}+ <Modal.Separator />+ <Modal.Content className="flex items-center space-x-2 justify-end">+ <Button+ type="default"+ htmlType="button"+ disabled={isCreating || isCreatingIcebergWrapper}+ onClick={() => onClose()}+ >+ Cancel+ </Button>+ <Button+ type="primary"+ htmlType="submit"+ loading={isCreating || isCreatingIcebergWrapper}+ disabled={isCreating || isCreatingIcebergWrapper}+ >+ Create+ </Button>+ </Modal.Content>+ </form>+ </Form_Shadcn_></Modal>)}diff --git a/apps/studio/components/interfaces/Storage/EditBucketModal.tsx b/apps/studio/components/interfaces/Storage/EditBucketModal.tsxindex aff15a75ef7..5abb63cd4d5 100644--- a/apps/studio/components/interfaces/Storage/EditBucketModal.tsx+++ b/apps/studio/components/interfaces/Storage/EditBucketModal.tsx@@ -15,11 +15,11 @@ import { useProjectStorageConfigQuery } from 'data/config/project-storage-configimport { useBucketUpdateMutation } from 'data/storage/bucket-update-mutation'import { IS_PLATFORM } from 'lib/constants'import { Admonition } from 'ui-patterns'-import type { StorageBucket } from './Storage.types'+import { Bucket } from 'data/storage/buckets-query'export interface EditBucketModalProps {visible: boolean- bucket?: StorageBucket+ bucket?: BucketonClose: () => void}diff --git a/apps/studio/components/interfaces/Storage/ImportForeignSchemaDialog.tsx b/apps/studio/components/interfaces/Storage/ImportForeignSchemaDialog.tsxnew file mode 100644index 00000000000..a173dbcfa52--- /dev/null+++ b/apps/studio/components/interfaces/Storage/ImportForeignSchemaDialog.tsx@@ -0,0 +1,167 @@+import { zodResolver } from '@hookform/resolvers/zod'+import { snakeCase } from 'lodash'+import { useEffect, useState } from 'react'+import { SubmitHandler, useForm } from 'react-hook-form'+import { toast } from 'sonner'+import z from 'zod'++import { useParams } from 'common'+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'+import SchemaSelector from 'components/ui/SchemaSelector'+import { useFDWImportForeignSchemaMutation } from 'data/fdw/fdw-import-foreign-schema-mutation'+import {+ Button,+ Form_Shadcn_,+ FormControl_Shadcn_,+ FormField_Shadcn_,+ Input_Shadcn_,+ Modal,+} from 'ui'+import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'+import SchemaEditor from '../TableGridEditor/SidePanelEditor/SchemaEditor'++export interface ImportForeignSchemaDialogProps {+ bucketName: string+ namespace: string+ excludedSchemas: string[]+ wrapperValues: Record<string, string>+ visible: boolean+ onClose: () => void+}++const FormSchema = z.object({+ bucketName: z.string().trim(),+ sourceNamespace: z.string().trim(),+ targetSchema: z.string().trim(),+})++export type ImportForeignSchemaForm = z.infer<typeof FormSchema>++export const ImportForeignSchemaDialog = ({+ bucketName,+ namespace,+ excludedSchemas,+ wrapperValues,+ visible,+ onClose,+}: ImportForeignSchemaDialogProps) => {+ const { project } = useProjectContext()+ const { ref } = useParams()+ const [loading, setLoading] = useState(false)+ const [createSchemaSheetOpen, setCreateSchemaSheetOpen] = useState(false)++ const { mutateAsync: importForeignSchema } = useFDWImportForeignSchemaMutation({+ onSuccess: () => {+ toast.success(`Successfully connected ${bucketName} to the database.`)+ onClose()+ },+ })++ const form = useForm<ImportForeignSchemaForm>({+ resolver: zodResolver(FormSchema),+ defaultValues: {+ bucketName,+ sourceNamespace: namespace,+ targetSchema: '',+ },+ })++ const onSubmit: SubmitHandler<ImportForeignSchemaForm> = async (values) => {+ if (!ref) return console.error('Project ref is required')+ setLoading(true)++ try {+ await importForeignSchema({+ projectRef: ref,+ connectionString: project?.connectionString,+ serverName: `${snakeCase(values.bucketName)}_fdw_server`,+ sourceSchema: values.sourceNamespace,+ targetSchema: values.targetSchema,+ })+ } catch (error: any) {+ // error will be handled by the mutation onError callback+ } finally {+ setLoading(false)+ }+ }++ useEffect(() => {+ if (visible) {+ form.reset({+ bucketName,+ sourceNamespace: namespace,+ targetSchema: '',+ })+ }+ }, [visible, form, bucketName, namespace])++ return (+ <Modal+ hideFooter+ visible={visible}+ size="medium"+ header={+ <span>+ Connect namespace <span className="text-brand">{namespace}</span>+ </span>+ }+ onCancel={() => onClose()}+ >+ <Form_Shadcn_ {...form}>+ <form onSubmit={form.handleSubmit(onSubmit)}>+ <Modal.Content className="flex flex-col gap-y-4">+ <FormField_Shadcn_+ control={form.control}+ name="sourceNamespace"+ render={({ field }) => (+ <FormItemLayout label="Namespace" layout="vertical">+ <FormControl_Shadcn_>+ <Input_Shadcn_ {...field} placeholder="Enter namespace name" disabled />+ </FormControl_Shadcn_>+ </FormItemLayout>+ )}+ />++ <FormField_Shadcn_+ control={form.control}+ name="targetSchema"+ render={({ field }) => (+ <FormItemLayout+ label="Target Schema"+ description="Select the database schema where the Iceberg data will be accessible. Each schema can only be connected to one namespace."+ layout="vertical"+ >+ <SchemaSelector+ portal={false}+ size="small"+ selectedSchemaName={field.value}+ excludedSchemas={excludedSchemas}+ onSelectSchema={(schema) => field.onChange(schema)}+ onSelectCreateSchema={() => setCreateSchemaSheetOpen(true)}+ />+ </FormItemLayout>+ )}+ />+ </Modal.Content>+ <Modal.Separator />+ <Modal.Content className="flex items-center space-x-2 justify-end">+ <Button type="default" htmlType="button" disabled={loading} onClick={onClose}>+ Cancel+ </Button>+ <Button type="primary" htmlType="submit" loading={loading}>+ Save+ </Button>+ </Modal.Content>+ </form>+ </Form_Shadcn_>+ <SchemaEditor+ visible={createSchemaSheetOpen}+ closePanel={() => setCreateSchemaSheetOpen(false)}+ onSuccess={(schema) => {+ form.setValue('targetSchema', schema)+ setCreateSchemaSheetOpen(false)+ }}+ />+ </Modal>+ )+}diff --git a/apps/studio/components/interfaces/Storage/Storage.types.ts b/apps/studio/components/interfaces/Storage/Storage.types.tsindex 37b00902f28..8de8a32625e 100644--- a/apps/studio/components/interfaces/Storage/Storage.types.ts+++ b/apps/studio/components/interfaces/Storage/Storage.types.ts@@ -4,17 +4,6 @@ export interface StoragePolicyFormField extends PolicyFormField {allowedOperations: string[]}-export interface StorageBucket {- id: string- name: string- owner: string- public: boolean- file_size_limit: number | null- allowed_mime_types: string[] | null- created_at: string- updated_at: string-}-export interface BucketUpdatePayload {public?: booleanfile_size_limit?: number | nulldiff --git a/apps/studio/components/layouts/StorageLayout/BucketRow.tsx b/apps/studio/components/layouts/StorageLayout/BucketRow.tsxindex 959c300986f..5b22530cc64 100644--- a/apps/studio/components/layouts/StorageLayout/BucketRow.tsx+++ b/apps/studio/components/layouts/StorageLayout/BucketRow.tsx@@ -1,6 +1,6 @@import { PermissionAction } from '@supabase/shared-types/out/constants'import { noop } from 'lodash'-import { ChevronDown, Edit2, Trash, XCircle } from 'lucide-react'+import { ChevronDown, Columns3, Edit2, Trash, XCircle } from 'lucide-react'import Link from 'next/link'import type { Bucket } from 'data/storage/buckets-query'@@ -13,6 +13,9 @@ import {DropdownMenuItem,DropdownMenuSeparator,DropdownMenuTrigger,+ Tooltip,+ TooltipContent,+ TooltipTrigger,cn,} from 'ui'@@ -46,7 +49,7 @@ const BucketRow = ({{/* Even though we trim whitespaces from bucket names, there may be some existing buckets with trailing whitespaces. */}<Linkhref={`/project/${projectRef}/storage/buckets/${encodeURIComponent(bucket.id)}`}- className={cn('py-1 px-3', isSelected ? 'w-[88%]' : 'w-full')}+ className={'py-1 px-3 grow'}><div className="flex items-center justify-between space-x-2 truncate w-full"><p@@ -58,31 +61,45 @@ const BucketRow = ({{bucket.name}</p>{bucket.public && <Badge variant="warning">Public</Badge>}+ {bucket.type === 'ANALYTICS' && (+ <Tooltip>+ <TooltipTrigger asChild>+ <Columns3 className="text-foreground-lighter" size="20" />+ </TooltipTrigger>+ <TooltipContent>+ <p>Analytics bucket</p>+ </TooltipContent>+ </Tooltip>+ )}</div></Link>{canUpdateBuckets && isSelected ? (<DropdownMenu><DropdownMenuTrigger asChild>- <Button type="text" icon={<ChevronDown />} className="mr-1 p-0.5" />+ <Button type="text" icon={<ChevronDown />} className="mr-1 p-1.5 w-7" /></DropdownMenuTrigger><DropdownMenuContent side="bottom" align="start">- <DropdownMenuItem- key="toggle-private"- className="space-x-2"- onClick={() => onSelectEditBucket()}- >- <Edit2 size={14} />- <p>Edit bucket</p>- </DropdownMenuItem>- <DropdownMenuSeparator />- <DropdownMenuItem- key="empty-bucket"- className="space-x-2"- onClick={() => onSelectEmptyBucket()}- >- <XCircle size={14} />- <p>Empty bucket</p>- </DropdownMenuItem>+ {bucket.type === 'ANALYTICS' && (+ <>+ <DropdownMenuItem+ key="toggle-private"+ className="space-x-2"+ onClick={() => onSelectEditBucket()}+ >+ <Edit2 size={14} />+ <p>Edit bucket</p>+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ <DropdownMenuItem+ key="empty-bucket"+ className="space-x-2"+ onClick={() => onSelectEmptyBucket()}+ >+ <XCircle size={14} />+ <p>Empty bucket</p>+ </DropdownMenuItem>+ </>+ )}<DropdownMenuItemkey="delete-bucket"className="space-x-2"@@ -94,7 +111,7 @@ const BucketRow = ({</DropdownMenuContent></DropdownMenu>) : (- <div className="w-5" />+ <div className="w-7 mr-1" />)}</div>)diff --git a/apps/studio/components/layouts/StorageLayout/StorageMenu.tsx b/apps/studio/components/layouts/StorageLayout/StorageMenu.tsxindex a91a4f3de24..094cbc5013d 100644--- a/apps/studio/components/layouts/StorageLayout/StorageMenu.tsx+++ b/apps/studio/components/layouts/StorageLayout/StorageMenu.tsx@@ -8,12 +8,11 @@ import { useState } from 'react'import { useParams } from 'common'import CreateBucketModal from 'components/interfaces/Storage/CreateBucketModal'import EditBucketModal from 'components/interfaces/Storage/EditBucketModal'-import type { StorageBucket } from 'components/interfaces/Storage/Storage.types'import { DeleteBucketModal } from 'components/to-be-cleaned/Storage'import { EmptyBucketModal } from 'components/to-be-cleaned/Storage/EmptyBucketModal'import { ButtonTooltip } from 'components/ui/ButtonTooltip'import ShimmeringLoader from 'components/ui/ShimmeringLoader'-import { useBucketsQuery } from 'data/storage/buckets-query'+import { Bucket, useBucketsQuery } from 'data/storage/buckets-query'import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'import { useSelectedProject } from 'hooks/misc/useSelectedProject'import { Alert_Shadcn_, AlertDescription_Shadcn_, AlertTitle_Shadcn_, Menu } from 'ui'@@ -34,9 +33,9 @@ const StorageMenu = () => {const [searchText, setSearchText] = useState<string>('')const [showCreateBucketModal, setShowCreateBucketModal] = useState(false)- const [selectedBucketToEdit, setSelectedBucketToEdit] = useState<StorageBucket>()- const [selectedBucketToEmpty, setSelectedBucketToEmpty] = useState<StorageBucket>()- const [selectedBucketToDelete, setSelectedBucketToDelete] = useState<StorageBucket>()+ const [selectedBucketToEdit, setSelectedBucketToEdit] = useState<Bucket>()+ const [selectedBucketToEmpty, setSelectedBucketToEmpty] = useState<Bucket>()+ const [selectedBucketToDelete, setSelectedBucketToDelete] = useState<Bucket>()const canCreateBuckets = useCheckPermissions(PermissionAction.STORAGE_WRITE, '*')const [sort, setSort] = useLocalStorage<'alphabetical' | 'created-at'>(diff --git a/apps/studio/components/to-be-cleaned/Storage/AnalyticBucketDetails/CopyEnvButton.tsx b/apps/studio/components/to-be-cleaned/Storage/AnalyticBucketDetails/CopyEnvButton.tsxnew file mode 100644index 00000000000..1c45eda3cf0--- /dev/null+++ b/apps/studio/components/to-be-cleaned/Storage/AnalyticBucketDetails/CopyEnvButton.tsx@@ -0,0 +1,62 @@+import { Copy } from 'lucide-react'+import { useCallback, useState } from 'react'+import { toast } from 'sonner'++import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'+import { ButtonTooltip } from 'components/ui/ButtonTooltip'+import { getDecryptedValue } from 'data/vault/vault-secret-decrypted-value-query'+import { copyToClipboard } from 'ui'++export const CopyEnvButton = ({+ serverOptions,+ values,+}: {+ serverOptions: { name: string; secureEntry: boolean }[]+ values: Record<string, string>+}) => {+ const { project } = useProjectContext()+ const [isLoading, setIsLoading] = useState(false)++ const onCopy = useCallback(async () => {+ setIsLoading(true)+ const envFile = Promise.all(+ serverOptions.map(async (option) => {+ if (option.secureEntry) {+ const decryptedValue = await getDecryptedValue({+ projectRef: project?.ref,+ connectionString: project?.connectionString,+ id: values[option.name],+ })+ return `${option.name.toUpperCase().replace('VAULT_', '')}=${decryptedValue[0].decrypted_secret}`+ }+ return `${option.name.toUpperCase().replace('.', '_')}=${values[option.name]}`+ })+ ).then((values) => values.join('\n'))++ copyToClipboard(envFile, () => {+ toast.success('Copied to clipboard')+ setIsLoading(false)+ })+ }, [serverOptions, values])++ return (+ <ButtonTooltip+ type="primary"+ loading={isLoading}+ icon={<Copy />}+ onClick={onCopy}+ tooltip={{+ content: {+ text: (+ <span>+ Copies an <span className="text-brand">.env file</span> with the configuration details+ to your clipboard.+ </span>+ ),+ },+ }}+ >+ Copy env values+ </ButtonTooltip>+ )+}diff --git a/apps/studio/components/to-be-cleaned/Storage/AnalyticBucketDetails/DecryptedReadOnlyInput.tsx b/apps/studio/components/to-be-cleaned/Storage/AnalyticBucketDetails/DecryptedReadOnlyInput.tsxnew file mode 100644index 00000000000..e22c8a8e694--- /dev/null+++ b/apps/studio/components/to-be-cleaned/Storage/AnalyticBucketDetails/DecryptedReadOnlyInput.tsx@@ -0,0 +1,70 @@+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'+import { useVaultSecretDecryptedValueQuery } from 'data/vault/vault-secret-decrypted-value-query'+import { Eye, EyeOff, Loader } from 'lucide-react'+import { useState } from 'react'+import { Button, Input } from 'ui'++export const DecryptedReadOnlyInput = ({+ value,+ secureEntry,+ descriptionText,+ label,+}: {+ value?: string+ secureEntry: boolean+ descriptionText: string+ label: string+}) => {+ const [showHidden, setShowHidden] = useState(false)+ const { project } = useProjectContext()++ const { isLoading: isDecryptedValueLoading, data: decryptedValue } =+ useVaultSecretDecryptedValueQuery(+ {+ projectRef: project?.ref,+ connectionString: project?.connectionString,+ id: value ?? '',+ },+ { enabled: secureEntry && showHidden }+ )++ const isLoading = isDecryptedValueLoading && showHidden++ return (+ <Input+ label={label}+ readOnly+ copy+ disabled+ value={+ secureEntry+ ? isLoading+ ? 'Fetching value from Vault...'+ : showHidden+ ? decryptedValue+ : value+ : value+ }+ type={secureEntry ? (isLoading ? 'text' : showHidden ? 'text' : 'password') : 'text'}+ descriptionText={descriptionText}+ layout="horizontal"+ actions={+ secureEntry ? (+ isLoading ? (+ <div className="flex items-center justify-center mr-1">+ <Button disabled type="default" icon={<Loader className="animate-spin" />} />+ </div>+ ) : (+ <div className="flex items-center justify-center mr-1">+ <Button+ type="default"+ icon={showHidden ? <Eye /> : <EyeOff />}+ onClick={() => setShowHidden(!showHidden)}+ />+ </div>+ )+ ) : null+ }+ />+ )+}diff --git a/apps/studio/components/to-be-cleaned/Storage/AnalyticBucketDetails/NamespaceRow.tsx b/apps/studio/components/to-be-cleaned/Storage/AnalyticBucketDetails/NamespaceRow.tsxnew file mode 100644index 00000000000..80d75a33da4--- /dev/null+++ b/apps/studio/components/to-be-cleaned/Storage/AnalyticBucketDetails/NamespaceRow.tsx@@ -0,0 +1,132 @@+import { RefreshCw, SquareArrowOutUpRight } from 'lucide-react'+import { useMemo, useState } from 'react'++import { FormattedWrapperTable } from 'components/interfaces/Integrations/Wrappers/Wrappers.utils'+import { ImportForeignSchemaDialog } from 'components/interfaces/Storage/ImportForeignSchemaDialog'+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'+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 { Badge, Button, TableCell, TableRow } from 'ui'++type NamespaceRowProps = {+ bucketName: string+ namespace: string+ schema: string+ excludedSchemas: string[]+ tables: (FormattedWrapperTable & { id: number })[]+ token: string+ wrapperInstance: FDW+ wrapperValues: Record<string, string>+}++export const NamespaceRow = ({+ bucketName,+ namespace,+ schema,+ excludedSchemas,+ tables,+ token,+ wrapperInstance,+ wrapperValues,+}: NamespaceRowProps) => {+ const { project } = useProjectContext()+ const [importForeignSchemaShown, setImportForeignSchemaShown] = useState(false)++ const targetSchema = tables[0]?.schema_name ?? ''++ 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: targetSchema,+ })+ }++ 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>+ <Badge variant="brand">{namespace}</Badge>+ </TableCell>+ <TableCell className="text-foreground-light">{schema && <Badge>{schema}</Badge>}</TableCell>+ <TableCell className="text-foreground-light text-center">+ {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 ? (+ <a+ href={`${BASE_PATH}/project/${project?.ref}/editor?schema=${schema}`}+ target="_blank"+ rel="noreferrer"+ >+ <Button type="default" icon={<SquareArrowOutUpRight />}>+ Table Editor+ </Button>+ </a>+ ) : (+ <ButtonTooltip+ type="default"+ icon={<SquareArrowOutUpRight />}+ disabled+ tooltip={{+ content: { text: 'There are no tables connected.' },+ }}+ >+ Table Editor+ </ButtonTooltip>+ )}+ </div>+ </TableCell>+ <ImportForeignSchemaDialog+ bucketName={bucketName}+ namespace={namespace}+ excludedSchemas={excludedSchemas}+ wrapperValues={wrapperValues}+ visible={importForeignSchemaShown}+ onClose={() => setImportForeignSchemaShown(false)}+ />+ </TableRow>+ )+}diff --git a/apps/studio/components/to-be-cleaned/Storage/AnalyticBucketDetails/SimpleConfigurationDetails.tsx b/apps/studio/components/to-be-cleaned/Storage/AnalyticBucketDetails/SimpleConfigurationDetails.tsxnew file mode 100644index 00000000000..feccb8aa02f--- /dev/null+++ b/apps/studio/components/to-be-cleaned/Storage/AnalyticBucketDetails/SimpleConfigurationDetails.tsx@@ -0,0 +1,69 @@+import Link from '@ui/components/Typography/Link'+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'+import { ScaffoldSectionDescription, ScaffoldSectionTitle } from 'components/layouts/Scaffold'+import { useProjectSettingsV2Query } from 'data/config/project-settings-v2-query'+import { Card } from 'ui'+import { getCatalogURI, getConnectionURL } from '../StorageSettings/StorageSettings.utils'+import { DESCRIPTIONS } from './constants'+import { CopyEnvButton } from './CopyEnvButton'+import { DecryptedReadOnlyInput } from './DecryptedReadOnlyInput'++const wrapperMeta = {+ options: [+ { name: 'vault_token', label: 'Vault Token', secureEntry: false },+ { name: 'warehouse', label: 'Warehouse', secureEntry: false },+ { name: 's3.endpoint', label: 'S3 Endpoint', secureEntry: false },+ { name: 'catalog_uri', label: 'Catalog URI', secureEntry: false },+ ],+}++export const SimpleConfigurationDetails = ({ bucketName }: { bucketName: string }) => {+ const { project } = useProjectContext()+ const { data: settings } = useProjectSettingsV2Query({ projectRef: project?.ref })+ const protocol = settings?.app_config?.protocol ?? 'https'+ const endpoint = settings?.app_config?.endpoint+ const serviceApiKey =+ (settings?.service_api_keys ?? []).find((key) => key.tags === 'service_role')?.api_key ??+ 'SUPABASE_CLIENT_SERVICE_KEY'++ const values: Record<string, string> = {+ vault_token: serviceApiKey,+ warehouse: bucketName,+ 's3.endpoint': getConnectionURL(project?.ref ?? '', protocol, endpoint),+ catalog_uri: getCatalogURI(project?.ref ?? '', protocol, endpoint),+ }++ return (+ <div>+ <div className="flex flex-row justify-between items-center">+ <div>+ <ScaffoldSectionTitle>Configuration Details</ScaffoldSectionTitle>+ <ScaffoldSectionDescription className="mb-4">+ You can use the following configuration details to connect to the bucket from your code.+ </ScaffoldSectionDescription>+ </div>+ <CopyEnvButton serverOptions={wrapperMeta.options} values={values} />+ </div>+ <Card className="flex flex-col gap-6 p-6 pb-0">+ <p className="text-sm text-foreground-light mb-4">+ To get AWS credentials, you can create them using the{' '}+ <Link href={`/project/${project?.ref}/settings/storage`}>+ <a className="underline ">S3 Access Keys</a>+ </Link>{' '}+ feature.+ </p>+ {wrapperMeta.options.map((option) => {+ return (+ <DecryptedReadOnlyInput+ key={option.name}+ label={option.label}+ value={values[option.name]}+ secureEntry={option.secureEntry}+ descriptionText={DESCRIPTIONS[option.name]}+ />+ )+ })}+ </Card>+ </div>+ )+}diff --git a/apps/studio/components/to-be-cleaned/Storage/AnalyticBucketDetails/constants.ts b/apps/studio/components/to-be-cleaned/Storage/AnalyticBucketDetails/constants.tsnew file mode 100644index 00000000000..c9851d3bef3--- /dev/null+++ b/apps/studio/components/to-be-cleaned/Storage/AnalyticBucketDetails/constants.ts@@ -0,0 +1,26 @@+export const OPTION_ORDER = [+ 'catalog_uri',+ 'vault_token',+ 'warehouse',+ 's3.endpoint',+ 'vault_aws_access_key_id',+ 'vault_aws_secret_access_key',+]++export const LABELS: Record<string, string> = {+ vault_aws_access_key_id: 'S3 Access Key ID',+ vault_aws_secret_access_key: 'S3 Secret Access Key',+ vault_token: 'Catalog Token',+ warehouse: 'Warehouse Name',+ 's3.endpoint': 'S3 Endpoint',+ catalog_uri: 'Catalog URI',+}++export const DESCRIPTIONS: Record<string, string> = {+ vault_aws_access_key_id: 'Matches the AWS access key ID from a S3 Access Key.',+ vault_aws_secret_access_key: 'Matches the AWS secret access from a S3 Access Key.',+ vault_token: 'Corresponds to the service role key.',+ warehouse: 'Matches the name of the bucket.',+ 's3.endpoint': '',+ catalog_uri: '',+}diff --git a/apps/studio/components/to-be-cleaned/Storage/AnalyticBucketDetails/index.tsx b/apps/studio/components/to-be-cleaned/Storage/AnalyticBucketDetails/index.tsxnew file mode 100644index 00000000000..49aead6e1f0--- /dev/null+++ b/apps/studio/components/to-be-cleaned/Storage/AnalyticBucketDetails/index.tsx@@ -0,0 +1,403 @@+import { snakeCase, uniq } from 'lodash'+import Link from 'next/link'+import { useMemo } from 'react'++import { INTEGRATIONS } from 'components/interfaces/Integrations/Landing/Integrations.constants'+import { WRAPPER_HANDLERS } from 'components/interfaces/Integrations/Wrappers/Wrappers.constants'+import { WrapperMeta } from 'components/interfaces/Integrations/Wrappers/Wrappers.types'+import {+ convertKVStringArrayToJson,+ formatWrapperTables,+ wrapperMetaComparator,+} from 'components/interfaces/Integrations/Wrappers/Wrappers.utils'+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'+import {+ ScaffoldContainer,+ ScaffoldHeader,+ ScaffoldSectionDescription,+ ScaffoldSectionTitle,+ ScaffoldTitle,+} from 'components/layouts/Scaffold'+import { DocsButton } from 'components/ui/DocsButton'+import {+ DatabaseExtension,+ useDatabaseExtensionsQuery,+} from 'data/database-extensions/database-extensions-query'+import { useFDWsQuery } from 'data/fdw/fdws-query'+import { Bucket } from 'data/storage/buckets-query'+import { useIcebergNamespacesQuery } from 'data/storage/iceberg-namespaces-query'+import { useIcebergWrapperCreateMutation } from 'data/storage/iceberg-wrapper-create-mutation'+import { useVaultSecretDecryptedValueQuery } from 'data/vault/vault-secret-decrypted-value-query'+import {+ Alert_Shadcn_,+ AlertDescription_Shadcn_,+ AlertTitle_Shadcn_,+ Button,+ Card,+ Table,+ TableBody,+ TableHead,+ TableHeader,+ TableRow,+ WarningIcon,+} from 'ui'+import { GenericSkeletonLoader } from 'ui-patterns/ShimmeringLoader'+import { DESCRIPTIONS, LABELS, OPTION_ORDER } from './constants'+import { CopyEnvButton } from './CopyEnvButton'+import { DecryptedReadOnlyInput } from './DecryptedReadOnlyInput'+import { NamespaceRow } from './NamespaceRow'+import { SimpleConfigurationDetails } from './SimpleConfigurationDetails'+import { useIcebergWrapperExtension } from './useIcebergWrapper'++export const AnalyticBucketDetails = ({ bucket }: { bucket: Bucket }) => {+ const { project } = useProjectContext()++ const { data: extensionsData } = useDatabaseExtensionsQuery({+ projectRef: project?.ref,+ connectionString: project?.connectionString,+ })++ const { data, isLoading: isFDWsLoading } = useFDWsQuery({+ projectRef: project?.ref,+ connectionString: project?.connectionString,+ })++ /** The wrapper instance is the wrapper that is installed for this Analytics bucket. */+ const wrapperInstance = useMemo(() => {+ return data+ ?.filter((wrapper) =>+ wrapperMetaComparator(+ {+ handlerName: WRAPPER_HANDLERS.ICEBERG,+ server: {+ options: [],+ },+ },+ wrapper+ )+ )+ .find((w) => w.name === snakeCase(`${bucket.name}_fdw`))+ }, [data, bucket.name])++ const extensionState = useIcebergWrapperExtension()++ const integration = INTEGRATIONS.find((i) => i.id === 'iceberg_wrapper' && i.type === 'wrapper')++ const wrapperValues = convertKVStringArrayToJson(wrapperInstance?.server_options ?? [])+ const wrapperMeta = (integration?.type === 'wrapper' && integration.meta) as WrapperMeta++ const { data: token, isSuccess: isSuccessToken } = useVaultSecretDecryptedValueQuery(+ {+ projectRef: project?.ref,+ connectionString: project?.connectionString,+ id: wrapperValues.vault_token,+ },+ {+ enabled: wrapperValues.vault_token !== undefined,+ }+ )++ const { data: namespacesData, isLoading: isLoadingNamespaces } = useIcebergNamespacesQuery(+ {+ catalogUri: wrapperValues.catalog_uri,+ warehouse: wrapperValues.warehouse,+ token: token!,+ },+ { enabled: isSuccessToken }+ )++ const wrapperTables = useMemo(() => {+ if (!wrapperInstance) return []++ return formatWrapperTables(wrapperInstance, wrapperMeta!)+ }, [wrapperInstance, wrapperMeta])++ const namespaces = useMemo(() => {+ const fdwNamespaces = wrapperTables.map((t) => t.table.split('.')[0]) as string[]+ const namespaces = uniq([...fdwNamespaces, ...(namespacesData ?? [])])++ return namespaces.map((namespace) => {+ const tables = wrapperTables.filter((t) => t.table.split('.')[0] === namespace)+ const schema = tables[0]?.schema++ return {+ namespace: namespace,+ schema: schema,+ tables: tables,+ }+ })+ }, [wrapperTables, namespacesData])+ const excludedSchemas = uniq(namespaces.map((n) => n.schema))++ const wrappersExtension = extensionsData?.find((ext) => ext.name === 'wrappers')++ const state = isFDWsLoading+ ? 'loading'+ : extensionState === 'installed'+ ? wrapperInstance+ ? 'added'+ : 'missing'+ : extensionState++ return (+ <div className="flex flex-col w-full">+ <ScaffoldContainer className="flex flex-row justify-between items-center gap-10">+ <ScaffoldHeader>+ <ScaffoldTitle>+ Analytics Bucket <span className="text-brand">{bucket.name}</span>+ </ScaffoldTitle>+ <ScaffoldSectionDescription>+ Namespaces and tables connected to this bucket.+ </ScaffoldSectionDescription>+ </ScaffoldHeader>+ <DocsButton href="https://supabase.com/docs/guides/storage/analytics/introduction" />+ </ScaffoldContainer>+ <ScaffoldContainer className="flex flex-col gap-4" bottomPadding>+ {state === 'loading' && <GenericSkeletonLoader />}+ {state === 'not-installed' && (+ <ExtensionNotInstalled+ bucketName={bucket.name}+ projectRef={project?.ref!}+ wrapperMeta={wrapperMeta}+ wrappersExtension={wrappersExtension!}+ />+ )}+ {state === 'needs-upgrade' && (+ <ExtensionNeedsUpgrade+ bucketName={bucket.name}+ projectRef={project?.ref!}+ wrapperMeta={wrapperMeta}+ wrappersExtension={wrappersExtension!}+ />+ )}+ {state === 'added' && wrapperInstance && (+ <>+ <div className="flex flex-col gap-4">+ {isLoadingNamespaces || isFDWsLoading ? (+ <GenericSkeletonLoader />+ ) : namespaces.length === 0 ? (+ <Card className="flex flex-col px-20 py-16 items-center justify-center space-y-3">+ <p className="text-sm text-foreground-light">No namespaces in this bucket</p>+ <p className="text-sm text-foreground-lighter">+ Create a namespace and add some data{' '}+ <a+ target="_blank"+ rel="noreferrer"+ className="text-brand underline"+ href="https://supabase.com/docs/guides/storage/analytics/connecting-to-analytics-bucket"+ >+ {' '}+ to get started+ </a>+ </p>+ </Card>+ ) : (+ <Card>+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead className="text-center">Namespace</TableHead>+ <TableHead className="text-center">Schema</TableHead>+ <TableHead className="text-center">Tables</TableHead>+ <TableHead className="text-center">Actions</TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {namespaces.map(({ namespace, schema, tables }) => (+ <NamespaceRow+ key={namespace}+ bucketName={bucket.name}+ namespace={namespace}+ schema={schema}+ excludedSchemas={excludedSchemas}+ tables={tables as any}+ token={token!}+ wrapperInstance={wrapperInstance}+ wrapperValues={wrapperValues}+ />+ ))}+ </TableBody>+ </Table>+ </Card>+ )}+ </div>++ <div>+ <div className="flex flex-row justify-between items-center">+ <div>+ <ScaffoldSectionTitle>Connection Details</ScaffoldSectionTitle>+ <ScaffoldSectionDescription className="mb-4">+ You can use the following parameters to connect to the bucket from an Iceberg+ client.+ </ScaffoldSectionDescription>+ </div>+ <div className="flex flex-row gap-2">+ <CopyEnvButton+ serverOptions={wrapperMeta.server.options.filter(+ (option) => !option.hidden && wrapperValues[option.name]+ )}+ values={wrapperValues}+ />+ <DocsButton href="https://supabase.com/docs/guides/storage/analytics/connecting-to-analytics-bucket" />+ </div>+ </div>+ <Card className="flex flex-col gap-8 p-6">+ {wrapperMeta.server.options+ .filter((option) => !option.hidden && wrapperValues[option.name])+ .sort((a, b) => OPTION_ORDER.indexOf(a.name) - OPTION_ORDER.indexOf(b.name))+ .map((option) => {+ return (+ <DecryptedReadOnlyInput+ key={option.name}+ label={LABELS[option.name]}+ value={wrapperValues[option.name]}+ secureEntry={option.secureEntry}+ descriptionText={DESCRIPTIONS[option.name]}+ />+ )+ })}+ </Card>+ </div>+ </>+ )}+ {state === 'missing' && <WrapperMissing bucketName={bucket.name} />}+ </ScaffoldContainer>+ </div>+ )+}++const ExtensionNotInstalled = ({+ bucketName,+ projectRef,+ wrapperMeta,+ wrappersExtension,+}: {+ bucketName: string+ projectRef: string+ wrapperMeta: WrapperMeta+ wrappersExtension: DatabaseExtension+}) => {+ const databaseNeedsUpgrading =+ (wrappersExtension?.default_version ?? '') < (wrapperMeta?.minimumExtensionVersion ?? '')++ return (+ <>+ <Alert_Shadcn_ variant="warning">+ <WarningIcon />+ <AlertTitle_Shadcn_>+ You need to install the wrappers extension to connect this Analytics bucket to the+ database.+ </AlertTitle_Shadcn_>+ <AlertDescription_Shadcn_ className="flex flex-col gap-y-2">+ <p>+ The {wrapperMeta.label} wrapper requires the Wrappers extension to be installed. You can+ install version {wrappersExtension?.installed_version}+ {databaseNeedsUpgrading &&+ ' which is below the minimum version that supports Iceberg wrapper'}+ . Please {databaseNeedsUpgrading && 'upgrade your database then '}install the{' '}+ <code className="text-xs">wrappers</code> extension to create this wrapper.+ </p>+ </AlertDescription_Shadcn_>+ <AlertDescription_Shadcn_ className="mt-3">+ <Button asChild type="default">+ <Link+ href={+ databaseNeedsUpgrading+ ? `/project/${projectRef}/settings/infrastructure`+ : `/project/${projectRef}/database/extensions?filter=wrappers`+ }+ >+ {databaseNeedsUpgrading ? 'Upgrade database' : 'Install wrappers extension'}+ </Link>+ </Button>+ </AlertDescription_Shadcn_>+ </Alert_Shadcn_>+ <SimpleConfigurationDetails bucketName={bucketName} />+ </>+ )+}++const ExtensionNeedsUpgrade = ({+ bucketName,+ projectRef,+ wrapperMeta,+ wrappersExtension,+}: {+ bucketName: string+ projectRef: string+ wrapperMeta: WrapperMeta+ wrappersExtension: DatabaseExtension+}) => {+ // [Joshen] Default version is what's on the DB, so if the installed version is already the default version+ // but still doesnt meet the minimum extension version, then DB upgrade is required+ const databaseNeedsUpgrading =+ wrappersExtension?.installed_version === wrappersExtension?.default_version++ return (+ <>+ <Alert_Shadcn_ variant="warning">+ <WarningIcon />+ <AlertTitle_Shadcn_>+ Your extension version is outdated for this wrapper.+ </AlertTitle_Shadcn_>+ <AlertDescription_Shadcn_ className="flex flex-col gap-y-2">+ <p>+ The {wrapperMeta.label} wrapper requires a minimum extension version of{' '}+ {wrapperMeta.minimumExtensionVersion}. You have version{' '}+ {wrappersExtension?.installed_version} installed. Please{' '}+ {databaseNeedsUpgrading && 'upgrade your database then '}update the extension by+ disabling and enabling the <code className="text-xs">wrappers</code> extension to create+ this wrapper.+ </p>+ <p className="text-warning">+ Warning: Before reinstalling the wrapper extension, you must first remove all existing+ wrappers. Afterward, you can recreate the wrappers.+ </p>+ </AlertDescription_Shadcn_>+ <AlertDescription_Shadcn_ className="mt-3">+ <Button asChild type="default">+ <Link+ href={+ databaseNeedsUpgrading+ ? `/project/${projectRef}/settings/infrastructure`+ : `/project/${projectRef}/database/extensions?filter=wrappers`+ }+ >+ {databaseNeedsUpgrading ? 'Upgrade database' : 'View wrappers extension'}+ </Link>+ </Button>+ </AlertDescription_Shadcn_>+ </Alert_Shadcn_>+ <SimpleConfigurationDetails bucketName={bucketName} />+ </>+ )+}++const WrapperMissing = ({ bucketName }: { bucketName: string }) => {+ const { mutateAsync: createIcebergWrapper, isLoading: isCreatingIcebergWrapper } =+ useIcebergWrapperCreateMutation()++ const onSetupWrapper = async () => {+ await createIcebergWrapper({ bucketName })+ }++ return (+ <>+ <Alert_Shadcn_ variant="warning">+ <WarningIcon />+ <AlertTitle_Shadcn_>+ This Analytics bucket does not have a foreign data wrapper setup.+ </AlertTitle_Shadcn_>+ <AlertDescription_Shadcn_ className="flex flex-col gap-y-2">+ <p>You need to setup a wrapper to connect this bucket to the database.</p>+ </AlertDescription_Shadcn_>+ <AlertDescription_Shadcn_ className="mt-3">+ <Button type="default" loading={isCreatingIcebergWrapper} onClick={onSetupWrapper}>+ Setup a wrapper+ </Button>+ </AlertDescription_Shadcn_>+ </Alert_Shadcn_>+ <SimpleConfigurationDetails bucketName={bucketName} />+ </>+ )+}diff --git a/apps/studio/components/to-be-cleaned/Storage/AnalyticBucketDetails/useIcebergWrapper.tsx b/apps/studio/components/to-be-cleaned/Storage/AnalyticBucketDetails/useIcebergWrapper.tsxnew file mode 100644index 00000000000..56387d46095--- /dev/null+++ b/apps/studio/components/to-be-cleaned/Storage/AnalyticBucketDetails/useIcebergWrapper.tsx@@ -0,0 +1,35 @@+import { INTEGRATIONS } from 'components/interfaces/Integrations/Landing/Integrations.constants'+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'+import { useDatabaseExtensionsQuery } from 'data/database-extensions/database-extensions-query'++export const useIcebergWrapperExtension = () => {+ const { project } = useProjectContext()+ const { data: extensionsData, isLoading: isExtensionsLoading } = useDatabaseExtensionsQuery({+ projectRef: project?.ref,+ connectionString: project?.connectionString,+ })++ const integration = INTEGRATIONS.find((i) => i.id === 'iceberg_wrapper')++ if (!integration || integration.type !== 'wrapper') {+ // This should never happen+ return 'not-found'+ }++ const wrapperMeta = integration.meta++ const wrappersExtension = extensionsData?.find((ext) => ext.name === 'wrappers')+ const isWrappersExtensionInstalled = !!wrappersExtension?.installed_version+ const hasRequiredVersion =+ (wrappersExtension?.installed_version ?? '') >= (wrapperMeta?.minimumExtensionVersion ?? '')++ const state = isExtensionsLoading+ ? 'loading'+ : isWrappersExtensionInstalled+ ? hasRequiredVersion+ ? 'installed'+ : 'needs-upgrade'+ : ('not-installed' as const)++ return state+}diff --git a/apps/studio/components/to-be-cleaned/Storage/DeleteBucketModal.tsx b/apps/studio/components/to-be-cleaned/Storage/DeleteBucketModal.tsxindex a02f950e8e2..ac7293b105c 100644--- a/apps/studio/components/to-be-cleaned/Storage/DeleteBucketModal.tsx+++ b/apps/studio/components/to-be-cleaned/Storage/DeleteBucketModal.tsx@@ -73,7 +73,7 @@ const DeleteBucketModal = ({ visible = false, bucket, onClose }: DeleteBucketModconst onDeleteBucket = async () => {if (!projectRef) return console.error('Project ref is required')if (!bucket) return console.error('No bucket is selected')- deleteBucket({ projectRef, id: bucket.id })+ deleteBucket({ projectRef, id: bucket.id, type: bucket.type })}return (diff --git a/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/StorageExplorer.tsx b/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/StorageExplorer.tsxindex a268b1aaeff..cfc8ecd5c40 100644--- a/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/StorageExplorer.tsx+++ b/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/StorageExplorer.tsx@@ -167,7 +167,7 @@ const StorageExplorer = ({ bucket }: StorageExplorerProps) => {return (<divref={storageExplorerRef}- className="bg-studio border rounded-md border-overlay flex h-full w-full flex-col"+ className="bg-studio border rounded-md border-overlay flex h-full w-full flex-col m-4">{selectedItems.length === 0 ? (<FileExplorerHeaderdiff --git a/apps/studio/components/to-be-cleaned/Storage/StorageSettings/StorageSettings.utils.ts b/apps/studio/components/to-be-cleaned/Storage/StorageSettings/StorageSettings.utils.tsindex 1cea637616b..e57efdba891 100644--- a/apps/studio/components/to-be-cleaned/Storage/StorageSettings/StorageSettings.utils.ts+++ b/apps/studio/components/to-be-cleaned/Storage/StorageSettings/StorageSettings.utils.ts@@ -25,10 +25,20 @@ export const convertToBytes = (size: number, unit: StorageSizeUnits = StorageSizreturn size * Math.pow(k, i)}-export function getConnectionURL(projectRef: string, protocol: string, endpoint?: string) {+function getStorageURL(projectRef: string, protocol: string, endpoint?: string) {const projUrl = endpoint ? `${protocol}://${endpoint}` : `https://${projectRef}.supabase.co`-const url = new URL(projUrl)+ return url+}++export function getConnectionURL(projectRef: string, protocol: string, endpoint?: string) {+ const url = getStorageURL(projectRef, protocol, endpoint)url.pathname = '/storage/v1/s3'return url.toString()}++export function getCatalogURI(projectRef: string, protocol: string, endpoint?: string) {+ const url = getStorageURL(projectRef, protocol, endpoint)+ url.pathname = '/storage/v1/iceberg'+ return url.toString()+}diff --git a/apps/studio/data/fdw/fdw-create-mutation.ts b/apps/studio/data/fdw/fdw-create-mutation.tsindex c2d203dca6a..c0962350421 100644--- a/apps/studio/data/fdw/fdw-create-mutation.ts+++ b/apps/studio/data/fdw/fdw-create-mutation.ts@@ -20,7 +20,8 @@ export type FDWCreateVariables = {formState: {[k: string]: string}- mode: 'tables' | 'schema'+ // If mode is skip, the wrapper will skip the last step, binding the schema/tables to foreign data. This could be done later.+ mode: 'tables' | 'schema' | 'skip'tables: any[]sourceSchema: stringtargetSchema: string@@ -43,9 +44,9 @@ export function getCreateFDWSql({.join('\n')const createWrapperSql = /* SQL */ `- create foreign data wrapper ${formState.wrapper_name}- handler ${wrapperMeta.handlerName}- validator ${wrapperMeta.validatorName};+ create foreign data wrapper "${formState.wrapper_name}"+ handler "${wrapperMeta.handlerName}"+ validator "${wrapperMeta.validatorName}";`const encryptedOptions = wrapperMeta.server.options.filter((option) => option.encrypted)@@ -170,7 +171,7 @@ export function getCreateFDWSql({.join('\n')}execute format(- E'create server ${formState.server_name} foreign data wrapper ${formState.wrapper_name} options (${optionsSqlArray});',+ E'create server "${formState.server_name}" foreign data wrapper "${formState.wrapper_name}" options (${optionsSqlArray});',${encryptedOptions.filter((option) => formState[option.name]).map((option) => `v_${option.name}`)@@ -233,7 +234,7 @@ export async function createFDW({ projectRef, connectionString, ...rest }: FDWCrreturn result}-type FDWCreateData = Awaited<ReturnType<typeof createFDW>>+export type FDWCreateData = Awaited<ReturnType<typeof createFDW>>export const useFDWCreateMutation = ({onSuccess,diff --git a/apps/studio/data/fdw/fdw-import-foreign-schema-mutation.ts b/apps/studio/data/fdw/fdw-import-foreign-schema-mutation.tsnew file mode 100644index 00000000000..81d257b57e4--- /dev/null+++ b/apps/studio/data/fdw/fdw-import-foreign-schema-mutation.ts@@ -0,0 +1,78 @@+import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'+import { toast } from 'sonner'++import { entityTypeKeys } from 'data/entity-types/keys'+import { foreignTableKeys } from 'data/foreign-tables/keys'+import { executeSql } from 'data/sql/execute-sql-query'+import { wrapWithTransaction } from 'data/sql/utils/transaction'+import { vaultSecretsKeys } from 'data/vault/keys'+import type { ResponseError } from 'types'+import { fdwKeys } from './keys'++export type FDWImportForeignSchemaVariables = {+ projectRef?: string+ connectionString?: string | null+ serverName: string+ sourceSchema: string+ targetSchema: string+}++export function getImportForeignSchemaSql({+ serverName,+ sourceSchema,+ targetSchema,+}: Pick<FDWImportForeignSchemaVariables, 'serverName' | 'sourceSchema' | 'targetSchema'>) {+ const sql = /* SQL */ `+ import foreign schema "${sourceSchema}" from server ${serverName} into ${targetSchema};+`+ return sql+}++export async function importForeignSchema({+ projectRef,+ connectionString,+ ...rest+}: FDWImportForeignSchemaVariables) {+ const sql = wrapWithTransaction(getImportForeignSchemaSql(rest))+ const { result } = await executeSql({ projectRef, connectionString, sql })+ return result+}++type ImportForeignSchemaData = Awaited<ReturnType<typeof importForeignSchema>>++export const useFDWImportForeignSchemaMutation = ({+ onSuccess,+ onError,+ ...options+}: Omit<+ UseMutationOptions<ImportForeignSchemaData, ResponseError, FDWImportForeignSchemaVariables>,+ 'mutationFn'+> = {}) => {+ const queryClient = useQueryClient()++ return useMutation<ImportForeignSchemaData, ResponseError, FDWImportForeignSchemaVariables>(+ (vars) => importForeignSchema(vars),+ {+ async onSuccess(data, variables, context) {+ const { projectRef } = variables++ await Promise.all([+ queryClient.invalidateQueries(fdwKeys.list(projectRef), { refetchType: 'all' }),+ queryClient.invalidateQueries(entityTypeKeys.list(projectRef)),+ queryClient.invalidateQueries(foreignTableKeys.list(projectRef)),+ queryClient.invalidateQueries(vaultSecretsKeys.list(projectRef)),+ ])++ await onSuccess?.(data, variables, context)+ },+ async onError(data, variables, context) {+ if (onError === undefined) {+ toast.error(`Failed to import schema for foreign data wrapper: ${data.message}`)+ } else {+ onError(data, variables, context)+ }+ },+ ...options,+ }+ )+}diff --git a/apps/studio/data/storage/bucket-create-mutation.ts b/apps/studio/data/storage/bucket-create-mutation.tsindex 81dc63d8b17..adfde525a43 100644--- a/apps/studio/data/storage/bucket-create-mutation.ts+++ b/apps/studio/data/storage/bucket-create-mutation.ts@@ -6,12 +6,9 @@ import { handleError, post } from 'data/fetchers'import type { ResponseError } from 'types'import { storageKeys } from './keys'-export type BucketCreateVariables = {+export type BucketCreateVariables = Omit<CreateStorageBucketBody, 'public'> & {projectRef: string- id: stringisPublic: boolean- file_size_limit: number | null- allowed_mime_types: string[] | null}type CreateStorageBucketBody = components['schemas']['CreateStorageBucketBody']@@ -19,6 +16,7 @@ type CreateStorageBucketBody = components['schemas']['CreateStorageBucketBody']export async function createBucket({projectRef,id,+ type,isPublic,file_size_limit,allowed_mime_types,@@ -26,13 +24,15 @@ export async function createBucket({if (!projectRef) throw new Error('projectRef is required')if (!id) throw new Error('Bucket name is required')- const payload: Partial<CreateStorageBucketBody> = { id, public: isPublic }- if (file_size_limit) payload.file_size_limit = file_size_limit- if (allowed_mime_types) payload.allowed_mime_types = allowed_mime_types+ const payload: CreateStorageBucketBody = { id, type, public: isPublic }+ if (type === 'STANDARD') {+ if (file_size_limit) payload.file_size_limit = file_size_limit+ if (allowed_mime_types) payload.allowed_mime_types = allowed_mime_types+ }const { data, error } = await post('/platform/storage/{ref}/buckets', {params: { path: { ref: projectRef } },- body: payload as CreateStorageBucketBody,+ body: payload,})if (error) handleError(error)diff --git a/apps/studio/data/storage/bucket-delete-mutation.ts b/apps/studio/data/storage/bucket-delete-mutation.tsindex 2333e5839a9..a623863551d 100644--- a/apps/studio/data/storage/bucket-delete-mutation.ts+++ b/apps/studio/data/storage/bucket-delete-mutation.ts@@ -3,25 +3,29 @@ import { toast } from 'sonner'import { del, handleError, post } from 'data/fetchers'import type { ResponseError } from 'types'+import { BucketType } from './buckets-query'import { storageKeys } from './keys'export type BucketDeleteVariables = {projectRef: stringid: string+ type: BucketType}-export async function deleteBucket({ projectRef, id }: BucketDeleteVariables) {+export async function deleteBucket({ projectRef, id, type }: BucketDeleteVariables) {if (!projectRef) throw new Error('projectRef is required')if (!id) throw new Error('Bucket name is requried')- const { error: emptyBucketError } = await post('/platform/storage/{ref}/buckets/{id}/empty', {- params: { path: { ref: projectRef, id } },- })- if (emptyBucketError) handleError(emptyBucketError)+ if (type !== 'ANALYTICS') {+ const { error: emptyBucketError } = await post('/platform/storage/{ref}/buckets/{id}/empty', {+ params: { path: { ref: projectRef, id } },+ })+ if (emptyBucketError) handleError(emptyBucketError)+ }const { data, error: deleteBucketError } = await del('/platform/storage/{ref}/buckets/{id}', {- params: { path: { ref: projectRef, id } },- })+ params: { path: { ref: projectRef, id }, query: { type } },+ } as any)if (deleteBucketError) handleError(deleteBucketError)return data}diff --git a/apps/studio/data/storage/buckets-query.ts b/apps/studio/data/storage/buckets-query.tsindex 1684a4ca86b..e26887d1a8f 100644--- a/apps/studio/data/storage/buckets-query.ts+++ b/apps/studio/data/storage/buckets-query.ts@@ -1,5 +1,6 @@import { useQuery, UseQueryOptions } from '@tanstack/react-query'+import { components } from 'api-types'import { get, handleError } from 'data/fetchers'import { useSelectedProject } from 'hooks/misc/useSelectedProject'import { PROJECT_STATUS } from 'lib/constants'@@ -8,16 +9,9 @@ import { storageKeys } from './keys'export type BucketsVariables = { projectRef?: string }-export type Bucket = {- id: string- name: string- owner: string- public: boolean- created_at: string- updated_at: string- file_size_limit: null | number- allowed_mime_types: null | string[]-}+export type Bucket = components['schemas']['StorageBucketResponse']++export type BucketType = Bucket['type']export async function getBuckets({ projectRef }: BucketsVariables, signal?: AbortSignal) {if (!projectRef) throw new Error('projectRef is required')diff --git a/apps/studio/data/storage/iceberg-namespace-create-mutation.ts b/apps/studio/data/storage/iceberg-namespace-create-mutation.tsnew file mode 100644index 00000000000..58f93dd4bd4--- /dev/null+++ b/apps/studio/data/storage/iceberg-namespace-create-mutation.ts@@ -0,0 +1,89 @@+import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'+import { toast } from 'sonner'++import { constructHeaders, fetchHandler, handleError } from 'data/fetchers'+import type { ResponseError } from 'types'+import { storageKeys } from './keys'++type CreateIcebergNamespaceVariables = {+ catalogUri: string+ warehouse: string+ token: string+ namespace: string+}++async function createIcebergNamespace({+ catalogUri,+ warehouse,+ token,+ namespace,+}: CreateIcebergNamespaceVariables) {+ const headers = await constructHeaders({+ 'Content-Type': 'application/json',+ Authorization: `Bearer ${token}`,+ })++ const url = `${catalogUri}/v1/${warehouse}/namespaces`.replaceAll(/(?<!:)\/\//g, '/')++ try {+ const response = await fetchHandler(url, {+ headers,+ method: 'POST',+ body: JSON.stringify({+ namespace: namespace,+ }),+ })++ const result = await response.json()+ if (result.error) {+ if (result.error.message) {+ throw new Error(result.error.message)+ }+ throw new Error('Failed to create Iceberg namespace')+ }+ return result+ } catch (error) {+ handleError(error)+ }+}++type IcebergNamespaceCreateData = Awaited<ReturnType<typeof createIcebergNamespace>>++export const useIcebergNamespaceCreateMutation = ({+ onSuccess,+ onError,+ ...options+}: Omit<+ UseMutationOptions<IcebergNamespaceCreateData, ResponseError, CreateIcebergNamespaceVariables>,+ 'mutationFn'+> = {}) => {+ const queryClient = useQueryClient()++ return useMutation<IcebergNamespaceCreateData, ResponseError, CreateIcebergNamespaceVariables>(+ (vars) => createIcebergNamespace(vars),+ {+ async onSuccess(data, variables, context) {+ await queryClient.invalidateQueries(+ storageKeys.icebergNamespace(+ variables.catalogUri,+ variables.warehouse,+ variables.namespace+ )+ )+ await onSuccess?.(data, variables, context)+ },+ async onError(data, variables, context) {+ if ((data.message = 'Request failed with status code 409')) {+ toast.error(`A namespace named ${variables.namespace} already exists in the catalog.`)+ return+ }+ if (onError === undefined) {+ toast.error(`Failed to create Iceberg namespace: ${data.message}`)+ } else {+ onError(data, variables, context)+ }+ },+ ...options,+ }+ )+}diff --git a/apps/studio/data/storage/iceberg-namespace-exists-query.ts b/apps/studio/data/storage/iceberg-namespace-exists-query.tsnew file mode 100644index 00000000000..e1a4a026bfb--- /dev/null+++ b/apps/studio/data/storage/iceberg-namespace-exists-query.ts@@ -0,0 +1,54 @@+import { UseQueryOptions, useQuery } from '@tanstack/react-query'++import { constructHeaders, fetchHandler, handleError } from 'data/fetchers'+import type { ResponseError } from 'types'+import { storageKeys } from './keys'++type ExistsNamespaceVariables = {+ catalogUri: string+ warehouse: string+ token: string+ namespace: string+}++async function checkNamespaceExists({+ catalogUri,+ warehouse,+ token,+ namespace,+}: ExistsNamespaceVariables) {+ const headers = await constructHeaders({+ 'Content-Type': 'application/json',+ Authorization: `Bearer ${token}`,+ })++ const url = `${catalogUri}/v1/${warehouse}/namespaces/${namespace}`.replaceAll(/(?<!:)\/\//g, '/')++ try {+ const response = await fetchHandler(url, {+ headers,+ method: 'HEAD',+ })++ return response.status === 204+ } catch (error) {+ handleError(error)+ }+}++type IcebergNamespaceExistsData = Awaited<ReturnType<typeof checkNamespaceExists>>++export type IcebergNamespaceExistsError = ResponseError++export const useIcebergNamespaceExistsQuery = <TData = IcebergNamespaceExistsData>(+ params: ExistsNamespaceVariables,+ {+ ...options+ }: UseQueryOptions<IcebergNamespaceExistsData, IcebergNamespaceExistsError, TData> = {}+) => {+ return useQuery<IcebergNamespaceExistsData, IcebergNamespaceExistsError, TData>(+ storageKeys.icebergNamespace(params.catalogUri, params.warehouse, params.namespace),+ () => checkNamespaceExists(params),+ { ...options }+ )+}diff --git a/apps/studio/data/storage/iceberg-namespace-tables-query.ts b/apps/studio/data/storage/iceberg-namespace-tables-query.tsnew file mode 100644index 00000000000..dd52d964d99--- /dev/null+++ b/apps/studio/data/storage/iceberg-namespace-tables-query.ts@@ -0,0 +1,65 @@+import { UseQueryOptions, useQuery } from '@tanstack/react-query'++import { constructHeaders, fetchHandler, handleError } from 'data/fetchers'+import type { ResponseError } from 'types'+import { storageKeys } from './keys'++type GetNamespaceTablesVariables = {+ catalogUri: string+ warehouse: string+ token: string+ namespace: string+}++async function getNamespaceTables({+ catalogUri,+ warehouse,+ token,+ namespace,+}: GetNamespaceTablesVariables) {+ const headers = await constructHeaders({+ 'Content-Type': 'application/json',+ Authorization: `Bearer ${token}`,+ })++ const url = `${catalogUri}/v1/${warehouse}/namespaces/${namespace}/tables`.replaceAll(+ /(?<!:)\/\//g,+ '/'+ )++ try {+ const response = await fetchHandler(url, {+ headers,+ method: 'GET',+ })++ const result = await response.json()+ if (result.error) {+ if (result.error.message) {+ throw new Error(result.error.message)+ }+ throw new Error('Failed to get iceberg namespace')+ }+ const r = result as { identifiers: { name: string; namespace: string[] }[] }+ return r.identifiers.map((i) => i.name)+ } catch (error) {+ handleError(error)+ }+}++type IcebergNamespaceTablesData = Awaited<ReturnType<typeof getNamespaceTables>>++export type IcebergNamespaceTablesError = ResponseError++export const useIcebergNamespaceTablesQuery = <TData = IcebergNamespaceTablesData>(+ params: GetNamespaceTablesVariables,+ {+ ...options+ }: UseQueryOptions<IcebergNamespaceTablesData, IcebergNamespaceTablesError, TData> = {}+) => {+ return useQuery<IcebergNamespaceTablesData, IcebergNamespaceTablesError, TData>(+ storageKeys.icebergNamespaceTables(params.catalogUri, params.warehouse, params.namespace),+ () => getNamespaceTables(params),+ { ...options }+ )+}diff --git a/apps/studio/data/storage/iceberg-namespaces-query.ts b/apps/studio/data/storage/iceberg-namespaces-query.tsnew file mode 100644index 00000000000..8ae16d34465--- /dev/null+++ b/apps/studio/data/storage/iceberg-namespaces-query.ts@@ -0,0 +1,54 @@+import { UseQueryOptions, useQuery } from '@tanstack/react-query'++import { constructHeaders, fetchHandler, handleError } from 'data/fetchers'+import type { ResponseError } from 'types'+import { storageKeys } from './keys'++type GetNamespacesVariables = {+ catalogUri: string+ warehouse: string+ token: string+}++async function getNamespaces({ catalogUri, warehouse, token }: GetNamespacesVariables) {+ const headers = await constructHeaders({+ 'Content-Type': 'application/json',+ Authorization: `Bearer ${token}`,+ })++ const url = `${catalogUri}/v1/${warehouse}/namespaces`.replaceAll(/(?<!:)\/\//g, '/')++ try {+ const response = await fetchHandler(url, {+ headers,+ method: 'GET',+ })++ const result = await response.json()+ if (result.error) {+ if (result.error.message) {+ throw new Error(result.error.message)+ }+ throw new Error('Failed to get iceberg namespaces')+ }+ const r = result as { namespaces: string[][] }+ return r.namespaces.flat()+ } catch (error) {+ handleError(error)+ }+}++type IcebergNamespacesData = Awaited<ReturnType<typeof getNamespaces>>++export type IcebergNamespacesError = ResponseError++export const useIcebergNamespacesQuery = <TData = IcebergNamespacesData>(+ params: GetNamespacesVariables,+ { ...options }: UseQueryOptions<IcebergNamespacesData, IcebergNamespacesError, TData> = {}+) => {+ return useQuery<IcebergNamespacesData, IcebergNamespacesError, TData>(+ storageKeys.icebergNamespaces(params.catalogUri, params.warehouse),+ () => getNamespaces(params),+ { ...options }+ )+}diff --git a/apps/studio/data/storage/iceberg-wrapper-create-mutation.ts b/apps/studio/data/storage/iceberg-wrapper-create-mutation.tsnew file mode 100644index 00000000000..e82f77ca537--- /dev/null+++ b/apps/studio/data/storage/iceberg-wrapper-create-mutation.ts@@ -0,0 +1,80 @@+import { PermissionAction } from '@supabase/shared-types/out/constants'++import { WRAPPERS } from 'components/interfaces/Integrations/Wrappers/Wrappers.constants'+import {+ useIsProjectActive,+ useProjectContext,+} from 'components/layouts/ProjectLayout/ProjectContext'+import {+ getCatalogURI,+ getConnectionURL,+} from 'components/to-be-cleaned/Storage/StorageSettings/StorageSettings.utils'+import { useProjectSettingsV2Query } from 'data/config/project-settings-v2-query'+import { useProjectStorageConfigQuery } from 'data/config/project-storage-config-query'+import { FDWCreateVariables, useFDWCreateMutation } from 'data/fdw/fdw-create-mutation'+import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'+import { snakeCase } from 'lodash'+import { useS3AccessKeyCreateMutation } from './s3-access-key-create-mutation'++export const useIcebergWrapperCreateMutation = () => {+ const { project } = useProjectContext()+ const { data: settings } = useProjectSettingsV2Query({ projectRef: project?.ref })+ const protocol = settings?.app_config?.protocol ?? 'https'+ const endpoint = settings?.app_config?.endpoint++ const serviceApiKey =+ (settings?.service_api_keys ?? []).find((key) => key.tags === 'service_role')?.api_key ??+ 'SUPABASE_CLIENT_SERVICE_KEY'++ const wrapperMeta = WRAPPERS.find((wrapper) => wrapper.name === 'iceberg_wrapper')++ const isProjectActive = useIsProjectActive()++ const canCreateCredentials = useCheckPermissions(PermissionAction.STORAGE_ADMIN_WRITE, '*')++ const { data: config } = useProjectStorageConfigQuery({ projectRef: project?.ref })+ const isS3ConnectionEnabled = config?.features.s3Protocol.enabled+ const disableCreation = !isProjectActive || !canCreateCredentials || !isS3ConnectionEnabled++ const { mutateAsync: createS3AccessKey, isLoading: isCreatingS3AccessKey } =+ useS3AccessKeyCreateMutation()++ const { mutateAsync: createFDW, isLoading: isCreatingFDW } = useFDWCreateMutation()++ const mutateAsync = async ({ bucketName }: { bucketName: string }) => {+ const createS3KeyData = await createS3AccessKey({+ projectRef: project?.ref,+ description: `${snakeCase(bucketName)}_keys`,+ })++ const wrapperName = `${snakeCase(bucketName)}_fdw`++ const params: FDWCreateVariables = {+ projectRef: project?.ref,+ connectionString: project?.connectionString,+ wrapperMeta: wrapperMeta!,+ formState: {+ wrapper_name: wrapperName,+ server_name: `${wrapperName}_server`,+ vault_aws_access_key_id: createS3KeyData?.access_key,+ vault_aws_secret_access_key: createS3KeyData?.secret_key,+ vault_token: serviceApiKey,+ warehouse: bucketName,+ 's3.endpoint': getConnectionURL(project?.ref ?? '', protocol, endpoint),+ catalog_uri: getCatalogURI(project?.ref ?? '', protocol, endpoint),+ },+ mode: 'skip',+ tables: [],+ sourceSchema: '',+ targetSchema: '',+ }++ await createFDW(params)+ }++ return {+ mutateAsync,+ isLoading: isCreatingFDW || isCreatingS3AccessKey,+ hasPermission: canCreateCredentials,+ }+}diff --git a/apps/studio/data/storage/keys.ts b/apps/studio/data/storage/keys.tsindex 5fa399773f4..e68911d547c 100644--- a/apps/studio/data/storage/keys.ts+++ b/apps/studio/data/storage/keys.ts@@ -1,4 +1,10 @@export const storageKeys = {buckets: (projectRef: string | undefined) => ['projects', projectRef, 'buckets'] as const,archive: (projectRef: string | undefined) => ['projects', projectRef, 'archive'] as const,+ icebergNamespaces: (catalog: string, warehouse: string) =>+ ['catalog', catalog, 'warehouse', warehouse, 'namespaces'] as const,+ icebergNamespace: (catalog: string, warehouse: string, namespace: string) =>+ ['catalog', catalog, 'warehouse', warehouse, 'namespaces', namespace] as const,+ icebergNamespaceTables: (catalog: string, warehouse: string, namespace: string) =>+ ['catalog', catalog, 'warehouse', warehouse, 'namespaces', namespace, 'tables'] as const,}diff --git a/apps/studio/data/vault/vault-secret-decrypted-value-query.ts b/apps/studio/data/vault/vault-secret-decrypted-value-query.tsindex b7009f02165..7b1235c206d 100644--- a/apps/studio/data/vault/vault-secret-decrypted-value-query.ts+++ b/apps/studio/data/vault/vault-secret-decrypted-value-query.ts@@ -1,5 +1,5 @@-import { UseQueryOptions, useQuery } from '@tanstack/react-query'import { Query } from '@supabase/pg-meta/src/query'+import { UseQueryOptions, useQuery } from '@tanstack/react-query'import { executeSql } from '../sql/execute-sql-query'import { vaultSecretsKeys } from './keys'@@ -33,25 +33,26 @@ export const getDecryptedValue = async (},signal)- return result+ return result as { decrypted_secret: string }[]}+type getDecryptedValueResult = Awaited<ReturnType<typeof getDecryptedValue>>export type VaultSecretsDecryptedValueData = stringexport type VaultSecretsDecryptedValueError = unknown-export const useVaultSecretDecryptedValueQuery = <TData = VaultSecretsDecryptedValueData>(+export const useVaultSecretDecryptedValueQuery = <TData = string>({ projectRef, connectionString, id }: VaultSecretsDecryptedValueVariables,{enabled = true,...options- }: UseQueryOptions<VaultSecretsDecryptedValueData, VaultSecretsDecryptedValueError, TData> = {}+ }: UseQueryOptions<getDecryptedValueResult, VaultSecretsDecryptedValueError, TData> = {}) =>- useQuery<VaultSecretsDecryptedValueData, VaultSecretsDecryptedValueError, TData>(+ useQuery<getDecryptedValueResult, VaultSecretsDecryptedValueError, TData>(vaultSecretsKeys.getDecryptedValue(projectRef, id),({ signal }) => getDecryptedValue({ projectRef, connectionString, id }, signal),{select(data) {- return (data[0] as any).decrypted_secret+ return (data[0]?.decrypted_secret ?? '') as TData},enabled: enabled && typeof projectRef !== 'undefined',...options,diff --git a/apps/studio/pages/project/[ref]/storage/buckets/[bucketId].tsx b/apps/studio/pages/project/[ref]/storage/buckets/[bucketId].tsxindex 24e88ca1ade..39cf2671d82 100644--- a/apps/studio/pages/project/[ref]/storage/buckets/[bucketId].tsx+++ b/apps/studio/pages/project/[ref]/storage/buckets/[bucketId].tsx@@ -5,6 +5,7 @@ import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectConteimport StorageBucketsError from 'components/layouts/StorageLayout/StorageBucketsError'import StorageLayout from 'components/layouts/StorageLayout/StorageLayout'import { StorageExplorer } from 'components/to-be-cleaned/Storage'+import { AnalyticBucketDetails } from 'components/to-be-cleaned/Storage/AnalyticBucketDetails'import { useSelectedBucket } from 'components/to-be-cleaned/Storage/StorageExplorer/useSelectedBucket'import { useStorageExplorerStateSnapshot } from 'state/storage-explorer'import type { NextPageWithLayout } from 'types'@@ -18,7 +19,7 @@ const PageLayout: NextPageWithLayout = () => {if (!project || !projectRef) return nullreturn (- <div className="storage-container flex flex-grow p-4">+ <div className="storage-container flex flex-grow">{isError && <StorageBucketsError error={error as any} />}{isSuccess ? (@@ -26,6 +27,8 @@ const PageLayout: NextPageWithLayout = () => {<div className="flex h-full w-full items-center justify-center"><p className="text-sm text-foreground-light">Bucket {bucketId} cannot be found</p></div>+ ) : bucket.type === 'ANALYTICS' ? (+ <AnalyticBucketDetails bucket={bucket} />) : (<StorageExplorer bucket={bucket} />)