Files
supabase/apps/studio/data/tables/table-create-mutation.ts
Han Qiao b09440bd47 fix: move table create update delete to query route (#35662)
* fix: move table create update delete to query route

* chore: implement query to fetch a single table

* fix: retrieve table after update

* chore: assign type to update table payload

* chore: use updated table columns for edit

* chore: make executeSql castable with generic (#35685)

* Chore/refactor derivate more types from queries (#35687)

* chore: make executeSql castable with generic

* chore: derivate types from performed queries

- It allows to decouple more the frontend logic and the pg-meta/sql-query logic allowing to reduce the number of cast
and get closer types between what we do fetch and what we expect in our components

* fix: remove existing check

* chore: handle null comment and check

* fix: format check name as identifier

---------

Co-authored-by: avallete <andrew.valleteau@supabase.io>
Co-authored-by: Andrew Valleteau <avallete@users.noreply.github.com>
2025-05-20 10:34:59 +08:00

67 lines
1.9 KiB
TypeScript

import pgMeta from '@supabase/pg-meta'
import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'
import { toast } from 'sonner'
import type { components } from 'data/api'
import { executeSql } from 'data/sql/execute-sql-query'
import type { ResponseError } from 'types'
import { tableKeys } from './keys'
export type CreateTableBody = components['schemas']['CreateTableBody']
export type TableCreateVariables = {
projectRef: string
connectionString?: string | null
// the schema is required field
payload: CreateTableBody & { schema: string }
}
export async function createTable({ projectRef, connectionString, payload }: TableCreateVariables) {
const { sql } = pgMeta.tables.create(payload)
const { result } = await executeSql<void>({
projectRef,
connectionString,
sql,
queryKey: ['table', 'create'],
})
return result
}
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 Promise.all([
queryClient.invalidateQueries(tableKeys.list(projectRef, payload.schema, true)),
queryClient.invalidateQueries(tableKeys.list(projectRef, payload.schema, false)),
])
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,
}
)
}