Files
supabase/apps/studio/data/table-rows/get-cell-value-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

67 lines
1.7 KiB
TypeScript

import { useMutation, UseMutationOptions } 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 type { ResponseError } from 'types'
export type GetCellValueVariables = {
projectRef: string
connectionString?: string
table: { schema: string; name: string }
column: string
pkMatch: { [key: string]: any }
}
export function getCellValueSql({
table,
column,
pkMatch,
}: Pick<GetCellValueVariables, 'table' | 'column' | 'pkMatch'>) {
return new Query()
.from(table.name, table.schema ?? undefined)
.select(`"${column}"`)
.match(pkMatch)
.toSql()
}
export async function getCellValue({
projectRef,
connectionString,
table,
column,
pkMatch,
}: GetCellValueVariables) {
const sql = getCellValueSql({ table, column, pkMatch })
const { result } = await executeSql({ projectRef, connectionString, sql })
return result?.[0][column]
}
type TableRowCreateData = Awaited<ReturnType<typeof getCellValue>>
export const useGetCellValueMutation = ({
onSuccess,
onError,
...options
}: Omit<
UseMutationOptions<TableRowCreateData, ResponseError, GetCellValueVariables>,
'mutationFn'
> = {}) => {
return useMutation<TableRowCreateData, ResponseError, GetCellValueVariables>(
(vars) => getCellValue(vars),
{
async onSuccess(data, variables, context) {
await onSuccess?.(data, variables, context)
},
async onError(data, variables, context) {
if (onError === undefined) {
toast.error(data.message)
} else {
onError(data, variables, context)
}
},
...options,
}
)
}