Files
supabase/apps/studio/data/tables/table-create-mutation.ts
T
e81442de56 chore: Migrate TableStore (#20033)
* Add create, update and delete mutations for tables.

* Use the new mutations instead of the table store.

* Fully remove the TableStore from the MetaStore.

* Move the methods from MetaStore into pure functions in SidePanelEditor utils.

* Remove TableStore.

* Refactor the onError callbacks to be on the mutations.

* Convert some of the UIStore invocations.

* Fixed not closing the modal in case of an error. Migrate some uses of uiStore.

* Use onSettled on all RQ hooks.

* Remove the ui param to the create/updateTable functions.

* Add a missing connection string.

* Add progress bar for loading UI for importing rows

* Update apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.tsx

Co-authored-by: Alaister Young <alaister@users.noreply.github.com>

---------

Co-authored-by: Joshen Lim <joshenlimek@gmail.com>
Co-authored-by: Alaister Young <alaister@users.noreply.github.com>
2024-02-06 14:56:59 +08:00

67 lines
1.9 KiB
TypeScript

import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'
import { toast } from 'react-hot-toast'
import { components } from 'data/api'
import { post } from 'data/fetchers'
import { ResponseError } from 'types'
import { tableKeys } from './keys'
export type CreateTableBody = components['schemas']['CreateTableBody']
export type TableCreateVariables = {
projectRef: string
connectionString?: string
// the schema is required field
payload: CreateTableBody & { schema: string }
}
export async function createTable({ projectRef, connectionString, payload }: TableCreateVariables) {
let headers = new Headers()
if (connectionString) headers.set('x-connection-encrypted', connectionString)
const { data, error } = await post('/platform/pg-meta/{ref}/tables', {
params: {
header: { 'x-connection-encrypted': connectionString! },
path: { ref: projectRef },
},
body: payload,
headers,
})
if (error) throw error
return data
}
type TableCreateData = Awaited<ReturnType<typeof createTable>>
export const useTableCreateMutation = ({
onSuccess,
onError,
...options
}: Omit<
UseMutationOptions<TableCreateData, ResponseError, TableCreateVariables>,
'mutationFn'
> = {}) => {
const queryClient = useQueryClient()
return useMutation<TableCreateData, ResponseError, TableCreateVariables>(
(vars) => createTable(vars),
{
async onSuccess(data, variables, context) {
const { projectRef, payload } = variables
await queryClient.invalidateQueries(tableKeys.list(projectRef, payload.schema))
await onSuccess?.(data, variables, context)
},
async onError(data, variables, context) {
if (onError === undefined) {
toast.error(`Failed to create database table: ${data.message}`)
} else {
onError(data, variables, context)
}
},
...options,
}
)
}