Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

feat: add base ui for fdw

Alaister Young2070919b644b
diff --git a/studio/components/interfaces/Database/Wrappers/WrapperCard.tsx b/studio/components/interfaces/Database/Wrappers/WrapperCard.tsx
new file mode 100644
index 00000000000..243ba078e1e
--- /dev/null
+++ b/studio/components/interfaces/Database/Wrappers/WrapperCard.tsx
@@ -0,0 +1,102 @@
+import { PermissionAction } from '@supabase/shared-types/out/constants'
+import { observer } from 'mobx-react-lite'
+import { useState } from 'react'
+import { IconLoader, Toggle } from 'ui'
+
+import { confirmAlert } from 'components/to-be-cleaned/ModalsDeprecated/ConfirmModal'
+import { checkPermissions, useStore } from 'hooks'
+import { Wrapper } from './types'
+import WrapperEditor from './WrapperEditor'
+
+export type WrapperCardProps = {
+ wrapper: Wrapper
+}
+
+const WrapperCard = ({ wrapper }: WrapperCardProps) => {
+ const { ui } = useStore()
+
+ const isOn = false
+ const [loading, setLoading] = useState(false)
+
+ const canUpdateWrappers = checkPermissions(PermissionAction.TENANT_SQL_ADMIN_WRITE, 'wrappers')
+
+ const [isEditorVisible, setIsEditorVisible] = useState(false)
+
+ async function enableWrapper() {
+ setIsEditorVisible(true)
+ }
+
+ async function disableWrapper() {
+ confirmAlert({
+ title: 'Confirm to disable wrapper',
+ message: `Are you sure you want to turn OFF "${wrapper.name}" wrapper?`,
+ onAsyncConfirm: async () => {
+ try {
+ setLoading(true)
+ // const response: any = await meta.wrappers.del(wrapper.name)
+ // if (response.error) {
+ // throw response.error
+ // } else {
+ // ui.setNotification({
+ // category: 'success',
+ // message: `${wrapper.name.toUpperCase()} is off.`,
+ // })
+ // }
+ } catch (error: any) {
+ ui.setNotification({
+ category: 'error',
+ message: `Toggle ${wrapper.name.toUpperCase()} failed: ${error.message}`,
+ })
+ } finally {
+ // Need to reload them because the delete function
+ // removes the wrapper from the store
+ // meta.wrappers.load()
+ setLoading(false)
+ }
+ },
+ })
+ }
+
+ return (
+ <>
+ <div
+ className={[
+ 'flex border-panel-border-light dark:border-panel-border-dark',
+ 'flex-col overflow-hidden rounded border shadow-sm',
+ ].join(' ')}
+ >
+ <div
+ className={[
+ 'border-panel-border-light bg-panel-header-light dark:bg-panel-header-dark',
+ 'flex border-b p-4 px-6 dark:border-panel-border-dark',
+ ].join(' ')}
+ >
+ <h3
+ title={wrapper.label}
+ className="flex-1 h-5 m-0 text-base uppercase truncate text-scale-1200"
+ >
+ {wrapper.label}
+ </h3>
+ {loading ? (
+ <IconLoader className="animate-spin" size={16} />
+ ) : (
+ <Toggle
+ size="tiny"
+ checked={isOn}
+ disabled={!canUpdateWrappers}
+ onChange={() => (isOn ? disableWrapper() : enableWrapper())}
+ />
+ )}
+ </div>
+ </div>
+
+ <WrapperEditor
+ visible={isEditorVisible}
+ wrapper={wrapper}
+ onCancel={() => setIsEditorVisible(false)}
+ />
+ </>
+ )
+}
+
+export default observer(WrapperCard)
diff --git a/studio/components/interfaces/Database/Wrappers/WrapperEditor.tsx b/studio/components/interfaces/Database/Wrappers/WrapperEditor.tsx
new file mode 100644
index 00000000000..80cd41394d8
--- /dev/null
+++ b/studio/components/interfaces/Database/Wrappers/WrapperEditor.tsx
@@ -0,0 +1,138 @@
+import { FC, useState } from 'react'
+import { Button, Checkbox, Form, Input, SidePanel } from 'ui'
+
+import ActionBar from 'components/interfaces/TableGridEditor/SidePanelEditor/ActionBar'
+import { useStore } from 'hooks'
+import { Wrapper } from './types'
+import WrapperTableEditor from './WrapperTableEditor'
+
+export type WrapperEditorProps = {
+ visible: boolean
+ wrapper: Wrapper
+ onCancel: () => void
+}
+
+const WrapperEditor = ({ visible, wrapper, onCancel }: WrapperEditorProps) => {
+ const { ui } = useStore()
+
+ const validate = (values: any) => {
+ const errors: any = {}
+ if (values.schema === 'custom' && !values.name) errors.name = 'Required field'
+ return errors
+ }
+
+ const onSubmit = async (values: any, { setSubmitting }: any) => {
+ setSubmitting(true)
+
+ console.log('values:', values)
+ // const { error } = await meta.wrappers.create({
+ // schema,
+ // name: wrapper.name,
+ // version: wrapper.default_version,
+ // cascade: true,
+ // })
+ // if (error) {
+ // ui.setNotification({
+ // error,
+ // category: 'error',
+ // message: `Failed to toggle ${wrapper.name.toUpperCase()}: ${error.message}`,
+ // })
+ // } else {
+ // ui.setNotification({
+ // category: 'success',
+ // message: `${wrapper.name.toUpperCase()} is on.`,
+ // })
+ // }
+
+ setSubmitting(false)
+ onCancel()
+ }
+
+ const initialValues = Object.fromEntries(
+ wrapper.server.options.map((option) => [option.name, option.defaultValue ?? ''])
+ )
+
+ const [newTables, setNewTables] = useState<any[]>([])
+
+ const [isAddTableOpen, setIsAddTableOpen] = useState(false)
+
+ const onTableAdd = (values: any) => {
+ setNewTables((prev) => [...prev, values])
+ setIsAddTableOpen(false)
+ }
+
+ const onSaveChanges = console.log
+
+ return (
+ <>
+ <SidePanel
+ size="large"
+ key="WrapperEditor"
+ visible={visible}
+ header={
+ <div className="flex items-baseline gap-2">
+ <h5 className="text-sm text-scale-1200">{wrapper.label} Foreign Data Wrapper</h5>
+ </div>
+ }
+ className={`transition-all duration-100 ease-in`}
+ onCancel={onCancel}
+ onConfirm={() => (resolve: () => void) => onSaveChanges(resolve)}
+ customFooter={
+ <ActionBar
+ backButtonLabel="Cancel"
+ applyButtonLabel="Save"
+ closePanel={onCancel}
+ applyFunction={(resolve: () => void) => onSaveChanges(resolve)}
+ />
+ }
+ onInteractOutside={(event) => {
+ const isToast = (event.target as Element)?.closest('#toast')
+ if (isToast) {
+ event.preventDefault()
+ }
+ }}
+ >
+ <Form initialValues={initialValues} validate={validate} onSubmit={onSubmit}>
+ {({ isSubmitting, values }: any) => {
+ return (
+ <div className="py-6">
+ <SidePanel.Content>
+ <div className="space-y-10">
+ {wrapper.server.options.map((option) => (
+ <Input
+ key={option.name}
+ id={option.name}
+ name={option.name}
+ label={option.label}
+ defaultValue={option.defaultValue ?? ''}
+ required={option.required ?? false}
+ layout="horizontal"
+ />
+ ))}
+
+ {newTables.map((table, i) => (
+ <div key={i}>{table.table_name}</div>
+ ))}
+
+ <Button type="default" onClick={() => setIsAddTableOpen(true)}>
+ Add table
+ </Button>
+ </div>
+ </SidePanel.Content>
+ </div>
+ )
+ }}
+ </Form>
+ </SidePanel>
+
+ <WrapperTableEditor
+ visible={isAddTableOpen}
+ tables={wrapper.tables}
+ onCancel={() => setIsAddTableOpen(false)}
+ onSave={onTableAdd}
+ />
+ </>
+ )
+}
+
+export default WrapperEditor
diff --git a/studio/components/interfaces/Database/Wrappers/WrapperTableEditor.tsx b/studio/components/interfaces/Database/Wrappers/WrapperTableEditor.tsx
new file mode 100644
index 00000000000..377c32a80e1
--- /dev/null
+++ b/studio/components/interfaces/Database/Wrappers/WrapperTableEditor.tsx
@@ -0,0 +1,157 @@
+import ActionBar from 'components/interfaces/TableGridEditor/SidePanelEditor/ActionBar'
+import { useState } from 'react'
+import { Checkbox, Input, Listbox, SidePanel, Accordion, Form } from 'ui'
+import { TableOption, Table } from './types'
+
+export type WrapperTableEditorProps = {
+ visible: boolean
+ onCancel: () => void
+ onSave: (values: any) => void
+
+ tables: Table[]
+}
+
+const WrapperTableEditor = ({ visible, onCancel, onSave, tables }: WrapperTableEditorProps) => {
+ const [selectedTableIndex, setSelectedTableIndex] = useState<string>('')
+
+ const selectedTable = selectedTableIndex === '' ? undefined : tables[parseInt(selectedTableIndex)]
+
+ const onSubmit = (values: any) => {
+ onSave(values)
+ }
+
+ return (
+ <SidePanel
+ key="WrapperTableEditor"
+ size="medium"
+ visible={visible}
+ onCancel={onCancel}
+ header={<span>Edit foreign table</span>}
+ customFooter={
+ <ActionBar
+ backButtonLabel="Cancel"
+ applyButtonLabel="Save"
+ formId="wrapper-table-editor-form"
+ closePanel={onCancel}
+ />
+ }
+ >
+ <SidePanel.Content>
+ <div className="mt-4 space-y-6">
+ <Listbox
+ label="Select a target the table will point to"
+ value={selectedTableIndex}
+ onChange={(value) => setSelectedTableIndex(value)}
+ >
+ <Listbox.Option key="empty" value="" label="---">
+ ---
+ </Listbox.Option>
+
+ {tables.map((table, i) => {
+ return (
+ <Listbox.Option key={String(i)} value={String(i)} label={table.label}>
+ <div className="flex items-center gap-2">{table.label}</div>
+ </Listbox.Option>
+ )
+ })}
+ </Listbox>
+
+ {selectedTable && <TableForm table={selectedTable} onSubmit={onSubmit} />}
+ </div>
+ </SidePanel.Content>
+ </SidePanel>
+ )
+}
+
+export default WrapperTableEditor
+
+const Option = ({ option }: { option: TableOption }) => {
+ return (
+ <Input
+ key={option.name}
+ id={option.name}
+ name={option.name}
+ label={option.label}
+ placeholder={option.placeholder ?? ''}
+ defaultValue={option.defaultValue ?? ''}
+ required={option.required ?? false}
+ />
+ )
+}
+
+const TableForm = ({ table, onSubmit }: { table: Table; onSubmit: (values: any) => void }) => {
+ const requiredOptions =
+ table.options.filter((option) => option.editable && option.required && !option.defaultValue) ??
+ []
+ const optionalOptions =
+ table.options.filter(
+ (option) => option.editable && (!option.required || option.defaultValue)
+ ) ?? []
+
+ const initialValues = Object.fromEntries(
+ [
+ ['table_name', ''],
+ ['columns', []],
+ ].concat(table.options.map((option) => [option.name, option.defaultValue ?? '']))
+ )
+
+ return (
+ <Form
+ id="wrapper-table-editor-form"
+ initialValues={initialValues}
+ // validate={validate}
+ onSubmit={onSubmit}
+ >
+ {() => (
+ <div className="space-y-4">
+ <Input
+ id="table-name"
+ name="table_name"
+ label="Table name"
+ descriptionText="The name of the local table table you will query after the wrapper is enabled."
+ required
+ />
+
+ {requiredOptions.map((option) => (
+ <Option key={option.name} option={option} />
+ ))}
+
+ <div className="space-y-2">
+ <label className="block text-sm break-all text-scale-1100">Columns</label>
+
+ <div>
+ {table.availableColumns.map((column, k) => (
+ <Checkbox
+ key={k}
+ id={column.name}
+ name="columns"
+ value={column.name}
+ label={`${column.name} (${column.type})`}
+ />
+ ))}
+ </div>
+ </div>
+
+ {optionalOptions.length > 0 && (
+ <Accordion
+ className="text-sm"
+ justified={false}
+ openBehaviour="multiple"
+ type="default"
+ chevronAlign="left"
+ size="small"
+ bordered={false}
+ iconPosition="left"
+ >
+ <Accordion.Item id="1" header="Optional Fields">
+ {optionalOptions.map((option) => (
+ <Option key={option.name} option={option} />
+ ))}
+ </Accordion.Item>
+ </Accordion>
+ )}
+ </div>
+ )}
+ </Form>
+ )
+}
diff --git a/studio/components/interfaces/Database/Wrappers/Wrappers.tsx b/studio/components/interfaces/Database/Wrappers/Wrappers.tsx
new file mode 100644
index 00000000000..b7346b72333
--- /dev/null
+++ b/studio/components/interfaces/Database/Wrappers/Wrappers.tsx
@@ -0,0 +1,181 @@
+import { Wrapper } from './types'
+import WrapperCard from './WrapperCard'
+
+const wrappers: Wrapper[] = [
+ {
+ name: 'stripe_wrapper',
+ extensionName: 'StripeFdw',
+ label: 'Stripe',
+ server: {
+ name: 'stripe_server',
+ options: [
+ {
+ name: 'api_key_id',
+ label: 'Stripe Secret Key',
+ required: true,
+ encrypted: true,
+ },
+ {
+ name: 'api_url',
+ label: 'Stripe API URL',
+ defaultValue: 'https://api.stripe.com/v1',
+ required: false,
+ encrypted: false,
+ },
+ ],
+ },
+ tables: [
+ {
+ label: 'Balance',
+ availableColumns: [
+ {
+ name: 'amount',
+ type: 'bigint',
+ },
+ {
+ name: 'currency',
+ type: 'text',
+ },
+ ],
+ options: [
+ {
+ name: 'object',
+ defaultValue: 'balance',
+ editable: false,
+ required: true,
+ },
+ ],
+ },
+ ],
+ },
+ {
+ name: 'firebase_wrapper',
+ extensionName: 'FirebaseFdw',
+ label: 'Firebase',
+ server: {
+ name: 'firebase_server',
+ options: [
+ {
+ name: 'project_id',
+ label: 'Project ID',
+ required: true,
+ encrypted: false,
+ },
+ {
+ name: 'sa_key_id',
+ label: 'Service Account Key',
+ required: true,
+ encrypted: true,
+ },
+ ],
+ },
+ tables: [
+ {
+ label: 'Users',
+ availableColumns: [
+ {
+ name: 'local_id',
+ type: 'text',
+ },
+ {
+ name: 'email',
+ type: 'text',
+ },
+ {
+ name: 'fields',
+ type: 'jsonb',
+ },
+ ],
+ options: [
+ {
+ name: 'object',
+ defaultValue: 'auth/users',
+ editable: false,
+ required: true,
+ },
+ {
+ name: 'base_url',
+ label: 'Base URL',
+ defaultValue: 'https://identitytoolkit.googleapis.com/v1/projects',
+ editable: true,
+ required: true,
+ },
+ ],
+ },
+ {
+ label: 'Firestore Collection',
+ availableColumns: [
+ {
+ name: 'name',
+ type: 'text',
+ },
+ {
+ name: 'fields',
+ type: 'jsonb',
+ },
+ {
+ name: 'create_time',
+ type: 'timestamp',
+ },
+ {
+ name: 'update_time',
+ type: 'timestamp',
+ },
+ ],
+ options: [
+ {
+ name: 'object',
+ label: 'Object',
+ placeholder: 'firestore/[collection_id]',
+ editable: true,
+ required: true,
+ },
+ {
+ name: 'base_url',
+ label: 'Base URL',
+ defaultValue: 'https://firestore.googleapis.com/v1beta1/projects',
+ editable: true,
+ required: true,
+ },
+ ],
+ },
+ ],
+ },
+]
+
+const Wrappers = () => {
+ const enabledWrappers: any[] = []
+ const disabledWrappers = wrappers
+
+ return (
+ <>
+ <div className="p-4 space-y-4">
+ <div className="w-full space-y-12">
+ {enabledWrappers.length > 0 && (
+ <div className="space-y-4">
+ <h4 className="text-lg">Enabled wrappers</h4>
+ <div className="grid grid-cols-1 gap-6 mb-4 md:grid-cols-2 xl:grid-cols-3">
+ {enabledWrappers.map((wrapper) => (
+ <WrapperCard key={wrapper.name} wrapper={wrapper} />
+ ))}
+ </div>
+ </div>
+ )}
+
+ {disabledWrappers.length > 0 && (
+ <div className="space-y-4">
+ <h4 className="text-lg">Available wrappers</h4>
+ <div className="grid grid-cols-1 gap-6 mb-4 md:grid-cols-2 xl:grid-cols-3">
+ {disabledWrappers.map((wrapper) => (
+ <WrapperCard key={wrapper.name} wrapper={wrapper} />
+ ))}
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+ </>
+ )
+}
+
+export default Wrappers
diff --git a/studio/components/interfaces/Database/Wrappers/types.ts b/studio/components/interfaces/Database/Wrappers/types.ts
new file mode 100644
index 00000000000..66a2f4f2ea3
--- /dev/null
+++ b/studio/components/interfaces/Database/Wrappers/types.ts
@@ -0,0 +1,40 @@
+export type Wrapper = {
+ name: string
+ extensionName: string
+ label: string
+ server: Server
+ tables: Table[]
+}
+
+export type ServerOption = {
+ name: string
+ label: string
+ required: boolean
+ encrypted: boolean
+ defaultValue?: string
+}
+
+export type Server = {
+ name: string
+ options: ServerOption[]
+}
+
+export type TableOption = {
+ name: string
+ defaultValue?: string
+ editable: boolean
+ required: boolean
+ label?: string
+ placeholder?: string
+}
+
+export type Table = {
+ label: string
+ availableColumns: AvailableColumn[]
+ options: TableOption[]
+}
+
+export type AvailableColumn = {
+ name: string
+ type: string
+}
diff --git a/studio/components/interfaces/Database/index.ts b/studio/components/interfaces/Database/index.ts
index 60141982fab..b294434c18e 100644
--- a/studio/components/interfaces/Database/index.ts
+++ b/studio/components/interfaces/Database/index.ts
@@ -6,6 +6,8 @@ import RolesSettings from './Roles/RolesSettings'
import Extensions from './Extensions/Extensions'
+import Wrappers from './Wrappers/Wrappers'
+
import PublicationsList from './Publications/PublicationsList'
import PublicationsTables from './Publications/PublicationsTables'
@@ -25,6 +27,7 @@ export {
RolesList,
RolesSettings,
Extensions,
+ Wrappers,
PublicationsList,
PublicationsTables,
BackupsList,
diff --git a/studio/components/interfaces/TableGridEditor/SidePanelEditor/ActionBar.tsx b/studio/components/interfaces/TableGridEditor/SidePanelEditor/ActionBar.tsx
index 03f8b01dc8d..4f4cb0c4595 100644
--- a/studio/components/interfaces/TableGridEditor/SidePanelEditor/ActionBar.tsx
+++ b/studio/components/interfaces/TableGridEditor/SidePanelEditor/ActionBar.tsx
@@ -10,6 +10,7 @@ interface ActionBarProps {
backButtonLabel?: string
applyFunction?: (resolve: any) => void
closePanel: () => void
+ formId?: string
}
const ActionBar: FC<ActionBarProps> = ({
loading = false,
@@ -20,6 +21,7 @@ const ActionBar: FC<ActionBarProps> = ({
backButtonLabel = 'Back',
applyFunction = undefined,
closePanel = () => {},
+ formId,
}) => {
const [isRunning, setIsRunning] = useState(false)
@@ -33,7 +35,7 @@ const ActionBar: FC<ActionBarProps> = ({
}
return (
- <div className="flex w-full justify-between space-x-3 border-t border-scale-500 px-3 py-4">
+ <div className="flex justify-between w-full px-3 py-4 space-x-3 border-t border-scale-500">
<Button size="small" onClick={closePanel} type="default" htmlType="button">
{backButtonLabel}
</Button>
@@ -53,7 +55,13 @@ const ActionBar: FC<ActionBarProps> = ({
) : !hideApply ? (
// New solution, when using the Form component, loading is handled by the Form itself
// Does not require applyFunction() callback
- <Button size="small" disabled={disableApply} loading={loading} htmlType="submit">
+ <Button
+ size="small"
+ disabled={disableApply}
+ loading={loading}
+ htmlType="submit"
+ form={formId}
+ >
{applyButtonLabel}
</Button>
) : (
diff --git a/studio/components/layouts/DatabaseLayout/DatabaseMenu.utils.ts b/studio/components/layouts/DatabaseLayout/DatabaseMenu.utils.ts
index b22828ad94b..0ba8e86a251 100644
--- a/studio/components/layouts/DatabaseLayout/DatabaseMenu.utils.ts
+++ b/studio/components/layouts/DatabaseLayout/DatabaseMenu.utils.ts
@@ -32,6 +32,12 @@ export const generateDatabaseMenu = (project?: Project): ProductMenuGroup[] => {
url: `/project/${ref}/database/extensions`,
items: [],
},
+ {
+ name: 'Wrappers',
+ key: 'wrappers',
+ url: `/project/${ref}/database/wrappers`,
+ items: [],
+ },
{ name: 'Roles', key: 'roles', url: `/project/${ref}/database/roles`, items: [] },
{
name: 'Replication',
diff --git a/studio/pages/project/[ref]/database/wrappers.tsx b/studio/pages/project/[ref]/database/wrappers.tsx
new file mode 100644
index 00000000000..f28e918c273
--- /dev/null
+++ b/studio/pages/project/[ref]/database/wrappers.tsx
@@ -0,0 +1,21 @@
+import { observer } from 'mobx-react-lite'
+import { PermissionAction } from '@supabase/shared-types/out/constants'
+
+import { NextPageWithLayout } from 'types'
+import { checkPermissions } from 'hooks'
+import { DatabaseLayout } from 'components/layouts'
+import { Wrappers } from 'components/interfaces/Database'
+import NoPermission from 'components/ui/NoPermission'
+
+const DatabaseWrappers: NextPageWithLayout = () => {
+ const canReadWrappers = checkPermissions(PermissionAction.TENANT_SQL_ADMIN_READ, 'wrappers')
+ if (!canReadWrappers) {
+ return <NoPermission isFullPage resourceText="view foreign data wrappers" />
+ }
+
+ return <Wrappers />
+}
+
+DatabaseWrappers.getLayout = (page) => <DatabaseLayout title="Wrappers">{page}</DatabaseLayout>
+
+export default observer(DatabaseWrappers)