The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
fix: move column delete and update to query route (#35497)
Han Qiaodc2f1270dbd9
diff --git a/apps/studio/components/interfaces/TableGridEditor/DeleteConfirmationDialogs.tsx b/apps/studio/components/interfaces/TableGridEditor/DeleteConfirmationDialogs.tsxindex 361f79ea9fe..971ec3fda43 100644--- a/apps/studio/components/interfaces/TableGridEditor/DeleteConfirmationDialogs.tsx+++ b/apps/studio/components/interfaces/TableGridEditor/DeleteConfirmationDialogs.tsx@@ -133,11 +133,10 @@ const DeleteConfirmationDialogs = ({if (selectedColumnToDelete === undefined) returndeleteColumn({- id: selectedColumnToDelete.id,+ column: selectedColumnToDelete,cascade: isDeleteWithCascade,projectRef: project.ref,connectionString: project?.connectionString,- table: selectedTable,})}diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsxindex 85cc650cde9..8c17af59bdc 100644--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx@@ -247,7 +247,7 @@ const SidePanelEditor = ({: await updateColumn({projectRef: project?.ref!,connectionString: project?.connectionString,- id: columnId as string,+ originalColumn: selectedColumnToEdit as PostgresColumn,payload: payload as UpdateColumnPayload,selectedTable,primaryKey,diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.tsxindex c47098b4afc..cff05312b88 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 { PostgresPrimaryKey, PostgresTable } from '@supabase/postgres-meta'+import type { PostgresColumn, PostgresPrimaryKey, PostgresTable } from '@supabase/postgres-meta'import { chunk, find, isEmpty, isEqual } from 'lodash'import Papa from 'papaparse'import { toast } from 'sonner'@@ -285,7 +285,7 @@ export const createColumn = async ({export const updateColumn = async ({projectRef,connectionString,- id,+ originalColumn,payload,selectedTable,primaryKey,@@ -296,7 +296,7 @@ export const updateColumn = async ({}: {projectRef: stringconnectionString?: string | null- id: string+ originalColumn: PostgresColumnpayload: UpdateColumnPayloadselectedTable: PostgresTableprimaryKey?: Constraint@@ -307,10 +307,10 @@ export const updateColumn = async ({}) => {try {const { isPrimaryKey, ...formattedPayload } = payload- const column = await updateDatabaseColumn({+ await updateDatabaseColumn({projectRef,connectionString,- id,+ originalColumn,payload: formattedPayload,})@@ -322,22 +322,23 @@ export const updateColumn = async ({await dropConstraint(projectRef,connectionString,- column.schema,- column.table,+ originalColumn.schema,+ originalColumn.table,primaryKey.name)}+ const columnName = formattedPayload.name ?? originalColumn.nameconst primaryKeyColumns = isPrimaryKey- ? existingPrimaryKeys.concat([column.name])- : existingPrimaryKeys.filter((x) => x !== column.name)+ ? existingPrimaryKeys.concat([columnName])+ : existingPrimaryKeys.filter((x) => x !== columnName)if (primaryKeyColumns.length) {await addPrimaryKey(projectRef,connectionString,- column.schema,- column.table,+ originalColumn.schema,+ originalColumn.table,primaryKeyColumns)}@@ -348,13 +349,13 @@ export const updateColumn = async ({await updateForeignKeys({projectRef,connectionString,- table: { schema: column.schema, name: column.table },+ table: { schema: originalColumn.schema, name: originalColumn.table },foreignKeys: foreignKeyRelations,existingForeignKeyRelations,})}- if (!skipSuccessMessage) toast.success(`Successfully updated column "${column.name}"`)+ if (!skipSuccessMessage) toast.success(`Successfully updated column "${originalColumn.name}"`)} catch (error: any) {return { error }}@@ -688,7 +689,7 @@ export const updateTable = async ({await deleteDatabaseColumn({projectRef,connectionString,- id: column.id,+ column,})}@@ -722,7 +723,7 @@ export const updateTable = async ({const res = await updateColumn({projectRef: projectRef,connectionString: connectionString,- id: column.id,+ originalColumn: originalColumn,payload: columnPayload,selectedTable: updatedTable,skipPKCreation: true,diff --git a/apps/studio/data/database-columns/database-column-delete-mutation.ts b/apps/studio/data/database-columns/database-column-delete-mutation.tsindex 508c448ae90..11717e92da3 100644--- a/apps/studio/data/database-columns/database-column-delete-mutation.ts+++ b/apps/studio/data/database-columns/database-column-delete-mutation.ts@@ -1,9 +1,11 @@+import pgMeta from '@supabase/pg-meta'+import { PGColumn } from '@supabase/pg-meta/src/pg-meta-columns'import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'import { toast } from 'sonner'import { databaseKeys } from 'data/database/keys'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 { tableRowKeys } from 'data/table-rows/keys'import { viewKeys } from 'data/views/keys'@@ -12,32 +14,26 @@ import type { ResponseError } from 'types'export type DatabaseColumnDeleteVariables = {projectRef: stringconnectionString?: string | null- id: string+ column: Pick<PGColumn, 'id' | 'name' | 'schema' | 'table' | 'table_id'>cascade?: boolean- table?: { id: number; schema: string; name: string }}export async function deleteDatabaseColumn({projectRef,connectionString,- id,+ column,cascade = false,}: DatabaseColumnDeleteVariables) {- let headers = new Headers()- if (connectionString) headers.set('x-connection-encrypted', connectionString)+ const { sql } = pgMeta.columns.remove(column, { cascade })- const { data, error } = await del('/platform/pg-meta/{ref}/columns', {- params: {- header: { 'x-connection-encrypted': connectionString! },- path: { ref: projectRef },- // cascade is expected to be a string 'true' or 'false'- query: { id, cascade },- },- headers,+ const { result } = await executeSql({+ projectRef,+ connectionString,+ sql,+ queryKey: ['column', 'delete', column.id],})- if (error) handleError(error)- return data+ return result}type DatabaseColumnDeleteData = Awaited<ReturnType<typeof deleteDatabaseColumn>>@@ -55,29 +51,25 @@ export const useDatabaseColumnDeleteMutation = ({(vars) => deleteDatabaseColumn(vars),{async onSuccess(data, variables, context) {- const { projectRef, table } = variables+ const { projectRef, column } = variablesawait Promise.all([// refetch all entities in the sidebar because deleting a column may regenerate a view (and change its id)queryClient.invalidateQueries(entityTypeKeys.list(projectRef)),- ...(table !== undefined- ? [- queryClient.invalidateQueries(- databaseKeys.foreignKeyConstraints(projectRef, table?.schema)- ),- queryClient.invalidateQueries(tableEditorKeys.tableEditor(projectRef, table.id)),- queryClient.invalidateQueries(databaseKeys.tableDefinition(projectRef, table.id)),- // invalidate all views from this schema, not sure if this is needed since you can't actually delete a column- // which has a view dependent on it- queryClient.invalidateQueries(viewKeys.listBySchema(projectRef, table.schema)),- ]- : []),+ queryClient.invalidateQueries(+ databaseKeys.foreignKeyConstraints(projectRef, column.schema)+ ),+ queryClient.invalidateQueries(tableEditorKeys.tableEditor(projectRef, column.table_id)),+ queryClient.invalidateQueries(databaseKeys.tableDefinition(projectRef, column.table_id)),+ // invalidate all views from this schema, not sure if this is needed since you can't actually delete a column+ // which has a view dependent on it+ queryClient.invalidateQueries(viewKeys.listBySchema(projectRef, column.schema)),])- if (table !== undefined) {- // We need to invalidate tableRowsAndCount after tableEditor- // to ensure the query sent is correct- await queryClient.invalidateQueries(tableRowKeys.tableRowsAndCount(projectRef, table.id))- }+ // We need to invalidate tableRowsAndCount after tableEditor+ // to ensure the query sent is correct+ await queryClient.invalidateQueries(+ tableRowKeys.tableRowsAndCount(projectRef, column.table_id)+ )await onSuccess?.(data, variables, context)},diff --git a/apps/studio/data/database-columns/database-column-update-mutation.ts b/apps/studio/data/database-columns/database-column-update-mutation.tsindex 91b1fb74b3e..17df890a1bb 100644--- a/apps/studio/data/database-columns/database-column-update-mutation.ts+++ b/apps/studio/data/database-columns/database-column-update-mutation.ts@@ -1,8 +1,10 @@+import pgMeta from '@supabase/pg-meta'+import { PGColumn } from '@supabase/pg-meta/src/pg-meta-columns'import { useMutation, UseMutationOptions } 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 type { ResponseError } from 'types'export type UpdateColumnBody = components['schemas']['UpdateColumnBody']@@ -10,31 +12,48 @@ export type UpdateColumnBody = components['schemas']['UpdateColumnBody']export type DatabaseColumnUpdateVariables = {projectRef: stringconnectionString?: string | null- id: string+ originalColumn: Pick<+ PGColumn,+ | 'id'+ | 'name'+ | 'schema'+ | 'table'+ | 'table_id'+ | 'ordinal_position'+ | 'is_identity'+ | 'is_unique'+ >payload: components['schemas']['UpdateColumnBody']}export async function updateDatabaseColumn({projectRef,connectionString,- id,+ originalColumn,payload,}: DatabaseColumnUpdateVariables) {- let headers = new Headers()- if (connectionString) headers.set('x-connection-encrypted', connectionString)+ const { sql } = pgMeta.columns.update(originalColumn, {+ name: payload.name,+ type: payload.type,+ drop_default: payload.dropDefault,+ default_value: payload.defaultValue,+ default_value_format: payload.defaultValueFormat,+ is_identity: payload.isIdentity,+ identity_generation: payload.identityGeneration,+ is_nullable: payload.isNullable,+ is_unique: payload.isUnique,+ comment: payload.comment,+ check: payload.check,+ })- const { data, error } = await patch('/platform/pg-meta/{ref}/columns', {- params: {- header: { 'x-connection-encrypted': connectionString! },- path: { ref: projectRef },- query: { id },- },- body: payload,- headers,+ const { result } = await executeSql({+ projectRef,+ connectionString,+ sql,+ queryKey: ['column', 'update', originalColumn.id],})- if (error) handleError(error)- return data+ return result}type DatabaseColumnUpdateData = Awaited<ReturnType<typeof updateDatabaseColumn>>diff --git a/packages/pg-meta/src/pg-meta-columns.ts b/packages/pg-meta/src/pg-meta-columns.tsindex aaedd84dd22..1c95b76c70a 100644--- a/packages/pg-meta/src/pg-meta-columns.ts+++ b/packages/pg-meta/src/pg-meta-columns.ts@@ -187,7 +187,10 @@ const typeIdent = (type: string) => {}function update(- id: string,+ old: Pick<+ PGColumn,+ 'name' | 'schema' | 'table' | 'table_id' | 'ordinal_position' | 'is_identity' | 'is_unique'+ >,{name,type,@@ -214,102 +217,176 @@ function update(check?: string | null}): { sql: string } {- if (is_identity) {- if (default_value !== undefined) {- throw new Error('Columns cannot both be identity and have a default value')+ const nameSql =+ name === undefined || name === old.name+ ? ''+ : `ALTER TABLE ${ident(old.schema)}.${ident(old.table)} RENAME COLUMN ${ident(+ old.name+ )} TO ${ident(name)};`+ // We use USING to allow implicit conversion of incompatible types (e.g. int4 -> text).+ const typeSql =+ type === undefined+ ? ''+ : `ALTER TABLE ${ident(old.schema)}.${ident(old.table)} ALTER COLUMN ${ident(+ old.name+ )} SET DATA TYPE ${typeIdent(type)} USING ${ident(old.name)}::${typeIdent(type)};`++ let defaultValueSql: string+ if (drop_default) {+ defaultValueSql = `ALTER TABLE ${ident(old.schema)}.${ident(+ old.table+ )} ALTER COLUMN ${ident(old.name)} DROP DEFAULT;`+ } else if (default_value === undefined) {+ defaultValueSql = ''+ } else {+ const defaultValue =+ default_value_format === 'expression' ? default_value : literal(default_value)+ defaultValueSql = `ALTER TABLE ${ident(old.schema)}.${ident(+ old.table+ )} ALTER COLUMN ${ident(old.name)} SET DEFAULT ${defaultValue};`+ }+ // What identitySql does vary depending on the old and new values of+ // is_identity and identity_generation.+ //+ // | is_identity: old \ new | undefined | true | false |+ // |------------------------+--------------------+--------------------+----------------|+ // | true | maybe set identity | maybe set identity | drop if exists |+ // |------------------------+--------------------+--------------------+----------------|+ // | false | - | add identity | drop if exists |+ let identitySql = `ALTER TABLE ${ident(old.schema)}.${ident(old.table)} ALTER COLUMN ${ident(+ old.name+ )}`+ if (is_identity === false) {+ identitySql += ' DROP IDENTITY IF EXISTS;'+ } else if (old.is_identity === true) {+ if (identity_generation === undefined) {+ identitySql = ''+ } else {+ identitySql += ` SET GENERATED ${identity_generation};`}+ } else if (is_identity === undefined) {+ identitySql = ''+ } else {+ identitySql += ` ADD GENERATED ${identity_generation} AS IDENTITY;`}- const sql = `+ let isNullableSql: string+ if (is_nullable === undefined) {+ isNullableSql = ''+ } else {+ isNullableSql = is_nullable+ ? `ALTER TABLE ${ident(old.schema)}.${ident(old.table)} ALTER COLUMN ${ident(+ old.name+ )} DROP NOT NULL;`+ : `ALTER TABLE ${ident(old.schema)}.${ident(old.table)} ALTER COLUMN ${ident(+ old.name+ )} SET NOT NULL;`+ }+ let isUniqueSql = ''+ if (old.is_unique === true && is_unique === false) {+ isUniqueSql = `DO $$DECLARE- v_schema name;- v_table name;- v_column name;- v_attnum int2;r record;BEGIN- WITH RECURSIVE column_info AS (- ${COLUMNS_SQL}- )- SELECT- schema,- ${ident('table')},- name,- ordinal_position::int2- INTO v_schema, v_table, v_column, v_attnum- FROM column_info- WHERE ${getIdentifierWhereClause({ id })};-- IF v_schema IS NULL THEN- RAISE EXCEPTION 'Column with id % not found', ${literal(id)};- END IF;-- ${is_nullable !== undefined ? `execute(format('ALTER TABLE %I.%I ALTER COLUMN %I ${is_nullable ? 'DROP NOT NULL' : 'SET NOT NULL'}', v_schema, v_table, v_column));` : ''}-- ${type ? `execute(format('ALTER TABLE %I.%I ALTER COLUMN %I TYPE %I USING %I::%I', v_schema, v_table, v_column, ${literal(type)}, v_column, ${literal(type)}));` : ''}-- ${drop_default ? `execute(format('ALTER TABLE %I.%I ALTER COLUMN %I DROP DEFAULT', v_schema, v_table, v_column));` : ''}+ FOR r IN+ SELECT conname FROM pg_constraint WHERE+ contype = 'u'+ AND cardinality(conkey) = 1+ AND conrelid = ${literal(old.table_id)}+ AND conkey[1] = ${literal(old.ordinal_position)}+ LOOP+ EXECUTE ${literal(+ `ALTER TABLE ${ident(old.schema)}.${ident(old.table)} DROP CONSTRAINT `+ )} || quote_ident(r.conname);+ END LOOP;+END+$$;+`+ } else if (old.is_unique === false && is_unique === true) {+ isUniqueSql = `ALTER TABLE ${ident(old.schema)}.${ident(old.table)} ADD UNIQUE (${ident(+ old.name+ )});`+ }+ const commentSql =+ comment === undefined+ ? ''+ : `COMMENT ON COLUMN ${ident(old.schema)}.${ident(old.table)}.${ident(+ old.name+ )} IS ${literal(comment)};`- ${default_value !== undefined ? `execute(format('ALTER TABLE %I.%I ALTER COLUMN %I SET DEFAULT %s', v_schema, v_table, v_column, ${default_value_format === 'expression' ? default_value : literal(default_value)}));` : ''}-- ${is_identity !== undefined ? `execute(format('ALTER TABLE %I.%I ALTER COLUMN %I ${is_identity ? `ADD GENERATED ${identity_generation} AS IDENTITY` : 'DROP IDENTITY IF EXISTS'}', v_schema, v_table, v_column));` : ''}-- ${is_unique !== undefined ? `execute(format('ALTER TABLE %I.%I ${is_unique ? 'ADD UNIQUE' : 'DROP CONSTRAINT IF EXISTS %I_key'}', v_schema, v_table, ${is_unique ? `(${literal(name || 'v_column')})` : 'v_column'}));` : ''}+ const checkSql =+ check === undefined+ ? ''+ : `+DO $$+DECLARE+ v_conname name;+ v_conkey int2[];+BEGIN+ SELECT conname into v_conname FROM pg_constraint WHERE+ contype = 'c'+ AND cardinality(conkey) = 1+ AND conrelid = ${literal(old.table_id)}+ AND conkey[1] = ${literal(old.ordinal_position)}+ ORDER BY oid asc+ LIMIT 1;- ${comment !== undefined ? `execute(format('COMMENT ON COLUMN %I.%I.%I IS %L', v_schema, v_table, v_column, ${literal(comment)}));` : ''}+ IF v_conname IS NOT NULL THEN+ EXECUTE format('ALTER TABLE ${ident(old.schema)}.${ident(+ old.table+ )} DROP CONSTRAINT %s', v_conname);+ END IF;${- check !== undefined+ check !== null? `- -- Drop existing check constraint if any- FOR r IN (- SELECT conname- FROM pg_constraint- WHERE conrelid = format('%I.%I', v_schema, v_table)::regclass- AND contype = 'c'- AND conkey = ARRAY[v_attnum]- ) LOOP- EXECUTE format('ALTER TABLE %I.%I DROP CONSTRAINT %I', v_schema, v_table, r.conname);- END LOOP;- -- Create the new constraints if mentionned- ${check !== null ? `execute(format('ALTER TABLE %I.%I ADD CONSTRAINT %I CHECK (%s)', v_schema, v_table, v_column || '_check', ${literal(check)}));` : ''}- `+ ALTER TABLE ${ident(old.schema)}.${ident(old.table)} ADD CONSTRAINT ${ident(+ `${old.table}_${old.name}_check`+ )} CHECK (${check});++ SELECT conkey into v_conkey FROM pg_constraint WHERE conname = ${literal(+ `${old.table}_${old.name}_check`+ )};++ ASSERT v_conkey IS NOT NULL, 'error creating column constraint: check condition must refer to this column';+ ASSERT cardinality(v_conkey) = 1, 'error creating column constraint: check condition cannot refer to multiple columns';+ ASSERT v_conkey[1] = ${literal(+ old.ordinal_position+ )}, 'error creating column constraint: check condition cannot refer to other columns';+`: ''}- ${name ? `execute(format('ALTER TABLE %I.%I RENAME COLUMN %I TO %I', v_schema, v_table, v_column, ${literal(name)}));` : ''}-END $$;`-- return { sql }-}+END+$$;+`-function remove(id: string, { cascade = false } = {}): { sql: string } {+ // TODO: Can't set default if column is previously identity even if+ // is_identity: false. Must do two separate PATCHes (once to drop identity+ // and another to set default).+ // NOTE: nameSql must be last. defaultValueSql must be after typeSql.+ // identitySql must be after isNullableSql.const sql = `-DO $$-DECLARE- v_schema name;- v_table name;- v_column name;-BEGIN- WITH RECURSIVE column_info AS (- ${COLUMNS_SQL}- )- SELECT schema, ${ident('table')}, name- INTO v_schema, v_table, v_column- FROM column_info- WHERE id = ${literal(id)};-- IF v_schema IS NULL THEN- RAISE EXCEPTION 'Column with id % not found', ${literal(id)};- END IF;+BEGIN;+ ${isNullableSql}+ ${typeSql}+ ${defaultValueSql}+ ${identitySql}+ ${isUniqueSql}+ ${commentSql}+ ${checkSql}+ ${nameSql}+COMMIT;`- EXECUTE format(- 'ALTER TABLE %I.%I DROP COLUMN %I ${cascade ? 'CASCADE' : 'RESTRICT'}',- v_schema,- v_table,- v_column- );-END $$;`+ return { sql }+}+function remove(+ column: Pick<PGColumn, 'name' | 'schema' | 'table'>,+ { cascade = false } = {}+): { sql: string } {+ const sql = `ALTER TABLE ${ident(column.schema)}.${ident(column.table)} DROP COLUMN ${ident(+ column.name+ )} ${cascade ? 'CASCADE' : 'RESTRICT'};`return { sql }}diff --git a/packages/pg-meta/test/columns.test.ts b/packages/pg-meta/test/columns.test.tsindex 3b524386408..ea8ae76b3f8 100644--- a/packages/pg-meta/test/columns.test.ts+++ b/packages/pg-meta/test/columns.test.ts@@ -226,7 +226,7 @@ withTestDatabase('retrieve, create, update, delete column', async ({ executeQuer)// Update column- const { sql: updateSql } = await pgMeta.columns.update(column!.id, {+ const { sql: updateSql } = await pgMeta.columns.update(column!, {name: 'c1',type: 'int4',drop_default: true,@@ -274,7 +274,7 @@ withTestDatabase('retrieve, create, update, delete column', async ({ executeQuer)// Remove column- const { sql: removeSql } = await pgMeta.columns.remove(column!.id)+ const { sql: removeSql } = await pgMeta.columns.remove(column!)await executeQuery(removeSql)// Verify column was removed@@ -591,7 +591,7 @@ withTestDatabase('alter column to type with uppercase', async ({ executeQuery })const column = retrieveZod.parse((await executeQuery(retrieveSql))[0])// Update column- const { sql: updateSql } = await pgMeta.columns.update(column!.id, { type: 'T' })+ const { sql: updateSql } = await pgMeta.columns.update(column!, { type: 'T' })await executeQuery(updateSql)// Verify updated column@@ -704,7 +704,7 @@ withTestDatabase('drop with cascade', async ({ executeQuery }) => {const column = retrieveZod.parse((await executeQuery(retrieveSql))[0])// Remove column with cascade- const { sql: removeSql } = await pgMeta.columns.remove(column!.id, { cascade: true })+ const { sql: removeSql } = await pgMeta.columns.remove(column!, { cascade: true })await executeQuery(removeSql)// Verify original column was removed@@ -811,7 +811,7 @@ withTestDatabase('dropping column checks', async ({ executeQuery }) => {const column = retrieveZod.parse((await executeQuery(retrieveSql))[0])// Update column to remove check- const { sql: updateSql } = await pgMeta.columns.update(column!.id, { check: null })+ const { sql: updateSql } = await pgMeta.columns.update(column!, { check: null })await executeQuery(updateSql)// Verify updated column