Skip to content

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

Feat/support schema creation in table editor (#17615)

Joshen Limc9a01f2566e6
diff --git a/studio/components/interfaces/TableGridEditor/SidePanelEditor/SchemaEditor.tsx b/studio/components/interfaces/TableGridEditor/SidePanelEditor/SchemaEditor.tsx
new file mode 100644
index 00000000000..9eeb00728bc
--- /dev/null
+++ b/studio/components/interfaces/TableGridEditor/SidePanelEditor/SchemaEditor.tsx
@@ -0,0 +1,87 @@
+import { useEffect, useState } from 'react'
+import { Input, SidePanel } from 'ui'
+import toast from 'react-hot-toast'
+
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
+import { useSchemaCreateMutation } from 'data/database/schema-create-mutation'
+import ActionBar from './ActionBar'
+
+interface SchemaEditorProps {
+ visible: boolean
+ closePanel: () => void
+ saveChanges: (resolve: any) => void
+}
+
+const SchemaEditor = ({ visible, closePanel, saveChanges }: SchemaEditorProps) => {
+ const { project } = useProjectContext()
+
+ const [errors, setErrors] = useState<{ name?: string }>({ name: undefined })
+ const [name, setName] = useState('')
+
+ const { mutate: createSchema } = useSchemaCreateMutation()
+
+ useEffect(() => {
+ if (visible) {
+ setName('')
+ setErrors({ name: undefined })
+ }
+ }, [visible])
+
+ const onSaveChanges = (resolve: any) => {
+ const errors: any = {}
+ if (name.length === 0) errors.name = 'Please provide a name for your schema'
+ if (Object.keys(errors).length > 0) {
+ resolve()
+ return setErrors(errors)
+ }
+
+ if (project === undefined) return console.error('Project is required')
+ createSchema(
+ { projectRef: project.ref, connectionString: project.connectionString, name },
+ {
+ onSuccess: () => {
+ resolve()
+ closePanel()
+ toast.success(`Successfully created schema "${name}"`)
+ },
+ }
+ )
+ }
+
+ return (
+ <SidePanel
+ size="large"
+ key="SchemaEditor"
+ visible={visible}
+ header={'Create a new schema'}
+ className="transition-all duration-100 ease-in"
+ onCancel={closePanel}
+ onConfirm={() => (resolve: () => void) => onSaveChanges(resolve)}
+ customFooter={
+ <ActionBar
+ backButtonLabel="Cancel"
+ applyButtonLabel="Save"
+ closePanel={closePanel}
+ applyFunction={(resolve: () => void) => onSaveChanges(resolve)}
+ />
+ }
+ >
+ <>
+ <SidePanel.Content>
+ <div className="space-y-10 py-6">
+ <Input
+ label="Name"
+ layout="horizontal"
+ type="text"
+ error={errors?.name}
+ value={name}
+ onChange={(event: any) => setName(event.target.value)}
+ />
+ </div>
+ </SidePanel.Content>
+ </>
+ </SidePanel>
+ )
+}
+
+export default SchemaEditor
diff --git a/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx b/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx
index 6f8dda6da38..22d656b7267 100644
--- a/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx
+++ b/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx
@@ -24,6 +24,7 @@ import {
UpdateColumnPayload,
} from './SidePanelEditor.types'
import { ImportContent } from './TableEditor/TableEditor.types'
+import SchemaEditor from './SchemaEditor'
export interface SidePanelEditorProps {
editable?: boolean
@@ -554,6 +555,11 @@ const SidePanelEditor = ({
saveChanges={saveTable}
updateEditorDirty={() => setIsEdited(true)}
/>
+ <SchemaEditor
+ visible={snap.sidePanel?.type === 'schema'}
+ closePanel={onClosePanel}
+ saveChanges={() => {}}
+ />
<JsonEdit
visible={snap.sidePanel?.type === 'json'}
column={(snap.sidePanel?.type === 'json' && snap.sidePanel.jsonValue.column) || ''}
diff --git a/studio/components/layouts/TableEditorLayout/TableEditorMenu.tsx b/studio/components/layouts/TableEditorLayout/TableEditorMenu.tsx
index ffe27f2fa52..c45ddb71087 100644
--- a/studio/components/layouts/TableEditorLayout/TableEditorMenu.tsx
+++ b/studio/components/layouts/TableEditorLayout/TableEditorMenu.tsx
@@ -1,30 +1,45 @@
import * as Tooltip from '@radix-ui/react-tooltip'
import { PermissionAction } from '@supabase/shared-types/out/constants'
+import { useParams } from 'common'
import { partition } from 'lodash'
import { useMemo, useState } from 'react'
-
-import { useParams } from 'common/hooks'
-import InfiniteList from 'components/ui/InfiniteList'
-import { useSchemasQuery } from 'data/database/schemas-query'
-import { useEntityTypesQuery } from 'data/entity-types/entity-types-infinite-query'
-import { useCheckPermissions, useLocalStorage } from 'hooks'
-import { EXCLUDED_SCHEMAS } from 'lib/constants/schemas'
-import { useTableEditorStateSnapshot } from 'state/table-editor'
import {
Alert,
+ AlertDescription_Shadcn_,
+ AlertTitle_Shadcn_,
+ Alert_Shadcn_,
Button,
+ CommandEmpty_Shadcn_,
+ CommandGroup_Shadcn_,
+ CommandInput_Shadcn_,
+ CommandItem_Shadcn_,
+ CommandList_Shadcn_,
+ Command_Shadcn_,
Dropdown,
IconCheck,
IconChevronsDown,
+ IconCode,
IconEdit,
IconLoader,
+ IconPlus,
IconRefreshCw,
IconSearch,
IconX,
Input,
- Listbox,
Menu,
+ Modal,
+ PopoverContent_Shadcn_,
+ PopoverTrigger_Shadcn_,
+ Popover_Shadcn_,
+ ScrollArea,
} from 'ui'
+
+import InfiniteList from 'components/ui/InfiniteList'
+import { useSchemasQuery } from 'data/database/schemas-query'
+import { useEntityTypesQuery } from 'data/entity-types/entity-types-infinite-query'
+import { useCheckPermissions, useLocalStorage } from 'hooks'
+import { EXCLUDED_SCHEMAS } from 'lib/constants/schemas'
+import { useTableEditorStateSnapshot } from 'state/table-editor'
import { useProjectContext } from '../ProjectLayout/ProjectContext'
import EntityListItem from './EntityListItem'
@@ -32,6 +47,8 @@ const TableEditorMenu = () => {
const { id } = useParams()
const snap = useTableEditorStateSnapshot()
+ const [open, setOpen] = useState(false)
+ const [showModal, setShowModal] = useState(false)
const [searchText, setSearchText] = useState<string>('')
const [sort, setSort] = useLocalStorage<'alphabetical' | 'grouped-alphabetical'>(
'table-editor-sort',
@@ -86,91 +103,123 @@ const TableEditorMenu = () => {
await refetch()
}
- const [protectedSchemas, openSchemas] = partition(schemas, (schema) =>
- EXCLUDED_SCHEMAS.includes(schema?.name ?? '')
+ const [protectedSchemas, openSchemas] = partition(
+ (schemas ?? []).sort((a, b) => a.name.localeCompare(b.name)),
+ (schema) => EXCLUDED_SCHEMAS.includes(schema?.name ?? '')
)
const isLocked = protectedSchemas.some((s) => s.id === schema?.id)
return (
- <div
- className="pt-6 flex flex-col flex-grow space-y-6 h-full"
- style={{ maxHeight: 'calc(100vh - 48px)' }}
- >
- {/* Schema selection dropdown */}
- <div className="px-3 mx-4">
- {isSchemasLoading && (
- <div className="flex h-[26px] items-center space-x-3 rounded border border-gray-500 px-3">
- <IconLoader className="animate-spin" size={12} />
- <span className="text-xs text-scale-900">Loading schemas...</span>
- </div>
- )}
-
- {isSchemasError && (
- <Alert variant="warning" title="Failed to load schemas" className="!px-3 !py-3">
- <p className="mb-2">Error: {schemasError.message}</p>
- <Button type="default" size="tiny" onClick={() => refetchSchemas()}>
- Reload schemas
+ <>
+ <div
+ className="pt-5 flex flex-col flex-grow space-y-4 h-full"
+ style={{ maxHeight: 'calc(100vh - 48px)' }}
+ >
+ {/* Schema selection dropdown */}
+ <div className="mx-4">
+ {isSchemasLoading && (
+ <Button
+ type="outline"
+ className="w-full [&>span]:w-full"
+ icon={<IconLoader className="animate-spin" size={12} />}
+ >
+ <div>
+ <div className="w-full flex space-x-3 py-0.5">
+ <p className="text-xs text-light">Loading schemas...</p>
+ </div>
+ </div>
</Button>
- </Alert>
- )}
+ )}
- {isSchemasSuccess && (
- <Listbox
- size="tiny"
- value={snap.selectedSchemaName}
- onChange={(name: string) => {
- setSearchText('')
- snap.setSelectedSchemaName(name)
- }}
- >
- <Listbox.Option
- disabled
- key="normal-schemas"
- value="normal-schemas"
- label="Schemas"
- className="!w-[200px]"
- >
- <p className="text-xs text-scale-1100">Schemas</p>
- </Listbox.Option>
- {openSchemas.map((schema) => (
- <Listbox.Option
- key={schema.id}
- value={schema.name}
- label={schema.name}
- className="!w-[200px]"
- addOnBefore={() => <span className="text-scale-900 text-xs">schema</span>}
- >
- <span className="text-scale-1200 text-xs">{schema.name}</span>
- </Listbox.Option>
- ))}
- <Listbox.Option
- disabled
- key="protected-schemas"
- value="protected-schemas"
- label="Protected schemas"
- className="!w-[200px]"
- >
- <p className="text-xs text-scale-1100">Protected schemas</p>
- </Listbox.Option>
- {protectedSchemas.map((schema) => (
- <Listbox.Option
- key={schema.id}
- value={schema.name}
- label={schema.name}
- className="!w-[200px]"
- addOnBefore={() => <span className="text-scale-900 text-xs">schema</span>}
- >
- <span className="text-scale-1200 text-xs">{schema.name}</span>
- </Listbox.Option>
- ))}
- </Listbox>
- )}
- </div>
+ {isSchemasError && (
+ <Alert variant="warning" title="Failed to load schemas" className="!px-3 !py-3">
+ <p className="mb-2">Error: {schemasError.message}</p>
+ <Button type="default" size="tiny" onClick={() => refetchSchemas()}>
+ Reload schemas
+ </Button>
+ </Alert>
+ )}
+
+ {isSchemasSuccess && (
+ <Popover_Shadcn_ open={open} onOpenChange={setOpen} modal={false}>
+ <PopoverTrigger_Shadcn_ asChild>
+ <Button
+ asChild
+ type="outline"
+ className="w-full [&>span]:w-full"
+ iconRight={
+ <IconCode className="text-scale-1100 rotate-90" strokeWidth={2} size={12} />
+ }
+ >
+ <div>
+ <div className="w-full flex space-x-3 py-0.5">
+ <p className="text-xs text-light">schema</p>
+ <p className="text-xs">{snap.selectedSchemaName}</p>
+ </div>
+ </div>
+ </Button>
+ </PopoverTrigger_Shadcn_>
+ <PopoverContent_Shadcn_ className="p-0 w-64" side="bottom" align="start">
+ <Command_Shadcn_>
+ <CommandInput_Shadcn_ placeholder="Find schema..." />
+ <CommandList_Shadcn_>
+ <CommandEmpty_Shadcn_>No schemas found</CommandEmpty_Shadcn_>
+ <CommandGroup_Shadcn_>
+ <ScrollArea className={(schemas || []).length > 7 ? 'h-[210px]' : ''}>
+ {schemas?.map((schema) => (
+ <CommandItem_Shadcn_
+ asChild
+ key={schema.id}
+ className="cursor-pointer flex items-center space-x-2 w-full"
+ onSelect={() => {
+ setSearchText('')
+ snap.setSelectedSchemaName(schema.name)
+ setOpen(false)
+ }}
+ onClick={() => {
+ setSearchText('')
+ snap.setSelectedSchemaName(schema.name)
+ setOpen(false)
+ }}
+ >
+ <div className="w-full flex items-center justify-between">
+ <p>{schema.name}</p>
+ {schema.name === snap.selectedSchemaName && (
+ <IconCheck className="text-brand" strokeWidth={2} />
+ )}
+ </div>
+ </CommandItem_Shadcn_>
+ ))}
+ </ScrollArea>
+ </CommandGroup_Shadcn_>
+ <CommandGroup_Shadcn_ className="border-t">
+ <CommandItem_Shadcn_
+ asChild
+ className="cursor-pointer flex items-center space-x-2 w-full"
+ onSelect={() => {
+ snap.onAddSchema()
+ setOpen(false)
+ }}
+ onClick={() => {
+ snap.onAddSchema()
+ setOpen(false)
+ }}
+ >
+ <div className="flex items-center space-x-2">
+ <IconPlus />
+ <p>Create a new schema</p>
+ </div>
+ </CommandItem_Shadcn_>
+ </CommandGroup_Shadcn_>
+ </CommandList_Shadcn_>
+ </Command_Shadcn_>
+ </PopoverContent_Shadcn_>
+ </Popover_Shadcn_>
+ )}
+ </div>
- <div className="space-y-1 mx-4">
- {!isLocked && (
- <div className="px-3">
- {/* Add new table button */}
+ <div className="space-y-1 mx-4">
+ {!isLocked ? (
<Tooltip.Root delayDuration={0}>
<Tooltip.Trigger className="w-full">
<Button
@@ -208,157 +257,208 @@ const TableEditorMenu = () => {
</Tooltip.Portal>
)}
</Tooltip.Root>
- </div>
- )}
- {/* Table search input */}
- <div className="mb-2 block px-3">
- <Input
- className="table-editor-search border-none"
- icon={
- isSearching ? (
- <IconLoader className="animate-spin text-scale-900" size={12} strokeWidth={1.5} />
- ) : (
- <IconSearch className="text-scale-900" size={12} strokeWidth={1.5} />
- )
- }
- placeholder="Search tables"
- onChange={(e) => setSearchText(e.target.value.trim())}
- value={searchText}
- size="tiny"
- actions={
- searchText && (
- <Button size="tiny" type="text" onClick={() => setSearchText('')}>
- <IconX size={12} strokeWidth={2} />
+ ) : (
+ <Alert_Shadcn_>
+ <AlertTitle_Shadcn_ className="text-xs tracking-normal">
+ Viewing protected schema
+ </AlertTitle_Shadcn_>
+ <AlertDescription_Shadcn_ className="text-xs">
+ <p className="mb-2">
+ This schema is managed by Supabase and is read-only through the table editor
+ </p>
+ <Button type="default" size="tiny" onClick={() => setShowModal(true)}>
+ Learn more
</Button>
- )
- }
- />
- </div>
- </div>
+ </AlertDescription_Shadcn_>
+ </Alert_Shadcn_>
+ )}
- {isLoading ? (
- <div className="mx-7 flex items-center space-x-2">
- <IconLoader className="animate-spin" size={14} strokeWidth={1.5} />
- <p className="text-sm text-scale-1000">Loading entities...</p>
- </div>
- ) : searchText.length === 0 && (entityTypes?.length ?? 0) === 0 ? (
- <div className="mx-7 space-y-1 rounded-md border border-scale-400 bg-scale-300 py-3 px-4">
- <p className="text-xs">No entities available</p>
- <p className="text-xs text-scale-1100">This schema has no entities available yet</p>
- </div>
- ) : searchText.length > 0 && (entityTypes?.length ?? 0) === 0 ? (
- <div className="mx-7 space-y-1 rounded-md border border-scale-400 bg-scale-300 py-3 px-4">
- <p className="text-xs">No results found</p>
- <p className="text-xs text-scale-1100">There are no entities that match your search</p>
+ {/* Table search input */}
+ <div className="mb-2 block">
+ <Input
+ className="table-editor-search border-none"
+ icon={
+ isSearching ? (
+ <IconLoader className="animate-spin text-scale-900" size={12} strokeWidth={1.5} />
+ ) : (
+ <IconSearch className="text-scale-900" size={12} strokeWidth={1.5} />
+ )
+ }
+ placeholder="Search tables"
+ onChange={(e) => setSearchText(e.target.value.trim())}
+ value={searchText}
+ size="tiny"
+ actions={
+ searchText && (
+ <Button size="tiny" type="text" onClick={() => setSearchText('')}>
+ <IconX size={12} strokeWidth={2} />
+ </Button>
+ )
+ }
+ />
+ </div>
</div>
- ) : (
- <Menu
- type="pills"
- className="flex flex-auto px-4 space-y-6 pb-4"
- ulClassName="flex flex-auto flex-col"
- >
- <Menu.Group
- // @ts-ignore
- title={
- <>
- <div className="flex w-full items-center justify-between">
- <div className="flex items-center space-x-1">
- <p>Tables</p>
- {totalCount !== undefined && (
- <p style={{ fontVariantNumeric: 'tabular-nums' }}>({totalCount})</p>
- )}
- </div>
- <div className="flex gap-3 items-center">
- <Dropdown
- size="small"
- side="bottom"
- align="start"
- style={{ zIndex: 1 }}
- overlay={[
- <Dropdown.Item
- key="alphabetical"
- icon={
- sort === 'alphabetical' ? (
- <IconCheck size="tiny" />
- ) : (
- <div className="w-[14px] h-[14px]" />
- )
- }
- onClick={() => {
- setSort('alphabetical')
- }}
- >
- Alphabetical
- </Dropdown.Item>,
- <Dropdown.Item
- key="grouped-alphabetical"
- icon={
- sort === 'grouped-alphabetical' ? (
- <IconCheck size="tiny" />
- ) : (
- <div className="w-[14px] h-[14px]" />
- )
- }
- onClick={() => {
- setSort('grouped-alphabetical')
- }}
- >
- Entity Type
- </Dropdown.Item>,
- ]}
- >
- <Tooltip.Root delayDuration={0}>
- <Tooltip.Trigger asChild>
- <div className="text-scale-900 transition-colors hover:text-scale-1200">
- <IconChevronsDown size={18} strokeWidth={1} />
- </div>
- </Tooltip.Trigger>
- <Tooltip.Portal>
- <Tooltip.Content side="bottom">
- <Tooltip.Arrow className="radix-tooltip-arrow" />
- <div
- className={[
- 'rounded bg-scale-100 py-1 px-2 leading-none shadow',
- 'border border-scale-200',
- ].join(' ')}
- >
- <span className="text-xs">Sort By</span>
+ {isLoading ? (
+ <div className="mx-4 flex items-center space-x-2">
+ <IconLoader className="animate-spin" size={14} strokeWidth={1.5} />
+ <p className="text-sm text-scale-1000">Loading entities...</p>
+ </div>
+ ) : searchText.length === 0 && (entityTypes?.length ?? 0) === 0 ? (
+ <div className="mx-4 space-y-1 rounded-md border border-scale-400 bg-scale-300 py-3 px-4">
+ <p className="text-xs">No entities available</p>
+ <p className="text-xs text-scale-1100">This schema has no entities available yet</p>
+ </div>
+ ) : searchText.length > 0 && (entityTypes?.length ?? 0) === 0 ? (
+ <div className="mx-4 space-y-1 rounded-md border border-scale-400 bg-scale-300 py-3 px-4">
+ <p className="text-xs">No results found</p>
+ <p className="text-xs text-scale-1100">There are no entities that match your search</p>
+ </div>
+ ) : (
+ <Menu
+ type="pills"
+ className="flex flex-auto px-2 space-y-6 pb-4"
+ ulClassName="flex flex-auto flex-col"
+ >
+ <Menu.Group
+ // @ts-ignore
+ title={
+ <>
+ <div className="flex w-full items-center justify-between">
+ <div className="flex items-center space-x-1">
+ <p>Tables</p>
+ {totalCount !== undefined && (
+ <p style={{ fontVariantNumeric: 'tabular-nums' }}>({totalCount})</p>
+ )}
+ </div>
+
+ <div className="flex gap-3 items-center">
+ <Dropdown
+ size="small"
+ side="bottom"
+ align="start"
+ style={{ zIndex: 1 }}
+ overlay={[
+ <Dropdown.Item
+ key="alphabetical"
+ icon={
+ sort === 'alphabetical' ? (
+ <IconCheck size="tiny" />
+ ) : (
+ <div className="w-[14px] h-[14px]" />
+ )
+ }
+ onClick={() => {
+ setSort('alphabetical')
+ }}
+ >
+ Alphabetical
+ </Dropdown.Item>,
+ <Dropdown.Item
+ key="grouped-alphabetical"
+ icon={
+ sort === 'grouped-alphabetical' ? (
+ <IconCheck size="tiny" />
+ ) : (
+ <div className="w-[14px] h-[14px]" />
+ )
+ }
+ onClick={() => {
+ setSort('grouped-alphabetical')
+ }}
+ >
+ Entity Type
+ </Dropdown.Item>,
+ ]}
+ >
+ <Tooltip.Root delayDuration={0}>
+ <Tooltip.Trigger asChild>
+ <div className="text-scale-900 transition-colors hover:text-scale-1200">
+ <IconChevronsDown size={18} strokeWidth={1} />
</div>
- </Tooltip.Content>
- </Tooltip.Portal>
- </Tooltip.Root>
- </Dropdown>
+ </Tooltip.Trigger>
+ <Tooltip.Portal>
+ <Tooltip.Content side="bottom">
+ <Tooltip.Arrow className="radix-tooltip-arrow" />
+ <div
+ className={[
+ 'rounded bg-scale-100 py-1 px-2 leading-none shadow',
+ 'border border-scale-200',
+ ].join(' ')}
+ >
+ <span className="text-xs">Sort By</span>
+ </div>
+ </Tooltip.Content>
+ </Tooltip.Portal>
+ </Tooltip.Root>
+ </Dropdown>
- <button
- className="cursor-pointer text-scale-900 transition-colors hover:text-scale-1200"
- onClick={refreshTables}
- >
- <IconRefreshCw className={isRefetching ? 'animate-spin' : ''} size={14} />
- </button>
+ <button
+ className="cursor-pointer text-scale-900 transition-colors hover:text-scale-1200"
+ onClick={refreshTables}
+ >
+ <IconRefreshCw className={isRefetching ? 'animate-spin' : ''} size={14} />
+ </button>
+ </div>
</div>
- </div>
- </>
- }
- />
-
- <div className="flex flex-1">
- <InfiniteList
- items={entityTypes}
- ItemComponent={EntityListItem}
- itemProps={{
- projectRef: project?.ref,
- id: Number(id),
- }}
- getItemSize={() => 28}
- hasNextPage={hasNextPage}
- isLoadingNextPage={isFetchingNextPage}
- onLoadNextPage={() => fetchNextPage()}
+ </>
+ }
/>
+
+ <div className="flex flex-1">
+ <InfiniteList
+ items={entityTypes}
+ ItemComponent={EntityListItem}
+ itemProps={{
+ projectRef: project?.ref,
+ id: Number(id),
+ }}
+ getItemSize={() => 28}
+ hasNextPage={hasNextPage}
+ isLoadingNextPage={isFetchingNextPage}
+ onLoadNextPage={() => fetchNextPage()}
+ />
+ </div>
+ </Menu>
+ )}
+ </div>
+
+ <Modal
+ size="medium"
+ visible={showModal}
+ header="Schemas managed by Supabase"
+ customFooter={
+ <div className="flex items-center justify-end space-x-2">
+ <Button type="default" onClick={() => setShowModal(false)}>
+ Understood
+ </Button>
+ </div>
+ }
+ onCancel={() => setShowModal(false)}
+ >
+ <Modal.Content className="py-4 space-y-2">
+ <p className="text-sm">
+ The following schemas are managed by Supabase and are currently protected from write
+ access through the Table Editor.
+ </p>
+ <div className="flex flex-wrap gap-1">
+ {EXCLUDED_SCHEMAS.map((schema) => (
+ <code key={schema} className="text-xs">
+ {schema}
+ </code>
+ ))}
</div>
- </Menu>
- )}
- </div>
+ <p className="text-sm !mt-4">
+ These schemas are critical to the functionality of your Supabase project and hence we
+ highly recommend not altering them.
+ </p>
+ <p className="text-sm">
+ You can, however, still interact with those schemas through the SQL Editor although we
+ advise you only do so if you know what you are doing.
+ </p>
+ </Modal.Content>
+ </Modal>
+ </>
)
}
diff --git a/studio/data/database/schema-create-mutation.ts b/studio/data/database/schema-create-mutation.ts
new file mode 100644
index 00000000000..a5519a6e9aa
--- /dev/null
+++ b/studio/data/database/schema-create-mutation.ts
@@ -0,0 +1,63 @@
+import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'
+import { toast } from 'react-hot-toast'
+
+import { post } from 'data/fetchers'
+import { ResponseError } from 'types'
+import { databaseKeys } from './keys'
+
+export type SchemaCreateVariables = {
+ name: string
+ projectRef?: string
+ connectionString?: string
+}
+
+export async function createSchema({ name, projectRef, connectionString }: SchemaCreateVariables) {
+ if (!projectRef) throw new Error('projectRef is required')
+ if (!connectionString) throw new Error('Connection string is required')
+
+ let headers = new Headers()
+ headers.set('x-connection-encrypted', connectionString)
+
+ const { data, error } = await post('/platform/pg-meta/{ref}/schemas', {
+ params: {
+ header: { 'x-connection-encrypted': connectionString },
+ path: { ref: projectRef },
+ },
+ body: { name, owner: 'postgres' },
+ headers: Object.fromEntries(headers),
+ })
+
+ if (error) throw error
+ return data
+}
+
+type SchemaCreateData = Awaited<ReturnType<typeof createSchema>>
+
+export const useSchemaCreateMutation = ({
+ onSuccess,
+ onError,
+ ...options
+}: Omit<
+ UseMutationOptions<SchemaCreateData, ResponseError, SchemaCreateVariables>,
+ 'mutationFn'
+> = {}) => {
+ const queryClient = useQueryClient()
+ return useMutation<SchemaCreateData, ResponseError, SchemaCreateVariables>(
+ (vars) => createSchema(vars),
+ {
+ async onSuccess(data, variables, context) {
+ const { projectRef } = variables
+ await queryClient.invalidateQueries(databaseKeys.schemaList(projectRef))
+ await onSuccess?.(data, variables, context)
+ },
+ async onError(data, variables, context) {
+ if (onError === undefined) {
+ toast.error(`Failed to create schema: ${data.message}`)
+ } else {
+ onError(data, variables, context)
+ }
+ },
+ ...options,
+ }
+ )
+}
diff --git a/studio/state/table-editor.tsx b/studio/state/table-editor.tsx
index 3b38c94f5e1..ccbb13ac511 100644
--- a/studio/state/table-editor.tsx
+++ b/studio/state/table-editor.tsx
@@ -15,6 +15,7 @@ export type SidePanel =
| { type: 'row'; row?: Dictionary<any> }
| { type: 'column'; column?: PostgresColumn }
| { type: 'table'; mode: 'new' | 'edit' | 'duplicate' }
+ | { type: 'schema'; mode: 'new' | 'edit' }
| { type: 'json'; jsonValue: JsonEditValue }
| {
type: 'foreign-row-selector'
@@ -61,6 +62,13 @@ export const createTableEditorState = () => {
state.ui = { open: 'none' }
},
+ onAddSchema: () => {
+ state.ui = {
+ open: 'side-panel',
+ sidePanel: { type: 'schema', mode: 'new' },
+ }
+ },
+
/* Tables */
onAddTable: () => {
state.ui = {