Skip to content

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

fix: move table create update delete to query route (#35662)

Han Qiaob09440bd47b9
diff --git a/apps/studio/components/interfaces/Auth/Policies/Policies.tsx b/apps/studio/components/interfaces/Auth/Policies/Policies.tsx
index 49c0947073a..ebb2a327ee1 100644
--- a/apps/studio/components/interfaces/Auth/Policies/Policies.tsx
+++ b/apps/studio/components/interfaces/Auth/Policies/Policies.tsx
@@ -99,7 +99,8 @@ const Policies = ({
updateTable({
projectRef: project?.ref!,
connectionString: project?.connectionString,
- id: payload.id,
+ id: selectedTableToToggleRLS.id,
+ name: selectedTableToToggleRLS.name,
schema: selectedTableToToggleRLS.schema,
payload: payload,
})
diff --git a/apps/studio/components/interfaces/Integrations/Queues/QueueTab.tsx b/apps/studio/components/interfaces/Integrations/Queues/QueueTab.tsx
index 56c19e5344e..53a53ae4888 100644
--- a/apps/studio/components/interfaces/Integrations/Queues/QueueTab.tsx
+++ b/apps/studio/components/interfaces/Integrations/Queues/QueueTab.tsx
@@ -91,7 +91,8 @@ export const QueueTab = () => {
updateTable({
projectRef: project?.ref,
connectionString: project?.connectionString,
- id: payload.id,
+ id: queueTable.id,
+ name: queueTable.name,
schema: 'pgmq',
payload: payload,
})
diff --git a/apps/studio/components/interfaces/Integrations/Queues/QueuesSettings.tsx b/apps/studio/components/interfaces/Integrations/Queues/QueuesSettings.tsx
index 6d7471e1e0e..e5ceebe670a 100644
--- a/apps/studio/components/interfaces/Integrations/Queues/QueuesSettings.tsx
+++ b/apps/studio/components/interfaces/Integrations/Queues/QueuesSettings.tsx
@@ -138,6 +138,7 @@ export const QueuesSettings = () => {
projectRef: project?.ref,
connectionString: project?.connectionString,
id: x.id,
+ name: x.name,
schema: x.schema,
payload: { id: x.id, rls_enabled: true },
})
diff --git a/apps/studio/components/interfaces/TableGridEditor/DeleteConfirmationDialogs.tsx b/apps/studio/components/interfaces/TableGridEditor/DeleteConfirmationDialogs.tsx
index 971ec3fda43..02989bf3690 100644
--- a/apps/studio/components/interfaces/TableGridEditor/DeleteConfirmationDialogs.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/DeleteConfirmationDialogs.tsx
@@ -149,8 +149,9 @@ const DeleteConfirmationDialogs = ({
deleteTable({
projectRef: project?.ref!,
connectionString: project?.connectionString,
- schema: selectedTableToDelete.schema,
id: selectedTableToDelete.id,
+ name: selectedTableToDelete.name,
+ schema: selectedTableToDelete.schema,
cascade: isDeleteWithCascade,
})
}
diff --git a/apps/studio/components/interfaces/TableGridEditor/GridHeaderActions.tsx b/apps/studio/components/interfaces/TableGridEditor/GridHeaderActions.tsx
index 28b749dea85..a14889e5736 100644
--- a/apps/studio/components/interfaces/TableGridEditor/GridHeaderActions.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/GridHeaderActions.tsx
@@ -177,7 +177,8 @@ const GridHeaderActions = ({ table }: GridHeaderActionsProps) => {
updateTable({
projectRef: project?.ref!,
connectionString: project?.connectionString,
- id: payload.id,
+ id: table.id,
+ name: table.name,
schema: table.schema,
payload: payload,
})
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.utils.ts b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.utils.ts
index ed670017759..ec127adad74 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.utils.ts
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.utils.ts
@@ -1,4 +1,4 @@
-import type { PostgresColumn, PostgresTable } from '@supabase/postgres-meta'
+import type { PostgresColumn } from '@supabase/postgres-meta'
import { isEqual, isNull } from 'lodash'
import type { Dictionary } from 'types'
@@ -11,6 +11,7 @@ import {
ExtendedPostgresRelationship,
UpdateColumnPayload,
} from '../SidePanelEditor.types'
+import type { RetrievedTableColumn, RetrieveTableResult } from 'data/tables/table-retrieve-query'
const isSQLExpression = (input: string) => {
if (['CURRENT_DATE'].includes(input)) return true
@@ -54,7 +55,7 @@ export const generateColumnField = (field: any = {}): ColumnField => {
export const generateColumnFieldFromPostgresColumn = (
column: PostgresColumn,
- table: PostgresTable,
+ table: RetrieveTableResult,
foreignKeys: ForeignKeyConstraint[]
): ColumnField => {
const { primary_keys } = table
@@ -84,7 +85,7 @@ export const generateColumnFieldFromPostgresColumn = (
}
export const generateCreateColumnPayload = (
- table: PostgresTable,
+ table: RetrieveTableResult,
field: ColumnField
): CreateColumnPayload => {
const isIdentity = field.format.includes('int') ? field.isIdentity : false
@@ -114,8 +115,8 @@ export const generateCreateColumnPayload = (
}
export const generateUpdateColumnPayload = (
- originalColumn: PostgresColumn,
- table: PostgresTable,
+ originalColumn: RetrievedTableColumn,
+ table: RetrieveTableResult,
field: ColumnField
): Partial<UpdateColumnPayload> => {
const primaryKeyColumns = table.primary_keys.map((key) => key.name)
@@ -124,8 +125,7 @@ export const generateUpdateColumnPayload = (
// Only append the properties which are getting updated
const name = field.name.trim()
const type = field.isArray ? `${field.format}[]` : field.format
- const comment = ((field.comment?.length ?? '') === 0 ? '' : field.comment)?.trim()
-
+ const comment = field.comment?.trim()
const check = field.check?.trim()
const payload: Partial<UpdateColumnPayload> = {}
@@ -135,10 +135,10 @@ export const generateUpdateColumnPayload = (
payload.name = name
}
if (!isEqual(originalColumn.comment?.trim(), comment)) {
- payload.comment = comment as string | undefined
+ payload.comment = comment || null
}
if (!isEqual(originalColumn.check?.trim(), check)) {
- payload.check = check
+ payload.check = check || null
}
if (!isEqual(originalColumn.format, type)) {
@@ -148,9 +148,7 @@ export const generateUpdateColumnPayload = (
const defaultValue = field.defaultValue
payload.defaultValue = defaultValue as unknown as Record<string, never> | undefined
payload.defaultValueFormat =
- isNull(defaultValue) || isSQLExpression(defaultValue)
- ? 'expression'
- : ('literal' as 'expression' | 'literal')
+ isNull(defaultValue) || isSQLExpression(defaultValue) ? 'expression' : 'literal'
}
if (!isEqual(originalColumn.is_identity, field.isIdentity)) {
payload.isIdentity = field.isIdentity
@@ -206,7 +204,7 @@ export const getForeignKeyUIState = (
export const getColumnForeignKey = (
column: PostgresColumn,
- table: PostgresTable,
+ table: RetrieveTableResult,
foreignKeys: ForeignKeyConstraint[]
) => {
const { relationships } = table
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx
index 8c17af59bdc..2bfb205ed15 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx
@@ -50,6 +50,7 @@ import {
import SpreadsheetImport from './SpreadsheetImport/SpreadsheetImport'
import TableEditor from './TableEditor/TableEditor'
import type { ImportContent } from './TableEditor/TableEditor.types'
+import { RetrieveTableResult } from 'data/tables/table-retrieve-query'
export interface SidePanelEditorProps {
editable?: boolean
@@ -58,7 +59,7 @@ export interface SidePanelEditorProps {
// Because the panel is shared between grid editor and database pages
// Both require different responses upon success of these events
- onTableCreated?: (table: PostgresTable) => void
+ onTableCreated?: (table: RetrieveTableResult) => void
}
const SidePanelEditor = ({
@@ -229,7 +230,7 @@ const SidePanelEditor = ({
resolve: any
) => {
const selectedColumnToEdit = snap.sidePanel?.type === 'column' && snap.sidePanel.column
- const { columnId, primaryKey, foreignKeyRelations, existingForeignKeyRelations } = configuration
+ const { primaryKey, foreignKeyRelations, existingForeignKeyRelations } = configuration
if (!project || selectedTable === undefined) {
return console.error('no project or table selected')
@@ -313,7 +314,7 @@ const SidePanelEditor = ({
})
}
- const updateTableRealtime = async (table: PostgresTable, enabled: boolean) => {
+ const updateTableRealtime = async (table: RetrieveTableResult, enabled: boolean) => {
if (!project) return console.error('Project is required')
const realtimePublication = publications?.find((pub) => pub.name === 'supabase_realtime')
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.tsx
index cff05312b88..18a5554960f 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.tsx
@@ -1,4 +1,4 @@
-import type { PostgresColumn, PostgresPrimaryKey, PostgresTable } from '@supabase/postgres-meta'
+import type { PostgresPrimaryKey } from '@supabase/postgres-meta'
import { chunk, find, isEmpty, isEqual } from 'lodash'
import Papa from 'papaparse'
import { toast } from 'sonner'
@@ -22,8 +22,16 @@ import { tableRowKeys } from 'data/table-rows/keys'
import { tableKeys } from 'data/tables/keys'
import { createTable as createTableMutation } from 'data/tables/table-create-mutation'
import { deleteTable as deleteTableMutation } from 'data/tables/table-delete-mutation'
-import { updateTable as updateTableMutation } from 'data/tables/table-update-mutation'
+import {
+ UpdateTableBody,
+ updateTable as updateTableMutation,
+} from 'data/tables/table-update-mutation'
import { getTables } from 'data/tables/tables-query'
+import {
+ getTable,
+ RetrievedTableColumn,
+ RetrieveTableResult,
+} from 'data/tables/table-retrieve-query'
import { timeout, tryParseJson } from 'lib/helpers'
import {
generateCreateColumnPayload,
@@ -220,7 +228,7 @@ export const createColumn = async ({
projectRef: string
connectionString?: string | null
payload: CreateColumnPayload
- selectedTable: PostgresTable
+ selectedTable: RetrieveTableResult
primaryKey?: Constraint
foreignKeyRelations?: ForeignKey[]
skipSuccessMessage?: boolean
@@ -296,9 +304,9 @@ export const updateColumn = async ({
}: {
projectRef: string
connectionString?: string | null
- originalColumn: PostgresColumn
+ originalColumn: RetrievedTableColumn
payload: UpdateColumnPayload
- selectedTable: PostgresTable
+ selectedTable: RetrieveTableResult
primaryKey?: Constraint
foreignKeyRelations?: ForeignKey[]
existingForeignKeyRelations?: ForeignKeyConstraint[]
@@ -366,7 +374,7 @@ export const duplicateTable = async (
connectionString: string | undefined | null,
payload: { name: string; comment?: string },
metadata: {
- duplicateTable: PostgresTable
+ duplicateTable: RetrieveTableResult
isRLSEnabled: boolean
isDuplicateRows: boolean
foreignKeyRelations: ForeignKey[]
@@ -434,6 +442,7 @@ export const duplicateTable = async (
projectRef,
connectionString,
id: duplicatedTable?.id!,
+ name: duplicatedTable?.name!,
schema: duplicatedTable?.schema!,
payload: { rls_enabled: isRLSEnabled },
})
@@ -468,12 +477,21 @@ export const createTable = async ({
const queryClient = getQueryClient()
// Create the table first. Error may be thrown.
- const table = await createTableMutation({
+ await createTableMutation({
projectRef: projectRef,
connectionString: connectionString,
payload: payload,
})
+ const table = await queryClient.fetchQuery({
+ queryKey: tableKeys.retrieve(projectRef, payload.name, payload.schema),
+ queryFn: ({ signal }) =>
+ getTable(
+ { projectRef, connectionString, name: payload.name, schema: payload.schema },
+ signal
+ ),
+ })
+
// If we face any errors during this process after the actual table creation
// We'll delete the table as a way to clean up and not leave behind bits that
// got through successfully. This is so that the user can continue editing in
@@ -485,6 +503,7 @@ export const createTable = async ({
projectRef,
connectionString,
id: table.id,
+ name: table.name,
schema: table.schema,
payload: { rls_enabled: isRLSEnabled },
})
@@ -625,6 +644,7 @@ export const createTable = async ({
projectRef,
connectionString,
id: table.id,
+ name: table.name,
schema: table.schema,
})
throw error
@@ -645,13 +665,15 @@ export const updateTable = async ({
projectRef: string
connectionString?: string | null
toastId: string | number
- table: PostgresTable
- payload: any
+ table: RetrieveTableResult
+ payload: UpdateTableBody
columns: ColumnField[]
foreignKeyRelations: ForeignKey[]
existingForeignKeyRelations: ForeignKeyConstraint[]
primaryKey?: Constraint
}) => {
+ const queryClient = getQueryClient()
+
// Prepare a check to see if primary keys to the tables were updated or not
const primaryKeyColumns = columns
.filter((column) => column.isPrimaryKey)
@@ -671,15 +693,34 @@ export const updateTable = async ({
}
// Update the table
- const updatedTable = await updateTableMutation({
+ await updateTableMutation({
projectRef,
connectionString,
id: table.id,
+ name: table.name,
schema: table.schema,
payload,
})
- const originalColumns = table.columns ?? []
+ const updatedTable = await queryClient.fetchQuery({
+ queryKey: tableKeys.retrieve(
+ projectRef,
+ payload.name ?? table.name,
+ payload.schema ?? table.schema
+ ),
+ queryFn: ({ signal }) =>
+ getTable(
+ {
+ projectRef,
+ connectionString,
+ name: payload.name ?? table.name,
+ schema: payload.schema ?? table.schema,
+ },
+ signal
+ ),
+ })
+
+ const originalColumns = updatedTable.columns ?? []
const columnIds = columns.map((column) => column.id)
// Delete any removed columns
@@ -758,8 +799,6 @@ export const updateTable = async ({
existingForeignKeyRelations,
})
- const queryClient = getQueryClient()
-
await Promise.all([
queryClient.invalidateQueries(tableEditorKeys.tableEditor(projectRef, table.id)),
queryClient.invalidateQueries(databaseKeys.foreignKeyConstraints(projectRef, table.schema)),
@@ -786,7 +825,7 @@ export const insertRowsViaSpreadsheet = async (
projectRef: string,
connectionString: string | undefined | null,
file: any,
- table: PostgresTable,
+ table: RetrieveTableResult,
selectedHeaders: string[],
onProgressUpdate: (progress: number) => void
) => {
@@ -847,7 +886,7 @@ export const insertRowsViaSpreadsheet = async (
export const insertTableRows = async (
projectRef: string,
connectionString: string | undefined | null,
- table: PostgresTable,
+ table: RetrieveTableResult,
rows: any,
selectedHeaders: string[],
onProgressUpdate: (progress: number) => void
diff --git a/apps/studio/data/database-columns/database-column-delete-mutation.ts b/apps/studio/data/database-columns/database-column-delete-mutation.ts
index 11717e92da3..41325ebb3af 100644
--- a/apps/studio/data/database-columns/database-column-delete-mutation.ts
+++ b/apps/studio/data/database-columns/database-column-delete-mutation.ts
@@ -26,7 +26,7 @@ export async function deleteDatabaseColumn({
}: DatabaseColumnDeleteVariables) {
const { sql } = pgMeta.columns.remove(column, { cascade })
- const { result } = await executeSql({
+ const { result } = await executeSql<void>({
projectRef,
connectionString,
sql,
diff --git a/apps/studio/data/database-columns/database-column-update-mutation.ts b/apps/studio/data/database-columns/database-column-update-mutation.ts
index 17df890a1bb..ac3db6c0772 100644
--- a/apps/studio/data/database-columns/database-column-update-mutation.ts
+++ b/apps/studio/data/database-columns/database-column-update-mutation.ts
@@ -7,7 +7,13 @@ import type { components } from 'data/api'
import { executeSql } from 'data/sql/execute-sql-query'
import type { ResponseError } from 'types'
-export type UpdateColumnBody = components['schemas']['UpdateColumnBody']
+export type UpdateColumnBody = Omit<
+ components['schemas']['UpdateColumnBody'],
+ 'check' | 'comment'
+> & {
+ check?: string | null
+ comment?: string | null
+}
export type DatabaseColumnUpdateVariables = {
projectRef: string
@@ -23,7 +29,7 @@ export type DatabaseColumnUpdateVariables = {
| 'is_identity'
| 'is_unique'
>
- payload: components['schemas']['UpdateColumnBody']
+ payload: UpdateColumnBody
}
export async function updateDatabaseColumn({
diff --git a/apps/studio/data/sql/execute-sql-query.ts b/apps/studio/data/sql/execute-sql-query.ts
index 5c321c5c3d4..b172ab00514 100644
--- a/apps/studio/data/sql/execute-sql-query.ts
+++ b/apps/studio/data/sql/execute-sql-query.ts
@@ -21,7 +21,7 @@ export type ExecuteSqlVariables = {
contextualInvalidation?: boolean
}
-export async function executeSql(
+export async function executeSql<T = any>(
{
projectRef,
connectionString,
@@ -40,7 +40,7 @@ export async function executeSql(
>,
signal?: AbortSignal,
headersInit?: HeadersInit
-): Promise<{ result: any }> {
+): Promise<{ result: T }> {
if (!projectRef) throw new Error('projectRef is required')
const sqlSize = new Blob([sql]).size
@@ -107,13 +107,13 @@ export async function executeSql(
Array.isArray(data) &&
data?.[0]?.[ROLE_IMPERSONATION_NO_RESULTS] === 1
) {
- return { result: [] }
+ return { result: [] as T }
}
- return { result: data }
+ return { result: data as T }
}
-export type ExecuteSqlData = Awaited<ReturnType<typeof executeSql>>
+export type ExecuteSqlData = Awaited<ReturnType<typeof executeSql<any[]>>>
export type ExecuteSqlError = ResponseError
/**
diff --git a/apps/studio/data/tables/keys.ts b/apps/studio/data/tables/keys.ts
index 2d5ccc776a1..ae12de36996 100644
--- a/apps/studio/data/tables/keys.ts
+++ b/apps/studio/data/tables/keys.ts
@@ -1,6 +1,8 @@
export const tableKeys = {
list: (projectRef: string | undefined, schema?: string, includeColumns?: boolean) =>
['projects', projectRef, 'tables', schema, includeColumns].filter(Boolean),
+ retrieve: (projectRef: string | undefined, name: string, schema: string) =>
+ ['projects', projectRef, 'tables', schema, name].filter(Boolean),
rolesAccess: (projectRef: string | undefined, schema: string, table: string) => [
'projects',
projectRef,
diff --git a/apps/studio/data/tables/table-create-mutation.ts b/apps/studio/data/tables/table-create-mutation.ts
index b1362801843..cc81e596e8d 100644
--- a/apps/studio/data/tables/table-create-mutation.ts
+++ b/apps/studio/data/tables/table-create-mutation.ts
@@ -1,9 +1,9 @@
-import type { PostgresTable } from '@supabase/postgres-meta'
+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 { handleError, post } from 'data/fetchers'
+import { executeSql } from 'data/sql/execute-sql-query'
import type { ResponseError } from 'types'
import { tableKeys } from './keys'
@@ -17,23 +17,16 @@ export type TableCreateVariables = {
}
export async function createTable({ projectRef, connectionString, payload }: TableCreateVariables) {
- let headers = new Headers()
- if (connectionString) headers.set('x-connection-encrypted', connectionString)
+ const { sql } = pgMeta.tables.create(payload)
- const { data, error } = await post('/platform/pg-meta/{ref}/tables', {
- params: {
- header: { 'x-connection-encrypted': connectionString! },
- path: { ref: projectRef },
- },
- body: payload,
- headers,
+ const { result } = await executeSql<void>({
+ projectRef,
+ connectionString,
+ sql,
+ queryKey: ['table', 'create'],
})
- if (error) handleError(error)
-
- // [Alaister] we have to manually cast the data to PostgresTable
- // because the API types are slightly wrong
- return data as PostgresTable
+ return result
}
type TableCreateData = Awaited<ReturnType<typeof createTable>>
diff --git a/apps/studio/data/tables/table-delete-mutation.ts b/apps/studio/data/tables/table-delete-mutation.ts
index a7678b28b90..d23a994419a 100644
--- a/apps/studio/data/tables/table-delete-mutation.ts
+++ b/apps/studio/data/tables/table-delete-mutation.ts
@@ -1,9 +1,9 @@
-import type { PostgresTable } from '@supabase/postgres-meta'
+import pgMeta from '@supabase/pg-meta'
import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'
import { toast } from 'sonner'
import { entityTypeKeys } from 'data/entity-types/keys'
-import { del, handleError } from 'data/fetchers'
+import { executeSql } from 'data/sql/execute-sql-query'
import { tableEditorKeys } from 'data/table-editor/keys'
import { viewKeys } from 'data/views/keys'
import type { ResponseError } from 'types'
@@ -13,6 +13,7 @@ export type TableDeleteVariables = {
projectRef: string
connectionString?: string | null
id: number
+ name: string
schema: string
cascade?: boolean
}
@@ -21,25 +22,20 @@ export async function deleteTable({
projectRef,
connectionString,
id,
+ name,
+ schema,
cascade = false,
}: TableDeleteVariables) {
- let headers = new Headers()
- if (connectionString) headers.set('x-connection-encrypted', connectionString)
+ const { sql } = pgMeta.tables.remove({ name, schema }, { cascade })
- const { data, error } = await del('/platform/pg-meta/{ref}/tables', {
- params: {
- header: { 'x-connection-encrypted': connectionString! },
- path: { ref: projectRef },
- query: { id, cascade },
- },
- headers,
+ const { result } = await executeSql<void>({
+ projectRef,
+ connectionString,
+ sql,
+ queryKey: ['table', 'delete', id],
})
- if (error) handleError(error)
-
- // [Alaister] we have to manually cast the data to PostgresTable
- // because the API types are slightly wrong
- return data as PostgresTable
+ return result
}
type TableDeleteData = Awaited<ReturnType<typeof deleteTable>>
diff --git a/apps/studio/data/tables/table-retrieve-query.ts b/apps/studio/data/tables/table-retrieve-query.ts
new file mode 100644
index 00000000000..f8bffcd851f
--- /dev/null
+++ b/apps/studio/data/tables/table-retrieve-query.ts
@@ -0,0 +1,49 @@
+import pgMeta from '@supabase/pg-meta'
+import { useQuery, type UseQueryOptions } from '@tanstack/react-query'
+
+import { executeSql } from 'data/sql/execute-sql-query'
+import type { ResponseError } from 'types'
+import { tableKeys } from './keys'
+
+export type TablesVariables = {
+ projectRef?: string
+ connectionString?: string | null
+ name: string
+ schema: string
+}
+
+export async function getTable(
+ { projectRef, connectionString, name, schema }: TablesVariables,
+ signal?: AbortSignal
+) {
+ const { sql, zod } = pgMeta.tables.retrieve({ name, schema })
+
+ const { result } = await executeSql(
+ {
+ projectRef,
+ connectionString,
+ sql,
+ queryKey: tableKeys.retrieve(projectRef, name, schema),
+ },
+ signal
+ )
+ return zod.parse(result[0])
+}
+
+export type RetrieveTableResult = Awaited<ReturnType<typeof getTable>>
+export type RetrieveTableError = ResponseError
+export type RetrievedTableColumn = NonNullable<RetrieveTableResult['columns']>[number]
+
+export const useTablesQuery = <TData = RetrieveTableResult>(
+ { projectRef, connectionString, name, schema }: TablesVariables,
+ {
+ enabled = true,
+ ...options
+ }: UseQueryOptions<RetrieveTableResult, RetrieveTableError, TData> = {}
+) => {
+ return useQuery<RetrieveTableResult, RetrieveTableError, TData>(
+ tableKeys.retrieve(projectRef, name, schema),
+ ({ signal }) => getTable({ projectRef, connectionString, name, schema }, signal),
+ { enabled: enabled && typeof projectRef !== 'undefined', ...options }
+ )
+}
diff --git a/apps/studio/data/tables/table-update-mutation.ts b/apps/studio/data/tables/table-update-mutation.ts
index 0adc62fd1c1..69ec11ef3e3 100644
--- a/apps/studio/data/tables/table-update-mutation.ts
+++ b/apps/studio/data/tables/table-update-mutation.ts
@@ -1,9 +1,9 @@
-import type { PostgresTable } from '@supabase/postgres-meta'
+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 { handleError, patch } from 'data/fetchers'
+import { executeSql } from 'data/sql/execute-sql-query'
import { lintKeys } from 'data/lint/keys'
import { tableEditorKeys } from 'data/table-editor/keys'
import type { ResponseError } from 'types'
@@ -15,6 +15,7 @@ export type TableUpdateVariables = {
projectRef: string
connectionString?: string | null
id: number
+ name: string
schema: string
payload: UpdateTableBody
}
@@ -23,26 +24,20 @@ export async function updateTable({
projectRef,
connectionString,
id,
+ name,
+ schema,
payload,
}: TableUpdateVariables) {
- let headers = new Headers()
- if (connectionString) headers.set('x-connection-encrypted', connectionString)
+ const { sql } = pgMeta.tables.update({ id, name, schema }, payload)
- const { data, error } = await patch('/platform/pg-meta/{ref}/tables', {
- params: {
- header: { 'x-connection-encrypted': connectionString! },
- path: { ref: projectRef },
- query: { id },
- },
- body: payload,
- headers,
+ const { result } = await executeSql<void>({
+ projectRef,
+ connectionString,
+ sql,
+ queryKey: ['table', 'update', id],
})
- if (error) handleError(error)
-
- // [Alaister] we have to manually cast the data to PostgresTable
- // because the API types are slightly wrong
- return data as PostgresTable
+ return result
}
type TableUpdateData = Awaited<ReturnType<typeof updateTable>>
diff --git a/packages/pg-meta/src/pg-meta-columns.ts b/packages/pg-meta/src/pg-meta-columns.ts
index 1c95b76c70a..b1c7ca2c1f1 100644
--- a/packages/pg-meta/src/pg-meta-columns.ts
+++ b/packages/pg-meta/src/pg-meta-columns.ts
@@ -213,7 +213,7 @@ function update(
identity_generation?: 'BY DEFAULT' | 'ALWAYS'
is_nullable?: boolean
is_unique?: boolean
- comment?: string
+ comment?: string | null
check?: string | null
}
): { sql: string } {
@@ -334,7 +334,7 @@ BEGIN
IF v_conname IS NOT NULL THEN
EXECUTE format('ALTER TABLE ${ident(old.schema)}.${ident(
old.table
- )} DROP CONSTRAINT %s', v_conname);
+ )} DROP CONSTRAINT %I', v_conname);
END IF;
${
diff --git a/packages/pg-meta/src/pg-meta-tables.ts b/packages/pg-meta/src/pg-meta-tables.ts
index c1c73994bd9..8c0759302bf 100644
--- a/packages/pg-meta/src/pg-meta-tables.ts
+++ b/packages/pg-meta/src/pg-meta-tables.ts
@@ -1,5 +1,5 @@
import { z } from 'zod'
-import { coalesceRowsToArray, exceptionIdentifierNotFound, filterByList } from './helpers'
+import { coalesceRowsToArray, filterByList } from './helpers'
import { TABLES_SQL } from './sql/tables'
import { COLUMNS_SQL } from './sql/columns'
import { DEFAULT_SYSTEM_SCHEMAS } from './constants'
@@ -107,37 +107,24 @@ function list<T extends boolean | undefined = true>(
function retrieve(identifier: TableIdentifier): {
sql: string
- zod: z.ZodType<PGTable | undefined>
+ zod: z.ZodType<TableWithColumns>
} {
let whereClause = getIdentifierWhereClause(identifier)
const sql = `${generateEnrichedTablesSql({ includeColumns: true })} where ${whereClause};`
return {
sql,
- zod: pgTableZod.optional(),
+ zod: pgTableZod,
}
}
-type TableRemoveParams = { cascade: boolean }
function remove(
- identifier: TableIdentifier,
- params: TableRemoveParams = { cascade: false }
+ table: Pick<PGTable, 'name' | 'schema'>,
+ { cascade = false } = {}
): { sql: string } {
- const whereClause = getIdentifierWhereClause(identifier)
- const sql = `
- do $$
- declare
- old record;
- begin
- with tables as (${generateEnrichedTablesSql({ includeColumns: false })})
- select * into old from tables where ${whereClause};
- if old is null then
- ${exceptionIdentifierNotFound('table', whereClause)}
- end if;
- execute format('drop table %I.%I ${params.cascade ? 'cascade' : 'restrict'}', old.schema, old.name);
- end
- $$;
- `
+ const sql = `DROP TABLE ${ident(table.schema)}.${ident(table.name)} ${
+ cascade ? 'CASCADE' : 'RESTRICT'
+ };`
return { sql }
}
@@ -156,19 +143,12 @@ type TableCreateParams = {
}
function create({ name, schema = 'public', comment }: TableCreateParams): { sql: string } {
- const sql = `
-do $$
-begin
- execute format('create table %I.%I ()', ${literal(schema)}, ${literal(name)});
- ${
+ const tableSql = `CREATE TABLE ${ident(schema)}.${ident(name)} ();`
+ const commentSql =
comment === undefined
? ''
- : `
- execute format('comment on table %I.%I is %L', ${literal(schema)}, ${literal(name)}, ${literal(comment)});`
- }
-end
-$$;`
-
+ : `COMMENT ON TABLE ${ident(schema)}.${ident(name)} IS ${literal(comment)};`
+ const sql = `BEGIN; ${tableSql} ${commentSql} COMMIT;`
return { sql }
}
@@ -184,7 +164,7 @@ type TableUpdateParams = {
}
function update(
- identifier: TableIdentifier,
+ old: Pick<PGTable, 'id' | 'name' | 'schema'>,
{
name,
schema,
@@ -196,103 +176,76 @@ function update(
comment,
}: TableUpdateParams
): { sql: string } {
- const sql = `
+ const alter = `ALTER TABLE ${ident(old.schema)}.${ident(old.name)}`
+ const schemaSql = schema === undefined ? '' : `${alter} SET SCHEMA ${ident(schema)};`
+ let nameSql = ''
+ if (name !== undefined && name !== old.name) {
+ const currentSchema = schema === undefined ? old.schema : schema
+ nameSql = `ALTER TABLE ${ident(currentSchema)}.${ident(old.name)} RENAME TO ${ident(name)};`
+ }
+ let enableRls = ''
+ if (rls_enabled !== undefined) {
+ const enable = `${alter} ENABLE ROW LEVEL SECURITY;`
+ const disable = `${alter} DISABLE ROW LEVEL SECURITY;`
+ enableRls = rls_enabled ? enable : disable
+ }
+ let forceRls = ''
+ if (rls_forced !== undefined) {
+ const enable = `${alter} FORCE ROW LEVEL SECURITY;`
+ const disable = `${alter} NO FORCE ROW LEVEL SECURITY;`
+ forceRls = rls_forced ? enable : disable
+ }
+ let replicaSql = ''
+ if (replica_identity === undefined) {
+ // skip
+ } else if (replica_identity === 'INDEX') {
+ replicaSql = `${alter} REPLICA IDENTITY USING INDEX ${replica_identity_index};`
+ } else {
+ replicaSql = `${alter} REPLICA IDENTITY ${replica_identity};`
+ }
+ let primaryKeysSql = ''
+ if (primary_keys === undefined) {
+ // skip
+ } else {
+ primaryKeysSql += `
DO $$
DECLARE
- v_table record;
r record;
BEGIN
- WITH tables AS (
- ${generateEnrichedTablesSql({ includeColumns: false })}
- )
- SELECT *
- INTO v_table
- FROM tables
- WHERE ${getIdentifierWhereClause(identifier)};
-
- IF v_table IS NULL THEN
- ${exceptionIdentifierNotFound('table', getIdentifierWhereClause(identifier))}
+ SELECT conname
+ INTO r
+ FROM pg_constraint
+ WHERE contype = 'p' AND conrelid = ${literal(old.id)};
+ IF r IS NOT NULL THEN
+ EXECUTE ${literal(`${alter} DROP CONSTRAINT `)} || quote_ident(r.conname);
END IF;
-
- ${
- rls_enabled !== undefined
- ? `execute format('ALTER TABLE %I.%I %s ROW LEVEL SECURITY',
- v_table.schema, v_table.name,
- CASE WHEN ${literal(rls_enabled)} THEN 'ENABLE' ELSE 'DISABLE' END);`
- : ''
- }
-
- ${
- rls_forced !== undefined
- ? `execute format('ALTER TABLE %I.%I %s FORCE ROW LEVEL SECURITY',
- v_table.schema, v_table.name,
- CASE WHEN ${literal(rls_forced)} THEN '' ELSE 'NO' END);`
- : ''
+END
+$$;
+`
+
+ if (primary_keys.length === 0) {
+ // skip
+ } else {
+ primaryKeysSql += `${alter} ADD PRIMARY KEY (${primary_keys
+ .map((x) => ident(x.name))
+ .join(',')});`
+ }
}
-
- ${
- replica_identity !== undefined
- ? `execute format('ALTER TABLE %I.%I REPLICA IDENTITY %s%s',
- v_table.schema, v_table.name,
- ${literal(replica_identity)},
- CASE WHEN ${literal(replica_identity)} = 'INDEX'
- THEN format(' USING INDEX %I', ${literal(replica_identity_index!)})
- ELSE '' END);`
- : ''
- }
-
- ${
- primary_keys !== undefined
- ? `
- -- Drop existing primary key if any
- FOR r IN (
- SELECT conname
- FROM pg_constraint
- WHERE conrelid = format('%I.%I', v_table.schema, v_table.name)::regclass
- AND contype = 'p'
- ) LOOP
- execute format('ALTER TABLE %I.%I DROP CONSTRAINT %I',
- v_table.schema, v_table.name, r.conname);
- END LOOP;
-
- ${
- primary_keys.length > 0
- ? `execute format('ALTER TABLE %I.%I ADD PRIMARY KEY (%s)',
- v_table.schema, v_table.name,
- ${literal(primary_keys.map((pk) => pk.name).join(', '))});`
- : ''
- }`
- : ''
- }
-
- ${
- comment !== undefined
- ? `execute format('COMMENT ON TABLE %I.%I IS %L',
- v_table.schema, v_table.name,
- ${literal(comment)});`
- : ''
- }
-
- ${
- schema !== undefined
- ? `execute format('ALTER TABLE %I.%I SET SCHEMA %I',
- v_table.schema, v_table.name,
- ${literal(schema)});`
- : ''
- }
-
- ${
- name !== undefined
- ? `
- if ${literal(name)} != v_table.name then
- execute format('ALTER TABLE %I.%I RENAME TO %I',
- ${schema !== undefined ? literal(schema) : 'v_table.schema'},
- v_table.name,
- ${literal(name)});
- end if;`
- : ''
- }
-END $$;`
+ const commentSql =
+ comment === undefined
+ ? ''
+ : `COMMENT ON TABLE ${ident(old.schema)}.${ident(old.name)} IS ${literal(comment)};`
+ // nameSql must be last, right below schemaSql
+ const sql = `
+BEGIN;
+ ${enableRls}
+ ${forceRls}
+ ${replicaSql}
+ ${primaryKeysSql}
+ ${commentSql}
+ ${schemaSql}
+ ${nameSql}
+COMMIT;`
return { sql }
}
diff --git a/packages/pg-meta/test/tables.test.ts b/packages/pg-meta/test/tables.test.ts
index d3ee7148159..d6a0d25a01c 100644
--- a/packages/pg-meta/test/tables.test.ts
+++ b/packages/pg-meta/test/tables.test.ts
@@ -311,16 +311,13 @@ withTestDatabase('create, retrieve, update, and delete table', async ({ executeQ
)
// Update table
- const { sql: updateSql } = await pgMeta.tables.update(
- { id: retrieveRes!.id },
- {
- name: 'test a',
- rls_enabled: true,
- rls_forced: true,
- replica_identity: 'NOTHING',
- comment: 'foo',
- }
- )
+ const { sql: updateSql } = await pgMeta.tables.update(retrieveRes!, {
+ name: 'test a',
+ rls_enabled: true,
+ rls_forced: true,
+ replica_identity: 'NOTHING',
+ comment: 'foo',
+ })
await executeQuery(updateSql)
// Retrieve the updated table
@@ -359,15 +356,11 @@ withTestDatabase('create, retrieve, update, and delete table', async ({ executeQ
)
// Remove table
- const { sql: removeSql } = await pgMeta.tables.remove({
- id: updateRes!.id,
- })
+ const { sql: removeSql } = await pgMeta.tables.remove(updateRes!)
await executeQuery(removeSql)
// Verify table is deleted
- const { sql: verifyDeleteSql } = await pgMeta.tables.retrieve({
- id: updateRes!.id,
- })
+ const { sql: verifyDeleteSql } = await pgMeta.tables.retrieve(updateRes!)
const verifyDeleteRes = await executeQuery(verifyDeleteSql)
expect(verifyDeleteRes).toHaveLength(0)
})
@@ -385,7 +378,7 @@ withTestDatabase('update with name unchanged', async ({ executeQuery }) => {
const table = retrieveZod.parse((await executeQuery(retrieveSql))[0])
// Update table with same name
- const { sql: updateSql } = await pgMeta.tables.update({ id: table!.id }, { name: 't' })
+ const { sql: updateSql } = await pgMeta.tables.update(table!, { name: 't' })
await executeQuery(updateSql)
// Verify update
@@ -486,10 +479,9 @@ withTestDatabase('primary keys', async ({ executeQuery }) => {
const table = retrieveZod.parse((await executeQuery(retrieveSql))[0])
// Update table with primary keys
- const { sql: updateSql } = await pgMeta.tables.update(
- { id: table!.id },
- { primary_keys: [{ name: 'c' }, { name: 'cc' }] }
- )
+ const { sql: updateSql } = await pgMeta.tables.update(table!, {
+ primary_keys: [{ name: 'c' }, { name: 'cc' }],
+ })
await executeQuery(updateSql)
// Verify update
@@ -948,10 +940,10 @@ withTestDatabase('remove table by id', async ({ executeQuery }) => {
// Get the table's id
const { sql: listSql, zod: listZod } = await pgMeta.tables.list()
const tables = listZod.parse(await executeQuery(listSql))
- const tableId = tables.find((t) => t.name === 'test_remove_table')!.id
+ const tableId = tables.find((t) => t.name === 'test_remove_table')!
// Remove the table
- const { sql } = await pgMeta.tables.remove({ id: tableId })
+ const { sql } = await pgMeta.tables.remove(tableId)
await executeQuery(sql)
// Verify the table is gone
@@ -989,22 +981,15 @@ withTestDatabase('remove throws error for non-existent table', async ({ executeQ
// With schema and name
await expect(executeQuery(sql)).rejects.toThrow(
- `Failed to execute query: Cannot find table with: name = 'non_existent_table' and schema = 'public'`
+ `Failed to execute query: table "non_existent_table" does not exist`
)
- await expect(
- executeQuery(
- pgMeta.tables.remove({
- id: 999999,
- }).sql
- )
- ).rejects.toThrow(`Failed to execute query: Cannot find table with: id = 999999`)
})
withTestDatabase('remove throws error with missing identifiers', async ({}) => {
await expect(async () => {
//@ts-expect-error use with missing params
await pgMeta.tables.remove({ name: 'some_table' })
- }).rejects.toThrow('Must provide either id or name and schema')
+ }).rejects.toThrow('SQL identifier cannot be null or undefined')
})
withTestDatabase('update table - rename', async ({ executeQuery }) => {
@@ -1014,7 +999,7 @@ withTestDatabase('update table - rename', async ({ executeQuery }) => {
// Update table name
const { sql: updateSql } = await pgMeta.tables.update(
- { name: 'test_rename', schema: 'public' },
+ { id: 0, name: 'test_rename', schema: 'public' },
{ name: 'test_renamed' }
)
await executeQuery(updateSql)
@@ -1036,7 +1021,7 @@ withTestDatabase('update table - change schema', async ({ executeQuery }) => {
// Move table to new schema
const { sql: updateSql } = await pgMeta.tables.update(
- { name: 'test_schema_move', schema: 'public' },
+ { id: 0, name: 'test_schema_move', schema: 'public' },
{ schema: 'test_schema' }
)
await executeQuery(updateSql)
@@ -1057,7 +1042,7 @@ withTestDatabase('update table - row level security', async ({ executeQuery }) =
// Enable RLS
const { sql: updateSql } = await pgMeta.tables.update(
- { name: 'test_rls', schema: 'public' },
+ { id: 0, name: 'test_rls', schema: 'public' },
{ rls_enabled: true, rls_forced: true }
)
await executeQuery(updateSql)
@@ -1079,7 +1064,7 @@ withTestDatabase('update table - replica identity', async ({ executeQuery }) =>
// Change replica identity
const { sql: updateSql } = await pgMeta.tables.update(
- { name: 'test_replica', schema: 'public' },
+ { id: 0, name: 'test_replica', schema: 'public' },
{ replica_identity: 'NOTHING' }
)
await executeQuery(updateSql)
@@ -1101,7 +1086,7 @@ withTestDatabase('update table - primary keys', async ({ executeQuery }) => {
// Add primary key
const { sql: updateSql } = await pgMeta.tables.update(
- { name: 'test_pk', schema: 'public' },
+ { id: 0, name: 'test_pk', schema: 'public' },
{ primary_keys: [{ name: 'id' }] }
)
await executeQuery(updateSql)
@@ -1122,11 +1107,14 @@ withTestDatabase('update table - remove primary keys', async ({ executeQuery })
await executeQuery(createSql)
await executeQuery('ALTER TABLE test_pk_remove ADD COLUMN id INT PRIMARY KEY')
+ const { sql: tableSql, zod: tableZod } = await pgMeta.tables.retrieve({
+ name: 'test_pk_remove',
+ schema: 'public',
+ })
+ const table = tableZod.parse((await executeQuery(tableSql))[0])
+
// Remove primary key
- const { sql: updateSql } = await pgMeta.tables.update(
- { name: 'test_pk_remove', schema: 'public' },
- { primary_keys: [] }
- )
+ const { sql: updateSql } = await pgMeta.tables.update(table!, { primary_keys: [] })
await executeQuery(updateSql)
// Verify update
@@ -1145,7 +1133,7 @@ withTestDatabase('update table - comment', async ({ executeQuery }) => {
// Add comment
const { sql: updateSql } = await pgMeta.tables.update(
- { name: 'test_comment', schema: 'public' },
+ { id: 0, name: 'test_comment', schema: 'public' },
{ comment: 'Test comment' }
)
await executeQuery(updateSql)
@@ -1167,7 +1155,7 @@ withTestDatabase('update table - multiple changes', async ({ executeQuery }) =>
// Make multiple changes
const { sql: updateSql } = await pgMeta.tables.update(
- { name: 'test_multiple', schema: 'public' },
+ { id: 0, name: 'test_multiple', schema: 'public' },
{
name: 'test_multiple_updated',
comment: 'Updated table',
@@ -1206,10 +1194,7 @@ withTestDatabase('update table - by id', async ({ executeQuery }) => {
const table = zod.parse((await executeQuery(retrieveSql))[0])
// Update by id
- const { sql: updateSql } = await pgMeta.tables.update(
- { id: table!.id },
- { name: 'test_by_id_updated' }
- )
+ const { sql: updateSql } = await pgMeta.tables.update(table!, { name: 'test_by_id_updated' })
await executeQuery(updateSql)
// Verify update
@@ -1223,7 +1208,7 @@ withTestDatabase('update table - by id', async ({ executeQuery }) => {
withTestDatabase('update table - error on non-existent table', async ({ executeQuery }) => {
const { sql: updateSql } = await pgMeta.tables.update(
- { name: 'non_existent', schema: 'public' },
+ { id: 0, name: 'non_existent', schema: 'public' },
{ name: 'new_name' }
)
@@ -1238,7 +1223,7 @@ withTestDatabase('update table - rename with schema change', async ({ executeQue
// Update both name and schema
const { sql: updateSql } = await pgMeta.tables.update(
- { name: 'test_rename_schema', schema: 'public' },
+ { id: 0, name: 'test_rename_schema', schema: 'public' },
{
name: 'test_renamed_schema',
schema: 'test_schema',