Files
supabase/apps/studio/data/table-rows/table-row-create-mutation.ts
T
Andrew Valleteau eb7efdef7f chore(studio): move Query to pgMeta add tests (#34232)
* chore(studio): move Query to pgMeta add tests

- Move the Query builder from studio to pgMeta
- Add e2e tests over the generated sql to ensure syntax and runtime
  result over pg database
- fix bug with orde by for table with undefined column

* chore: fix query import path

* chore: set ES target for lint

* chore: add github action for pg-meta test package

* chore: add tsconfig to sparse checkout
2025-03-20 19:04:58 +00:00

91 lines
2.5 KiB
TypeScript

import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'
import { toast } from 'sonner'
import { Query } from '@supabase/pg-meta/src/query'
import { executeSql } from 'data/sql/execute-sql-query'
import { ImpersonationRole, wrapWithRoleImpersonation } from 'lib/role-impersonation'
import { isRoleImpersonationEnabled } from 'state/role-impersonation-state'
import type { ResponseError } from 'types'
import { tableRowKeys } from './keys'
export type TableRowCreateVariables = {
projectRef: string
connectionString?: string
table: { id: number; name: string; schema?: string }
payload: any
enumArrayColumns: string[]
returning?: boolean
impersonatedRole?: ImpersonationRole
}
export function getTableRowCreateSql({
table,
payload,
returning = false,
enumArrayColumns,
}: Pick<TableRowCreateVariables, 'table' | 'payload' | 'enumArrayColumns' | 'returning'>) {
return new Query()
.from(table.name, table.schema ?? undefined)
.insert([payload], { returning, enumArrayColumns })
.toSql()
}
export async function createTableRow({
projectRef,
connectionString,
table,
payload,
enumArrayColumns,
returning,
impersonatedRole,
}: TableRowCreateVariables) {
const sql = wrapWithRoleImpersonation(
getTableRowCreateSql({ table, payload, enumArrayColumns, returning }),
{
projectRef,
role: impersonatedRole,
}
)
const { result } = await executeSql({
projectRef,
connectionString,
sql,
isRoleImpersonationEnabled: isRoleImpersonationEnabled(impersonatedRole),
})
return result
}
type TableRowCreateData = Awaited<ReturnType<typeof createTableRow>>
export const useTableRowCreateMutation = ({
onSuccess,
onError,
...options
}: Omit<
UseMutationOptions<TableRowCreateData, ResponseError, TableRowCreateVariables>,
'mutationFn'
> = {}) => {
const queryClient = useQueryClient()
return useMutation<TableRowCreateData, ResponseError, TableRowCreateVariables>(
(vars) => createTableRow(vars),
{
async onSuccess(data, variables, context) {
const { projectRef, table } = variables
await queryClient.invalidateQueries(tableRowKeys.tableRowsAndCount(projectRef, table.id))
await onSuccess?.(data, variables, context)
},
async onError(data, variables, context) {
if (onError === undefined) {
toast.error(data.message)
} else {
onError(data, variables, context)
}
},
...options,
}
)
}