Skip to content

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

Write sql txn for updating of webhooks

Joshen Lim35a9fad059ce
diff --git a/studio/components/interfaces/Database/Hooks/EditHookPanel.tsx b/studio/components/interfaces/Database/Hooks/EditHookPanel.tsx
index 03c65be1d67..ddcc6327f8c 100644
--- a/studio/components/interfaces/Database/Hooks/EditHookPanel.tsx
+++ b/studio/components/interfaces/Database/Hooks/EditHookPanel.tsx
@@ -11,8 +11,7 @@ import { AVAILABLE_WEBHOOK_TYPES, HOOK_EVENTS } from './Hooks.constants'
import { FormSection, FormSectionLabel, FormSectionContent } from 'components/ui/Forms'
import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import { useDatabaseTriggerCreateMutation } from 'data/database-triggers/database-trigger-create-mutation'
-import { useDatabaseTriggerUpdateMutation } from 'data/database-triggers/database-trigger-update-mutation'
-import { useDatabaseTriggerDeleteMutation } from 'data/database-triggers/database-trigger-delete-mutation'
+import { useDatabaseTriggerUpdateMutation } from 'data/database-triggers/database-trigger-update-transaction-mutation'
export interface EditHookPanelProps {
visible: boolean
@@ -40,7 +39,6 @@ const EditHookPanel = ({ visible, selectedHook, onClose }: EditHookPanelProps) =
const { project } = useProjectContext()
const { mutateAsync: createDatabaseTrigger } = useDatabaseTriggerCreateMutation()
const { mutateAsync: updateDatabaseTrigger } = useDatabaseTriggerUpdateMutation()
- const { mutateAsync: deleteDatabaseTrigger } = useDatabaseTriggerDeleteMutation()
useEffect(() => {
if (visible) {
@@ -78,7 +76,7 @@ const EditHookPanel = ({ visible, selectedHook, onClose }: EditHookPanelProps) =
function_name: selectedHook?.function_name ?? 'http_request',
http_url: selectedHook?.function_args?.[0] ?? '',
- http_method: selectedHook?.function_args?.[1] ?? '',
+ http_method: selectedHook?.function_args?.[1] ?? 'GET',
}
const onUpdateSelectedEvents = (event: string) => {
@@ -168,43 +166,51 @@ const EditHookPanel = ({ visible, selectedHook, onClose }: EditHookPanelProps) =
payload.function_args = []
}
- // [Joshen] As the PATCH triggers endpoint currently only supports updating of name
- // and enabled_mode, we'll do a DELETE and POST behind the scenes as a workaround
- try {
- setIsSubmitting(true)
- await createDatabaseTrigger({
- projectRef: project?.ref,
- connectionString: project?.connectionString,
- payload,
- })
- if (selectedHook === undefined) {
+ if (selectedHook === undefined) {
+ try {
+ setIsSubmitting(true)
+ await createDatabaseTrigger({
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ payload,
+ })
ui.setNotification({
category: 'success',
message: `Successfully created new webhook "${values.name}"`,
})
- } else {
- await deleteDatabaseTrigger({
- id: selectedHook.id,
- projectRef: project.ref,
- connectionString: project.connectionString,
+ onClose()
+ } catch (error: any) {
+ ui.setNotification({
+ error,
+ category: 'error',
+ message: `Failed to create webhook: ${error.message}`,
+ })
+ } finally {
+ setIsSubmitting(false)
+ }
+ } else {
+ try {
+ setIsSubmitting(true)
+ await updateDatabaseTrigger({
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ originalTrigger: selectedHook,
+ updatedTrigger: payload,
})
ui.setNotification({
category: 'success',
message: `Successfully updated webhook "${values.name}"`,
})
+ onClose()
+ } catch (error: any) {
+ ui.setNotification({
+ error,
+ category: 'error',
+ message: `Failed to update webhook: ${error.message}`,
+ })
+ } finally {
+ setIsSubmitting(false)
}
- onClose()
- } catch (error: any) {
- ui.setNotification({
- error,
- category: 'error',
- message:
- selectedHook === undefined
- ? `Failed to create webhook: ${error.message}`
- : `Failed to update webhook: ${error.message}`,
- })
- } finally {
- setIsSubmitting(false)
}
}
diff --git a/studio/data/database-triggers/database-trigger-update-transaction-mutation.ts b/studio/data/database-triggers/database-trigger-update-transaction-mutation.ts
new file mode 100644
index 00000000000..9665237532c
--- /dev/null
+++ b/studio/data/database-triggers/database-trigger-update-transaction-mutation.ts
@@ -0,0 +1,66 @@
+import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'
+import { executeSql } from 'data/sql/execute-sql-query'
+import { databaseTriggerKeys } from './keys'
+import { quoteLiteral } from 'lib/pg-format'
+
+// [Joshen] Writing this query within FE as the PATCH endpoint from pg-meta only supports updating
+// trigger name and enabled mode. So we'll delete and create the trigger, within a single transaction
+// Copying the SQL from https://github.com/supabase/postgres-meta/blob/master/src/lib/PostgresMetaTriggers.ts
+
+export type DatabaseTriggerUpdateVariables = {
+ projectRef: string
+ connectionString?: string
+ originalTrigger: any
+ updatedTrigger: any
+}
+
+export function getDatabaseTriggerUpdateSQL({
+ originalTrigger,
+ updatedTrigger,
+}: Pick<DatabaseTriggerUpdateVariables, 'originalTrigger' | 'updatedTrigger'>) {
+ const { name, activation, events, schema, table, function_schema, function_name, function_args } =
+ updatedTrigger
+ return `
+BEGIN;
+DROP TRIGGER "${originalTrigger.name}" ON "${originalTrigger.schema}"."${originalTrigger.table}";
+CREATE TRIGGER "${name}" ${activation} ${events.join(' OR ')} ON "${schema}"."${table}"
+ FOR EACH ROW EXECUTE FUNCTION
+ "${function_schema}"."${function_name}"(${function_args?.map(quoteLiteral).join(',') ?? ''});
+COMMIT;
+`.trim()
+}
+
+export async function updateDatabaseTrigger({
+ projectRef,
+ connectionString,
+ originalTrigger,
+ updatedTrigger,
+}: DatabaseTriggerUpdateVariables) {
+ const sql = getDatabaseTriggerUpdateSQL({ originalTrigger, updatedTrigger })
+ const { result } = await executeSql({ projectRef, connectionString, sql })
+ return result
+}
+
+type DatabaseTriggerUpdateTxnData = Awaited<ReturnType<typeof updateDatabaseTrigger>>
+
+export const useDatabaseTriggerUpdateMutation = ({
+ onSuccess,
+ ...options
+}: Omit<
+ UseMutationOptions<DatabaseTriggerUpdateTxnData, unknown, DatabaseTriggerUpdateVariables>,
+ 'mutationFn'
+> = {}) => {
+ const queryClient = useQueryClient()
+
+ return useMutation<DatabaseTriggerUpdateTxnData, unknown, DatabaseTriggerUpdateVariables>(
+ (vars) => updateDatabaseTrigger(vars),
+ {
+ async onSuccess(data, variables, context) {
+ const { projectRef } = variables
+ await queryClient.invalidateQueries(databaseTriggerKeys.list(projectRef))
+ await onSuccess?.(data, variables, context)
+ },
+ ...options,
+ }
+ )
+}
diff --git a/studio/lib/pg-format.ts b/studio/lib/pg-format.ts
new file mode 100644
index 00000000000..fcc7bc055c0
--- /dev/null
+++ b/studio/lib/pg-format.ts
@@ -0,0 +1,77 @@
+// [Joshen] These are from https://github.com/datalanche/node-pg-format/blob/master/lib/index.js
+function formatDate(date: any) {
+ date = date.replace('T', ' ')
+ date = date.replace('Z', '+00')
+ return date
+}
+
+function arrayToList(useSpace: any, array: any, formatter: any) {
+ let sql = ''
+
+ sql += useSpace ? ' (' : '('
+ for (var i = 0; i < array.length; i++) {
+ sql += (i === 0 ? '' : ', ') + formatter(array[i])
+ }
+ sql += ')'
+
+ return sql
+}
+
+export function quoteLiteral(value: any): any {
+ let literal = null
+ let explicitCast = null
+
+ if (value === undefined || value === null) {
+ return 'NULL'
+ } else if (value === false) {
+ return "'f'"
+ } else if (value === true) {
+ return "'t'"
+ } else if (value instanceof Date) {
+ return "'" + formatDate(value.toISOString()) + "'"
+ } else if (value instanceof Buffer) {
+ return "E'\\\\x" + value.toString('hex') + "'"
+ } else if (Array.isArray(value) === true) {
+ let temp = []
+ for (let i = 0; i < value.length; i++) {
+ if (Array.isArray(value[i]) === true) {
+ temp.push(arrayToList(i !== 0, value[i], quoteLiteral))
+ } else {
+ temp.push(quoteLiteral(value[i]))
+ }
+ }
+ return temp.toString()
+ } else if (value === Object(value)) {
+ explicitCast = 'jsonb'
+ literal = JSON.stringify(value)
+ } else {
+ literal = value.toString().slice(0) // create copy
+ }
+
+ let hasBackslash = false
+ let quoted = "'"
+
+ for (let i = 0; i < literal.length; i++) {
+ let c = literal[i]
+ if (c === "'") {
+ quoted += c + c
+ } else if (c === '\\') {
+ quoted += c + c
+ hasBackslash = true
+ } else {
+ quoted += c
+ }
+ }
+
+ quoted += "'"
+
+ if (hasBackslash === true) {
+ quoted = 'E' + quoted
+ }
+
+ if (explicitCast) {
+ quoted += '::' + explicitCast
+ }
+
+ return quoted
+}